query
stringlengths
7
3.85k
document
stringlengths
11
430k
metadata
dict
negatives
sequencelengths
0
101
negative_scores
sequencelengths
0
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
querying execute sql from raw string
func querying(query string, db *sql.DB) []*authlog.AuthInfo { geoDB, err := ip2location.OpenDB("assets/geo/IP2LOCATION-LITE-DB5.BIN") if err != nil { panic(err.Error()) } // now := time.Now() rows, err := db.Query(query) if err != nil { panic(err.Error()) } defer rows.Close() // fmt.Printf("query time: %v\n", time.Since(now)) authInfoList := authlog.AuthInfoSlice{} // now = time.Now() for rows.Next() { authRawInfo := mapper(rows) authInfoList = append(authInfoList, authRawInfo.ConvertToAuthInfo(geoDB)) } // fmt.Printf("convert time: %v\n", time.Since(now)) return authInfoList }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *SQLStore) exec(e execer, sqlString string, args ...interface{}) (sql.Result, error) {\n\tsqlString = s.db.Rebind(sqlString)\n\treturn e.Exec(sqlString, args...)\n}", "func (ex *Execer) execSQL(fullSQL string, args []interface{}) (sql.Result, error) {\n\tdefer logExecutionTime(time.Now(), fullSQL, args)\n\n\tvar result sql.Result\n\tvar err error\n\tresult, err = ex.database.Exec(fullSQL, args...)\n\tif err != nil {\n\t\treturn nil, logSQLError(err, \"execSQL.30\", fullSQL, args)\n\t}\n\n\treturn result, nil\n}", "func executeSQL(db *sql.DB, sql string) error {\n\tsql = strings.TrimSpace(sql)\n\tif db == nil {\n\t\tfmt.Printf(\"%s;\\n\", sql)\n\t} else {\n\t\tlog.Info(fmt.Printf(\"executeSQL: %s\", sql))\n\t\tif _, err := db.Exec(sql); err != nil {\n\t\t\treturn fmt.Errorf(\"Error executing SQL: %v: %v\", sql, err)\n\t\t}\n\t}\n\treturn nil\n}", "func rawDmsaSql(d *Database, ddlOperator string, ddlOperand string) (sqlStrings []string, err error) {\n\n\turl := joinUrlPath(d.DmsaUrl, fmt.Sprintf(\"/%s/%s/%s/postgresql/%s/\", d.Model, d.ModelVersion, ddlOperator, ddlOperand))\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\treturn sqlStrings, fmt.Errorf(\"Error getting %v: %v\", url, err)\n\t}\n\tif response.StatusCode != 200 {\n\t\treturn sqlStrings, fmt.Errorf(\"Data-models-sqlalchemy web service (%v) returned error: %v\", url, http.StatusText(response.StatusCode))\n\t}\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn sqlStrings, fmt.Errorf(\"Error reading body from %v: %v\", url, err)\n\t}\n\tbodyString := string(body)\n\n\tstmts := strings.Split(bodyString, \";\")\n\n\tfor _, stmt := range stmts {\n\t\tif strings.Contains(stmt, \"version_history\") {\n\t\t\tif strings.Contains(stmt, \"CREATE TABLE\") {\n\t\t\t\t// Kludge to work around a data-models-sqlalchemy problem; kludge will be benign even after the problem is fixed.\n\t\t\t\tstmt = strings.Replace(stmt, \"dms_version VARCHAR(16)\", \"dms_version VARCHAR(50)\", 1)\n\t\t\t}\n\t\t}\n\t\tsqlStrings = append(sqlStrings, stmt)\n\t} // end for all SQL statements\n\treturn\n}", "func (conn *dbconn) exec(ctx context.Context, name string, params []interface{}) (result sql.Result, err error) {\n\n\t// TODO: check Parameters for injection here\n\t// TODO: update the params parameter to use an interface type? So that Parameters to the sproc can have the types validated?\n\n\t// Build the command\n\tvar command string\n\tif command, err = conn.buildSprocCall(name, params); err == nil {\n\n\t\t// Verify that a valid command was created\n\t\tif len(command) > 0 {\n\t\t\tresult, err = conn.db.ExecContext(ctx, command, params...)\n\t\t} else {\n\t\t\terr = errors.Errorf(\"Invalid command creation for stored Procedure %s\", name)\n\t\t}\n\t} else {\n\t\terr = errors.Errorf(\"Error while building execution call for stored Procedure %s: %v\", name, err)\n\t}\n\treturn result, err\n}", "func Execute(query string, args ...interface{}) (sql.Result, error){\n result, err := db.Exec(query, args...)\n if err != nil && !debug { \n log.Println(err)\n }\n return result, err\n}", "func (w *Wrapper) exec(query string, args ...interface{}) (sql.Result, error) {\n\tw.connLock.RLock()\n\tdefer w.connLock.RUnlock()\n\n\treturn w.connection.Exec(w.prepare(query), args...)\n}", "func executeRequestFromStrings(s []string) *command.ExecuteRequest {\n\tstmts := make([]*command.Statement, len(s))\n\tfor i := range s {\n\t\tstmts[i] = &command.Statement{\n\t\t\tSql: s[i],\n\t\t}\n\t}\n\treturn &command.ExecuteRequest{\n\t\tRequest: &command.Request{\n\t\t\tStatements: stmts,\n\t\t\tTransaction: false,\n\t\t},\n\t\tTimings: false,\n\t}\n}", "func ProcessSQLString(sqlstr string) (string, error) {\n\t//Parse input string into an AST\n\tast, parseErr := parser.ParseInput(sqlstr)\n\tif parseErr != nil {\n\t\treturn \"\", parseErr\n\t}\n\n\t//Generate execution plan in bytecode from AST (TODO)\n\tinsns, codeGenErr := codegen.GenByteCode(ast)\n\tif codeGenErr != nil {\n\t\treturn \"\", codeGenErr\n\t}\n\n\t//Exectue bytecode on virtual machine and return results (TODO)\n\tresults, execErr := virtual_machine.ExecByteCode(insns)\n\tif execErr != nil {\n\t\treturn \"\", execErr\n\t}\n\n\treturn results, nil\n}", "func ParseQuery(query string, stmtid int) *QueryInfo {\n // Remove any comments that start before the command.\n if strings.HasPrefix(query, \"/*cmd*/\") {\n query = query[len(\"/*cmd*/\"):]\n }\n\n // Get the first word in the query, which is the command.\n words := strings.Fields(query)\n var columns []string\n var numParams int\n var numColumns int\n\n // Handle the command accordingly\n switch strings.ToLower(words[0]) {\n case \"select\":\n // WILL eventually fix to use a regex parser.\n split1 := strings.Split(query, \"from\")\n // If there was no from, then set the numParams to...0?\n // UNCLEAR\n if split1[0] == query {\n // this should be accurate\n numParams = 0\n columns = strings.Split(split1[0], \",\")\n numColumns = len(columns)\n } else {\n // Split the columns (listed after SELECT but before FROM)\n // // by ',''\n // columns = strings.Split(split1[0], \",\")\n // numParams = len(columns)\n\n\n // set temporarily to the com_stmt_prepare\n // expected in coordinator_basic\n numParams = 1\n numColumns = 2\n }\n\n case \"update\":\n // Isolate the string after keyword 'SET'\n split1 := strings.Split(query, \"set\")\n // Isolate the string before keyword 'WHERE'\n split2 := strings.Split(split1[1], \"WHERE\")\n // Split the string of column names separated by ','\n // which are between keywords SET and WHERE\n columns = strings.Split(split2[0], \",\")\n numColumns = len(columns)\n\n case \"insert\":\n // Isolate the string after '('\n split1 := strings.Split(query, \"(\")\n // Isolate the string before ')'\n split2 := strings.Split(split1[1], \")\")\n // Split the string of column names separated by ','\n // which are between table name and keyword VALUES\n columns = strings.Split(split2[0], \",\")\n numParams = len(columns)\n\n }\n\n // Return QueryInfo struct.\n return &QueryInfo{numParams:numParams, colNames:columns,\n stmtid:stmtid, query:query, numColumns:numColumns}\n}", "func (mc *MysqlConn) exec(query string) error {\n\t// Send command\n\terr := mc.writeCommandPacketStr(COM_QUERY, query)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Read Result\n\tresLen, err := mc.readResultSetHeaderPacket()\n\tif err == nil && resLen > 0 {\n\t\tif err = mc.readUntilEOF(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = mc.readUntilEOF()\n\t}\n\n\treturn err\n}", "func executeSqlFromFile(r *repo.Repo, p string) error {\n\tpath := filepath.Join(p)\n\tc, ioErr := ioutil.ReadFile(path)\n\tif ioErr != nil {\n\t\treturn ioErr\n\t}\n\tsql := string(c)\n\t_, err := r.Db.Exec(sql)\n\treturn err\n}", "func (c *sqlmock) Exec(query string, args []driver.Value) (driver.Result, error) {\n\tnamedArgs := make([]driver.NamedValue, len(args))\n\tfor i, v := range args {\n\t\tnamedArgs[i] = driver.NamedValue{\n\t\t\tOrdinal: i + 1,\n\t\t\tValue: v,\n\t\t}\n\t}\n\n\tex, err := c.exec(query, namedArgs)\n\tif ex != nil {\n\t\ttime.Sleep(ex.delay)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ex.result, nil\n}", "func execQuery(db *sql.DB, sqlQuery string, args ...interface{}) {\n\t_, dbErr := db.Exec(sqlQuery, args...)\n\tif dbErr != nil {\n\t\tLogErr(\"%s\\n\", dbErr)\n\t}\n}", "func (mc *mysqlConn) exec(query string) (e error) {\n\t// Send command\n\te = mc.writeCommandPacket(COM_QUERY, query)\n\tif e != nil {\n\t\treturn\n\t}\n\n\t// Read Result\n\tresLen, e := mc.readResultSetHeaderPacket()\n\tif e != nil {\n\t\treturn\n\t}\n\n\tmc.affectedRows = 0\n\tmc.insertId = 0\n\n\tif resLen > 0 {\n\t\t_, e = mc.readUntilEOF()\n\t\tif e != nil {\n\t\t\treturn\n\t\t}\n\n\t\tmc.affectedRows, e = mc.readUntilEOF()\n\t\tif e != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn\n}", "func (c *ClientConn) GetExecDB(tokens []string, sql string) (*ExecuteDB, error) {\n\ttokensLen := len(tokens)\n\tif 0 < tokensLen {\n\t\ttokenId, ok := mysql.PARSE_TOKEN_MAP[strings.ToLower(tokens[0])]\n\t\tif ok == true {\n\t\t\tswitch tokenId {\n\t\t\tcase mysql.TK_ID_SELECT:\n\t\t\t\tfmt.Println(\"select command\")\n\t\t\t\t//return c.getSelectExecDB(sql, tokens, tokensLen)\n\t\t\tcase mysql.TK_ID_DELETE:\n\t\t\t\tfmt.Println(\"delete command\")\n\t\t\t\t//return c.getDeleteExecDB(sql, tokens, tokensLen)\n\t\t\tcase mysql.TK_ID_INSERT, mysql.TK_ID_REPLACE:\n\t\t\t\tfmt.Println(\"insert repliace command\")\n\t\t\t\t//return c.getInsertOrReplaceExecDB(sql, tokens, tokensLen)\n\t\t\tcase mysql.TK_ID_UPDATE:\n\t\t\t\tfmt.Println(\"update command\")\n\t\t\t\t//return c.getUpdateExecDB(sql, tokens, tokensLen)\n\t\t\tcase mysql.TK_ID_SET:\n\t\t\t\tfmt.Println(\"set commmand\")\n\t\t\t\t//return c.getSetExecDB(sql, tokens, tokensLen)\n\t\t\tcase mysql.TK_ID_SHOW:\n\t\t\t\tfmt.Println(\"show command\")\n\t\t\t\t//return c.getShowExecDB(sql, tokens, tokensLen)\n\t\t\tcase mysql.TK_ID_TRUNCATE:\n\t\t\t\tfmt.Println(\"truncate command \")\n\t\t\t\t//return c.getTruncateExecDB(sql, tokens, tokensLen)\n\t\t\tdefault:\n\t\t\t\treturn nil, nil\n\t\t\t}\n\t\t}\n\t}\n\texecuteDB := new(ExecuteDB)\n\texecuteDB.sql = sql\n\t//err := c.setExecuteNode(tokens, tokensLen, executeDB)\n\t// if err != nil {\n\t// \treturn nil, err\n\t// }\n\treturn executeDB, nil\n}", "func parseSQL(ql string) (*stmt.Metadata, error) {\n\tquery, err := sql.Parse(ql)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmetaQuery, ok := query.(*stmt.Metadata)\n\tif !ok {\n\t\treturn nil, errWrongQueryStmt\n\t}\n\treturn metaQuery, nil\n}", "func TestToSql(t *testing.T) {\n\tfor _, sqlStrIn := range sqlStrings {\n\t\tu.Debug(\"parsing next one \", sqlStrIn)\n\t\tstmt1 := parseOrPanic(t, sqlStrIn)\n\t\tsqlSel1 := stmt1.(*SqlSelect)\n\t\tsqlRt := sqlSel1.StringAST()\n\t\tu.Warnf(\"About to parse roundtrip \\n%v\", sqlRt)\n\t\tstmt2 := parseOrPanic(t, sqlRt)\n\t\tcompareAst(t, stmt1, stmt2)\n\t}\n}", "func ExecuteScriptQuery(rq *http.Request, queriesPath string, script string)([]byte,error) {\n\t//log.Printf(\"script:%+v\\n\",script)\n\tsqlPath, err := config.PrestConf.Adapter.GetScript(rq.Method, queriesPath, script)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"could not get script %s/%s, %+v\", queriesPath, script, err)\n\t\treturn nil, err\n\t}\n\t//fmt.Printf(\"rq.URL.Query():%+v \\n\", rq.URL.Query())\n\tsql, values, err := config.PrestConf.Adapter.ParseScript(sqlPath, rq.URL.Query())\n\tif err != nil {\n\t\terr = fmt.Errorf(\"could not parse script %s/%s, %+v\", queriesPath, script, err)\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"sql:%+v\\n\",sql)\n\t//test\n\t// A,B,C:=config.PrestConf.Adapter.WhereByRequest(rq,10)\n\t// fmt.Printf(\"%+v %+v %+v\\n\",A,B,C )\n\t// fmt.Printf(\"A:%+v \\n\", A)\n\t// fmt.Printf(\"values:%+v \\n\",values )\n\t//test\n\t_ , _ ,PaginateStr := GetPaginateStr(rq)\n\tpaginateSql := sql + PaginateStr\n\tsc := config.PrestConf.Adapter.ExecuteScripts(rq.Method, paginateSql, values)\n\tif sc.Err() != nil {\n\t\terr = fmt.Errorf(\"could not execute sql %+v, %s\", sc.Err(), sql)\n\t\treturn nil , err\n\t}\n\treturn sc.Bytes(), nil\n}", "func (db *DB) do(query string, arguments []interface{}) (sql.Result, error) {\n\tquery = db.replacePlaceholders(query)\n\n\t// Execute the statement\n\tstartTime := time.Now()\n\tqueryable, err := db.getQueryable(query)\n\tif err != nil {\n\t\tdb.logExecutionErr(err, query, arguments)\n\t\treturn nil, err\n\t}\n\tresult, err := queryable.Exec(arguments...)\n\tconsumedTime := timeElapsedSince(startTime)\n\tdb.addConsumedTime(consumedTime)\n\tdb.logExecution(consumedTime, query, arguments)\n\tif err != nil {\n\t\tdb.logExecutionErr(err, query, arguments)\n\t\tif db.useErrorParser {\n\t\t\treturn nil, db.adapter.ParseError(err)\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn result, err\n}", "func (ar *ActiveRecord) ExecString() string {\n\tstr := strings.Join(ar.Tokens, \" \")\n\tif len(ar.Args) > 0 {\n\t\tfor i, _ := range ar.Args {\n\t\t\tstr = strings.Replace(str, holder, fmt.Sprintf(\"$%d\", i+1), 1)\n\t\t}\n\t}\n\treturn str\n}", "func (pge *PgEngine) ExecuteSQLCommand(ctx context.Context, executor executor, command string, paramValues []string) (out string, err error) {\n\tvar ct pgconn.CommandTag\n\tvar params []interface{}\n\n\tif strings.TrimSpace(command) == \"\" {\n\t\treturn \"\", errors.New(\"SQL command cannot be empty\")\n\t}\n\tif len(paramValues) == 0 { //mimic empty param\n\t\tct, err = executor.Exec(ctx, command)\n\t\tout = string(ct)\n\t} else {\n\t\tfor _, val := range paramValues {\n\t\t\tif val > \"\" {\n\t\t\t\tif err = json.Unmarshal([]byte(val), &params); err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tct, err = executor.Exec(ctx, command, params...)\n\t\t\t\tout = out + string(ct) + \"\\n\"\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func exec(stmt *sql.Stmt, args ...interface{}) error {\n\t_, err := stmt.Exec(args...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"mysql: could not execute statement: %v\", err)\n\t}\n\treturn nil\n}", "func (statement *Statement) SQL(query interface{}, args ...interface{}) *Statement {\n\tswitch query.(type) {\n\tcase (*builder.Builder):\n\t\tvar err error\n\t\tstatement.RawSQL, statement.RawParams, err = query.(*builder.Builder).ToSQL()\n\t\tif err != nil {\n\t\t\tstatement.LastError = err\n\t\t}\n\tcase string:\n\t\tstatement.RawSQL = query.(string)\n\t\tstatement.RawParams = args\n\tdefault:\n\t\tstatement.LastError = ErrUnSupportedSQLType\n\t}\n\n\treturn statement\n}", "func (db *DB) PlanAndExecute(querystring string) ([]*influxql.Row, error) {\n\t// Plan statement.\n\tp := influxql.NewPlanner(db)\n\tp.Now = func() time.Time { return db.Now }\n\te, err := p.Plan(MustParseSelectStatement(querystring))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Execute plan.\n\tch, err := e.Execute()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Collect resultset.\n\tvar rs []*influxql.Row\n\tfor row := range ch {\n\t\trs = append(rs, row)\n\t}\n\n\treturn rs, nil\n}", "func (db *DB) executeQuery(query string, arguments []interface{}, noTx, noStmtCache bool) (*sql.Rows, []string, error) {\n\tquery = db.replacePlaceholders(query)\n\n\tstartTime := time.Now()\n\tqueryable, err := db.getQueryableWithOptions(query, noTx, noStmtCache)\n\tif err != nil {\n\t\tdb.logExecutionErr(err, query, arguments)\n\t\treturn nil, nil, err\n\t}\n\trows, err := queryable.Query(arguments...)\n\tconsumedTime := timeElapsedSince(startTime)\n\tdb.addConsumedTime(consumedTime)\n\tdb.logExecution(consumedTime, query, arguments)\n\tif err != nil {\n\t\tdb.logExecutionErr(err, query, arguments)\n\t\treturn nil, nil, err\n\t}\n\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\tdb.logExecutionErr(err, query, arguments)\n\t\trows.Close()\n\t\treturn nil, nil, err\n\t}\n\n\treturn rows, columns, nil\n}", "func execAqlQuery(query string) (interface{}, error) {\n\turl := \"rest/v1/query/?aql=\" + url.QueryEscape(query)\n\tdata, err := HttpGetJsonThink(url)\n\terrorHandler(err, \"execAqlQuery()\")\n\n\treturn data, nil\n}", "func GenerateSQLFromInput(db *sql.DB, input string) (string, error) {\n\tvar output string\n\tqueryTypes := [4]string{\n\t\t`([a-zA-Z].*?) ([<>]) ([0-9-]*)`,\n\t\t`([a-zA-Z].*?) ([a-zA-Z].*)`,\n\t\t`([a-zA-Z].*) ([a-zA-Z].*) [\\/] ([a-zA-Z].*) ([a-zA-Z]*)`,\n\t\t`([a-zA-Z].*?) \\*`}\n\n\t// TODO Update SQL to more accurately query last statement\n\tqueryTemplates := [4]string{\n\t\t`SELECT distinct(company) from financials where key='%v' and value %v %v order by end_date desc;`,\n\t\t`SELECT value from financials where company = '%v' and key='%v' order by end_date desc limit 1;`,\n\t\t`SELECT A.value / B.value AS value FROM (SELECT value from financials where company = '%v' and key='%v' order by end_date desc limit 1) A,(SELECT value from financials where company = '%v' and key='%v' order by end_date desc limit 1) B;`,\n\t\t`SELECT distinct(key), value from financials where company = '%v' order by end_date desc;`}\n\n\tvar rowsArray []string\n\n\tfor i, queryType := range queryTypes {\n\t\tr := regexp.MustCompile(queryType)\n\t\tmatches := r.FindStringSubmatch(input)\n\t\tif matches == nil {\n\t\t\tcontinue\n\t\t}\n\t\t// We found a matching regex, now let's make the SQL query\n\t\tt := queryTemplates[i]\n\t\tvar q string\n\n\t\tswitch i {\n\t\tcase 0:\n\t\t\tq = fmt.Sprintf(t, matches[1], matches[2], matches[3])\n\t\t\tbreak\n\t\tcase 1:\n\t\t\tq = fmt.Sprintf(t, matches[1], matches[2])\n\t\t\tbreak\n\t\tcase 2:\n\t\t\tq = fmt.Sprintf(t, matches[1], matches[2], matches[3], matches[4])\n\t\t\tbreak\n\t\tcase 3:\n\t\t\tq = fmt.Sprintf(t, matches[1])\n\t\t\tbreak\n\t\t}\n\n\t\trows, err := db.Query(q)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\treturn \"\", err\n\t\t}\n\t\tdefer rows.Close()\n\t\tfor rows.Next() {\n\t\t\tvar err error\n\t\t\tvar key, value, row, company string\n\t\t\tswitch i {\n\t\t\tcase 0:\n\t\t\t\terr = rows.Scan(&company)\n\t\t\t\trow = company\n\t\t\t\tbreak\n\t\t\tcase 3:\n\t\t\t\terr = rows.Scan(&key, &value)\n\t\t\t\trow = key + \", \" + value\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\terr = rows.Scan(&value)\n\t\t\t\trow = value\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\trowsArray = append(rowsArray, row)\n\t\t}\n\t\toutput = strings.Join(rowsArray, \"\\n\")\n\t}\n\n\treturn output, nil\n}", "func queryRequestFromStrings(s []string) *command.QueryRequest {\n\tstmts := make([]*command.Statement, len(s))\n\tfor i := range s {\n\t\tstmts[i] = &command.Statement{\n\t\t\tSql: s[i],\n\t\t}\n\t}\n\treturn &command.QueryRequest{\n\t\tRequest: &command.Request{\n\t\t\tStatements: stmts,\n\t\t\tTransaction: false,\n\t\t},\n\t\tTimings: false,\n\t}\n}", "func Run(sql string) response.Message {\n\n\tr := new(run)\n\tjson.Unmarshal([]byte(sql), &r)\n\n\tif db.DB() == nil {\n\t\treturn response.Message{\n\t\t\tType: legend.TypeError,\n\t\t\tMessage: translate.T(legend.MessageNoConnection),\n\t\t}\n\t}\n\n\t//Normalize query\n\n\t//Check select\n\tif strings.HasPrefix(strings.TrimSpace(strings.ToUpper(r.Run)), legend.SELECT) {\n\n\t\trows, err := db.DB().Conx().QueryContext(context.Background(), r.Run)\n\n\t\tif err != nil {\n\t\t\treturn response.Message{\n\t\t\t\tType: legend.TypeError,\n\t\t\t\tMessage: err.Error(),\n\t\t\t}\n\t\t}\n\n\t\tdefer rows.Close()\n\n\t\tcols, _ := rows.Columns()\n\t\tdata := make([][]interface{}, 0)\n\t\tt, _ := rows.ColumnTypes()\n\t\tfor i := range t {\n\t\t\tfmt.Println(*t[i])\n\t\t}\n\n\t\tfor rows.Next() {\n\n\t\t\tvalues := make([]interface{}, len(cols))\n\t\t\tpointers := make([]interface{}, len(cols))\n\n\t\t\tfor i := range values {\n\t\t\t\tpointers[i] = &values[i]\n\t\t\t}\n\n\t\t\tif err := rows.Scan(pointers...); err != nil {\n\t\t\t\t// Check for a scan error.\n\t\t\t\t// Query rows will be closed with defer.\n\t\t\t\treturn response.Message{\n\t\t\t\t\tType: legend.TypeError,\n\t\t\t\t\tMessage: err.Error(),\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tfor key, val := range values {\n\n\t\t\t\tswitch val.(type) {\n\n\t\t\t\tcase []uint8:\n\t\t\t\t\tf, _ := strconv.ParseFloat(string(val.([]byte)), 64)\n\t\t\t\t\tvalues[key] = f\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tdata = append(data, values)\n\n\t\t}\n\n\t\t// If the database is being written to ensure to check for Close\n\t\t// errors that may be returned from the driver. The query may\n\t\t// encounter an auto-commit error and be forced to rollback changes.\n\t\terr = rows.Close()\n\n\t\tif err != nil {\n\t\t\treturn response.Message{\n\t\t\t\tType: legend.TypeError,\n\t\t\t\tMessage: err.Error(),\n\t\t\t}\n\t\t}\n\n\t\terr = rows.Err()\n\n\t\tif err != nil {\n\t\t\treturn response.Message{\n\t\t\t\tType: legend.TypeError,\n\t\t\t\tMessage: err.Error(),\n\t\t\t}\n\t\t}\n\n\t\treturn response.Message{\n\t\t\tData: ReturnRows{\n\t\t\t\tRows: data,\n\t\t\t\tColumns: cols,\n\t\t\t},\n\t\t}\n\t\t//Check others types\n\t} else {\n\n\t\tz, err := db.DB().Conx().ExecContext(context.Background(), r.Run)\n\n\t\tif err != nil {\n\t\t\treturn response.Message{\n\t\t\t\tType: legend.TypeError,\n\t\t\t\tMessage: err.Error(),\n\t\t\t}\n\t\t}\n\t\tfmt.Println(z.LastInsertId())\n\t\tnr, _ := z.RowsAffected()\n\n\t\treturn response.Message{\n\t\t\tType: legend.TypeSucces,\n\t\t\tMessage: translate.T(legend.MessageRowsAffected, nr),\n\t\t}\n\n\t}\n\n}", "func Exec(sql string) (sql.Result, error) {\n\treturn database.Exec(sql)\n}", "func CreateCommandSQL() rm.Command {\n\treturn rm.Command{\n\t\tUsage: \"SQL query\",\n\t\tDesc: `Execute a query with SQLITE`,\n\t\tName: \"sql\",\n\t\tFlags: \"readonly random no-cluster\",\n\t\tFirstKey: 1, LastKey: 1, KeyStep: 1,\n\t\tAction: func(cmd rm.CmdContext) int {\n\t\t\tctx, args := cmd.Ctx, cmd.Args\n\t\t\tif len(cmd.Args) != 2 {\n\t\t\t\treturn ctx.WrongArity()\n\t\t\t}\n\t\t\tctx.AutoMemory()\n\t\t\tsql := args[1].String()\n\t\t\tctx.Log(rm.LOG_DEBUG, sql)\n\n\t\t\t// query the database\n\t\t\trows, err := db.Query(sql)\n\t\t\tdefer rows.Close()\n\n\t\t\t// output\n\t\t\tout := make([]map[string]interface{}, 0)\n\t\t\tcolumns, err := rows.Columns()\n\t\t\tif err != nil {\n\t\t\t\tctx.ReplyWithError(err.Error())\n\t\t\t\treturn rm.ERR\n\t\t\t}\n\n\t\t\tcount := len(columns)\n\t\t\tvalues := make([]interface{}, count)\n\t\t\tscanArgs := make([]interface{}, count)\n\t\t\tfor i := range values {\n\t\t\t\tscanArgs[i] = &values[i]\n\t\t\t}\n\t\t\tfor rows.Next() {\n\t\t\t\terr = rows.Scan(scanArgs...)\n\t\t\t\tif err != nil {\n\t\t\t\t\tctx.ReplyWithError(err.Error())\n\t\t\t\t\treturn rm.ERR\n\t\t\t\t}\n\t\t\t\trecord := make(map[string]interface{})\n\t\t\t\tfor i, v := range values {\n\t\t\t\t\trecord[columns[i]] = v\n\t\t\t\t}\n\t\t\t\tout = append(out, record)\n\t\t\t}\n\t\t\terr = rows.Err()\n\t\t\tif err != nil {\n\t\t\t\tctx.ReplyWithError(err.Error())\n\t\t\t\treturn rm.ERR\n\t\t\t}\n\t\t\tbytes, err := json.Marshal(out)\n\t\t\tif err != nil {\n\t\t\t\tctx.ReplyWithError(err.Error())\n\t\t\t\treturn rm.ERR\n\t\t\t}\n\t\t\tres := string(bytes)\n\n\t\t\tctx.Log(rm.LOG_DEBUG, res)\n\t\t\tctx.ReplyWithSimpleString(res)\n\t\t\treturn rm.OK\n\t\t},\n\t}\n}", "func (stmt *Statement) Run(params ...interface{}) (res *Result, err os.Error) {\n defer stmt.db.unlockIfError(&err)\n defer catchOsError(&err)\n stmt.db.lock()\n\n if stmt.db.conn == nil {\n return nil, NOT_CONN_ERROR\n }\n if stmt.db.unreaded_rows {\n return nil, UNREADED_ROWS_ERROR\n }\n\n // Bind parameters if any\n if len(params) != 0 {\n stmt.BindParams(params...)\n }\n\n // Send EXEC command with binded parameters\n stmt.sendCmdExec()\n // Get response\n res = stmt.db.getResponse(true)\n res.binary = true\n return\n}", "func execn1ql(line string, t *testing.T) bool {\n\n\tvar liner = liner.NewLiner()\n\tdefer liner.Close()\n\n\tvar b bytes.Buffer\n\tw := bufio.NewWriter(&b)\n\tcommand.SetWriter(w)\n\n\tdBn1ql, err := n1ql.OpenExtended(Server)\n\tn1ql.SetUsernamePassword(\"Administrator\", \"password\")\n\tif err != nil {\n\t\t// If the test cannot connect to a server\n\t\t// don't execute the TestExecN1QLStmt method.\n\t\ttestconn := false\n\t\tt.Logf(\"Cannot connect to %v\", Server)\n\t\treturn testconn\n\t} else {\n\t\t//Successfully logged into the server\n\t\t//For the case where server url is valid\n\t\t//sql.Open will not throw an error. Hence ping\n\t\t//the server and see if it returns an error.\n\n\t\terr = dBn1ql.Ping()\n\n\t\tif err != nil {\n\t\t\ttestconn := false\n\t\t\tt.Logf(\"Cannot connect to %v\", Server)\n\t\t\treturn testconn\n\t\t}\n\n\t\terrC, errS := ExecN1QLStmt(line, dBn1ql, w)\n\t\tw.Flush()\n\t\tif errC != 0 {\n\t\t\tt.Errorf(\"Error executing statement : %v\", line)\n\t\t\tt.Error(command.HandleError(errC, errS))\n\t\t} else {\n\t\t\tt.Log(\"Ran command \", line, \" successfully.\")\n\t\t\tt.Logf(\"%s\", b.String())\n\t\t}\n\t}\n\tb.Reset()\n\treturn true\n}", "func execSQL(stmt *sql.Stmt, args ...interface{}) (sql.Result, error) {\n\tr, err := stmt.Exec(args...)\n\tif err != nil {\n\t\treturn r, fmt.Errorf(\"mysql: could not execute statement: %v\", err)\n\t}\n\trowsAffected, err := r.RowsAffected()\n\tif err != nil {\n\t\treturn r, fmt.Errorf(\"mysql: could not get rows affected: %v\", err)\n\t} else if rowsAffected != 1 {\n\t\treturn r, fmt.Errorf(\"mysql: expected 1 row affected, got %d\", rowsAffected)\n\t}\n\treturn r, nil\n}", "func SqlcmdExec(\n\tcfg Config,\n\tquery string,\n) (string, error) {\n\targs := []string{\n\t\t\"-S\", fmt.Sprintf(\"%s,%s\", cfg.Host, cfg.Port),\n\t\t\"-U\", cfg.Username,\n\t\t\"-P\", cfg.Password,\n\t\t\"-Q\", query,\n\t}\n\n\tif cfg.ReadOnly == true {\n\t\targs = append(args, \"-K\", \"ReadOnly\")\n\t}\n\n\tif db := cfg.Database; db != \"\" {\n\t\targs = append(args, \"-d\", db)\n\t}\n\n\tout, err := exec.Command(\n\t\t\"sqlcmd\",\n\t\targs...,\n\t).Output()\n\n\tif err != nil {\n\t\tif exitErrr, ok := err.(*exec.ExitError); ok {\n\t\t\treturn \"\", errors.New(string(exitErrr.Stderr))\n\t\t}\n\n\t\treturn \"\", err\n\t}\n\n\treturn string(out), nil\n}", "func Exec(query string, args ...interface{}) (sql.Result, error) {\n\tdb, err := sql.Open(driver, conninfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer db.Close()\n\n\tres, err := db.Exec(query, args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n}", "func execute(dbStr string, db *gorm.DB) []newhorizons.NookMiles {\n\tdb.RWMutex.RLock()\n\tdefer db.RWMutex.RUnlock()\n\tvar nm []newhorizons.NookMiles\n\tdb.Raw(dbStr).Find(&nm)\n\tif len(nm) == 0 {\n\t\treturn nil\n\t}\n\treturn nm\n}", "func (session *Session) SQL(query interface{}, args ...interface{}) *Session {\n\tsession.Session = session.Session.SQL(query, args...)\n\treturn session\n}", "func (c *Conn) Query(ctx context.Context, sql string, args ...any) (Rows, error) {\n\tif c.queryTracer != nil {\n\t\tctx = c.queryTracer.TraceQueryStart(ctx, c, TraceQueryStartData{SQL: sql, Args: args})\n\t}\n\n\tif err := c.deallocateInvalidatedCachedStatements(ctx); err != nil {\n\t\tif c.queryTracer != nil {\n\t\t\tc.queryTracer.TraceQueryEnd(ctx, c, TraceQueryEndData{Err: err})\n\t\t}\n\t\treturn &baseRows{err: err, closed: true}, err\n\t}\n\n\tvar resultFormats QueryResultFormats\n\tvar resultFormatsByOID QueryResultFormatsByOID\n\tmode := c.config.DefaultQueryExecMode\n\tvar queryRewriter QueryRewriter\n\noptionLoop:\n\tfor len(args) > 0 {\n\t\tswitch arg := args[0].(type) {\n\t\tcase QueryResultFormats:\n\t\t\tresultFormats = arg\n\t\t\targs = args[1:]\n\t\tcase QueryResultFormatsByOID:\n\t\t\tresultFormatsByOID = arg\n\t\t\targs = args[1:]\n\t\tcase QueryExecMode:\n\t\t\tmode = arg\n\t\t\targs = args[1:]\n\t\tcase QueryRewriter:\n\t\t\tqueryRewriter = arg\n\t\t\targs = args[1:]\n\t\tdefault:\n\t\t\tbreak optionLoop\n\t\t}\n\t}\n\n\tif queryRewriter != nil {\n\t\tvar err error\n\t\toriginalSQL := sql\n\t\toriginalArgs := args\n\t\tsql, args, err = queryRewriter.RewriteQuery(ctx, c, sql, args)\n\t\tif err != nil {\n\t\t\trows := c.getRows(ctx, originalSQL, originalArgs)\n\t\t\terr = fmt.Errorf(\"rewrite query failed: %v\", err)\n\t\t\trows.fatal(err)\n\t\t\treturn rows, err\n\t\t}\n\t}\n\n\t// Bypass any statement caching.\n\tif sql == \"\" {\n\t\tmode = QueryExecModeSimpleProtocol\n\t}\n\n\tc.eqb.reset()\n\tanynil.NormalizeSlice(args)\n\trows := c.getRows(ctx, sql, args)\n\n\tvar err error\n\tsd, explicitPreparedStatement := c.preparedStatements[sql]\n\tif sd != nil || mode == QueryExecModeCacheStatement || mode == QueryExecModeCacheDescribe || mode == QueryExecModeDescribeExec {\n\t\tif sd == nil {\n\t\t\tsd, err = c.getStatementDescription(ctx, mode, sql)\n\t\t\tif err != nil {\n\t\t\t\trows.fatal(err)\n\t\t\t\treturn rows, err\n\t\t\t}\n\t\t}\n\n\t\tif len(sd.ParamOIDs) != len(args) {\n\t\t\trows.fatal(fmt.Errorf(\"expected %d arguments, got %d\", len(sd.ParamOIDs), len(args)))\n\t\t\treturn rows, rows.err\n\t\t}\n\n\t\trows.sql = sd.SQL\n\n\t\terr = c.eqb.Build(c.typeMap, sd, args)\n\t\tif err != nil {\n\t\t\trows.fatal(err)\n\t\t\treturn rows, rows.err\n\t\t}\n\n\t\tif resultFormatsByOID != nil {\n\t\t\tresultFormats = make([]int16, len(sd.Fields))\n\t\t\tfor i := range resultFormats {\n\t\t\t\tresultFormats[i] = resultFormatsByOID[uint32(sd.Fields[i].DataTypeOID)]\n\t\t\t}\n\t\t}\n\n\t\tif resultFormats == nil {\n\t\t\tresultFormats = c.eqb.ResultFormats\n\t\t}\n\n\t\tif !explicitPreparedStatement && mode == QueryExecModeCacheDescribe {\n\t\t\trows.resultReader = c.pgConn.ExecParams(ctx, sql, c.eqb.ParamValues, sd.ParamOIDs, c.eqb.ParamFormats, resultFormats)\n\t\t} else {\n\t\t\trows.resultReader = c.pgConn.ExecPrepared(ctx, sd.Name, c.eqb.ParamValues, c.eqb.ParamFormats, resultFormats)\n\t\t}\n\t} else if mode == QueryExecModeExec {\n\t\terr := c.eqb.Build(c.typeMap, nil, args)\n\t\tif err != nil {\n\t\t\trows.fatal(err)\n\t\t\treturn rows, rows.err\n\t\t}\n\n\t\trows.resultReader = c.pgConn.ExecParams(ctx, sql, c.eqb.ParamValues, nil, c.eqb.ParamFormats, c.eqb.ResultFormats)\n\t} else if mode == QueryExecModeSimpleProtocol {\n\t\tsql, err = c.sanitizeForSimpleQuery(sql, args...)\n\t\tif err != nil {\n\t\t\trows.fatal(err)\n\t\t\treturn rows, err\n\t\t}\n\n\t\tmrr := c.pgConn.Exec(ctx, sql)\n\t\tif mrr.NextResult() {\n\t\t\trows.resultReader = mrr.ResultReader()\n\t\t\trows.multiResultReader = mrr\n\t\t} else {\n\t\t\terr = mrr.Close()\n\t\t\trows.fatal(err)\n\t\t\treturn rows, err\n\t\t}\n\n\t\treturn rows, nil\n\t} else {\n\t\terr = fmt.Errorf(\"unknown QueryExecMode: %v\", mode)\n\t\trows.fatal(err)\n\t\treturn rows, rows.err\n\t}\n\n\tc.eqb.reset() // Allow c.eqb internal memory to be GC'ed as soon as possible.\n\n\treturn rows, rows.err\n}", "func (b *Blueprint) Execute(conn Connection) []string {\n\tgrammar := conn.GetQueryGrammar()\n\tstatements := b.toSQL(&conn, grammar)\n\n\tfor _, statement := range statements {\n\t\tfmt.Println(statement)\n\t\tif _, err := conn.Exec(statement); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\treturn statements\n}", "func (q *Query) execute(db *sqlx.DB, resultPtr interface{}, mode executeMode) (numRowsAffected uint64, err error) {\n\t// Handle invalid input.\n\tif db == nil {\n\t\treturn 0, errors.New(\"db cannot be nil\")\n\t}\n\tswitch mode {\n\tcase _EXECUTE_MODE_NO_PARSE:\n\t\tbreak\n\tcase _EXECUTE_MODE_PARSE_SINGLE:\n\t\tif !isPointer(resultPtr) || isPointerToSlice(resultPtr) {\n\t\t\treturn 0, fmt.Errorf(\"Result pointer cannot point to slice when in ParseSingle mode. ResultPtr: %+v\", resultPtr)\n\t\t}\n\tcase _EXECUTE_MODE_PARSE_LIST:\n\t\tif !isPointer(resultPtr) || !isPointerToSlice(resultPtr) {\n\t\t\treturn 0, fmt.Errorf(\"Result pointer must point to slice when in ParseList mode. ResultPtr: %+v\", resultPtr)\n\t\t}\n\tdefault:\n\t\treturn 0, fmt.Errorf(\"Invalid execute mode: %d\", mode)\n\t}\n\n\t// Get SQL.\n\tqSql, qSqlArgs, err := q.ToSql()\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"Error building Query SQL: %s\", err.Error())\n\t}\n\n\t// Execute SQL with args on db.\n\tvar rawExecResult sql.Result\n\tswitch mode {\n\tcase _EXECUTE_MODE_NO_PARSE:\n\t\trawExecResult, err = db.Exec(qSql, qSqlArgs...)\n\tcase _EXECUTE_MODE_PARSE_SINGLE:\n\t\terr = db.Get(resultPtr, qSql, qSqlArgs...)\n\tcase _EXECUTE_MODE_PARSE_LIST:\n\t\terr = db.Select(resultPtr, qSql, qSqlArgs...)\n\t}\n\n\t// Handle any specific soft errors.\n\tif err == sql.ErrNoRows {\n\t\t// If specifically encountered this error, then set the number of rows affected to 0, and\n\t\t// return with no error immediately.\n\t\treturn 0, nil\n\t}\n\n\t// Handle hard errors.\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"Error running Query: %s. SQL:%s, SQL args:%+v\", err.Error(), qSql, qSqlArgs)\n\t}\n\n\t// Do any additional per-mode handling of result/return values.\n\tswitch mode {\n\tcase _EXECUTE_MODE_NO_PARSE:\n\t\t// If no-parse mode, then attempt using the raw sql.Result to determine number of rows\n\t\t// affected\n\t\tnumRowsAffectedInt, err := rawExecResult.RowsAffected()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tnumRowsAffected = uint64(numRowsAffectedInt)\n\tcase _EXECUTE_MODE_PARSE_SINGLE:\n\t\t// If single mode, then assuming sql.ErrNoRows was caught above, we must have retrieved a\n\t\t// single result.\n\t\tnumRowsAffected = 1\n\tcase _EXECUTE_MODE_PARSE_LIST:\n\t\t// Otherwise, if in multi mode, then explicitly count number of items returned via\n\t\t// reflection, assuming the input was indeed a pointer to a slice.\n\t\tnumRowsAffected, err = getPointerSliceLength(resultPtr)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\t// Return with success.\n\treturn numRowsAffected, nil\n}", "func queryStmt(queryStmt string) []byte {\n\tif db == nil {\n\t\tdb = getDB()\n\t}\n\tvar result []byte\n\terr := db.QueryRow(getJSONQuery(queryStmt)).Scan(&result)\n\n\t//rows, _ := db.Query(queryStmt)\n\t//printRows(rows)\n\tif err != nil {\n\t\tresult = []byte(\"there was an error executing query\")\n\t}\n\treturn result\n\n}", "func TestRawQuery(t *testing.T) {\n\tassert := assert.New(t)\n\tquery, params := Build(NewRawQuery(\"SELECT * FROM Users WHERE ID >= ?\", 10))\n\tassertEqual(assert, \"SELECT * FROM Users WHERE ID >= ?\", query)\n\tassertParams(assert, []interface{}{10}, params)\n}", "func TestSingleSQL(t *testing.T) {\n\t// sql := \"INSERT INTO NATION VALUES (1, 'NAME1',21, 'COMMENT1'), (2, 'NAME2', 22, 'COMMENT2')\"\n\t// sql := \"insert into dept values (11, 'aa', 'bb')\"\n\t// sql := \"delete from dept where deptno > 10\"\n\t// sql := \"delete from nation where n_nationkey > 10\"\n\t// sql := \"delete nation, nation2 from nation join nation2 on nation.n_name = nation2.n_name\"\n\t// sql := \"update nation set n_name ='a' where n_nationkey > 10\"\n\t// sql := \"update dept set deptno = 11 where deptno = 10\"\n\tsql := \"prepare stmt1 from update nation set n_name = ? where n_nationkey = ?\"\n\tmock := NewMockOptimizer(true)\n\tlogicPlan, err := runOneStmt(mock, t, sql)\n\tif err != nil {\n\t\tt.Fatalf(\"%+v\", err)\n\t}\n\toutPutPlan(logicPlan, true, t)\n}", "func (d *Database) Execute(query string, args ...interface{}) (sql.Result, error) {\n\tvar result sql.Result\n\n\tstmtIns, err := d.Conn.Prepare(query)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tdefer stmtIns.Close()\n\n\tresult, err = stmtIns.Exec(args...)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\treturn result, nil\n}", "func (conn *dbconn) call(ctx context.Context, sproc string, params []interface{}) (rows *sql.Rows, err error) {\n\n\t// TODO: check Parameters for injection here\n\t// TODO: update the params parameter to use an interface type? So that Parameters to the sproc can have the types validated?\n\n\t// Build the command\n\tvar command string\n\tif command, err = conn.buildSprocCall(sproc, params); err == nil {\n\n\t\t// Verify that a valid command was created\n\t\tif len(command) > 0 {\n\t\t\tvar stmt *sql.Stmt\n\t\t\tif stmt, err = conn.db.Prepare(command); err == nil {\n\t\t\t\tdefer func() {\n\t\t\t\t\t_ = stmt.Close()\n\t\t\t\t}()\n\n\t\t\t\t// Return rows and error from the query\n\t\t\t\trows, err = stmt.Query(params...)\n\t\t\t}\n\t\t} else {\n\t\t\terr = errors.Errorf(\"Invalid command creation for stored Procedure %s\", sproc)\n\t\t}\n\t} else {\n\t\terr = errors.Errorf(\"Error while building execution call for stored Procedure %s: %v\", sproc, err)\n\t}\n\n\treturn rows, err\n}", "func (w *Wrapper) query(query string, args ...interface{}) (*sql.Rows, error) {\n\tw.connLock.RLock()\n\tdefer w.connLock.RUnlock()\n\n\treturn w.connection.Query(w.prepare(query), args...)\n}", "func (c *Connection) RawQuery(stmt string, args ...interface{}) *Query {\n\treturn Q(c).RawQuery(stmt, args...)\n}", "func SQL(query string) {\n\tprintLog(\"sql\", query)\n}", "func (session *Session) Sql(query string, args ...interface{}) *Session {\n\tsession.Session = session.Session.Sql(query, args...)\n\treturn session\n}", "func (p *PgSQL) Execute(query string, args ...interface{}) (sql.Result, error) {\n\tvar result sql.Result\n\n\tstmtIns, err := p.Connection.Prepare(query)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tdefer stmtIns.Close()\n\n\tresult, err = stmtIns.Exec(args...)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\treturn result, nil\n}", "func executor(in string) {\n\ts := strings.TrimSpace(in)\n\ts = strings.TrimSuffix(in, \";\")\n\tif s == \"\" {\n\t\treturn\n\t} else if s == \"quit\" || s == \"exit\" {\n\t\tos.Exit(0)\n\t} else {\n\t\tspin := spinner.New(spinner.CharSets[14], 100*time.Millisecond)\n\t\tspin.Start()\n\t\tdefer spin.Stop()\n\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tsigCh := make(chan os.Signal, 1)\n\t\tsignal.Notify(sigCh, os.Interrupt) // sigCh only listens to os.Interrupt\n\t\t// Listen to the os interrupt signal which is ctrl+c\n\t\t// when ctrl+c is pressed, cancel current query\n\t\tgo func() {\n\t\t\tselect {\n\t\t\tcase <-sigCh:\n\t\t\t\tcancel()\n\t\t\t\treturn\n\t\t\t}\n\t\t}()\n\n\t\tresultCh := make(chan string, 1)\n\t\terrCh := make(chan error, 1)\n\t\tgo sqlRunner(s, resultCh, errCh)\n\n\t\t// The main executor function will have to wait until the query is done or canceled\n\t\t// so that new prompts won't popup\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase r := <-resultCh:\n\t\t\tfmt.Println(r)\n\t\tcase e := <-errCh:\n\t\t\tfmt.Println(e)\n\t\t}\n\t}\n}", "func (w *Wrapper) runQuery() (rows *sql.Rows, err error) {\n\tw.cleanBefore()\n\tw.buildQuery()\n\tw.LastQuery = w.query\n\tw.LastParams = w.params\n\t// Calculate the execution time.\n\tvar start time.Time\n\tif w.tracing {\n\t\tstart = time.Now()\n\t}\n\t// Execute the query if the wrapper is executable.\n\tif w.executable {\n\t\tvar stmt *sql.Stmt\n\t\tvar count int\n\n\t\tstmt, err = w.db.Prepare(w.query)\n\t\tif err != nil {\n\t\t\tif w.tracing {\n\t\t\t\tw.saveTrace(err, w.query, start)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\trows, err = stmt.Query(w.params...)\n\t\tif err != nil {\n\t\t\tif w.tracing {\n\t\t\t\tw.saveTrace(err, w.query, start)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\terr = stmt.Close()\n\t\tif err != nil {\n\t\t\tif w.tracing {\n\t\t\t\tw.saveTrace(err, w.query, start)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tcount, err = load(rows, w.destination)\n\t\tif err != nil {\n\t\t\tif w.tracing {\n\t\t\t\tw.saveTrace(err, w.query, start)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tw.count = count\n\t}\n\tif w.tracing {\n\t\tw.saveTrace(err, w.query, start)\n\t}\n\tw.cleanAfter()\n\treturn\n}", "func (w *Wrapper) RawQuery(query string, values ...interface{}) (err error) {\n\tw.query = query\n\tw.params = values\n\t_, err = w.runQuery()\n\treturn\n}", "func (s *Stmt) Query(args []driver.Value) (driver.Rows, error) {\n\texecutor, err := exec.BuildExecutor(s.res.dbType, s.txCtx.TransactionMode, s.query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\texecCtx := &types.ExecContext{\n\t\tTxCtx: s.txCtx,\n\t\tQuery: s.query,\n\t\tValues: args,\n\t}\n\n\tret, err := executor.ExecWithValue(context.Background(), execCtx,\n\t\tfunc(ctx context.Context, query string, args []driver.NamedValue) (types.ExecResult, error) {\n\t\t\tret, err := s.stmt.Query(util.NamedValueToValue(args))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\treturn types.NewResult(types.WithRows(ret)), nil\n\t\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ret.GetRows(), nil\n}", "func TestIssue46(t *testing.T) {\n\t// problem with UPDATE hello.world HW\n\tsql, args, err := Update(\"public.world pw\").Set(\"pw.name\", \"John Doe\").Where(\"pw.id = $1\", 23).ToSQL()\n\tassert.NoError(t, err)\n\tassert.Equal(t, stripWS(`UPDATE public.world pw SET pw.name=$1 WHERE (pw.id=$2)`), stripWS(sql))\n\tassert.Exactly(t, []interface{}{\"John Doe\", 23}, args)\n\n\tsql, args, err = Select(\"id\").From(\"public.table\").ToSQL()\n\tassert.NoError(t, err)\n\tassert.Equal(t, stripWS(`SELECT id FROM public.table`), stripWS(sql))\n\tassert.Nil(t, args)\n\n\t// raw SQL should not escape anything\n\tsql, args, err = SQL(`CREATE TABLE public.table`).ToSQL()\n\tassert.NoError(t, err)\n\tassert.Equal(t, stripWS(`CREATE TABLE public.table`), stripWS(sql))\n\tassert.Nil(t, args)\n\n}", "func (e *Executor) ExecSQL(sql *types.SQL) error {\n\te.Lock()\n\tdefer e.Unlock()\n\t// e.parseOnlineTable(sql)\n\te.SQLCh <- sql\n\treturn errors.Trace(<-e.ErrCh)\n}", "func (q *Query) RawQuery(stmt string, args ...interface{}) *Query {\n\tq.RawSQL = &clause{stmt, args}\n\treturn q\n}", "func DecodeSQL(s *string) *[]string {\r\n\tls := strings.Split(*s, \"-\")\r\n\treturn &ls\r\n}", "func NewSQL(\n\tconf Config, mgr types.Manager, log log.Modular, stats metrics.Type,\n) (Type, error) {\n\tdeprecated := false\n\tdsn := conf.SQL.DataSourceName\n\tif len(conf.SQL.DSN) > 0 {\n\t\tif len(dsn) > 0 {\n\t\t\treturn nil, errors.New(\"specified both a deprecated `dsn` as well as a `data_source_name`\")\n\t\t}\n\t\tdsn = conf.SQL.DSN\n\t\tdeprecated = true\n\t}\n\n\tif len(conf.SQL.Args) > 0 && conf.SQL.ArgsMapping != \"\" {\n\t\treturn nil, errors.New(\"cannot specify both `args` and an `args_mapping` in the same processor\")\n\t}\n\n\tvar argsMapping *mapping.Executor\n\tif conf.SQL.ArgsMapping != \"\" {\n\t\tif deprecated {\n\t\t\treturn nil, errors.New(\"the field `args_mapping` cannot be used when running the `sql` processor in deprecated mode (using the `dsn` field), use the `data_source_name` field instead\")\n\t\t}\n\t\tlog.Warnln(\"using unsafe_dynamic_query leaves you vulnerable to SQL injection attacks\")\n\t\tvar err error\n\t\tif argsMapping, err = interop.NewBloblangMapping(mgr, conf.SQL.ArgsMapping); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse `args_mapping`: %w\", err)\n\t\t}\n\t}\n\n\tvar args []*field.Expression\n\tfor i, v := range conf.SQL.Args {\n\t\texpr, err := interop.NewBloblangField(mgr, v)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse arg %v expression: %v\", i, err)\n\t\t}\n\t\targs = append(args, expr)\n\t}\n\n\tif conf.SQL.Driver == \"mssql\" {\n\t\t// For MSSQL, if the user part of the connection string is in the\n\t\t// `DOMAIN\\username` format, then the backslash character needs to be\n\t\t// URL-encoded.\n\t\tconf.SQL.DataSourceName = strings.ReplaceAll(conf.SQL.DataSourceName, `\\`, \"%5C\")\n\t}\n\n\ts := &SQL{\n\t\tlog: log,\n\t\tstats: stats,\n\t\tconf: conf.SQL,\n\t\targs: args,\n\t\targsMapping: argsMapping,\n\n\t\tqueryStr: conf.SQL.Query,\n\n\t\tdeprecated: deprecated,\n\t\tcloseChan: make(chan struct{}),\n\t\tclosedChan: make(chan struct{}),\n\t\tmCount: stats.GetCounter(\"count\"),\n\t\tmErr: stats.GetCounter(\"error\"),\n\t\tmSent: stats.GetCounter(\"sent\"),\n\t\tmBatchSent: stats.GetCounter(\"batch.sent\"),\n\t}\n\n\tvar err error\n\tif deprecated {\n\t\ts.log.Warnln(\"Using deprecated SQL functionality due to use of field 'dsn'. To switch to the new processor use the field 'data_source_name' instead. The new processor is not backwards compatible due to differences in how message batches are processed. For more information check out the docs at https://www.benthos.dev/docs/components/processors/sql.\")\n\t\tif conf.SQL.Driver != \"mysql\" && conf.SQL.Driver != \"postgres\" && conf.SQL.Driver != \"mssql\" {\n\t\t\treturn nil, fmt.Errorf(\"driver '%v' is not supported with deprecated SQL features (using field 'dsn')\", conf.SQL.Driver)\n\t\t}\n\t\tif s.resCodecDeprecated, err = strToSQLResultCodecDeprecated(conf.SQL.ResultCodec); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else if s.resCodec, err = strToSQLResultCodec(conf.SQL.ResultCodec); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif s.db, err = sql.Open(conf.SQL.Driver, dsn); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif conf.SQL.UnsafeDynamicQuery {\n\t\tif deprecated {\n\t\t\treturn nil, errors.New(\"cannot use dynamic queries when running in deprecated mode\")\n\t\t}\n\t\tif s.dynQuery, err = interop.NewBloblangField(mgr, s.queryStr); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse dynamic query expression: %v\", err)\n\t\t}\n\t}\n\n\tisSelectQuery := s.resCodecDeprecated != nil || s.resCodec != nil\n\n\t// Some drivers only support transactional prepared inserts.\n\tif s.dynQuery == nil && (isSelectQuery || !insertRequiresTransactionPrepare(conf.SQL.Driver)) {\n\t\tif s.query, err = s.db.Prepare(s.queryStr); err != nil {\n\t\t\ts.db.Close()\n\t\t\treturn nil, fmt.Errorf(\"failed to prepare query: %v\", err)\n\t\t}\n\t}\n\n\tgo func() {\n\t\tdefer func() {\n\t\t\ts.dbMux.Lock()\n\t\t\ts.db.Close()\n\t\t\tif s.query != nil {\n\t\t\t\ts.query.Close()\n\t\t\t}\n\t\t\ts.dbMux.Unlock()\n\t\t\tclose(s.closedChan)\n\t\t}()\n\t\t<-s.closeChan\n\t}()\n\treturn s, nil\n}", "func (ng *Engine) exec(ctx context.Context, q *query) (model.Value, error) {\n\tcurrentQueries.Inc()\n\tdefer currentQueries.Dec()\n\tctx, cancel := context.WithTimeout(ctx, ng.options.Timeout)\n\tq.cancel = cancel\n\n\tqueueTimer := q.stats.GetTimer(stats.ExecQueueTime).Start()\n\n\tif err := ng.gate.Start(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\tdefer ng.gate.Done()\n\n\tqueueTimer.Stop()\n\n\t// Cancel when execution is done or an error was raised.\n\tdefer q.cancel()\n\n\tconst env = \"query execution\"\n\n\tevalTimer := q.stats.GetTimer(stats.TotalEvalTime).Start()\n\tdefer evalTimer.Stop()\n\n\t// The base context might already be canceled on the first iteration (e.g. during shutdown).\n\tif err := contextDone(ctx, env); err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch s := q.Statement().(type) {\n\tcase *EvalStmt:\n\t\treturn ng.execEvalStmt(ctx, q, s)\n\tcase testStmt:\n\t\treturn nil, s(ctx)\n\t}\n\n\tpanic(fmt.Errorf(\"promql.Engine.exec: unhandled statement of type %T\", q.Statement()))\n}", "func (db *TestDB) q(sql string) string {\n\tswitch db.dialect {\n\tcase POSTGRESQL: // replace with $1, $2, ..\n\t\tqrx := regexp.MustCompile(`\\?`)\n\t\tn := 0\n\t\treturn qrx.ReplaceAllStringFunc(sql, func(string) string {\n\t\t\tn++\n\t\t\treturn \"$\" + strconv.Itoa(n)\n\t\t})\n\t}\n\treturn sql\n}", "func (q queryManager) processQuery(sql string, pubKey []byte, executeifallowed bool) (uint, []byte, []byte, *structures.Transaction, error) {\n\tlocalError := func(err error) (uint, []byte, []byte, *structures.Transaction, error) {\n\t\treturn SQLProcessingResultError, nil, nil, nil, err\n\t}\n\tqp := q.getQueryParser()\n\t// this will get sql type and data from comments. data can be pubkey, txBytes, signature\n\tqparsed, err := qp.ParseQuery(sql)\n\n\tif err != nil {\n\t\treturn localError(err)\n\t}\n\n\t// maybe this query contains signature and txData from previous calls\n\tif len(qparsed.Signature) > 0 && len(qparsed.TransactionBytes) > 0 {\n\t\t// this is a case when signature and txdata were part of SQL comments.\n\t\ttx, err := q.processQueryWithSignature(qparsed.TransactionBytes, qparsed.Signature, executeifallowed)\n\n\t\tif err != nil {\n\t\t\treturn localError(err)\n\t\t}\n\n\t\treturn SQLProcessingResultTranactionComplete, nil, nil, tx, nil\n\t}\n\n\tneedsTX, err := q.checkQueryNeedsTransaction(qparsed)\n\n\tif err != nil {\n\t\treturn localError(err)\n\t}\n\n\tif !needsTX {\n\t\tif !executeifallowed {\n\t\t\t// no need to execute query. just return\n\t\t\treturn SQLProcessingResultExecuted, nil, nil, nil, nil\n\t\t}\n\t\t// no need to have TX\n\t\tif qparsed.IsUpdate() {\n\t\t\t_, err := qp.ExecuteQuery(qparsed.SQL)\n\t\t\tif err != nil {\n\t\t\t\treturn localError(err)\n\t\t\t}\n\t\t}\n\t\treturn SQLProcessingResultExecuted, nil, nil, nil, nil\n\t}\n\t// decide which pubkey to use.\n\n\t// first priority for a key posted as argument, next is the key in SQL comment (parsed) and final is the key\n\t// provided to thi module\n\tif len(pubKey) == 0 {\n\t\tif len(qparsed.PubKey) > 0 {\n\t\t\tpubKey = qparsed.PubKey\n\t\t} else if len(q.pubKey) > 0 {\n\t\t\tpubKey = q.pubKey\n\t\t} else {\n\t\t\t// no pubkey to use. return notice about pubkey required\n\t\t\treturn SQLProcessingResultPubKeyRequired, nil, nil, nil, nil\n\t\t}\n\t}\n\n\t// check if the key has permissions to execute this query\n\thasPerm, err := q.checkExecutePermissions(qparsed, pubKey)\n\n\tif err != nil {\n\t\treturn localError(err)\n\t}\n\n\tif !hasPerm {\n\t\treturn localError(errors.New(\"No permissions to execute this query\"))\n\t}\n\n\tamount, err := q.checkQueryNeedsPayment(qparsed)\n\n\tif err != nil {\n\t\treturn localError(err)\n\t}\n\t// prepare SQL part of a TX\n\t// this builds RefID for a TX update\n\tsqlUpdate, err := qp.MakeSQLUpdateStructure(qparsed)\n\n\tif err != nil {\n\t\treturn localError(err)\n\t}\n\n\t// prepare curency TX and add SQL part\n\n\ttxBytes, datatosign, err := q.getTransactionsManager().PrepareNewSQLTransaction(pubKey, sqlUpdate, amount, \"MINTER\")\n\n\tif err != nil {\n\t\treturn localError(err)\n\t}\n\n\ttx, err := structures.DeserializeTransaction(txBytes)\n\n\tif err != nil {\n\t\treturn localError(err)\n\t}\n\n\tif len(q.pubKey) > 0 && bytes.Compare(q.pubKey, pubKey) == 0 {\n\t\t// transaction was created by internal pubkey. we have private key for it\n\t\tsignature, err := utils.SignDataByPubKey(q.pubKey, q.privKey, datatosign)\n\t\tif err != nil {\n\t\t\treturn localError(err)\n\t\t}\n\n\t\ttx, err = q.processQueryWithSignature(txBytes, signature, executeifallowed)\n\n\t\tif err != nil {\n\t\t\treturn localError(err)\n\t\t}\n\n\t\treturn SQLProcessingResultTranactionCompleteInternally, nil, nil, tx, nil\n\t}\n\treturn SQLProcessingResultSignatureRequired, txBytes, datatosign, nil, nil\n}", "func (ses *Ses) Sel(sqlFrom string, columnPairs ...interface{}) (rset *Rset, err error) {\n\tses.log(_drv.Cfg().Log.Ses.Sel)\n\terr = ses.checkClosed()\n\tif err != nil {\n\t\treturn nil, errE(err)\n\t}\n\tif len(columnPairs) == 0 {\n\t\treturn nil, errF(\"No column name-type pairs specified.\")\n\t}\n\tif len(columnPairs)%2 != 0 {\n\t\treturn nil, errF(\"Variadic parameter 'columnPairs' received an odd number of elements. Parameter 'columnPairs' expects an even number of elements.\")\n\t}\n\t// build select statement, gcts\n\tgcts := make([]GoColumnType, len(columnPairs)/2)\n\tbuf := new(bytes.Buffer)\n\tbuf.WriteString(\"SELECT \")\n\tfor n := 0; n < len(columnPairs); n += 2 {\n\t\tcolumnName, ok := columnPairs[n].(string)\n\t\tif !ok {\n\t\t\treturn nil, errF(\"Variadic parameter 'columnPairs' expected an element at index %v to be of type string\", n)\n\t\t}\n\t\tgct, ok := columnPairs[n+1].(GoColumnType)\n\t\tif !ok {\n\t\t\treturn nil, errF(\"Variadic parameter 'columnPairs' expected an element at index %v to be of type ora.GoColumnType\", n+1)\n\t\t}\n\t\tbuf.WriteString(columnName)\n\t\tif n != len(columnPairs)-2 {\n\t\t\tbuf.WriteRune(',')\n\t\t}\n\t\tbuf.WriteRune(' ')\n\t\tgcts[n/2] = gct\n\t}\n\t// add FROM keyword?\n\tfromIndex := strings.Index(strings.ToUpper(sqlFrom), \"FROM\")\n\tif fromIndex < 0 {\n\t\tbuf.WriteString(\"FROM \")\n\t}\n\tbuf.WriteString(sqlFrom)\n\t// prep\n\tstmt, err := ses.Prep(buf.String(), gcts...)\n\tif err != nil {\n\t\tdefer stmt.Close()\n\t\treturn nil, errE(err)\n\t}\n\t// qry\n\trset, err = stmt.Qry()\n\tif err != nil {\n\t\tdefer stmt.Close()\n\t\treturn nil, errE(err)\n\t}\n\trset.autoClose = true\n\treturn rset, nil\n}", "func Query(sql string) (q *sql.Rows, e error) {\n\tfmt.Printf(\"sql: %s\\n\", sql)\n\tst, e := database.Prepare(sql)\n\tif e != nil {\n\t\treturn\n\t}\n\tdefer st.Close()\n\n\tq, e = st.Query()\n\treturn\n}", "func (w *Wrapper) executeQuery() (res sql.Result, err error) {\n\tw.cleanBefore()\n\tw.buildQuery()\n\tw.LastQuery = w.query\n\tw.LastParams = w.params\n\t// Calculate the execution time.\n\tvar start time.Time\n\tif w.tracing {\n\t\tstart = time.Now()\n\t}\n\t// Execute the query if the wrapper is executable.\n\tif w.executable {\n\t\tvar stmt *sql.Stmt\n\t\tvar count int64\n\t\tstmt, err = w.db.Prepare(w.query)\n\t\tif err != nil {\n\t\t\tif w.tracing {\n\t\t\t\tw.saveTrace(err, w.query, start)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tres, err = stmt.Exec(w.params...)\n\t\tif err != nil {\n\t\t\tif w.tracing {\n\t\t\t\tw.saveTrace(err, w.query, start)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tw.LastResult = res\n\t\tcount, err = res.RowsAffected()\n\t\tif err != nil {\n\t\t\tif w.tracing {\n\t\t\t\tw.saveTrace(err, w.query, start)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tw.count = int(count)\n\t\terr = stmt.Close()\n\t\tif err != nil {\n\t\t\tif w.tracing {\n\t\t\t\tw.saveTrace(err, w.query, start)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n\tif w.tracing {\n\t\tw.saveTrace(err, w.query, start)\n\t}\n\tw.cleanAfter()\n\treturn\n}", "func GomssqlExec(\n\tcfg Config,\n\tquery string,\n) (string, error) {\n\tapplicationIntent := \"ReadWrite\"\n\tif cfg.ReadOnly {\n\t\tapplicationIntent = \"ReadOnly\"\n\t}\n\n\tdsnString := fmt.Sprintf(\n\t\t\"user id=%s;password=%s;server=%s;port=%s;encrypt=%s;applicationintent=%s\",\n\t\tcfg.Username,\n\t\tcfg.Password,\n\t\tcfg.Host,\n\t\tcfg.Port,\n\t\t\"disable\",\n\t\tapplicationIntent,\n\t)\n\n\tif db := cfg.Database; db != \"\" {\n\t\tdsnString += fmt.Sprintf(\";database=%s\", db)\n\t}\n\n\t// Open the connection\n\tconn, err := sql.Open(\n\t\t\"mssql\",\n\t\tdsnString,\n\t)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer conn.Close()\n\n\tctx, _ := context.WithDeadline(\n\t\tcontext.Background(),\n\t\ttime.Now().Add(1*time.Second),\n\t)\n\n\tif query == \"\" {\n\t\t_, err := conn.Conn(ctx)\n\t\treturn \"\", err\n\t}\n\n\t// Execute the query\n\trows, err := conn.QueryContext(ctx, query)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer rows.Close()\n\n\t// Execute the query\n\tcols, err := rows.Columns()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\trawResult := make([][]byte, len(cols))\n\n\tdest := make([]interface{}, len(cols)) // A temporary interface{} slice\n\tfor i := range rawResult {\n\t\tdest[i] = &rawResult[i] // Put pointers to each string in the interface slice\n\t}\n\n\tw := new(tabwriter.Writer)\n\tbuf := &bytes.Buffer{}\n\tw.Init(buf, 0, 0, 0, ' ', tabwriter.Debug|tabwriter.AlignRight)\n\n\tfor rows.Next() {\n\t\terr = rows.Scan(dest...)\n\t\tif err != nil {\n\t\t\treturn \"\", nil\n\t\t}\n\n\t\trowString := \"\"\n\t\tfor _, raw := range rawResult {\n\t\t\tif raw == nil {\n\t\t\t\trowString += \"\\\\N\"\n\t\t\t} else {\n\t\t\t\trowString += string(raw)\n\t\t\t}\n\n\t\t\trowString += \"\\t\"\n\t\t}\n\n\t\tfmt.Fprintln(w, rowString)\n\t}\n\n\tw.Flush()\n\n\treturn string(buf.Bytes()), err\n}", "func (ar *ActiveRecord) ExecSQL(sql string, args ...interface{}) (sql.Result, error) {\n\treturn ar.DB.Exec(sql, args...)\n}", "func (s *Schema) Exec(query string, args ...interface{}) (sql.Result, error) {\n\n\tvar e error\n\tvar stmt *sql.Stmt\n\tstmt, e = s.Dal.Connection.Prepare(query)\n\t// fmt.Printf(\"Stmt: %v\\n\", stmt)\n\tif e != nil {\n\t\tfmt.Printf(\"Error: %s\", e.Error())\n\t\treturn nil, e\n\t}\n\tdefer stmt.Close()\n\treturn stmt.Exec(args...)\n}", "func (c *sqlmock) Query(query string, args []driver.Value) (driver.Rows, error) {\n\tnamedArgs := make([]driver.NamedValue, len(args))\n\tfor i, v := range args {\n\t\tnamedArgs[i] = driver.NamedValue{\n\t\t\tOrdinal: i + 1,\n\t\t\tValue: v,\n\t\t}\n\t}\n\n\tex, err := c.query(query, namedArgs)\n\tif ex != nil {\n\t\ttime.Sleep(ex.delay)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ex.rows, nil\n}", "func (statement *Statement) Prepare(input string) error {\n\tif len(input) < 6 {\n\t\treturn errors.New(\"Wrong Command\")\n\t}\n\tcommand := string(input[0:6])\n\tswitch command {\n\tcase \"insert\":\n\t\tstatement.Type = StatementInsert\n\t\tvar tempUserName, tempEmail []byte\n\t\tr := bytes.NewReader([]byte(input))\n\t\tnumberOfItems, err := fmt.Fscanf(r, \"insert %d %s %s\", &statement.Row.ID, &tempUserName, &tempEmail)\n\t\tif len(tempUserName) > len(statement.Row.Username) || len(tempEmail) > len(statement.Row.Email) {\n\t\t\tfmt.Println(\"Input too long\")\n\t\t\treturn errors.New(\"Input too long\")\n\t\t}\n\t\tif numberOfItems != 3 || err != nil {\n\t\t\treturn errors.New(\"Syntax Error insert (number) (string) (string)\")\n\t\t}\n\t\tcopy(statement.Row.Username[:], tempUserName)\n\t\tcopy(statement.Row.Email[:], tempEmail)\n\tcase \"select\":\n\t\tstatement.Type = StatementSelect\n\tdefault:\n\t\tstatement.Type = StatementUnknown\n\t}\n\treturn nil\n}", "func (b *bot) query(query string, args ...interface{}) (*sql.Rows, error) {\n\treturn b.DB.client.Query(query, args...)\n}", "func SQL(sql string, args ...interface{}) *RawBuilder {\n\treturn NewRawBuilder(sql, args...)\n}", "func ExecQuery(ctx context.Context, sql string) {\n\t_, span := opentelemetry.StartSpan(ctx, \"database-call\")\n\tdefer span.Finish(0)\n\n\t// Do the query execution\n}", "func (c *PostgreSQLConnection) Execute(query string, arguments []interface{}) sql.Result {\n\tif arguments == nil {\n\t\tresult, err := c.db.Exec(query)\n\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[!] Couldn't execute query. Reason %v\", err)\n\t\t\treturn nil\n\t\t}\n\n\t\treturn result\n\t}\n\n\tstmt, err := c.db.Prepare(query)\n\n\tif err != nil {\n\t\tlog.Printf(\"[!] Couldn't prepare statement. Reason %v\", err)\n\t\treturn nil\n\t}\n\n\tresult, err := stmt.Exec(arguments...)\n\n\tif err != nil {\n\t\tlog.Printf(\"[!] Couldn't execute query. Reason %v\", err)\n\t\treturn nil\n\t}\n\n\treturn result\n}", "func (q *QueryGoPg) Raw(dst interface{}, sql string, args ...interface{}) (err error) {\n\t_, err = goPgConnection.Query(dst, sql, args...)\n\treturn\n}", "func (ses *Ses) PrepAndQry(sql string, params ...interface{}) (rset *Rset, err error) {\n\tses.log(_drv.Cfg().Log.Ses.PrepAndQry)\n\terr = ses.checkClosed()\n\tif err != nil {\n\t\treturn nil, errE(err)\n\t}\n\tstmt, err := ses.Prep(sql)\n\tif err != nil {\n\t\tdefer stmt.Close()\n\t\treturn nil, errE(err)\n\t}\n\trset, err = stmt.Qry(params...)\n\tif err != nil {\n\t\tdefer stmt.Close()\n\t\treturn nil, errE(err)\n\t}\n\trset.autoClose = true\n\treturn rset, nil\n}", "func runQuery(slct string, db *DB) *PipeReader {\n\trd, wr := Pipe()\n\tgo func() {\n\t\tdefer wr.Close()\n\n\t\terr := func() error {\n\t\t\tstartAt := time.Now()\n\t\t\tlog.Infof(\"Starting runStanrardSQL:%s\", slct)\n\n\t\t\trows, err := db.Query(slct)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"runQuery failed: %v\", err)\n\t\t\t}\n\t\t\tdefer rows.Close()\n\n\t\t\tcols, err := rows.Columns()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to get columns: %v\", err)\n\t\t\t}\n\n\t\t\theader := make(map[string]interface{})\n\t\t\theader[\"columnNames\"] = cols\n\t\t\tif e := wr.Write(header); e != nil {\n\t\t\t\treturn e\n\t\t\t}\n\n\t\t\tfor rows.Next() {\n\t\t\t\t// Since we don't know the table schema in advance, need to\n\t\t\t\t// create an slice of empty interface and adds column type\n\t\t\t\t// at runtime. Some databases support dynamic types between\n\t\t\t\t// rows, such as sqlite's affinity. So we move columnTypes inside\n\t\t\t\t// the row.Next() loop.\n\t\t\t\tcount := len(cols)\n\t\t\t\tvalues := make([]interface{}, count)\n\t\t\t\tcolumnTypes, err := rows.ColumnTypes()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"failed to get columnTypes: %v\", err)\n\t\t\t\t}\n\t\t\t\tfor i, ct := range columnTypes {\n\t\t\t\t\tv, e := createByType(ct.ScanType())\n\t\t\t\t\tif e != nil {\n\t\t\t\t\t\treturn e\n\t\t\t\t\t}\n\t\t\t\t\tvalues[i] = v\n\t\t\t\t}\n\n\t\t\t\tif err := rows.Scan(values...); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\trow := make([]interface{}, count)\n\t\t\t\tfor i, val := range values {\n\t\t\t\t\tv, e := parseVal(val)\n\t\t\t\t\tif e != nil {\n\t\t\t\t\t\treturn e\n\t\t\t\t\t}\n\t\t\t\t\trow[i] = v\n\t\t\t\t}\n\t\t\t\tif e := wr.Write(row); e != nil {\n\t\t\t\t\treturn e\n\t\t\t\t}\n\t\t\t}\n\t\t\tlog.Infof(\"runQuery finished, elapsed: %v\", time.Since(startAt))\n\t\t\treturn nil\n\t\t}()\n\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"runQuery error:%v\", err)\n\t\t\tif err != ErrClosedPipe {\n\t\t\t\tif err := wr.Write(err); err != nil {\n\t\t\t\t\tlog.Errorf(\"runQuery error(piping):%v\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\treturn rd\n}", "func execExprString(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret := types.ExprString(args[0].(ast.Expr))\n\tp.Ret(1, ret)\n}", "func queryRgPyexecute(qm queryModel, client redisClient) backend.DataResponse {\n\tresponse := backend.DataResponse{}\n\n\tvar result interface{}\n\n\t// Check and create list of optional parameters\n\tvar args []interface{}\n\tif qm.Unblocking {\n\t\targs = append(args, \"UNBLOCKING\")\n\t}\n\n\tif qm.Requirements != \"\" {\n\t\targs = append(args, \"REQUIREMENTS\", qm.Requirements)\n\t}\n\n\t// Run command\n\terr := client.RunFlatCmd(&result, \"RG.PYEXECUTE\", qm.Key, args...)\n\n\t// Check error\n\tif err != nil {\n\t\treturn errorHandler(response, err)\n\t}\n\n\t// UNBLOCKING\n\tif qm.Unblocking {\n\t\t// when running with UNBLOCKING only operationId is returned\n\t\tframe := data.NewFrame(\"operationId\")\n\t\tframe.Fields = append(frame.Fields, data.NewField(\"operationId\", nil, []string{string(result.([]byte))}))\n\n\t\t// Adding frame to response\n\t\tresponse.Frames = append(response.Frames, frame)\n\t\treturn response\n\t}\n\n\t// New Frame for results\n\tframeWithResults := data.NewFrame(\"results\")\n\tframeWithResults.Fields = append(frameWithResults.Fields, data.NewField(\"results\", nil, []string{}))\n\n\t// New Frame for errors\n\tframeWithErrors := data.NewFrame(\"errors\")\n\tframeWithErrors.Fields = append(frameWithErrors.Fields, data.NewField(\"errors\", nil, []string{}))\n\n\t// Adding frames to response\n\tresponse.Frames = append(response.Frames, frameWithResults)\n\tresponse.Frames = append(response.Frames, frameWithErrors)\n\n\t// Parse result\n\tswitch value := result.(type) {\n\tcase string:\n\t\treturn response\n\tcase []interface{}:\n\t\t// Inserting results\n\t\tfor _, entry := range value[0].([]interface{}) {\n\t\t\tframeWithResults.AppendRow(string(entry.([]byte)))\n\t\t}\n\n\t\t// Inserting errors\n\t\tfor _, entry := range value[1].([]interface{}) {\n\t\t\tframeWithErrors.AppendRow(string(entry.([]byte)))\n\t\t}\n\t\treturn response\n\tdefault:\n\t\tlog.DefaultLogger.Error(\"Unexpected type received\", \"value\", value, \"type\", reflect.TypeOf(value).String())\n\t\treturn response\n\t}\n}", "func Query(query string, args ...interface{}) error {\n\tstmt := database.prepare(query)\n\tdefer stmt.Close()\n\ttx := database.begin()\n\tif _, err := tx.Stmt(stmt).Exec(args...); err != nil {\n\t\tlog.Println(\"Query error: \", err)\n\t\ttx.Rollback()\n\t}\n\terr := tx.Commit()\n\treturn err\n}", "func RawQuery(q []byte) Term {\n\tdata := json.RawMessage(q)\n\treturn Term{\n\t\tname: \"RawQuery\",\n\t\trootTerm: true,\n\t\trawQuery: true,\n\t\tdata: &data,\n\t\targs: []Term{\n\t\t\tTerm{\n\t\t\t\ttermType: p.Term_DATUM,\n\t\t\t\tdata: string(q),\n\t\t\t},\n\t\t},\n\t}\n}", "func (conn *n1qlConn) Exec(query string, args ...interface{}) (godbc.Result, error) {\n\n\tif len(args) > 0 {\n\t\tvar argCount int\n\t\tquery, argCount = prepareQuery(query)\n\t\tif argCount != len(args) {\n\t\t\treturn nil, fmt.Errorf(\"Argument count mismatch %d != %d\", argCount, len(args))\n\t\t}\n\t\tquery, args = preparePositionalArgs(query, argCount, args)\n\t}\n\n\treturn conn.performExec(query, nil)\n}", "func (q *DataQuerySQL) sql() (s string, e error) {\n\tif q.baseClass == \"\" {\n\t\treturn \"\", errors.New(\"No base class\")\n\t}\n\n\t// columns\n\tsql := \"select \"\n\tif len(q.columns) == 0 {\n\t\tsql += \"* \"\n\t} else {\n\t\tsql += \"\\\"\" + strings.Join(q.columns, \"\\\",\\\"\") + \"\\\" \"\n\t}\n\n\t// Tables. This is basically a join of all tables from base DataObject thru to the table for the class, and all\n\t// tables for subclasses. This will have been precalculated, so it's trivial here.\n\tbaseClass := dbMetadata.GetClass(q.baseClass)\n\tsql += \"from \" + baseClass.defaultFrom\n\n\t// where clause\n\tsql += \" where \" + baseClass.defaultWhere\n\tif len(q.where) > 0 {\n\t\tsql += \" and \" + strings.Join(q.where, \" and \")\n\t}\n\n\tif q.orderBy != \"\" {\n\t\tsql += \" order by \" + q.orderBy\n\t}\n\n\tif q.start >= 0 {\n\t\tsql += \" limit \" + strconv.Itoa(q.start) + \", \" + strconv.Itoa(q.limit)\n\t}\n\t//\tfmt.Printf(\"query is %s\\n\", sql)\n\treturn sql, nil\n}", "func testSQLCmd(SQLCmd string, scanType string, output *string) error {\n\tif scanType == \"\" {\n\t\tscanType = \"string\"\n\t}\n\tconn, err := pgx.Connect(context.Background(), os.Getenv(\"DATABASE_URL\"))\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to connect to database: %v\\n\", err)\n\t\t//os.Exit(1)\n\t\treturn err\n\t}\n\tdefer conn.Close(context.Background())\n\n\tvar sum string\n\t// Send the query to the server. The returned rows MUST be closed\n\t// before conn can be used again.\n\trows, err := conn.Query(context.Background(), SQLCmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// No errors found - do something with sum\n\tdefer rows.Close()\n\n\t// Iterate through the result set\n\tfor rows.Next() {\n\t\tif scanType == \"int\" {\n\t\t\tvar n int\n\t\t\terr = rows.Scan(&n)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tsum += strconv.Itoa(n) + \"\\n\"\n\t\t} else {\n\t\t\tvar n string\n\t\t\terr = rows.Scan(&n)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tsum += n + \"\\n\"\n\t\t}\n\n\t}\n\n\t// Any errors encountered by rows.Next or rows.Scan will be returned here\n\tif rows.Err() != nil {\n\t\treturn err\n\t}\n\t*output = sum\n\treturn nil\n}", "func (ctrl *PGCtrl) Execute(q string) error {\n\t_, err := ctrl.conn.Exec(q)\n\treturn err\n}", "func (cl *Client) Sphinxql(cmd string) ([]Sqlresult, error) {\n\tblob, err := cl.netQuery(commandSphinxql,\n\t\tbuildSphinxqlRequest(cmd),\n\t\tparseSphinxqlAnswer())\n\tif blob == nil {\n\t\treturn nil, err\n\t}\n\treturn blob.([]Sqlresult), err\n}", "func executeQuery(db *sql.DB, query string, args ...interface{}) (int64, error) {\n\tresult, err := db.Exec(query, args...)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn result.RowsAffected()\n}", "func executeQuery(db *sql.DB, query string, args ...interface{}) (int64, error) {\n\tresult, err := db.Exec(query, args...)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn result.RowsAffected()\n}", "func (db *DB) Query(sql string) *ResponseMessage {\n\n\turl := db.url\n\tmethod := \"POST\"\n\n\tjsonTxt := sqlStatementJSON(sql)\n\t//payload := strings.NewReader(\"{\\n \\\"statement\\\": \\\"SELECT * FROM master_erp WHERE type='login_session'\\\"\\n}\\n\\n\")\n\n\tpayload := strings.NewReader(jsonTxt)\n\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(method, url, payload)\n\n\tif err != nil {\n\t\tfmt.Println(\"ERROR @ Query:\", err.Error())\n\t}\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treq.Header.Add(\"Authorization\", db.authorization())\n\n\tres, err := client.Do(req)\n\tbody, err := ioutil.ReadAll(res.Body)\n\tdefer res.Body.Close()\n\n\t//local variable as a pointer\n\tvar resPonse ResponseMessage\n\n\tjson.Unmarshal(body, &resPonse)\n\n\treturn &resPonse\n}", "func execPrepareStmt(prepStmt string) {\n\tif db == nil {\n\t\tdb = getDB()\n\t}\n\n\tstmt, err := db.Prepare(prepStmt)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t_, err = stmt.Exec()\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (s *HTTPServer) preparedQueryExecute(id string, resp http.ResponseWriter, req *http.Request) (interface{}, error) {\n\targs := structs.PreparedQueryExecuteRequest{\n\t\tQueryIDOrName: id,\n\t\tAgent: structs.QuerySource{\n\t\t\tNode: s.agent.config.NodeName,\n\t\t\tDatacenter: s.agent.config.Datacenter,\n\t\t\tSegment: s.agent.config.SegmentName,\n\t\t},\n\t}\n\ts.parseSource(req, &args.Source)\n\tif done := s.parse(resp, req, &args.Datacenter, &args.QueryOptions); done {\n\t\treturn nil, nil\n\t}\n\tif err := parseLimit(req, &args.Limit); err != nil {\n\t\treturn nil, fmt.Errorf(\"Bad limit: %s\", err)\n\t}\n\n\tparams := req.URL.Query()\n\tif raw := params.Get(\"connect\"); raw != \"\" {\n\t\tval, err := strconv.ParseBool(raw)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error parsing 'connect' value: %s\", err)\n\t\t}\n\n\t\targs.Connect = val\n\t}\n\n\tvar reply structs.PreparedQueryExecuteResponse\n\tdefer setMeta(resp, &reply.QueryMeta)\n\n\tif args.QueryOptions.UseCache {\n\t\traw, m, err := s.agent.cache.Get(cachetype.PreparedQueryName, &args)\n\t\tif err != nil {\n\t\t\t// Don't return error if StaleIfError is set and we are within it and had\n\t\t\t// a cached value.\n\t\t\tif raw != nil && m.Hit && args.QueryOptions.StaleIfError > m.Age {\n\t\t\t\t// Fall through to the happy path below\n\t\t\t} else {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\tdefer setCacheMeta(resp, &m)\n\t\tr, ok := raw.(*structs.PreparedQueryExecuteResponse)\n\t\tif !ok {\n\t\t\t// This should never happen, but we want to protect against panics\n\t\t\treturn nil, fmt.Errorf(\"internal error: response type not correct\")\n\t\t}\n\t\treply = *r\n\t} else {\n\tRETRY_ONCE:\n\t\tif err := s.agent.RPC(\"PreparedQuery.Execute\", &args, &reply); err != nil {\n\t\t\t// We have to check the string since the RPC sheds\n\t\t\t// the specific error type.\n\t\t\tif err.Error() == consul.ErrQueryNotFound.Error() {\n\t\t\t\tresp.WriteHeader(http.StatusNotFound)\n\t\t\t\tfmt.Fprint(resp, err.Error())\n\t\t\t\treturn nil, nil\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\tif args.QueryOptions.AllowStale && args.MaxStaleDuration > 0 && args.MaxStaleDuration < reply.LastContact {\n\t\t\targs.AllowStale = false\n\t\t\targs.MaxStaleDuration = 0\n\t\t\tgoto RETRY_ONCE\n\t\t}\n\t}\n\treply.ConsistencyLevel = args.QueryOptions.ConsistencyLevel()\n\n\t// Note that we translate using the DC that the results came from, since\n\t// a query can fail over to a different DC than where the execute request\n\t// was sent to. That's why we use the reply's DC and not the one from\n\t// the args.\n\ts.agent.TranslateAddresses(reply.Datacenter, reply.Nodes)\n\n\t// Use empty list instead of nil.\n\tif reply.Nodes == nil {\n\t\treply.Nodes = make(structs.CheckServiceNodes, 0)\n\t}\n\treturn reply, nil\n}", "func ParseSqlStatement(statement string) *ParsedSql {\n\tnamedParameters := coll.NewHashSet()\n\tparsedSql := NewParsedSql(statement)\n\n\tlength := len(statement)\n\tfor i := 0; i < length; i++ {\n\t\tc := statement[i]\n\t\tif c == ':' || c == '&' {\n\t\t\tj := i + 1\n\t\t\tif j < length && statement[j] == ':' && c == ':' {\n\t\t\t\t// Postgres-style \"::\" casting operator - to be skipped.\n\t\t\t\ti = i + 2\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor j < length && !isParameterSeparator(rune(statement[j])) {\n\t\t\t\tj++\n\t\t\t}\n\t\t\tif (j - i) > 1 {\n\t\t\t\tparameter := ext.Str(statement[i+1 : j])\n\t\t\t\tif !namedParameters.Contains(parameter) {\n\t\t\t\t\tnamedParameters.Add(parameter)\n\t\t\t\t}\n\t\t\t\tparsedSql.AddNamedParameter(parameter.String(), i, j)\n\t\t\t}\n\t\t\ti = j - 1\n\t\t}\n\t}\n\treturn parsedSql\n}", "func (c *queryClient) RunSQL(source string, sql string, cascade bool) (io.ReadCloser, error) {\n\trequestBody := NewRunSQLRequest(source, sql, cascade)\n\treturn c.Send(requestBody)\n}", "func QueryAsString(sql string, bindVariables map[string]interface{}) string {\n\tbuf := &bytes.Buffer{}\n\tfmt.Fprintf(buf, \"Sql: %q, BindVars: {\", sqlparser.TruncateForLog(sql))\n\tfor k, v := range bindVariables {\n\t\tvar valString string;\n\t\tswitch val := v.(type) {\n\t\tcase []byte:\n\t\t\tvalString = string(val);\n\t\tcase string:\n\t\t\tvalString = val;\n\t\tdefault:\n\t\t\tvalString = fmt.Sprintf(\"%v\", v);\n\t\t}\n\n\t\tfmt.Fprintf(buf, \"%s: %q\", k, sqlparser.TruncateForLog(valString));\n\t}\n\tfmt.Fprintf(buf, \"}\")\n\treturn string(buf.Bytes())\n}", "func (w *Wrapper) prepare(query string) string {\n\tw.connLock.RLock()\n\tdefer w.connLock.RUnlock()\n\n\tswitch w.prepareType {\n\tcase dbUnknown:\n\t\tw.prepareType = examineDB(w.connection)\n\t\tif w.prepareType == dbUnknown {\n\t\t\tpanic(UnknownDatabase)\n\t\t}\n\t\treturn w.prepare(query)\n\tcase dbPostgres:\n\t\treturn query\n\tcase dbMysql:\n\t\treturn postgresRegex.ReplaceAllString(query, \"?\")\n\t}\n\tpanic(\"unreachable\")\n}", "func PythonODBCExec(\n\tcfg Config,\n\tquery string,\n) (string, error) {\n\tapplicationintent := \"readwrite\"\n\tif cfg.ReadOnly {\n\t\tapplicationintent = \"readonly\"\n\t}\n\n\targs := []string{\n\t\t\"--server\", fmt.Sprintf(\"%s,%s\", cfg.Host, cfg.Port),\n\t\t\"--username\", cfg.Username,\n\t\t\"--password\", cfg.Password,\n\t\t\"--query\", query,\n\t\t\"--application-intent\", applicationintent,\n\t}\n\n\tif db := cfg.Database; db != \"\" {\n\t\targs = append(args, \"--database\", db)\n\t}\n\n\tout, err := exec.Command(\n\t\t\"./client/odbc_client.py\",\n\t\targs...,\n\t).Output()\n\n\tif err != nil {\n\t\tif exitErrr, ok := err.(*exec.ExitError); ok {\n\t\t\treturn \"\", errors.New(string(exitErrr.Stderr))\n\t\t}\n\n\t\treturn \"\", err\n\t}\n\n\treturn string(out), nil\n}", "func _prep_sql(tls *crt.TLS, _db unsafe.Pointer, _zFormat *int8, args ...interface{}) (r0 unsafe.Pointer) {\n\tvar _rc, _i int32\n\tvar _zSql *int8\n\tvar _pStmt unsafe.Pointer\n\tvar _ap []interface{}\n\t_pStmt = nil\n\t_ap = args\n\t_zSql = bin.Xsqlite3_vmprintf(tls, _zFormat, _ap)\n\t_ap = nil\n\t_check_oom(tls, unsafe.Pointer(_zSql))\n\t_i = int32(0)\n_0:\n\tif _i >= int32(1000) {\n\t\tgoto _3\n\t}\n\t_rc = bin.Xsqlite3_prepare_v2(tls, (*bin.Xsqlite3)(_db), _zSql, int32(-1), &_pStmt, nil)\n\tif _rc == int32(0) {\n\t\tgoto _3\n\t}\n\t_i += 1\n\tgoto _0\n_3:\n\tif _rc != int32(0) {\n\t\tcrt.Xfprintf(tls, (*crt.XFILE)(Xstderr), str(991), _rc, bin.Xsqlite3_extended_errcode(tls, (*bin.Xsqlite3)(_db)), unsafe.Pointer(bin.Xsqlite3_errmsg(tls, (*bin.Xsqlite3)(_db))), unsafe.Pointer(_zSql))\n\t\tcrt.Xexit(tls, int32(1))\n\t}\n\tbin.Xsqlite3_free(tls, unsafe.Pointer(_zSql))\n\treturn _pStmt\n}", "func execute_input(line string, w io.Writer) (int, string) {\n\n\tcommand.W = w\n\n\tif DISCONNECT == true || NoQueryService == true {\n\t\tif strings.HasPrefix(strings.ToLower(line), \"\\\\connect\") {\n\t\t\tNoQueryService = false\n\t\t\tcommand.DISCONNECT = false\n\t\t\tDISCONNECT = false\n\t\t}\n\t}\n\n\tif strings.HasPrefix(line, \"\\\\\\\\\") {\n\t\t// This block handles aliases\n\t\tcommandkey := line[2:]\n\t\tcommandkey = strings.TrimSpace(commandkey)\n\n\t\tval, ok := command.AliasCommand[commandkey]\n\n\t\tif !ok {\n\t\t\treturn errors.NO_SUCH_ALIAS, \" : \" + commandkey + \"\\n\"\n\t\t}\n\n\t\terr_code, err_str := execute_input(val, w)\n\t\t/* Error handling for Shell errors and errors recieved from\n\t\t go_n1ql.\n\t\t*/\n\t\tif err_code != 0 {\n\t\t\treturn err_code, err_str\n\t\t}\n\n\t} else if strings.HasPrefix(line, \"\\\\\") {\n\t\t//This block handles the shell commands\n\t\terr_code, err_str := ExecShellCmd(line)\n\t\tif err_code != 0 {\n\t\t\treturn err_code, err_str\n\t\t}\n\n\t} else {\n\t\t//This block handles N1QL statements\n\t\t// If connected to a query service then NoQueryService == false.\n\t\tif NoQueryService == true {\n\t\t\t//Not connected to a query service\n\t\t\treturn errors.NO_CONNECTION, \"\"\n\t\t} else {\n\t\t\t/* Try opening a connection to the endpoint. If successful, ping.\n\t\t\t If successful execute the n1ql command. Else try to connect\n\t\t\t again.\n\t\t\t*/\n\t\t\tn1ql, err := sql.Open(\"n1ql\", ServerFlag)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.GO_N1QL_OPEN, \"\"\n\t\t\t} else {\n\t\t\t\t//Successfully logged into the server\n\t\t\t\terr_code, err_str := ExecN1QLStmt(line, n1ql, w)\n\t\t\t\tif err_code != 0 {\n\t\t\t\t\treturn err_code, err_str\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n\n\treturn 0, \"\"\n}", "func (dbmap *dataBaseMap) executeGetCoursesSql(dbName string, query string, args []interface{}) []Course {\n\n\tdb := dbmap.dbases[dbName].db\n\trows, err := db.Query(query, args...)\n\tif err != nil {\n\t\tlog.Println(\"Error while fetching students courses \", err)\n\t\treturn nil\n\t}\n\tdefer rows.Close()\n\tvar courses []Course\n\tfor rows.Next() {\n\t\tvar course Course\n\t\terr = rows.Scan(&course.courseName, &course.courseCode)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error while fetching students courses \", err)\n\t\t\treturn nil\n\t\t}\n\t\tcourses = append(courses, course)\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\tlog.Println(\"Error while fetching students courses \", err)\n\t\treturn nil\n\t}\n\treturn courses\n}" ]
[ "0.6136839", "0.6110776", "0.60540634", "0.60480565", "0.6026476", "0.5976955", "0.5960659", "0.594576", "0.58952475", "0.5792017", "0.57658356", "0.5734749", "0.57277894", "0.5712368", "0.57083046", "0.5702991", "0.56882405", "0.5655821", "0.5600363", "0.55933875", "0.556885", "0.55673736", "0.55572796", "0.5544161", "0.55392426", "0.5538866", "0.5523525", "0.5522531", "0.5506627", "0.5499539", "0.5495682", "0.54923034", "0.54826427", "0.54699564", "0.5455155", "0.54398537", "0.5421403", "0.5415724", "0.5397916", "0.53940386", "0.5377912", "0.5368182", "0.53543913", "0.534605", "0.5344237", "0.53400904", "0.5326566", "0.53263456", "0.53247076", "0.5306871", "0.5299979", "0.5279271", "0.52602816", "0.5258084", "0.5258025", "0.5239902", "0.5235103", "0.52344596", "0.5227285", "0.52002096", "0.51881427", "0.5186407", "0.5183174", "0.5176544", "0.5173391", "0.51640964", "0.5162871", "0.515979", "0.5150465", "0.5143474", "0.51402617", "0.5139535", "0.51377636", "0.5135745", "0.5134035", "0.5125375", "0.5117434", "0.5107972", "0.5093995", "0.5092685", "0.5092337", "0.5089666", "0.5084796", "0.5083212", "0.5078516", "0.5075214", "0.5073417", "0.5066857", "0.5065042", "0.5065042", "0.50541353", "0.5049751", "0.5038068", "0.50326514", "0.50321454", "0.5028525", "0.5012523", "0.50051475", "0.50051093", "0.499729", "0.499712" ]
0.0
-1
In order for 'go test' to run this suite, we need to create a normal test function and pass our suite to suite.Run
func TestAddWithoutPlus(t *testing.T) { suite.Run(t, new(AddWithoutPlusTestingSuite)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TestRunMain(t *testing.T) {\n\tmain()\n}", "func TestRun(t *testing.T) {\n\tRun()\n}", "func TestMain(t *testing.T) {\n}", "func TestMain(t *testing.T) { TestingT(t) }", "func (suite *TrackvisitedTestSuite) SetupTest() {}", "func setupTest() {\n}", "func TestRun(t *testing.T) {\n\tsuite.Run(t, new(CategoryTestSuite))\n\tsuite.Run(t, new(ProductTestSuite))\n}", "func Suite(name string, test Test) *suite {\n\tsuite := &suite{\n\t\tName: name,\n\t\tTest: test,\n\t\tStats: &stats{},\n\t}\n\tsuite.ctx = &C{\n\t\tsuite: suite,\n\t}\n\tDefaultRunner.Add(suite)\n\treturn suite\n}", "func Test(t *testing.T) {\n}", "func TestMainTestSuite(t *testing.T) {\n\tsuite.Run(t, new(MainTestSuite))\n}", "func Test1IsATest(t *testing.T) {\n}", "func Test_sampe002(t *testing.T) {\n\n}", "func Run(t *testing.T, s suite.TestingSuite) {\n\tsuite.Run(t, s)\n}", "func (suite *applyTestSuite) SetupTest() {\n\tsuite.col1 = series.NewSeries(\"col1\", 12, 34, 54, 65, 90)\n\tsuite.col2 = series.NewSeries(\"col2\", 54.31, 1.23, 45.6, 23.12, 23.2)\n\tsuite.col3 = series.NewSeries(\"col3\", 14, 124.23, 32, 64.65, 34)\n\tsuite.df = NewDataFrame(suite.col1, suite.col2, suite.col3)\n\tsuite.err = errors.New(\"not a float\")\n\tsuite.fun1 = func(val interface{}) (interface{}, error) {\n\t\tfloatVal, ok := val.(float64)\n\t\tif !ok {\n\t\t\treturn nil, suite.err\n\t\t}\n\t\treturn math.Round(floatVal), nil\n\t}\n\tsuite.fun2 = func(val interface{}) (interface{}, error) {\n\t\tnum, ok := val.(float64)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"not a float\")\n\t\t}\n\t\treturn math.Sqrt(num), nil\n\t}\n}", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func TestCallFunc_function(t *testing.T) {\n\n}", "func runSuite(t *testing.T, db *H, suite interface{}) {\n\trv := reflect.ValueOf(suite)\n\t//if not pointer quit\n\tif rv.Kind() != reflect.Ptr {\n\t\treturn\n\t}\n\n\trt := rv.Type()\n\tfor i := 0; i < rt.NumMethod(); i++ {\n\t\tm := rt.Method(i)\n\t\tif strings.HasPrefix(m.Name, \"Test\") {\n\t\t\tt.Run(m.Name, func(t *testing.T) {\n\n\t\t\t\tdb, err := localizeLogger(db, t)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\n\t\t\t\tvar args = []reflect.Value{\n\t\t\t\t\trv,\n\t\t\t\t\treflect.ValueOf(t),\n\t\t\t\t\treflect.ValueOf(db),\n\t\t\t\t}\n\t\t\t\tm.Func.Call(args)\n\t\t\t})\n\t\t}\n\n\t}\n}", "func TestServiceSuite(t *testing.T) {\n\tsuite.Run(t, new(TestSuite))\n}", "func TestTools(t *testing.T) { TestingT(t) }", "func TestMain(m *testing.M) {\n\ttestsuite.RevelTestHelper(m, \"dev\", run.Run)\n}", "func newSuiteRunner(suite interface{}, runConf *RunConf) *suiteRunner {\n var output io.Writer\n var filter string\n\n output = os.Stdout\n\n if runConf != nil {\n if runConf.Output != nil {\n output = runConf.Output\n }\n if runConf.Filter != \"\" {\n filter = runConf.Filter\n }\n }\n\n suiteType := reflect.Typeof(suite)\n suiteNumMethods := suiteType.NumMethod()\n suiteValue := reflect.NewValue(suite)\n\n runner := suiteRunner{suite:suite,\n tracker:newResultTracker(output)}\n runner.tests = make([]*reflect.FuncValue, suiteNumMethods)\n runner.tempDir = new(tempDir)\n testsLen := 0\n\n var filterRegexp *regexp.Regexp\n if filter != \"\" {\n if regexp, err := regexp.Compile(filter); err != nil {\n msg := \"Bad filter expression: \" + err.String()\n runner.tracker.result.RunError = os.NewError(msg)\n return &runner\n } else {\n filterRegexp = regexp\n }\n }\n\n // This map will be used to filter out duplicated methods. This\n // looks like a bug in Go, described on issue 906:\n // http://code.google.com/p/go/issues/detail?id=906\n seen := make(map[uintptr]bool, suiteNumMethods)\n\n // XXX Shouldn't Name() work here? Why does it return an empty string?\n suiteName := suiteType.String()\n if index := strings.LastIndex(suiteName, \".\"); index != -1 {\n suiteName = suiteName[index+1:]\n }\n\n for i := 0; i != suiteNumMethods; i++ {\n funcValue := suiteValue.Method(i)\n funcPC := funcValue.Get()\n if _, found := seen[funcPC]; found {\n continue\n }\n seen[funcPC] = true\n method := suiteType.Method(i)\n switch method.Name {\n case \"SetUpSuite\":\n runner.setUpSuite = funcValue\n case \"TearDownSuite\":\n runner.tearDownSuite = funcValue\n case \"SetUpTest\":\n runner.setUpTest = funcValue\n case \"TearDownTest\":\n runner.tearDownTest = funcValue\n default:\n if isWantedTest(suiteName, method.Name, filterRegexp) {\n runner.tests[testsLen] = funcValue\n testsLen += 1\n }\n }\n }\n\n runner.tests = runner.tests[0:testsLen]\n return &runner\n}", "func TestMain(m *testing.M) {\n\tfstest.TestMain(m)\n}", "func TestMain(m *testing.M) {\n\tfstest.TestMain(m)\n}", "func TestMain(m *testing.M) {\n\tfstest.TestMain(m)\n}", "func TestTestSuite(t *testing.T) {\n\tRunSuite(t, new(SuiteSuite))\n}", "func (suite *SmsTests) SetUpSuite(c *C) {\n}", "func RunTestSuite(t *testing.T, s storage.Storage) {\n\tt.Run(\"UpdateAuthRequest\", func(t *testing.T) { testUpdateAuthRequest(t, s) })\n\tt.Run(\"CreateRefresh\", func(t *testing.T) { testCreateRefresh(t, s) })\n}", "func TestWorkerTestSuite(t *testing.T) {\n\tsuite.Run(t, new(WorkerTestSuite))\n}", "func (pg *PortalIntegrationTestSuite) SetupSuite() {\n\tfmt.Println(\"Setting up the suite...\")\n\t// Kovan env\n\tpg.IncKBNTokenIDStr = \"0000000000000000000000000000000000000000000000000000000000000082\"\n\tpg.IncSALTTokenIDStr = \"0000000000000000000000000000000000000000000000000000000000000081\"\n\tpg.IncOMGTokenIDStr = \"0000000000000000000000000000000000000000000000000000000000000072\"\n\tpg.IncSNTTokenIDStr = \"0000000000000000000000000000000000000000000000000000000000000071\"\n\tpg.OMGAddressStr = \"0xdB7ec4E4784118D9733710e46F7C83fE7889596a\" // kovan\n\tpg.SNTAddressStr = \"0x4c99B04682fbF9020Fcb31677F8D8d66832d3322\" // kovan\n\tpg.DepositingEther = float64(5)\n\tpg.ETHPrivKeyStr = \"1ABA488300A9D7297A315D127837BE4219107C62C61966ECDF7A75431D75CC61\"\n\tpg.PortalAdminKey = \"B8DB29A7A43FB88AD520F762C5FDF6F1B0155637FA1E5CB2C796AFE9E5C04E31\"\n\tpg.ETHHost = \"http://localhost:8545\"\n\n\tvar err error\n\tfmt.Println(\"Pulling image if not exist, please wait...\")\n\t// remove container if already running\n\texec.Command(\"/bin/sh\", \"-c\", \"docker rm -f portalv3\").Output()\n\texec.Command(\"/bin/sh\", \"-c\", \"docker rm -f incognito\").Output()\n\t_, err = exec.Command(\"/bin/sh\", \"-c\", \"docker run -d -p 8545:8545 --name portalv3 trufflesuite/ganache-cli --account=\\\"0x1ABA488300A9D7297A315D127837BE4219107C62C61966ECDF7A75431D75CC61,10000000000000000000000000000000000,0xB8DB29A7A43FB88AD520F762C5FDF6F1B0155637FA1E5CB2C796AFE9E5C04E31,10000000000000000000000000000000000\\\"\").Output()\n\trequire.Equal(pg.T(), nil, err)\n\ttime.Sleep(10 * time.Second)\n\n\tETHPrivKey, ETHClient, err := ethInstance(pg.ETHPrivKeyStr, pg.ETHHost)\n\trequire.Equal(pg.T(), nil, err)\n\tpg.ETHClient = ETHClient\n\tpg.ETHPrivKey = ETHPrivKey\n\tpg.auth = bind.NewKeyedTransactor(ETHPrivKey)\n\n\t// admin key\n\tprivKey, err := crypto.HexToECDSA(pg.PortalAdminKey)\n\trequire.Equal(pg.T(), nil, err)\n\tadmin := bind.NewKeyedTransactor(privKey)\n\n\t//pg.Portalv3 = common.HexToAddress(\"0x8c13AFB7815f10A8333955854E6ec7503eD841B7\")\n\t//pg.portalV3Inst, err = portalv3.NewPortalv3(pg.Portalv3, pg.ETHClient)\n\t//require.Equal(pg.T(), nil, err)\n\t//incAddr := common.HexToAddress(\"0x2fe0423B148739CD9D0E49e07b5ca00d388A15ac\")\n\t//pg.incProxy, err = incognitoproxy.NewIncognitoproxy(incAddr, pg.ETHClient)\n\t//require.Equal(pg.T(), nil, err)\n\n\tc := getFixedCommittee()\n\tincAddr, _, _, err := incognitoproxy.DeployIncognitoproxy(pg.auth, pg.ETHClient, admin.From, c.beacons)\n\trequire.Equal(pg.T(), nil, err)\n\tfmt.Printf(\"Proxy address: %s\\n\", incAddr.Hex())\n\tportalv3Logic, _, _, err := portalv3.DeployPortalv3(pg.auth, pg.ETHClient)\n\trequire.Equal(pg.T(), nil, err)\n\tfmt.Printf(\"portalv3 address: %s\\n\", portalv3Logic.Hex())\n\n\tportalv3ABI, _ := abi.JSON(strings.NewReader(portalv3.Portalv3ABI))\n\tinput, _ := portalv3ABI.Pack(\"initialize\")\n\n\t//PortalV3\n\tpg.Portalv3, _, _, err = delegator.DeployDelegator(pg.auth, pg.ETHClient, portalv3Logic, admin.From, incAddr, input)\n\trequire.Equal(pg.T(), nil, err)\n\tfmt.Printf(\"delegator address: %s\\n\", pg.Portalv3.Hex())\n\tpg.portalV3Inst, err = portalv3.NewPortalv3(pg.Portalv3, pg.ETHClient)\n\trequire.Equal(pg.T(), nil, err)\n\tpg.incProxy, err = incognitoproxy.NewIncognitoproxy(incAddr, pg.ETHClient)\n\trequire.Equal(pg.T(), nil, err)\n\n\t// 0x54d28562271De782B261807a01d1D2fb97417912\n\tpg.USDTAddress, _, _, err = usdt.DeployUsdt(pg.auth, pg.ETHClient, big.NewInt(100000000000), \"Tether\", \"USDT\", big.NewInt(6))\n\trequire.Equal(pg.T(), nil, err)\n\tfmt.Printf(\"usdt address: %s\\n\", pg.USDTAddress.Hex())\n\n\t//get portalv3 ip\n\tipAddress, err := exec.Command(\"/bin/sh\", \"-c\", \"docker inspect -f \\\"{{ .NetworkSettings.IPAddress }}\\\" portalv3\").Output()\n\trequire.Equal(pg.T(), nil, err)\n\n\t// run incognito chaind\n\tincogitoWithArgument := fmt.Sprintf(\"docker run -d -p 9334:9334 -p 9338:9338 --name incognito -e GETH_NAME=%v -e PORTAL_CONTRACT=%v incognito\", string(ipAddress), pg.Portalv3.Hex())\n\tincogitoWithArgument = strings.Replace(incogitoWithArgument, \"\\n\", \"\", -1)\n\t_, err = exec.Command(\"/bin/sh\", \"-c\", incogitoWithArgument).Output()\n\trequire.Equal(pg.T(), nil, err)\n\n\tfor {\n\t\ttime.Sleep(5 * time.Second)\n\t\tif checkRepsonse(pg.IncBridgeHost) {\n\t\t\tbreak\n\t\t}\n\t}\n\ttime.Sleep(40 * time.Second)\n}", "func TestBasic(t *testing.T) {\n\tt.Log(\"Start TestBasic ++++++++++++++\")\n\n\ttcase(tmake(), t)\n\n\tt.Log(\"End TestBasic ++++++++++++++\")\n}", "func TestMain(m *testing.M) {\n\tprintln(\"do stuff before all tests\")\n\tm.Run()\n\tprintln(\"do stuff after all tests\")\n}", "func (s Suite) Run(t *testing.T) bool {\n\tt.Helper()\n\treturn s(\"\", nil, func(c *config) { c.t = t })\n}", "func runTestSuite(t *testing.T, ts TestSuite) {\n\t// Load only the rule for this test suite\n\truleConfigPath := strings.Split(ts.RootPath, \"config-lint/cli/assets/\")[1] + \"/rule.yml\"\n\truleSet, err := loadBuiltInRuleSet(ruleConfigPath)\n\tif err != nil {\n\t\tassert.Nil(t, err, \"Cannot load built-in Terraform rule\")\n\t}\n\n\tfor _, tc := range ts.Tests {\n\t\toptions := linter.Options{\n\t\t\tRuleIDs: []string{tc.RuleId},\n\t\t}\n\t\tvs := assertion.StandardValueSource{}\n\n\t\t// validate the rule set\n\t\tif contains(tc.Tags, \"terraform11\") {\n\t\t\t// Load the test resources for this test suite\n\t\t\ttestResourceDirectory := strings.Split(ts.RootPath, \"config-lint/cli/\")[1] + \"/tests/terraform11/\"\n\t\t\ttestResources, err := getTestResources(testResourceDirectory)\n\t\t\tif err != nil {\n\t\t\t\tassert.Nil(t, err, \"Cannot load built-in Terraform 11 test resources\")\n\n\t\t\t}\n\t\t\t// Defining 'tf11' for the Parser type\n\t\t\tl, err := linter.NewLinter(ruleSet, vs, testResources, \"tf11\")\n\n\t\t\treport, err := l.Validate(ruleSet, options)\n\t\t\tassert.Nil(t, err, \"Validate failed for file\")\n\n\t\t\twarningViolationsReported := getViolationsString(\"WARNING\", report.Violations)\n\t\t\twarningMessage := fmt.Sprintf(\"Expecting %d warnings for rule %s:\\n %s\", tc.Warnings, tc.RuleId, warningViolationsReported)\n\t\t\tassert.Equal(t, tc.Warnings, numberOfWarnings(report.Violations), warningMessage)\n\n\t\t\tfailureViolationsReported := getViolationsString(\"FAILURE\", report.Violations)\n\t\t\tfailureMessage := fmt.Sprintf(\"Expecting %d failures for rule %s:\\n %s\", tc.Failures, tc.RuleId, failureViolationsReported)\n\t\t\tassert.Equal(t, tc.Failures, numberOfFailures(report.Violations), failureMessage)\n\t\t}\n\n\t\tif contains(tc.Tags, \"terraform12\") {\n\t\t\t// Load the test resources for this test suite\n\t\t\ttestResourceDirectory := strings.Split(ts.RootPath, \"config-lint/cli/\")[1] + \"/tests/terraform12/\"\n\t\t\ttestResources, err := getTestResources(testResourceDirectory)\n\t\t\tif err != nil {\n\t\t\t\tassert.Nil(t, err, \"Cannot load built-in Terraform 12 test resources\")\n\n\t\t\t}\n\t\t\t// Defining 'tf11' for the Parser type\n\t\t\tl, err := linter.NewLinter(ruleSet, vs, testResources, \"tf12\")\n\n\t\t\treport, err := l.Validate(ruleSet, options)\n\t\t\tassert.Nil(t, err, \"Validate failed for file\")\n\n\t\t\twarningViolationsReported := getViolationsString(\"WARNING\", report.Violations)\n\t\t\twarningMessage := fmt.Sprintf(\"Expecting %d warnings for rule %s:\\n %s\", tc.Warnings, tc.RuleId, warningViolationsReported)\n\t\t\tassert.Equal(t, tc.Warnings, numberOfWarnings(report.Violations), warningMessage)\n\n\t\t\tfailureViolationsReported := getViolationsString(\"FAILURE\", report.Violations)\n\t\t\tfailureMessage := fmt.Sprintf(\"Expecting %d failures for rule %s:\\n %s\", tc.Failures, tc.RuleId, failureViolationsReported)\n\t\t\tassert.Equal(t, tc.Failures, numberOfFailures(report.Violations), failureMessage)\n\t\t}\n\t}\n}", "func TestCreate(t *testing.T) {\n\n}", "func (runner *suiteRunner) run() *Result {\n if runner.tracker.result.RunError == nil && len(runner.tests) > 0 {\n runner.tracker.start()\n if runner.checkFixtureArgs() {\n if runner.runFixture(runner.setUpSuite) {\n for i := 0; i != len(runner.tests); i++ {\n c := runner.runTest(runner.tests[i])\n if c.status == fixturePanickedSt {\n runner.missTests(runner.tests[i+1:])\n break\n }\n }\n } else {\n runner.missTests(runner.tests)\n }\n runner.runFixture(runner.tearDownSuite)\n } else {\n runner.missTests(runner.tests)\n }\n runner.tracker.waitAndStop()\n runner.tempDir.removeAll()\n }\n return &runner.tracker.result\n}", "func TestMain(m *testing.M) {\n\tframework.\n\t\tNewSuite(m).\n\t\tRequireSingleCluster().\n\t\tSetup(istio.Setup(&i, func(cfg *istio.Config) {\n\t\t\tcfg.Values[\"telemetry.enabled\"] = \"true\"\n\t\t\tcfg.Values[\"telemetry.v2.enabled\"] = \"true\"\n\t\t\tcfg.Values[\"telemetry.v2.stackdriver.enabled\"] = \"true\"\n\t\t\tcfg.Values[\"telemetry.v2.stackdriver.logging\"] = \"true\"\n\t\t})).\n\t\tSetup(testSetup).\n\t\tRun()\n}", "func TestA(t *testing.T) {}", "func TestExampleTestSuite(t *testing.T) {\n\tsuite.Run(t, new(ExampleTestSuite))\n}", "func Test(t *testing.T, driver, dsn string, testSuites []string, rw bool) {\n\tclients, err := ConnectClients(t, driver, dsn, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to connect to %s (%s driver): %s\\n\", dsn, driver, err)\n\t}\n\tclients.RW = rw\n\ttests := make(map[string]struct{})\n\tfor _, test := range testSuites {\n\t\ttests[test] = struct{}{}\n\t}\n\tif _, ok := tests[SuiteAuto]; ok {\n\t\tt.Log(\"Detecting target service compatibility...\")\n\t\tsuites, err := detectCompatibility(clients.Admin)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Unable to determine server suite compatibility: %s\\n\", err)\n\t\t}\n\t\ttests = make(map[string]struct{})\n\t\tfor _, suite := range suites {\n\t\t\ttests[suite] = struct{}{}\n\t\t}\n\t}\n\ttestSuites = make([]string, 0, len(tests))\n\tfor test := range tests {\n\t\ttestSuites = append(testSuites, test)\n\t}\n\tt.Logf(\"Running the following test suites: %s\\n\", strings.Join(testSuites, \", \"))\n\tfor _, suite := range testSuites {\n\t\tRunTestsInternal(clients, suite)\n\t}\n}", "func (test Test) Run(t *testing.T) {\n\tt.Logf(\"Starting test %v\", t.Name())\n\tt.Helper()\n\t// Double negative cannot be helped, this is intended to mitigate test failures where a global\n\t// resource is manipulated, e.g.: the default AWS security group.\n\tif !test.RunOptions.NoParallel {\n\t\tt.Parallel()\n\t}\n\tt.Run(\"Python\", func(t *testing.T) {\n\t\trunOpts := integration.ProgramTestOptions{}\n\t\tif test.RunOptions != nil {\n\t\t\trunOpts = *test.RunOptions\n\t\t}\n\t\tconvertOpts := test.Options\n\t\tif test.Python != nil {\n\t\t\tconvertOpts = convertOpts.With(*test.Python)\n\t\t}\n\n\t\ttargetTest := targetTest{\n\t\t\trunOpts: &runOpts,\n\t\t\tconvertOpts: &convertOpts,\n\t\t\tprojectName: test.ProjectName,\n\t\t\tlanguage: \"python\",\n\t\t\truntime: \"python\",\n\t\t}\n\t\ttargetTest.Run(t)\n\t})\n\tt.Run(\"TypeScript\", func(t *testing.T) {\n\t\trunOpts := integration.ProgramTestOptions{}\n\t\tif test.RunOptions != nil {\n\t\t\trunOpts = *test.RunOptions\n\t\t}\n\t\tconvertOpts := test.Options\n\t\tif test.TypeScript != nil {\n\t\t\tconvertOpts = convertOpts.With(*test.TypeScript)\n\t\t}\n\n\t\ttargetTest := targetTest{\n\t\t\trunOpts: &runOpts,\n\t\t\tconvertOpts: &convertOpts,\n\t\t\tprojectName: test.ProjectName,\n\t\t\tlanguage: \"typescript\",\n\t\t\truntime: \"nodejs\",\n\t\t}\n\t\ttargetTest.Run(t)\n\t})\n}", "func (suite FeatureTestSuite) Run(t *testing.T, buildFunc feature.BuildFunc) {\n\tfor _, test := range suite {\n\t\trunTest(t, test, buildFunc)\n\t}\n}", "func TestPermissionsJob(t *testing.T) {\n suite.Run(t, new(PermissionsJobTestSuite))\n}", "func (ts *TestSuite) RunTests() {\n\n\tif len(ts.Tests) == 0 {\n\t\tout.Printf(\"No tests to run\\n\")\n\t\treturn\n\t}\n\n\tstartTime := time.Now()\n\n\t// setup search\n\ts := search.NewSearch()\n\tsl := search.NewSearchLimits()\n\tsl.MoveTime = ts.Time\n\tsl.Depth = ts.Depth\n\tif sl.MoveTime > 0 {\n\t\tsl.TimeControl = true\n\t}\n\n\tout.Printf(\"Running Test Suite\\n\")\n\tout.Printf(\"==================================================================\\n\")\n\tout.Printf(\"EPD File: %s\\n\", ts.FilePath)\n\tout.Printf(\"SearchTime: %d ms\\n\", ts.Time.Milliseconds())\n\tout.Printf(\"MaxDepth: %d\\n\", ts.Depth)\n\tout.Printf(\"Date: %s\\n\", time.Now().Local())\n\tout.Printf(\"No of tests: %d\\n\", len(ts.Tests))\n\tout.Println()\n\n\t// execute all tests and store results in the\n\t// test instance\n\tfor i, t := range ts.Tests {\n\t\tout.Printf(\"Test %d of %d\\nTest: %s -- Target Result %s\\n\", i+1, len(ts.Tests), t.line, t.targetMoves.StringUci())\n\t\tstartTime2 := time.Now()\n\t\trunSingleTest(s, sl, t)\n\t\telapsedTime := time.Since(startTime2)\n\t\tt.nodes = s.NodesVisited()\n\t\tt.time = s.LastSearchResult().SearchTime\n\t\tt.nps = util.Nps(s.NodesVisited(), s.LastSearchResult().SearchTime)\n\t\tout.Printf(\"Test finished in %d ms with result %s (%s) - nps: %d\\n\\n\",\n\t\t\telapsedTime.Milliseconds(), t.rType.String(), t.actual.StringUci(), t.nps)\n\t}\n\n\t// sum up result for report\n\ttr := &SuiteResult{}\n\tfor _, t := range ts.Tests {\n\t\ttr.Counter++\n\t\tswitch t.rType {\n\t\tcase NotTested:\n\t\t\ttr.NotTestedCounter++\n\t\tcase Skipped:\n\t\t\ttr.SkippedCounter++\n\t\tcase Failed:\n\t\t\ttr.FailedCounter++\n\t\tcase Success:\n\t\t\ttr.SuccessCounter++\n\t\t}\n\t\ttr.Nodes += t.nodes\n\t\ttr.Time += t.time\n\t}\n\tts.LastResult = tr\n\n\telapsed := time.Since(startTime)\n\n\t// print report\n\tout.Printf(\"Results for Test Suite\\n\", ts.FilePath)\n\tout.Printf(\"------------------------------------------------------------------------------------------------------------------------------------\\n\")\n\tout.Printf(\"EPD File: %s\\n\", ts.FilePath)\n\tout.Printf(\"SearchTime: %d ms\\n\", ts.Time.Milliseconds())\n\tout.Printf(\"MaxDepth: %d\\n\", ts.Depth)\n\tout.Printf(\"Date: %s\\n\", time.Now().Local())\n\tout.Printf(\"====================================================================================================================================\\n\")\n\tout.Printf(\" %-4s | %-10s | %-8s | %-8s | %-15s | %s | %s\\n\", \" Nr.\", \"Result\", \"Move\", \"Value\", \"Expected Result\", \"Fen\", \"Id\")\n\tout.Printf(\"====================================================================================================================================\\n\")\n\tfor i, t := range ts.Tests {\n\t\tif t.tType == DM {\n\t\t\tout.Printf(\" %-4d | %-10s | %-8s | %-8s | %s%-15d | %s | %s\\n\",\n\t\t\t\ti+1, t.rType.String(), t.actual.StringUci(), t.value.String(), \"dm \", t.mateDepth, t.fen, t.id)\n\t\t} else {\n\t\t\tout.Printf(\" %-4d | %-10s | %-8s | %-8s | %s %-15s | %s | %s\\n\",\n\t\t\t\ti+1, t.rType.String(), t.actual.StringUci(), t.value.String(), t.tType.String(), t.targetMoves.StringUci(), t.fen, t.id)\n\t\t}\n\t}\n\tout.Printf(\"====================================================================================================================================\\n\")\n\tout.Printf(\"Summary:\\n\")\n\tout.Printf(\"EPD File: %s\\n\", ts.FilePath)\n\tout.Printf(\"SearchTime: %d ms\\n\", ts.Time.Milliseconds())\n\tout.Printf(\"MaxDepth: %d\\n\", ts.Depth)\n\tout.Printf(\"Date: %s\\n\", time.Now().Local())\n\tout.Printf(\"Successful: %-3d (%d %%)\\n\", tr.SuccessCounter, 100*tr.SuccessCounter/tr.Counter)\n\tout.Printf(\"Failed: %-3d (%d %%)\\n\", tr.FailedCounter, 100*tr.FailedCounter/tr.Counter)\n\tout.Printf(\"Skipped: %-3d (%d %%)\\n\", tr.SkippedCounter, 100*tr.SkippedCounter/tr.Counter)\n\tout.Printf(\"Not tested: %-3d (%d %%)\\n\", tr.NotTestedCounter, 100*tr.NotTestedCounter/tr.Counter)\n\tout.Printf(\"Test time: %s\\n\", elapsed)\n\tout.Printf(\"Configuration: %s\\n\", config.Settings.String())\n}", "func RunTests(t *testing.T, svctest ServiceTest) {\n\tt.Run(\"NewSite\", func(t *testing.T) { clearEnvWrapper(t, svctest.TestNewSite) })\n\tt.Run(\"DeleteSite\", func(t *testing.T) { clearEnvWrapper(t, svctest.TestDeleteSite) })\n\tt.Run(\"WritePost\", func(t *testing.T) { clearEnvWrapper(t, svctest.TestWritePost) })\n\tt.Run(\"RemovePost\", func(t *testing.T) { clearEnvWrapper(t, svctest.TestRemovePost) })\n\tt.Run(\"ReadPost\", func(t *testing.T) { clearEnvWrapper(t, svctest.TestReadPost) })\n\tt.Run(\"WriteConfig\", func(t *testing.T) { clearEnvWrapper(t, svctest.TestWriteConfig) })\n\tt.Run(\"ReadConfig\", func(t *testing.T) { clearEnvWrapper(t, svctest.TestReadConfig) })\n\tt.Run(\"UpdateAbout\", func(t *testing.T) { clearEnvWrapper(t, svctest.TestUpdateAbout) })\n\tt.Run(\"ReadAbout\", func(t *testing.T) { clearEnvWrapper(t, svctest.TestReadAbout) })\n\tt.Run(\"ChangeDefaultConfig\", func(t *testing.T) { clearEnvWrapper(t, svctest.TestChangeDefaultConfig) })\n}", "func TestMain(m *testing.M) {\n\tframework.Run(\"pilot_test\", m)\n}", "func TestMain(m *testing.M) {\n\tsetup()\n\tcode := m.Run() \n os.Exit(code)\n}", "func TestSuite(ctx context.Context, tswg *sync.WaitGroup, testSuites chan *junitxml.TestSuite, logger *log.Logger, testSuiteRegex, testCaseRegex *regexp.Regexp) {\n\tdefer tswg.Done()\n\n\tif testSuiteRegex != nil && !testSuiteRegex.MatchString(testSuiteName) {\n\t\treturn\n\t}\n\n\ttestSuite := junitxml.NewTestSuite(testSuiteName)\n\tdefer testSuite.Finish(testSuites)\n\n\tlogger.Printf(\"Running TestSuite %q\", testSuite.Name)\n\n\ttestSetup := []*packageManagementTestSetup{\n\t\t// Debian images.\n\t\t&packageManagementTestSetup{\n\t\t\timage: \"projects/debian-cloud/global/images/family/debian-9\",\n\t\t\tpackageType: []string{\"deb\"},\n\t\t\tshortName: \"debian\",\n\t\t\tstartup: &api.MetadataItems{\n\t\t\t\tKey: \"startup-script\",\n\t\t\t\tValue: &installOsConfigAgentDeb,\n\t\t\t},\n\t\t},\n\t}\n\n\tvar wg sync.WaitGroup\n\ttests := make(chan *junitxml.TestCase)\n\tfor _, setup := range testSetup {\n\t\twg.Add(1)\n\t\tgo packageManagementTestCase(ctx, setup, tests, &wg, logger, testCaseRegex)\n\t}\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(tests)\n\t}()\n\n\tfor ret := range tests {\n\t\ttestSuite.TestCase = append(testSuite.TestCase, ret)\n\t}\n\n\tlogger.Printf(\"Finished TestSuite %q\", testSuite.Name)\n}", "func TestHealthCheckTestSuite(t *testing.T) {\n\tsuite.Run(t, new(HealthCheckTestSuite))\n}", "func Test(t *testing.T) { check.TestingT(t) }", "func Test(t *testing.T) { check.TestingT(t) }" ]
[ "0.7153396", "0.7129117", "0.7105195", "0.7049557", "0.68031365", "0.67593354", "0.67246485", "0.6681974", "0.6678224", "0.66272557", "0.6620877", "0.66015744", "0.659783", "0.65667325", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.65663517", "0.6554572", "0.65484726", "0.65371877", "0.652594", "0.6507288", "0.6501091", "0.6458981", "0.6458981", "0.6458981", "0.6439115", "0.6430419", "0.6425264", "0.64138305", "0.63955337", "0.637615", "0.63725597", "0.6340195", "0.6335555", "0.63290864", "0.63236266", "0.6306916", "0.630538", "0.6303619", "0.63027084", "0.62994695", "0.629831", "0.62872136", "0.6240623", "0.6240524", "0.62398285", "0.6229006", "0.6216066", "0.62044954", "0.6202716", "0.6202716" ]
0.0
-1
TABLE TEST OMIT SUB TEST START
func TestSubFibonacci(t *testing.T) { var tests = []struct { input, result int }{ {input: 2, result: 1}, {input: 8, result: 21}, {input: 10, result: 55}, } for _, test := range tests { t.Run(fmt.Sprintf("Fibonacci(%d)", test.input), func(t *testing.T) { testingFunc(t, test.input, test.result) }) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TestHelloWorldTable(t *testing.T) {\n\ttests := []struct{\n\t\tname\t\tstring \t//name of sub-test\n\t\trequest\t\tstring \t//what's ur request?\n\t\texpected\tstring\t//expectation\n\t}{\n\t\t{\n\t\t\tname: \"Aji\",\n\t\t\trequest: \"Aji\",\n\t\t\texpected: \"Hello Aji\",\n\t\t},\n\t\t{\n\t\t\tname: \"Wahidin\",\n\t\t\trequest: \"Wahidin\",\n\t\t\texpected: \"Hello Wahidin\",\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tresult := HelloWorld(test.request)\n\t\t\trequire.Equal(t, test.expected, result)\n\t\t})\n\t}\n}", "func doTableTest(t *testing.T, out io.Writer, f decoder.New, endianness bool, teTa decoder.TestTable) {\n\tvar (\n\t\t// til is the trace id list content for test\n\t\tidl = `{\n\t\t\t\"3713\": {\n\t\t\t\t\"Type\": \"TRICE16\",\n\t\t\t\t\"Strg\": \"MSG: 💚 START select = %d\\\\n\"\n\t\t\t},\n\t\t\t\"935\": {\n\t\t\t\t\"Type\": \"TRICE\",\n\t\t\t\t\"Strg\": \"MSG:triceFifoDepthMax = %d of max %d, triceStreamBufferDepthMax = %d of max %d\\\\n\"\n\t\t\t}\n\t\t}\n\t`\n\t)\n\tilu := make(id.TriceIDLookUp) // empty\n\tli := make(id.TriceIDLookUpLI) // empty\n\tluM := new(sync.RWMutex)\n\tassert.Nil(t, ilu.FromJSON([]byte(idl)))\n\tilu.AddFmtCount(os.Stdout)\n\tbuf := make([]byte, decoder.DefaultSize)\n\tdec := f(out, ilu, luM, li, nil, endianness) // a new decoder instance\n\tfor _, x := range teTa {\n\t\tin := io.NopCloser(bytes.NewBuffer(x.In))\n\t\tdec.SetInput(in)\n\t\tlineStart := true\n\t\tvar err error\n\t\tvar n int\n\t\tvar act string\n\t\tfor nil == err {\n\t\t\tn, err = dec.Read(buf)\n\t\t\tif n == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif decoder.ShowID != \"\" && lineStart {\n\t\t\t\tact += fmt.Sprintf(decoder.ShowID, decoder.LastTriceID)\n\t\t\t}\n\t\t\tact += fmt.Sprint(string(buf[:n]))\n\t\t\tlineStart = false\n\t\t}\n\t\tact = strings.TrimSuffix(act, \"\\\\n\")\n\t\tact = strings.TrimSuffix(act, \"\\n\")\n\t\tassert.Equal(t, x.Exp, act)\n\t}\n}", "func TestGetAllOrdersForTableID(t *testing.T) {\n\n // ...\n\n}", "func TestTableAdd(t *testing.T) {\n\n\t//iterate over test array\n\tfor _, test := range testingArray {\n\n\t\t//call Add and get the result\n\t\tresult := Add(test.x, test.y)\n\n\t\t//compare the result to expected. return error if failed\n\t\tif result != test.expected {\n\t\t\tt.Error(\"Testing failed\")\n\t\t}\n\t}\n\n}", "func TestEmptyPrewrite4A(t *testing.T) {\n}", "func Test_sampe002(t *testing.T) {\n\n}", "func createTestTable(t *testing.T, db *sql.DB, dbName string, schema string) tableInfo {\n\tvar tableName string\n\nouter:\n\tfor {\n\t\t// Create the testing database\n\t\ttableNum := r.Intn(10000)\n\t\ttableName = fmt.Sprintf(\"_test_table_%d\", tableNum)\n\n\t\t// Find the DB.\n\t\tvar actualTableName string\n\t\terr := crdb.Execute(func() error {\n\t\t\treturn db.QueryRow(\n\t\t\t\tfmt.Sprintf(\"SELECT table_name FROM [SHOW TABLES FROM %s] WHERE table_name = $1\", dbName),\n\t\t\t\ttableName,\n\t\t\t).Scan(&actualTableName)\n\t\t})\n\t\tswitch err {\n\t\tcase sql.ErrNoRows:\n\t\t\tbreak outer\n\t\tcase nil:\n\t\t\tcontinue\n\t\tdefault:\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\n\tif err := Execute(db, fmt.Sprintf(tableSimpleSchema, dbName, tableName)); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tt.Logf(\"Testing Table: %s.%s\", dbName, tableName)\n\treturn tableInfo{\n\t\tdb: db,\n\t\tdbName: dbName,\n\t\tname: tableName,\n\t}\n}", "func setupTestSuite() {\n\t_1000CharString = stringOfLength(1000)\n\ttableName = \"test\"\n}", "func TestGetEmpty4A(t *testing.T) {\n}", "func TestData(t *testing.T) { TestingT(t) }", "func testTableInfo(store kv.Storage, name string, num int) (*model.TableInfo, error) {\n\ttblInfo := &model.TableInfo{\n\t\tName: model.NewCIStr(name),\n\t}\n\tgenIDs, err := genGlobalIDs(store, 1)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttblInfo.ID = genIDs[0]\n\n\tcols := make([]*model.ColumnInfo, num)\n\tfor i := range cols {\n\t\tcol := &model.ColumnInfo{\n\t\t\tName: model.NewCIStr(fmt.Sprintf(\"c%d\", i+1)),\n\t\t\tOffset: i,\n\t\t\tDefaultValue: i + 1,\n\t\t\tState: model.StatePublic,\n\t\t}\n\n\t\tcol.FieldType = *types.NewFieldType(mysql.TypeLong)\n\t\ttblInfo.MaxColumnID++\n\t\tcol.ID = tblInfo.MaxColumnID\n\t\tcols[i] = col\n\t}\n\ttblInfo.Columns = cols\n\ttblInfo.Charset = \"utf8\"\n\ttblInfo.Collate = \"utf8_bin\"\n\treturn tblInfo, nil\n}", "func TestPrewriteMultiple4A(t *testing.T) {\n}", "func TestDisableTableLeases() func() {\n\ttestDisableTableLeases = true\n\treturn func() {\n\t\ttestDisableTableLeases = false\n\t}\n}", "func (suite *QueryTestSuite) TearDownTest() {\n\terr := test.DeleteTable(suite.table, \"sid\", \"id\")\n\tsuite.NoError(err)\n}", "func ExecuteGenericTestTable(t *testing.T, testTable []GenericTestEntry) {\n\tfor _, testCase := range testTable {\n\t\terr := ocpp2.Validate.Struct(testCase.Element)\n\t\tif err != nil {\n\t\t\tassert.Equal(t, testCase.ExpectedValid, false, err.Error())\n\t\t} else {\n\t\t\tassert.Equal(t, testCase.ExpectedValid, true, \"%v is valid\", testCase.Element)\n\t\t}\n\t}\n}", "func TestGetDeleted4A(t *testing.T) {\n}", "func init() { //nolint\n\ttestSample := TestCase{\n\t\tName: \"should exclude provided queries [E2E-CLI-020]\",\n\t\tArgs: args{\n\t\t\tArgs: []cmdArgs{\n\t\t\t\t[]string{\"scan\", \"--exclude-queries\", \"15ffbacc-fa42-4f6f-a57d-2feac7365caa,0a494a6a-ebe2-48a0-9d77-cf9d5125e1b3\", \"-s\",\n\t\t\t\t\t\"-q\", \"../assets/queries\", \"-p\", \"fixtures/samples/terraform-single.tf\"},\n\t\t\t},\n\t\t},\n\t\tWantStatus: []int{20},\n\t}\n\n\tTests = append(Tests, testSample)\n}", "func TestSuite(t *testing.T, ts *topo.Server, client vtctlclient.VtctlClient) {\n\tctx := context.Background()\n\n\t// Create a fake tablet\n\ttablet := &topodatapb.Tablet{\n\t\tAlias: &topodatapb.TabletAlias{Cell: \"cell1\", Uid: 1},\n\t\tHostname: \"localhost\",\n\t\tMysqlHostname: \"localhost\",\n\t\tPortMap: map[string]int32{\n\t\t\t\"vt\": 3333,\n\t\t},\n\t\tPrimaryTermStartTime: protoutil.TimeToProto(time.Date(1970, 1, 1, 1, 1, 1, 1, time.UTC)),\n\t\tTags: map[string]string{\"tag\": \"value\"},\n\t\tKeyspace: \"test_keyspace\",\n\t\tType: topodatapb.TabletType_PRIMARY,\n\t}\n\ttablet.MysqlPort = 3334\n\tif err := ts.CreateTablet(ctx, tablet); err != nil {\n\t\tt.Errorf(\"CreateTablet: %v\", err)\n\t}\n\n\t// run a command that's gonna return something on the log channel\n\tstream, err := client.ExecuteVtctlCommand(ctx, []string{\"ListAllTablets\", \"cell1\"}, 30*time.Second)\n\tif err != nil {\n\t\tt.Fatalf(\"Remote error: %v\", err)\n\t}\n\n\tgot, err := stream.Recv()\n\tif err != nil {\n\t\tt.Fatalf(\"failed to get first line: %v\", err)\n\t}\n\texpected := \"cell1-0000000001 test_keyspace <null> primary localhost:3333 localhost:3334 [tag: \\\"value\\\"] 1970-01-01T01:01:01Z\\n\"\n\tif logutil.EventString(got) != expected {\n\t\tt.Errorf(\"Got unexpected log line '%v' expected '%v'\", got.String(), expected)\n\t}\n\n\tgot, err = stream.Recv()\n\tif err != io.EOF {\n\t\tt.Errorf(\"Didn't get end of log stream: %v %v\", got, err)\n\t}\n\n\t// run a command that's gonna fail\n\tstream, err = client.ExecuteVtctlCommand(ctx, []string{\"ListAllTablets\", \"cell2\"}, 30*time.Second)\n\tif err != nil {\n\t\tt.Fatalf(\"Remote error: %v\", err)\n\t}\n\n\t_, err = stream.Recv()\n\texpected = \"node doesn't exist\"\n\tif err == nil || !strings.Contains(err.Error(), expected) {\n\t\tt.Fatalf(\"Unexpected remote error, got: '%v' was expecting to find '%v'\", err, expected)\n\t}\n\n\t// run a command that's gonna panic\n\tstream, err = client.ExecuteVtctlCommand(ctx, []string{\"Panic\"}, 30*time.Second)\n\tif err != nil {\n\t\tt.Fatalf(\"Remote error: %v\", err)\n\t}\n\n\t_, err = stream.Recv()\n\texpected1 := \"this command panics on purpose\"\n\texpected2 := \"uncaught vtctl panic\"\n\tif err == nil || !strings.Contains(err.Error(), expected1) || !strings.Contains(err.Error(), expected2) {\n\t\tt.Fatalf(\"Unexpected remote error, got: '%v' was expecting to find '%v' and '%v'\", err, expected1, expected2)\n\t}\n\n\t// and clean up the tablet\n\tif err := ts.DeleteTablet(ctx, tablet.Alias); err != nil {\n\t\tt.Errorf(\"DeleteTablet: %v\", err)\n\t}\n}", "func TestDeleteOrder(t *testing.T) {\n\n // ...\n\n}", "func createTestTable(\n\tt *testing.T,\n\ttc *testcluster.TestCluster,\n\tid int,\n\tdb *gosql.DB,\n\twgStart *sync.WaitGroup,\n\twgEnd *sync.WaitGroup,\n\tsignal chan struct{},\n\tcompleted chan int,\n) {\n\tdefer wgEnd.Done()\n\n\twgStart.Done()\n\t<-signal\n\n\ttableSQL := fmt.Sprintf(`\n\t\tCREATE TABLE IF NOT EXISTS \"test\".\"table_%d\" (\n\t\t\tid INT PRIMARY KEY,\n\t\t\tval INT\n\t\t)`, id)\n\n\tfor {\n\t\tif _, err := db.Exec(tableSQL); err != nil {\n\t\t\tif testutils.IsSQLRetryableError(err) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tt.Errorf(\"table %d: could not be created: %v\", id, err)\n\t\t\treturn\n\t\t}\n\t\tcompleted <- id\n\t\tbreak\n\t}\n}", "func ReadTabTestData(filename string) ([]testrow, error) {\n\trows := make([]testrow, 0) // rows of test data\n\t// read data from tab-delimited file\n\tcsvFile, err := os.Open(\"./testdata.txt\")\n\tif err != nil {\n\t\treturn rows, err\n\t}\n\tdefer csvFile.Close()\n\treader := csv.NewReader(csvFile)\n\treader.Comma = '\\t' // Use tab-delimited instead of comma <---- here!\n\treader.FieldsPerRecord = -1\n\tcsvdata, err := reader.ReadAll() // test file is not huge\n\tif err != nil {\n\t\treturn rows, err\n\t}\n\t// Put data into table of testrows\n\ttripid := GenerateRandomTripid() // generate a random trip ID\n\tfor i := range csvdata {\n\t\tvar ritem testrow // working test row\n\t\tritem.hdr = make(map[string]([]string))\n\t\trow := csvdata[i]\n\t\tif verbose || i == 0 {\n\t\t\tfmt.Printf(\"Test entry\")\n\t\t\tfor j := range row {\n\t\t\t\tfmt.Printf(\" %d=\\\"%s\\\"\", j, row[j])\n\t\t\t}\n\t\t\tfmt.Printf(\"\\n\")\n\t\t}\n\t\tvar v vehlogevent // logger data\n\t\tv.Timestamp, err = strconv.ParseInt(row[1], 10, 64)\n\t\tif err != nil { // file may have header lines\n\t\t\tcontinue\n\t\t} // skip them\n\t\tsr, _ := strconv.ParseInt(row[0], 10, 32)\n\t\tv.Serial = int32(sr)\n\t\tv.Tripid = row[10]\n\t\tsv, _ := strconv.ParseInt(row[11], 10, 8)\n\t\tv.Severity = int8(sv)\n\t\tv.Eventtype = row[12]\n\t\tv.Msg = row[13]\n\t\tau, _ := strconv.ParseFloat(row[14], 32)\n\t\tv.Auxval = float32(au)\n\t\tv.Debug = 0\n\t\tritem.hdr[\"X-Secondlife-Shard\"] = append(make([]string, 0), row[2])\n\t\tritem.hdr[\"X-Secondlife-Owner-Name\"] = append(make([]string, 0), row[3])\n\t\tritem.hdr[\"X-Secondlife-Object-Name\"] = append(make([]string, 0), row[4])\n\t\tritem.hdr[\"X-Secondlife-Region\"] = append(make([]string, 0), fmt.Sprintf(\"%s (%s,%s)\", row[5], row[6], row[7]))\n\t\tritem.hdr[\"X-Secondlife-Local-Position\"] = append(make([]string, 0), fmt.Sprintf(\"(%s,%s,0.0)\", row[8], row[9]))\n\t\t// Adjust test data\n\t\tv.Tripid = tripid // use random tripID\n\t\t// Make up JSON\n\t\tjson, err := json.Marshal(v) // convert to JSON\n\t\tif err != nil {\n\t\t\treturn rows, err\n\t\t}\n\t\tif verbose || i == 0 {\n\t\t\tfmt.Printf(\"JSON: %s\\n\", json)\n\t\t}\n\t\t// Sign JSON\n\t\tritem.hdr[\"X-Authtoken-Name\"] = append(make([]string, 0), testtokenname)\n\t\tritem.json = []byte(json)\n\t\tSignLogMsg(ritem.json, ritem.hdr, testtokenname)\n\t\trows = append(rows, ritem) // add new row\n\n\t}\n\treturn rows, nil\n}", "func TestMain(m *testing.M) {\n\tdao.PrepareTestForPostgresSQL()\n\n\tvar code = m.Run()\n\n\t// clear test database\n\tvar clearSqls = []string{\n\t\t`DROP TABLE \"access\", \"access_log\", \"admin_job\", \"alembic_version\", \"clair_vuln_timestamp\",\n \"harbor_label\", \"harbor_resource_label\", \"harbor_user\", \"img_scan_job\", \"img_scan_overview\",\n \"job_log\", \"project\", \"project_member\", \"project_metadata\", \"properties\", \"registry\",\n \"replication_policy\", \"repository\", \"robot\", \"role\", \"schema_migrations\", \"user_group\",\n \"replication_execution\", \"replication_task\", \"replication_schedule_job\", \"oidc_user\";`,\n\t\t`DROP FUNCTION \"update_update_time_at_column\"();`,\n\t}\n\tdao.PrepareTestData(clearSqls, nil)\n\n\tos.Exit(code)\n}", "func TestEmptyCommit4A(t *testing.T) {\n}", "func testHeader(t *testing.T) {\n\tlogging.Info(fmt.Sprintf(\"=============== Starting test [%s] ===============\", t.Name()))\n}", "func TestTableTruncate(t *testing.T) {\n\tt.Run(\"Should succeed if table empty\", func(t *testing.T) {\n\t\ttb, cleanup := newTestTable(t)\n\t\tdefer cleanup()\n\n\t\terr := tb.Truncate()\n\t\tassert.NoError(t, err)\n\t})\n\n\tt.Run(\"Should truncate the table\", func(t *testing.T) {\n\t\ttb, cleanup := newTestTable(t)\n\t\tdefer cleanup()\n\n\t\t// create two documents\n\t\tdoc1 := newDocument()\n\t\tdoc2 := newDocument()\n\n\t\t_, err := tb.Insert(doc1)\n\t\tassert.NoError(t, err)\n\t\t_, err = tb.Insert(doc2)\n\t\tassert.NoError(t, err)\n\n\t\terr = tb.Truncate()\n\t\tassert.NoError(t, err)\n\n\t\terr = tb.Iterate(func(_ types.Document) error {\n\t\t\treturn errors.New(\"should not iterate\")\n\t\t})\n\n\t\tassert.NoError(t, err)\n\t})\n}", "func initTests() int {\n\trows, err := db.Query(\"SELECT idTEST, categories, conditions, params, period, scoreMap, custORacct FROM TXTEST\")\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t// defer rows.Close()\n\ti := 0\n\tfor rows.Next() {\n\t\ttest := new(TxTest)\n\t\terr := rows.Scan(&test.TName, &test.CategoryStr, &test.Conditions, &test.ParamStr, &test.PeriodStr, &test.ScoreMapStr, &test.CustOrAcct)\n\t\tif err != nil {\n\t\t\trows.Close()\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\ttest.Params, test.QueryType = parseParams(strings.Split(test.ParamStr, \",\"), test.CustOrAcct)\n\t\ttest.Period = *parsePeriod(test.PeriodStr)\n\t\ttest.ScoreMap = parseScoreMap(test.ScoreMapStr)\n\n\t\ttxTestCache[test.TName] = test\n\t\ti++\n\t\tfmt.Printf(\"\\ntest %s: %+v\", txTestCache[test.TName].TName, txTestCache[test.TName])\n\t}\n\trows.Close()\n\t//\treturn custs, err\n\treturn i\n}", "func verifyTables(\n\tt *testing.T,\n\ttc *testcluster.TestCluster,\n\tcompleted chan int,\n\texpectedNumOfTables int,\n\tdescIDStart int64,\n) {\n\tdescIDEnd := descIDStart + int64(expectedNumOfTables)\n\tusedTableIDs := make(map[sqlbase.ID]string)\n\tvar count int\n\tfor id := range completed {\n\t\tcount++\n\t\ttableName := fmt.Sprintf(\"table_%d\", id)\n\t\tkvDB := tc.Servers[count%tc.NumServers()].KVClient().(*client.DB)\n\t\ttableDesc := sqlbase.GetTableDescriptor(kvDB, \"test\", tableName)\n\t\tif int64(tableDesc.ID) < descIDStart || int64(tableDesc.ID) >= descIDEnd {\n\t\t\tt.Fatalf(\n\t\t\t\t\"table %s's ID %d is not within the expected range of %d to %d\",\n\t\t\t\ttableName,\n\t\t\t\ttableDesc.ID,\n\t\t\t\tdescIDStart,\n\t\t\t\tdescIDEnd,\n\t\t\t)\n\t\t}\n\t\tusedTableIDs[tableDesc.ID] = tableName\n\t}\n\n\tif e, a := expectedNumOfTables, len(usedTableIDs); e != a {\n\t\tt.Fatalf(\"expected %d tables created, only got %d\", e, a)\n\t}\n\n\tkvDB := tc.Servers[count%tc.NumServers()].KVClient().(*client.DB)\n\tif descID, err := kvDB.Get(context.Background(), keys.DescIDGenerator); err != nil {\n\t\tt.Fatal(err)\n\t} else {\n\t\tif e, a := descIDEnd, descID.ValueInt(); e != a {\n\t\t\tt.Fatalf(\"expected next descriptor ID to be %d, got %d\", e, a)\n\t\t}\n\t}\n}", "func Test_Basic(t *testing.T) {\n\ttt := TT{t}\n\n\ttt.ForeachDB(\"+nothing\", func(db *sql.DB) {\n\t\ttt.MustResult(db.Exec(`INSERT INTO knowledge VALUES (5, 'chaos')`)).RowsAffected()\n\n\t\taffected, err := tt.MustResult(db.Exec(`UPDATE knowledge SET thing = $1 WHERE number = $2`, \"douglas\", \"42\")).RowsAffected()\n\t\ttt.Must(err)\n\t\tif affected != 1 {\n\t\t\ttt.Unexpected(\"affected\", 1, affected)\n\t\t}\n\n\t\ttt.MustResult(db.Exec(`DELETE FROM knowledge WHERE thing = 'conspiracy'`))\n\n\t\trows := tt.MustRows(db.Query(`SELECT * FROM knowledge ORDER BY number`))\n\t\ttt.ExpectRow(rows, 5, \"chaos\")\n\t\ttt.ExpectRow(rows, 42, \"douglas\")\n\t\tif rows.Next() {\n\t\t\tt.Fatalf(\"unexpected continuation of result set\")\n\t\t}\n\t\ttt.Must(rows.Close())\n\t})\n\n\ttt.CleanupDB()\n}", "func TestSinglePrewrite4A(t *testing.T) {\n}", "func createTestTable(ctx context.Context, db *pgxpool.Pool, dbName, schemaSpec string) (tableInfo, error) {\n\tvar tableName string\n\nouter:\n\tfor {\n\t\t// Create the testing database\n\t\ttableNum := r.Intn(10000)\n\t\ttableName = fmt.Sprintf(\"_test_table_%d\", tableNum)\n\n\t\t// Find the DB.\n\t\tvar actualTableName string\n\t\terr := Retry(ctx, func(ctx context.Context) error {\n\t\t\treturn db.QueryRow(ctx,\n\t\t\t\tfmt.Sprintf(\"SELECT table_name FROM [SHOW TABLES FROM %s] WHERE table_name = $1\", dbName),\n\t\t\t\ttableName,\n\t\t\t).Scan(&actualTableName)\n\t\t})\n\t\tswitch err {\n\t\tcase pgx.ErrNoRows:\n\t\t\tbreak outer\n\t\tcase nil:\n\t\t\tcontinue\n\t\tdefault:\n\t\t\treturn tableInfo{}, err\n\t\t}\n\t}\n\n\tif err := Execute(ctx, db, fmt.Sprintf(schemaSpec, dbName, tableName)); err != nil {\n\t\treturn tableInfo{}, err\n\t}\n\n\treturn tableInfo{\n\t\tdb: db,\n\t\tdbName: dbName,\n\t\tname: tableName,\n\t}, nil\n}", "func doCHARableTest(t *testing.T, out io.Writer, f decoder.New, endianness bool, teTa decoder.TestTable) {\n\t//var (\n\t//\t// til is the trace id list content for test\n\t//\tidl = ``\n\t//)\n\t//lu := make(id.TriceIDLookUp) // empty\n\t//luM := new(sync.RWMutex)\n\t//assert.Nil(t, ilu.FromJSON([]byte(idl)))\n\t//lu.AddFmtCount(os.Stdout)\n\tbuf := make([]byte, decoder.DefaultSize)\n\tdec := f(out, nil, nil, nil, nil, endianness) // a new decoder instance\n\tfor _, x := range teTa {\n\t\tin := ioutil.NopCloser(bytes.NewBuffer(x.In))\n\t\tdec.SetInput(in)\n\t\tlineStart := true\n\t\tvar err error\n\t\tvar n int\n\t\tvar act string\n\t\tfor err == nil {\n\t\t\tn, err = dec.Read(buf)\n\t\t\tif n == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif decoder.ShowID != \"\" && lineStart {\n\t\t\t\tact += fmt.Sprintf(decoder.ShowID, decoder.LastTriceID)\n\t\t\t}\n\t\t\tact += fmt.Sprint(string(buf[:n]))\n\t\t\tlineStart = false\n\t\t}\n\t\tact = strings.TrimSuffix(act, \"\\\\n\")\n\t\tact = strings.TrimSuffix(act, \"\\n\")\n\t\tassert.Equal(t, x.Exp, act)\n\t}\n}", "func testFooter(t *testing.T) {\n\tlogging.Info(fmt.Sprintf(\"=============== Ending test [%s] ===============\", t.Name()))\n}", "func TestTestdataAll(t *testing.T) {\n\tout := new(bytes.Buffer)\n\terr := listPath(out, \"testdata\", true, false, true)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error:%s\", err)\n\t}\n\tresult := out.String()\n\tif result != resultTestdataAll {\n\t\tt.Errorf(\"bad result\\nexpected:\\n%v\\ngot:\\n%v\\n\", result, resultTestdataAll)\n\t}\n}", "func (h *HandlersApp01sqVendor) TableLoadTestData(w http.ResponseWriter, r *http.Request) {\n\tvar err error\n\tvar rcd App01sqVendor.App01sqVendor\n\n\tlog.Printf(\"hndlrVendor.TableLoadTestData(%s)\\n\", r.Method)\n\n\tif r.Method != \"GET\" {\n\t\thttp.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\t// Create the table.\n\terr = h.db.TableCreate()\n\tif err == nil {\n\t\tw.Write([]byte(\"Table was created\\n\"))\n\t} else {\n\t\tw.Write([]byte(\"Table creation had an error of:\" + util.ErrorString(err)))\n\t}\n\n\t// Load the test rows.\n\t// Now add some records.\n\tfor i := 0; i < 26; i++ {\n\t\tchr := 'A' + i\n\t\trcd.TestData(i)\n\t\terr = h.db.RowInsert(&rcd)\n\t\tif err == nil {\n\t\t\tstr := fmt.Sprintf(\"Added row: %c\\n\", chr)\n\t\t\tw.Write([]byte(str))\n\t\t} else {\n\t\t\tstr := fmt.Sprintf(\"Table creation had an error of: %c\\n\", chr)\n\t\t\tw.Write([]byte(str))\n\t\t}\n\t}\n\n\tlog.Printf(\"...end hndlrVendor.TableLoadTestData(%s)\\n\", util.ErrorString(err))\n\n}", "func (suite *SuiteTester) SetupTest() {\n r.Table(\"users\").Delete().RunWrite(session)\n user_fixtures := make([]User, 4)\n user_fixtures[0] = User{\n FirstName: \"Tyrion\",\n LastName: \"Lannister\",\n Email: \"[email protected]\",\n Bio: \"Younger brother to Cersei and Jaime.\",\n FacebookId: \"0b8a2b98-f2c5-457a-adc0-34d10a6f3b5c\",\n CreatedAt: time.Date(2008, time.June, 13, 18, 30, 10, 0, time.UTC),\n UpdatedAt: time.Date(2014, time.October, 5, 18, 30, 10, 0, time.UTC),\n }\n user_fixtures[1] = User{\n FirstName: \"Tywin\",\n LastName: \"Lannister\",\n Email: \"[email protected]\",\n Bio: \"Lord of Casterly Rock, Shield of Lannisport and Warden of the West.\",\n FacebookId: \"bb2d8a7b-92e6-4baf-b4f7-b664bdeee25b\",\n CreatedAt: time.Date(1980, time.July, 14, 18, 30, 10, 0, time.UTC),\n UpdatedAt: time.Date(2014, time.October, 6, 18, 30, 10, 0, time.UTC),\n }\n user_fixtures[2] = User{\n FirstName: \"Jaime\",\n LastName: \"Lannister\",\n Email: \"[email protected]\",\n Bio: \"Nicknamed 'Kingslayer' for killing the previous King, Aerys II.\",\n FacebookId: \"d4c19866-eaff-4417-a1c1-93882162606d\",\n CreatedAt: time.Date(2000, time.September, 15, 18, 30, 10, 0, time.UTC),\n UpdatedAt: time.Date(2014, time.October, 7, 18, 30, 10, 0, time.UTC),\n }\n user_fixtures[3] = User{\n FirstName: \"Cersei\",\n LastName: \"Lannister\",\n Email: \"[email protected]\",\n Bio: \"Queen of the Seven Kingdoms of Westeros, is the wife of King Robert Baratheon.\",\n FacebookId: \"251d74d8-7462-4f2a-b132-6f7e429507e5\",\n CreatedAt: time.Date(2002, time.May, 12, 18, 30, 10, 0, time.UTC),\n UpdatedAt: time.Date(2014, time.October, 8, 18, 30, 10, 0, time.UTC),\n }\n\n r.Table(\"users\").Insert(user_fixtures).RunWrite(session)\n}", "func aroundNegativeTest(t *testing.T) {\n\n\tresult := newFooter(1, 15, 0, 1).List\n\texpected := []string{}\n\tfor i := 0; i < len(expected); i++ {\n\t\tif result[i] != expected[i] {\n\t\t\tt.Error()\n\t\t}\n\t}\n\n}", "func (suite *EventStoreTestSuite) TearDownTest() {\n\tassert.Nil(suite.T(), suite.store.DeleteTable(context.Background()), \"could not delete table\")\n\tassert.Nil(suite.T(), suite.store.DeleteTable(suite.ctx), \"could not delete table\")\n}", "func (suite *MetricsTestSuite) SetupTest() {\n\tsuite.db.Unscoped().Delete(new(ResponseTime))\n\n\t// Delete sub tables\n\tvar subTables []*SubTable\n\tif err := suite.db.Order(\"id\").Find(&subTables).Error; err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor _, subTable := range subTables {\n\t\tif err := suite.db.DropTable(subTable.Name).Error; err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\tsuite.db.Unscoped().Delete(new(SubTable))\n\n\t// Reset mocks\n\tsuite.oauthServiceMock.ExpectedCalls = suite.oauthServiceMock.ExpectedCalls[:0]\n\tsuite.oauthServiceMock.Calls = suite.oauthServiceMock.Calls[:0]\n\tsuite.accountsServiceMock.ExpectedCalls = suite.accountsServiceMock.ExpectedCalls[:0]\n\tsuite.accountsServiceMock.Calls = suite.accountsServiceMock.Calls[:0]\n}", "func TestMyRowIndexResults(t *testing.T) {\n\toptions := &Options{\n\t\tHasHeader: false,\n\t\tRecordDelimiter: \"\\n\",\n\t\tFieldDelimiter: \",\",\n\t\tComments: \"\",\n\t\tName: \"S3Object\", // Default table name for all objects\n\t\tReadFrom: bytes.NewReader([]byte(\"Here , is, a, string + \\n + random,random,stuff,stuff \")),\n\t\tCompressed: \"\",\n\t\tExpression: \"\",\n\t\tOutputFieldDelimiter: \",\",\n\t\tStreamSize: 20,\n\t}\n\ts3s, err := NewInput(options)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\ttables := []struct {\n\t\tmyReq []string\n\t\tmyHeaders map[string]int\n\t\tmyDup map[string]bool\n\t\tmyLow map[string]int\n\t\tmyOpts *Options\n\t\tinput *Input\n\t\tmyRecord []string\n\t\tmyTarget string\n\t\tmyAsterix string\n\t\tcolumns []string\n\t\terr error\n\t}{\n\t\t{[]string{\"1\", \"2\"}, make(map[string]int), make(map[string]bool), make(map[string]int), options, s3s, []string{\"target\", \"random\", \"hello\", \"stuff\"}, \"target,random\", \"target,random,hello,stuff\", []string{\"1\", \"2\", \"3\", \"4\"}, nil},\n\t\t{[]string{\"2\", \"3\", \"4\"}, make(map[string]int), make(map[string]bool), make(map[string]int), options, s3s, []string{\"random\", \"hullo\", \"thing\", \"stuff\"}, \"hullo,thing,stuff\", \"random,hullo,thing,stuff\", []string{\"1\", \"2\", \"3\", \"4\"}, nil},\n\t\t{[]string{\"3\", \"2\"}, make(map[string]int), make(map[string]bool), make(map[string]int), options, s3s, []string{\"random\", \"hullo\", \"thing\", \"stuff\"}, \"thing,hullo\", \"random,hullo,thing,stuff\", []string{\"1\", \"2\", \"3\", \"4\"}, nil},\n\t\t{[]string{\"11\", \"1\"}, make(map[string]int), make(map[string]bool), make(map[string]int), options, s3s, []string{\"random\", \"hullo\", \"thing\", \"stuff\"}, \"\", \"random,hullo,thing,stuff\", []string{\"1\", \"2\", \"3\", \"4\"}, ErrInvalidColumnIndex},\n\t}\n\tfor _, table := range tables {\n\t\tcheckForDuplicates(table.columns, table.myHeaders, table.myDup, table.myLow)\n\t\tmyRow, err := s3s.processColNameIndex(table.myRecord, table.myReq, table.columns)\n\t\tif err != table.err {\n\t\t\tt.Error()\n\t\t}\n\t\tif myRow != table.myTarget {\n\t\t\tt.Error()\n\t\t}\n\t\tmyRow = table.input.printAsterix(table.myRecord)\n\t\tif myRow != table.myAsterix {\n\t\t\tt.Error()\n\t\t}\n\t}\n}", "func DropTestTable(db *sql.DB, tableSQLs []string) {\n\tfor i := range tableSQLs {\n\t\ttable := newTable()\n\t\terr := parseTableSQL(table, tableSQLs[i])\n\t\tif err != nil {\n\t\t\tlog.S().Fatal(err)\n\t\t}\n\n\t\terr = execSQL(db, fmt.Sprintf(\"drop table %s\", table.name))\n\t\tif err != nil {\n\t\t\tlog.S().Fatal(err)\n\t\t}\n\t}\n}", "func TestMain(m *testing.M) {\n\tcode := test.TestMain(m, func(svc *dynamodb.Client) error { // this function setups the database\n\t\t// create testing table\n\t\tcreateRequest := svc.CreateTableRequest(&dynamodb.CreateTableInput{\n\t\t\tAttributeDefinitions: []dynamodb.AttributeDefinition{\n\t\t\t\t{\n\t\t\t\t\tAttributeName: aws.String(\"PK\"),\n\t\t\t\t\tAttributeType: \"S\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tKeySchema: []dynamodb.KeySchemaElement{\n\t\t\t\t{\n\t\t\t\t\tAttributeName: aws.String(\"PK\"),\n\t\t\t\t\tKeyType: dynamodb.KeyTypeHash,\n\t\t\t\t},\n\t\t\t},\n\t\t\tProvisionedThroughput: &dynamodb.ProvisionedThroughput{\n\t\t\t\tReadCapacityUnits: aws.Int64(1),\n\t\t\t\tWriteCapacityUnits: aws.Int64(1),\n\t\t\t},\n\t\t\tTableName: aws.String(table),\n\t\t})\n\t\t_, err := createRequest.Send(context.Background())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// add testing data\n\t\trequest := svc.PutItemRequest(&dynamodb.PutItemInput{\n\t\t\tItem: map[string]dynamodb.AttributeValue{\n\t\t\t\t\"PK\": {S: aws.String(\"abc123\")},\n\t\t\t\t\"name\": {S: aws.String(\"John\")},\n\t\t\t},\n\t\t\tTableName: aws.String(table),\n\t\t})\n\t\t_, err = request.Send(context.Background())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\tos.Exit(code)\n}", "func TestTableCreation(t *testing.T) {\n\tcommon.InitConfig()\n\n\tdb := GetInstance()\n\n\t// A map of table name to creation function,\n\t// as in database.go\n\tvar tableMap = map[string]func() error{\n\t\tpaymentsTable: db.createPaymentsTable,\n\t}\n\n\t// Loop through our creation funcs, execute and test\n\tfor _, createFunc := range tableMap {\n\t\terr := createFunc()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n}", "func LoadSenUserTable_NOTUSED(dbRef *pg.DB) {\r\n\tlog.Println(\"===>sensorRelation.LoadSenUserTable()\")\r\n\tvar testCase = 0\r\n\tif testCase == 1 {\r\n\t\tCreateSenUserTest_NOTUSED(dbRef, 1, 1)\r\n\t} else if testCase == 2 {\r\n\t\t//GetAllSensors(dbRef)\r\n\t} else if testCase == 3 {\r\n\t} else if testCase == 4 {\r\n\t}\r\n}", "func runTests(c *C, overrider configOverrider, tests ...func(dbt *DBTest)) {\n\tdb, err := sql.Open(\"mysql\", getDSN(overrider))\n\tc.Assert(err, IsNil, Commentf(\"Error connecting\"))\n\tdefer db.Close()\n\n\tdb.Exec(\"DROP TABLE IF EXISTS test\")\n\n\tdbt := &DBTest{c, db}\n\tfor _, test := range tests {\n\t\ttest(dbt)\n\t\tdbt.db.Exec(\"DROP TABLE IF EXISTS test\")\n\t}\n}", "func makeDataForTileTests() schema.Tables {\n\tb := databuilder.TablesBuilder{TileWidth: 4}\n\tb.CommitsWithData().\n\t\tInsert(\"0000000098\", \"user\", \"commit 98, expected tile 0\", \"2020-12-01T00:00:00Z\").\n\t\tInsert(\"0000000099\", \"user\", \"commit 99, expected tile 0\", \"2020-12-02T00:00:00Z\").\n\t\tInsert(\"0000000100\", \"user\", \"commit 100, expected tile 0\", \"2020-12-03T00:00:00Z\").\n\t\tInsert(\"0000000101\", \"user\", \"commit 101, expected tile 0\", \"2020-12-04T00:00:00Z\").\n\t\tInsert(\"0000000103\", \"user\", \"commit 103, expected tile 1\", \"2020-12-05T00:00:00Z\").\n\t\tInsert(\"0000000106\", \"user\", \"commit 106, expected tile 1\", \"2020-12-07T00:00:00Z\").\n\t\tInsert(\"0000000107\", \"user\", \"commit 107, expected tile 1\", \"2020-12-08T00:00:00Z\").\n\t\tInsert(\"0000000108\", \"user\", \"commit 108, expected tile 1\", \"2020-12-09T00:00:00Z\")\n\tb.CommitsWithNoData().\n\t\tInsert(\"0000000102\", \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\", \"user\", \"commit 102, expected tile 1\", \"2020-12-05T00:00:00Z\").\n\t\tInsert(\"0000000105\", \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\", \"user\", \"commit 105, expected tile 1\", \"2020-12-05T00:00:00Z\").\n\t\tInsert(\"0000000109\", \"cccccccccccccccccccccccccccccccccccccccc\", \"user\", \"commit 109, expected tile 2\", \"2020-12-05T00:00:00Z\")\n\tb.SetDigests(map[rune]types.Digest{\n\t\t'B': dks.DigestA02Pos,\n\t\t'C': dks.DigestA03Pos,\n\t})\n\tb.SetGroupingKeys(types.CorpusField, types.PrimaryKeyField)\n\tb.AddTracesWithCommonKeys(paramtools.Params{\n\t\ttypes.CorpusField: dks.CornersCorpus,\n\t\ttypes.PrimaryKeyField: dks.SquareTest,\n\t}).History(\n\t\t\"BBBBCBCB\",\n\t\t\"CCCCCCCC\",\n\t).Keys([]paramtools.Params{\n\t\t{dks.OSKey: dks.AndroidOS},\n\t\t{dks.OSKey: dks.Windows10dot3OS},\n\t}).OptionsAll(paramtools.Params{\"ext\": \"png\"}).\n\t\tIngestedFrom(repeat(\"dontcare\", 8), repeat(\"2020-12-01T00:42:00Z\", 8))\n\texistingData := b.Build()\n\treturn existingData\n}", "func TestMain(t *testing.M) {\n\tres := t.Run()\n\tmock.DropTables(db)\n\tos.Exit(res)\n}", "func Run(sourceDB *sql.DB, targetDB *sql.DB, schema string, workerCount int, jobCount int, batch int) {\n\n\tTableSQLs := []string{`\ncreate table ptest(\n\ta int primary key,\n\tb double NOT NULL DEFAULT 2.0,\n\tc varchar(10) NOT NULL,\n\td time unique\n);\n`,\n\t\t`\ncreate table itest(\n\ta int,\n\tb double NOT NULL DEFAULT 2.0,\n\tc varchar(10) NOT NULL,\n\td time unique,\n\tPRIMARY KEY(a, b)\n);\n`,\n\t\t`\ncreate table ntest(\n\ta int,\n\tb double NOT NULL DEFAULT 2.0,\n\tc varchar(10) NOT NULL,\n\td time unique\n);\n`}\n\n\t// run the simple test case\n\tRunCase(sourceDB, targetDB, schema)\n\n\tRunTest(sourceDB, targetDB, schema, func(src *sql.DB) {\n\t\t// generate insert/update/delete sqls and execute\n\t\tRunDailyTest(sourceDB, TableSQLs, workerCount, jobCount, batch)\n\t})\n\n\tRunTest(sourceDB, targetDB, schema, func(src *sql.DB) {\n\t\t// truncate test data\n\t\tTruncateTestTable(sourceDB, TableSQLs)\n\t})\n\n\tRunTest(sourceDB, targetDB, schema, func(src *sql.DB) {\n\t\t// drop test table\n\t\tDropTestTable(sourceDB, TableSQLs)\n\t})\n\n\tlog.S().Info(\"test pass!!!\")\n\n}", "func TestHelloSubTest(t *testing.T) {\n\t// 前処理etc\n\n\tt.Run(\"Hoge\", func(t *testing.T) {\n\t\ts := Hello(\"Hoge\")\n\t\twant := \"Hello, Hoge!\"\n\t\tif s != want {\n\t\t\tt.Fatalf(`Hello(\"Hoge\") = %s\"; want \"%s\"`, s, want)\n\t\t}\n\t})\n\tt.Run(\"Moke\", func(t *testing.T) {\n\t\t// さらにネストできる\n\t\tt.Run(\"Fuga\", func(t *testing.T) {\n\t\t\ts := Hello(\"Fuga\")\n\t\t\twant := \"Hello, Fuga!\"\n\t\t\tif s != want {\n\t\t\t\tt.Fatalf(`Hello(\"Fuga\") = %s\"; want \"%s\"`, s, want)\n\t\t\t}\n\t\t})\n\t})\n\n\t// 後処理etc\n}", "func TruncateTestTable(db *sql.DB, tableSQLs []string) {\n\tfor i := range tableSQLs {\n\t\ttable := newTable()\n\t\terr := parseTableSQL(table, tableSQLs[i])\n\t\tif err != nil {\n\t\t\tlog.S().Fatal(err)\n\t\t}\n\n\t\terr = execSQL(db, fmt.Sprintf(\"truncate table %s\", table.name))\n\t\tif err != nil {\n\t\t\tlog.S().Fatal(err)\n\t\t}\n\t}\n}", "func Test1IsATest(t *testing.T) {\n}", "func TestSingleCommit4A(t *testing.T) {\n}", "func TableData(\n\tctx context.Context, tableName string, executor sqlutil.InternalExecutor,\n) [][]string {\n\tif it, err := executor.QueryIterator(\n\t\tctx, \"test-select-\"+tableName, nil /* txn */, \"select * from \"+tableName,\n\t); err == nil {\n\t\tvar result [][]string\n\t\tvar ok bool\n\t\tfor ok, err = it.Next(ctx); ok; ok, err = it.Next(ctx) {\n\t\t\trow := it.Cur()\n\t\t\tstringRow := make([]string, 0, row.Len())\n\t\t\tfor _, item := range row {\n\t\t\t\tstringRow = append(stringRow, item.String())\n\t\t\t}\n\t\t\tresult = append(result, stringRow)\n\t\t}\n\t\tif err == nil {\n\t\t\treturn result\n\t\t}\n\t}\n\treturn nil\n}", "func MoreTest() {}", "func TestPrewriteWritten4A(t *testing.T) {\n}", "func TestComplexifyRandom(t *testing.T) {\n\n}", "func TestGetAllOrders(t *testing.T) {\n\n // ...\n\n}", "func TestMain(m *testing.M) {\n\tvar err error\n\ttestDB, err = sql.Open(\"mysql\", \"/test\")\n\tif err != nil {\n\t\tfmt.Printf(\"unable to connect to DB: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)\n\tdefer cancel()\n\n\t_, err = testDB.QueryContext(ctx, \"select * from kv limit 1\")\n\tif err != nil {\n\t\tif strings.Index(err.Error(), \"Error 1146\") > -1 {\n\t\t\t_, err := testDB.ExecContext(ctx, sqlTableKV)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"unable to create kv table: %v\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Printf(\"unable to query kv table: %v\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\t_, err = testDB.QueryContext(ctx, \"delete from kv\")\n\tif err != nil {\n\t\tfmt.Printf(\"unable to clean up kv table: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tos.Exit(m.Run())\n}", "func init() { //nolint\n\ttestSample := TestCase{\n\t\tName: \"should hide the progress bar in the CLI [E2E-CLI-009]\",\n\t\tArgs: args{\n\t\t\tArgs: []cmdArgs{\n\t\t\t\t[]string{\"scan\", \"-q\", \"../assets/queries\", \"-p\", \"fixtures/samples/terraform.tf\", \"--no-progress\"},\n\t\t\t},\n\t\t},\n\t\tWantStatus: []int{50},\n\t\tValidation: func(outputText string) bool {\n\t\t\tgetProgressRegex := \"Executing queries:\"\n\t\t\tmatch, _ := regexp.MatchString(getProgressRegex, outputText)\n\t\t\t// if not found -> the the test was successful\n\t\t\treturn !match\n\t\t},\n\t}\n\n\tTests = append(Tests, testSample)\n}", "func TestPart2(t *testing.T){\n\n\tfor _, test := range tests {\n\n\t\tpart2( test.input )\n\t}\n}", "func TestSIFTLib2(t *testing.T) { TestingT(t) }", "func TestSqlSMSStorage_GetSMSs(t *testing.T) {\n\n}", "func testDeleteSimple(tree T, insert, delete []interface{}, exact bool, errPrfx string, t *testing.T) {\n\tx, y := randomPosition(tree.View())\n\tfor _, e := range insert {\n\t\ttree.Insert(x, y, e)\n\t}\n\texpCol := new(list.List)\nOUTER_LOOP:\n\tfor _, i := range insert {\n\t\tfor _, d := range delete {\n\t\t\tif i == d {\n\t\t\t\tcontinue OUTER_LOOP\n\t\t\t}\n\t\t}\n\t\texpCol.PushBack(i)\n\t}\n\texpDel := new(list.List)\n\tfor _, d := range delete {\n\t\texpDel.PushBack(d)\n\t}\n\tpred, deleted := makeDelClosure(delete)\n\tdelView := tree.View()\n\tif exact {\n\t\tdelView = NewViewP(x, x, y, y)\n\t}\n\ttestDelete(tree, delView, pred, deleted, expDel, t, errPrfx)\n\tfun, collected := SimpleSurvey()\n\ttestSurvey(tree, tree.View(), fun, collected, expCol, t, errPrfx)\n}", "func renderTTTestFunction(tdh ttHolder) []byte {\n\tbuf := new(bytes.Buffer)\n\terr := ttTmpl.Execute(buf, tdh)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"rendering table test function : %v\", err))\n\t}\n\ttestContent, _ := ioutil.ReadAll(buf)\n\treturn testContent\n}", "func Test_Something(t *testing.T) {\n\t// test stuff here...\n\tSomething(t)\n}", "func SubtestAll(t *testing.T, tr mux.Multiplexer) {\n\ttmux.SubtestAll(t, tr)\n\n}", "func loadTableTestResults(filename string, srcData *mockstore.Snapshot) (resultsVerifier, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\ts := bufio.NewScanner(bufio.NewReader(f))\n\trow := 0\n\texp := ResultChunk{\n\t\tColumns: make(exec.Columns, 0, 4),\n\t}\n\tfor s.Scan() {\n\t\tline := strings.TrimSpace(s.Text())\n\t\trow++\n\t\tif len(line) == 0 || line[0] == '#' {\n\t\t\tcontinue\n\t\t}\n\t\tif len(exp.Columns) == 0 {\n\t\t\t// column headers. The Fields func splits the input on unicode.isSpace boundaries\n\t\t\tfor _, c := range strings.Fields(line) {\n\t\t\t\texp.Columns = append(exp.Columns, &plandef.Variable{Name: c})\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tcells := strings.Fields(line)\n\t\tif len(cells) != len(exp.Columns) {\n\t\t\treturn nil, fmt.Errorf(\"row %d has %d columns, but expecting %d\", row, len(cells), len(exp.Columns))\n\t\t}\n\t\tfor i, cell := range cells {\n\t\t\tparsed, err := parser.ParseTerm(cell)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"row %d column %d unable to parse '%s' into a valid term: %v\", row, i, cell, err)\n\t\t\t}\n\t\t\tval := exec.Value{}\n\n\t\t\tresolveUnitLanguageID := func(xid string) uint64 {\n\t\t\t\tif len(xid) > 0 {\n\t\t\t\t\treturn srcData.ResolveXID(xid)\n\t\t\t\t}\n\t\t\t\treturn uint64(0)\n\t\t\t}\n\t\t\tswitch t := parsed.(type) {\n\t\t\tcase *parser.Variable:\n\t\t\t\treturn nil, fmt.Errorf(\"row %d column %d unexpected variable %s found in results\", row, i, t)\n\t\t\tcase *parser.LiteralID:\n\t\t\t\treturn nil, fmt.Errorf(\"row %d column %d unexpected literal ID %s found in results\", row, i, t)\n\t\t\tcase *parser.LiteralBool:\n\t\t\t\tval.KGObject = rpc.ABool(t.Value, resolveUnitLanguageID(t.Unit.Value))\n\t\t\t\tif len(t.Unit.Value) > 0 {\n\t\t\t\t\tval.SetUnitExtID(t.Unit.Value)\n\t\t\t\t}\n\t\t\tcase *parser.LiteralFloat:\n\t\t\t\tval.KGObject = rpc.AFloat64(t.Value, resolveUnitLanguageID(t.Unit.Value))\n\t\t\t\tif len(t.Unit.Value) > 0 {\n\t\t\t\t\tval.SetUnitExtID(t.Unit.Value)\n\t\t\t\t}\n\t\t\tcase *parser.LiteralInt:\n\t\t\t\tval.KGObject = rpc.AInt64(t.Value, resolveUnitLanguageID(t.Unit.Value))\n\t\t\t\tif len(t.Unit.Value) > 0 {\n\t\t\t\t\tval.SetUnitExtID(t.Unit.Value)\n\t\t\t\t}\n\t\t\tcase *parser.LiteralTime:\n\t\t\t\tval.KGObject = rpc.ATimestamp(t.Value,\n\t\t\t\t\tlogentry.TimestampPrecision(t.Precision),\n\t\t\t\t\tresolveUnitLanguageID(t.Unit.Value))\n\t\t\t\tif len(t.Unit.Value) > 0 {\n\t\t\t\t\tval.SetUnitExtID(t.Unit.Value)\n\t\t\t\t}\n\t\t\tcase *parser.LiteralString:\n\t\t\t\tval.KGObject = rpc.AString(t.Value, resolveUnitLanguageID(t.Language.Value))\n\t\t\t\tval.SetLangExtID(t.Language.Value)\n\t\t\tcase *parser.QName:\n\t\t\t\tval.KGObject = rpc.AKID(srcData.ResolveXID(t.Value))\n\t\t\t\tval.ExtID = t.String()\n\t\t\tcase *parser.Entity:\n\t\t\t\tval.KGObject = rpc.AKID(srcData.ResolveXID(t.Value))\n\t\t\t\tval.ExtID = t.String()\n\t\t\tdefault:\n\t\t\t\treturn nil, fmt.Errorf(\"row %d column %d unexpected value type %T %s in results\", row, i, t, t)\n\t\t\t}\n\t\t\texp.Values = append(exp.Values, val)\n\t\t}\n\t}\n\tformat := func(r ResultChunk) []string {\n\t\tformatted := make([]string, r.NumRows()+1)\n\t\tformatted[0] = r.Columns.String()\n\t\tfor i := 0; i < r.NumRows(); i++ {\n\t\t\tformatted[i+1] = fmt.Sprintf(\"%v\", r.Row(i))\n\t\t}\n\t\treturn formatted\n\t}\n\tverify := func(t *testing.T, queryError error, actual ResultChunk) {\n\t\tassert.NoError(t, queryError)\n\t\tassert.Equal(t, format(exp), format(actual))\n\t}\n\treturn verify, nil\n}", "func testResult(t *testing.T) {\n\tdb.tearDown()\n\tdb.mustExec(\"create temporary table test (id \" + db.serialPK() + \", name varchar(10))\")\n\n\tfor i := 1; i < 3; i++ {\n\t\tr := db.mustExec(db.q(\"insert into test (name) values (?)\"), fmt.Sprintf(\"row %d\", i))\n\t\tn, err := r.RowsAffected()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif n != 1 {\n\t\t\tt.Errorf(\"got %v, want %v\", n, 1)\n\t\t}\n\t\tn, err = r.LastInsertId()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif n != int64(i) {\n\t\t\tt.Errorf(\"got %v, want %v\", n, i)\n\t\t}\n\t}\n\tif _, err := db.Exec(\"error!\"); err == nil {\n\t\tt.Fatalf(\"expected error\")\n\t}\n}", "func TestCBOWithoutAnalyze(t *testing.T) {\n\tstore, dom := testkit.CreateMockStoreAndDomain(t)\n\ttestKit := testkit.NewTestKit(t, store)\n\ttestKit.MustExec(\"use test\")\n\ttestKit.MustExec(\"create table t1 (a int)\")\n\ttestKit.MustExec(\"create table t2 (a int)\")\n\th := dom.StatsHandle()\n\trequire.NoError(t, h.HandleDDLEvent(<-h.DDLEventCh()))\n\trequire.NoError(t, h.HandleDDLEvent(<-h.DDLEventCh()))\n\ttestKit.MustExec(\"insert into t1 values (1), (2), (3), (4), (5), (6)\")\n\ttestKit.MustExec(\"insert into t2 values (1), (2), (3), (4), (5), (6)\")\n\trequire.NoError(t, h.DumpStatsDeltaToKV(handle.DumpAll))\n\trequire.NoError(t, h.Update(dom.InfoSchema()))\n\tvar input []string\n\tvar output []struct {\n\t\tSQL string\n\t\tPlan []string\n\t}\n\tanalyzeSuiteData := GetAnalyzeSuiteData()\n\tanalyzeSuiteData.LoadTestCases(t, &input, &output)\n\tfor i, sql := range input {\n\t\tplan := testKit.MustQuery(sql)\n\t\ttestdata.OnRecord(func() {\n\t\t\toutput[i].SQL = sql\n\t\t\toutput[i].Plan = testdata.ConvertRowsToStrings(plan.Rows())\n\t\t})\n\t\tplan.Check(testkit.Rows(output[i].Plan...))\n\t}\n}", "func TestMyHelperFunctions(t *testing.T) {\n\ttables := []struct {\n\t\tmyReq string\n\t\tmyList []string\n\t\tmyIndex int\n\t\texpected bool\n\t}{\n\t\t{\"test1\", []string{\"test1\", \"test2\", \"test3\", \"test4\", \"test5\"}, 0, true},\n\t\t{\"random\", []string{\"test1\", \"test2\", \"test3\", \"test4\", \"test5\"}, -1, false},\n\t\t{\"test3\", []string{\"test1\", \"test2\", \"test3\", \"test4\", \"test5\"}, 2, true},\n\t}\n\tfor _, table := range tables {\n\t\tif stringInSlice(table.myReq, table.myList) != table.expected {\n\t\t\tt.Error()\n\t\t}\n\t\tif stringIndex(table.myReq, table.myList) != table.myIndex {\n\t\t\tt.Error()\n\t\t}\n\t}\n}", "func Run(\n\tdao DAO,\n\tstatements, setupStatements, teardownStatements, solutions []Statement,\n\tselectedQuestions []string,\n) ([]TestResult, error) {\n\tvar testResult = []TestResult{}\n\n\ti := 0\n\tresults, errs, err := dao.ExecuteStatements(setupStatements, teardownStatements, statements)\n\tsolutionResults, _, err := dao.ExecuteStatements(setupStatements, teardownStatements, solutions)\n\ttestcases := ConvertTablesToTestCases(solutionResults)\n\n\tif err != nil {\n\t\treturn testResult, err\n\t}\n\n\tfor _, expected := range testcases {\n\t\tif !stringInSlice(expected.Index, selectedQuestions) && len(selectedQuestions) > 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif i >= len(results) {\n\t\t\ttestResult = append(\n\t\t\t\ttestResult,\n\t\t\t\tTestResult{\n\t\t\t\t\tExpected: expected,\n\t\t\t\t\tActual: Result{},\n\t\t\t\t\tPass: false,\n\t\t\t\t},\n\t\t\t)\n\t\t\ti++\n\t\t\tcontinue\n\t\t}\n\t\ttable := results[i]\n\t\terr := errs[i]\n\t\t// Query has syntax error\n\t\tif err != nil {\n\t\t\ttestResult = append(\n\t\t\t\ttestResult,\n\t\t\t\tTestResult{\n\t\t\t\t\tExpected: expected,\n\t\t\t\t\tActual: table,\n\t\t\t\t\tPass: false,\n\t\t\t\t\tError: err,\n\t\t\t\t},\n\t\t\t)\n\t\t\ti++\n\t\t\tcontinue\n\t\t}\n\t\tif !reflect.DeepEqual(table.Content, expected.Content) {\n\t\t\ttestResult = append(\n\t\t\t\ttestResult,\n\t\t\t\tTestResult{\n\t\t\t\t\tExpected: expected,\n\t\t\t\t\tActual: table,\n\t\t\t\t\tPass: false,\n\t\t\t\t},\n\t\t\t)\n\t\t} else {\n\t\t\ttestResult = append(\n\t\t\t\ttestResult,\n\t\t\t\tTestResult{\n\t\t\t\t\tExpected: expected,\n\t\t\t\t\tActual: table,\n\t\t\t\t\tPass: true,\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\ti++\n\t}\n\n\treturn testResult, nil\n}", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }" ]
[ "0.62746644", "0.61851776", "0.6095943", "0.58346945", "0.5810767", "0.5754181", "0.57068765", "0.56937987", "0.56519985", "0.5645815", "0.56432045", "0.5606986", "0.5601892", "0.5591612", "0.5587944", "0.5582124", "0.55760455", "0.5574959", "0.55607486", "0.5556562", "0.55428976", "0.5504102", "0.54782236", "0.5435696", "0.54351133", "0.5428735", "0.54192615", "0.541705", "0.5393195", "0.5383889", "0.53561234", "0.5348072", "0.5347158", "0.534402", "0.5341841", "0.53393793", "0.5317287", "0.53164524", "0.5309072", "0.5302176", "0.5298732", "0.529669", "0.5278294", "0.527588", "0.52723485", "0.526088", "0.5245194", "0.5238601", "0.52372015", "0.5232022", "0.52266264", "0.52246356", "0.5220156", "0.5209274", "0.5203496", "0.5201424", "0.52000856", "0.5196614", "0.5191476", "0.5189111", "0.51702243", "0.51440006", "0.51439565", "0.51413447", "0.5139298", "0.51288754", "0.512459", "0.5115716", "0.5102188", "0.50947046", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215", "0.50909215" ]
0.0
-1
SUB TEST OMIT SUB BENCHMARK START
func BenchmarkSubFibonacci(b *testing.B) { var tests = []struct { input, result int }{ {input: 2, result: 1}, {input: 8, result: 21}, {input: 10, result: 55}, } for _, test := range tests { b.Run(fmt.Sprintf("BFibonacci(%d)", test.input), func(b *testing.B) { for i := 0; i < b.N; i++ { testingFunc(b, test.input, test.result) } }) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TestHelloSubTest(t *testing.T) {\n\t// 前処理etc\n\n\tt.Run(\"Hoge\", func(t *testing.T) {\n\t\ts := Hello(\"Hoge\")\n\t\twant := \"Hello, Hoge!\"\n\t\tif s != want {\n\t\t\tt.Fatalf(`Hello(\"Hoge\") = %s\"; want \"%s\"`, s, want)\n\t\t}\n\t})\n\tt.Run(\"Moke\", func(t *testing.T) {\n\t\t// さらにネストできる\n\t\tt.Run(\"Fuga\", func(t *testing.T) {\n\t\t\ts := Hello(\"Fuga\")\n\t\t\twant := \"Hello, Fuga!\"\n\t\t\tif s != want {\n\t\t\t\tt.Fatalf(`Hello(\"Fuga\") = %s\"; want \"%s\"`, s, want)\n\t\t\t}\n\t\t})\n\t})\n\n\t// 後処理etc\n}", "func TESTB(ir, amr operand.Op) { ctx.TESTB(ir, amr) }", "func TestSub(t *testing.T) {\n\tfmt.Println(Sub(2,1))\n}", "func init() { //nolint\n\ttestSample := TestCase{\n\t\tName: \"should exclude provided queries [E2E-CLI-020]\",\n\t\tArgs: args{\n\t\t\tArgs: []cmdArgs{\n\t\t\t\t[]string{\"scan\", \"--exclude-queries\", \"15ffbacc-fa42-4f6f-a57d-2feac7365caa,0a494a6a-ebe2-48a0-9d77-cf9d5125e1b3\", \"-s\",\n\t\t\t\t\t\"-q\", \"../assets/queries\", \"-p\", \"fixtures/samples/terraform-single.tf\"},\n\t\t\t},\n\t\t},\n\t\tWantStatus: []int{20},\n\t}\n\n\tTests = append(Tests, testSample)\n}", "func TestEmptyPrewrite4A(t *testing.T) {\n}", "func main() {\n\ttest1()\n\tfmt.Println(\"-----------------------------------\")\n\ttest2()\n\tfmt.Println(\"-----------------------------------\")\n\ttest3()\n}", "func TestBBIExpandsWithoutPrefix(tt *testing.T) {\n\t//\tlines :=`DEBU[0000] expanded models: [240/001.mod 240/002.mod 240/003.mod 240/004.mod 240/005.mod 240/006.mod 240/007.mod 240/008.mod 240/009.mod]\n\t// INFO[0000] A total of 9 models have completed the initial preparation phase`\n\tt := wrapt.WrapT(tt)\n\n\tScenario := InitializeScenarios([]string{\n\t\t\"bbi_expansion\",\n\t})[0]\n\n\tScenario.Prepare(context.Background())\n\n\ttargets := `10[1:5].ctl`\n\n\tcommandAndArgs := []string{\n\t\t\"-d\", // Needs to be in debug mode to generate the expected output\n\t\t\"--threads\",\n\t\t\"2\",\n\t\t\"nonmem\",\n\t\t\"run\",\n\t\t\"local\",\n\t\t\"--nm_version\",\n\t\tos.Getenv(\"NMVERSION\"),\n\t\tfilepath.Join(Scenario.Workpath, \"model\", targets),\n\t}\n\n\toutput, err := executeCommand(context.Background(), \"bbi\", commandAndArgs...)\n\n\tt.R.NoError(err)\n\tt.R.NotEmpty(output)\n\n\tmodelsLine, _ := findOutputLine(strings.Split(output, \"\\n\"))\n\tmodelsLine = strings.TrimSuffix(modelsLine, \"\\n\")\n\texpandedModels := outputLineToModels(modelsLine)\n\n\t// Verify that we expanded to five models\n\tt.R.Len(expandedModels, 5)\n\n\t// Verify nonmem completed for all five\n\tfor _, m := range expandedModels {\n\t\tfile := filepath.Base(m)\n\t\textension := filepath.Ext(file)\n\t\tidentifier := strings.Replace(file, extension, \"\", 1)\n\t\toutputDir := filepath.Join(Scenario.Workpath, \"model\", identifier)\n\n\t\tinternalModel := Model{\n\t\t\tidentifier: identifier,\n\t\t\tfilename: file,\n\t\t\textension: extension,\n\t\t\tpath: outputDir,\n\t\t}\n\n\t\tnmd := NonMemTestingDetails{\n\t\t\tOutputDir: internalModel.path,\n\t\t\tModel: internalModel,\n\t\t\tOutput: output,\n\t\t\tScenario: Scenario,\n\t\t}\n\n\t\tAssertNonMemCompleted(t, nmd)\n\t\tAssertNonMemCreatedOutputFiles(t, nmd)\n\t}\n}", "func SubtestAll(t *testing.T, tr mux.Multiplexer) {\n\ttmux.SubtestAll(t, tr)\n\n}", "func TestBBIExpandsWithPrefixToPartialMatch(tt *testing.T) {\n\t//\tlines :=`DEBU[0000] expanded models: [240/001.mod 240/002.mod 240/003.mod 240/004.mod 240/005.mod 240/006.mod 240/007.mod 240/008.mod 240/009.mod]\n\t// INFO[0000] A total of 9 models have completed the initial preparation phase`\n\tt := wrapt.WrapT(tt)\n\n\tScenario := InitializeScenarios([]string{\n\t\t\"bbi_expansion\",\n\t})[0]\n\n\tScenario.Prepare(context.Background())\n\n\ttargets := `bbi_mainrun_10[2:3].ctl`\n\n\tcommandAndArgs := []string{\n\t\t\"-d\", // Needs to be in debug mode to generate the expected output\n\t\t\"--threads\",\n\t\t\"2\",\n\t\t\"nonmem\",\n\t\t\"run\",\n\t\t\"local\",\n\t\t\"--nm_version\",\n\t\tos.Getenv(\"NMVERSION\"),\n\t\tfilepath.Join(Scenario.Workpath, \"model\", targets),\n\t}\n\n\toutput, err := executeCommand(context.Background(), \"bbi\", commandAndArgs...)\n\n\tt.R.NoError(err)\n\tt.R.NotEmpty(output)\n\n\tmodelsLine, _ := findOutputLine(strings.Split(output, \"\\n\"))\n\tmodelsLine = strings.TrimSuffix(modelsLine, \"\\n\")\n\texpandedModels := outputLineToModels(modelsLine)\n\n\t// Verify that we expanded to three models\n\tt.R.Len(expandedModels, 2)\n\n\t// Verify nonmem completed for all five\n\tfor _, m := range expandedModels {\n\t\tfile := filepath.Base(m)\n\t\textension := filepath.Ext(file)\n\t\tidentifier := strings.Replace(file, extension, \"\", 1)\n\t\toutputDir := filepath.Join(Scenario.Workpath, \"model\", identifier)\n\n\t\tinternalModel := Model{\n\t\t\tidentifier: identifier,\n\t\t\tfilename: file,\n\t\t\textension: extension,\n\t\t\tpath: outputDir,\n\t\t}\n\n\t\tnmd := NonMemTestingDetails{\n\t\t\tOutputDir: internalModel.path,\n\t\t\tModel: internalModel,\n\t\t\tOutput: output,\n\t\t}\n\n\t\tAssertNonMemCompleted(t, nmd)\n\t\tAssertNonMemCreatedOutputFiles(t, nmd)\n\t}\n}", "func TestPart2(t *testing.T){\n\n\tfor _, test := range tests {\n\n\t\tpart2( test.input )\n\t}\n}", "func TestBBIExpandsWithPrefix(tt *testing.T) {\n\t//\tlines :=`DEBU[0000] expanded models: [240/001.mod 240/002.mod 240/003.mod 240/004.mod 240/005.mod 240/006.mod 240/007.mod 240/008.mod 240/009.mod]\n\t// INFO[0000] A total of 9 models have completed the initial preparation phase`\n\tt := wrapt.WrapT(tt)\n\n\tScenario := InitializeScenarios([]string{\n\t\t\"bbi_expansion\",\n\t})[0]\n\n\tScenario.Prepare(context.Background())\n\n\ttargets := `bbi_mainrun_10[1:3].ctl`\n\n\tcommandAndArgs := []string{\n\t\t\"-d\", // Needs to be in debug mode to generate the expected output\n\t\t\"--threads\",\n\t\t\"2\",\n\t\t\"nonmem\",\n\t\t\"run\",\n\t\t\"local\",\n\t\t\"--nm_version\",\n\t\tos.Getenv(\"NMVERSION\"),\n\t\tfilepath.Join(Scenario.Workpath, \"model\", targets),\n\t}\n\n\toutput, err := executeCommand(context.Background(), \"bbi\", commandAndArgs...)\n\n\tt.R.NoError(err)\n\tt.R.NotEmpty(output)\n\n\tmodelsLine, _ := findOutputLine(strings.Split(output, \"\\n\"))\n\tmodelsLine = strings.TrimSuffix(modelsLine, \"\\n\")\n\texpandedModels := outputLineToModels(modelsLine)\n\n\t// Verify that we expanded to three models\n\tt.R.Len(expandedModels, 3)\n\n\t// Verify nonmem completed for all five\n\tfor _, m := range expandedModels {\n\t\tfile := filepath.Base(m)\n\t\textension := filepath.Ext(file)\n\t\tidentifier := strings.Replace(file, extension, \"\", 1)\n\t\toutputDir := filepath.Join(Scenario.Workpath, \"model\", identifier)\n\n\t\tinternalModel := Model{\n\t\t\tidentifier: identifier,\n\t\t\tfilename: file,\n\t\t\textension: extension,\n\t\t\tpath: outputDir,\n\t\t}\n\n\t\tnmd := NonMemTestingDetails{\n\t\t\tOutputDir: internalModel.path,\n\t\t\tModel: internalModel,\n\t\t\tOutput: output,\n\t\t}\n\n\t\tAssertNonMemCompleted(t, nmd)\n\t\tAssertNonMemCreatedOutputFiles(t, nmd)\n\t}\n}", "func MoreTest() {}", "func SubtestTestVerbosity(t *testing.T, tw *testWriter, verbosity int) {\n\tLogDebug(\"TEST_1\")\n\tLogVerbose(\"TEST_2\")\n\tLogInfo(\"TEST_3\")\n\tLogWarning(\"TEST_4\")\n\tLogError(\"TEST_5\")\n\n\tbMatch := make([]bool, 5)\n\tbMatch[0], _ = regexp.MatchString(\"TEST_1\", tw.GetString())\n\tbMatch[1], _ = regexp.MatchString(\"TEST_2\", tw.GetString())\n\tbMatch[2], _ = regexp.MatchString(\"TEST_3\", tw.GetString())\n\tbMatch[3], _ = regexp.MatchString(\"TEST_4\", tw.GetString())\n\tbMatch[4], _ = regexp.MatchString(\"TEST_5\", tw.GetString())\n\n\tfor i := 4; i >= 4-verbosity; i-- {\n\t\tif !bMatch[i] {\n\t\t\tt.Fail()\n\t\t\treturn\n\t\t}\n\t}\n\n\tfor i := 0; i < 4-verbosity; i++ {\n\t\tif bMatch[i] {\n\t\t\tt.Fail()\n\t\t\treturn\n\t\t}\n\t}\n\n}", "func (p *Parser) sub() {\n\tp.primary()\n\tp.emitByte(OP_SUB)\n}", "func init() { //nolint\n\ttestSample := TestCase{\n\t\tName: \"should hide the progress bar in the CLI [E2E-CLI-009]\",\n\t\tArgs: args{\n\t\t\tArgs: []cmdArgs{\n\t\t\t\t[]string{\"scan\", \"-q\", \"../assets/queries\", \"-p\", \"fixtures/samples/terraform.tf\", \"--no-progress\"},\n\t\t\t},\n\t\t},\n\t\tWantStatus: []int{50},\n\t\tValidation: func(outputText string) bool {\n\t\t\tgetProgressRegex := \"Executing queries:\"\n\t\t\tmatch, _ := regexp.MatchString(getProgressRegex, outputText)\n\t\t\t// if not found -> the the test was successful\n\t\t\treturn !match\n\t\t},\n\t}\n\n\tTests = append(Tests, testSample)\n}", "func TestEmptyCommit4A(t *testing.T) {\n}", "func SubtestStress1Conn100Stream100Msg10MB(t *testing.T, tr mux.Multiplexer) {\n\ttmux.SubtestStress1Conn100Stream100Msg10MB(t, tr)\n}", "func TestPrewriteMultiple4A(t *testing.T) {\n}", "func TestSinglePrewrite4A(t *testing.T) {\n}", "func TestTranscodeSubUnreachable(t *testing.T) {\n\tglog.Infof(\"\\n\\nTesting TranscodesubUnreachable...\")\n\t// Tests whether a transcoder node can still receive data even if unreachable\n\tn2, n3 := setupNodes(t, 15000, 15001)\n\tn1, _ := setupNodes(t, 15000, 15002) // make subscriber (n1) unreachable\n\tdefer n1.NetworkNode.(*BasicNetworkNode).PeerHost.Close()\n\tdefer n2.NetworkNode.(*BasicNetworkNode).PeerHost.Close()\n\tdefer n3.NetworkNode.(*BasicNetworkNode).PeerHost.Close()\n\tconnectHosts(n1.NetworkNode.(*BasicNetworkNode).PeerHost, n3.NetworkNode.(*BasicNetworkNode).PeerHost)\n\tconnectHosts(n2.NetworkNode.(*BasicNetworkNode).PeerHost, n3.NetworkNode.(*BasicNetworkNode).PeerHost)\n\n\t// Sanity check that no connection exists between broadcaster (n2) and sub (n1)\n\tif !n2.peerListIs([]peer.ID{n3.NetworkNode.ID()}) {\n\t\tt.Error(\"Broadcaster did not have expected peer list (check #1)\")\n\t}\n\n\tstrmID := fmt.Sprintf(\"%vstrmID\", peer.IDHexEncode(n2.NetworkNode.(*BasicNetworkNode).Identity))\n\tbcaster, _ := n2.GetBroadcaster(strmID)\n\tresult := make(map[uint64][]byte)\n\tlock := &sync.Mutex{}\n\tn1.TranscodeSub(context.Background(), strmID, func(seqNo uint64, data []byte, eof bool) {\n\t\t// glog.Infof(\"Got response: %v, %v\", seqNo, data)\n\t\tlock.Lock()\n\t\tresult[seqNo] = data\n\t\tlock.Unlock()\n\t})\n\ttime.Sleep(time.Millisecond * 50) // allow TranscodeSub goroutine to run\n\n\ts1tmp, _ := n1.GetSubscriber(strmID)\n\ts1, _ := s1tmp.(*BasicSubscriber)\n\tif s1.cancelWorker == nil {\n\t\tt.Error(\"Cancel function should be assigned\")\n\t}\n\tif !s1.working {\n\t\tt.Error(\"Subscriber should be working\")\n\t}\n\n\t// XXX find a way to check subMsg.StrmID\n\ttime.Sleep(time.Millisecond * 50)\n\n\tfor i := 0; i < 10; i++ {\n\t\ttime.Sleep(time.Millisecond * 50)\n\t\tbcaster.Broadcast(uint64(i), []byte(\"test data\"))\n\t}\n\n\tfor start := time.Now(); time.Since(start) < 3*time.Second; {\n\t\tif len(result) == 10 {\n\t\t\tbreak\n\t\t} else {\n\t\t\ttime.Sleep(time.Millisecond * 50)\n\t\t}\n\t}\n\tif len(result) != 10 {\n\t\tt.Errorf(\"Expecting length of result to be 10, but got %v: %v\", len(result), result)\n\t}\n\n\tfor _, d := range result {\n\t\tif string(d) != \"test data\" {\n\t\t\tt.Errorf(\"Expecting data to be 'test data', but got %v\", d)\n\t\t}\n\t}\n\n\t// Ensure that no connection exists between broadcaster (n2) and sub\n\tif !n2.peerListIs([]peer.ID{n3.NetworkNode.ID()}) {\n\t\tt.Error(\"Broadcaster did not have expected peer list (check #2)\", n2.NetworkNode.GetPeers())\n\t}\n\t// Ensure that the relay still has the stream\n\tif n1.getSubscriber(strmID) == nil ||\n\t\tbcaster.(*BasicBroadcaster).listeners[peer.IDHexEncode(n3.NetworkNode.ID())] == nil ||\n\t\tn3.relayers[relayerMapKey(strmID, SubReqID)] == nil || n3.relayers[relayerMapKey(strmID, SubReqID)].listeners[peer.IDHexEncode(n1.NetworkNode.ID())] == nil {\n\t\tt.Error(\"Subscriptions not set up as expected on nodes\")\n\t}\n\n\t//Call cancel\n\ts1.cancelWorker()\n\n\t// XXX find a way to check cancelMsg.StrmID\n\n\ttime.Sleep(time.Millisecond * 100)\n\n\tif s1.working {\n\t\tt.Error(\"subscriber shouldn't be working after 'cancel' is called\")\n\t}\n\n}", "func (suite *AddCommandTestSuite) TestExecuteWhenNoTracksFound() {\n\n}", "func TestAuxiliary(t *testing.T) {\n\t// Create a Backend with the test node.\n\tbtc, shutdown := testBackend(false)\n\tdefer shutdown()\n\n\t// Add a transaction and retrieve it.\n\tcleanTestChain()\n\tmaturity := int64(testParams.CoinbaseMaturity)\n\tmsg := testMakeMsgTx(false)\n\tvalueSats := int64(29e6)\n\tmsg.tx.TxOut[0].Value = valueSats\n\ttxid := hex.EncodeToString(randomBytes(32))\n\ttxHash, _ := chainhash.NewHashFromStr(txid)\n\ttxHeight := rand.Uint32()\n\tblockHash := testAddBlockVerbose(nil, nil, 1, txHeight)\n\ttestAddTxOut(msg.tx, msg.vout, txHash, blockHash, int64(txHeight), maturity)\n\tcoinID := toCoinID(txHash, msg.vout)\n\n\tverboseTx := testChain.txRaws[*txHash]\n\tvout := btcjson.Vout{\n\t\tValue: 0.29,\n\t\tN: 0,\n\t\t//ScriptPubKey\n\t}\n\tverboseTx.Vout = append(verboseTx.Vout, vout)\n\n\tutxo, err := btc.FundingCoin(context.Background(), coinID, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif utxo.TxID() != txid {\n\t\tt.Fatalf(\"utxo txid doesn't match\")\n\t}\n\n\tif utxo.(*UTXO).value != uint64(msg.tx.TxOut[0].Value) {\n\t\tt.Errorf(\"incorrect value. got %d, wanted %d\", utxo.(*UTXO).value, msg.tx.TxOut[0].Value)\n\t}\n\n\tvoutVal, err := btc.prevOutputValue(txid, 0)\n\tif err != nil {\n\t\tt.Fatalf(\"prevOutputValue: %v\", err)\n\t}\n\tif voutVal != uint64(msg.tx.TxOut[0].Value) {\n\t\tt.Errorf(\"incorrect value. got %d, wanted %d\", utxo.(*UTXO).value, msg.tx.TxOut[0].Value)\n\t}\n}", "func testFooter(t *testing.T) {\n\tlogging.Info(fmt.Sprintf(\"=============== Ending test [%s] ===============\", t.Name()))\n}", "func TestCBOWithoutAnalyze(t *testing.T) {\n\tstore, dom := testkit.CreateMockStoreAndDomain(t)\n\ttestKit := testkit.NewTestKit(t, store)\n\ttestKit.MustExec(\"use test\")\n\ttestKit.MustExec(\"create table t1 (a int)\")\n\ttestKit.MustExec(\"create table t2 (a int)\")\n\th := dom.StatsHandle()\n\trequire.NoError(t, h.HandleDDLEvent(<-h.DDLEventCh()))\n\trequire.NoError(t, h.HandleDDLEvent(<-h.DDLEventCh()))\n\ttestKit.MustExec(\"insert into t1 values (1), (2), (3), (4), (5), (6)\")\n\ttestKit.MustExec(\"insert into t2 values (1), (2), (3), (4), (5), (6)\")\n\trequire.NoError(t, h.DumpStatsDeltaToKV(handle.DumpAll))\n\trequire.NoError(t, h.Update(dom.InfoSchema()))\n\tvar input []string\n\tvar output []struct {\n\t\tSQL string\n\t\tPlan []string\n\t}\n\tanalyzeSuiteData := GetAnalyzeSuiteData()\n\tanalyzeSuiteData.LoadTestCases(t, &input, &output)\n\tfor i, sql := range input {\n\t\tplan := testKit.MustQuery(sql)\n\t\ttestdata.OnRecord(func() {\n\t\t\toutput[i].SQL = sql\n\t\t\toutput[i].Plan = testdata.ConvertRowsToStrings(plan.Rows())\n\t\t})\n\t\tplan.Check(testkit.Rows(output[i].Plan...))\n\t}\n}", "func Test_sampe002(t *testing.T) {\n\n}", "func TestAbCommonResults(t *testing.T) {\n\tvar tool AbTool\n\n\tcfg.Cfg.Verbose = true\n\tconfig := &cfg.Config{}\n\tconfig.Ab.Keepalive = false\n\tconfig.Ab.Concurency = 1\n\tconfig.Ab.Requests = 1\n\ttool = AbTool{&config.Ab}\n\tresult, err := tool.BenchCommand(\"test\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t_ = result.Command()\n\t_ = result.Params()\n\tdata := []byte(\"\")\n\tresult.Parse(data)\n\tdata = []byte(AB_RESULT)\n\tresult.Parse(data)\n}", "func (scenTest *GetStartedFunctionsScenarioTest) RunSubTest(stubber *testtools.AwsmStubber) {\n\tmockQuestioner := demotools.MockQuestioner{Answers: scenTest.Answers}\n\tscenario := NewGetStartedFunctionsScenario(*stubber.SdkConfig, &mockQuestioner, &scenTest.helper)\n\tscenario.isTestRun = true\n\tscenario.Run()\n}", "func TestSubFibonacci(t *testing.T) {\n\tvar tests = []struct {\n\t\tinput, result int\n\t}{\n\t\t{input: 2, result: 1},\n\t\t{input: 8, result: 21},\n\t\t{input: 10, result: 55},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(fmt.Sprintf(\"Fibonacci(%d)\", test.input), func(t *testing.T) {\n\t\t\ttestingFunc(t, test.input, test.result)\n\t\t})\n\t}\n}", "func main() {\n\tflag.Parse()\n\t// To test that the sequential version gathers the same blobs in commits\n\tif *test {\n\t\tblobsInCommitsSequential := getBlobsInCommitSequential(false)\n\t\tblobsInCommits := getBlobsInCommit(false)\n\t\tif diff := cmp.Diff(&blobsInCommits, &blobsInCommitsSequential); diff != \"\" {\n\t\t\tfmt.Println(fmt.Errorf(\"blobs mismatch (-want +got):\\n%s\", diff))\n\t\t\tos.Exit(1)\n\t\t}\n\t\tos.Exit(0)\n\t}\n\n\tgo http.ListenAndServe(\":1234\", nil)\n\t// if *cpuprofile != \"\" {\n\t// \tf, err := os.Create(*cpuprofile)\n\t// \tif err != nil {\n\t// \t\tlog.Fatal(err)\n\t// \t}\n\t// \tpprof.StartCPUProfile(f)\n\t// \tdefer pprof.StopCPUProfile()\n\t// }\n\tadditions := GetAdditions(false)\n\t_ = additions\n}", "func main() {\n\tbenchMark()\n\tlevelDemo()\n}", "func SubtestStress1Conn100Stream100Msg(t *testing.T, tr mux.Multiplexer) {\n\ttmux.SubtestStress1Conn100Stream100Msg(t, tr)\n}", "func TestUnsubscribeEnd(t *testing.T) {\n\tPrintTestMessage(\"==========Unsubscribe tests end==========\")\n}", "func (s *cmdIntegrationSuite) TestRemoveWithExcludeFlag(c *chk.C) {\n\tbsu := getBSU()\n\n\t// set up the container with numerous blobs\n\tcontainerURL, containerName := createNewContainer(c, bsu)\n\tblobList := scenarioHelper{}.generateCommonRemoteScenarioForBlob(c, containerURL, \"\")\n\tdefer deleteContainer(c, containerURL)\n\tc.Assert(containerURL, chk.NotNil)\n\tc.Assert(len(blobList), chk.Not(chk.Equals), 0)\n\n\t// add special blobs that we wish to exclude\n\tblobsToExclude := []string{\"notGood.pdf\", \"excludeSub/lame.jpeg\", \"exactName\"}\n\tscenarioHelper{}.generateBlobsFromList(c, containerURL, blobsToExclude)\n\texcludeString := \"*.pdf;*.jpeg;exactName\"\n\n\t// set up interceptor\n\tmockedRPC := interceptor{}\n\tRpc = mockedRPC.intercept\n\tmockedRPC.init()\n\n\t// construct the raw input to simulate user input\n\trawContainerURLWithSAS := scenarioHelper{}.getRawContainerURLWithSAS(c, containerName)\n\traw := getDefaultRemoveRawInput(rawContainerURLWithSAS.String(), true)\n\traw.exclude = excludeString\n\traw.recursive = true\n\n\trunCopyAndVerify(c, raw, func(err error) {\n\t\tc.Assert(err, chk.IsNil)\n\t\tvalidateDownloadTransfersAreScheduled(c, \"\", \"\", blobList, mockedRPC)\n\t})\n}", "func main() {\n\tlog.Println(\"TEST CASE 1:\")\n\ttest_case_1()\n\tlog.Println(\"\\n\\n\")\n\n\tlog.Println(\"TEST CASE 2:\")\n\ttest_case_2()\n\tlog.Println(\"\\n\\n\")\n\n\tlog.Println(\"TEST CASE 3:\")\n\ttest_case_3()\n\tlog.Println(\"\\n\\n\")\n\n\tlog.Println(\"TEST CASE 4:\")\n\ttest_case_4()\n\tlog.Println(\"\\n\\n\")\n}", "func (s *cmdIntegrationSuite) TestDownloadBlobContainerWithMultRegexExclude(c *chk.C) {\n\tbsu := getBSU()\n\n\t// set up the container with blobs\n\tcontainerURL, containerName := createNewContainer(c, bsu)\n\tblobsToInclude := scenarioHelper{}.generateCommonRemoteScenarioForBlob(c, containerURL, \"\")\n\tdefer deleteContainer(c, containerURL)\n\tc.Assert(containerURL, chk.NotNil)\n\tc.Assert(len(blobsToInclude), chk.Not(chk.Equals), 0)\n\n\t// add blobs that we wish to exclude\n\tblobsToIgnore := []string{\"tessssssssssssst.txt\", \"subOne/dogs.jpeg\", \"subOne/subTwo/tessssst.pdf\"}\n\tscenarioHelper{}.generateBlobsFromList(c, containerURL, blobsToIgnore, blockBlobDefaultData)\n\n\t// set up the destination with an empty folder\n\tdstDirName := scenarioHelper{}.generateLocalDirectory(c)\n\tdefer os.RemoveAll(dstDirName)\n\n\t// set up interceptor\n\tmockedRPC := interceptor{}\n\tRpc = mockedRPC.intercept\n\tmockedRPC.init()\n\n\t// construct the raw input to simulate user input\n\trawContainerURLWithSAS := scenarioHelper{}.getRawContainerURLWithSAS(c, containerName)\n\trawContainerURLWithSAS.Path = path.Join(rawContainerURLWithSAS.Path, string([]byte{0x00}))\n\tcontainerString := strings.ReplaceAll(rawContainerURLWithSAS.String(), \"%00\", \"*\")\n\traw := getDefaultCopyRawInput(containerString, dstDirName)\n\traw.recursive = true\n\traw.excludeRegex = \"es{4,};o(g)\"\n\n\trunCopyAndVerify(c, raw, func(err error) {\n\t\tc.Assert(err, chk.IsNil)\n\t\t// validate that the right number of transfers were scheduled\n\t\tc.Assert(len(mockedRPC.transfers), chk.Equals, len(blobsToInclude))\n\t\t// comparing is names of files, since not in order need to sort each string and the compare them\n\t\tactualTransfer := []string{}\n\t\tfor i := 0; i < len(mockedRPC.transfers); i++ {\n\t\t\tactualTransfer = append(actualTransfer, strings.Trim(mockedRPC.transfers[i].Destination, \"/\"))\n\t\t}\n\t\tsort.Strings(actualTransfer)\n\t\tsort.Strings(blobsToInclude)\n\t\tc.Assert(actualTransfer, chk.DeepEquals, blobsToInclude)\n\n\t\t// validate that the right transfers were sent\n\t\tvalidateDownloadTransfersAreScheduled(c, common.AZCOPY_PATH_SEPARATOR_STRING, common.AZCOPY_PATH_SEPARATOR_STRING,\n\t\t\tblobsToInclude, mockedRPC)\n\t})\n}", "func (s *cmdIntegrationSuite) TestRemoveWithIncludeAndExcludeFlag(c *chk.C) {\n\tbsu := getBSU()\n\n\t// set up the container with numerous blobs\n\tcontainerURL, containerName := createNewContainer(c, bsu)\n\tblobList := scenarioHelper{}.generateCommonRemoteScenarioForBlob(c, containerURL, \"\")\n\tdefer deleteContainer(c, containerURL)\n\tc.Assert(containerURL, chk.NotNil)\n\tc.Assert(len(blobList), chk.Not(chk.Equals), 0)\n\n\t// add special blobs that we wish to include\n\tblobsToInclude := []string{\"important.pdf\", \"includeSub/amazing.jpeg\"}\n\tscenarioHelper{}.generateBlobsFromList(c, containerURL, blobsToInclude)\n\tincludeString := \"*.pdf;*.jpeg;exactName\"\n\n\t// add special blobs that we wish to exclude\n\t// note that the excluded files also match the include string\n\tblobsToExclude := []string{\"sorry.pdf\", \"exclude/notGood.jpeg\", \"exactName\", \"sub/exactName\"}\n\tscenarioHelper{}.generateBlobsFromList(c, containerURL, blobsToExclude)\n\texcludeString := \"so*;not*;exactName\"\n\n\t// set up interceptor\n\tmockedRPC := interceptor{}\n\tRpc = mockedRPC.intercept\n\tmockedRPC.init()\n\n\t// construct the raw input to simulate user input\n\trawContainerURLWithSAS := scenarioHelper{}.getRawContainerURLWithSAS(c, containerName)\n\traw := getDefaultRemoveRawInput(rawContainerURLWithSAS.String(), true)\n\traw.include = includeString\n\traw.exclude = excludeString\n\traw.recursive = true\n\n\trunCopyAndVerify(c, raw, func(err error) {\n\t\tc.Assert(err, chk.IsNil)\n\t\tvalidateDownloadTransfersAreScheduled(c, \"\", \"\", blobsToInclude, mockedRPC)\n\t})\n}", "func RunSTest(b int) {\n for i := 0; i < b; i++ {\n if !Stest() {\n os.Exit(1)\n }\n } \n}", "func MainCrawl() {\n\t// testFetchURL()\n\t// testFetchlLinks01()\n\t// testFetchlLinks02()\n\n\t// testCrawl01()\n\t// testCrawl02()\n\t// testCrawl03()\n\n\tfmt.Println(\"golang crawl examples DONE.\")\n}", "func SUBB(imr, amr operand.Op) { ctx.SUBB(imr, amr) }", "func TestSingleCommit4A(t *testing.T) {\n}", "func SubtestStress1Conn1Stream100Msg(t *testing.T, tr mux.Multiplexer) {\n\ttmux.SubtestStress1Conn1Stream100Msg(t, tr)\n}", "func (suite *AddCommandTestSuite) TestExecuteWhenMultipleTracksFound() {\n\n}", "func main() {\r\n\t//scenario1()\r\n\t//scenario2()\r\n\t//scenario3()\r\n\t//scenario4()\r\n}", "func TestDontRun(t *testing.T) {\n\tt.Log(\"This is a Test not a Benchmark!\")\n}", "func TestUnsubscribeStart(t *testing.T) {\n\tPrintTestMessage(\"==========Unsubscribe tests start==========\")\n}", "func SubtestStress(t *testing.T, opt Options) {\n\ttmux.SubtestStress(t, opt)\n}", "func TestAckInstalledApplicationListDuplicateRegression(t *testing.T) {\n\n}", "func SubtestStress1Conn1000Stream10Msg(t *testing.T, tr mux.Multiplexer) {\n\ttmux.SubtestStress1Conn1000Stream10Msg(t, tr)\n}", "func TestPrewriteWritten4A(t *testing.T) {\n}", "func main() {\n\ttest_plain_background()\n\ttest_cloud()\n\ttest_enemy()\n\ttest_move_background()\n\ttest_display_score()\n}", "func (s *SignSuite) TearDownTest(c *C) {\n}", "func TestMain(m *testing.M) {\n\tDropTestData(0)\n\tanswer := m.Run()\n\tDropTestData(0)\n\tos.Exit(answer)\n}", "func aroundNegativeTest(t *testing.T) {\n\n\tresult := newFooter(1, 15, 0, 1).List\n\texpected := []string{}\n\tfor i := 0; i < len(expected); i++ {\n\t\tif result[i] != expected[i] {\n\t\t\tt.Error()\n\t\t}\n\t}\n\n}", "func TestMain(m *testing.M) {\n\tif os.Getenv(\"BENT_TEST_IS_CMD_BENT\") != \"\" {\n\t\tmain()\n\t\tos.Exit(0)\n\t}\n\tvar err error\n\tdir, err = os.MkdirTemp(\"\", \"bent_test\")\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n\tdefer os.RemoveAll(dir)\n\tm.Run()\n}", "func (b *KRMBlueprintTest) Teardown(assert *assert.Assertions) {\n\tb.teardown(assert)\n}", "func Test2(t *testing.T) {\n\tlog.Print(\"\\n\\n========== SOLUTION 2 =========\\n\\n\\n\")\n\ttestOld()\n}", "func (s *cmdIntegrationSuite) TestDownloadBlobContainerWithRegexExclude(c *chk.C) {\n\tbsu := getBSU()\n\n\t// set up the container with blobs\n\tcontainerURL, containerName := createNewContainer(c, bsu)\n\tblobsToInclude := scenarioHelper{}.generateCommonRemoteScenarioForBlob(c, containerURL, \"\")\n\tdefer deleteContainer(c, containerURL)\n\tc.Assert(containerURL, chk.NotNil)\n\tc.Assert(len(blobsToInclude), chk.Not(chk.Equals), 0)\n\n\t// add blobs that we wish to exclude\n\tblobsToIgnore := []string{\"tessssssssssssst.txt\", \"subOne/tetingessssss.jpeg\", \"subOne/subTwo/tessssst.pdf\"}\n\tscenarioHelper{}.generateBlobsFromList(c, containerURL, blobsToIgnore, blockBlobDefaultData)\n\n\t// set up the destination with an empty folder\n\tdstDirName := scenarioHelper{}.generateLocalDirectory(c)\n\tdefer os.RemoveAll(dstDirName)\n\n\t// set up interceptor\n\tmockedRPC := interceptor{}\n\tRpc = mockedRPC.intercept\n\tmockedRPC.init()\n\n\t// construct the raw input to simulate user input\n\trawContainerURLWithSAS := scenarioHelper{}.getRawContainerURLWithSAS(c, containerName)\n\trawContainerURLWithSAS.Path = path.Join(rawContainerURLWithSAS.Path, string([]byte{0x00}))\n\tcontainerString := strings.ReplaceAll(rawContainerURLWithSAS.String(), \"%00\", \"*\")\n\traw := getDefaultCopyRawInput(containerString, dstDirName)\n\traw.recursive = true\n\traw.excludeRegex = \"es{4,}\"\n\n\trunCopyAndVerify(c, raw, func(err error) {\n\t\tc.Assert(err, chk.IsNil)\n\t\t// validate that only blobsTo\n\t\tc.Assert(len(mockedRPC.transfers), chk.Equals, len(blobsToInclude))\n\t\t// comparing is names of files, since not in order need to sort each string and the compare them\n\t\tactualTransfer := []string{}\n\t\tfor i := 0; i < len(mockedRPC.transfers); i++ {\n\t\t\tactualTransfer = append(actualTransfer, strings.Trim(mockedRPC.transfers[i].Destination, \"/\"))\n\t\t}\n\t\tsort.Strings(actualTransfer)\n\t\tsort.Strings(blobsToInclude)\n\t\tc.Assert(actualTransfer, chk.DeepEquals, blobsToInclude)\n\n\t\t// validate that the right transfers were sent\n\t\tvalidateDownloadTransfersAreScheduled(c, common.AZCOPY_PATH_SEPARATOR_STRING, common.AZCOPY_PATH_SEPARATOR_STRING,\n\t\t\tblobsToInclude, mockedRPC)\n\t})\n}", "func (suite *AddCommandTestSuite) TestExecuteWhenTrackFound() {\n\n}", "func (a *api) cleanUpTestData() {\n\tfmt.Println(\"Nothing to see here - move along\")\n\n\t/* Set up authorization with the token obtained earlier in the test */\n\ta.c.SetJWTSigner(&goaclient.APIKeySigner{\n\t\tSignQuery: false,\n\t\tKeyName: \"Authorization\",\n\t\tKeyValue: savedToken,\n\t\tFormat: \"Bearer %s\",\n\t})\n\n\t/* Delete the workitem */\n\tInfo.Println(\"The ID of the workitem to be deleted is:\", idString)\n\tresp, err := a.c.DeleteWorkitem(context.Background(), \"/api/workitems/\"+idString)\n\ta.resp = resp\n\ta.err = err\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}", "func TestMain(m *testing.M) {\n\tlog.SetOutput(ioutil.Discard)\n}", "func AfterSuiteActions() {\n\t// Run only Ginkgo on node 1\n}", "func TestEmpty(t *testing.T) {\n\tt.Logf(\"TODO\")\n}", "func TestUnsubscribe(t *testing.T) {\n\tif testing.Short() {\n\t\tt.SkipNow()\n\t}\n\tt.Parallel()\n\tcst, err := createConsensusSetTester(t.Name())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer cst.Close()\n\n\t// Subscribe the mock subscriber to the consensus set.\n\tms := newMockSubscriber()\n\terr = cst.cs.ConsensusSetSubscribe(&ms, modules.ConsensusChangeBeginning, cst.cs.tg.StopChan())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Check that the subscriber is receiving updates.\n\tmsLen := len(ms.updates)\n\tif msLen == 0 {\n\t\tt.Error(\"mock subscriber is not receiving updates\")\n\t}\n\t_, err = cst.miner.AddBlock() // should cause another update to be sent to the subscriber\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(ms.updates) != msLen+1 {\n\t\tt.Error(\"mock subscriber did not receive the correct number of updates\")\n\t}\n\n\t// Unsubscribe the subscriber and then check that it is no longer receiving\n\t// updates.\n\tcst.cs.Unsubscribe(&ms)\n\t_, err = cst.miner.AddBlock()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(ms.updates) != msLen+1 {\n\t\tt.Error(\"mock subscriber was not correctly unsubscribed\")\n\t}\n}", "func TestGetEmpty4A(t *testing.T) {\n}", "func main() {\n\tfmt.Printf(\"valid for part 1: %v\\n\", part1())\n\tfmt.Printf(\"valid for part 2: %v\\n\", part2())\n}", "func controllerSubtest(name string, tc *sessionTestCase) func(t *testing.T) {\n\treturn func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\t// This test uses the same controller to manage two sessions that are communicating with\n\t\t// each other (basically, both the \"local\" and \"remote\" session are on the same system).\n\t\t// This is possible because the local discriminators are chosen such that they are\n\t\t// different.\n\t\t//\n\t\t// While this is something that rarely (if ever) occurs in practice, it makes test setup\n\t\t// much simpler here. In the real world, BFD would configured between two systems and each\n\t\t// system would have its own controller which is in charge only of sessions on that system.\n\t\tcontroller := &bfd.Controller{\n\t\t\tSessions: []*bfd.Session{tc.sessionA, tc.sessionB},\n\t\t\tReceiveQueueSize: 10,\n\t\t}\n\n\t\t// both sessions send their messages through the same controller\n\t\tmessageQueue := &redirectSender{Destination: controller.Messages()}\n\t\ttc.sessionA.Sender = messageQueue\n\t\ttc.sessionB.Sender = messageQueue\n\t\ttc.sessionA.Logger = testlog.NewLogger(t).New(\"session\", \"a\")\n\t\ttc.sessionB.Logger = testlog.NewLogger(t).New(\"session\", \"b\")\n\n\t\t// the wait group is not used for synchronization, but rather to check that the controller\n\t\t// returns\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(1)\n\n\t\tgo func() {\n\t\t\terr := controller.Run()\n\t\t\trequire.NoError(t, err)\n\t\t\twg.Done()\n\t\t}()\n\n\t\t// second argument is not used because we have a single queue\n\t\ttc.testBehavior(messageQueue, nil)\n\n\t\tassert.Equal(t, tc.expectedUpA, controller.IsUp(tc.sessionA.LocalDiscriminator))\n\t\tassert.Equal(t, tc.expectedUpB, controller.IsUp(tc.sessionB.LocalDiscriminator))\n\n\t\tmessageQueue.Close()\n\n\t\tfor i := 0; i < 2; i++ {\n\t\t\terr := <-controller.Errors()\n\t\t\tassert.NoError(t, err)\n\t\t}\n\t\twg.Wait()\n\t}\n}", "func TESTW(ir, amr operand.Op) { ctx.TESTW(ir, amr) }", "func SubtestSimpleWrite(t *testing.T, tr mux.Multiplexer) {\n\ttmux.SubtestSimpleWrite(t, tr)\n}", "func (sub *subState) stopAckSub() {\n\tif sub.ackSub != nil {\n\t\tsub.ackSub.Unsubscribe()\n\t\tsub.ackSub = nil\n\t}\n}", "func KTESTB(k, k1 operand.Op) { ctx.KTESTB(k, k1) }", "func (s *mergeBaseSuite) TestDoubleCommonInSubFeatureBranches(c *C) {\n\trevs := []string{\"G\", \"Q\"}\n\texpectedRevs := []string{\"GQ1\", \"GQ2\"}\n\ts.AssertMergeBase(c, revs, expectedRevs)\n}", "func (m *OrgUnitMutation) ClearSubUnits() {\n\tm.clearedsubUnits = true\n}", "func TestMultiplePrewrites4A(t *testing.T) {\n}", "func TestSplitO2(t *testing.T) {\n test := func() {\n // fmt.Println(\"------ TestSplitO2 ------\")\n order := 2\n n := order*(order+2) + 1\n for i := 1; i <= order*(order+2)+1; i++ {\n self := makebtree(ORDER_2)\n constructCompleteLevel2(self, order, i)\n self.Insert(ByteSlice32(uint32(i)), rec)\n verify_tree(self, n, t)\n cleanbtree(self)\n }\n }\n test()\n}", "func SubtestStress50Conn10Stream50Msg(t *testing.T, tr mux.Multiplexer) {\n\ttmux.SubtestStress50Conn10Stream50Msg(t, tr)\n}", "func TestMain(t *testing.T) {\n\trunEndToEnd(t, \"testdata/config.yaml\")\n}", "func Test1(t *testing.T) {\n\tfmt.Println(\"Starting test 1 ...\")\n\n\t// create waitGroup for user defined pause\n\tvar wg sync.WaitGroup\n\tc := make(chan os.Signal)\n\tsignal.Notify(c, os.Interrupt)\n\n\t// get machine data\n\tmyIp, myId := InitNode()\n\n\tStaticDelay(myId, \"milliseconds\")\n\n\t// test create/join ring function\n\tInitRing(myIp, myId)\n\n\tStaticDelay(5, \"\")\n\n\t// Update new chord ring\n\tfmt.Println(\"\\nAll nodes completed test 1\\nChecking chord ring details ...\")\n\tipRing, ipNot := chord.CheckRing()\n\tfmt.Println(\"\\nin RING: \", ipRing)\n\tfmt.Println(\"Outside: \", ipNot, \"\\n \")\n\tchord.ChordNode.PrintNode()\n\n\t// wait for exit\n\tfmt.Println(\"\\nWaiting to exit ...\\nPress crtl+c to continue\")\n\twg.Add(1)\n\tgo func() {\n\t\t<-c\n\t\twg.Done()\n\t}()\n\twg.Wait()\n\n\tfmt.Println(\"\\nTest completed.\")\n}", "func main() {\n\n mainTests{}.mainTests117SortFileMgrsCaseSensitive()\n\n}", "func TestComplexifyRandom(t *testing.T) {\n\n}", "func TESTQ(ir, mr operand.Op) { ctx.TESTQ(ir, mr) }", "func collectParseTests(t *parseTest) (items []item) {\n//\tl := Lex(t.name, t.input)\n//\tfor {\n//\t\titem := l.nextItem()\n//\t\titems = append(items, item)\n//\t\tif item.typ == itemEOF || item.typ == itemError {\n//\t\t\tbreak\n//\t\t}\n//\t}\n\treturn\n}", "func SimpleNegativeTest(t *testing.T, contents string) {\n\tt.Helper()\n\tif !strings.HasPrefix(contents, `<?php`) {\n\t\tt.Fatalf(\"PHP script doesn't start with <?php\")\n\t}\n\ts := NewSuite(t)\n\ts.AddFile(contents)\n\ts.RunAndMatch()\n}", "func TestMain() { //nolint:deadcode\n\tmain()\n}", "func TestIntegration1(t *testing.T) {\n\n\ttemp_dir_name, err := ioutil.TempDir(\".\", \"loupe-tmp\")\n\tif err != nil {\n\t\tlog.Printf(\"cannot get temporary directory: %v\", err)\n\t}\n\n\tpreprocessor.PreprocessRunData(temp_dir_name, \"inputs/bigfile.vcf\", \"inputs/integration1.bed\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"awesome-output.json\", map[string]string{})\n\t/* XXX: The output here needs to be tested... somehow */\n}", "func main() {\n\tadapter.RunStage(split, chunk, join)\n}", "func (c *Context) TESTB(ir, amr operand.Op) {\n\tc.addinstruction(x86.TESTB(ir, amr))\n}", "func TestAnagramCountShort(t *testing.T) { testAnagramCount(t, testData[0]) }", "func CleanupSuite() {\n\t// Run on all Ginkgo nodes\n}", "func printTest(args *Args, isJustTest bool) {\n\tmessage := fmt.Sprintf(`%s %s configuration file %s test is `, appname, appversion, args.ConfigFile)\n\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tfmt.Printf(\"%s wrong !!!\\n> %s\\n\", message, err)\n\t\t\tos.Exit(0)\n\t\t}\n\t}()\n\n\t// Get config file content to struct\n\tcfg := config.GetConfig(args.ConfigFile)\n\n\t// check statistic redis source\n\tif \"redis\" == strings.ToLower(cfg.Statistic.SourceType) {\n\t\toredis.GetInstancePanic(cfg.Statistic.RedisSource)\n\t}\n\n\tenabledQueueCount := 0\n\t// sort the DelayOnFailure array\n\tfor _, r := range cfg.Redis {\n\t\toredis.GetInstancePanic(r.Config)\n\t\tfor _, n := range r.Queues {\n\t\t\tif n.IsEnabled {\n\t\t\t\tenabledQueueCount++\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, r := range cfg.RabbitMQ {\n\t\tr.Config.GetConnectionPanic()\n\t\tfor _, n := range r.Queues {\n\t\t\tif n.IsEnabled {\n\t\t\t\tenabledQueueCount++\n\t\t\t}\n\t\t}\n\t}\n\n\tif enabledQueueCount < 1 {\n\t\tpanic(`There has no enabled queue, please check configure file \"IsEnabled\" fields for every queue`)\n\t}\n\n\t// if -t\n\tif isJustTest {\n\t\tfmt.Printf(\"%s ok\\n\", message)\n\t\tos.Exit(0)\n\t}\n}", "func (c *ExampleController) Sub(ctx *app.SubExampleContext) error {\n\t// ExampleController_Sub: start_implement\n\n\t// Put your logic here\n\n\t// ExampleController_Sub: end_implement\n\tres := &app.Messagetype{}\n\treturn ctx.OK(res)\n}", "func VPTESTMB(ops ...operand.Op) { ctx.VPTESTMB(ops...) }", "func TestMain(m *testing.M) {\n\tprintln(\"do stuff before all tests\")\n\tm.Run()\n\tprintln(\"do stuff after all tests\")\n}", "func TestKyberTradingTestSuite(t *testing.T) {\n\tfmt.Println(\"Starting entry point for Kyber test suite...\")\n\n\ttradingSuite := new(TradingTestSuite)\n\tsuite.Run(t, tradingSuite)\n\n\tkyberTradingSuite := NewKyberTradingTestSuite(tradingSuite)\n\tsuite.Run(t, kyberTradingSuite)\n\n\tfmt.Println(\"Finishing entry point for 0x test suite...\")\n}", "func doCHARableTest(t *testing.T, out io.Writer, f decoder.New, endianness bool, teTa decoder.TestTable) {\n\t//var (\n\t//\t// til is the trace id list content for test\n\t//\tidl = ``\n\t//)\n\t//lu := make(id.TriceIDLookUp) // empty\n\t//luM := new(sync.RWMutex)\n\t//assert.Nil(t, ilu.FromJSON([]byte(idl)))\n\t//lu.AddFmtCount(os.Stdout)\n\tbuf := make([]byte, decoder.DefaultSize)\n\tdec := f(out, nil, nil, nil, nil, endianness) // a new decoder instance\n\tfor _, x := range teTa {\n\t\tin := ioutil.NopCloser(bytes.NewBuffer(x.In))\n\t\tdec.SetInput(in)\n\t\tlineStart := true\n\t\tvar err error\n\t\tvar n int\n\t\tvar act string\n\t\tfor err == nil {\n\t\t\tn, err = dec.Read(buf)\n\t\t\tif n == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif decoder.ShowID != \"\" && lineStart {\n\t\t\t\tact += fmt.Sprintf(decoder.ShowID, decoder.LastTriceID)\n\t\t\t}\n\t\t\tact += fmt.Sprint(string(buf[:n]))\n\t\t\tlineStart = false\n\t\t}\n\t\tact = strings.TrimSuffix(act, \"\\\\n\")\n\t\tact = strings.TrimSuffix(act, \"\\n\")\n\t\tassert.Equal(t, x.Exp, act)\n\t}\n}", "func (mock *QueuerMock) UnsubCalls() []struct {\n\tTopic string\n} {\n\tvar calls []struct {\n\t\tTopic string\n\t}\n\tmock.lockUnsub.RLock()\n\tcalls = mock.calls.Unsub\n\tmock.lockUnsub.RUnlock()\n\treturn calls\n}", "func (b ExpectedTip) FullBlockTestInstance() {}", "func (b ExpectedTip) FullBlockTestInstance() {}", "func SubtestStreamReset(t *testing.T, tr mux.Multiplexer) {\n\ttmux.SubtestStreamReset(t, tr)\n}", "func TestMain(m *testing.M) {\n\t// Set RabbitMQ connection\n\tif err := amqp.Set(_url); err != nil {\n\t\tpanic(fmt.Errorf(\"test main: %s\",err))\n\t}\n\t\n\tc := m.Run()\n\n\t// Wait for consumer test\n\t<-_done\n\n\tos.Exit(c)\n}", "func TestMain(m *testing.M) {\n\tfields := []FieldOffset{\n\t\t{\n\t\t\tName: \"Batch.Measurments\",\n\t\t\tOffset: unsafe.Offsetof(Batch{}.Measurements),\n\t\t},\n\t\t{\n\t\t\tName: \"Measurement.Number\",\n\t\t\tOffset: unsafe.Offsetof(Measurement{}.Number),\n\t\t},\n\t}\n\tif !Aligned8Byte(fields, os.Stderr) {\n\t\tos.Exit(1)\n\t}\n\n\tos.Exit(m.Run())\n}", "func TestRunMain(t *testing.T) {\n\tmain()\n}" ]
[ "0.5852912", "0.57938725", "0.5762686", "0.57162184", "0.5705786", "0.56626695", "0.56479615", "0.5604835", "0.5578083", "0.55233574", "0.5514207", "0.5408424", "0.53840244", "0.53645414", "0.53431845", "0.5330831", "0.5294767", "0.5288314", "0.5282433", "0.52654684", "0.52601236", "0.52480084", "0.52270883", "0.5196341", "0.51953405", "0.519267", "0.5183621", "0.5182315", "0.5150964", "0.51461095", "0.5145554", "0.51446813", "0.5129098", "0.51035273", "0.50845194", "0.5075752", "0.5070477", "0.5070425", "0.5068621", "0.506403", "0.50614506", "0.5049913", "0.50415504", "0.5038319", "0.5037134", "0.50356776", "0.50338143", "0.5012014", "0.50115275", "0.4987315", "0.49829572", "0.4980957", "0.49780315", "0.49748886", "0.49743986", "0.49736667", "0.49678573", "0.49649608", "0.49483818", "0.49452266", "0.49449652", "0.4928407", "0.4914071", "0.48996595", "0.48988557", "0.4897635", "0.48975983", "0.48957813", "0.488597", "0.48788643", "0.48778382", "0.48766842", "0.48617384", "0.48573083", "0.48548514", "0.48547688", "0.48547417", "0.48541227", "0.48508808", "0.48456532", "0.4832003", "0.48299044", "0.4827935", "0.48257533", "0.48250347", "0.4821982", "0.48209992", "0.48196626", "0.48168302", "0.48091555", "0.48089427", "0.48074034", "0.47966298", "0.4793374", "0.47901782", "0.47872594", "0.47872594", "0.4786637", "0.47830522", "0.47827864", "0.47804523" ]
0.0
-1
Pop remueve un valor al final y retorna el valor removido
func (s *Stack) Pop() int { l := len(s-item) - 1 toRemove := s.items[l] s.items = s.items[:l] return toRemove }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func lvalPop(v *LVal, i int) *LVal {\n\tx := v.Cell[i]\n\n\tv.Cell = append(v.Cell[:i], v.Cell[i+1:]...)\n\treturn x\n}", "func (this *MyStack) Pop() int {\n\ttemp := this.val[0]\n\tthis.val = this.val[1:]\n\treturn temp\n}", "func (h *Heap) Pop() interface{} {\n\tif h.size == 0 {\n\t\treturn nil\n\t}\n\tres := h.values[1]\n\th.values[1] = h.values[h.size]\n\th.values = h.values[:h.size]\n\th.size--\n\n\th.bubbleDown()\n\n\treturn res\n}", "func(k *Stack) Pop(){\n\tl := len(k.nums)-1\n\n\tk.nums = k.nums[:l]\n\n\n}", "func (this *MyStack) Pop() int {\n\tres := this.v[len(this.v)-1]\n\tthis.v = this.v[:len(this.v)-1]\n\treturn res\n}", "func (t *Tower) pop() (result int) {\n\tresult = (*t)[len(*t)-1]\n\t*t = (*t)[:len(*t)-1]\n\treturn result\n}", "func (c *Clac) Pop() (value.Value, error) {\n\tx, err := c.remove(0, 1)\n\tif err != nil {\n\t\treturn zero, err\n\t}\n\treturn x[0], err\n}", "func (v *Vector) PopBack() (string, error) {\n\tif len(v.Vector) == 0 {\n\t\treturn \"\", fmt.Errorf(\"nothing to pop\")\n\t}\n\tres := v.Vector[len(v.Vector)-1]\n\t// v.Vector[len(v.Vector)-1] = \"\"\n\tv.Vector = v.Vector[:len(v.Vector)-1]\n\treturn res, nil\n}", "func (s *MyStack) Pop() int {\n v := s.queue1[0]\n s.queue1 = s.queue1[1:]\n return v\n}", "func (w *walk) pop() {\n\tif len(*w) > 0 {\n\t\t*w = (*w)[:len(*w)-1]\n\t}\n}", "func (ll *LinkedList) PopBack() T {\n\tif ll.tail == nil {\n\t\treturn nil\n\t}\n\n\tval := ll.tail.val\n\tif ll.head == ll.tail {\n\t\tll.head = nil\n\t\tll.tail = nil\n\t} else {\n\t\ttail := ll.tail.prev\n\t\ttail.next = nil\n\t\tll.tail.prev = nil\n\t\tll.tail = tail\n\t}\n\n\tll.size--\n\treturn val\n}", "func (s *Slot) pop() Item {\n\titem := s.item\n\ts.item = Empty\n\treturn item\n}", "func (t *topK) Pop() interface{} {\n\tn := len(t.values)\n\tx := t.values[n-1]\n\tt.values = t.values[:n-1]\n\treturn x\n}", "func (s *state) pop(mark int) {\n\ts.vars = s.vars[0:mark]\n}", "func (a *ArrayObject) pop() Object {\n\tif len(a.Elements) < 1 {\n\t\treturn NULL\n\t}\n\n\tvalue := a.Elements[len(a.Elements)-1]\n\ta.Elements = a.Elements[:len(a.Elements)-1]\n\treturn value\n}", "func (w *MetricWindow) Pop() bitflow.Value {\n\tif w.Empty() {\n\t\treturn 0\n\t}\n\tval := w.data[w.first]\n\tw.first = w.inc(w.first)\n\tw.full = false\n\treturn val\n}", "func (s *Uint64) Pop() uint64 {\n\tfor val := range s.m {\n\t\tdelete(s.m, val)\n\t\treturn val\n\t}\n\treturn 0\n}", "func (s *Stack) Pop() (value interface{}) {\n\n if s.size > 0 {\n\n value, s.top = s.top.value, s.top.next\n\n s.size--\n\n return\n\n }\n\n return nil\n\n}", "func (h *heap) pop() int {\n\t\n\treturnVal := h.getValueAtIndex(1);\n\tcurrent :=1 \n\t\n\t//set last to first position and decrese length\n\th.s[0] = h.getValueAtIndex(h.length)\n\th.length = h.length-1\n\n\t\n\tfor getLeftIndex(current) <= h.length {\n\t\tleft := getLeftIndex(current)\n\t\tright := getRightIndex(current)\n\t\tmove := left\n\t\t\n\t\t//if right is smaller \n\t\tif (right <= h.length && h.getValueAtIndex(left) > h.getValueAtIndex(right)) {\n\t\t\tmove = right\n\t\t}\n\n\t\t//swap\n\t\tif h.getValueAtIndex(current) >= h.getValueAtIndex(move) {\n\t\t\th.s[current-1], h.s[move-1] = h.s[move-1], h.s[current-1]\n\t\t}\n\n\t\tcurrent = move\n\t}\n\n\treturn returnVal\n}", "func (l *List) Pop() (v Value, err error) {\n\tif l.tail == nil {\n\t\terr = errEmpty\n\t} else {\n\t\tv = l.tail.Value\n\t\tl.tail = l.tail.prev\n\t\tif l.tail == nil {\n\t\t\tl.head = nil\n\t\t}\n\t}\n\treturn v, err\n}", "func (this *MyStack) Pop() int {\n\tfor this.current.Qsize() != 1 {\n\t\tthis.backup.push(this.current.pop())\n\t}\n\tres := this.current.pop()\n\tthis.current, this.backup = this.backup, this.current\n\n\treturn res\n}", "func (cq *cQT) PopBack() (el T, ok bool) {\n\tvar zero T\n\tif cq.s == cq.e {\n\t\treturn zero, false\n\t}\n\tcq.e--\n\tel = cq.b[cq.e&cq.m]\n\tcq.b[cq.e&cq.m] = zero\n\treturn el, true\n}", "func (this *MyStack) Pop() int {\n\tret := this.Head.Val\n\tthis.Head = this.Head.Next\n\tif this.Head != nil {\n\t\tthis.Head.Pre = nil\n\t}\n\tthis.Len--\n\treturn ret\n}", "func (this *MyStack) Pop() int {\n\tif this.top == nil {return -1}\n\tr := this.top.Val\n\tthis.top.Next, this.top = nil, this.top.Next // 这里注意把pop的节点的Next置为nil,防止内存泄露\n\treturn r\n}", "func (s *Int64) Pop() int64 {\n\tfor val := range s.m {\n\t\tdelete(s.m, val)\n\t\treturn val\n\t}\n\treturn 0\n}", "func (a *MovAvg) pop() {\n\tp := a.q[a.r]\n\tfor i := range a.sum {\n\t\ta.sum[i] -= p.v[i]\n\t}\n\tif a.r++; a.r == len(a.q) {\n\t\ta.r = 0\n\t}\n}", "func (s *StackInt) Pop() int {\nlength := len(s.s)\nres := s.s[length-1]\ns.s = s.s[:length-1]\nreturn res\n}", "func (this *MyStack) Pop() int {\n\tans := this.Ele[this.Len-1]\n\tthis.Ele = this.Ele[:this.Len-1]\n\tthis.Len--\n\treturn ans\n}", "func (heap *MinHeap) Pop() int {\n\tvalue := heap.Heap[0]\n\theap.Heap[0] = heap.Count - 1\n\theap.Heap[heap.Count-1] = 0\n\theap.Count--\n\theap.heapifyDown()\n\treturn value\n}", "func (h *minPath) Pop() interface{} {\n\told := *h\n\tn := len(old)\n\tx := old[n-1]\n\t*h = old[0 : n-1]\n\treturn x\n}", "func (h *heap) pop() int {\n\tr := h.H[0];\n\th.V--;\n\th.H[0] = h.H[h.V];\n\tif h.V > 1 {\n\t\th.bubble_down(0);\n\t}\n\treturn r;\n}", "func (s *stack) pop() int {\n\tl := len(s.items)\n\tremovedItem := s.items[l-1]\n\ts.items = s.items[:l-1]\n\treturn removedItem\n}", "func (this *MyQueue) Pop() int {\n\tv := this.Stack[0]\n\tthis.Stack = this.Stack[1:]\n\treturn v\n}", "func (p *path) Pop() interface{} {\n\told := *p\n\tn := len(old)\n\tx := old[n-1]\n\t*p = old[0 : n-1]\n\treturn x\n}", "func (s *stack) pop() {\n\ts.items = s.items[:len(s.items)-1]\n}", "func (s *items) pop() (out Item) {\n\tindex := len(*s) - 1\n\tout = (*s)[index]\n\t(*s)[index] = nil\n\t*s = (*s)[:index]\n\treturn\n}", "func (vector *Vector) Pop() {\n\tvar element interface{}\n\telement, *vector = (*vector)[len(*vector)-1], (*vector)[:len(*vector)-1]\n\t// Note: dropping element here.\n\t_ = element\n}", "func (a *Array) Pop() interface{} {\n\tdefer func() {\n\t\ta.Data = a.Data[:a.Length-1]\n\t\ta.Length--\n\t}()\n\treturn a.Data[a.Length-1]\n}", "func (que *Queue) Pop() string {\n\tnode := que.values[0]\n\tque.values = que.values[1:]\n\treturn node\n}", "func (s *Queue) Pop() interface{} {\n\tif s.IsEmpty() {\n\t\tpanic(\"Pop on empty queue\")\n\t} else {\n\t\tcurrent_head := s.head\n\t\tval := current_head.val\n\t\ts.head = current_head.previous\n\t\tcurrent_head.val = nil\n\t\treturn val\n\t}\n}", "func (s *SliceOfUint) Pop() uint {\n\tpoppedItem := s.items[len(s.items)-1]\n\ts.items = s.items[:len(s.items)-1]\n\treturn poppedItem\n}", "func (s *Stack) Pop() (value interface{}) {\r\n\tif s.size > 0 {\r\n\t\tvalue, s.top = s.top.value, s.top.next\r\n\t\ts.size--\r\n\t\treturn value\r\n\t}\r\n\treturn nil\r\n}", "func (s *Storage) RPop() *list.Element {\r\n\tele := s.Back()\r\n\tif ele != nil {\r\n\t\ts.Remove(ele)\r\n\t}\r\n\treturn ele\r\n}", "func (this *MyQueue) Pop() int {\n x := this.q[0]\n this.q = this.q[1:]\n return x\n}", "func (this *MyStack) Pop() int {\n\tfor this.wareHouse.Size() > 1 {\n\t\tthis.backup.Push(this.wareHouse.Pop())\n\t}\n\tval := this.wareHouse.Pop()\n\tthis.wareHouse, this.backup = this.backup, this.wareHouse\n\treturn val\n}", "func (s *Stack) Pop() interface{} {\n\tv := s.v[len(s.v)]\n\ts.v = s.v[:len(s.v)-1]\n\treturn v\n}", "func (t *Thread) Pop() Value {\n\tt.sp--\n\treturn t.stack[t.sp]\n}", "func (s *stack) pop() {\n\tif s.isEmpty() {\n\t\tfmt.Println(\"Stack Underflows\")\n\t\treturn\n\t}\n\t*s = (*s)[:len(*s)-1]\n}", "func (this *Stack) Pop() interface{} {\n\tif this.length == 0 {\n\t\treturn nil\n\t}\n\n\tn := this.top\n\tthis.top = n.prev\n\tthis.length--\n\treturn n.value\n}", "func (vm *VM) bufferPop() (string, error) {\n\tcurrentBuffer := vm.buffer\n\tif currentBuffer == nil {\n\t\treturn \"\", ErrorBufferEmpty\n\t}\n\tvm.buffer = currentBuffer.previous\n\treturn currentBuffer.value, nil\n}", "func (this *MyStack) Pop() int {\n\tx := this.Queue[0]\n\tthis.Queue = this.Queue[1:]\n\treturn x\n}", "func (g *Generator) popField() {\n\tg.fieldStack = g.fieldStack[:len(g.fieldStack)-1]\n}", "func (s *Stack) Pop() interface{} {\r\n\tn := len(s.stk)\r\n\tvalue := s.stk[n-1]\r\n\ts.stk = s.stk[:n-1]\r\n\treturn value\r\n}", "func (v *Data) Pop() PicData {\n\treturn v.Remove(len(*v) - 1)\n}", "func (l *list) Pop() {\n\tl.elements = l.elements[:len(l.elements)-1]\n}", "func (s *Stack) Pop() int {\n\tif s.length == 0 {\n\t\treturn MIN\n\t}\n\n\tn := s.top\n\ts.top = n.prev\n\ts.length--\n\treturn n.value\n}", "func (recv *Value) Unset() {\n\tC.g_value_unset((*C.GValue)(recv.native))\n\n\treturn\n}", "func (s *StackF64) pop() (float64, error) {\n\tif s.top == 0 {\n\t\terr := fmt.Errorf(\"stack is empty\")\n\t\treturn 0, err\n\t}\n\ts.top--\n\treturn s.data[s.top], nil\n}", "func (self *Queue)Pop()interface{}{\r\n\tdefer self.popkey.Release()\r\n\tself.popkey.Get()\t\r\n\te:=self.list.Front()\r\n\tif e!=nil {\r\n\t\tself.list.Remove(e)\r\n\t\treturn e.Value\r\n\t}else{\r\n\t\treturn e\r\n\t}\r\n}", "func (s *orderedItems) Pop() interface{} {\n\told := *s\n\tn := len(old)\n\tx := old[n-1]\n\t*s = old[0 : n-1]\n\treturn x\n}", "func (s *Stack) Pop() (value interface{}) {\n\tif s.size > 0 {\n\t\tvalue, s.top = s.top.value, s.top.next\n\t\ts.size--\n\t\treturn\n\t}\n\treturn nil\n}", "func (s *Stack) Pop() (value interface{}) {\n\tif s.size > 0 {\n\t\tvalue, s.top = s.top.value, s.top.next\n\t\ts.size--\n\t\treturn\n\t}\n\treturn nil\n}", "func (s *SliceOfByte) Pop() byte {\n\tpoppedItem := s.items[len(s.items)-1]\n\ts.items = s.items[:len(s.items)-1]\n\treturn poppedItem\n}", "func (self *Dll) popBack() *node{\n\n\tret := self.tail.prev\n\ttemp := ret.prev\n\ttemp.setNext(self.tail)\n\tself.tail.setPrev(temp)\n\n\tret.setPrev(nil)\n\tret.setNext(nil)\n\n\tself.len -= 1\n\n\treturn ret\n}", "func (tb *TreeBuilder) Pop() {\n if debug.DEBUG {\n fmt.Println(\"<<<<<<<<<<<<<<< START POP NODE <<<<<<<<<<<<<<<\")\n defer fmt.Println(\" <<<<<<<<<<<<<<< DONE POP NODE <<<<<<<<<<<<<<<\")\n }\n if debug.DEBUG {\n fmt.Println(len(tb.stack), tb.node)\n }\n tb.stack, tb.node = tb.stack[:len(tb.stack)-1], tb.stack[len(tb.stack)-1]\n if debug.DEBUG {\n fmt.Println(len(tb.stack))\n }\n}", "func (s *Stack) Pop() (item float64) {\n\ts.Length--\n\titem = s.Items[s.Length]\n\ts.Items = s.Items[:s.Length]\n\treturn\n}", "func (stack *Stack) Pop() int {\n\tif stack.length == 0 {\n\t\treturn 0\n\t}\n\ttop := stack.top\n\tstack.top = top.prev\n\tstack.length--\n\treturn top.value\n}", "func (s *Stack) Pop() (value Game) {\n\tif s.size > 0 {\n\t\tvalue, s.top = s.top.value, s.top.next\n\t\ts.size--\n\t\treturn\n\t}\n\treturn NullGame()\n}", "func (s *children) pop() (out *node) {\n\tindex := len(*s) - 1\n\tout = (*s)[index]\n\t(*s)[index] = nil\n\t*s = (*s)[:index]\n\treturn\n}", "func (stack *Stack) Pop() (value interface{}) {\n\tif stack.size > 0 {\n\t\tvalue, stack.top = stack.top.value, stack.top.next\n\t\tstack.size--\n\t\treturn\n\t}\n\treturn nil\n}", "func (s *Stack) Pop() interface{} {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\tif s.length == 0 {\n\t\treturn nil\n\t}\n\tn := s.top\n\ts.top = n.prev\n\ts.length--\n\treturn n.value\n}", "func (s *Stack) Pop() (value interface{}) {\n\tif s.size > 0 {\n\t\ts.top, value = s.top.next, s.top.value\n\t\ts.elements = s.elements[:s.size-1]\n\t\ts.size--\n\t\treturn\n\t}\n\treturn nil\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.last == nil {\n\t\treturn 0, ErrEmptyList\n\t}\n\n\tdata := l.last.Val\n\n\tif l.last.Prev() == nil {\n\t\tl.head = nil\n\t\tl.last = nil\n\t} else {\n\t\tl.last.Prev().next = nil\n\t\tl.last = l.last.Prev()\n\t}\n\n\treturn data, nil\n}", "func (heap *maxheap) Pop() interface{} {\n\told := *heap\n\tn := len(old)\n\n\titem := old[n-1]\n\told[n-1] = nil\n\titem.index = -1\n\n\t*heap = old[0 : n-1]\n\n\treturn item\n}", "func (pq *PrioQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\tx := old[n-1]\n\t*pq = old[0 : n-1]\n\treturn x\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.tail == nil {\n\t\treturn nil, ErrEmptyList\n\t}\n\n\tval := l.tail.Val\n\tl.tail = l.tail.prev\n\n\tif l.tail == nil {\n\t\tl.head = nil\n\t} else {\n\t\tl.tail.next = nil\n\t}\n\n\treturn val, nil\n}", "func (s *SliceOfInt8) Pop() int8 {\n\tpoppedItem := s.items[len(s.items)-1]\n\ts.items = s.items[:len(s.items)-1]\n\treturn poppedItem\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.Len == 0 {\n\t\treturn nil, ErrEmptyList\n\t}\n\tv := l.tail.Val\n\tl.tail = l.tail.prev\n\tl.Len--\n\tif l.Len == 0 {\n\t\tl.head = nil\n\t} else {\n\t\tl.tail.next = nil\n\t}\n\treturn v, nil\n}", "func (s *Stack) Pop() int {\n\tlength := len(s.items) - 1\n\ttoRemove := s.items[length]\n\ts.items = s.items[:length]\n\treturn toRemove\n}", "func (que *QueueUsingStack) Remove() int {\r\n\tvar value int\r\n\tif que.stk2.IsEmpty() == false {\r\n\t\tvalue = que.stk2.Pop().(int)\r\n\t\treturn value\r\n\t}\r\n\r\n\t// Move elements from stk1 to stk2 to reverse the order.\r\n\tfor que.stk1.IsEmpty() == false {\r\n\t\tvalue = que.stk1.Pop().(int)\r\n\t\tque.stk2.Push(value)\r\n\t}\r\n\r\n\tvalue = que.stk2.Pop().(int)\r\n\treturn value\r\n}", "func (s *stack) Pop() []byte {\n\tif len(*s) == 0 {\n\t\treturn nil\n\t}\n\n\tv := (*s)[len(*s)-1]\n\t*s = (*s)[:len(*s)-1]\n\n\treturn v\n}", "func (h *IntMaxHeap) Pop() interface{} {\n\told := *h\n\tn := len(old)\n\tx := old[n-1]\n\t*h = old[0 : n-1]\n\treturn x\n}", "func (t *queueStorage) Pop() interface{} {\n\tn := len(*t)\n\tres := (*t)[n-1]\n\t*t = (*t)[:n-1]\n\treturn res\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.last == nil {\n\t\treturn nil, ErrEmptyList\n\t}\n\tn := l.last\n\tif l.first == n {\n\t\tl.first = nil\n\t}\n\tl.last = n.prev\n\tif l.last != nil {\n\t\tl.last.next = nil\n\t}\n\treturn n.Val, nil\n}", "func (this *Stack) Pop() (string, time.Time) {\n\tif this.length == 0 {\n\t\tvar t time.Time\n\t\treturn \"\", t\n\t}\n\n\tn := this.top\n\tthis.top = n.prev\n\tthis.length--\n\treturn n.value, n.time_stamp\n}", "func (s *SimpleStack) Pop() (val interface{}, err error) {\n\tif s.isEmpty() {\n\t\terr = errors.New(\"stack is empty\")\n\t\treturn\n\t}\n\tval = s.data[s.top]\n\ts.top--\n\treturn\n}", "func (pq *MaxPQ) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (self *OperandStack) PopSlot() Slot {\n\tself.top--\n\tvalue := self.slots[self.top]\n\tself.slots[self.top].Num = 0\n\tself.slots[self.top].Ref = nil\n\treturn value\n}", "func (s *SliceOfUint8) Pop() uint8 {\n\tpoppedItem := s.items[len(s.items)-1]\n\ts.items = s.items[:len(s.items)-1]\n\treturn poppedItem\n}", "func PopValue_Helper(unset bool, param map[string]*Stack, vble string) (err_code int, err_str string) {\n\terr_code = 0\n\terr_str = \"\"\n\n\tst_Val, ok := param[vble]\n\n\tif unset == true {\n\t\t// Unset the enire stack for given parameter\n\t\tif ok {\n\t\t\tfor st_Val.Len() > 0 {\n\t\t\t\t_, err_code, err_str := st_Val.Pop()\n\t\t\t\tif err_code != 0 {\n\t\t\t\t\treturn err_code, err_str\n\t\t\t\t}\n\t\t\t}\n\t\t\t//While unsetting also delete the stack for the\n\t\t\t//given variable.\n\t\t\tdelete(param, vble)\n\t\t} else {\n\t\t\terr_code = errors.NO_SUCH_PARAM\n\t\t\terr_str = \" \" + vble + \" \"\n\t\t}\n\t} else {\n\t\t//To pop a value from the input stack\n\t\tif ok {\n\t\t\t_, err_code, err_str = st_Val.Pop()\n\n\t\t\t// If after popping the stack is now empty, then delete the stack.\n\t\t\t// We dont need to check for stack empty here because ok will be false\n\t\t\t// if the stack is empty. So it will return Parameter doesnt exist.\n\t\t\tif st_Val.Len() == 0 {\n\t\t\t\tdelete(param, vble)\n\t\t\t}\n\t\t} else {\n\t\t\terr_code = errors.NO_SUCH_PARAM\n\t\t\terr_str = \" \" + vble + \" \"\n\t\t}\n\t}\n\treturn\n\n}", "func (this *MyQueue) Pop() int {\n\tr := this.q[len(this.q)-1]\n\tthis.q = this.q[:len(this.q)-1]\n\treturn r\n}", "func (vm *VM) opPop(instr []uint16) int {\n\tif len(vm.stack) == 0 {\n\t\t// error\n\t\tvm.Status = \"opPop has empty stack!\"\n\t\treturn 0\n\t}\n\n\tv := vm.stack[len(vm.stack)-1]\n\tvm.stack = vm.stack[:len(vm.stack)-1]\n\ta, _, _ := vm.getAbc(instr)\n\tvm.registers[a] = v\n\treturn 2\n}", "func (gdt *Array) PopBack() Variant {\n\targ0 := gdt.getBase()\n\n\tret := C.go_godot_array_pop_back(GDNative.api, arg0)\n\n\treturn Variant{base: &ret}\n\n}", "func (list *List) Pop() string {\n\tsize := list.Len() - 1\n\n\tif size == -1 {\n\t\tpanic(\"Trying to pop from an empty List\")\n\t}\n\n\tstr := list.data[size]\n\tlist.data = list.data[:size]\n\n\treturn str\n}", "func (sm *StackMax) Pop() (int, error) {\n\tif sm.Empty() {\n\t\treturn -1, ErrstackEmpty\n\t}\n\n\ttop, _ := sm.Top()\n\n\tsm.length--\n\tsm.container = sm.container[:sm.length]\n\tsm.maxer = sm.maxer[:sm.length]\n\treturn top, nil\n}", "func (v *Int32Vec) Pop() int32 {\n\treturn v.Remove(len(*v) - 1)\n}", "func (d *Deck) PopBack() (string, error) {\n\tif d.head == d.tail {\n\t\treturn \"\", fmt.Errorf(\"nothing to pop\")\n\t}\n\td.tail -= inv\n\tif d.tail < 0 {\n\t\td.tail = cap(d.deck) - 1\n\t}\n\tres := d.deck[d.tail]\n\td.deck[d.tail] = \"\"\n\treturn res, nil\n}", "func (h *stringCounterHeap) Pop() interface{} {\n\told := *h\n\tn := len(old)\n\tx := old[n-1]\n\t*h = old[0 : n-1]\n\treturn x\n}", "func (h *MinHeap) Remove() int {\n\th.swap(0, len(h.Heap)-1)\n\tvalueToRemove := h.Heap[len(h.Heap)-1]\n\th.Heap = h.Heap[:len(h.Heap)-1]\n\th.siftDown(0, len(h.Heap)-1)\n\t// fmt.Printf(\"value to remove: %v, heap: %v\\n\", valueToRemove, h.Heap)\n\treturn valueToRemove\n}", "func (q *Stack) Pop() string {\n\ts := *q\n\tlast := s[len(s)-1]\n\t*q = s[:len(s)-1]\n\treturn last\n}" ]
[ "0.65451896", "0.63795406", "0.6210631", "0.611558", "0.6060175", "0.60053587", "0.60033137", "0.599745", "0.5968359", "0.5965431", "0.59515804", "0.5949218", "0.59340066", "0.5931988", "0.5921974", "0.5912604", "0.59104484", "0.5904659", "0.58952945", "0.58862823", "0.58814156", "0.5878878", "0.5878328", "0.5871161", "0.5846682", "0.5845975", "0.583997", "0.58324665", "0.58112514", "0.57994926", "0.57978547", "0.5795617", "0.5789191", "0.5785325", "0.5780669", "0.5774699", "0.576821", "0.57656926", "0.5763896", "0.5752191", "0.5745741", "0.5744217", "0.5731287", "0.5727834", "0.57255745", "0.5721752", "0.5718276", "0.5717384", "0.57060486", "0.5695128", "0.56941795", "0.5690887", "0.56850916", "0.5683109", "0.5681639", "0.5680558", "0.56745136", "0.56729674", "0.56722903", "0.5658058", "0.5654197", "0.5654197", "0.5652949", "0.56496155", "0.5645506", "0.56426746", "0.5634381", "0.5625", "0.5613295", "0.5612814", "0.5602094", "0.5598388", "0.55932206", "0.55925816", "0.55913544", "0.558613", "0.5582607", "0.55801636", "0.5575313", "0.5569855", "0.5563337", "0.5562106", "0.55576915", "0.5555504", "0.5547717", "0.554665", "0.55442166", "0.5540085", "0.55363154", "0.5534703", "0.5534209", "0.5532006", "0.55256253", "0.55192506", "0.55126673", "0.55113214", "0.5498944", "0.5496875", "0.5495752", "0.5486104" ]
0.5653878
62
GetInstalledReleases gets the installed Helm releases in a given namespace
func GetInstalledReleases(o GetInstalledReleasesOptions) ([]ReleaseSpec, error) { tillerNamespace := "kube-system" labels := "OWNER=TILLER,STATUS in (DEPLOYED,FAILED)" if !o.IncludeFailed { labels = strings.Replace(labels, "FAILED", "", -1) } storage, err := getTillerStorage(o.KubeContext, tillerNamespace) if err != nil { return nil, err } var releaseSpecs []ReleaseSpec list, err := listReleases(o.KubeContext, o.Namespace, storage, tillerNamespace, labels) if err != nil { return nil, err } for _, releaseData := range list { if releaseData.status != "DEPLOYED" { continue } var releaseSpec ReleaseSpec releaseSpec.ReleaseName = releaseData.name releaseSpec.ChartName = releaseData.chart releaseSpec.ChartVersion = releaseData.version releaseSpecs = append(releaseSpecs, releaseSpec) } if !o.IncludeFailed { return releaseSpecs, nil } for _, releaseData := range list { if releaseData.status != "FAILED" { continue } exists := false for _, rs := range releaseSpecs { if releaseData.name == rs.ReleaseName { exists = true break } } if exists { continue } var releaseSpec ReleaseSpec releaseSpec.ReleaseName = releaseData.name releaseSpec.ChartName = releaseData.chart releaseSpec.ChartVersion = releaseData.version releaseSpecs = append(releaseSpecs, releaseSpec) } return releaseSpecs, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (sfc *stepFactoryCreator) getInstalledReleases() (map[string]kymahelm.ReleaseStatus, error) {\n\n\texistingReleases := make(map[string]kymahelm.ReleaseStatus)\n\n\treleases, err := sfc.helmClient.ListReleases()\n\tif err != nil {\n\t\treturn nil, errors.New(\"Helm error: \" + err.Error())\n\t}\n\n\tif releases != nil {\n\t\tlog.Println(\"Helm releases list:\")\n\n\t\tfor _, release := range releases {\n\t\t\tvar lastDeployedRev int\n\n\t\t\tstatusCode := release.Status\n\t\t\tif statusCode == kymahelm.StatusDeployed {\n\t\t\t\tlastDeployedRev = release.CurrentRevision\n\t\t\t} else {\n\t\t\t\tlastDeployedRev, err = sfc.helmClient.ReleaseDeployedRevision(kymahelm.NamespacedName{Namespace: release.Namespace, Name: release.Name})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, errors.New(\"Helm error: \" + err.Error())\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlog.Printf(\"%s status: %s, last deployed revision: %d\", release.Name, statusCode, lastDeployedRev)\n\t\t\texistingReleases[release.Name] = kymahelm.ReleaseStatus{\n\t\t\t\tStatus: statusCode,\n\t\t\t\tCurrentRevision: release.CurrentRevision,\n\t\t\t\tLastDeployedRevision: lastDeployedRev,\n\t\t\t}\n\t\t}\n\t}\n\treturn existingReleases, nil\n}", "func (a *Agent) ListReleases(\n\tctx context.Context,\n\tnamespace string,\n\tfilter *types.ReleaseListFilter,\n) ([]*release.Release, error) {\n\tctx, span := telemetry.NewSpan(ctx, \"helm-list-releases\")\n\tdefer span.End()\n\n\ttelemetry.WithAttributes(span,\n\t\ttelemetry.AttributeKV{Key: \"namespace\", Value: namespace},\n\t)\n\n\tlsel := fmt.Sprintf(\"owner=helm,status in (%s)\", strings.Join(filter.StatusFilter, \",\"))\n\n\t// list secrets\n\tsecretList, err := a.K8sAgent.Clientset.CoreV1().Secrets(namespace).List(\n\t\tcontext.Background(),\n\t\tv1.ListOptions{\n\t\t\tLabelSelector: lsel,\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, telemetry.Error(ctx, span, err, \"error getting secret list\")\n\t}\n\n\t// before decoding to helm release, only keep the latest releases for each chart\n\tlatestMap := make(map[string]corev1.Secret)\n\n\tfor _, secret := range secretList.Items {\n\t\trelName, relNameExists := secret.Labels[\"name\"]\n\n\t\tif !relNameExists {\n\t\t\tcontinue\n\t\t}\n\n\t\tid := fmt.Sprintf(\"%s/%s\", secret.Namespace, relName)\n\n\t\tif currLatest, exists := latestMap[id]; exists {\n\t\t\t// get version\n\t\t\tcurrVersionStr, currVersionExists := currLatest.Labels[\"version\"]\n\t\t\tversionStr, versionExists := secret.Labels[\"version\"]\n\n\t\t\tif versionExists && currVersionExists {\n\t\t\t\tcurrVersion, currErr := strconv.Atoi(currVersionStr)\n\t\t\t\tversion, err := strconv.Atoi(versionStr)\n\t\t\t\tif currErr == nil && err == nil && currVersion < version {\n\t\t\t\t\tlatestMap[id] = secret\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlatestMap[id] = secret\n\t\t}\n\t}\n\n\tchartList := []string{}\n\tres := make([]*release.Release, 0)\n\n\tfor _, secret := range latestMap {\n\t\trel, isErr, err := kubernetes.ParseSecretToHelmRelease(secret, chartList)\n\n\t\tif !isErr && err == nil {\n\t\t\tres = append(res, rel)\n\t\t}\n\t}\n\n\treturn res, nil\n}", "func LabelInstalledReleases(localReleases string, githubReleases []string, output []string) []string {\n\n\t// Parse helm semver releases\n\tlsToSlice := []string{}\n\tlsToSlice = strings.Split(localReleases, \"\\n\")\n\tlsToSlice = lsToSlice[:len(lsToSlice)-1]\n\tfor _, v := range lsToSlice {\n\t\tlocalReleases = strings.Trim(v, \"helm-\")\n\n\t\t// Erase release from list if it's already installed\n\t\tfor k, j := range githubReleases {\n\t\t\tif localReleases == j {\n\t\t\t\tgithubReleases = append(githubReleases[:k], githubReleases[k+1:]...)\n\t\t\t}\n\t\t}\n\n\t\tlocalReleases = fmt.Sprintf(\"%-15s %s\", localReleases, installed)\n\t\toutput = append(output, localReleases)\n\t}\n\t// Descending order of installed releases\n\tsort.Sort(sort.Reverse(sort.StringSlice(output)))\n\treturn output\n}", "func getHelmsmanReleases() map[string]map[string]bool {\n\tvar lines []string\n\treleases := make(map[string]map[string]bool)\n\tstorageBackend := \"configmap\"\n\n\tif s.Settings.StorageBackend == \"secret\" {\n\t\tstorageBackend = \"secret\"\n\t}\n\n\tnamespaces := make([]string, len(s.Namespaces))\n\ti := 0\n\tfor s, v := range s.Namespaces {\n\t\tif v.InstallTiller || v.UseTiller {\n\t\t\tnamespaces[i] = s\n\t\t\ti++\n\t\t}\n\t}\n\tnamespaces = namespaces[0:i]\n\tif v, ok := s.Namespaces[\"kube-system\"]; !ok || (ok && (v.UseTiller || v.InstallTiller)) {\n\t\tnamespaces = append(namespaces, \"kube-system\")\n\t}\n\n\tfor _, ns := range namespaces {\n\t\tcmd := command{\n\t\t\tCmd: \"bash\",\n\t\t\tArgs: []string{\"-c\", \"kubectl get \" + storageBackend + \" -n \" + ns + \" -l MANAGED-BY=HELMSMAN\"},\n\t\t\tDescription: \"getting helm releases which are managed by Helmsman in namespace [[ \" + ns + \" ]].\",\n\t\t}\n\n\t\texitCode, output := cmd.exec(debug, verbose)\n\n\t\tif exitCode != 0 {\n\t\t\tlogError(output)\n\t\t}\n\t\tif strings.ToUpper(\"No resources found.\") != strings.ToUpper(strings.TrimSpace(output)) {\n\t\t\tlines = strings.Split(output, \"\\n\")\n\t\t}\n\n\t\tfor i := 0; i < len(lines); i++ {\n\t\t\tif lines[i] == \"\" || strings.HasSuffix(strings.TrimSpace(lines[i]), \"AGE\") {\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tfields := strings.Fields(lines[i])\n\t\t\t\tif _, ok := releases[ns]; !ok {\n\t\t\t\t\treleases[ns] = make(map[string]bool)\n\t\t\t\t}\n\t\t\t\treleases[ns][fields[0][0:strings.LastIndex(fields[0], \".v\")]] = true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn releases\n}", "func cmdGetReleases(ccmd *cobra.Command, args []string) {\n\taplSvc := apl.NewClient()\n\toutput := runGetCommand(args, aplSvc.Releases.Get)\n\tif output != nil {\n\t\tfields := []string{\"ID\", \"StackID\", \"Version\", \"CreatedTime\"}\n\t\tprintTableResultsCustom(output.(apl.Release), fields)\n\t}\n}", "func (ctx *Context) ListInstalledPackages(name, version, release string) ([]*yum.Package, error) {\n\tvar err error\n\tinstalled, err := ctx.listInstalledPackages()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfilter := func(pkg [3]string) bool { return true }\n\tif release != \"\" && version != \"\" && name != \"\" {\n\t\tre_name := regexp.MustCompile(name)\n\t\tre_vers := regexp.MustCompile(version)\n\t\tre_release := regexp.MustCompile(release)\n\t\tfilter = func(pkg [3]string) bool {\n\t\t\treturn re_name.MatchString(pkg[0]) &&\n\t\t\t\tre_vers.MatchString(pkg[1]) &&\n\t\t\t\tre_release.MatchString(pkg[2])\n\t\t}\n\t} else if version != \"\" && name != \"\" {\n\t\tre_name := regexp.MustCompile(name)\n\t\tre_vers := regexp.MustCompile(version)\n\t\tfilter = func(pkg [3]string) bool {\n\t\t\treturn re_name.MatchString(pkg[0]) &&\n\t\t\t\tre_vers.MatchString(pkg[1])\n\t\t}\n\n\t} else if name != \"\" {\n\t\tre_name := regexp.MustCompile(name)\n\t\tfilter = func(pkg [3]string) bool {\n\t\t\treturn re_name.MatchString(pkg[0])\n\t\t}\n\t}\n\n\tpkgs := make([]*yum.Package, 0, len(installed))\n\tfor _, pkg := range installed {\n\t\tif !filter(pkg) {\n\t\t\tcontinue\n\t\t}\n\t\tp, err := ctx.yum.FindLatestProvider(pkg[0], pkg[1], pkg[2])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpkgs = append(pkgs, p)\n\t}\n\tif len(pkgs) <= 0 {\n\t\tfmt.Printf(\"** No Match found **\\n\")\n\t\treturn nil, err\n\t}\n\n\tsort.Sort(yum.Packages(pkgs))\n\tfor _, pkg := range pkgs {\n\t\tfmt.Printf(\"%s\\n\", pkg.ID())\n\t}\n\treturn pkgs, err\n}", "func GetReleases(dbOwner, dbFolder, dbName string) (releases map[string]ReleaseEntry, err error) {\n\tdbQuery := `\n\t\tSELECT release_list\n\t\tFROM sqlite_databases\n\t\tWHERE user_id = (\n\t\t\t\tSELECT user_id\n\t\t\t\tFROM users\n\t\t\t\tWHERE lower(user_name) = lower($1)\n\t\t\t)\n\t\t\tAND folder = $2\n\t\t\tAND db_name = $3`\n\terr = pdb.QueryRow(dbQuery, dbOwner, dbFolder, dbName).Scan(&releases)\n\tif err != nil {\n\t\tlog.Printf(\"Error when retrieving releases for database '%s%s%s': %v\\n\", dbOwner, dbFolder, dbName, err)\n\t\treturn nil, err\n\t}\n\tif releases == nil {\n\t\t// If there aren't any releases yet, return an empty set instead of nil\n\t\treleases = make(map[string]ReleaseEntry)\n\t}\n\treturn releases, nil\n}", "func (ctx *Context) listInstalledPackages() ([][3]string, error) {\n\tlist := make([][3]string, 0)\n\targs := []string{\"-qa\", \"--queryformat\", \"%{NAME} %{VERSION} %{RELEASE}\\n\"}\n\tout, err := ctx.rpm(false, args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tscan := bufio.NewScanner(bytes.NewBuffer(out))\n\tfor scan.Scan() {\n\t\tline := scan.Text()\n\t\tpkg := strings.Split(line, \" \")\n\t\tif len(pkg) != 3 {\n\t\t\terr = fmt.Errorf(\"lbpkr: invalid line %q\", line)\n\t\t\treturn nil, err\n\t\t}\n\t\tfor i, p := range pkg {\n\t\t\tpkg[i] = strings.Trim(p, \" \\n\\r\\t\")\n\t\t}\n\t\tlist = append(list, [3]string{pkg[0], pkg[1], pkg[2]})\n\t}\n\terr = scan.Err()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn list, err\n}", "func GetVersions(ctx context.Context, config *packages.Autoupdate) ([]version.Version, *string) {\n\tname := *config.Target\n\tresp, err := http.Get(util.GetProtocol() + \"://registry.npmjs.org/\" + name)\n\tutil.Check(err)\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tutil.Check(err)\n\n\tvar r Registry\n\tutil.Check(json.Unmarshal(body, &r))\n\n\tversions := make([]version.Version, 0)\n\tfor k, v := range r.Versions {\n\t\tif v, ok := v.(map[string]interface{}); ok {\n\t\t\tdist := v[\"dist\"].(map[string]interface{})\n\t\t\ttarball := dist[\"tarball\"].(string)\n\n\t\t\tif timeInt, ok := r.TimeStamps[k]; ok {\n\t\t\t\tif timeStr, ok := timeInt.(string); ok {\n\t\t\t\t\t// parse time.Time from time stamp\n\t\t\t\t\ttimeStamp, err := time.Parse(time.RFC3339, timeStr)\n\t\t\t\t\tutil.Check(err)\n\n\t\t\t\t\tif !version.IsVersionIgnored(config, k) {\n\t\t\t\t\t\tversions = append(versions, version.Version{\n\t\t\t\t\t\t\tVersion: k,\n\t\t\t\t\t\t\tTarball: tarball,\n\t\t\t\t\t\t\tDate: timeStamp,\n\t\t\t\t\t\t\tSource: \"npm\",\n\t\t\t\t\t\t})\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlog.Printf(\"%s: version %s is ignored\\n\", name, k)\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tpanic(fmt.Errorf(\"no time stamp for npm version %s/%s\", name, k))\n\t\t}\n\t}\n\n\t// attempt to get latest version according to npm\n\tif latest, ok := r.DistTags[\"latest\"]; ok {\n\t\treturn versions, &latest\n\t}\n\treturn versions, nil\n}", "func (in *IstioClient) GetNamespacePodsByRelease(namespace string, release string) (*v1.PodList, error) {\n\tfmt.Println(\"Called method GetNamespacePodsByRelease\")\n\tpodList, err := in.k8s.CoreV1().Pods(namespace).List(meta_v1.ListOptions{LabelSelector: \"release=\" + release})\n\tpods := podList.Items\n\tif err == nil {\n\t\tfor _, pod := range pods {\n\t\t\tfmt.Println(\"Pod found: \", pod.Name, \", release: \", pod.Labels[\"release\"])\n\t\t}\n\t}\n\n\treturn podList, err\n}", "func (h *Helm3Client) ListReleasesNames(labelSelector map[string]string) ([]string, error) {\n\tlabelsSet := make(kblabels.Set)\n\tfor k, v := range labelSelector {\n\t\tlabelsSet[k] = v\n\t}\n\tlabelsSet[\"owner\"] = \"helm\"\n\n\tlist, err := h.KubeClient.CoreV1().\n\t\tSecrets(h.Namespace).\n\t\tList(context.TODO(), metav1.ListOptions{LabelSelector: labelsSet.AsSelector().String()})\n\tif err != nil {\n\t\th.LogEntry.Debugf(\"helm: list of releases ConfigMaps failed: %s\", err)\n\t\treturn nil, err\n\t}\n\n\tuniqNamesMap := make(map[string]struct{})\n\tfor _, secret := range list.Items {\n\t\treleaseName, hasKey := secret.Labels[\"name\"]\n\t\tif hasKey && releaseName != \"\" {\n\t\t\tuniqNamesMap[releaseName] = struct{}{}\n\t\t}\n\t}\n\n\t// Do not return ignored release.\n\tdelete(uniqNamesMap, app.HelmIgnoreRelease)\n\n\tuniqNames := make([]string, 0)\n\tfor name := range uniqNamesMap {\n\t\tuniqNames = append(uniqNames, name)\n\t}\n\n\tsort.Strings(uniqNames)\n\treturn uniqNames, nil\n}", "func GetOnlineVersions() ([]string, error) {\n\tversions := make([]string, 0)\n\tbaseURL := \"https://releases.hashicorp.com/terraform/\"\n\n\tlogger.Debug(\"Listing all available versions of kubectl to download\")\n\tresponse, err := http.Get(baseURL)\n\n\tif err != nil {\n\t\treturn versions, err\n\t}\n\n\tdefer response.Body.Close()\n\n\tif response.StatusCode == http.StatusOK {\n\t\tbodyBytes, err := ioutil.ReadAll(response.Body)\n\n\t\tif err != nil {\n\t\t\treturn versions, err\n\t\t}\n\n\t\tbodyString := string(bodyBytes)\n\t\tre := regexp.MustCompile(\"/terraform/[0-9]*.[0-9]*.[0-9]*/\")\n\t\tmatch := re.FindAllStringSubmatch(bodyString, 20)\n\t\tfor _, v := range match {\n\t\t\tversions = append(versions, strings.ReplaceAll(strings.ReplaceAll(v[0], \"terraform/\", \"\"), \"/\", \"\"))\n\t\t}\n\t\treturn versions, nil\n\t}\n\n\treturn versions, nil\n}", "func (repo BoshDirectorRepository) GetReleases() (releases models.Releases, apiResponse net.ApiResponse) {\n\tresponse := []releaseResponse{}\n\n\tpath := \"/releases\"\n\tapiResponse = repo.gateway.GetResource(repo.config.TargetURL+path, repo.config.Username, repo.config.Password, &response)\n\tif apiResponse.IsNotSuccessful() {\n\t\treturn\n\t}\n\n\tlist := []*models.Release{}\n\tfor _, resource := range response {\n\t\tlist = append(list, resource.ToModel())\n\t}\n\treleases = models.Releases(list)\n\n\treturn\n}", "func CheckOnlineReleases(url string) ([]string, error) {\n\n\t// Perform request to get helm releases\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif resp.StatusCode != 200 {\n\t\terr := errors.New(string(body))\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Unmarshall JSON response\n\tvar versions []Version\n\tjson.Unmarshal(body, &versions)\n\n\t// Convert Struct to array and sort it\n\tgithubReleases := []string{}\n\tfor _, v := range versions {\n\t\tgithubReleases = append(githubReleases, v.Tag)\n\t}\n\treturn githubReleases, nil\n}", "func (m *UserTeamwork) GetInstalledApps()([]UserScopeTeamsAppInstallationable) {\n val, err := m.GetBackingStore().Get(\"installedApps\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]UserScopeTeamsAppInstallationable)\n }\n return nil\n}", "func GetRelease(cmd *cobra.Command, args []string) {\n\treq := &helmmanager.ListReleaseReq{}\n\n\tif !flagAll {\n\t\treq.Size = common.GetUint32P(uint32(flagNum))\n\t}\n\tif len(args) > 0 {\n\t\treq.Size = common.GetUint32P(1)\n\t\treq.Name = common.GetStringP(args[0])\n\t}\n\treq.ClusterID = &flagCluster\n\treq.Namespace = &flagNamespace\n\n\tc := newClientWithConfiguration()\n\tr, err := c.Release().List(cmd.Context(), req)\n\tif err != nil {\n\t\tfmt.Printf(\"get release failed, %s\\n\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\tif flagOutput == outputTypeJson {\n\t\tprinter.PrintReleaseInJson(r)\n\t\treturn\n\t}\n\n\tprinter.PrintReleaseInTable(flagOutput == outputTypeWide, r)\n}", "func GetReleases(sandboxName string) ([]Release, error) {\n\treturn getReleases(sandboxName)\n}", "func (a KubectlLayerApplier) GetOrphanedHelmReleases(ctx context.Context, layer layers.Layer) (foundHrs map[string]*helmctlv2.HelmRelease, err error) {\n\tlogging.TraceCall(a.getLog(layer))\n\tdefer logging.TraceExit(a.getLog(layer))\n\n\thrList := &helmctlv2.HelmReleaseList{}\n\tvar labels client.HasLabels = []string{orphanedLabel}\n\tlistOptions := &client.ListOptions{}\n\tlabels.ApplyToList(listOptions)\n\n\terr = a.client.List(ctx, hrList, listOptions)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"%s - failed to list orphaned HelmRelease resources '%s'\", logging.CallerStr(logging.Me), layer.GetName())\n\t}\n\n\tfoundHrs = map[string]*helmctlv2.HelmRelease{}\n\tfor _, hr := range hrList.Items {\n\t\tif layer.GetName() != layerOwner(&hr) { // nolint: scopelint // ok\n\t\t\tfoundHrs[getLabel(hr.ObjectMeta)] = hr.DeepCopy()\n\t\t}\n\t}\n\treturn foundHrs, nil\n}", "func GetAllKymaReleases() []*SupportedRelease {\n\treturn []*SupportedRelease{\n\t\tRelease111,\n\t\tRelease110,\n\t\tRelease19,\n\t}\n}", "func (r *GitLabRelease) ListReleases(ctx context.Context) ([]string, error) {\n\tversions := []string{}\n\topt := &gitlab.ListReleasesOptions{\n\t\tPerPage: 100, // max\n\t}\n\n\tfor {\n\t\treleases, resp, err := r.api.ProjectListReleases(ctx, r.owner, r.project, opt)\n\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to list releases for %s/%s: %s\", r.owner, r.project, err)\n\t\t}\n\n\t\tfor _, release := range releases {\n\t\t\tv := tagNameToVersion(release.TagName)\n\t\t\tversions = append(versions, v)\n\t\t}\n\t\tif resp.NextPage == 0 {\n\t\t\tbreak\n\t\t}\n\t\topt.Page = resp.NextPage\n\t}\n\n\treturn versions, nil\n}", "func (a KubectlLayerApplier) GetResources(ctx context.Context, layer layers.Layer) (resources []kraanv1alpha1.Resource, err error) {\n\tlogging.TraceCall(a.getLog(layer))\n\tdefer logging.TraceExit(a.getLog(layer))\n\n\tsourceHrs, clusterHrs, err := a.GetSourceAndClusterHelmReleases(ctx, layer)\n\tif err != nil {\n\t\treturn nil, errors.WithMessagef(err, \"%s - failed to get helm releases\", logging.CallerStr(logging.Me))\n\t}\n\n\tfor key, source := range sourceHrs {\n\t\tresource := kraanv1alpha1.Resource{\n\t\t\tNamespace: source.GetNamespace(),\n\t\t\tName: source.GetName(),\n\t\t\tKind: \"helmreleases.helm.toolkit.fluxcd.io\",\n\t\t\tLastTransitionTime: metav1.Now(),\n\t\t\tStatus: \"Unknown\",\n\t\t}\n\t\thr, ok := clusterHrs[key]\n\t\tif ok {\n\t\t\ta.logDebug(\"HelmRelease in AddonsLayer source directory and on cluster\", layer, logging.GetObjKindNamespaceName(source)...)\n\t\t\tresources = append(resources, a.getResourceInfo(layer, resource, hr.Status.Conditions))\n\t\t} else {\n\t\t\t// this resource exists in the source directory but not on the cluster\n\t\t\ta.logDebug(\"HelmRelease in AddonsLayer source directory but not on cluster\", layer, logging.GetObjKindNamespaceName(source)...)\n\t\t\tresource.Status = kraanv1alpha1.NotDeployed\n\t\t\tresources = append(resources, resource)\n\t\t}\n\t}\n\n\tfor key, hr := range clusterHrs {\n\t\tresource := kraanv1alpha1.Resource{\n\t\t\tNamespace: hr.GetNamespace(),\n\t\t\tName: hr.GetName(),\n\t\t\tKind: \"helmreleases.helm.toolkit.fluxcd.io\",\n\t\t\tLastTransitionTime: metav1.Now(),\n\t\t\tStatus: \"Unknown\",\n\t\t}\n\t\t_, ok := sourceHrs[key]\n\t\tif !ok {\n\t\t\ta.logDebug(\"HelmRelease not in AddonsLayer source directory but on cluster\", layer, \"name\", clusterHrs[key])\n\t\t\tresources = append(resources, a.getResourceInfo(layer, resource, hr.Status.Conditions))\n\t\t}\n\t}\n\treturn resources, err\n}", "func (client *Client) GetDeploymentVersions(namespace, deplName string) (model.DeploymentsList, error) {\n\tvar list model.DeploymentsList\n\treturn list, client.RestAPI.Get(rest.Rq{\n\t\tResult: &list,\n\t\tURL: rest.URL{\n\t\t\tPath: deploymentVersionsPath,\n\t\t\tParams: rest.P{\n\t\t\t\t\"namespace\": namespace,\n\t\t\t\t\"deployment\": deplName,\n\t\t\t},\n\t\t},\n\t})\n}", "func (a *Agent) GetRelease(\n\tctx context.Context,\n\tname string,\n\tversion int,\n\tgetDeps bool,\n) (*release.Release, error) {\n\tctx, span := telemetry.NewSpan(ctx, \"helm-get-release\")\n\tdefer span.End()\n\n\ttelemetry.WithAttributes(span,\n\t\ttelemetry.AttributeKV{Key: \"name\", Value: name},\n\t\ttelemetry.AttributeKV{Key: \"version\", Value: version},\n\t\ttelemetry.AttributeKV{Key: \"getDeps\", Value: getDeps},\n\t)\n\n\t// Namespace is already known by the RESTClientGetter.\n\tcmd := action.NewGet(a.ActionConfig)\n\n\tcmd.Version = version\n\n\trelease, err := cmd.Run(name)\n\tif err != nil {\n\t\treturn nil, telemetry.Error(ctx, span, err, \"error running get release\")\n\t}\n\n\tif getDeps && release.Chart != nil && release.Chart.Metadata != nil {\n\t\tfor _, dep := range release.Chart.Metadata.Dependencies {\n\t\t\t// only search for dependency if it passes the condition specified in Chart.yaml\n\t\t\tif dep.Enabled {\n\t\t\t\tdepExists := false\n\n\t\t\t\tfor _, currDep := range release.Chart.Dependencies() {\n\t\t\t\t\t// we just case on name for now -- there might be edge cases we're missing\n\t\t\t\t\t// but this will cover 99% of cases\n\t\t\t\t\tif dep != nil && currDep != nil && dep.Name == currDep.Name() {\n\t\t\t\t\t\tdepExists = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif !depExists {\n\t\t\t\t\tdepChart, err := loader.LoadChartPublic(ctx, dep.Repository, dep.Name, dep.Version)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, telemetry.Error(ctx, span, err, fmt.Sprintf(\"Error retrieving chart dependency %s/%s-%s\", dep.Repository, dep.Name, dep.Version))\n\t\t\t\t\t}\n\n\t\t\t\t\trelease.Chart.AddDependency(depChart)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn release, err\n}", "func (a *Agent) GetReleaseHistory(\n\tctx context.Context,\n\tname string,\n) ([]*release.Release, error) {\n\tctx, span := telemetry.NewSpan(ctx, \"helm-get-release-history\")\n\tdefer span.End()\n\n\ttelemetry.WithAttributes(span,\n\t\ttelemetry.AttributeKV{Key: \"name\", Value: name},\n\t)\n\n\tcmd := action.NewHistory(a.ActionConfig)\n\n\treturn cmd.Run(name)\n}", "func (c *Client) List(p ListParameters) ([]Release, error) {\n\tresponse, err := c.client.ListReleases(p.Options()...) // TODO Paging.\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tvar releases []Release\n\tif response != nil && response.Releases != nil {\n\t\tfor _, item := range response.Releases {\n\t\t\treleases = append(releases, *(fromHelm(item)))\n\t\t}\n\t}\n\treturn releases, nil\n}", "func (r *ChatInstalledAppsCollectionRequest) Get(ctx context.Context) ([]TeamsAppInstallation, error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\treturn r.Paging(ctx, \"GET\", query, nil)\n}", "func cmdListReleases(ccmd *cobra.Command, args []string) {\n\taplSvc := apl.NewClient()\n\toutput := runListCommand(&releaseParams, aplSvc.Releases.List)\n\tif output != nil {\n\t\tfields := []string{\"ID\", \"StackID\", \"Version\", \"CreatedTime\"}\n\t\tprintTableResultsCustom(output.([]apl.Release), fields)\n\t}\n}", "func (d *Deployment) GetDeployedVersions() []string {\n\n\tvar versionList []string\n\n\t// Everything in the release directory is an available version.\n\tif fi, err := ioutil.ReadDir(d.releaseDir); err == nil {\n\t\tfor _, v := range fi {\n\t\t\tversionList = append(versionList, v.Name())\n\t\t}\n\t}\n\n\treturn versionList\n}", "func installedPackages(state client.GooGetState) packageMap {\n\tpm := make(packageMap)\n\tfor _, p := range state {\n\t\tpm[p.PackageSpec.Name+\".\"+p.PackageSpec.Arch] = p.PackageSpec.Version\n\t}\n\treturn pm\n}", "func (u *uninstaller) findCrdNamesForRelease(namespace string) (crdNames []string, err error) {\n\tlister, err := u.helmClient.ReleaseList(namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treleases, err := lister.Run()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(releases) == 0 {\n\t\treturn nil, NoReleaseForCRDs\n\t} else if len(releases) > 1 {\n\t\treturn nil, MultipleReleasesForCRDs\n\t}\n\n\trel := releases[0]\n\tfor _, crd := range rel.Chart.CRDObjects() {\n\t\tresource, err := makeUnstructured(string(crd.File.Data))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tcrdNames = append(crdNames, resource.GetName())\n\t}\n\n\treturn crdNames, nil\n}", "func (t *tkgctl) GetTanzuKubernetesReleases(tkrName string) ([]runv1alpha1.TanzuKubernetesRelease, error) {\n\ttkrs, err := t.tkgClient.GetTanzuKubernetesReleases(tkrName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn tkrs, nil\n}", "func (p *preImpl) installedPackages(ctx context.Context) (map[string]struct{}, error) {\n\tctx, st := timing.Start(ctx, \"installed_packages\")\n\tdefer st.End()\n\n\tout, err := p.arc.Command(ctx, \"pm\", \"list\", \"packages\").Output(testexec.DumpLogOnError)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"listing packages failed\")\n\t}\n\n\tpkgs := make(map[string]struct{})\n\tfor _, pkg := range strings.Split(strings.TrimSpace(string(out)), \"\\n\") {\n\t\t// |pm list packages| prepends \"package:\" to installed packages. Not needed.\n\t\tn := strings.TrimPrefix(pkg, \"package:\")\n\t\tpkgs[n] = struct{}{}\n\t}\n\treturn pkgs, nil\n}", "func releases(ctx context.Context, c *github.Client, org string, project string) ([]*release, error) {\n\tvar result []*release\n\n\topts := &github.ListOptions{PerPage: 100}\n\n\tklog.Infof(\"Downloading releases for %s/%s ...\", org, project)\n\n\tfor page := 1; page != 0; {\n\t\topts.Page = page\n\t\trs, resp, err := c.Repositories.ListReleases(ctx, org, project, opts)\n\t\tif err != nil {\n\t\t\treturn result, err\n\t\t}\n\n\t\tpage = resp.NextPage\n\t\tuntil := time.Now()\n\n\t\tfor _, r := range rs {\n\t\t\tname := r.GetName()\n\t\t\tif name == \"\" {\n\t\t\t\tname = r.GetTagName()\n\t\t\t}\n\n\t\t\trel := &release{\n\t\t\t\tName: name,\n\t\t\t\tDraft: r.GetDraft(),\n\t\t\t\tPrerelease: r.GetPrerelease(),\n\t\t\t\tPublishedAt: r.GetPublishedAt().Time,\n\t\t\t\tActiveUntil: until,\n\t\t\t\tDownloads: map[string]int{},\n\t\t\t\tDownloadRatios: map[string]float64{},\n\t\t\t}\n\n\t\t\tfor _, a := range r.Assets {\n\t\t\t\tif ignoreAssetRe.MatchString(a.GetName()) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\trel.Downloads[a.GetName()] = a.GetDownloadCount()\n\t\t\t\trel.DownloadsTotal += int64(a.GetDownloadCount())\n\t\t\t}\n\n\t\t\tif !rel.Draft && !rel.Prerelease {\n\t\t\t\tuntil = rel.PublishedAt\n\t\t\t}\n\n\t\t\tresult = append(result, rel)\n\t\t}\n\t}\n\n\tfor _, r := range result {\n\t\tr.DaysActive = r.ActiveUntil.Sub(r.PublishedAt).Hours() / 24\n\t\tr.DownloadsPerDay = float64(r.DownloadsTotal) / r.DaysActive\n\n\t\tfor k, v := range r.Downloads {\n\t\t\tr.DownloadRatios[k] = float64(v) / float64(r.DownloadsTotal)\n\t\t}\n\t}\n\n\treturn result, nil\n}", "func (s *Server) GetAvailablePackageVersions(ctx context.Context, request *corev1.GetAvailablePackageVersionsRequest) (*corev1.GetAvailablePackageVersionsResponse, error) {\n\tlog.Infof(\"+fluxv2 GetAvailablePackageVersions [%v]\", request)\n\tdefer log.Infof(\"-fluxv2 GetAvailablePackageVersions\")\n\n\tif request.GetPkgVersion() != \"\" {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.Unimplemented,\n\t\t\t\"not supported yet: request.GetPkgVersion(): [%v]\",\n\t\t\trequest.GetPkgVersion())\n\t}\n\n\tpackageRef := request.GetAvailablePackageRef()\n\tnamespace := packageRef.GetContext().GetNamespace()\n\tif namespace == \"\" || packageRef.GetIdentifier() == \"\" {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"required context or identifier not provided\")\n\t}\n\n\tcluster := packageRef.Context.Cluster\n\tif cluster != \"\" && cluster != s.kubeappsCluster {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.Unimplemented,\n\t\t\t\"not supported yet: request.AvailablePackageRef.Context.Cluster: [%v]\",\n\t\t\tcluster)\n\t}\n\n\trepoName, chartName, err := pkgutils.SplitChartIdentifier(packageRef.Identifier)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Infof(\"Requesting chart [%s] in namespace [%s]\", chartName, namespace)\n\trepo := types.NamespacedName{Namespace: namespace, Name: repoName}\n\tchart, err := s.getChart(ctx, repo, chartName)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if chart != nil {\n\t\t// found it\n\t\treturn &corev1.GetAvailablePackageVersionsResponse{\n\t\t\tPackageAppVersions: pkgutils.PackageAppVersionsSummary(\n\t\t\t\tchart.ChartVersions,\n\t\t\t\ts.versionsInSummary),\n\t\t}, nil\n\t} else {\n\t\treturn nil, status.Errorf(codes.Internal, \"unable to retrieve versions for chart: [%s]\", packageRef.Identifier)\n\t}\n}", "func (d *RetryDownloader) GetReleases() ([]*Release, error) {\n\tvar (\n\t\treleases []*Release\n\t\terr error\n\t)\n\n\terr = d.retry(func() error {\n\t\treleases, err = d.Downloader.GetReleases()\n\t\treturn err\n\t})\n\n\treturn releases, err\n}", "func (a KubectlLayerApplier) GetSourceAndClusterHelmReleases(ctx context.Context, layer layers.Layer) (sourceHrs, clusterHrs map[string]*helmctlv2.HelmRelease, err error) {\n\tlogging.TraceCall(a.getLog(layer))\n\tdefer logging.TraceExit(a.getLog(layer))\n\n\tsourceHrs, err = a.getSourceHelmReleases(layer)\n\tif err != nil {\n\t\treturn nil, nil, errors.WithMessagef(err, \"%s - failed to get source helm releases\", logging.CallerStr(logging.Me))\n\t}\n\n\tclusterHrs, err = a.GetHelmReleases(ctx, layer)\n\tif err != nil {\n\t\treturn nil, nil, errors.WithMessagef(err, \"%s - failed to get helm releases\", logging.CallerStr(logging.Me))\n\t}\n\treturn sourceHrs, clusterHrs, nil\n}", "func (client *Client) GetDeploymentList(namespace string) (model.DeploymentsList, error) {\n\tvar depls model.DeploymentsList\n\terr := client.RestAPI.Get(rest.Rq{\n\t\tResult: &depls,\n\t\tURL: rest.URL{\n\t\t\tPath: deploymentsPath,\n\t\t\tParams: rest.P{\n\t\t\t\t\"namespace\": namespace,\n\t\t\t},\n\t\t},\n\t})\n\treturn depls, err\n}", "func CheckLocalReleases(helmVersionPath string) (string, error) {\n\n\t// List installed helm releases\n\tls := &BashCmd{\n\t\tCmd: \"ls\",\n\t\tArgs: []string{\"-1\"},\n\t\tExecPath: helmVersionPath,\n\t}\n\tlocalReleases, err := ExecBashCmd(ls)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn localReleases, nil\n}", "func IsHelmReleaseInstalled(releaseName string, cfg *helm.Configuration) bool {\n\thistClient := helm.NewHistory(cfg)\n\thistClient.Max = 1\n\t\n\tif release, err := histClient.Run(releaseName); release != nil {\n\t\tdebug(\"release %s is installed\", releaseName)\n\t\treturn true\n\t} else {\n\t\tdebug(\"query release %s returned error %v\", releaseName, err)\n\t\treturn false\n\t}\n}", "func (api *RestAPI) GetRelease(epicID string) ([]ReleaseItem, error) {\n\tresults := []ReleaseItem{}\n\tissue, err := api.getIssue(epicID)\n\tif err != nil {\n\t\treturn results, err\n\t}\n\n\tscanner := bufio.NewScanner(strings.NewReader(issue.Fields.Description.(string)))\n\tfor scanner.Scan() {\n\t\tline := strings.ToLower(scanner.Text())\n\t\tif strings.Contains(line, \"/app#/projects\") {\n\t\t\tparts := strings.Split(line, \"/\")\n\t\t\tresults = append(results, ReleaseItem{Project: parts[5], Version: parts[7]})\n\t\t}\n\t}\n\treturn results, nil\n}", "func ListReleases(ctx *context.APIContext) {\n\t// swagger:operation GET /repos/{owner}/{repo}/releases repository repoListReleases\n\t// ---\n\t// summary: List a repo's releases\n\t// produces:\n\t// - application/json\n\t// parameters:\n\t// - name: owner\n\t// in: path\n\t// description: owner of the repo\n\t// type: string\n\t// required: true\n\t// - name: repo\n\t// in: path\n\t// description: name of the repo\n\t// type: string\n\t// required: true\n\t// - name: draft\n\t// in: query\n\t// description: filter (exclude / include) drafts, if you dont have repo write access none will show\n\t// type: boolean\n\t// - name: pre-release\n\t// in: query\n\t// description: filter (exclude / include) pre-releases\n\t// type: boolean\n\t// - name: per_page\n\t// in: query\n\t// description: page size of results, deprecated - use limit\n\t// type: integer\n\t// deprecated: true\n\t// - name: page\n\t// in: query\n\t// description: page number of results to return (1-based)\n\t// type: integer\n\t// - name: limit\n\t// in: query\n\t// description: page size of results\n\t// type: integer\n\t// responses:\n\t// \"200\":\n\t// \"$ref\": \"#/responses/ReleaseList\"\n\tlistOptions := utils.GetListOptions(ctx)\n\tif listOptions.PageSize == 0 && ctx.FormInt(\"per_page\") != 0 {\n\t\tlistOptions.PageSize = ctx.FormInt(\"per_page\")\n\t}\n\n\topts := repo_model.FindReleasesOptions{\n\t\tListOptions: listOptions,\n\t\tIncludeDrafts: ctx.Repo.AccessMode >= perm.AccessModeWrite || ctx.Repo.UnitAccessMode(unit.TypeReleases) >= perm.AccessModeWrite,\n\t\tIncludeTags: false,\n\t\tIsDraft: ctx.FormOptionalBool(\"draft\"),\n\t\tIsPreRelease: ctx.FormOptionalBool(\"pre-release\"),\n\t}\n\n\treleases, err := repo_model.GetReleasesByRepoID(ctx, ctx.Repo.Repository.ID, opts)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetReleasesByRepoID\", err)\n\t\treturn\n\t}\n\trels := make([]*api.Release, len(releases))\n\tfor i, release := range releases {\n\t\tif err := release.LoadAttributes(ctx); err != nil {\n\t\t\tctx.Error(http.StatusInternalServerError, \"LoadAttributes\", err)\n\t\t\treturn\n\t\t}\n\t\trels[i] = convert.ToAPIRelease(ctx, ctx.Repo.Repository, release)\n\t}\n\n\tfilteredCount, err := repo_model.CountReleasesByRepoID(ctx.Repo.Repository.ID, opts)\n\tif err != nil {\n\t\tctx.InternalServerError(err)\n\t\treturn\n\t}\n\n\tctx.SetLinkHeader(int(filteredCount), listOptions.PageSize)\n\tctx.SetTotalCountHeader(filteredCount)\n\tctx.JSON(http.StatusOK, rels)\n}", "func (c *Clients) GetKubeResources(r *ReleaseData) (map[string]interface{}, error) {\n\tlog.Printf(\"Getting resources for %s\", r.Name)\n\tif r.Manifest == \"\" {\n\t\treturn nil, errors.New(\"manifest not provided in the request\")\n\t}\n\tresources := map[string]interface{}{}\n\tinfos, err := c.getManifestDetails(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnamespace := \"default\"\n\tfor _, info := range infos {\n\t\tvar spec interface{}\n\t\tkind := info.Object.GetObjectKind().GroupVersionKind().GroupKind().Kind\n\t\tv := kube.AsVersioned(info)\n\t\tif checkSize(resources, ResourcesOutputSize) {\n\t\t\tbreak\n\t\t}\n\n\t\tif stringInSlice(reflect.TypeOf(v).String(), ResourcesOutputIgnoredTypes) {\n\t\t\tcontinue\n\t\t}\n\t\tinner := make(map[string]interface{})\n\t\tname, ok := ScanFromStruct(v, \"ObjectMeta.Name\")\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tns, ok := ScanFromStruct(v, \"ObjectMeta.Namespace\")\n\t\tif ok {\n\t\t\tnamespace = fmt.Sprint(ns)\n\t\t}\n\t\tif stringInSlice(reflect.TypeOf(v).String(), ResourcesOutputIncludedSpec) {\n\t\t\tspec, ok = ScanFromStruct(v, \"Spec\")\n\t\t\tif ok {\n\t\t\t\tspec = structToMap(spec)\n\t\t\t}\n\t\t}\n\t\tstatus, ok := ScanFromStruct(v, \"Status\")\n\t\tif ok {\n\t\t\tstatus = structToMap(status)\n\t\t}\n\t\tinner = map[string]interface{}{\n\t\t\tfmt.Sprint(name): map[string]interface{}{\n\t\t\t\t\"Namespace\": namespace,\n\t\t\t\t\"Spec\": spec,\n\t\t\t\t\"Status\": status,\n\t\t\t},\n\t\t}\n\t\tif IsZero(resources[kind]) {\n\t\t\tresources[kind] = map[string]interface{}{}\n\t\t}\n\t\ttemp := resources[kind].(map[string]interface{})\n\t\tresources[kind] = mergeMaps(temp, inner)\n\t}\n\treturn resources, nil\n}", "func (hc *Actions) ListReleases() ([]api.Stack, error) {\n\tactList := action.NewList(hc.Config)\n\treleases, err := actList.Run()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := []api.Stack{}\n\tfor _, rel := range releases {\n\t\tresult = append(result, api.Stack{\n\t\t\tID: rel.Name,\n\t\t\tName: rel.Name,\n\t\t\tStatus: string(rel.Info.Status),\n\t\t})\n\t}\n\treturn result, nil\n}", "func (operator *AccessOperator) ListReleaseByApp(cxt context.Context, appName, cfgsetName string) ([]*common.Release, error) {\n\t//query business and app first\n\tbusiness, app, err := getBusinessAndApp(operator, operator.Business, appName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfigSet, err := operator.innergetConfigSet(cxt, business.Bid, app.Appid, cfgsetName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif configSet == nil {\n\t\treturn nil, nil\n\t}\n\n\trequest := &accessserver.QueryHistoryReleasesReq{\n\t\tSeq: pkgcommon.Sequence(),\n\t\tBid: business.Bid,\n\t\tCfgsetid: configSet.Cfgsetid,\n\t\t//fix: list all release\n\t\t//Operator: operator.User,\n\t\tIndex: operator.index,\n\t\tLimit: operator.limit,\n\t}\n\tgrpcOptions := []grpc.CallOption{\n\t\tgrpc.WaitForReady(true),\n\t}\n\tresponse, err := operator.Client.QueryHistoryReleases(cxt, request, grpcOptions...)\n\tif err != nil {\n\t\tlogger.V(3).Infof(\"ListReleaseByApp failed, %s\", err.Error())\n\t\treturn nil, err\n\t}\n\tif response.ErrCode != common.ErrCode_E_OK {\n\t\tlogger.V(3).Infof(\"ListReleaseByApp all successfully, but response Err, %s\", response.ErrMsg)\n\t\treturn nil, fmt.Errorf(\"%s\", response.ErrMsg)\n\t}\n\treturn response.Releases, nil\n}", "func (s *ReleaseService) GetReleases(page, perPage uint) ([]*Release, error) {\n\tp := PaginateParams{}\n\tp.Limit, p.Offset = calculateLimitOffset(page, perPage)\n\treturn s.SearchReleases(\"\", \"\", p)\n}", "func (a App) GetVersions(name string) (VersionsResponse, error) {\n\tvar response VersionsResponse\n\turl := strings.Join([]string{\"/v2/apps\", name, \"versions\"}, \"/\")\n\n\tres, err := a.client.Request(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn response, err\n\t}\n\tdefer res.Body.Close()\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn response, err\n\t}\n\tjson.Unmarshal(body, &response)\n\treturn response, nil\n}", "func BeeReleasesInfo() (repos []Releases) {\n\tvar url = \"https://api.github.com/repos/beego/bee/releases\"\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tbeeLogger.Log.Warnf(\"Get bee releases from github error: %s\", err)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\tbodyContent, _ := ioutil.ReadAll(resp.Body)\n\tif err = json.Unmarshal(bodyContent, &repos); err != nil {\n\t\tbeeLogger.Log.Warnf(\"Unmarshal releases body error: %s\", err)\n\t\treturn\n\t}\n\treturn\n}", "func getList(p *Pkg) pkgList {\n\tinstallPkgs := pkgList{p.fullName()}\n\n\tfor _, pkg := range p.dependencies {\n\t\tinstallPkgs = append(installPkgs, pkg.fullName())\n\t}\n\n\treturn installPkgs\n}", "func (c *CLIUpdater) GetAvailableVersions(minVersion semver.Version) ([]string, error) {\n\treq := cloudpb.GetArtifactListRequest{\n\t\tArtifactName: \"cli\",\n\t\tArtifactType: getArtifactTypes(),\n\t\tLimit: 10,\n\t}\n\n\tclient, err := newATClient(c.cloudAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := client.GetArtifactList(context.Background(), &req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tversionList := make([]string, 0)\n\tfor _, art := range resp.Artifact {\n\t\tv := strings.TrimPrefix(art.VersionStr, \"v\")\n\t\t// FIXME: remove me before checkin.\n\t\tif !strings.HasPrefix(v, \"0\") {\n\t\t\tcontinue\n\t\t}\n\t\tversion := semver.MustParse(v)\n\t\tif minVersion.LT(version) {\n\t\t\tversionList = append(versionList, art.VersionStr)\n\t\t}\n\t}\n\treturn versionList, nil\n}", "func (taker *TakerGCP) ListVersions(rs *reportService) (versions []*appengine.Version, err error) {\n\tserviceService := appengine.NewAppsServicesVersionsService(taker.appEngine)\n\tif listResponse, listErr := serviceService.List(rs.application.gcpApplication.Id, rs.gcpService.Id).View(\"FULL\").Do(); listErr == nil {\n\t\tversions = listResponse.Versions\n\t} else {\n\t\terr = listErr\n\t}\n\treturn\n}", "func (f *Factory) findReleases(ctx context.Context, u *url.URL) ([]*claircore.Distribution, error) {\n\tdir, err := u.Parse(\"dists/\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"debian: unable to construct URL: %w\", err)\n\t}\n\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, dir.String(), nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"debian: unable to construct request: %w\", err)\n\t}\n\tres, err := f.c.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"debian: unable to do request: %w\", err)\n\t}\n\tdefer res.Body.Close()\n\tswitch res.StatusCode {\n\tcase http.StatusOK:\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"debian: unexpected status fetching %q: %s\", dir.String(), res.Status)\n\t}\n\tvar buf bytes.Buffer\n\tif _, err := buf.ReadFrom(res.Body); err != nil {\n\t\treturn nil, fmt.Errorf(\"debian: unable to read dists listing: %w\", err)\n\t}\n\tms := linkRegexp.FindAllStringSubmatch(buf.String(), -1)\n\n\tvar todos []*claircore.Distribution\nListing:\n\tfor _, m := range ms {\n\t\tdist := m[1]\n\t\tswitch {\n\t\tcase dist == \"\":\n\t\t\tcontinue\n\t\tcase dist[0] == '/', dist[0] == '?':\n\t\t\tcontinue\n\t\t}\n\t\tfor _, s := range skipList {\n\t\t\tif strings.Contains(dist, s) {\n\t\t\t\tcontinue Listing\n\t\t\t}\n\t\t}\n\t\tdist = strings.Trim(dist, \"/\")\n\t\trf, err := dir.Parse(path.Join(dist, `Release`))\n\t\tif err != nil {\n\t\t\tzlog.Info(ctx).\n\t\t\t\tErr(err).\n\t\t\t\tStringer(\"context\", dir).\n\t\t\t\tStr(\"target\", path.Join(dist, `Release`)).\n\t\t\t\tMsg(\"unable to construct URL\")\n\t\t\tcontinue\n\t\t}\n\t\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, rf.String(), nil)\n\t\tif err != nil {\n\t\t\tzlog.Info(ctx).\n\t\t\t\tErr(err).\n\t\t\t\tStringer(\"url\", rf).\n\t\t\t\tMsg(\"unable to construct request\")\n\t\t\tcontinue\n\t\t}\n\t\treq.Header.Set(\"range\", \"bytes=0-512\")\n\t\tres, err := f.c.Do(req)\n\t\tif err != nil {\n\t\t\tzlog.Info(ctx).\n\t\t\t\tErr(err).\n\t\t\t\tStringer(\"url\", rf).\n\t\t\t\tMsg(\"unable to do request\")\n\t\t\tcontinue\n\t\t}\n\t\tbuf.Reset()\n\t\tbuf.ReadFrom(res.Body)\n\t\tres.Body.Close()\n\t\tswitch res.StatusCode {\n\t\tcase http.StatusPartialContent, http.StatusOK:\n\t\tcase http.StatusNotFound: // Probably extremely old, it's fine.\n\t\t\tcontinue\n\t\tdefault:\n\t\t\tzlog.Info(ctx).\n\t\t\t\tStr(\"status\", res.Status).\n\t\t\t\tStringer(\"url\", rf).\n\t\t\t\tMsg(\"unexpected response\")\n\t\t\tcontinue\n\t\t}\n\t\ttp := textproto.NewReader(bufio.NewReader(io.MultiReader(&buf, bytes.NewReader([]byte(\"\\r\\n\\r\\n\")))))\n\t\th, err := tp.ReadMIMEHeader()\n\t\tif err != nil {\n\t\t\tzlog.Info(ctx).Err(err).Msg(\"unable to read MIME-ish headers\")\n\t\t\tcontinue\n\t\t}\n\t\tsv := h.Get(\"Version\")\n\t\tif sv == \"\" {\n\t\t\tzlog.Debug(ctx).Str(\"dist\", dist).Msg(\"no version assigned, skipping\")\n\t\t\tcontinue\n\t\t}\n\t\tvs := strings.Split(sv, \".\")\n\t\tif len(vs) == 1 {\n\t\t\tzlog.Debug(ctx).Str(\"dist\", dist).Msg(\"no version assigned, skipping\")\n\t\t\tcontinue\n\t\t}\n\t\tver, err := strconv.ParseInt(vs[0], 10, 32)\n\t\tif err != nil {\n\t\t\tzlog.Info(ctx).Err(err).Msg(\"unable to parse version\")\n\t\t\tcontinue\n\t\t}\n\n\t\ttodos = append(todos, mkDist(dist, int(ver)))\n\t}\n\n\treturn todos, nil\n}", "func (r *ReleaseConfig) GetVersionsBundles(imageDigests map[string]string) ([]anywherev1alpha1.VersionsBundle, error) {\n\tversionsBundles := []anywherev1alpha1.VersionsBundle{}\n\n\tcertManagerBundle, err := r.GetCertManagerBundle(imageDigests)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Error getting bundle for cert-manager\")\n\t}\n\n\tcoreClusterApiBundle, err := r.GetCoreClusterAPIBundle(imageDigests)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Error getting bundle for core cluster-api\")\n\t}\n\n\tkubeadmBootstrapBundle, err := r.GetKubeadmBootstrapBundle(imageDigests)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Error getting bundle for cluster-api kubeadm-bootstrap\")\n\t}\n\n\tkubeadmControlPlaneBundle, err := r.GetKubeadmControlPlaneBundle(imageDigests)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Error getting bundle for cluster-api kubeadm-control-plane\")\n\t}\n\n\tawsBundle, err := r.GetAwsBundle(imageDigests)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Error getting bundle for AWS infrastructure provider\")\n\t}\n\n\tdockerBundle, err := r.GetDockerBundle(imageDigests)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Error getting bundle for Docker infrastructure provider\")\n\t}\n\n\teksaBundle, err := r.GetEksaBundle(imageDigests)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Error getting bundle for eks-a tools component\")\n\t}\n\n\tciliumBundle, err := r.GetCiliumBundle(imageDigests)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Error getting bundle for Cilium\")\n\t}\n\n\tfluxBundle, err := r.GetFluxBundle(imageDigests)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Error getting bundle for Flux controllers\")\n\t}\n\n\tetcdadmBootstrapBundle, err := r.GetEtcdadmBootstrapBundle(imageDigests)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Error getting bundle for external Etcdadm bootstrap\")\n\t}\n\n\tetcdadmControllerBundle, err := r.GetEtcdadmControllerBundle(imageDigests)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Error getting bundle for external Etcdadm controller\")\n\t}\n\n\teksDReleaseMap, err := readEksDReleases(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbottlerocketSupportedK8sVersions, err := getBottlerocketSupportedK8sVersions(r, imageBuilderProjectSource)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Error getting supported Kubernetes versions for bottlerocket\")\n\t}\n\n\tfor channel, release := range eksDReleaseMap {\n\t\tif channel == \"latest\" || !existsInList(channel, bottlerocketSupportedK8sVersions) {\n\t\t\tcontinue\n\t\t}\n\t\treleaseNumber := release.(map[interface{}]interface{})[\"number\"]\n\t\treleaseNumberInt := releaseNumber.(int)\n\t\treleaseNumberStr := strconv.Itoa(releaseNumberInt)\n\n\t\tkubeVersion := release.(map[interface{}]interface{})[\"kubeVersion\"]\n\t\tkubeVersionStr := kubeVersion.(string)\n\t\tshortKubeVersion := kubeVersionStr[1:strings.LastIndex(kubeVersionStr, \".\")]\n\n\t\teksDReleaseBundle, err := r.GetEksDReleaseBundle(channel, kubeVersionStr, releaseNumberStr, imageDigests)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"Error getting bundle for eks-d %s-%s release bundle\", channel, releaseNumberStr)\n\t\t}\n\n\t\tvsphereBundle, err := r.GetVsphereBundle(channel, imageDigests)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"Error getting bundle for vSphere infrastructure provider\")\n\t\t}\n\n\t\tbottlerocketBootstrapBundle, err := r.GetBottlerocketBootstrapBundle(channel, releaseNumberStr, imageDigests)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"Error getting bundle for bottlerocket bootstrap\")\n\t\t}\n\n\t\tversionsBundle := anywherev1alpha1.VersionsBundle{\n\t\t\tKubeVersion: shortKubeVersion,\n\t\t\tEksD: eksDReleaseBundle,\n\t\t\tCertManager: certManagerBundle,\n\t\t\tClusterAPI: coreClusterApiBundle,\n\t\t\tBootstrap: kubeadmBootstrapBundle,\n\t\t\tControlPlane: kubeadmControlPlaneBundle,\n\t\t\tAws: awsBundle,\n\t\t\tVSphere: vsphereBundle,\n\t\t\tDocker: dockerBundle,\n\t\t\tEksa: eksaBundle,\n\t\t\tCilium: ciliumBundle,\n\t\t\tFlux: fluxBundle,\n\t\t\tExternalEtcdBootstrap: etcdadmBootstrapBundle,\n\t\t\tExternalEtcdController: etcdadmControllerBundle,\n\t\t\tBottleRocketBootstrap: bottlerocketBootstrapBundle,\n\t\t}\n\t\tversionsBundles = append(versionsBundles, versionsBundle)\n\t}\n\treturn versionsBundles, nil\n}", "func (p *Pilot) getInstalledPlugins(pilot *v1alpha1.Pilot) (sets.String, error) {\n\tstdout := new(bytes.Buffer)\n\tcmd := exec.Command(p.Options.ElasticsearchOptions.PluginBinary, \"list\")\n\tcmd.Env = p.env().Strings()\n\tcmd.Stdout = stdout\n\tcmd.Stderr = p.Options.StdErr\n\tif err := cmd.Run(); err != nil {\n\t\treturn nil, err\n\t}\n\tstrOutput := stdout.String()\n\tpluginsSlice := strings.Split(strOutput, \"\\n\")\n\treturn sets.NewString(pluginsSlice...), nil\n}", "func listInstalledUnits(ns string, suffix string) ([]string, error) {\n\targs := []string{\n\t\t\"list-units\",\n\t\t\"--no-legend\",\n\t\t\"--no-pager\",\n\t\tfmt.Sprintf(\"%s_*.%s\", ns, suffix),\n\t}\n\tout, err := exec.Command(\"systemctl\", args...).Output()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn parseListUnits(string(out), ns, suffix)\n}", "func (chs *ChartChangeSync) getCustomResourcesForMirror(mirror string) ([]helmfluxv1.HelmRelease, error) {\n\tvar hrs []helmfluxv1.HelmRelease\n\tlist, err := chs.hrLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, hr := range list {\n\t\tif hr.Spec.GitChartSource == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif mirror != mirrorName(hr.Spec.GitChartSource) {\n\t\t\tcontinue\n\t\t}\n\t\thrs = append(hrs, *hr)\n\t}\n\treturn hrs, nil\n}", "func (m *operatorCRDVersionMap) GetVersions() []string {\n\tversions := []string{}\n\tfor v := range m.versionMap {\n\t\tversions = append(versions, v)\n\t}\n\treturn versions\n}", "func getCatalogs(_ string) []string {\n\tvar (\n\t\terr error\n\t\tsession *Session\n\t\tclient orchestrator.OrchestratorClient\n\t\tres *orchestrator.ListCatalogsResponse\n\t)\n\n\tif session, err = ContinueSession(); err != nil {\n\t\tfmt.Printf(\"Error while retrieving the session. Please re-authenticate.\\n\")\n\t\treturn nil\n\t}\n\n\tclient = orchestrator.NewOrchestratorClient(session)\n\n\tif res, err = client.ListCatalogs(context.Background(), &orchestrator.ListCatalogsRequest{}); err != nil {\n\t\treturn []string{}\n\t}\n\n\tvar output []string\n\tfor _, v := range res.Catalogs {\n\t\toutput = append(output, fmt.Sprintf(\"%s\\t%s: %s\", v.Id, v.Name, v.Description))\n\t}\n\n\treturn output\n}", "func listReleaseChannelsHandler(c echo.Context) error {\n\tchannels, err := upgrade_client.ListReleaseChannels()\n\tif err != nil {\n\t\treturn handlers.HttpError(err)\n\t}\n\t// Return a deterministic ordering of channels\n\tsort.Strings(channels)\n\treturn c.JSON(http.StatusOK, channels)\n}", "func parseReleasesAPI() (releases, error) {\n\tr, err := http.Get(\"https://api.github.com/repos/eze-kiel/shaloc/releases\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer r.Body.Close()\n\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar rel releases\n\tif err = json.Unmarshal(body, &rel); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn rel, nil\n}", "func (c *Client) ListReleases(ctx context.Context) ([]*github.RepositoryRelease, error) {\n\tresult := []*github.RepositoryRelease{}\n\tpage := 1\n\tfor {\n\t\tassets, res, err := c.Repositories.ListReleases(context.TODO(), c.Owner, c.Repo, &github.ListOptions{Page: page})\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to list releases\")\n\t\t}\n\t\tif res.StatusCode != http.StatusOK {\n\t\t\treturn nil, errors.Errorf(\"list repository releases: invalid status code: %s\", res.Status)\n\t\t}\n\t\tresult = append(result, assets...)\n\t\tif res.NextPage <= page {\n\t\t\tbreak\n\t\t}\n\t\tpage = res.NextPage\n\t}\n\treturn result, nil\n}", "func (c Provider) Releases(params []string) (rs *results.ResultSet, err error) {\n\t// Query the API\n\tid := strings.Join(strings.Split(params[1], \"/\"), \"%2f\")\n\turl := fmt.Sprintf(TagsEndpoint, params[0], id)\n\tvar tags Tags\n\tif err = util.FetchJSON(url, \"releases\", &tags); err != nil {\n\t\treturn\n\t}\n\trs = tags.Convert(params[0], params[1])\n\treturn\n}", "func GetAllReleases(ctx context.Context, client models.Client, opts models.ListReleasesOptions) (Releases, error) {\n\tvar (\n\t\tvariables = map[string]interface{}{\n\t\t\t\"cursor\": (*githubv4.String)(nil),\n\t\t\t\"owner\": githubv4.String(opts.Owner),\n\t\t\t\"name\": githubv4.String(opts.Repository),\n\t\t}\n\n\t\treleases = []Release{}\n\t)\n\n\tfor {\n\t\tq := &QueryListReleases{}\n\t\tif err := client.Query(ctx, q, variables); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treleases = append(releases, q.Repository.Releases.Nodes...)\n\t\tif !q.Repository.Releases.PageInfo.HasNextPage {\n\t\t\tbreak\n\t\t}\n\t\tvariables[\"cursor\"] = q.Repository.Releases.PageInfo.EndCursor\n\t}\n\n\treturn releases, nil\n}", "func List(namespace string, c kubernetes.Interface) ([]appsv1.Deployment, error) {\n\tdList, err := c.AppsV1().Deployments(namespace).List(metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn dList.Items, nil\n}", "func (c *Client) AllReleases() ([]db.Release, error) {\n\tnames, err := c.names()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuiprogress.Start()\n\tbar := uiprogress.AddBar(len(names))\n\tbar.PrependFunc(func(b *uiprogress.Bar) string {\n\t\trate := float64(b.Current()) / b.TimeElapsed().Seconds()\n\t\tremainingCount := b.Total - b.Current()\n\t\tremainingTime := time.Duration(float64(remainingCount)/rate) * time.Second\n\n\t\treturn fmt.Sprintf(\n\t\t\t\"%v left (%.f/s)\",\n\t\t\tremainingTime,\n\t\t\trate,\n\t\t)\n\t})\n\treleases := make(chan db.Release)\n\tc.addReleases(names, releases, bar)\n\tclose(releases)\n\treturn releaseChanToSlice(releases), nil\n}", "func (s *Server) GetInstalledPackageResourceRefs(ctx context.Context, request *corev1.GetInstalledPackageResourceRefsRequest) (*corev1.GetInstalledPackageResourceRefsResponse, error) {\n\tpkgRef := request.GetInstalledPackageRef()\n\tcontextMsg := fmt.Sprintf(\"(cluster=%q, namespace=%q)\", pkgRef.GetContext().GetCluster(), pkgRef.GetContext().GetNamespace())\n\tidentifier := pkgRef.GetIdentifier()\n\tlog.Infof(\"+fluxv2 GetInstalledPackageResourceRefs %s %s\", contextMsg, identifier)\n\n\treturn resourcerefs.GetInstalledPackageResourceRefs(ctx, request, s.actionConfigGetter)\n}", "func retrievePackages(pkgSelector string) ([]string, error) {\n\tr := []string{}\n\tcmd := exec.Command(\"go\", \"list\", pkgSelector)\n\tvar stdout, stderr bytes.Buffer\n\tcmd.Stdout = &stdout\n\tcmd.Stderr = &stderr\n\terr := cmd.Run()\n\toutStr, errStr := string(stdout.Bytes()), string(stderr.Bytes())\n\tif err != nil {\n\t\treturn r, errors.New(errStr)\n\t}\n\n\tr = strings.Split(outStr, \"\\n\")\n\n\treturn r[:len(r)-1], nil\n}", "func printReleases(m map[string]string) string {\n\trelease := parseUrlforStu(m[\"release\"])\n\tvar output string\n\tfor _, thing := range release.Items {\n\t\toutput += strFormatOut(thing)\n\t\toutput += \"\\n\"\n\t}\n\treturn output\n}", "func (responses Responses) GetReleaseNames() []string {\n\tvar releaseNames []string\n\tfor _, response := range responses {\n\t\treleaseNames = append(releaseNames, response.ReleaseName)\n\t}\n\treturn releaseNames\n}", "func PullDeployments(namespaceString string, deploymentStrings []string) (err error, deploymentList appsv1.DeploymentList) {\n\n err, deploymentList = kube.ListDeployments(namespaceString, deploymentStrings)\n\n if err != nil {\n fmt.Printf(\"Error getting deployment list: %s\\n\", err)\n os.Exit(1)\n }\n\n return err, deploymentList\n}", "func ListDeployments(filter *string, kubeConfig []byte) (*rls.ListReleasesResponse, error) {\n\tdefer tearDown()\n\thClient, err := GetHelmClient(kubeConfig)\n\t// TODO doc the options here\n\tvar sortBy = int32(2)\n\tvar sortOrd = int32(1)\n\tops := []helm.ReleaseListOption{\n\t\thelm.ReleaseListSort(sortBy),\n\t\thelm.ReleaseListOrder(sortOrd),\n\t\t//helm.ReleaseListLimit(limit),\n\t\t//helm.ReleaseListFilter(filter),\n\t\t//helm.ReleaseListStatuses(codes),\n\t\t//helm.ReleaseListNamespace(\"\"),\n\t}\n\tif filter != nil {\n\t\tops = append(ops, helm.ReleaseListFilter(*filter))\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := hClient.ListReleases(ops...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}", "func GetHelmRelease(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *HelmReleaseState, opts ...pulumi.ResourceOption) (*HelmRelease, error) {\n\tvar resource HelmRelease\n\terr := ctx.ReadResource(\"kubernetes:apps.open-cluster-management.io/v1:HelmRelease\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (m *ManagementTemplateStep) GetVersions()([]ManagementTemplateStepVersionable) {\n val, err := m.GetBackingStore().Get(\"versions\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]ManagementTemplateStepVersionable)\n }\n return nil\n}", "func (s Client) GetVersions(prefix string) ([]string, error) {\n\tdv, err := s.ListObjects(prefix, \"/\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar versions []string\n\t// split the object prefixes to get the last part which is the version\n\tfor _, p := range dv.CommonPrefixes {\n\t\ts := strings.Split(strings.Trim(*p.Prefix, \"/\"), \"/\")\n\t\tversions = append(versions, s[len(s)-1])\n\t}\n\treturn versions, nil\n}", "func ListResources(limit int64, namespace string, kubeclient *kubernetes.Clientset) (*[]string, error) {\n\tif namespace == \"\" {\n\t\tnamespace = \"default\"\n\t}\n\n\topts := metaV1.ListOptions{\n\t\tLimit: limit,\n\t}\n\topts.APIVersion = \"apps/v1\"\n\topts.Kind = \"Deployment\"\n\n\tlist, err := kubeclient.AppsV1().Deployments(namespace).List(opts)\n\tif err != nil {\n\t\treturn nil, pkgerrors.Wrap(err, \"Get Deployment list error\")\n\t}\n\n\tresult := make([]string, 0, limit)\n\tif list != nil {\n\t\tfor _, deployment := range list.Items {\n\t\t\tresult = append(result, deployment.Name)\n\t\t}\n\t}\n\n\treturn &result, nil\n}", "func (resolver *NpmResolver) GetInstalledPkgs(pkgDir string) []*Package {\n\tbuffer, err := resolver.ListPkgPaths()\n\t// Error occurs all the time in npm commands, so no return statement here\n\tif err != nil {\n\t\tlogger.Log.Errorln(err)\n\t}\n\tpkgs := make([]*Package, 0)\n\tsc := bufio.NewScanner(buffer)\n\tfor sc.Scan() {\n\t\tabsPath := sc.Text()\n\t\trel, err := filepath.Rel(pkgDir, absPath)\n\t\tif err != nil {\n\t\t\tlogger.Log.Errorln(err)\n\t\t\tcontinue\n\t\t}\n\t\tif rel == \"\" || rel == \".\" || rel == \"..\" {\n\t\t\tcontinue\n\t\t}\n\t\tpkgName := filepath.ToSlash(rel)\n\t\tpkgs = append(pkgs, &Package{\n\t\t\tName: pkgName,\n\t\t\tPath: absPath,\n\t\t})\n\t}\n\treturn pkgs\n}", "func GetVersions() semver.Collection {\n\tresult := Execute(false, \"git\", \"tag\")\n\tresult.Verify(\"git\", \"Cannot list GIT tags\")\n\n\tvar versions semver.Collection\n\tfor _, tag := range strings.Split(strings.TrimSpace(result.Stdout), \"\\n\") {\n\t\tif !versionMatcher.MatchString(tag) {\n\t\t\tcontinue\n\t\t}\n\n\t\tversion, err := semver.NewVersion(versionMatcher.ReplaceAllString(tag, \"\"))\n\n\t\tif err != nil {\n\t\t\tFail(\"Cannot parse GIT tag {errorPrimary}%s{-} as a version, will skip it: {errorPrimary}%s{-}\", tag, err.Error())\n\t\t\tcontinue\n\t\t}\n\n\t\tversions = append(versions, version)\n\t}\n\n\t// Sort versions\n\tsort.Sort(versions)\n\n\treturn versions\n}", "func (h Client) ListNamespaceReleasesYAML(namespace string) ([]byte, error) {\n\tout, err := h.list(namespace, \"--output\", \"yaml\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn []byte(out), nil\n}", "func generateResourceList(mgr manager.Manager, s *releasev1.HelmRelease) (kube.ResourceList, error) {\n\tchartDir, err := downloadChart(mgr.GetClient(), s)\n\tif err != nil {\n\t\tklog.Error(err, \" - Failed to download the chart\")\n\t\treturn nil, err\n\t}\n\n\tvar values map[string]interface{}\n\n\treqBodyBytes := new(bytes.Buffer)\n\n\terr = json.NewEncoder(reqBodyBytes).Encode(s.Spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = yaml.Unmarshal(reqBodyBytes.Bytes(), &values)\n\tif err != nil {\n\t\tklog.Error(err, \" - Failed to Unmarshal the spec \", s.Spec)\n\t\treturn nil, err\n\t}\n\n\tklog.V(3).Info(\"ChartDir: \", chartDir)\n\n\tchart, err := loader.LoadDir(chartDir)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load chart dir: %w\", err)\n\t}\n\n\trcg, err := newRESTClientGetter(mgr, s.Namespace)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get REST client getter from manager: %w\", err)\n\t}\n\n\tkubeClient := kube.New(rcg)\n\n\tactionConfig := &action.Configuration{}\n\tif err := actionConfig.Init(rcg, s.GetNamespace(), \"secret\", func(_ string, _ ...interface{}) {}); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialized actionConfig: %w\", err)\n\t}\n\n\tinstall := action.NewInstall(actionConfig)\n\tinstall.ReleaseName = s.Name\n\tinstall.Namespace = s.Namespace\n\tinstall.DryRun = true\n\tinstall.ClientOnly = true\n\tinstall.Replace = true\n\n\trelease, err := install.Run(chart, values)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresources, err := kubeClient.Build(bytes.NewBufferString(release.Manifest), false)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to build kubernetes objects from release manifest: %w\", err)\n\t}\n\n\treturn resources, nil\n}", "func (p *Project) Releases() []Release {\n\treturn p.releases\n}", "func (g GithubClient) ListAllReleases(owner, repo string) ([]*github.RepositoryRelease, error) {\n\tlo := &github.ListOptions{\n\t\tPage: 1,\n\t\tPerPage: 100,\n\t}\n\n\treleases, resp, err := g.client.Repositories.ListReleases(context.Background(), owner, repo, lo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlo.Page++\n\n\tfor lo.Page <= resp.LastPage {\n\t\tre, _, err := g.client.Repositories.ListReleases(context.Background(), owner, repo, lo)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, r := range re {\n\t\t\treleases = append(releases, r)\n\t\t}\n\t\tlo.Page++\n\t}\n\treturn releases, nil\n}", "func (db *DB) getPackages(\n\tappAlias string,\n\tversionID int,\n\tenv string,\n\tchannel string,\n) ([]*Package, error) {\n\tpkgs := make([]*Package, 0)\n\tsql := `\n\t\tselect \n\t\t\tp.* \n\t\tfrom package p \n\t\t\tleft join version v\n\t\t\t\ton p.version_id = v.id\n\t\t\tleft join app a\n\t\t\t\ton v.app_id = a.id\n\t\twhere\n\t\t\ta.alias = $1\n\t`\n\tvar params []interface{}\n\tparams = append(params, appAlias)\n\tn := 2\n\n\tif versionID != -1 {\n\t\tsql += fmt.Sprintf(` and v.id = $%d`, n)\n\t\tparams = append(params, versionID)\n\t\tn += 1\n\t}\n\n\tif env != \"\" {\n\t\tsql += fmt.Sprintf(` and p.env = $%d`, n)\n\t\tparams = append(params, env)\n\t\tn += 1\n\t}\n\n\tif channel != \"\" {\n\t\tsql += fmt.Sprintf(` and p.channel = $%d`, n)\n\t\tparams = append(params, channel)\n\t\tn += 1\n\t}\n\n\tsql += ` order by v.sort_key desc, p.created_at desc`\n\n\tif err := db.Select(&pkgs, sql, params...); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn pkgs, nil\n}", "func (s *Server) GetAvailablePackageSummaries(ctx context.Context, request *corev1.GetAvailablePackageSummariesRequest) (*corev1.GetAvailablePackageSummariesResponse, error) {\n\tlog.Infof(\"+fluxv2 GetAvailablePackageSummaries(request: [%v])\", request)\n\tdefer log.Infof(\"-fluxv2 GetAvailablePackageSummaries\")\n\n\t// grpc compiles in getters for you which automatically return a default (empty) struct if the pointer was nil\n\tcluster := request.GetContext().GetCluster()\n\tif request != nil && cluster != \"\" && cluster != s.kubeappsCluster {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.Unimplemented,\n\t\t\t\"not supported yet: request.Context.Cluster: [%v]\",\n\t\t\trequest.Context.Cluster)\n\t}\n\n\tpageOffset, err := paginate.PageOffsetFromAvailableRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcharts, err := s.getChartsForRepos(ctx, request.GetFilterOptions().GetRepositories())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpageSize := request.GetPaginationOptions().GetPageSize()\n\tpackageSummaries, err := filterAndPaginateCharts(\n\t\trequest.GetFilterOptions(), pageSize, pageOffset, charts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// per https://github.com/kubeapps/kubeapps/pull/3686#issue-1038093832\n\tfor _, summary := range packageSummaries {\n\t\tsummary.AvailablePackageRef.Context.Cluster = s.kubeappsCluster\n\t}\n\n\t// Only return a next page token if the request was for pagination and\n\t// the results are a full page.\n\tnextPageToken := \"\"\n\tif pageSize > 0 && len(packageSummaries) == int(pageSize) {\n\t\tnextPageToken = fmt.Sprintf(\"%d\", pageOffset+1)\n\t}\n\n\treturn &corev1.GetAvailablePackageSummariesResponse{\n\t\tAvailablePackageSummaries: packageSummaries,\n\t\tNextPageToken: nextPageToken,\n\t\t// TODO (gfichtenholt) Categories?\n\t\t// Just happened to notice that helm plug-in returning this.\n\t\t// Never discussed this and the design doc appears to have a lot of back-and-forth comments\n\t\t// about this, semantics aren't very clear\n\t}, nil\n}", "func (s *Server) GetInstalledPackageSummaries(ctx context.Context, request *corev1.GetInstalledPackageSummariesRequest) (*corev1.GetInstalledPackageSummariesResponse, error) {\n\tlog.Infof(\"+fluxv2 GetInstalledPackageSummaries [%v]\", request)\n\tpageOffset, err := paginate.PageOffsetFromInstalledRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcluster := request.GetContext().GetCluster()\n\tif cluster != \"\" && cluster != s.kubeappsCluster {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.Unimplemented,\n\t\t\t\"not supported yet: request.Context.Cluster: [%v]\",\n\t\t\tcluster)\n\t}\n\n\tpageSize := request.GetPaginationOptions().GetPageSize()\n\tinstalledPkgSummaries, err := s.paginatedInstalledPkgSummaries(\n\t\tctx, request.GetContext().GetNamespace(), pageSize, pageOffset)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Only return a next page token if the request was for pagination and\n\t// the results are a full page.\n\tnextPageToken := \"\"\n\tif pageSize > 0 && len(installedPkgSummaries) == int(pageSize) {\n\t\tnextPageToken = fmt.Sprintf(\"%d\", pageOffset+1)\n\t}\n\n\tresponse := &corev1.GetInstalledPackageSummariesResponse{\n\t\tInstalledPackageSummaries: installedPkgSummaries,\n\t\tNextPageToken: nextPageToken,\n\t}\n\treturn response, nil\n}", "func (s blueGreenDeploymentNamespaceLister) List(selector labels.Selector) (ret []*v1.BlueGreenDeployment, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.BlueGreenDeployment))\n\t})\n\treturn ret, err\n}", "func list_versions(w rest.ResponseWriter, r *rest.Request) {\n\tarch := r.PathParam(\"arch\")\n\tversions := []string{\"nightly\", \"beta\", \"stable\"}\n\t// get the numbered versions available\n\tdb_directories := get_directories(cache_instance, db, arch)\n\tfor _, dir := range db_directories {\n\t\tversion_path := strings.Split(dir.Path, \"/\")\n\t\tversion := version_path[len(version_path)-1]\n\t\tif version != \"snapshots\" {\n\t\t\tversions = append(versions, version)\n\t\t}\n\t}\n\t// Filter things folders we don't want in the versions out\n\n\tw.WriteJson(versions)\n}", "func GetDeploymentList(client client.Interface, nsQuery *common.NamespaceQuery, dsQuery *dataselect.DataSelectQuery,\n\tmetricClient metricapi.MetricClient) (*DeploymentList, error) {\n\tlog.Print(\"Getting list of all deployments in the cluster\")\n\n\tchannels := &common.ResourceChannels{\n\t\tDeploymentList: common.GetDeploymentListChannel(client, nsQuery, 1),\n\t\tPodList: common.GetPodListChannel(client, nsQuery, 1),\n\t\tEventList: common.GetEventListChannel(client, nsQuery, 1),\n\t\tReplicaSetList: common.GetReplicaSetListChannel(client, nsQuery, 1),\n\t\t// List and error channels to Services.\n\t\tServiceList: common.GetServiceListChannel(client, nsQuery, 1),\n\t\t// List and error channels to Ingresses.\n\t\tIngressList: common.GetIngressListChannel(client, nsQuery, 1),\n\t}\n\n\treturn GetDeploymentListFromChannels(channels, dsQuery, metricClient)\n}", "func (client *CachedSchemaRegistryClient) GetVersions(subject string) ([]int, error) {\n\treturn client.SchemaRegistryClient.GetVersions(subject)\n}", "func (h *KubernetesHelper) GetResources(ctx context.Context, containerName, deploymentName, namespace string) (corev1.ResourceRequirements, error) {\n\tdep, err := h.clientset.AppsV1().Deployments(namespace).Get(ctx, deploymentName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn corev1.ResourceRequirements{}, err\n\t}\n\n\tfor _, container := range dep.Spec.Template.Spec.Containers {\n\t\tif container.Name == containerName {\n\t\t\treturn container.Resources, nil\n\t\t}\n\t}\n\treturn corev1.ResourceRequirements{}, fmt.Errorf(\"container %s not found in deployment %s in namespace %s\", containerName, deploymentName, namespace)\n}", "func DeployHelmRelease(releaseName string, chart string, vals map[string]interface{}, cfg *helm.Configuration, client *helm.Upgrade) (*release.Release, error) {\n\t\n\tinfo(\"Deploying release %s of chart %s ...\", releaseName, chart)\n\thelmChartOptions, err := NewHelmChartOptionsFromConfig(chart, vals)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tchartRequested, err := helmChartOptions.LoadChart()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif chartRequested == nil || chartRequested.Metadata == nil {\n\t\treturn nil, fmt.Errorf(\"Failed to load %s chart. Check helm chart options in config\", chart)\n\t}\n\n\tvar release *release.Release\n\n\t// Checking if chart already installed and decide to use install or upgrade helm client\n\thistClient := helm.NewHistory(cfg)\n\thistClient.Max = 1\n\tif _, err := histClient.Run(releaseName); err == driver.ErrReleaseNotFound {\n\t\t// Only print this to stdout for table output\n\t\n\t\tinfo(\"Release %q does not exist. Installing it now.\\n\", releaseName)\n\t\t\n\t\tinstClient := helm.NewInstall(cfg)\n\t\tinstClient.CreateNamespace = false //TODO\n\t\tinstClient.ChartPathOptions = client.ChartPathOptions\n\t\tinstClient.DryRun = client.DryRun\n\t\tinstClient.DisableHooks = client.DisableHooks\n\t\tinstClient.SkipCRDs = client.SkipCRDs\n\t\tinstClient.Timeout = client.Timeout\n\t\tinstClient.Wait = client.Wait\n\t\tinstClient.Devel = client.Devel\n\t\tinstClient.Namespace = client.Namespace\n\t\tinstClient.Atomic = client.Atomic\n\t\tinstClient.PostRenderer = client.PostRenderer\n\t\tinstClient.DisableOpenAPIValidation = client.DisableOpenAPIValidation\n\t\tinstClient.SubNotes = client.SubNotes\n\n\t\tinstClient.ReleaseName = releaseName\n\t\n\t\tif chartRequested.Metadata.Deprecated {\n\t\t\tfmt.Println(\"WARNING: This chart is deprecated\")\n\t\t}\n\t\treturn instClient.Run(chartRequested, vals)\n\t\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\n\tif req := chartRequested.Metadata.Dependencies; req != nil {\n\t\tif err := helm.CheckDependencies(chartRequested, req); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\trelease, err = client.Run(releaseName, chartRequested, vals)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"UPGRADE of %s FAILED\", releaseName)\n\t}\n\tinfo(\"Release %q has been upgraded\\n\", releaseName)\n\n\treturn release, nil\n}", "func (r *Repository) GetVersions() ([]string, error) {\n\tversions := make([]string, 0, len(r.versions))\n\tfor availableVersion := range r.versions {\n\t\t_, err := version.ParseSemantic(availableVersion)\n\t\tif err != nil {\n\t\t\t// discard releases with tags that are not a valid semantic versions (the user can point explicitly to such releases)\n\t\t\tcontinue\n\t\t}\n\t\tversions = append(versions, availableVersion)\n\t}\n\treturn versions, nil\n}", "func getPodsFromDeployment(namespace, deploymentName string, clientset *kubernetes.Clientset) (*corev1.PodList, error) {\n\tctx := context.TODO()\n\tdeployment, err := clientset.AppsV1().Deployments(namespace).Get(ctx, deploymentName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tset := labels.Set(deployment.GetLabels())\n\tlistOptions := metav1.ListOptions{LabelSelector: set.AsSelector().String()}\n\n\treturn clientset.CoreV1().Pods(namespace).List(ctx, listOptions)\n}", "func (s installedPackageNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.InstalledPackage, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.InstalledPackage))\n\t})\n\treturn ret, err\n}", "func (c *Client) Get(name string) (*Release, error) {\n\treleases, err := c.List(ListParameters{Filter: name})\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tfor _, release := range releases {\n\t\tif release.Name == name {\n\t\t\treturn &release, nil\n\t\t}\n\t}\n\treturn nil, trace.NotFound(\"release %v not found\", name)\n}", "func (c Provider) Releases(params []string) (rs *results.ResultSet, err error) {\n\tname := params[0]\n\t// Query the API\n\turl := fmt.Sprintf(SeriesAPI, name)\n\tvar seriesList SeriesList\n\tif err = util.FetchJSON(url, \"series\", &seriesList); err != nil {\n\t\treturn\n\t}\n\t// Proccess Releases\n\tvar lrs Releases\n\tfor _, s := range seriesList.Entries {\n\t\t// Only Active Series\n\t\tif !s.Active {\n\t\t\tcontinue\n\t\t}\n\t\t// Only stable or supported\n\t\tswitch s.Status {\n\t\tcase \"Active Development\":\n\t\tcase \"Current Stable Release\":\n\t\tcase \"Supported\":\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\t\turl := fmt.Sprintf(ReleasesAPI, name, s.Name)\n\t\tvar vl VersionList\n\t\tif err = util.FetchJSON(url, \"releases\", &vl); err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor i := len(vl.Versions) - 1; i >= 0; i-- {\n\t\t\tr := vl.Versions[i]\n\t\t\turl := fmt.Sprintf(FilesAPI, name, s.Name, r.Number)\n\t\t\tvar fl FileList\n\t\t\tif err = util.FetchJSON(url, \"files\", &fl); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvar lr Release\n\t\t\tfor _, f := range fl.Files {\n\t\t\t\tif f.Type != \"Code Release Tarball\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tlr.name = name\n\t\t\t\tlr.series = s.Name\n\t\t\t\tlr.release = r.Number\n\t\t\t\tlr.uploaded = f.Uploaded\n\t\t\t}\n\t\t\tlrs = append(lrs, lr)\n\t\t}\n\t}\n\tif len(lrs) == 0 {\n\t\terr = results.NotFound\n\t\treturn\n\t}\n\trs = lrs.Convert(name)\n\terr = nil\n\treturn\n}", "func (s appDeploymentNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.AppDeployment, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.AppDeployment))\n\t})\n\treturn ret, err\n}", "func getNamespaces(ctx context.Context, k8sc *Client) ([]string, error) {\n\tgvr := schema.GroupVersionResource{\n\t\tGroup: \"\",\n\t\tVersion: \"v1\",\n\t\tResource: \"namespaces\",\n\t}\n\tobjList, err := k8sc.Client.Resource(gvr).List(ctx, metav1.ListOptions{})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnames := make([]string, len(objList.Items))\n\tfor i, obj := range objList.Items {\n\t\tnames[i] = obj.GetName()\n\t}\n\n\treturn names, nil\n}", "func (c Provider) Releases(name string) (rs *results.ResultSet, s results.Status) {\n\trs, s = c.GetReleases(name, 100)\n\treturn\n}", "func InstalledSdks(root string, candidate string) []Sdk {\n\tversions, err := ioutil.ReadDir(candPath(root, candidate))\n\tif err != nil {\n\t\treturn []Sdk{}\n\t}\n\tvar res []Sdk\n\tfor _, ver := range versions {\n\t\tres = append(res, Sdk{candidate, ver.Name(), root})\n\t}\n\treturn res\n}", "func unpackCtlFromRelease(ctx context.Context, s *Staged) ([]binaries.Archive, error) {\n\tlog.Printf(\"Unpacking 'cmctl' and 'kubectl-cert_manager' type artifacts\")\n\n\tif s.Metadata().BuildSource == BuildSourceMake {\n\t\treturn unpackCtlFromMakeRelease(ctx, s)\n\t} else {\n\t\treturn unpackCtlFromBazelRelease(ctx, s)\n\t}\n}", "func (r DockerhubRegistry) GetCatalog() (*RegistryCatalog, error) {\n\trepos := r.RepoConfig.Repositories\n\tbaseURL := r.RepoConfig.AddressOrDefault(dockerhubApiBase)\n\ttoken := \"\"\n\tif r.RepoConfig.Password != \"\" && r.RepoConfig.Username != \"\" {\n\t\ttok, err := r.getAuthToken()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttoken = tok\n\t}\n\tfor _, org := range r.RepoConfig.Orgs {\n\t\tcatalog, err := getRepositoryPage(fmt.Sprintf(\"%s/repositories/%s?page=1&page_size=2\", baseURL, org), token)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trepos = append(repos, catalog...)\n\t}\n\n\treturn &RegistryCatalog{Repositories: repos}, nil\n}" ]
[ "0.68681026", "0.66842574", "0.64231557", "0.6184956", "0.59211946", "0.56907654", "0.56102777", "0.56035805", "0.5596758", "0.558608", "0.5576202", "0.554659", "0.5541887", "0.55345273", "0.5524537", "0.5522686", "0.5513921", "0.55089676", "0.5455595", "0.54419965", "0.54031444", "0.52801865", "0.52423435", "0.5240737", "0.52252436", "0.52233416", "0.5214336", "0.5214057", "0.5205673", "0.5192487", "0.519159", "0.5142118", "0.5119638", "0.510982", "0.5099853", "0.5082581", "0.5066602", "0.5063649", "0.50366867", "0.49856147", "0.49820393", "0.49725264", "0.49358717", "0.49344122", "0.4920763", "0.48946553", "0.4894526", "0.48935726", "0.48920697", "0.48910326", "0.48605552", "0.48551816", "0.48548815", "0.48548025", "0.48401117", "0.48283976", "0.48229247", "0.48215282", "0.48145893", "0.48058224", "0.47959766", "0.4788024", "0.4775646", "0.4774581", "0.47674614", "0.4758875", "0.4750956", "0.47373977", "0.4730982", "0.47290874", "0.4728535", "0.47099823", "0.47045967", "0.47017902", "0.46899268", "0.46887064", "0.4687517", "0.4678212", "0.4673724", "0.46716273", "0.4658557", "0.4653172", "0.4641317", "0.46257478", "0.46191403", "0.46107394", "0.4580104", "0.45674655", "0.4556894", "0.4541617", "0.45270655", "0.45165172", "0.45164067", "0.45162362", "0.45134723", "0.4512347", "0.45076844", "0.45052546", "0.44897214", "0.4482849" ]
0.7249984
0
GetClientToK8s returns a k8s ClientSet
func GetClientToK8s() (*kubernetes.Clientset, error) { var kubeconfig string if kubeConfigPath := os.Getenv("KUBECONFIG"); kubeConfigPath != "" { kubeconfig = kubeConfigPath // CI process } else { kubeconfig = filepath.Join(os.Getenv("HOME"), ".kube", "config") // Development environment } var config *rest.Config _, err := os.Stat(kubeconfig) if err != nil { // In cluster configuration config, err = rest.InClusterConfig() if err != nil { return nil, err } } else { // Out of cluster configuration config, err = clientcmd.BuildConfigFromFlags("", kubeconfig) if err != nil { return nil, err } } clientset, err := kubernetes.NewForConfig(config) if err != nil { return nil, err } return clientset, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetClientToK8s() (*K8sClient, error) {\n\tvar kubeconfig string\n\tif kubeConfigPath := os.Getenv(\"KUBECONFIG\"); kubeConfigPath != \"\" {\n\t\tkubeconfig = kubeConfigPath // CI process\n\t} else {\n\t\tkubeconfig = filepath.Join(os.Getenv(\"HOME\"), \".kube\", \"config\") // Development environment\n\t}\n\n\tvar config *rest.Config\n\n\t_, err := os.Stat(kubeconfig)\n\tif err != nil {\n\t\t// In cluster configuration\n\t\tconfig, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\t// Out of cluster configuration\n\t\tconfig, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar client = &K8sClient{ClientSet: clientset, Config: config}\n\treturn client, nil\n}", "func getk8sClientset(cluster *model.Cluster) (*kubernetes.Clientset, error) {\n\tif cluster.ClientSet != nil {\n\t\treturn cluster.ClientSet, nil\n\t}\n\n\tclientSet, err := k8sTools.GetClientset()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn clientSet, nil\n\n}", "func getClientSetOut() *kubernetes.Clientset {\n // Getting deploymentsClient object\n home := homedir.HomeDir();\n abspath := filepath.Join(home, \".kube\", \"config\")\n config, err := clientcmd.BuildConfigFromFlags(\"\", abspath)\n if err != nil {\n panic(err)\n }\n clientset, err := kubernetes.NewForConfig(config)\n if err != nil {\n panic(err)\n }\n\n return clientset\n}", "func getClient(k8sconfig string) (*kubernetes.Clientset, error) {\n\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", k8sconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn clientset, nil\n}", "func (t *DeployManager) GetK8sClient() *kubernetes.Clientset {\n\treturn t.k8sClient\n}", "func getClientSetIn() *kubernetes.Clientset {\n config, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n return clientset\n}", "func (k *KubernetesClient) getK8sClient() (*kubernetes.Clientset, error) {\n\thome, err := homedir.Dir()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"home directory not found, error: %s\", err.Error())\n\t}\n\n\tconfigPath := filepath.Join(home, \".kube\", \"config\")\n\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", configPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create k8s config, error: %s\", err.Error())\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create K8s clientset, error: %s\", err.Error())\n\t}\n\n\treturn clientset, nil\n}", "func GenerateK8sClientSet(config *rest.Config) (*kubernetes.Clientset, error) {\n\tk8sClientSet, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to generate kubernetes clientSet %s: \", err)\n\t}\n\treturn k8sClientSet, nil\n}", "func getK8sAPIClient() *kubernetes.Clientset {\n\tconfig, err := getInClusterConfig()\n\tif err != nil {\n\t\tlogrus.Warnf(\"Failed to use in-cluster configuration, will \"+\n\t\t\t\"attempt out-of-cluster authentication. Error: %v\", err.Error())\n\t\tconfig, err = getClusterConfig()\n\t\tif err != nil {\n\t\t\tlogrus.Fatalf(\"Failed to use the out-of-cluster \"+\n\t\t\t\t\"authentication too, error: %v\", err.Error())\n\t\t}\n\t}\n\n\t// Create the client object from in-cluster configuration\n\tlogrus.Debug(\"Creating the k8s client object\")\n\tclientset, err := kubernetes.NewForConfig(&config)\n\tif err != nil {\n\t\tlogrus.Fatalf(\"Failed to create the K8s client \"+\n\t\t\t\"authentication too, error: %v\", err.Error())\n\t}\n\treturn clientset\n}", "func Client() (*k8s.Clientset, error) {\n\tconfig, err := getConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn k8s.NewForConfig(config)\n}", "func getClient() *kubernetes.Clientset {\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tglog.Fatal(err)\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tglog.Fatal(err)\n\t}\n\treturn clientset\n}", "func NewK8sClient() (*kubernetes.Clientset, error) {\n\n\tconfig, err := BuildK8sConfig()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to generate k8s config from flags: %w\", err)\n\t}\n\n\treturn kubernetes.NewForConfig(config)\n}", "func K8Init() *kubernetes.Clientset {\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tClientSet, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn ClientSet\n}", "func k8sConnect(ip string) (*kubernetes.Clientset, error) {\n\ttoken := os.Getenv(\"tokenEnvVar\")\n\tcaFile := os.Getenv(\"caFileEnvVar\")\n\tvar err error\n\tvar caData []byte\n\tif len(caFile) > 0 {\n\t\tcaData, err = ioutil.ReadFile(caFile)\n\t}\n\tif err != nil {\n\t\tlogger.Println(err)\n\t\treturn nil,err\n\t}\n\tconfig := &rest.Config{\n\t\tHost: \"https://\" + ip + \":6443\",\n\t\tBearerToken: token,\n\t\tTLSClientConfig: rest.TLSClientConfig{CAData: caData},\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\treturn clientset, err\n}", "func GetClientset(config *rest.Config) *clientset.Clientset {\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tlog.Fatalf(\"Can not get kubernetes kfdef: %v\", err)\n\t}\n\treturn clientset\n}", "func getClients(kubeConfig, kubeContext string) (k8sClient k8sclient.Interface, svcatClient svcatclient.Interface, namespaces string, err error) {\n\tvar restConfig *rest.Config\n\tvar config clientcmd.ClientConfig\n\n\tif plugin.IsPlugin() {\n\t\trestConfig, config, err = pluginutils.InitClientAndConfig()\n\t\tif err != nil {\n\t\t\treturn nil, nil, \"\", fmt.Errorf(\"could not get Kubernetes config from kubectl plugin context: %s\", err)\n\t\t}\n\t} else {\n\t\tconfig = kube.GetConfig(kubeContext, kubeConfig)\n\t\trestConfig, err = config.ClientConfig()\n\t\tif err != nil {\n\t\t\treturn nil, nil, \"\", fmt.Errorf(\"could not get Kubernetes config for context %q: %s\", kubeContext, err)\n\t\t}\n\t}\n\n\tnamespace, _, err := config.Namespace()\n\tk8sClient, err = k8sclient.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn nil, nil, \"\", err\n\t}\n\tsvcatClient, err = svcatclient.NewForConfig(restConfig)\n\treturn k8sClient, svcatClient, namespace, nil\n}", "func getClient() (*kubernetes.Clientset, error) {\n\t// Create a clientset to drive API operations on resources.\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn clientset, err\n}", "func (k *k8sUtil) K8sClient() (K8sClient, bool) {\n\treturn k, true\n}", "func getKubernetesClient() (*kubernetes.Clientset, error) {\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn kubernetes.NewForConfig(config)\n}", "func kubernetesClient(cluster *gkev1.Cluster) (k8sclient *kubernetes.Clientset, err error) {\n\tvar decodedClientCertificate []byte\n\tif decodedClientCertificate, err = b64.StdEncoding.\n\t\tDecodeString(cluster.MasterAuth.ClientCertificate); err != nil {\n\t\treturn\n\t}\n\tvar decodedClientKey []byte\n\tif decodedClientKey, err = b64.StdEncoding.\n\t\tDecodeString(cluster.MasterAuth.ClientKey); err != nil {\n\t\treturn\n\t}\n\tvar decodedClusterCaCertificate []byte\n\tif decodedClusterCaCertificate, err = b64.StdEncoding.\n\t\tDecodeString(cluster.MasterAuth.ClusterCaCertificate); err != nil {\n\t\treturn\n\t}\n\treturn kubernetes.NewForConfig(&rest.Config{\n\t\tUsername: cluster.MasterAuth.Username,\n\t\tPassword: cluster.MasterAuth.Password,\n\t\tHost: \"https://\" + cluster.Endpoint,\n\t\tTLSClientConfig: rest.TLSClientConfig{\n\t\t\tInsecure: false,\n\t\t\tCertData: decodedClientCertificate,\n\t\t\tKeyData: decodedClientKey,\n\t\t\tCAData: decodedClusterCaCertificate,\n\t\t},\n\t\tAuthProvider: &clientcmdapi.AuthProviderConfig{Name: googleAuthPlugin},\n\t})\n}", "func getK8sConfig(context string) clientcmd.ClientConfig {\n\trules := clientcmd.NewDefaultClientConfigLoadingRules()\n\toverrides := &clientcmd.ConfigOverrides{}\n\tif context != \"\" {\n\t\toverrides.CurrentContext = context\n\t}\n\treturn clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides)\n}", "func GetClientSet(path string) (*kubernetes.Clientset, error) {\n\tvar config *rest.Config\n\tvar err error\n\tif path == \"\" {\n\t\tconfig, err = rest.InClusterConfig()\n\t} else {\n\t\tconfig, err = clientcmd.BuildConfigFromFlags(\"\", path)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn kubernetes.NewForConfig(config)\n}", "func GetKubernetesClient() ClientSets {\n\t// construct the path to resolve to `~/.kube/config`\n\tkubeConfigPath := os.Getenv(\"HOME\") + \"/.kube/config\"\n\n\t// create the config from the path\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kubeConfigPath)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"GetClusterConfig config: %v\", err))\n\n\t}\n\n\tfmt.Println(\"Successfully constructed config\")\n\n\t// generate the client based off of the config\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"GetClusterConfig originalClient: %v\", err))\n\t}\n\n\tfmt.Println(\"Successfully constructed k8s client\")\n\n\n\tcustomClient, err := netsys_client.NewForConfig(config)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"GetClusterConfig customClient: %v\", err))\n\t}\n\n\tfmt.Println(\"Successfully constructed custom client\")\n\n\treturn ClientSets{\n\t\tOriginalClient: client,\n\t\tNetsysClient: customClient,\n\t}\n}", "func NewK8sClient(cfgfile string) (*K8sClient, error) {\n\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", cfgfile)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\t// Create the ClientSet\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\treturn &K8sClient{\n\t\tkubeConfig: cfgfile,\n\t\tclientSet: client,\n\t}, nil\n}", "func createClientset() *kubernetes.Clientset {\n\tkubeconfig := getKubeConfig()\n\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\n\treturn clientset\n}", "func (ts *Tester) KubernetesClientSet() *kubernetes.Clientset {\n\treturn ts.k8sClientSet\n}", "func Clients() (*kubernetes.Clientset, scheme.Interface, error) {\n\tvar config *rest.Config\n\tvar err error\n\tpathToKubeConfig := os.Getenv(\"DAPR_DASHBOARD_KUBECONFIG\")\n\tif pathToKubeConfig != \"\" {\n\t\tconfig, err = clientcmd.BuildConfigFromFlags(\"\", pathToKubeConfig)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\tif config == nil {\n\t\tconfig, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\tkubeClient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn kubeClient, nil, err\n\t}\n\n\tdaprClient, err := scheme.NewForConfig(config)\n\treturn kubeClient, daprClient, err\n}", "func GetGenericK8sClient() (*kubernetes.Clientset, error) {\n\tconfig, err := GetKubeConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn kubernetes.NewForConfig(config)\n}", "func (cloud *K8SCloud) Client() *kubernetes.Clientset {\n\treturn cloud.client\n}", "func Client(kubeConfig string) *kubernetes.Clientset {\n\tvar config *rest.Config\n\tvar clientSet *kubernetes.Clientset\n\tvar err error\n\tif os.Getenv(\"KUBERNETES_SERVICE_HOST\") != \"\" && os.Getenv(\"KUBERNETES_SERVICE_PORT\") != \"\" {\n\t\tconfig, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\tclientSet, err = kubernetes.NewForConfig(config)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t} else {\n\t\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kubeConfig)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\tclientSet, err = kubernetes.NewForConfig(config)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t}\n\treturn clientSet\n}", "func Client() (*ClientK8s, error) {\n\tcfg, err := CreateConfig(option.OperatorConfig.K8sAPIServerURL,\n\t\toption.OperatorConfig.KubeCfgPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc, err := kubernetes.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ClientK8s{Interface: c}, nil\n}", "func NewK8sClient(cPath string) (*kubernetes.Clientset, error) {\n\t// clientcmd.BuildConfigFromFlags will call rest.InClusterConfig when the kubeconfigPath\n\t// passed into it is empty. However it logs an inappropriate warning could give the operator\n\t// unnecessary concern. Thus, we'll only call this when there is a kubeconfig explicitly\n\t// passed.\n\tif cPath != \"\" {\n\t\tglog.Infof(\"--kubeconfig flag specified, attempting to load kubeconfig from %s\", cPath)\n\n\t\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", cPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tglog.Infof(\"client being created to communicate with API server at %s\", config.Host)\n\n\t\tcs, err := kubernetes.NewForConfig(config)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn cs, err\n\t}\n\n\t// attempt to create client from in-cluster config (the service account associated witht the pod)\n\tglog.Infof(`no --kubeconfig flag specified, loading Kubernetes service account assigned to pod \n\t\tlocated at /var/run/secrets/kubernetes.io/serviceaccount/.`)\n\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tglog.Infof(\"client being created to communicate with API server at %s\", config.Host)\n\n\tcs, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cs, err\n}", "func getClientInCluster() kubernetes.Interface {\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tlogger.Fatalf(\"Can not get kubernetes config: %v\", err)\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tlogger.Fatalf(\"Can not create kubernetes client: %v\", err)\n\t}\n\n\treturn clientset\n}", "func InitClientSet() (*ClientSet, error) {\n\trestconfig, err := config.GetConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tctrlClient, err := client.New(restconfig, client.Options{Scheme: scheme})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create client\")\n\t}\n\tkubeClient, err := kubernetes.NewForConfig(restconfig)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error in getting acess to k8s\")\n\t}\n\treturn &ClientSet{ctrlClient, kubeClient}, nil\n}", "func GetClientSet() (*kubernetes.Clientset, error) {\n\tdebugMode := os.Getenv(\"DEBUG_LOCAL\")\n\tif debugMode != \"\" {\n\t\treturn getOutOfClusterClientSet()\n\t} else {\n\t\treturn getInClusterClientSet()\n\t}\n}", "func getK8sClientSetOutsideClusterConfig() *kubernetes.Clientset {\n\t// use the current context in kubeconfig to create the clientset\n\tvar kubeconfig *string\n\tif home := homeDir(); home != \"\" {\n\t\tkubeconfig = flag.String(\"kubeconfig\", filepath.Join(home, \".kube\", \"config\"), \"(optional) absolute path to the kubeconfig file\")\n\t} else {\n\t\tkubeconfig = flag.String(\"kubeconfig\", \"\", \"absolute path to the kubeconfig file\")\n\t}\n\tflag.Parse()\n\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", *kubeconfig)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\treturn clientset\n}", "func GetKubeClient(t testing.TB) *kube.Clientset {\n\tvar config *rest.Config\n\thost := os.Getenv(\"KUBERNETES_SERVICE_HOST\")\n\tif host != \"\" {\n\t\tvar err error\n\t\tconfig, err = rest.InClusterConfig()\n\t\trequire.NoError(t, err)\n\t} else {\n\t\t// Use kubectl binary to parse .kube/config and get address of current\n\t\t// cluster. Hopefully, once we upgrade to k8s.io/client-go, we will be able\n\t\t// to do this in-process with a library\n\t\t// First, figure out if we're talking to minikube or localhost\n\t\tcmd := exec.Command(\"kubectl\", \"config\", \"current-context\")\n\t\tcmd.Stderr = os.Stderr\n\t\tif context, err := cmd.Output(); err == nil {\n\t\t\tcontext = bytes.TrimSpace(context)\n\t\t\t// kubectl has a context -- not talking to localhost\n\t\t\t// Get cluster and user name from kubectl\n\t\t\tbuf := &bytes.Buffer{}\n\t\t\tcmd := BashCmd(strings.Join([]string{\n\t\t\t\t`kubectl config get-contexts \"{{.context}}\" | tail -n+2 | awk '{print $3}'`,\n\t\t\t\t`kubectl config get-contexts \"{{.context}}\" | tail -n+2 | awk '{print $4}'`,\n\t\t\t}, \"\\n\"),\n\t\t\t\t\"context\", string(context))\n\t\t\tcmd.Stdout = buf\n\t\t\trequire.NoError(t, cmd.Run(), \"couldn't get kubernetes context info\")\n\t\t\tlines := strings.Split(buf.String(), \"\\n\")\n\t\t\tclustername, username := lines[0], lines[1]\n\n\t\t\t// Get user info\n\t\t\tbuf.Reset()\n\t\t\tcmd = BashCmd(strings.Join([]string{\n\t\t\t\t`cluster=\"$(kubectl config view -o json | jq -r '.users[] | select(.name == \"{{.user}}\") | .user' )\"`,\n\t\t\t\t`echo \"${cluster}\" | jq -r '.[\"client-certificate\"]'`,\n\t\t\t\t`echo \"${cluster}\" | jq -r '.[\"client-key\"]'`,\n\t\t\t}, \"\\n\"),\n\t\t\t\t\"user\", username)\n\t\t\tcmd.Stdout = buf\n\t\t\trequire.NoError(t, cmd.Run(), \"couldn't get kubernetes user info\")\n\t\t\tlines = strings.Split(buf.String(), \"\\n\")\n\t\t\tclientCert, clientKey := lines[0], lines[1]\n\n\t\t\t// Get cluster info\n\t\t\tbuf.Reset()\n\t\t\tcmd = BashCmd(strings.Join([]string{\n\t\t\t\t`cluster=\"$(kubectl config view -o json | jq -r '.clusters[] | select(.name == \"{{.cluster}}\") | .cluster')\"`,\n\t\t\t\t`echo \"${cluster}\" | jq -r .server`,\n\t\t\t\t`echo \"${cluster}\" | jq -r '.[\"certificate-authority\"]'`,\n\t\t\t}, \"\\n\"),\n\t\t\t\t\"cluster\", clustername)\n\t\t\tcmd.Stdout = buf\n\t\t\trequire.NoError(t, cmd.Run(), \"couldn't get kubernetes cluster info: %s\", buf.String())\n\t\t\tlines = strings.Split(buf.String(), \"\\n\")\n\t\t\taddress, CAKey := lines[0], lines[1]\n\n\t\t\t// Generate config\n\t\t\tconfig = &rest.Config{\n\t\t\t\tHost: address,\n\t\t\t\tTLSClientConfig: rest.TLSClientConfig{\n\t\t\t\t\tCertFile: clientCert,\n\t\t\t\t\tKeyFile: clientKey,\n\t\t\t\t\tCAFile: CAKey,\n\t\t\t\t},\n\t\t\t}\n\t\t} else {\n\t\t\t// no context -- talking to localhost\n\t\t\tconfig = &rest.Config{\n\t\t\t\tHost: \"http://0.0.0.0:8080\",\n\t\t\t\tTLSClientConfig: rest.TLSClientConfig{\n\t\t\t\t\tInsecure: false,\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t}\n\tk, err := kube.NewForConfig(config)\n\trequire.NoError(t, err)\n\treturn k\n}", "func Client() *K8sClient {\n\treturn k8sCLI\n}", "func GetClient(restConfig *restclient.Config) *kubernetes.Clientset {\n\tclientset, err := kubernetes.NewForConfig(restConfig)\n\tif err != nil {\n\t\tglog.Fatal(err)\n\t}\n\treturn clientset\n}", "func GetKubernetesClient() (*K8s, error) {\n\tlogger := utils.GetK8sAPILogger()\n\tif !TRACE_API {\n\t\tlogger.SetLevel(utils.Info)\n\t}\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tlogger.Trace(config)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn &K8s{\n\t\tAPI: clientset,\n\t\tLogger: logger,\n\t}, nil\n}", "func Client() (*kubernetes.Clientset, error) {\n\n\t// manually use ~/.kube/config for now\n\tkubeConfigFilePath := filepath.Join(os.Getenv(\"HOME\"), \".kube\", \"config\")\n\t// fmt.Println(kubeConfigFilePath)\n\tfmt.Printf(\"\\n\\nKubeConfig Path: %s\\n\\n\", kubeConfigFilePath)\n\n\tkubeConfigFile, err := ioutil.ReadFile(kubeConfigFilePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkubeConfig, err := clientcmd.RESTConfigFromKubeConfig(kubeConfigFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclientSet, err := kubernetes.NewForConfig(kubeConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn clientSet, err\n\n}", "func getClient(kubeconfig *Kubeconfig) (*kubernetes.Clientset, error) {\n\t// Usually we don't need a client. But in this case, we _might_ if we're using detect.\n\t// So pass in nil if we get an error, then display the errors from trying to get a client\n\t// if it turns out we needed it.\n\tcfg, err := kubeconfig.Get()\n\tvar client *kubernetes.Clientset\n\n\tvar kubeError error\n\tif err == nil {\n\t\tclient, err = kubernetes.NewForConfig(cfg)\n\t\tif err != nil {\n\t\t\tkubeError = err\n\t\t}\n\t} else {\n\t\tkubeError = err\n\t}\n\n\treturn client, kubeError\n}", "func (t *Target) SetK8sClient(c client.Client) target.Target {\n\tif t.err != nil {\n\t\treturn t\n\t}\n\tt.k8sclient = c\n\treturn t\n}", "func (kr *KRun) K8SClient(ctx context.Context) error {\n\tif kr.Client != nil {\n\t\treturn nil\n\t}\n\n\terr := kr.initUsingKubeConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = kr.initInCluster()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif kr.VendorInit != nil {\n\t\terr = kr.VendorInit(ctx, kr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif kr.Client != nil {\n\t\treturn nil\n\t}\n\n\treturn errors.New(\"not found\")\n}", "func Client() (*kubernetes.Clientset, error) {\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tconfig, err = getKubeConfig()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn clientset, nil\n}", "func getKubernetesClient() (kubernetes.Interface){\r\n\t// construct the path to resolve to `~/.kube/config`\r\n config, err := rest.InClusterConfig()\r\n if err != nil {\r\n kubeConfigPath := os.Getenv(\"HOME\") + \"/.kube/config\"\r\n // kubeConfigPath := \"/etc/kubernetes/scheduler.conf\"\r\n\r\n //create the config from the path\r\n config, err = clientcmd.BuildConfigFromFlags(\"\", kubeConfigPath)\r\n if err != nil {\r\n log.Fatalf(\"getInClusterConfig: %v\", err)\r\n panic(\"Failed to load kube config\")\r\n }\r\n }\r\n\r\n // Same settings as the default scheduler\r\n config.QPS = 100\r\n config.Burst = 200\r\n\r\n // generate the client based off of the config\r\n client, err := kubernetes.NewForConfig(config)\r\n if err != nil {\r\n panic(\"Failed to create kube client\")\r\n }\r\n\r\n\tlog.Info(\"Successfully constructed k8s client\")\r\n\treturn client\r\n}", "func GetKubeBatchClient(restConfig *restclient.Config) *versioned.Clientset {\n\tclientset, err := versioned.NewForConfig(restConfig)\n\tif err != nil {\n\t\tglog.Fatal(err)\n\t}\n\treturn clientset\n}", "func GetKubernetesClientFromOptions(kubectlOptions *KubectlOptions) (*kubernetes.Clientset, error) {\n\tlogger := logging.GetProjectLogger()\n\tlogger.Infof(\"Loading Kubernetes Client\")\n\n\tconfig, err := LoadApiClientConfigFromOptions(kubectlOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn kubernetes.NewForConfig(config)\n}", "func (k *k8sUtil) inClusterCS() (*kubernetes.Clientset, error) {\n\n\t// creates the in-cluster config\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// creates the in-cluster clientset\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn clientset, nil\n}", "func NewClientSet() (kubernetes.Interface, error) {\n\tlr := clientcmd.NewDefaultClientConfigLoadingRules()\n\tkc := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(lr, &clientcmd.ConfigOverrides{})\n\n\tconfig, err := kc.ClientConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn kubernetes.NewForConfig(config)\n}", "func getKubeClient() (*kubernetes.Clientset, error) {\n\tcmd, err := clientcmd.BuildConfigFromFlags(*master, *kubeConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn getKubeClientFromRESTConfig(cmd)\n}", "func getClientOutOfCluster() kubernetes.Interface {\n\tconfig, err := buildOutOfClusterConfig()\n\tif err != nil {\n\t\tlogger.Fatalf(\"Cannot get kubernetes config: %v\", err)\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\n\tif err != nil {\n\t\tlogger.Fatalf(\"Cannot create new kubernetes client from config: %v\", err)\n\t}\n\n\treturn clientset\n}", "func (w *workloadCluster) GenerateWorkloadClusterK8sClient(ctx *context.MachineContext) (k8sclient.Interface, error) {\n\t// get workload cluster kubeconfig\n\tkubeConfig, err := w.getKubeconfigForWorkloadCluster(ctx)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get kubeconfig for workload cluster\")\n\t}\n\n\t// generate REST config\n\trestConfig, err := clientcmd.RESTConfigFromKubeConfig([]byte(kubeConfig))\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create REST config\")\n\t}\n\n\t// create the client\n\tworkloadClusterClient, err := k8sclient.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create workload cluster client\")\n\t}\n\n\treturn workloadClusterClient, nil\n}", "func FakeK8sClient(initObjects ...runtime.Object) client.Client {\n\ts := scheme.Scheme\n\tcorev1.AddToScheme(s)\n\tmonitoringv1.AddToScheme(s)\n\tcluster_v1alpha1.AddToScheme(s)\n\treturn fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(initObjects...).Build()\n}", "func getKubeClient(dnsAddress string) (*kubernetes.Clientset, *rest.Config, error) {\n\terr := httplib.InGravity(dnsAddress)\n\tif err != nil {\n\t\tlogrus.Infof(\"Not in Gravity: %v.\", err)\n\t\treturn utils.GetLocalKubeClient()\n\t}\n\t// Resolve the API server address in advance.\n\thost, err := utils.ResolveAddr(dnsAddress, fmt.Sprintf(\"%v:%v\",\n\t\tconstants.APIServerDomainName, defaults.APIServerSecurePort))\n\tif err != nil {\n\t\treturn nil, nil, trace.Wrap(err)\n\t}\n\tkubeClient, kubeConfig, err := httplib.GetClusterKubeClient(dnsAddress,\n\t\thttplib.WithHost(fmt.Sprintf(\"https://%v\", host)))\n\tif err != nil {\n\t\treturn nil, nil, trace.Wrap(err)\n\t}\n\treturn kubeClient, kubeConfig, nil\n}", "func NewK8sClient() scheduler.Scheduler {\n\treturn &Client{\n\t\tlogger: defaultLogger,\n\t}\n}", "func GetClient() (*kubernetes.Clientset, error) {\n\tvar kubeConfig rest.Config\n\n\t// Set the Kubernetes configuration based on the environment\n\tif RunningInCluster() {\n\t\tconfig, err := rest.InClusterConfig()\n\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to create in-cluster config: %v\", err)\n\t\t}\n\n\t\tkubeConfig = *config\n\t} else {\n\t\tloadingRules := clientcmd.NewDefaultClientConfigLoadingRules()\n\t\tconfigOverrides := &clientcmd.ConfigOverrides{}\n\t\tconfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides)\n\t\ttmpKubeConfig, err := config.ClientConfig()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to load local kube config: %v\", err)\n\t\t}\n\n\t\tkubeConfig = *tmpKubeConfig\n\t}\n\n\t// Create the Kubernetes client based on the configuration\n\treturn kubernetes.NewForConfig(&kubeConfig)\n}", "func GetKubernetesClient(logger logrus.FieldLogger, config *viper.Viper, inCluster bool, kubeConfigPath string) (kubernetes.Interface, metricsClient.Interface, error) {\n\tvar err error\n\tl := logger.WithFields(logrus.Fields{\n\t\t\"operation\": \"configureKubernetesClient\",\n\t})\n\tvar conf *rest.Config\n\tif inCluster {\n\t\tl.Debug(\"starting with incluster configuration\")\n\t\tconf, err = rest.InClusterConfig()\n\t} else {\n\t\tl.Debug(\"starting outside Kubernetes cluster\")\n\t\tconf, err = clientcmd.BuildConfigFromFlags(\"\", kubeConfigPath)\n\t}\n\tconf.Timeout = config.GetDuration(\"extensions.kubernetesClient.timeout\")\n\tconf.RateLimiter = nil\n\tconf.Burst = config.GetInt(\"extensions.kubernetesClient.burst\")\n\tconf.QPS = float32(config.GetInt(\"extensions.kubernetesClient.qps\"))\n\tif err != nil {\n\t\tl.WithError(err).Error(\"start Kubernetes failed\")\n\t\treturn nil, nil, err\n\t}\n\tl.Debug(\"connecting to Kubernetes...\")\n\tclientset, err := kubernetesExtensions.NewForConfig(conf)\n\tif err != nil {\n\t\tl.WithError(err).Error(\"connection to Kubernetes failed\")\n\t\treturn nil, nil, err\n\t}\n\tmetricsClientset, err := metricsClient.NewForConfig(conf)\n\tif err != nil {\n\t\tl.WithError(err).Error(\"connection to Kubernetes Metrics Server failed\")\n\t\treturn nil, nil, err\n\t}\n\n\tl.Info(\"successfully connected to Kubernetes\")\n\treturn clientset, metricsClientset, nil\n}", "func getKubernetesClient() kubernetes.Interface {\n\t// construct the path to resolve to `~/.kube/config`\n\tkubeConfigPath := os.Getenv(\"HOME\") + \"/.kube/config\"\n\n\t// create the config from the path\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kubeConfigPath)\n\tif err != nil {\n\t\tlog.Fatalf(\"getClusterConfig: %v\", err)\n\t}\n\n\t// generate the client based off of the config\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tlog.Fatalf(\"getClusterConfig: %v\", err)\n\t}\n\n\tlog.Info(\"Successfully constructed k8s client\")\n\treturn client\n}", "func (c *AKSCluster) GetK8sConfig() ([]byte, error) {\n\tif c.k8sConfig != nil {\n\t\treturn c.k8sConfig, nil\n\t}\n\tclient, err := c.GetAKSClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.With(log.Logger)\n\n\tdatabase := model.GetDB()\n\tdatabase.Where(model.AzureClusterModel{ClusterModelId: c.modelCluster.ID}).First(&c.modelCluster.Azure)\n\t//TODO check banzairesponses\n\tconfig, err := azureClient.GetClusterConfig(client, c.modelCluster.Name, c.modelCluster.Azure.ResourceGroup, \"clusterUser\")\n\tif err != nil {\n\t\t// TODO status code !?\n\t\treturn nil, err\n\t}\n\tlog.Info(\"Get k8s config succeeded\")\n\tc.k8sConfig = []byte(config.Properties.KubeConfig)\n\treturn c.k8sConfig, nil\n}", "func (m *MockAgentQuerier) GetK8sClient() kubernetes.Interface {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetK8sClient\")\n\tret0, _ := ret[0].(kubernetes.Interface)\n\treturn ret0\n}", "func ClientsetFromContext(ctx context.Context) (*Clientset, error) {\n\trestConfig, err := kubeutils.GetConfig(\"\", \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkubeClient, err := kubernetes.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcrdCache := kube.NewKubeCache(ctx)\n\tkubeCoreCache, err := cache.NewKubeCoreCache(ctx, kubeClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpromClient, err := promv1.NewPrometheusConfigClient(prometheus.ResourceClientFactory(kubeClient, kubeCoreCache))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t/*\n\t\tsupergloo config clients\n\t*/\n\tinstall, err := v1.NewInstallClient(clientForCrd(v1.InstallCrd, restConfig, crdCache))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := install.Register(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmesh, err := v1.NewMeshClient(clientForCrd(v1.MeshCrd, restConfig, crdCache))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := mesh.Register(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmeshIngress, err := v1.NewMeshIngressClient(clientForCrd(v1.MeshIngressCrd, restConfig, crdCache))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := meshIngress.Register(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmeshGroup, err := v1.NewMeshGroupClient(clientForCrd(v1.MeshGroupCrd, restConfig, crdCache))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := meshGroup.Register(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tupstream, err := gloov1.NewUpstreamClient(clientForCrd(gloov1.UpstreamCrd, restConfig, crdCache))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := upstream.Register(); err != nil {\n\t\treturn nil, err\n\t}\n\n\troutingRule, err := v1.NewRoutingRuleClient(clientForCrd(v1.RoutingRuleCrd, restConfig, crdCache))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := routingRule.Register(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tsecurityRule, err := v1.NewSecurityRuleClient(clientForCrd(v1.SecurityRuleCrd, restConfig, crdCache))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := securityRule.Register(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// ilackarms: should we use Kube secret here? these secrets follow a different format (specific to istio)\n\ttlsSecret, err := v1.NewTlsSecretClient(&factory.KubeSecretClientFactory{\n\t\tClientset: kubeClient,\n\t\tPlainSecrets: true,\n\t\tCache: kubeCoreCache,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := tlsSecret.Register(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tsecret, err := gloov1.NewSecretClient(&factory.KubeSecretClientFactory{\n\t\tClientset: kubeClient,\n\t\tCache: kubeCoreCache,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := secret.Register(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tsettings, err := gloov1.NewSettingsClient(clientForCrd(gloov1.SettingsCrd, restConfig, crdCache))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := settings.Register(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// special resource client wired up to kubernetes pods\n\t// used by the istio policy syncer to watch pods for service account info\n\tpods := pod.NewPodClient(kubeClient, kubeCoreCache)\n\tservices := service.NewServiceClient(kubeClient, kubeCoreCache)\n\n\treturn newClientset(\n\t\trestConfig,\n\t\tkubeClient,\n\t\tpromClient,\n\t\tnewSuperglooClients(install, mesh, meshGroup, meshIngress, upstream,\n\t\t\troutingRule, securityRule, tlsSecret, secret, settings),\n\t\tnewDiscoveryClients(pods, services),\n\t), nil\n}", "func GetClient() kubernetes.Interface {\n\tvar kubeClient kubernetes.Interface\n\t_, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tkubeClient = getClientOutOfCluster()\n\t} else {\n\t\tkubeClient = getClientInCluster()\n\t}\n\n\treturn kubeClient\n}", "func (cmk *ConfigMapKey) toK8S() *v1.ConfigMapKeySelector {\n\treturn &v1.ConfigMapKeySelector{\n\t\tLocalObjectReference: v1.LocalObjectReference{Name: cmk.ConfigMapName},\n\t\tKey: cmk.Key,\n\t\tOptional: &cmk.Optional,\n\t}\n}", "func New() (kubernetes.Interface, error) {\n\tcs, err := getClientSet()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cs, nil\n}", "func (c *clientProxy) createK8sClient() (kubernetes.Interface, error) {\n\tvar config *rest.Config\n\tvar err error\n\tif c.kubeconfig == \"\" {\n\t\tconfig, err = rest.InClusterConfig()\n\t} else {\n\t\tconfig, err = clientcmd.BuildConfigFromFlags(\"\", c.kubeconfig)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn kubernetes.NewForConfig(config)\n}", "func (k *Kubeclient) getClientOrCached() (*kubernetes.Clientset, error) {\n\tif k.clientset != nil {\n\t\treturn k.clientset, nil\n\t}\n\tc, err := k.getClientset()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to get clientset\")\n\t}\n\tk.clientset = c\n\treturn k.clientset, nil\n}", "func getKubeClientFromRESTConfig(config *rest.Config) (*kubernetes.Clientset, error) {\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\tconfig.APIPath = \"/apis\"\n\tconfig.ContentType = runtime.ContentTypeJSON\n\treturn kubernetes.NewForConfig(config)\n}", "func (t Test) K8s() error {\n\tmg.Deps(Tool{}.Kind)\n\n\terr := sh.RunWithV(ENV, \"kind\", \"create\", \"cluster\", \"--name\", \"kind-test\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\t_ = sh.RunWithV(ENV, \"kind\", \"delete\", \"cluster\", \"--name\", \"kind-test\")\n\t}()\n\terr = sh.RunWithV(ENV, \"kubectl\", \"apply\", \"-f\", \"./integration/testdata/fixtures/k8s/test_nginx.yaml\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn sh.RunWithV(ENV, \"go\", \"test\", \"-v\", \"-tags=k8s_integration\", \"./integration/...\")\n}", "func getKubeClient(kubeConfig, kubeContext string) (*rest.Config, *clientset.Clientset, error) {\n\tconfig, err := configForContext(kubeConfig, kubeContext)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"could not load Kubernetes configuration (%s)\", err)\n\t}\n\n\tclient, err := clientset.NewForConfig(config)\n\treturn nil, client, err\n}", "func GetKubernetesClientFromOptionsE(t testing.TestingT, options *KubectlOptions) (*kubernetes.Clientset, error) {\n\tvar err error\n\tvar config *rest.Config\n\n\tif options.InClusterAuth {\n\t\tconfig, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlogger.Log(t, \"Configuring Kubernetes client to use the in-cluster serviceaccount token\")\n\t} else {\n\t\tkubeConfigPath, err := options.GetConfigPath(t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlogger.Logf(t, \"Configuring Kubernetes client using config file %s with context %s\", kubeConfigPath, options.ContextName)\n\t\t// Load API config (instead of more low level ClientConfig)\n\t\tconfig, err = LoadApiClientConfigE(kubeConfigPath, options.ContextName)\n\t\tif err != nil {\n\t\t\tlogger.Logf(t, \"Error loading api client config, falling back to in-cluster authentication via serviceaccount token: %s\", err)\n\t\t\tconfig, err = rest.InClusterConfig()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tlogger.Log(t, \"Configuring Kubernetes client to use the in-cluster serviceaccount token\")\n\t\t}\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn clientset, nil\n}", "func NewClient(logger log.Logger) (Client, error) {\n\tclient, err := k8s.NewInClusterClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn k8sclient{\n\t\tclient: client,\n\t\tlogger: logger,\n\t}, nil\n}", "func (kc *KubernetesClient) ConfigMapClientSet(namespace string) corev1.ConfigMapInterface {\n\treturn kc.clientset.CoreV1().ConfigMaps(namespace)\n}", "func getKubernetesClient(context, kubeConfigPath string) (kubernetes.Interface, error) {\n\tconfig, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(\n\t\t&clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeConfigPath},\n\t\t&clientcmd.ConfigOverrides{\n\t\t\tCurrentContext: context,\n\t\t}).ClientConfig()\n\n\tif err != nil {\n\t\treturn nil, xerrors.Errorf(\"failed to create client config: %w\", err)\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\n\tif err != nil {\n\t\treturn nil, xerrors.Errorf(\"failed to create kubernetes clientset: %w\", err)\n\t}\n\n\treturn clientset, nil\n}", "func (k *kubeclient) getClientOrCached() (*clientset.Clientset, error) {\n\tif k.clientset != nil {\n\t\treturn k.clientset, nil\n\t}\n\tc, err := k.getClientset()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tk.clientset = c\n\treturn k.clientset, nil\n}", "func (k *kubeclient) getClientOrCached() (*clientset.Clientset, error) {\n\tif k.clientset != nil {\n\t\treturn k.clientset, nil\n\t}\n\tc, err := k.getClientset()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tk.clientset = c\n\treturn k.clientset, nil\n}", "func getClient(file string, dryRun bool) (clientset.Interface, error) {\n\tif dryRun {\n\t\tdryRunGetter, err := apiclient.NewClientBackedDryRunGetterFromKubeconfig(file)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// In order for fakeclient.Discovery().ServerVersion() to return the backing API Server's\n\t\t// real version; we have to do some clever API machinery tricks. First, we get the real\n\t\t// API Server's version\n\t\trealServerVersion, err := dryRunGetter.Client().Discovery().ServerVersion()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to get server version\")\n\t\t}\n\n\t\t// Get the fake clientset\n\t\tdryRunOpts := apiclient.GetDefaultDryRunClientOptions(dryRunGetter, os.Stdout)\n\t\t// Print GET and LIST requests\n\t\tdryRunOpts.PrintGETAndLIST = true\n\t\tfakeclient := apiclient.NewDryRunClientWithOpts(dryRunOpts)\n\t\t// As we know the return of Discovery() of the fake clientset is of type *fakediscovery.FakeDiscovery\n\t\t// we can convert it to that struct.\n\t\tfakeclientDiscovery, ok := fakeclient.Discovery().(*fakediscovery.FakeDiscovery)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"couldn't set fake discovery's server version\")\n\t\t}\n\t\t// Lastly, set the right server version to be used\n\t\tfakeclientDiscovery.FakedServerVersion = realServerVersion\n\t\t// return the fake clientset used for dry-running\n\t\treturn fakeclient, nil\n\t}\n\treturn kubeconfigutil.ClientSetFromFile(file)\n}", "func Kubernetes(log *logging.Logger) (*clientset.Clientset, error) {\n\terrMsg := \"Something went wrong while initializing kubernetes client!\\n\"\n\tonce.Kubernetes.Do(func() {\n\t\tclient, err := newKubernetes(log)\n\t\tif err != nil {\n\t\t\tlog.Error(errMsg)\n\t\t\t// NOTE: Looking to leverage panic recovery to gracefully handle this\n\t\t\t// with things like retries or better intelligence, but the environment\n\t\t\t// is probably in a unrecoverable state as far as the broker is concerned,\n\t\t\t// and demands the attention of an operator.\n\t\t\tpanic(err.Error())\n\t\t}\n\t\tinstances.Kubernetes = client\n\t})\n\tif instances.Kubernetes == nil {\n\t\treturn nil, errors.New(\"Kubernetes client instance is nil\")\n\t}\n\treturn instances.Kubernetes, nil\n}", "func GetRemoteKubernetesClient(kubeconfig string) (*K8s, error) {\n\tlogger := utils.GetK8sAPILogger()\n\tif !TRACE_API {\n\t\tlogger.SetLevel(utils.Info)\n\t}\n\n\t// use the current context in kubeconfig\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\t// create the clientset\n\tclientset, err := kubernetes.NewForConfig(config)\n\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn &K8s{\n\t\tAPI: clientset,\n\t\tLogger: logger,\n\t}, nil\n}", "func (f *factoryImpl) KarmadaClientSet() (karmadaclientset.Interface, error) {\n\tclientConfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn karmadaclientset.NewForConfig(clientConfig)\n}", "func BuildClientset() {\n\tonce.Do(func() {\n\t\tif err := setupKubeClientset(); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t})\n}", "func NewClient() (*kubernetes.Clientset, error) {\n\tvar config *rest.Config\n\tvar err error\n\tinCluster := os.Getenv(\"IN_CLUSTER\")\n\tif inCluster == \"true\" {\n\t\tconfig, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t} else {\n\t\thome := homedir.HomeDir()\n\t\tp := filepath.Join(home, \".kube\", \"config\")\n\t\tconfig, err = clientcmd.BuildConfigFromFlags(\"\", p)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t}\n\n\treturn kubernetes.NewForConfig(config)\n}", "func getActiveK8SPods(orchestrator string) (map[string]string, error) {\n\n\tlog.Infof(\"Obtaining currently active K8S pods on agent node\")\n\n\t// creates the in-cluster config\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tlog.Errorf(\"creating the in-cluster config failed %v\", err)\n\t\treturn map[string]string{}, err\n\t}\n\t// creates the clientset\n\tkubeClient, err := kclient.NewForConfig(config)\n\tif err != nil {\n\t\tlog.Errorf(\"Error trying to create kubeclient %v\", err)\n\t\treturn map[string]string{}, err\n\t}\n\tselector := fields.OneTermEqualSelector(PodHostField, hostname).String()\n\tlistOpts := metav1.ListOptions{FieldSelector: selector}\n\tpods, err := kubeClient.CoreV1().Pods(metav1.NamespaceAll).List(listOpts)\n\tif err != nil {\n\t\tlog.Errorf(\"Error occured while fetching pods from k8s api server\")\n\t\treturn map[string]string{}, err\n\t}\n\n\tentityMap := make(map[string]string)\n\tfor _, pod := range pods.Items {\n\t\tentityMap[string(pod.UID)] = pod.Name\n\t}\n\n\treturn entityMap, err\n}", "func NewClientSetForConfig(config *rest.Config, opts client.Options) (*ClientSet, error) {\n\tclient, err := client.New(config, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkube, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &ClientSet{config, client, kube}, err\n}", "func (b *Buckets) Clients() *cmd.Clients {\n\treturn b.clients\n}", "func GetK8sConfig(c *gin.Context) ([]byte, bool) {\n\tlog := logger.WithFields(logrus.Fields{\"tag\": \"GetKubernetesConfig\"})\n\tcommonCluster, ok := GetCommonClusterFromRequest(c)\n\tif ok != true {\n\t\treturn nil, false\n\t}\n\tkubeConfig, err := commonCluster.GetK8sConfig()\n\tif err != nil {\n\t\tlog.Errorf(\"Error getting config: %s\", err.Error())\n\t\tc.JSON(http.StatusBadRequest, htype.ErrorResponse{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tMessage: \"Error getting kubeconfig\",\n\t\t\tError: err.Error(),\n\t\t})\n\t\treturn nil, false\n\t}\n\treturn kubeConfig, true\n}", "func GetKubeConfigClient() (*rest.Config, *k8s.Clientset, error) {\n\tconfig, err := getConfig()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tclient, err := k8s.NewForConfig(config)\n\tif err != nil {\n\t\treturn config, nil, err\n\t}\n\treturn config, client, nil\n}", "func getAvailabilitySetsClient(resourceManagerEndpoint, subscriptionID string, authorizer autorest.Authorizer) compute.AvailabilitySetsClient {\n\tavailabilitySetClient := compute.NewAvailabilitySetsClientWithBaseURI(resourceManagerEndpoint, subscriptionID)\n\tavailabilitySetClient.Authorizer = authorizer\n\tavailabilitySetClient.AddToUserAgent(azure.UserAgent)\n\treturn availabilitySetClient\n}", "func ExampleClustersClient_ListByResourceGroup() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armservicefabric.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewClustersClient().ListByResourceGroup(ctx, \"resRg\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.ClusterListResult = armservicefabric.ClusterListResult{\n\t// \tValue: []*armservicefabric.Cluster{\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"myCluster\"),\n\t// \t\t\tType: to.Ptr(\"Microsoft.ServiceFabric/clusters\"),\n\t// \t\t\tEtag: to.Ptr(\"W/\\\"636462502169240745\\\"\"),\n\t// \t\t\tID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/resRg/providers/Microsoft.ServiceFabric/clusters/myCluster\"),\n\t// \t\t\tLocation: to.Ptr(\"eastus\"),\n\t// \t\t\tTags: map[string]*string{\n\t// \t\t\t},\n\t// \t\t\tProperties: &armservicefabric.ClusterProperties{\n\t// \t\t\t\tAddOnFeatures: []*armservicefabric.AddOnFeatures{\n\t// \t\t\t\t\tto.Ptr(armservicefabric.AddOnFeaturesRepairManager),\n\t// \t\t\t\t\tto.Ptr(armservicefabric.AddOnFeaturesDNSService),\n\t// \t\t\t\t\tto.Ptr(armservicefabric.AddOnFeaturesBackupRestoreService),\n\t// \t\t\t\t\tto.Ptr(armservicefabric.AddOnFeaturesResourceMonitorService)},\n\t// \t\t\t\t\tAvailableClusterVersions: []*armservicefabric.ClusterVersionDetails{\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tCodeVersion: to.Ptr(\"6.1.480.9494\"),\n\t// \t\t\t\t\t\t\tEnvironment: to.Ptr(armservicefabric.ClusterEnvironmentWindows),\n\t// \t\t\t\t\t\t\tSupportExpiryUTC: to.Ptr(\"2018-06-15T23:59:59.9999999\"),\n\t// \t\t\t\t\t}},\n\t// \t\t\t\t\tAzureActiveDirectory: &armservicefabric.AzureActiveDirectory{\n\t// \t\t\t\t\t\tClientApplication: to.Ptr(\"d151ad89-4bce-4ae8-b3d1-1dc79679fa75\"),\n\t// \t\t\t\t\t\tClusterApplication: to.Ptr(\"5886372e-7bf4-4878-a497-8098aba608ae\"),\n\t// \t\t\t\t\t\tTenantID: to.Ptr(\"6abcc6a0-8666-43f1-87b8-172cf86a9f9c\"),\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\tCertificateCommonNames: &armservicefabric.ServerCertificateCommonNames{\n\t// \t\t\t\t\t\tCommonNames: []*armservicefabric.ServerCertificateCommonName{\n\t// \t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\tCertificateCommonName: to.Ptr(\"abc.com\"),\n\t// \t\t\t\t\t\t\t\tCertificateIssuerThumbprint: to.Ptr(\"12599211F8F14C90AFA9532AD79A6F2CA1C00622\"),\n\t// \t\t\t\t\t\t}},\n\t// \t\t\t\t\t\tX509StoreName: to.Ptr(armservicefabric.StoreNameMy),\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\tClientCertificateCommonNames: []*armservicefabric.ClientCertificateCommonName{\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tCertificateCommonName: to.Ptr(\"abc.com\"),\n\t// \t\t\t\t\t\t\tCertificateIssuerThumbprint: to.Ptr(\"5F3660C715EBBDA31DB1FFDCF508302348DE8E7A\"),\n\t// \t\t\t\t\t\t\tIsAdmin: to.Ptr(true),\n\t// \t\t\t\t\t}},\n\t// \t\t\t\t\tClientCertificateThumbprints: []*armservicefabric.ClientCertificateThumbprint{\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tCertificateThumbprint: to.Ptr(\"5F3660C715EBBDA31DB1FFDCF508302348DE8E7A\"),\n\t// \t\t\t\t\t\t\tIsAdmin: to.Ptr(false),\n\t// \t\t\t\t\t}},\n\t// \t\t\t\t\tClusterCodeVersion: to.Ptr(\"6.1.480.9494\"),\n\t// \t\t\t\t\tClusterEndpoint: to.Ptr(\"https://eastus.servicefabric.azure.com\"),\n\t// \t\t\t\t\tClusterID: to.Ptr(\"92584666-9889-4ae8-8d02-91902923d37f\"),\n\t// \t\t\t\t\tClusterState: to.Ptr(armservicefabric.ClusterStateWaitingForNodes),\n\t// \t\t\t\t\tDiagnosticsStorageAccountConfig: &armservicefabric.DiagnosticsStorageAccountConfig{\n\t// \t\t\t\t\t\tBlobEndpoint: to.Ptr(\"https://diag.blob.core.windows.net/\"),\n\t// \t\t\t\t\t\tProtectedAccountKeyName: to.Ptr(\"StorageAccountKey1\"),\n\t// \t\t\t\t\t\tQueueEndpoint: to.Ptr(\"https://diag.queue.core.windows.net/\"),\n\t// \t\t\t\t\t\tStorageAccountName: to.Ptr(\"diag\"),\n\t// \t\t\t\t\t\tTableEndpoint: to.Ptr(\"https://diag.table.core.windows.net/\"),\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\tFabricSettings: []*armservicefabric.SettingsSectionDescription{\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tName: to.Ptr(\"UpgradeService\"),\n\t// \t\t\t\t\t\t\tParameters: []*armservicefabric.SettingsParameterDescription{\n\t// \t\t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\t\tName: to.Ptr(\"AppPollIntervalInSeconds\"),\n\t// \t\t\t\t\t\t\t\t\tValue: to.Ptr(\"60\"),\n\t// \t\t\t\t\t\t\t}},\n\t// \t\t\t\t\t}},\n\t// \t\t\t\t\tManagementEndpoint: to.Ptr(\"https://myCluster.eastus.cloudapp.azure.com:19080\"),\n\t// \t\t\t\t\tNodeTypes: []*armservicefabric.NodeTypeDescription{\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tName: to.Ptr(\"nt1vm\"),\n\t// \t\t\t\t\t\t\tApplicationPorts: &armservicefabric.EndpointRangeDescription{\n\t// \t\t\t\t\t\t\t\tEndPort: to.Ptr[int32](30000),\n\t// \t\t\t\t\t\t\t\tStartPort: to.Ptr[int32](20000),\n\t// \t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\tClientConnectionEndpointPort: to.Ptr[int32](19000),\n\t// \t\t\t\t\t\t\tDurabilityLevel: to.Ptr(armservicefabric.DurabilityLevelBronze),\n\t// \t\t\t\t\t\t\tEphemeralPorts: &armservicefabric.EndpointRangeDescription{\n\t// \t\t\t\t\t\t\t\tEndPort: to.Ptr[int32](64000),\n\t// \t\t\t\t\t\t\t\tStartPort: to.Ptr[int32](49000),\n\t// \t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\tHTTPGatewayEndpointPort: to.Ptr[int32](19007),\n\t// \t\t\t\t\t\t\tIsPrimary: to.Ptr(true),\n\t// \t\t\t\t\t\t\tVMInstanceCount: to.Ptr[int32](5),\n\t// \t\t\t\t\t}},\n\t// \t\t\t\t\tProvisioningState: to.Ptr(armservicefabric.ProvisioningStateSucceeded),\n\t// \t\t\t\t\tReliabilityLevel: to.Ptr(armservicefabric.ReliabilityLevelSilver),\n\t// \t\t\t\t\tReverseProxyCertificateCommonNames: &armservicefabric.ServerCertificateCommonNames{\n\t// \t\t\t\t\t\tCommonNames: []*armservicefabric.ServerCertificateCommonName{\n\t// \t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\tCertificateCommonName: to.Ptr(\"abc.com\"),\n\t// \t\t\t\t\t\t\t\tCertificateIssuerThumbprint: to.Ptr(\"12599211F8F14C90AFA9532AD79A6F2CA1C00622\"),\n\t// \t\t\t\t\t\t}},\n\t// \t\t\t\t\t\tX509StoreName: to.Ptr(armservicefabric.StoreNameMy),\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\tUpgradeDescription: &armservicefabric.ClusterUpgradePolicy{\n\t// \t\t\t\t\t\tDeltaHealthPolicy: &armservicefabric.ClusterUpgradeDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\tApplicationDeltaHealthPolicies: map[string]*armservicefabric.ApplicationDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\"fabric:/myApp1\": &armservicefabric.ApplicationDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\tDefaultServiceTypeDeltaHealthPolicy: &armservicefabric.ServiceTypeDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\t\tMaxPercentDeltaUnhealthyServices: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\t\tServiceTypeDeltaHealthPolicies: map[string]*armservicefabric.ServiceTypeDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\t\t\"myServiceType1\": &armservicefabric.ServiceTypeDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\t\t\tMaxPercentDeltaUnhealthyServices: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\tMaxPercentDeltaUnhealthyApplications: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\tMaxPercentDeltaUnhealthyNodes: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\tMaxPercentUpgradeDomainDeltaUnhealthyNodes: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\tForceRestart: to.Ptr(false),\n\t// \t\t\t\t\t\tHealthCheckRetryTimeout: to.Ptr(\"00:05:00\"),\n\t// \t\t\t\t\t\tHealthCheckStableDuration: to.Ptr(\"00:00:30\"),\n\t// \t\t\t\t\t\tHealthCheckWaitDuration: to.Ptr(\"00:00:30\"),\n\t// \t\t\t\t\t\tHealthPolicy: &armservicefabric.ClusterHealthPolicy{\n\t// \t\t\t\t\t\t\tApplicationHealthPolicies: map[string]*armservicefabric.ApplicationHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\"fabric:/myApp1\": &armservicefabric.ApplicationHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\tDefaultServiceTypeHealthPolicy: &armservicefabric.ServiceTypeHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\t\tMaxPercentUnhealthyServices: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\t\tServiceTypeHealthPolicies: map[string]*armservicefabric.ServiceTypeHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\t\t\"myServiceType1\": &armservicefabric.ServiceTypeHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\t\t\tMaxPercentUnhealthyServices: to.Ptr[int32](100),\n\t// \t\t\t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\tMaxPercentUnhealthyApplications: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\tMaxPercentUnhealthyNodes: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\tUpgradeDomainTimeout: to.Ptr(\"00:15:00\"),\n\t// \t\t\t\t\t\tUpgradeReplicaSetCheckTimeout: to.Ptr(\"00:10:00\"),\n\t// \t\t\t\t\t\tUpgradeTimeout: to.Ptr(\"01:00:00\"),\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\tUpgradeMode: to.Ptr(armservicefabric.UpgradeModeManual),\n\t// \t\t\t\t\tVMImage: to.Ptr(\"Windows\"),\n\t// \t\t\t\t},\n\t// \t\t\t},\n\t// \t\t\t{\n\t// \t\t\t\tName: to.Ptr(\"myCluster2\"),\n\t// \t\t\t\tType: to.Ptr(\"Microsoft.ServiceFabric/clusters\"),\n\t// \t\t\t\tEtag: to.Ptr(\"W/\\\"636462502164040075\\\"\"),\n\t// \t\t\t\tID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/resRg/providers/Microsoft.ServiceFabric/clusters/myCluster2\"),\n\t// \t\t\t\tLocation: to.Ptr(\"eastus\"),\n\t// \t\t\t\tTags: map[string]*string{\n\t// \t\t\t\t},\n\t// \t\t\t\tProperties: &armservicefabric.ClusterProperties{\n\t// \t\t\t\t\tAddOnFeatures: []*armservicefabric.AddOnFeatures{\n\t// \t\t\t\t\t\tto.Ptr(armservicefabric.AddOnFeaturesRepairManager)},\n\t// \t\t\t\t\t\tAvailableClusterVersions: []*armservicefabric.ClusterVersionDetails{\n\t// \t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\tCodeVersion: to.Ptr(\"6.1.187.1\"),\n\t// \t\t\t\t\t\t\t\tEnvironment: to.Ptr(armservicefabric.ClusterEnvironmentLinux),\n\t// \t\t\t\t\t\t\t\tSupportExpiryUTC: to.Ptr(\"2018-06-15T23:59:59.9999999\"),\n\t// \t\t\t\t\t\t}},\n\t// \t\t\t\t\t\tClientCertificateCommonNames: []*armservicefabric.ClientCertificateCommonName{\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\tClientCertificateThumbprints: []*armservicefabric.ClientCertificateThumbprint{\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\tClusterCodeVersion: to.Ptr(\"6.1.187.1\"),\n\t// \t\t\t\t\t\tClusterEndpoint: to.Ptr(\"https://eastus.servicefabric.azure.com\"),\n\t// \t\t\t\t\t\tClusterID: to.Ptr(\"2747e469-b24e-4039-8a0a-46151419523f\"),\n\t// \t\t\t\t\t\tClusterState: to.Ptr(armservicefabric.ClusterStateWaitingForNodes),\n\t// \t\t\t\t\t\tDiagnosticsStorageAccountConfig: &armservicefabric.DiagnosticsStorageAccountConfig{\n\t// \t\t\t\t\t\t\tBlobEndpoint: to.Ptr(\"https://diag.blob.core.windows.net/\"),\n\t// \t\t\t\t\t\t\tProtectedAccountKeyName: to.Ptr(\"StorageAccountKey1\"),\n\t// \t\t\t\t\t\t\tQueueEndpoint: to.Ptr(\"https://diag.queue.core.windows.net/\"),\n\t// \t\t\t\t\t\t\tStorageAccountName: to.Ptr(\"diag\"),\n\t// \t\t\t\t\t\t\tTableEndpoint: to.Ptr(\"https://diag.table.core.windows.net/\"),\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\tFabricSettings: []*armservicefabric.SettingsSectionDescription{\n\t// \t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\tName: to.Ptr(\"UpgradeService\"),\n\t// \t\t\t\t\t\t\t\tParameters: []*armservicefabric.SettingsParameterDescription{\n\t// \t\t\t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\t\t\tName: to.Ptr(\"AppPollIntervalInSeconds\"),\n\t// \t\t\t\t\t\t\t\t\t\tValue: to.Ptr(\"60\"),\n\t// \t\t\t\t\t\t\t\t}},\n\t// \t\t\t\t\t\t}},\n\t// \t\t\t\t\t\tManagementEndpoint: to.Ptr(\"http://myCluster2.eastus.cloudapp.azure.com:19080\"),\n\t// \t\t\t\t\t\tNodeTypes: []*armservicefabric.NodeTypeDescription{\n\t// \t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\tName: to.Ptr(\"nt1vm\"),\n\t// \t\t\t\t\t\t\t\tApplicationPorts: &armservicefabric.EndpointRangeDescription{\n\t// \t\t\t\t\t\t\t\t\tEndPort: to.Ptr[int32](30000),\n\t// \t\t\t\t\t\t\t\t\tStartPort: to.Ptr[int32](20000),\n\t// \t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\tClientConnectionEndpointPort: to.Ptr[int32](19000),\n\t// \t\t\t\t\t\t\t\tDurabilityLevel: to.Ptr(armservicefabric.DurabilityLevelBronze),\n\t// \t\t\t\t\t\t\t\tEphemeralPorts: &armservicefabric.EndpointRangeDescription{\n\t// \t\t\t\t\t\t\t\t\tEndPort: to.Ptr[int32](64000),\n\t// \t\t\t\t\t\t\t\t\tStartPort: to.Ptr[int32](49000),\n\t// \t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\tHTTPGatewayEndpointPort: to.Ptr[int32](19007),\n\t// \t\t\t\t\t\t\t\tIsPrimary: to.Ptr(true),\n\t// \t\t\t\t\t\t\t\tVMInstanceCount: to.Ptr[int32](5),\n\t// \t\t\t\t\t\t}},\n\t// \t\t\t\t\t\tProvisioningState: to.Ptr(armservicefabric.ProvisioningStateSucceeded),\n\t// \t\t\t\t\t\tReliabilityLevel: to.Ptr(armservicefabric.ReliabilityLevelSilver),\n\t// \t\t\t\t\t\tUpgradeDescription: &armservicefabric.ClusterUpgradePolicy{\n\t// \t\t\t\t\t\t\tDeltaHealthPolicy: &armservicefabric.ClusterUpgradeDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\t\tMaxPercentDeltaUnhealthyApplications: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t\tMaxPercentDeltaUnhealthyNodes: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t\tMaxPercentUpgradeDomainDeltaUnhealthyNodes: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\tForceRestart: to.Ptr(false),\n\t// \t\t\t\t\t\t\tHealthCheckRetryTimeout: to.Ptr(\"00:05:00\"),\n\t// \t\t\t\t\t\t\tHealthCheckStableDuration: to.Ptr(\"00:00:30\"),\n\t// \t\t\t\t\t\t\tHealthCheckWaitDuration: to.Ptr(\"00:00:30\"),\n\t// \t\t\t\t\t\t\tHealthPolicy: &armservicefabric.ClusterHealthPolicy{\n\t// \t\t\t\t\t\t\t\tMaxPercentUnhealthyApplications: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t\tMaxPercentUnhealthyNodes: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\tUpgradeDomainTimeout: to.Ptr(\"00:15:00\"),\n\t// \t\t\t\t\t\t\tUpgradeReplicaSetCheckTimeout: to.Ptr(\"00:10:00\"),\n\t// \t\t\t\t\t\t\tUpgradeTimeout: to.Ptr(\"01:00:00\"),\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\tUpgradeMode: to.Ptr(armservicefabric.UpgradeModeManual),\n\t// \t\t\t\t\t\tVMImage: to.Ptr(\"Ubuntu\"),\n\t// \t\t\t\t\t},\n\t// \t\t\t}},\n\t// \t\t}\n}", "func NewInClusterK8sClient() (Client, error) {\n\thost, port := os.Getenv(\"KUBERNETES_SERVICE_HOST\"), os.Getenv(\"KUBERNETES_SERVICE_PORT\")\n\tif host == \"\" || port == \"\" {\n\t\treturn nil, fmt.Errorf(\"unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be defined\")\n\t}\n\ttoken, err := os.ReadFile(serviceAccountToken)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tca, err := os.ReadFile(serviceAccountCACert)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcertPool := x509.NewCertPool()\n\tcertPool.AppendCertsFromPEM(ca)\n\ttransport := &http.Transport{TLSClientConfig: &tls.Config{\n\t\tMinVersion: tls.VersionTLS12,\n\t\tRootCAs: certPool,\n\t}}\n\thttpClient := &http.Client{Transport: transport, Timeout: time.Nanosecond * 0}\n\n\treturn &k8sClient{\n\t\thost: \"https://\" + net.JoinHostPort(host, port),\n\t\ttoken: string(token),\n\t\thttpClient: httpClient,\n\t}, nil\n}", "func GetKubernetesClientE(t testing.TestingT) (*kubernetes.Clientset, error) {\n\tkubeConfigPath, err := GetKubeConfigPathE(t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\toptions := NewKubectlOptions(\"\", kubeConfigPath, \"default\")\n\treturn GetKubernetesClientFromOptionsE(t, options)\n}", "func New(c rest.Interface) *Clientset {\n\tvar cs Clientset\n\tcs.ApiextensionsV1beta1Client = apiextensionsv1beta1.New(c)\n\tcs.ConfigV1alpha1Client = configv1alpha1.New(c)\n\tcs.LoadbalanceV1alpha2Client = loadbalancev1alpha2.New(c)\n\tcs.ReleaseV1alpha1Client = releasev1alpha1.New(c)\n\tcs.ResourceV1alpha1Client = resourcev1alpha1.New(c)\n\tcs.ResourceV1beta1Client = resourcev1beta1.New(c)\n\n\tcs.Clientset = kubernetes.New(c)\n\treturn &cs\n}", "func getDSClient() v1.DaemonSetInterface {\n\tlog.Debug(\"Creating Daemonset client.\")\n\treturn client.AppsV1().DaemonSets(checkNamespace)\n}", "func newK8sExtClient(config Config) (apiextensionsclient.Interface, error) {\n\trestConfig, err := newBaseRestConfig(config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"creating REST config: %s\", err)\n\t}\n\n\treturn apiextensionsclient.NewForConfig(restConfig)\n}", "func GetClient() *rest.RESTClient {\n\tconfig, err := buildOutOfClusterConfig()\n\tif err != nil {\n\t\tlog.Warnf(\"Can not get kubernetes config: %v\", err)\n\n\t\tconfig, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Can not get kubernetes config: %v\", err)\n\t\t}\n\t}\n\tconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}\n\tc, err := rest.UnversionedRESTClientFor(config)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Cannot create REST client, try setting KUBECONFIG environment variable: %v\", err)\n\t}\n\treturn c\n}", "func (s *service) getKeySet(ctx context.Context) (jwk.Set, error) {\n\n\tb, err := s.cache.JWKS(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unexpected error occured querying redis for jwks: %w\", err)\n\t}\n\n\tif b == nil {\n\t\tres, err := s.client.Get(s.config.JWKSURI)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to retrieve jwks from sso: %w\", err)\n\t\t}\n\n\t\tif res.StatusCode != http.StatusOK {\n\t\t\treturn nil, fmt.Errorf(\"unexpected status code recieved while fetching jwks. %d\", res.StatusCode)\n\t\t}\n\n\t\tbuf, err := ioutil.ReadAll(res.Body)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to read jwk response body: %w\", err)\n\t\t}\n\n\t\terr = s.cache.SaveJWKS(ctx, buf)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to save jwks to cache layer: %w\", err)\n\t\t}\n\n\t\tb = buf\n\t}\n\n\treturn jwk.ParseString(string(b))\n\n}", "func getK8sEvents(eventList *v1.EventList, namespace string) AsyncAssertion {\n\tctx := context.TODO()\n\treturn Eventually(func() v1.EventList {\n\t\terr := k8sClient.List(ctx, eventList, client.InNamespace(namespace))\n\t\tif err != nil {\n\t\t\treturn v1.EventList{}\n\t\t}\n\t\treturn *eventList\n\t})\n}", "func GetClients(srcPrefix, dstPrefix, srcPath, dstPath string) (interface{}, interface{}, error) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tsrcClient, tested, err := initClient(ctx, nil, srcPrefix, srcPath, \"\")\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdstClient, _, err := initClient(ctx, srcClient, dstPrefix, dstPath, tested)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn srcClient, dstClient, nil\n}", "func createClientMap(memberClusters []string, operatorCluster, kubeConfigPath string, getClient func(clusterName string, kubeConfigPath string) (kubernetes.Interface, error)) (map[string]kubernetes.Interface, error) {\n\tclientMap := map[string]kubernetes.Interface{}\n\tfor _, c := range memberClusters {\n\t\tclientset, err := getClient(c, kubeConfigPath)\n\t\tif err != nil {\n\t\t\treturn nil, xerrors.Errorf(\"failed to create clientset map: %w\", err)\n\t\t}\n\t\tclientMap[c] = clientset\n\t}\n\n\tclientset, err := getClient(operatorCluster, kubeConfigPath)\n\tif err != nil {\n\t\treturn nil, xerrors.Errorf(\"failed to create clientset map: %w\", err)\n\t}\n\tclientMap[operatorCluster] = clientset\n\treturn clientMap, nil\n}", "func NewImpersonatingKubernetesClientset(user user.Info, config restclient.Config) (kclientset.Interface, error) {\n\timpersonatingConfig := NewImpersonatingConfig(user, config)\n\treturn kclientset.NewForConfig(&impersonatingConfig)\n}" ]
[ "0.76710963", "0.7585634", "0.7210688", "0.7179806", "0.7169011", "0.71687186", "0.71082574", "0.7073691", "0.7067189", "0.69029", "0.67942584", "0.67574716", "0.6589422", "0.6555601", "0.6509815", "0.65093964", "0.6495728", "0.6439707", "0.64083123", "0.63930845", "0.6371384", "0.625096", "0.62347823", "0.6215395", "0.6196365", "0.6191963", "0.6184185", "0.6181337", "0.61800814", "0.61509216", "0.6136459", "0.61255795", "0.6113789", "0.61110413", "0.60891455", "0.605866", "0.6048746", "0.60453695", "0.60437965", "0.6000736", "0.59846324", "0.59622526", "0.5927958", "0.59105974", "0.59009486", "0.5867864", "0.5852429", "0.5851405", "0.5850107", "0.58428234", "0.5830175", "0.58157724", "0.5799595", "0.57970417", "0.5794705", "0.5793992", "0.57926106", "0.5782094", "0.57782483", "0.57610184", "0.57454675", "0.57330847", "0.57253385", "0.5708612", "0.57076955", "0.5689706", "0.5687369", "0.5678799", "0.5676938", "0.56510466", "0.56380516", "0.56363666", "0.5625316", "0.5611877", "0.5611403", "0.5611403", "0.5602503", "0.5598608", "0.5584233", "0.55828345", "0.5576855", "0.5540017", "0.5539269", "0.5537103", "0.55340534", "0.55308795", "0.5525517", "0.55129665", "0.5505399", "0.55014116", "0.54955715", "0.5492923", "0.54916286", "0.5486746", "0.54863036", "0.54634976", "0.54628664", "0.5455921", "0.545467", "0.5443412" ]
0.797845
0
GetMappedNote returns AD2 note for givem GP6
func GetMappedNote(key int) int { return noteMap[key] }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetRuleNote(ruleGetNote map[string]string) (note string, err error) {\n sidMap := ruleGetNote[\"sid\"]\n uuidMap := ruleGetNote[\"uuid\"]\n var noteText string\n if ndb.Rdb == nil {\n logs.Error(\"GetRuleNote -- Can't access to database\")\n return \"\", errors.New(\"GetRuleNote -- Can't access to database\")\n }\n row := ndb.Rdb.QueryRow(\"SELECT ruleNote FROM rule_note WHERE ruleset_uniqueid=\\\"\" + uuidMap + \"\\\" and rule_sid=\\\"\" + sidMap + \"\\\";\")\n err = row.Scan(&noteText)\n\n if err != nil {\n // logs.Error(\"DB GetNote -> Can't read query result: \"+err.Error())\n return \"\", err\n }\n return noteText, nil\n}", "func (g *Grafeas) GetNote(pID, nID string) (*swagger.Note, *errors.AppError) {\n\treturn g.S.GetNote(pID, nID)\n}", "func (pg *MongoDb) GetNote(ctx context.Context, pID, nID string) (*pb.Note, error) {\n\treturn nil, nil\n}", "func (db *AssistantDB) GetNote(userID string, noteID int64) (*pb.Note, error) {\n\tparams := make(map[string]interface{})\n\n\tparams[\"userID\"] = userID\n\tparams[\"noteID\"] = noteID\n\n\tresult, err := db.ankaDB.Query(context.Background(), queryGetNote, params)\n\tif err != nil {\n\t\tjarvisbase.Warn(\"AssistantDB.GetNote\", zap.Error(err), jarvisbase.JSON(\"params\", params))\n\n\t\treturn nil, err\n\t}\n\n\terr = ankadb.GetResultError(result)\n\tif err != nil {\n\t\tjarvisbase.Warn(\"AssistantDB.GetNote\", zap.Error(err), jarvisbase.JSON(\"params\", params))\n\n\t\treturn nil, err\n\t}\n\n\t// jarvisbase.Info(\"AssistantDB.GetNote\",\n\t// \tjarvisbase.JSON(\"result\", result))\n\n\trn := &ResultNote{}\n\terr = ankadb.MakeObjFromResult(result, rn)\n\tif err != nil {\n\t\tjarvisbase.Warn(\"AssistantDB.GetNote\", zap.Error(err), jarvisbase.JSON(\"params\", params))\n\n\t\treturn nil, err\n\t}\n\n\treturn ResultNote2Note(rn), nil\n}", "func bbGetNote(w http.ResponseWriter, r *http.Request) {\n\ttaskId := gimlet.GetVars(r)[\"task_id\"]\n\tn, err := model.NoteForTask(taskId)\n\tif err != nil {\n\t\tgimlet.WriteJSONInternalError(w, err.Error())\n\t\treturn\n\t}\n\tif n == nil {\n\t\tgimlet.WriteJSON(w, \"\")\n\t\treturn\n\t}\n\tgimlet.WriteJSON(w, n)\n}", "func bbGetNote(w http.ResponseWriter, r *http.Request) {\n\ttaskId := gimlet.GetVars(r)[\"task_id\"]\n\tn, err := model.NoteForTask(taskId)\n\tif err != nil {\n\t\tgimlet.WriteJSONInternalError(w, err.Error())\n\t\treturn\n\t}\n\tif n == nil {\n\t\tgimlet.WriteJSON(w, \"\")\n\t\treturn\n\t}\n\tgimlet.WriteJSON(w, n)\n}", "func bbGetNote(w http.ResponseWriter, r *http.Request) {\n\ttaskId := mux.Vars(r)[\"task_id\"]\n\tn, err := model.NoteForTask(taskId)\n\tif err != nil {\n\t\tgimlet.WriteJSONInternalError(w, err.Error())\n\t\treturn\n\t}\n\tif n == nil {\n\t\tgimlet.WriteJSON(w, \"\")\n\t\treturn\n\t}\n\tgimlet.WriteJSON(w, n)\n}", "func (p *NoteStoreClient) GetNote(ctx context.Context, authenticationToken string, guid Types.Guid, withContent bool, withResourcesData bool, withResourcesRecognition bool, withResourcesAlternateData bool) (r *Types.Note, userException *Errors.EDAMUserException, systemException *Errors.EDAMSystemException, notFoundException *Errors.EDAMNotFoundException, err error) {\n\tif err = p.sendGetNote(ctx, authenticationToken, guid, withContent, withResourcesData, withResourcesRecognition, withResourcesAlternateData); err != nil {\n\t\treturn\n\t}\n\treturn p.recvGetNote(ctx)\n}", "func GetNote(Ob map[string]interface{}, userId string) *utils.Response {\n\tvar path string\n\tvar reNote utils.Note\n\tvar status uint8 = 0\n\tif _, ok := Ob[\"Path\"].(string); ok {\n\t\tpath = Ob[\"Path\"].(string)\n\t} else {\n\t\treturn utils.WITHOUT_PARAMETERS\n\t}\n\tif _, ok := Ob[\"Status\"].(float64); ok {\n\t\tstatus = uint8(Ob[\"Status\"].(float64))\n\t}\n\tnote := model.NewNote(path)\n\tnote.UID = userId\n\tbeego.Debug(note)\n\tnotebook, err := note.GetByPathAndStatus(status)\n\tif notebook == nil || err != nil {\n\t\treturn utils.NOTE_NOT_EXIST\n\t}\n\treNote = NoteResp(*notebook)\n\treturn utils.NewResponse(0, \"\", reNote)\n}", "func (p *NoteStoreClient) GetNote(ctx context.Context, authenticationToken string, guid GUID, withContent bool, withResourcesData bool, withResourcesRecognition bool, withResourcesAlternateData bool) (r *Note, err error) {\n var _args103 NoteStoreGetNoteArgs\n _args103.AuthenticationToken = authenticationToken\n _args103.GUID = guid\n _args103.WithContent = withContent\n _args103.WithResourcesData = withResourcesData\n _args103.WithResourcesRecognition = withResourcesRecognition\n _args103.WithResourcesAlternateData = withResourcesAlternateData\n var _result104 NoteStoreGetNoteResult\n if err = p.Client_().Call(ctx, \"getNote\", &_args103, &_result104); err != nil {\n return\n }\n switch {\n case _result104.UserException!= nil:\n return r, _result104.UserException\n case _result104.SystemException!= nil:\n return r, _result104.SystemException\n case _result104.NotFoundException!= nil:\n return r, _result104.NotFoundException\n }\n\n return _result104.GetSuccess(), nil\n}", "func (m *Application) GetNotes()(*string) {\n return m.notes\n}", "func (c *API) GetNote(module Module, id string) (data NotesResponse, err error) {\n\tendpoint := zoho.Endpoint{\n\t\tName: \"notes\",\n\t\tURL: fmt.Sprintf(\n\t\t\t\"https://www.zohoapis.%s/crm/v2/%s/%s/Notes\",\n\t\t\tc.ZohoTLD,\n\t\t\tmodule,\n\t\t\tid,\n\t\t),\n\t\tMethod: zoho.HTTPGet,\n\t\tResponseData: &NotesResponse{},\n\t}\n\terr = c.Zoho.HTTPRequest(&endpoint)\n\tif err != nil {\n\t\treturn NotesResponse{}, fmt.Errorf(\"Failed to retrieve notes: %s\", err)\n\t}\n\n\tif v, ok := endpoint.ResponseData.(*NotesResponse); ok {\n\t\treturn *v, nil\n\t}\n\n\treturn NotesResponse{}, fmt.Errorf(\"Data returned was not 'NotesResponse'\")\n}", "func LookupNote(ctx *pulumi.Context, args *LookupNoteArgs, opts ...pulumi.InvokeOption) (*LookupNoteResult, error) {\n\topts = internal.PkgInvokeDefaultOpts(opts)\n\tvar rv LookupNoteResult\n\terr := ctx.Invoke(\"google-native:containeranalysis/v1alpha1:getNote\", args, &rv, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &rv, nil\n}", "func (g *Grafeas) GetOccurrenceNote(pID, oID string) (*swagger.Note, *errors.AppError) {\n\to, err := g.S.GetOccurrence(pID, oID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnpID, nID, err := name.ParseNote(o.NoteName)\n\tif err != nil {\n\t\tlog.Printf(\"Invalid note name: %v\", o.Name)\n\t\treturn nil, &errors.AppError{Err: fmt.Sprintf(\"Invalid note name: %v\", o.NoteName),\n\t\t\tStatusCode: http.StatusBadRequest}\n\t}\n\treturn g.S.GetNote(npID, nID)\n}", "func (o *Cell) GetMidiNote() int {\n\tif o.diff.MidiNote != nil {\n\t\treturn *o.diff.MidiNote\n\t}\n\treturn o.MidiNote\n}", "func getNote(event *types.Event) (string, error) {\n\teventJSON, err := json.Marshal(event)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"Event data update:\\n\\n%s\", eventJSON), nil\n}", "func getNote(event *types.Event) (string, error) {\n\teventJSON, err := json.Marshal(event)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"Event data update:\\n\\n%s\", eventJSON), nil\n}", "func (rn *ReleaseNote) ToNoteMap() (string, error) {\n\tnoteMap := &ReleaseNotesMap{\n\t\tPR: rn.PrNumber,\n\t\tCommit: rn.Commit,\n\t}\n\n\tnoteMap.ReleaseNote.Text = &rn.Text\n\tnoteMap.ReleaseNote.Documentation = &rn.Documentation\n\tnoteMap.ReleaseNote.Author = &rn.Author\n\tnoteMap.ReleaseNote.Areas = &rn.Areas\n\tnoteMap.ReleaseNote.Kinds = &rn.Kinds\n\tnoteMap.ReleaseNote.SIGs = &rn.SIGs\n\tnoteMap.ReleaseNote.Feature = &rn.Feature\n\tnoteMap.ReleaseNote.ActionRequired = &rn.ActionRequired\n\tnoteMap.ReleaseNote.DoNotPublish = &rn.DoNotPublish\n\n\tyamlCode, err := yaml.Marshal(&noteMap)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"marshalling release note to map: %w\", err)\n\t}\n\n\treturn string(yamlCode), nil\n}", "func (pg *MongoDb) GetOccurrenceNote(ctx context.Context, pID, oID string) (*pb.Note, error) {\n\treturn nil, nil\n}", "func (a *Authorization) GetNote() string {\n\tif a == nil || a.Note == nil {\n\t\treturn \"\"\n\t}\n\treturn *a.Note\n}", "func (o *IPAllowlistEntryAttributes) GetNote() string {\n\tif o == nil || o.Note == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Note\n}", "func (s *NotesService) GetEpicNote(gid interface{}, epic, note int, options ...RequestOptionFunc) (*Note, *Response, error) {\n\tgroup, err := parseID(gid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"groups/%s/epics/%d/notes/%d\", PathEscape(group), epic, note)\n\n\treq, err := s.client.NewRequest(http.MethodGet, u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tn := new(Note)\n\tresp, err := s.client.Do(req, n)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn n, resp, nil\n}", "func (bbp *BuildBaronPlugin) getNote(w http.ResponseWriter, r *http.Request) {\n\ttaskId := mux.Vars(r)[\"task_id\"]\n\tn, err := NoteForTask(taskId)\n\tif err != nil {\n\t\tplugin.WriteJSON(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\tif n == nil {\n\t\tplugin.WriteJSON(w, http.StatusOK, \"\")\n\t\treturn\n\t}\n\tplugin.WriteJSON(w, http.StatusOK, n)\n}", "func (a *AuthorizationUpdateRequest) GetNote() string {\n\tif a == nil || a.Note == nil {\n\t\treturn \"\"\n\t}\n\treturn *a.Note\n}", "func (b *Button) GetNote() (str string) {\n\ttextLength := b.SendMessage(win.BCM_GETNOTELENGTH, 0, 0)\n\tbuf := make([]uint16, textLength+1)\n\tret := b.SendMessage(win.BCM_GETNOTE, textLength+1, uintptr(unsafe.Pointer(&buf[0])))\n\tif int(ret) == 0 {\n\t\tlog.Println(\"GetNote error:\", b, \"len:\", textLength)\n\t} else {\n\t\tstr = syscall.UTF16ToString(buf)\n\t}\n\treturn\n}", "func ReadNote(noteID string) (Note, error) {\n\t// construct the query parameters\n\tquery := &dynamodb.GetItemInput{\n\t\tKey: map[string]*dynamodb.AttributeValue{\n\t\t\t\"NoteID\": {\n\t\t\t\tS: aws.String(noteID),\n\t\t\t},\n\t\t},\n\t\tTableName: aws.String(DDBTable),\n\t}\n\n\t// query note from DynamoDB, checking for errors\n\tresult, err := ddb.GetItem(query)\n\tif err != nil {\n\t\treturn Note{}, err\n\t}\n\tif result.Item == nil {\n\t\tmsg := \"A note with ID \" + noteID + \" does not exist\"\n\t\treturn Note{}, errors.New(msg)\n\t}\n\n\t// unmarshall return date into a Note struct\n\tnote := Note{}\n\terr = dynamodbattribute.UnmarshalMap(result.Item, &note)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Failed to unmarshal Record, %v\", err))\n\t}\n\n\treturn note, nil\n}", "func (ns *NoteServiceContext) GetNote(id int) (*model.Note, error) {\n\treturn ns.Store.GetNote(nil, id)\n}", "func (a *AuthorizationRequest) GetNote() string {\n\tif a == nil || a.Note == nil {\n\t\treturn \"\"\n\t}\n\treturn *a.Note\n}", "func NoteForTask(taskId string) (*Note, error) {\n\tn := &Note{}\n\terr := db.FindOneQ(\n\t\tNotesCollection,\n\t\tdb.Query(bson.D{{TaskIdKey, taskId}}),\n\t\tn,\n\t)\n\tif err == mgo.ErrNotFound {\n\t\treturn nil, nil\n\t}\n\treturn n, err\n}", "func (o *TransactionSplit) GetNotes() string {\n\tif o == nil || o.Notes.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Notes.Get()\n}", "func GetReleaseNote(tag string, list string) string {\n\treturn \"Release \" + tag + \"\\n\\n\" + \"## \" + tag + \"\\n\" + list\n}", "func getNoteView(c *gin.Context) {\n\tidString := c.Param(\"id\")\n\tid, err := strconv.Atoi(idString)\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, common.ErrorHolder{Error: err.Error()})\n\t\treturn\n\t}\n\n\tdb := db.GetDbConnection()\n\tdefer db.Close()\n\n\tnote := &Note{ID: id}\n\terr = db.Model(note).WherePK().Select()\n\tif err != nil {\n\t\tc.JSON(http.StatusNotFound, common.ErrorHolder{Error: err.Error()})\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, note)\n}", "func (o *IPAllowlistEntryAttributes) GetNoteOk() (*string, bool) {\n\tif o == nil || o.Note == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Note, true\n}", "func (rs RESTServer) GetNote(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tid := vars[\"id\"]\n\n\tnote, err := rs.NoteRepo.GetNoteByUUID(id)\n\tif err != nil {\n\t\trs.buildErrorResponse(w, err)\n\t\treturn\n\t}\n\trs.buildSuccNoteResponse(w, *note)\n}", "func (db *DB) Note(id int64) (*Note, error) {\n\tvar note string\n\tvar created, modified int64\n\terr := db.db.QueryRow(\"SELECT note, created, modified FROM notes WHERE rowid=?\", id).Scan(&note, &created, &modified)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttopics, tags, err := topicsAndTags(db.db, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Note{ID: id, Text: note, Created: time.Unix(created, 0), Modified: time.Unix(modified, 0),\n\t\tTopics: topics, Tags: tags}, nil\n}", "func (p *ProjectCard) GetNote() string {\n\tif p == nil || p.Note == nil {\n\t\treturn \"\"\n\t}\n\treturn *p.Note\n}", "func (o *LocalDatabaseProvider) GetNotes() string {\n\tif o == nil || o.Notes == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Notes\n}", "func MRCreateNote(project string, discussionId string, mrNum int, opts *gitlab.CreateMergeRequestNoteOptions) (string, *gitlab.Note, error) {\n\tp, err := FindProject(project)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\tvar note *gitlab.Note\n\tif discussionId == \"\" {\n\t\tnote, _, err = lab.Notes.CreateMergeRequestNote(p.ID, mrNum, opts)\n\t} else {\n\t\tdopts := gitlab.AddMergeRequestDiscussionNoteOptions{\n\t\t\tBody: opts.Body,\n\t\t}\n\t\tnote, _, err = lab.Discussions.AddMergeRequestDiscussionNote(p.ID, mrNum, discussionId, &dopts)\n\t}\n\tif err != nil {\n\t\treturn \"\", note, err\n\t}\n\t// Command only note, probably.\n\tif note.ID == 0 {\n\t\treturn \"Added note\", note, nil\n\t}\n\n\t// Unlike MR, Note has no WebURL property, so we have to create it\n\t// ourselves from the project, noteable id and note id\n\treturn fmt.Sprintf(\"%s/merge_requests/%d#note_%d\", p.WebURL, note.NoteableIID, note.ID), note, nil\n}", "func (m *IosDeviceFeaturesConfiguration) GetLockScreenFootnote()(*string) {\n val, err := m.GetBackingStore().Get(\"lockScreenFootnote\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (p *NoteStoreClient) GetNoteApplicationData(ctx context.Context, authenticationToken string, guid Types.Guid) (r *Types.LazyMap, userException *Errors.EDAMUserException, systemException *Errors.EDAMSystemException, notFoundException *Errors.EDAMNotFoundException, err error) {\n\tif err = p.sendGetNoteApplicationData(ctx, authenticationToken, guid); err != nil {\n\t\treturn\n\t}\n\treturn p.recvGetNoteApplicationData(ctx)\n}", "func (o *InlineResponse20027Person) GetPrivateNotes() string {\n\tif o == nil || o.PrivateNotes == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.PrivateNotes\n}", "func CoveredPersonNoteGT(v string) predicate.CoveredPerson {\n\treturn predicate.CoveredPerson(func(s *sql.Selector) {\n\t\ts.Where(sql.GT(s.C(FieldCoveredPersonNote), v))\n\t})\n}", "func (c *Client) Note(userID discord.UserID) (string, error) {\n\tvar body struct {\n\t\tNote string `json:\"note\"`\n\t}\n\n\treturn body.Note, c.RequestJSON(&body, \"GET\", EndpointMe+\"/notes/\"+userID.String())\n}", "func (o *ApplianceImageBundleAllOf) GetNotes() string {\n\tif o == nil || o.Notes == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Notes\n}", "func (s *NotesService) GetSnippetNote(pid interface{}, snippet, note int, options ...RequestOptionFunc) (*Note, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects/%s/snippets/%d/notes/%d\", PathEscape(project), snippet, note)\n\n\treq, err := s.client.NewRequest(http.MethodGet, u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tn := new(Note)\n\tresp, err := s.client.Do(req, n)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn n, resp, nil\n}", "func (o *Cell) GetPrevMidiNote() int { return o.MidiNote }", "func (s *NotesService) GetIssueNote(pid interface{}, issue, note int, options ...RequestOptionFunc) (*Note, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects/%s/issues/%d/notes/%d\", PathEscape(project), issue, note)\n\n\treq, err := s.client.NewRequest(http.MethodGet, u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tn := new(Note)\n\tresp, err := s.client.Do(req, n)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn n, resp, nil\n}", "func RepoAddNote(g Grade, n Note) Note {\n g.Notes = append(g.Notes, n)\n return n\n}", "func (p *NoteStoreClient) GetNoteVersion(ctx context.Context, authenticationToken string, noteGuid Types.Guid, updateSequenceNum int32, withResourcesData bool, withResourcesRecognition bool, withResourcesAlternateData bool) (r *Types.Note, userException *Errors.EDAMUserException, systemException *Errors.EDAMSystemException, notFoundException *Errors.EDAMNotFoundException, err error) {\n\tif err = p.sendGetNoteVersion(ctx, authenticationToken, noteGuid, updateSequenceNum, withResourcesData, withResourcesRecognition, withResourcesAlternateData); err != nil {\n\t\treturn\n\t}\n\treturn p.recvGetNoteVersion(ctx)\n}", "func (o AppSharedCredentialsOutput) EnduserNote() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *AppSharedCredentials) pulumi.StringPtrOutput { return v.EnduserNote }).(pulumi.StringPtrOutput)\n}", "func (b *RouteBuilder) Note(notes string) *RouteBuilder {\n\tb.notes = notes\n\treturn b\n}", "func (o AppSharedCredentialsOutput) AdminNote() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *AppSharedCredentials) pulumi.StringPtrOutput { return v.AdminNote }).(pulumi.StringPtrOutput)\n}", "func (h *Handler) GetNoteByNoteID(c echo.Context) error {\n\tid, _ := strconv.Atoi(c.Param(\"id\"))\n\tnote, err := models.NoteByNoteID(h.DB, int64(id))\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Can't get note by ID \"+c.Param(\"id\"))\n\t}\n\n\treturn c.JSON(http.StatusOK, note)\n}", "func (p *NoteStoreClient) GetNoteVersion(ctx context.Context, authenticationToken string, noteGuid GUID, updateSequenceNum int32, withResourcesData bool, withResourcesRecognition bool, withResourcesAlternateData bool) (r *Note, err error) {\n var _args133 NoteStoreGetNoteVersionArgs\n _args133.AuthenticationToken = authenticationToken\n _args133.NoteGuid = noteGuid\n _args133.UpdateSequenceNum = updateSequenceNum\n _args133.WithResourcesData = withResourcesData\n _args133.WithResourcesRecognition = withResourcesRecognition\n _args133.WithResourcesAlternateData = withResourcesAlternateData\n var _result134 NoteStoreGetNoteVersionResult\n if err = p.Client_().Call(ctx, \"getNoteVersion\", &_args133, &_result134); err != nil {\n return\n }\n switch {\n case _result134.UserException!= nil:\n return r, _result134.UserException\n case _result134.SystemException!= nil:\n return r, _result134.SystemException\n case _result134.NotFoundException!= nil:\n return r, _result134.NotFoundException\n }\n\n return _result134.GetSuccess(), nil\n}", "func (p *NoteStoreClient) GetNoteApplicationData(ctx context.Context, authenticationToken string, guid GUID) (r *LazyMap, err error) {\n var _args105 NoteStoreGetNoteApplicationDataArgs\n _args105.AuthenticationToken = authenticationToken\n _args105.GUID = guid\n var _result106 NoteStoreGetNoteApplicationDataResult\n if err = p.Client_().Call(ctx, \"getNoteApplicationData\", &_args105, &_result106); err != nil {\n return\n }\n switch {\n case _result106.UserException!= nil:\n return r, _result106.UserException\n case _result106.SystemException!= nil:\n return r, _result106.SystemException\n case _result106.NotFoundException!= nil:\n return r, _result106.NotFoundException\n }\n\n return _result106.GetSuccess(), nil\n}", "func (c *Client) GetNote(id string, filters ...Filter) (Note, error) {\n\tresp, err := c.doRequest(http.MethodGet, fmt.Sprintf(EndpointFormatGetObject, TypeNote, id, formatFilters(filters)), nil)\n\tif err != nil {\n\t\treturn Note{}, err\n\t}\n\n\t// Check if we didn't get a result and return an error if true.\n\tif len(resp.Notes) <= 0 {\n\t\treturn Note{}, fmt.Errorf(\"get note id %s returned an empty result\", id)\n\t}\n\n\t// Return the object.\n\treturn resp.Notes[0], nil\n}", "func (mh *MidiLogger) HandleNote(n gm.Note) {\n\tif n.Vel == 0 {\n\t\tn.On = false\n\t}\n\tnotes := mh.keys[int(n.Ch)]\n\n\t// Update our note maps maps\n\tif n.On {\n\t\tnotes[n.Note] = n.Vel\n\t} else {\n\t\tnotes[n.Note] = 0\n\t}\n\tfmt.Printf(\"%s - %d.%d (%v)\\n\", n, mh.sixteenthsElapsed, mh.beatPosition, time.Since(mh.startTime))\n}", "func (r renderer) FootnoteRef(out *bytes.Buffer, ref []byte, id int) {}", "func GetRecord(m interface{}) (ret int, ts interface{}, rec map[string]string) {\n\tslice := reflect.ValueOf(m)\n\tt := slice.Index(0).Interface()\n\tdata := slice.Index(1)\n\n\tmapInterfaceData := data.Interface().(map[interface{}]interface{})\n\n\tmapData := make(map[string]string)\n\n\tfor kData, vData := range mapInterfaceData {\n\t\tmapData[kData.(string)] = string(vData.([]uint8))\n\t}\n\n\tmapData[\"id\"] = uuid.NewV4().String()\n\n\treturn 0, t, mapData\n}", "func (s *NotesService) GetMergeRequestNote(pid interface{}, mergeRequest, note int, options ...RequestOptionFunc) (*Note, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects/%s/merge_requests/%d/notes/%d\", PathEscape(project), mergeRequest, note)\n\n\treq, err := s.client.NewRequest(http.MethodGet, u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tn := new(Note)\n\tresp, err := s.client.Do(req, n)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn n, resp, nil\n}", "func (o LookupOccurrenceResultOutput) NoteName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupOccurrenceResult) string { return v.NoteName }).(pulumi.StringOutput)\n}", "func (m *CleaningroomMutation) Note() (r string, exists bool) {\n\tv := m.note\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (m *OnlineMeetingInfo) GetAdditionalData()(map[string]any) {\n val , err := m.backingStore.Get(\"additionalData\")\n if err != nil {\n panic(err)\n }\n if val == nil {\n var value = make(map[string]any);\n m.SetAdditionalData(value);\n }\n return val.(map[string]any)\n}", "func (b *GroupsSetUserNoteBuilder) Note(v string) *GroupsSetUserNoteBuilder {\n\tb.Params[\"note\"] = v\n\treturn b\n}", "func get(i int, latin bool) string {\n\tif i < 0 {\n\t\ti = 12 + (i % 12)\n\t}\n\n\ti %= 12\n\n\tif latin {\n\t\ti += 12\n\t}\n\n\treturn allNotes[i]\n}", "func (o *InlineResponse20027Person) GetEmailAlt2() string {\n\tif o == nil || o.EmailAlt2 == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.EmailAlt2\n}", "func (m *MailTips) GetAdditionalData()(map[string]any) {\n val , err := m.backingStore.Get(\"additionalData\")\n if err != nil {\n panic(err)\n }\n if val == nil {\n var value = make(map[string]any);\n m.SetAdditionalData(value);\n }\n return val.(map[string]any)\n}", "func CoveredPersonNoteLTE(v string) predicate.CoveredPerson {\n\treturn predicate.CoveredPerson(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldCoveredPersonNote), v))\n\t})\n}", "func (r Room) Notes() string {\n\ttemplate := `Use for meeting location:\n%v: %v\nOR\n%v\n\nPut in meeting body:\nThis meeting is scheduled in a %v called %v\nDial-in: %v\nMeeting URL: %v`\n\n\treturn fmt.Sprintf(template, r.Name, r.MeetingURL(), r.Phone(), r.Classification(), r.Name, r.Phone(), r.MeetingURL())\n}", "func GetOtherNoteList(userId string) *utils.Response {\n\tnoteList := model.NewNoteList(\"\", userId)\n\tnotes, err := noteList.GetListNoCategory()\n\tif err != nil {\n\t\tbeego.Error(err)\n\t\treturn utils.NewResponse(utils.SYSTEM_CODE, err.Error(), nil)\n\t}\n\treturn utils.NewResponse(0, \"\", convertNote(notes))\n\n}", "func (p *NoteStoreClient) GetNoteContent(ctx context.Context, authenticationToken string, guid Types.Guid) (r string, userException *Errors.EDAMUserException, systemException *Errors.EDAMSystemException, notFoundException *Errors.EDAMNotFoundException, err error) {\n\tif err = p.sendGetNoteContent(ctx, authenticationToken, guid); err != nil {\n\t\treturn\n\t}\n\treturn p.recvGetNoteContent(ctx)\n}", "func (o LookupTestCaseResultOutput) Notes() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupTestCaseResult) string { return v.Notes }).(pulumi.StringOutput)\n}", "func (m *TransportMutation) Note() (r string, exists bool) {\n\tv := m.note\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (m *Reminder) GetAdditionalData()(map[string]any) {\n val , err := m.backingStore.Get(\"additionalData\")\n if err != nil {\n panic(err)\n }\n if val == nil {\n var value = make(map[string]any);\n m.SetAdditionalData(value);\n }\n return val.(map[string]any)\n}", "func (m *CarCheckInOutMutation) Note() (r string, exists bool) {\n\tv := m.note\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (msql *MysqlDBLayer) PatchNote(ID int, note database.Note) (database.Note, error) {\n\t// Create the todo if it already exists.\n\tif msql.noteExist(ID) == false {\n\t\treturn msql.AddNote(note)\n\t}\n\n\t// Otherwise, update the todo\n\tquery, err := msql.session.Prepare(\"UPDATE notes SET content=?, last_edit=? WHERE id=?\")\n\tif err != nil {\n\t\treturn database.Note{}, err\n\t}\n\tdefer query.Close()\n\n\t// Patch note\n\t_, err = query.Exec(note.Content, time.Now(), ID)\n\tif err != nil {\n\t\treturn database.Note{}, err\n\t}\n\t// Return the patched note and error\n\treturn msql.GetNoteByID(ID)\n}", "func (a *GrafeasApiService) GetOccurrenceNote(ctx context.Context, name string) (ApiNote, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ApiNote\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/v1alpha1/{name}/notes\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"name\"+\"}\", fmt.Sprintf(\"%v\", name), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode < 300 {\n\t\t// If we succeed, return the data, otherwise pass on to decode error.\n\t\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\tif err == nil { \n\t\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t\t}\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\t\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v ApiNote\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\t\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (r renderer) FootnoteItem(out *bytes.Buffer, name, text []byte, flags int) {}", "func (p *NoteStoreClient) GetNoteContent(ctx context.Context, authenticationToken string, guid GUID) (r string, err error) {\n var _args113 NoteStoreGetNoteContentArgs\n _args113.AuthenticationToken = authenticationToken\n _args113.GUID = guid\n var _result114 NoteStoreGetNoteContentResult\n if err = p.Client_().Call(ctx, \"getNoteContent\", &_args113, &_result114); err != nil {\n return\n }\n switch {\n case _result114.UserException!= nil:\n return r, _result114.UserException\n case _result114.SystemException!= nil:\n return r, _result114.SystemException\n case _result114.NotFoundException!= nil:\n return r, _result114.NotFoundException\n }\n\n return _result114.GetSuccess(), nil\n}", "func (m *ChatMessageAttachment) GetAdditionalData()(map[string]any) {\n val , err := m.backingStore.Get(\"additionalData\")\n if err != nil {\n panic(err)\n }\n if val == nil {\n var value = make(map[string]any);\n m.SetAdditionalData(value);\n }\n return val.(map[string]any)\n}", "func CoveredPersonNote(v string) predicate.CoveredPerson {\n\treturn predicate.CoveredPerson(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldCoveredPersonNote), v))\n\t})\n}", "func readNote(writer http.ResponseWriter, request *http.Request) {\n\tvals := request.URL.Query()\n\tuuid := vals.Get(\"id\")\n\tversion := vals.Get(\"version\")\n\tnote, err := data.NoteByUUIDVersion(uuid, version)\n\tif err != nil {\n\t\terror_message(writer, request, \"Cannot read note\")\n\t} else {\n\t\tgenerateHTML(writer, &note, \"layout\", \"navbar\", \"note\")\n\n\t}\n}", "func Note(v string) predicate.Surgeryappointment {\n\treturn predicate.Surgeryappointment(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldNote), v))\n\t})\n}", "func (m *ProfileCardAnnotation) GetAdditionalData()(map[string]any) {\n val , err := m.backingStore.Get(\"additionalData\")\n if err != nil {\n panic(err)\n }\n if val == nil {\n var value = make(map[string]any);\n m.SetAdditionalData(value);\n }\n return val.(map[string]any)\n}", "func (a Meta_Note) Get(fieldName string) (value interface{}, found bool) {\n\tif a.AdditionalProperties != nil {\n\t\tvalue, found = a.AdditionalProperties[fieldName]\n\t}\n\treturn\n}", "func (m *CarInspectionMutation) Note() (r string, exists bool) {\n\tv := m.note\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (m *PortalNotification) GetAdditionalData()(map[string]any) {\n val , err := m.backingStore.Get(\"additionalData\")\n if err != nil {\n panic(err)\n }\n if val == nil {\n var value = make(map[string]any);\n m.SetAdditionalData(value);\n }\n return val.(map[string]any)\n}", "func (m *PrinterLocation) GetAdditionalData()(map[string]any) {\n val , err := m.backingStore.Get(\"additionalData\")\n if err != nil {\n panic(err)\n }\n if val == nil {\n var value = make(map[string]any);\n m.SetAdditionalData(value);\n }\n return val.(map[string]any)\n}", "func (c *API) GetNotes(params map[string]zoho.Parameter) (data NotesResponse, err error) {\n\tendpoint := zoho.Endpoint{\n\t\tName: \"notes\",\n\t\tURL: fmt.Sprintf(\"https://www.zohoapis.%s/crm/v2/Notes\", c.ZohoTLD),\n\t\tMethod: zoho.HTTPGet,\n\t\tResponseData: &NotesResponse{},\n\t\tURLParameters: map[string]zoho.Parameter{\n\t\t\t\"page\": \"\",\n\t\t\t\"per_page\": \"200\",\n\t\t},\n\t}\n\n\tif len(params) > 0 {\n\t\tfor k, v := range params {\n\t\t\tendpoint.URLParameters[k] = v\n\t\t}\n\t}\n\n\terr = c.Zoho.HTTPRequest(&endpoint)\n\tif err != nil {\n\t\treturn NotesResponse{}, fmt.Errorf(\"Failed to retrieve notes: %s\", err)\n\t}\n\n\tif v, ok := endpoint.ResponseData.(*NotesResponse); ok {\n\t\treturn *v, nil\n\t}\n\n\treturn NotesResponse{}, fmt.Errorf(\"Data returned was not 'NotesResponse'\")\n}", "func ReadNote(row *sql.Row, a *Note) error {\n\terr := row.Scan(&a.NID, &a.BID, &a.NLID, &a.PNID, &a.NTID, &a.RID, &a.RAID, &a.TCID, &a.Comment, &a.CreateTS, &a.CreateBy, &a.LastModTime, &a.LastModBy)\n\tSkipSQLNoRowsError(&err)\n\treturn err\n}", "func (o *InlineResponse20027Person) GetPrivateNotesOk() (*string, bool) {\n\tif o == nil || o.PrivateNotes == nil {\n\t\treturn nil, false\n\t}\n\treturn o.PrivateNotes, true\n}", "func (m *DeviceEnrollmentWindowsHelloForBusinessConfiguration) GetPinSpecialCharactersUsage()(*WindowsHelloForBusinessPinUsage) {\n val, err := m.GetBackingStore().Get(\"pinSpecialCharactersUsage\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*WindowsHelloForBusinessPinUsage)\n }\n return nil\n}", "func (o *LocalDatabaseProvider) GetNotesOk() (*string, bool) {\n\tif o == nil || o.Notes == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Notes, true\n}", "func (m *EmbeddedSIMActivationCode) GetAdditionalData()(map[string]any) {\n val , err := m.backingStore.Get(\"additionalData\")\n if err != nil {\n panic(err)\n }\n if val == nil {\n var value = make(map[string]any);\n m.SetAdditionalData(value);\n }\n return val.(map[string]any)\n}", "func LoadNote(db *gorm.DB) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tvar notes []models.Note\n\t\terr := db.Limit(1).\n\t\t\tWhere(\"id = ?\", c.Param(\"note\")).\n\t\t\tFind(&notes).\n\t\t\tError\n\t\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\t\terrors.Apply(c, err)\n\t\t} else if len(notes) == 0 {\n\t\t\terrors.Apply(c, errors.NoteNotFound)\n\t\t} else {\n\t\t\tc.Set(\"note\", &notes[0])\n\t\t}\n\t}\n}", "func Note(help plush.HelperContext) (template.HTML, error) {\n\tif !help.HasBlock() {\n\t\treturn \"\", nil\n\t}\n\ts, err := help.Block()\n\tif err != nil {\n\t\treturn \"\", errors.WithStack(err)\n\t}\n\n\tb := github_flavored_markdown.Markdown([]byte(s))\n\n\t// Generate info div\n\t// Strip the first <p> from Markdown result to insert the icon.\n\tt := tags.New(\"div\", tags.Options{\n\t\t\"class\": \"info\",\n\t\t\"body\": fmt.Sprintf(note, b[3:]),\n\t})\n\n\treturn t.HTML(), nil\n}", "func (pg *MongoDb) UpdateNote(ctx context.Context, pID, nID string, n *pb.Note, mask *fieldmaskpb.FieldMask) (*pb.Note, error) {\n\treturn nil, nil\n}", "func (m *TransportMutation) OldNote(ctx context.Context) (v string, err error) {\n\tif !m.op.Is(OpUpdateOne) {\n\t\treturn v, fmt.Errorf(\"OldNote is allowed only on UpdateOne operations\")\n\t}\n\tif m.id == nil || m.oldValue == nil {\n\t\treturn v, fmt.Errorf(\"OldNote requires an ID field in the mutation\")\n\t}\n\toldValue, err := m.oldValue(ctx)\n\tif err != nil {\n\t\treturn v, fmt.Errorf(\"querying old value for OldNote: %w\", err)\n\t}\n\treturn oldValue.Note, nil\n}", "func NoteGT(v string) predicate.Surgeryappointment {\n\treturn predicate.Surgeryappointment(func(s *sql.Selector) {\n\t\ts.Where(sql.GT(s.C(FieldNote), v))\n\t})\n}", "func (msql *MysqlDBLayer) GetNoteByID(ID int) (database.Note, error) {\n\tresp, err := msql.session.Query(\"SELECT * FROM notes WHERE id = ?\", strconv.Itoa(ID))\n\tif err != nil {\n\t\treturn database.Note{}, err\n\t}\n\n\tdefer resp.Close()\n\tvar note database.Note\n\n\tif resp.Next() {\n\t\terr = resp.Scan(&note.ID, &note.Title, &note.Content, &note.LastEdit, &note.CreatedAt)\n\t\tif err != nil {\n\t\t\treturn note, err\n\t\t}\n\t} else {\n\t\treturn note, errors.New(message.NoDataFoundError.Message)\n\t}\n\treturn note, nil\n}" ]
[ "0.6433666", "0.6135928", "0.6029246", "0.58651245", "0.56893414", "0.56893414", "0.568336", "0.5633651", "0.56210583", "0.55268145", "0.54661596", "0.5396061", "0.5380602", "0.53759795", "0.53320974", "0.5308852", "0.5308852", "0.5295827", "0.52743185", "0.5269993", "0.52621895", "0.51601464", "0.51495796", "0.51150614", "0.51012075", "0.5098531", "0.50744694", "0.5052357", "0.5003581", "0.5000857", "0.49975824", "0.4967497", "0.4954319", "0.4948135", "0.49431148", "0.49420524", "0.4930772", "0.49065214", "0.4901075", "0.4895264", "0.48952144", "0.48665884", "0.4854219", "0.4853835", "0.48153138", "0.4782619", "0.47767863", "0.4775716", "0.4758395", "0.47517148", "0.47513807", "0.47460318", "0.47251076", "0.47201532", "0.47098124", "0.47007507", "0.4684553", "0.46783423", "0.46699175", "0.46647245", "0.46602994", "0.4648257", "0.4647702", "0.46464947", "0.46335614", "0.46158528", "0.4604168", "0.46032906", "0.46030927", "0.4577454", "0.457596", "0.45536494", "0.45489585", "0.45437828", "0.45428517", "0.45388177", "0.45210287", "0.45148176", "0.45116776", "0.44955528", "0.44920474", "0.44793725", "0.44776675", "0.44675398", "0.44658425", "0.44607598", "0.4452209", "0.44495586", "0.44308215", "0.44176948", "0.44174415", "0.44158533", "0.44152796", "0.4406696", "0.44050023", "0.44037938", "0.43921843", "0.4386339", "0.4384161", "0.43799275" ]
0.6029165
3
Function returning an integer and a String
func getIntString() (int, string) { return 5, "Hello" }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func IntString(x *big.Int,) string", "func StringInt(i int) string { return strconv.FormatInt(int64(i), 10) }", "func (x *Int) String() string {}", "func addStrInt(a string, b int) string {\n\treturn a + strconv.Itoa(b)\n}", "func (x *Int) Text(base int) string {}", "func (t IntType) String() (name string) {\r\n\treturn fmt.Sprintf(\"%d\", t)\r\n}", "func Int(i int) string {\n\t// The \"a\" is short for \"string\", obviously.\n\treturn strconv.Itoa(i)\n}", "func Int2String(i int) string {\n\ts := strconv.Itoa(i)\n\treturn s\n}", "func IntToString(intValue int) (ret string) {\n\tret = strconv.Itoa(intValue)\n\treturn\n}", "func Int2Str(v interface{}) (s string) {\n\tswitch v.(type) {\n\tcase string:\n\t\ts = v.(string)\n\n\tcase int:\n\t\ts = strconv.Itoa(v.(int))\n\t}\n\n\treturn\n}", "func IntToString(n int) string {\n\treturn strconv.Itoa(n)\n}", "func IntText(x *big.Int, base int) string", "func Int2Str(i int) string {\n\treturn strconv.Itoa(i)\n}", "func IntegerToString(param int) string {\n\treturn strconv.Itoa(param)\n}", "func IntToString(int_ int) (string_ string) {\n\tstring_ = fmt.Sprint(int_)\n\treturn\n}", "func (i GinJwtSignAlgorithm) IntString() string {\n\treturn strconv.Itoa(int(i))\n}", "func Add(a,b int) (sum int ,result string) {\n\n\tsum = a+b\n\n\treturn sum, \"This is addition\"\n\n//fmt.Println(\"Addition\")\n\n}", "func Int2String(v int) string {\n\treturn strconv.Itoa(v)\n}", "func (l Integer) String() string {\n\treturn fmt.Sprintf(\"%d\", l)\n}", "func Str(a int) string {\n\treturn strconv.Itoa(a)\n}", "func intToStr(ii int) string {\n\treturn strconv.FormatInt(int64(ii), 10)\n}", "func intStr(v int64) string {\n\treturn strconv.FormatInt(v, 10)\n}", "func IntToString(i int64) string {\n\treturn strconv.FormatInt(i, 10)\n}", "func String(n int) string {\n\treturn global.String(n)\n}", "func (strint *StringInt) String() string {\n\treturn strconv.Itoa(strint.Value)\n}", "func (strint *StringInt) String() string {\n\treturn strconv.Itoa(strint.Value)\n}", "func (e Int) String() string {\n\treturn fmt.Sprintf(\"%v\", e)\n}", "func (i SNSProtocol) IntString() string {\n\treturn strconv.Itoa(int(i))\n}", "func IntAsString(min, max int) string {\n\treturn strconv.Itoa(Int(min, max))\n}", "func dumbfunc() (string, int) {\n return \"Alex Herrmann\", 19\n}", "func itoa3(val int) string {\n return \"hello world\"\n}", "func IntToStr(num int64) string {\r\n\treturn strconv.FormatInt(num, 10)\r\n}", "func int32Str(u int32) string {\n\treturn fmt.Sprint(u)\n}", "func (n StringNumber) Int() int {\n\treturn int(n)\n}", "func (vl IntegerValue) String() string {\n\treturn strconv.Itoa(int(vl))\n}", "func (vl IntegerValue) String() string {\n\treturn strconv.Itoa(int(vl))\n}", "func (id ID) String() string {\n\treturn strconv.Itoa(int(id))\n}", "func StringOrInt(raw string) (s string, i uint16) {\n\trawInt, err := strconv.Atoi(raw)\n\tif err == nil {\n\t\t// it's a number\n\t\treturn \"\", uint16(rawInt)\n\t}\n\t// or, it's a variable\n\treturn raw, 0\n}", "func (v ModuleID) String() string {\n\tx := (int32)(v)\n\n\treturn fmt.Sprint(x)\n}", "func bar() (int, string) {\n\ta := 77\n\tb := \"Sunandan\"\n\treturn a, b\n}", "func String(n int32) string {\n\tbuf := [11]byte{}\n\tpos := len(buf)\n\ti := int64(n)\n\tsigned := i < 0\n\tif signed {\n\t\ti = -i\n\t}\n\tfor {\n\t\tpos--\n\t\tbuf[pos], i = '0'+byte(i%10), i/10\n\t\tif i == 0 {\n\t\t\tif signed {\n\t\t\t\tpos--\n\t\t\t\tbuf[pos] = '-'\n\t\t\t}\n\t\t\treturn string(buf[pos:])\n\t\t}\n\t}\n}", "func (n Number) String() string { return string(n) }", "func (i GinBindType) IntString() string {\n\treturn strconv.Itoa(int(i))\n}", "func gatherInts(params ...int) string {\n\tswitch len(params) {\n\tcase 1:\n\t\treturn strconv.Itoa(params[0])\n\tdefault:\n\t\treturn \"\"\n\t}\n}", "func multString(a, b string) string {\n\ta2, _ := strconv.Atoi(a)\n\tb2, _ := strconv.Atoi(b)\n\tvar c int\n\tfor i := 0; i < b2; i++ {\n\t\tc += a2\n\t}\n\treturn fmt.Sprintf(\"%d\", c)\n}", "func IntToStr(val int) string {\n\treturn strconv.FormatInt(int64(val), 10)\n}", "func ConverteIntParaString(numero int) string {\n\treturn strconv.Itoa(numero)\n}", "func (me TartIdTypeInt) String() string { return xsdt.Token(me).String() }", "func ToString(n int32) string {\n\treturn strconv.Itoa(int(n))\n}", "func (v *Value) String() string { return fmt.Sprintf(\"%d\", v.progID) }", "func (r IntBoundedStrictly) String() string { return IntBounded(r).String() }", "func (c CallCode) String() string {\n\treturn \"+\" + strconv.FormatInt(int64(c), 10)\n}", "func ToStringInt(min, max int, minExclusive, maxExclusive bool) string {\n\tmin, max, minExclusive, maxExclusive = MinMaxExclusiveInt(min, max, minExclusive, maxExclusive)\n\tvar minBracket = \"[\"\n\tif minExclusive {\n\t\tminBracket = \"(\"\n\t}\n\tvar maxBracket = \"]\"\n\tif maxExclusive {\n\t\tmaxBracket = \")\"\n\t}\n\treturn minBracket + strconv.FormatInt(int64(min), 10) + \",\" + strconv.FormatInt(int64(max), 10) + maxBracket\n}", "func IntToString(v Int) String {\n\tstr := &stringFromInt{from: v}\n\tv.AddListener(str)\n\treturn str\n}", "func (a Age) toString() string {\n\treturn fmt.Sprintf(\"%d\", a)\n}", "func rollchar(firstName string, lastName string) (string, error) {\n return firstName + \" the \" + lastName, nil\n}", "func (i IntType) String() string {\n\treturn \"int\"\n}", "func returnMulti2() (n int, s string) {\n\tn = 42\n\ts = \"foobar\"\n\t// n and s will be returned\n\treturn\n}", "func StringNumber(numberPairs int, separator string) string {\n\treturn StringNumberExt(numberPairs, separator, 2)\n}", "func (i SNSSubscribeAttribute) IntString() string {\n\treturn strconv.Itoa(int(i))\n}", "func (lit *IntegerLit) String() string {\n\treturn lit.Value\n}", "func getInstanceIDString(originalID interface{}) string {\n\tswitch id := originalID.(type) {\n\tcase goracle.Number:\n\t\treturn id.String()\n\tcase int:\n\t\treturn strconv.Itoa(id)\n\tcase string:\n\t\treturn id\n\tdefault:\n\t\treturn \"\"\n\t}\n}", "func (me TSAFPTPortugueseVatNumber) String() string { return xsdt.Integer(me).String() }", "func (x ID) Str(m *Map) string { return m.ByID(x) }", "func (i *IntValue) String() string {\n\treturn fmt.Sprintf(\"%v\", *i)\n}", "func type2name(i int) string {\n\tif i == 0 {\n\t\treturn \"Str\"\n\t}\n\treturn \"Num\"\n}", "func Int2String(seq uint64) (shortURL string) {\n\tcharSeq := []rune{}\n\tif seq != 0 {\n\t\tfor seq != 0 {\n\t\t\tmod := seq % BaseStringLength\n\t\t\tdiv := seq / BaseStringLength\n\t\t\tcharSeq = append(charSeq, rune(BaseString[mod]))\n\t\t\tseq = div\n\t\t}\n\t} else {\n\t\tcharSeq = append(charSeq, rune(BaseString[seq]))\n\t}\n\n\ttmpShortURL := string(charSeq)\n\tshortURL = reverse(tmpShortURL)\n\treturn\n}", "func returnMulti() (int, string) {\n\treturn 42, \"foobar\"\n}", "func (v RangeInt) String() string {\n\treturn ToStringInt(v.min, v.max, v.minExclusive, v.maxExclusive)\n}", "func (sl SolLst) StringNum(val int) string {\n\treturn sl.Get(val).render() + \"\\n\"\n}", "func (v *VInteger) String() string {\n\treturn strconv.FormatInt(int64(v.value), 10)\n}", "func (p PaymentID) String() string {\n\treturn strconv.FormatInt(p.ProjectID, 10) + \"-\" + strconv.FormatInt(p.PaymentID, 10)\n}", "func IntToStr(v int64) (str string) {\n\tstr = strconv.FormatInt(v, 10)\n\tneg := str[0:1] == \"-\"\n\tif neg {\n\t\tstr = str[1:]\n\t}\n\tstr = StrDelimit(str, \",\", 3)\n\tif neg {\n\t\tstr = \"-\" + str\n\t}\n\treturn\n}", "func ratIntStr(v *big.Rat) string {\n\treturn new(big.Int).Div(v.Num(), v.Denom()).String()\n}", "func textify(n int) string {\n\tif n > 1000 {\n\t\tpanic(\"Number out of range\")\n\t} else if n == 1000 {\n\t\treturn \"one thousand\"\n\t} else if n >= 100 {\n\t\tnum := n % 100\n\t\tandText := \"and \"\n\t\tif num == 0 {\n\t\t\tandText = \"\"\n\t\t}\n\t\treturn oneNames[n/100-1] + \" hundred \" + andText + textify(num)\n\t} else if n >= 20 {\n\t\tnum := n % 10\n\t\thyphen := \"-\"\n\t\tif num == 0 {\n\t\t\thyphen = \" \"\n\t\t}\n\t\treturn tenNames[n/10-1] + hyphen + textify(num)\n\t} else if n >= 1 {\n\t\treturn oneNames[n-1]\n\t} else {\n\t\treturn \"\"\n\t}\n\tpanic(\"Not reached\")\n}", "func ConvertNumToString(n int) (w string) {\n\tif n < 20 {\n\t\tw = NumberToWord[n]\n\t\treturn\n\t}\n\n\tr := n % 10\n\tif r == 0 {\n\t\tw = NumberToWord[n]\n\t} else {\n\t\tw = NumberToWord[n-r] + \"-\" + NumberToWord[r]\n\t}\n\treturn\n}", "func convStr(i int) string {\n\treturn strconv.Itoa(i)\n}", "func StringI64(i64 int64) string { return strconv.FormatInt(i64, 10) }", "func intToMultiBaseString(id int, digitSpec []string) string {\n\tvar pos, rmndr, minVal int\n\tvar result string\n\n\trmndr = id\n\tfor i, digitChars := range digitSpec {\n\t\tminVal = digitIncrements[i]\n\n\t\t// The character for this digit position is determined by the number of\n\t\t// times that the minimum/increment value of that digit can evenly\n\t\t// divide into the remainder from the last digit's calculations (or the\n\t\t// original ID in the case of the most significant digit).\n\t\tpos = rmndr / minVal\n\t\tresult += string(digitChars[pos])\n\n\t\t// Calculate the remainder to be used for the next digit.\n\t\trmndr %= minVal\n\t}\n\n\treturn result\n}", "func (g Generator) String() string {\n\tif g.b == nil {\n\t\tg.b = &big.Int{}\n\t}\n\tsum := g.Sum(nil)\n\tg.b.SetBytes(sum)\n\treturn toBase(g.b, g.Words)\n}", "func sommeNameReturned(x, y, z int) (somme int) {\n\tsomme = x + y + z\n\treturn somme\n}", "func getStringFromGivenType(v interface{}) string {\n\tvar str string\n\tswitch v.(type) {\n\tcase int:\n\t\tstr = strconv.Itoa(v.(int))\n\tcase int64:\n\t\tstr = strconv.FormatInt(v.(int64), 10)\n\tcase string:\n\t\tstr, _ = v.(string)\n\tcase decimal.Decimal:\n\t\tstr = v.(decimal.Decimal).String()\n\tdefault:\n\t\tstr = \"\"\n\t}\n\treturn str\n}", "func getBiography(age int, name string, status string) (string, string){\n\tageNow := strconv.Itoa(age)\n\n\treturn name + \" adalah seorang \"+ status,\n\t\t \"umurnya \"+ ageNow\n\n\n}", "func (p pair) string() string { // p is called the \"receiver\"\n return fmt.Sprintf(\"(%f, %f)\", p.x, p.y)\n}", "func StringUint(i uint) string { return strconv.FormatUint(uint64(i), 10) }", "func (value *Value) String() string {\n\treturn strconv.FormatInt(value.Data, 10)\n}", "func (i NotSpecific) String() string { return toString(i) }", "func (v ServiceID) String() string {\n\tx := (int32)(v)\n\n\treturn fmt.Sprint(x)\n}", "func test6() (int, s string, e error) {\n\n\treturn \"\", \"s\", nil\n}", "func (t Tower) String() string {\n\treturn fmt.Sprint([]int(t))\n}", "func (i SNSPlatformApplicationAttribute) IntString() string {\n\treturn strconv.Itoa(int(i))\n}", "func (s SubtractionResult) String() string {\n\treturn s.StringQuestion() + strconv.FormatInt(s.Difference, 10)\n}", "func getInteger(source string, i int) (TokenType, int) {\n\tvar tokenType TokenType = Constant\n\tiEnd := len(source) - 1\n\tc := source[i]\n\tif c == '0' && isByteInString(source[i+1], \"xX\") {\n\t\ti += 2\n\t\tfor i <= iEnd && isByteInString(source[i], hexDigits) {\n\t\t\ti++\n\t\t}\n\t} else {\n\t\tfor i <= iEnd && isByteInString(source[i], intOrFloatDigits2) {\n\t\t\ti++\n\t\t}\n\t}\n\tfor _, suffix := range []string{\"ull\", \"ll\", \"ul\", \"l\", \"f\", \"u\"} {\n\t\tsize := len(suffix)\n\t\tif i+size <= iEnd && suffix == strings.ToLower(source[i:i+size]) {\n\t\t\ti += size\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn tokenType, i\n}", "func (x Number) String() string {\n\tif str, ok := _NumberMap[x]; ok {\n\t\treturn str\n\t}\n\treturn fmt.Sprintf(\"Number(%d)\", x)\n}", "func IntCase2Str(i int) string {\n\tret := \"Invalid\"\n\tswitch i {\n\tcase CaseGt:\n\t\tret = \">\"\n\tcase CaseGe:\n\t\tret = \">=\"\n\tcase CaseLt:\n\t\tret = \"<\"\n\tcase CaseLe:\n\t\tret = \"<=\"\n\tcase CaseEq:\n\t\tret = \"==\"\n\tcase CaseNe:\n\t\tret = \"!=\"\n\tcase CaseContains:\n\t\tret = \"contains\"\n\tcase CaseNotContains:\n\t\tret = \"not_contains\"\n\t}\n\treturn ret\n}", "func (l *BigInt) String() string {\n\treturn (*big.Int)(l).String()\n}", "func (v *CallValue) String() string { return strconv.FormatUint(uint64(v.progID), 10) }", "func LogIn() (r string, c string) {\n return \"You've logged in. Have fun!\", \"Green\"\n}", "func (m monome) string(times, leftGroup, rightGroup string) string {\n\t// if monome is zero, just return 0\n\tif m.isZero() {\n\t\treturn \"0\"\n\t}\n\n\t// elementary blocks\n\tstrCoeff := strconv.FormatInt(int64(m.coeff), 10)\n\tstrBase := strconv.FormatInt(int64(m.base), 10)\n\ttimes = \" \" + times + \" \"\n\n\tswitch {\n\tcase m.exponent.IsZero():\n\t\t// base ^ exponent is one, so monome is equal to its coeff\n\t\treturn strCoeff\n\n\tcase m.exponent.isOne():\n\t\t// base ^ exponent is base\n\t\tif m.coeff == 1 {\n\t\t\t// 1 times base is useless, just return the base\n\t\t\treturn strBase\n\t\t}\n\t\t// result is coeff times base\n\t\treturn strCoeff + times + strBase\n\n\tdefault:\n\t\t// general case for the base ^ exponent part\n\t\tresult := strBase + \" ^ \" + leftGroup + m.exponent.string(times, leftGroup, rightGroup) + rightGroup\n\t\tif m.coeff == 1 {\n\t\t\t// 1 times ... is useless\n\t\t\treturn result\n\t\t}\n\t\t// most general case\n\t\treturn strCoeff + times + result\n\t}\n}", "func FormatInt(name string) string {\n\treturn formatIntFunction(name, true)\n}" ]
[ "0.7078133", "0.6915031", "0.68899345", "0.6515276", "0.6468381", "0.64191395", "0.6378561", "0.63749486", "0.63145816", "0.6214758", "0.6194673", "0.61858964", "0.61575055", "0.61489695", "0.6143603", "0.6098942", "0.6091935", "0.60840064", "0.6070489", "0.60343933", "0.60338277", "0.60096866", "0.59890914", "0.5969556", "0.594371", "0.594371", "0.5933788", "0.5925735", "0.5896718", "0.5896225", "0.5845156", "0.5844898", "0.58300763", "0.58095616", "0.57950413", "0.57950413", "0.573398", "0.57243156", "0.5677118", "0.5672996", "0.5672356", "0.5662694", "0.562813", "0.56206805", "0.56068665", "0.55932415", "0.5582001", "0.55743426", "0.5553541", "0.55379534", "0.5520525", "0.5520316", "0.55153733", "0.5515356", "0.5511551", "0.55110204", "0.549588", "0.5486", "0.5477364", "0.5467911", "0.54656255", "0.54486805", "0.5448321", "0.5447871", "0.54268885", "0.5426137", "0.5422686", "0.54124576", "0.5402264", "0.53980297", "0.53925693", "0.5389828", "0.53861076", "0.53835374", "0.5378543", "0.5366148", "0.53590536", "0.53452075", "0.5337088", "0.53289527", "0.5328924", "0.5325697", "0.5324107", "0.5315296", "0.53152543", "0.53047335", "0.5289974", "0.5282505", "0.52775633", "0.52748054", "0.5273085", "0.52672106", "0.5258373", "0.5256578", "0.5247643", "0.52473164", "0.5238152", "0.52362263", "0.52292883", "0.5221037" ]
0.7265145
0
New creates a new in memory db
func New(supportedSymbols []string) (*DB, error) { var ( db = &DB{ store: map[string]*models.Currency{}, supportedSymbols: supportedSymbols, } ) for _, symbol := range supportedSymbols { // Get all currencies var res, err = http.Get(base + symbolPath + symbol) if err != nil { err = errors.Wrap(err, "http.Get") log.Printf("Error: %+v\n", err) return nil, err } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { err = errors.Wrap(err, "ioutil.ReadAll") log.Printf("Error: %+v\n", err) return nil, err } var s symbolCurrency err = json.Unmarshal(body, &s) if err != nil { err = errors.Wrap(err, "json.Unmarshal") log.Printf("Error: %+v\n", err) return nil, err } var currency = &models.Currency{ FeeCurrency: s.FeeCurrency, } // Get all currencies res, err = http.Get(base + pricePath + symbol) if err != nil { err = errors.Wrap(err, "http.Get") log.Printf("Error: %+v\n", err) return nil, err } defer res.Body.Close() body, err = ioutil.ReadAll(res.Body) if err != nil { err = errors.Wrap(err, "ioutil.ReadAll") log.Printf("Error: %+v\n", err) return nil, err } var p priceCurrency err = json.Unmarshal(body, &p) if err != nil { err = errors.Wrap(err, "json.Unmarshal") log.Printf("Error: %+v\n", err) return nil, err } currency.Ask = p.Ask currency.Bid = p.Bid currency.Last = p.Last currency.High = p.High currency.Low = p.Low currency.Open = p.Open // Get all currencies res, err = http.Get(base + currencyPath + s.BaseCurrency) if err != nil { err = errors.Wrap(err, "http.Get") log.Printf("Error: %+v\n", err) return nil, err } defer res.Body.Close() body, err = ioutil.ReadAll(res.Body) if err != nil { err = errors.Wrap(err, "ioutil.ReadAll") log.Printf("Error: %+v\n", err) return nil, err } // Unmarshal the ID and FullName into currency err = json.Unmarshal(body, &currency) if err != nil { err = errors.Wrap(err, "json.Unmarshal") log.Printf("Error: %+v\n", err) return nil, err } db.Insert(currency) } return db, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func dbNew() *DB {\n\treturn &DB{\n\t\tdata: make(map[string]string),\n\t}\n}", "func newMemorySliceDB() (*sliceDB, error) {\r\n\tdb, err := leveldb.Open(storage.NewMemStorage(), nil)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\treturn &sliceDB{\r\n\t\tlvl: db,\r\n\t\tquit: make(chan struct{}),\r\n\t}, nil\r\n}", "func New(ctx context.Context, ng engine.Engine) (*DB, error) {\n\treturn newDatabase(ctx, ng, database.Options{Codec: msgpack.NewCodec()})\n}", "func New(path string) (*DB, error) {\n\tdb, err := bolt.Open(path, 0600, &bolt.Options{Timeout: 1 * time.Second})\n\treturn &DB{Bolt: db}, err\n}", "func New(dsn string, maxConn int) dao.DB {\n\treturn &db{\n\t\tDB: open(dsn, maxConn),\n\t}\n}", "func NewDb() *Db { //s interface{}\n\td := &Db{\n\t\tarr: make(Lister, 0, 100),\n\t\tupdate: time.Now().UnixNano(),\n\t}\n\treturn d\n}", "func New(size int) *DB {\n\treturn &DB{\n\t\tdocs: make(map[int][]byte, size),\n\t\tall: intset.NewBitSet(0),\n\t}\n}", "func newDatabase(s *Server) *Database {\n\treturn &Database{\n\t\tserver: s,\n\t\tusers: make(map[string]*DBUser),\n\t\tpolicies: make(map[string]*RetentionPolicy),\n\t\tshards: make(map[uint64]*Shard),\n\t\tseries: make(map[string]*Series),\n\t}\n}", "func New(metainfo *Client, encStore *encryption.Store) *DB {\n\treturn &DB{\n\t\tmetainfo: metainfo,\n\t\tencStore: encStore,\n\t}\n}", "func New(path string) (*DB, error) {\n\tdb, err := badger.Open(badger.DefaultOptions(path))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"new db error: %w\", err)\n\t}\n\treturn &DB{db}, nil\n}", "func New(ctx context.Context, ng engine.Engine, opts Options) (*Database, error) {\n\tif opts.Codec == nil {\n\t\treturn nil, errors.New(\"missing codec\")\n\t}\n\n\tdb := Database{\n\t\tng: ng,\n\t\tCodec: opts.Codec,\n\t}\n\n\tntx, err := db.ng.Begin(ctx, engine.TxOptions{\n\t\tWritable: true,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer ntx.Rollback()\n\n\terr = db.initInternalStores(ntx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = ntx.Commit()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &db, nil\n}", "func New() (database, error) {\n\tdb, err := sql.Open(driverName, databaseName)\n\tif err != nil {\n\t\treturn database{}, err\n\t}\n\n\treturn database{db}, nil\n}", "func newDatabase(info extraInfo, db *sql.DB) *database {\n\treturn &database{\n\t\tname: info.dbName,\n\t\tdriverName: info.driverName,\n\t\tdb: db,\n\t}\n}", "func newDB(client *gorm.DB) (*DB, error) {\n\tif client == nil {\n\t\treturn nil, fmt.Errorf(\"Mysql: could not connect\")\n\t}\n\tdb := &DB{\n\t\tclient: client,\n\t}\n\treturn db, nil\n}", "func New() (db.DB, error) {\n\tx := &MemDB{\n\t\teMap: make(map[string]*pb.Entity),\n\t\tgMap: make(map[string]*pb.Group),\n\t}\n\n\thealth.RegisterCheck(\"MemDB\", x.healthCheck)\n\treturn x, nil\n}", "func newDatabase(count int) (*database, error) {\n\tdb, err := sql.Open(\"postgres\", fmt.Sprintf(`host=%s port=%s user=%s\n\t\tpassword=%s dbname=%s sslmode=disable`,\n\t\thost, port, user, password, dbname))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := db.Ping(); err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"connected to psql client, host: %s\\n\", host)\n\n\treturn &database{\n\t\tdb: db,\n\t\terrChan: make(chan error, count),\n\t}, nil\n}", "func createNewDB(log *logrus.Entry, cnf *Config) error {\n\tvar err error\n\n\tpsqlInfo := fmt.Sprintf(\"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable\",\n\t\tcnf.DBHost, cnf.DBPort, cnf.DBUser, cnf.DBPassword, cnf.DBName)\n\n\tdb, err = sql.Open(\"postgres\", psqlInfo)\n\n\tif err != nil {\n\t\tlog.WithError(err).Fatalf(\"Failed to connect to db\")\n\t}\n\n\t//try to ping the db\n\terr = db.Ping()\n\tif err != nil {\n\t\tlog.WithError(err).Fatalf(\"Failed to ping db\")\n\t}\n\n\tif err = helpers.MigrateDB(db, cnf.SQLMigrationDir); err != nil {\n\t\treturn err\n\t}\n\n\tboil.SetDB(db)\n\n\treturn nil\n}", "func New(db *sql.DB, maxGatewayCount int) DB {\n\treturn database{\n\t\tdb: db,\n\t\tmaxGatewayCount: maxGatewayCount,\n\t}\n}", "func New(db *sql.DB) *Database {\n\treturn &Database{\n\t\tdb: db,\n\t}\n}", "func New(db *sql.DB) *Database {\n\treturn &Database{\n\t\tdb: db,\n\t}\n}", "func newEmptyDB(ctx context.Context) (*sql.DB, error) {\n\tdb, err := sql.Open(\"mysql\", dataSource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a randomly-named database and then connect using the new name.\n\tname := fmt.Sprintf(\"mono_%v\", time.Now().UnixNano())\n\n\tstmt := fmt.Sprintf(\"CREATE DATABASE %v\", name)\n\tif _, err := db.ExecContext(ctx, stmt); err != nil {\n\t\treturn nil, fmt.Errorf(\"error running statement %q: %v\", stmt, err)\n\t}\n\tdb.Close()\n\n\tdb, err = sql.Open(\"mysql\", dataSource+name+\"?parseTime=true\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open new database %q: %v\", name, err)\n\t}\n\treturn db, db.Ping()\n}", "func newCacheDB(persistent, memory storage.DataStore) storage.DataStore {\n\treturn &memoryDB{\n\t\tpersistent: persistent,\n\t\tinmem: memory,\n\t\tpersistentAPN: nil,\n\t\tinmemAPN: nil,\n\t}\n}", "func New(destination string) (*gorm.DB, error) {\n\n\tdb, err := gorm.Open(\"mysql\", destination)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdb = db.Set(\"gorm:table_options\", \"DEFAULT CHARACTER SET=utf8mb4 COLLATE=utf8mb4_general_ci ENGINE=InnoDB\")\n\n\tdb.DB().SetMaxIdleConns(10)\n\tdb.DB().SetMaxOpenConns(100)\n\tdb.DB().SetConnMaxLifetime(time.Minute)\n\n\tdb = db.Set(\"gorm:auto_preload\", true)\n\n\treturn db, nil\n}", "func New(t *testing.T) *sql.DB {\n\tt.Helper()\n\n\tif testing.Short() {\n\t\tt.Skip(\"skip store test because short mode\")\n\t}\n\n\tdb, err := sql.Open(\"txdb\", t.Name())\n\tif err != nil {\n\t\tt.Fatalf(\"can't open db: %s\", err)\n\t}\n\n\tt.Cleanup(func() {\n\t\tdb.Close()\n\t})\n\n\treturn db\n}", "func New(config *Config) (Database, error) {\n\tdb, err := connectToDB(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfmt.Println(\"Successfully connected to db\")\n\n\terr = migrateDB(config, db)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfmt.Println(\"Successfully ran migrations\")\n\n\tsqlxDB := sqlx.NewDb(db, config.Driver)\n\n\tbaseDB := database{\n\t\tdb: sqlxDB,\n\t}\n\n\treturn &queries{\n\t\tauthorsQueries{baseDB},\n\t\tpostsQueries{baseDB},\n\t}, nil\n}", "func New(dsn string) *DB {\n\tconnection, err := sql.Open(\"postgres\", dsn)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t// passive attempt to create table\n\t_, _ = connection.Exec(fmt.Sprintf(`create table %s (job jsonb);`, TABLE_NAME))\n\treturn &DB{\n\t\tconn: connection,\n\t}\n}", "func New(ctx context.Context, dirPath string, opts *Options) (*DB, error) {\n\tvar (\n\t\trepo storage.Repository\n\t\terr error\n\t\tdbCloser io.Closer\n\t)\n\tif opts == nil {\n\t\topts = defaultOptions()\n\t}\n\n\tif opts.Logger == nil {\n\t\topts.Logger = log.Noop\n\t}\n\n\tlock := multex.New()\n\tmetrics := newMetrics()\n\topts.LdbStats.CompareAndSwap(nil, &metrics.LevelDBStats)\n\n\tlocker := func(addr swarm.Address) func() {\n\t\tlock.Lock(addr.ByteString())\n\t\treturn func() {\n\t\t\tlock.Unlock(addr.ByteString())\n\t\t}\n\t}\n\n\tif dirPath == \"\" {\n\t\trepo, dbCloser, err = initInmemRepository(locker)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\t// only perform migration if not done already\n\t\tif _, err := os.Stat(path.Join(dirPath, indexPath)); err != nil {\n\t\t\terr = performEpochMigration(ctx, dirPath, opts)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\trepo, dbCloser, err = initDiskRepository(ctx, dirPath, locker, opts)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tsharkyBasePath := \"\"\n\tif dirPath != \"\" {\n\t\tsharkyBasePath = path.Join(dirPath, sharkyPath)\n\t}\n\terr = migration.Migrate(\n\t\trepo.IndexStore(),\n\t\tlocalmigration.AllSteps(sharkyBasePath, sharkyNoOfShards, repo.ChunkStore()),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcacheObj, err := initCache(ctx, opts.CacheCapacity, repo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogger := opts.Logger.WithName(loggerName).Register()\n\n\tdb := &DB{\n\t\tmetrics: metrics,\n\t\tlogger: logger,\n\t\tbaseAddr: opts.Address,\n\t\trepo: repo,\n\t\tlock: lock,\n\t\tcacheObj: cacheObj,\n\t\tretrieval: noopRetrieval{},\n\t\tpusherFeed: make(chan *pusher.Op),\n\t\tquit: make(chan struct{}),\n\t\tbgCacheLimiter: make(chan struct{}, 16),\n\t\tdbCloser: dbCloser,\n\t\tbatchstore: opts.Batchstore,\n\t\tvalidStamp: opts.ValidStamp,\n\t\tevents: events.NewSubscriber(),\n\t\treserveBinEvents: events.NewSubscriber(),\n\t\topts: workerOpts{\n\t\t\twarmupDuration: opts.WarmupDuration,\n\t\t\twakeupDuration: opts.ReserveWakeUpDuration,\n\t\t},\n\t\tdirectUploadLimiter: make(chan struct{}, pusher.ConcurrentPushes),\n\t\tinFlight: new(util.WaitingCounter),\n\t}\n\n\tif db.validStamp == nil {\n\t\tdb.validStamp = postage.ValidStamp(db.batchstore)\n\t}\n\n\tif opts.ReserveCapacity > 0 {\n\t\trs, err := reserve.New(\n\t\t\topts.Address,\n\t\t\trepo.IndexStore(),\n\t\t\topts.ReserveCapacity,\n\t\t\topts.RadiusSetter,\n\t\t\tlogger,\n\t\t\tfunc(ctx context.Context, store internal.Storage, addrs ...swarm.Address) error {\n\t\t\t\tdefer func() { db.metrics.CacheSize.Set(float64(db.cacheObj.Size())) }()\n\n\t\t\t\tdb.lock.Lock(cacheAccessLockKey)\n\t\t\t\tdefer db.lock.Unlock(cacheAccessLockKey)\n\n\t\t\t\treturn cacheObj.MoveFromReserve(ctx, store, addrs...)\n\t\t\t},\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdb.reserve = rs\n\n\t\tdb.metrics.StorageRadius.Set(float64(rs.Radius()))\n\t\tdb.metrics.ReserveSize.Set(float64(rs.Size()))\n\t}\n\tdb.metrics.CacheSize.Set(float64(db.cacheObj.Size()))\n\n\t// Cleanup any dirty state in upload and pinning stores, this could happen\n\t// in case of dirty shutdowns\n\terr = errors.Join(\n\t\tupload.CleanupDirty(db),\n\t\tpinstore.CleanupDirty(db),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func New(db *sql.DB) *Database {\n\treturn &Database{\n\t\tUsers: users.New(db),\n\t\tSessions: sessions.New(db),\n\t\tWorkouts: workouts.New(db),\n\t\tExercises: exercises.New(db),\n\t}\n}", "func (d *DB) newMem() (m *memdb.DB, err error) {\n\ts := d.s\n\n\tnum := s.allocFileNum()\n\tw, err := newJournalWriter(s.getJournalFile(num))\n\tif err != nil {\n\t\ts.reuseFileNum(num)\n\t\treturn\n\t}\n\n\told := d.journal\n\td.journal = w\n\tif old != nil {\n\t\told.close()\n\t\td.fjournal = old\n\t}\n\n\td.fseq = d.seq\n\n\tm = memdb.New(s.cmp)\n\tmem := &memSet{cur: m}\n\tif old := d.getMem_NB(); old != nil {\n\t\tmem.froze = old.cur\n\t}\n\tatomic.StorePointer(&d.mem, unsafe.Pointer(mem))\n\n\treturn\n}", "func (fact FileFactory) CreateDB(ctx context.Context, nbf *types.NomsBinFormat, urlObj *url.URL, params map[string]interface{}) (datas.Database, types.ValueReadWriter, tree.NodeStore, error) {\n\tsingletonLock.Lock()\n\tdefer singletonLock.Unlock()\n\n\tif s, ok := singletons[urlObj.Path]; ok {\n\t\treturn s.ddb, s.vrw, s.ns, nil\n\t}\n\n\tpath, err := url.PathUnescape(urlObj.Path)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tpath = filepath.FromSlash(path)\n\tpath = urlObj.Host + path\n\n\terr = validateDir(path)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tvar useJournal bool\n\tif params != nil {\n\t\t_, useJournal = params[ChunkJournalParam]\n\t}\n\n\tvar newGenSt *nbs.NomsBlockStore\n\tq := nbs.NewUnlimitedMemQuotaProvider()\n\tif useJournal && chunkJournalFeatureFlag {\n\t\tnewGenSt, err = nbs.NewLocalJournalingStore(ctx, nbf.VersionString(), path, q)\n\t} else {\n\t\tnewGenSt, err = nbs.NewLocalStore(ctx, nbf.VersionString(), path, defaultMemTableSize, q)\n\t}\n\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\toldgenPath := filepath.Join(path, \"oldgen\")\n\terr = validateDir(oldgenPath)\n\tif err != nil {\n\t\tif !errors.Is(err, os.ErrNotExist) {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\terr = os.Mkdir(oldgenPath, os.ModePerm)\n\t\tif err != nil && !errors.Is(err, os.ErrExist) {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t}\n\n\toldGenSt, err := nbs.NewLocalStore(ctx, newGenSt.Version(), oldgenPath, defaultMemTableSize, q)\n\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tst := nbs.NewGenerationalCS(oldGenSt, newGenSt)\n\t// metrics?\n\n\tvrw := types.NewValueStore(st)\n\tns := tree.NewNodeStore(st)\n\tddb := datas.NewTypesDatabase(vrw, ns)\n\n\tsingletons[urlObj.Path] = singletonDB{\n\t\tddb: ddb,\n\t\tvrw: vrw,\n\t\tns: ns,\n\t}\n\n\treturn ddb, vrw, ns, nil\n}", "func New(cfg config.DB) (*gorm.DB, error) {\n\tdb, err := database.New(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := db.AutoMigrate(\n\t\trepository.Client{},\n\t\trepository.Deal{},\n\t\trepository.Position{},\n\t\trepository.OHLCV{},\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func NewDB(filePath string) (*LDB, error) {\n ldb, err := leveldb.OpenFile(filePath, &opt.Options{\n Filter: filter.NewBloomFilter(10),\n })\n if _, corrupt := err.(*errors.ErrCorrupted); corrupt {\n ldb, err = leveldb.RecoverFile(filePath, nil)\n }\n\n logger := log.New(\"db\", filePath)\n\n //catch errors if db if we don't have a db\n if err != nil {\n return nil, err\n }\n\n //return new wrapped db\n return &LDB {\n db: ldb,\n path: filePath,\n log: logger,\n }, nil\n}", "func (b backend) New(ctx context.Context, l log.Interface, cfg *config.Config) (persist.Database, error) {\n\tusername, password, host, port, db :=\n\t\tcfg.Database.Postgres.Username,\n\t\tcfg.Database.Postgres.Password,\n\t\tcfg.Database.Postgres.Host,\n\t\tcfg.Database.Postgres.Port,\n\t\tcfg.Database.Postgres.DB\n\n\tconnString := fmt.Sprintf(\n\t\t\"postgres://%s:%s@%s:%d/%s\",\n\t\tusername,\n\t\tpassword,\n\t\thost,\n\t\tport,\n\t\tdb,\n\t)\n\n\tconn, err := pgxpool.Connect(ctx, connString)\n\tif err != nil {\n\t\treturn nil, errwrap.Wrap(err, \"failed to connect to postgres\")\n\t}\n\n\tq := gen.New(conn)\n\n\treturn &database{\n\t\tqueries: q,\n\t}, nil\n}", "func New(dsn string) (*Storage, error) {\n\t//dsn := \"host=localhost user=gorm password=gorm dbname=gorm port=9920 sslmode=disable TimeZone=Asia/Shanghai\"\n\tdb, err := sqlOpen(postgres.Open(dsn), &gorm.Config{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open database connection: %w\", err)\n\t}\n\n\terr = db.AutoMigrate(User{}, Token{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to auto-migrate persistence: %w\", err)\n\t}\n\n\treturn &Storage{\n\t\tdb: db,\n\t}, nil\n}", "func newRecipeDB() (RecipeDB, error) {\n\tdb := make(RecipeDB)\n\tf, err := os.Open(filepath.Join(getDbDir(), dbFileName))\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn db, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tbytes, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar recipelist []Recipe\n\tif err := json.Unmarshal(bytes, &recipelist); err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, recipe := range recipelist {\n\t\tdb[recipe.Name] = recipe\n\t}\n\treturn db, nil\n}", "func New(db *bolt.DB) *kvq.DB {\n\treturn kvq.NewDB(&DB{db})\n}", "func New(host string, port string, user string, pass string, dbname string) (*DataBase, error) {\n\tdsn := \"host=\" + host + \" user=\" + user + \" password=\" + pass + \" dbname=\" + dbname + \" port=\" + port + \" sslmode=disable\" + \" TimeZone=America/Sao_Paulo\"\n\tdb, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})\n\tif err != nil{\n\t\treturn nil, err\n\t}\t\n\tdb.AutoMigrate(&entity.SalesData{})\n\treturn &DataBase{\n\t\thost: host,\n\t\tport: port,\n\t\tuser: user,\n\t\tpass: pass,\n\t\tdbname: dbname,\n\t\tconnection: db,\n\t}, err\n}", "func NewDB(now string) *DB {\n\treturn &DB{\n\t\tmeasurements: make(map[string]*Measurement),\n\t\tseries: make(map[uint32]*Series),\n\t\tNow: mustParseTime(now),\n\t}\n}", "func NewInMemDatabase() Database {\n\tdb := new(InMemDatabase)\n\tdb.objByIDMap = make(map[UID]contrail.IObject)\n\tdb.typeDB = make(map[string]TypeMap)\n\tdb.objectData = make(map[UID]*ObjectData)\n\treturn db\n}", "func New(config *connect.Config) Db {\n\tvar db Db\n\t// first find db in dbMap by DatabaseName\n\tdb = dbMap[config.DatabaseName]\n\t// find\n\tif db != nil {\n\t\treturn db\n\t}\n\t// not find in dbMap - New\n\tswitch config.DbType {\n\tcase connect.MONGODB:\n\t\t// init mongodb\n\t\tdb = mongo.New(config)\n\t}\n\tdbMap[config.DatabaseName] = db\n\treturn db\n}", "func New(url string, timeout time.Duration) (*DB, error) {\n\n\tif timeout == 0 {\n\t\ttimeout = 60 * time.Second\n\t}\n\n\t// Create a session which maintains a pool of socket connections.\n\tsession, err := mgo.DialWithTimeout(url, timeout)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"mgo.DialWithTimeout: %s,%v\", url, timeout)\n\t}\n\n\tsession.SetMode(mgo.Monotonic, true)\n\n\tdb := DB{\n\t\tdatabase: session.DB(apiDatabase),\n\t\tsession: session,\n\t}\n\n\treturn &db, nil\n}", "func New(db SqlxDB) *DB {\n\treturn &DB{\n\t\tDB: db,\n\t}\n}", "func New(ctx context.Context, db *sql.DB, m map[string]string) (*Store, error) {\n\tstore := &Store{db: db}\n\terr := store.InitTable(ctx, m)\n\treturn store, err\n}", "func New() *gorm.DB {\n\tdb, err := gorm.Open(\n\t\tsqlite.Open(\"fiber_api.db\"),\n\t\t&gorm.Config{},\n\t)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdb.AutoMigrate(&transactions.Transaction{})\n\tdb.AutoMigrate(&users.User{})\n\n\treturn db\n}", "func New(tb testing.TB, dir string, ver string, logger func(string)) (*DB, error) {\n\tdb, err := doNew(tb, dir, ver, logger)\n\tif err != nil && tb != nil {\n\t\ttb.Fatal(\"failed initializing database: \", err)\n\t}\n\treturn db, err\n}", "func NewDb(storeType StoreType, dataDir string) (*Db, error) {\n\n\tvar store *genji.DB\n\tvar err error\n\n\tswitch storeType {\n\tcase StoreTypeMemory:\n\t\tstore, err = genji.Open(\":memory:\")\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Error opening memory store: \", err)\n\t\t}\n\n\tcase StoreTypeBolt:\n\t\tdbFile := path.Join(dataDir, \"data.db\")\n\t\tstore, err = genji.Open(dbFile)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\tcase StoreTypeBadger:\n\t\tlog.Fatal(\"Badger not currently supported\")\n\t\t/*\n\t\t\t // uncomment the following to enable badger support\n\t\t\t\t// Create a badger engine\n\t\t\t\tdbPath := path.Join(dataDir, \"badger\")\n\t\t\t\tng, err := badgerengine.NewEngine(badger.DefaultOptions(dbPath))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\n\t\t\t\t// Pass it to genji\n\t\t\t\tstore, err = genji.New(context.Background(), ng)\n\t\t*/\n\n\tdefault:\n\t\tlog.Fatal(\"Unknown store type: \", storeType)\n\t}\n\n\terr = store.Exec(`CREATE TABLE IF NOT EXISTS meta (id INT PRIMARY KEY)`)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating meta table: %w\", err)\n\t}\n\n\terr = store.Exec(`CREATE TABLE IF NOT EXISTS nodes (id TEXT PRIMARY KEY)`)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating nodes table: %w\", err)\n\t}\n\n\terr = store.Exec(`CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type)`)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating idx_nodes_type: %w\", err)\n\t}\n\n\terr = store.Exec(`CREATE TABLE IF NOT EXISTS edges (id TEXT PRIMARY KEY)`)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating edges table: %w\", err)\n\t}\n\n\terr = store.Exec(`CREATE INDEX IF NOT EXISTS idx_edge_up ON edges(up)`)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating idx_edge_up: %w\", err)\n\t}\n\n\terr = store.Exec(`CREATE INDEX IF NOT EXISTS idx_edge_down ON edges(down)`)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating idx_edge_down: %w\", err)\n\t}\n\n\tdb := &Db{store: store}\n\treturn db, db.initialize()\n}", "func New(options *pg.Options) *pg.DB {\n\n db := pg.Connect(options)\n db.AddQueryHook(dbLogger{})\n return db\n}", "func newPebbleDB(conf store.Conf) (store.DB, error) {\n\terr := os.MkdirAll(conf.Path, 0755)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\tdb, err := pebble.Open(conf.Path, &pebble.Options{})\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\treturn &pebbleDB{\n\t\tDB: db,\n\t\tconf: conf,\n\t}, nil\n}", "func newSqlDB(dsn string) *mysql.DB {\n\n\tdb, err := mysql.Open(\"dbatman\", dsn)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%s is unavailable\", dsn)\n\t\tos.Exit(2)\n\t}\n\n\tif err := db.Ping(); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%s is unreacheable\", dsn)\n\t\tos.Exit(2)\n\t}\n\n\treturn db\n}", "func newPage(db *Database, pageHead *pageHead) *page {\n\tp := page{\n\t\tdb: db,\n\t\tindex: db.dbHead.pageCount + 1,\n\t\tpageHead: pageHead,\n\t\tdata: make([]byte, db.dbHead.pageSize-PAGE_HEAD_SIZE),\n\t}\n\tdb.dbHead.pageCount++\n\tdb.writeHead()\n\treturn &p\n}", "func newSliceDB(path string, version int) (*sliceDB, error) {\r\n\tif path == \"\" {\r\n\t\treturn newMemorySliceDB()\r\n\t}\r\n\treturn newPersistentSliceDB(path, version)\r\n}", "func NewDb(db *sql.DB, driverName string) *DB {\n return &DB{DB: db, driverName: driverName, Mapper: mapper()}\n}", "func NewDB(session *mgo.Session) *DB {\n\treturn &DB{session: session}\n}", "func New(dl logbook.Logbook, databaseName string) (*Database, error) {\n\tdb := &Database{\n\t\tDlog: dl,\n\t}\n\n\t// Check if data folder exists\n\t_, err := os.Stat(config.DBFolder)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\t// If folder does not exist, create it\n\t\t\terr := os.Mkdir(config.DBFolder, 0777)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.New(\"error\")\n\t\t\t}\n\t\t}\n\t}\n\n\terr = os.Chdir(config.DBFolder)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil, errors.New(\"error\")\n\t}\n\n\tf, err := os.Create(databaseName)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil, errors.New(\"error\")\n\t}\n\n\tdefer f.Close()\n\n\tdb.DatabaseName = databaseName\n\tdb.Version = 001\n\tdb.File = f\n\tdb.Data = map[string][]byte{}\n\n\twr := bufio.NewWriter(f)\n\n\t_, err = fmt.Fprintf(wr, \"DolceDB.%d\", config.DBVersion)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\twr.Flush()\n\n\terr = db.RebuildMap()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func New(db *sql.DB) qbdb.DB {\n\treturn qbdb.New(Driver{}, db)\n}", "func New(db *sql.DB) qbdb.DB {\n\treturn qbdb.New(Driver{}, db)\n}", "func New(folder string, cfg *Config) (*DB, error) {\n\tenv, err := lmdb.NewEnv()\n\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"env create failed\")\n\t}\n\n\terr = env.SetMaxDBs(cfg.MaxDBs)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"env config failed\")\n\t}\n\terr = env.SetMapSize(cfg.SizeMbs * 1024 * 1024)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"map size failed\")\n\t}\n\n\tif err = env.SetFlags(cfg.EnvFlags); err != nil {\n\t\treturn nil, errors.Wrap(err, \"set flag\")\n\t}\n\n\tos.MkdirAll(folder, os.ModePerm)\n\terr = env.Open(folder, 0, cfg.Mode)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"open env\")\n\t}\n\n\tvar staleReaders int\n\tif staleReaders, err = env.ReaderCheck(); err != nil {\n\t\treturn nil, errors.Wrap(err, \"reader check\")\n\t}\n\tif staleReaders > 0 {\n\t\tlog.Printf(\"cleared %d reader slots from dead processes\", staleReaders)\n\t}\n\n\tvar dbi lmdb.DBI\n\terr = env.Update(func(txn *lmdb.Txn) (err error) {\n\t\tdbi, err = txn.CreateDBI(\"agg\")\n\t\treturn err\n\t})\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"create DB\")\n\t}\n\n\treturn &DB{env, dbi}, nil\n\n}", "func New(host string) *Database {\n\treturn &Database{\n\t\tHost: host,\n\t}\n}", "func New(path string) (*DB, error) {\n\tdb := &DB{path: path}\n\tif err := db.open(); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Could not initialize DB\")\n\t}\n\n\treturn db, nil\n}", "func newClientDatabase(database string) (*clientDatabase, error) {\n\tif database == \"\" {\n\t\tusr, err := user.Current()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdatabase = path.Join(usr.HomeDir, _DEFAULT_DATABASE_PATH)\n\t}\n\tos.MkdirAll(path.Dir(database), os.ModePerm)\n\tdb, err := sql.Open(\"sqlite\", database)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = db.Exec(`\n\tCREATE TABLE IF NOT EXISTS identity (\n\t\tid BOOLEAN PRIMARY KEY CONSTRAINT one_row CHECK (id) NOT NULL,\n\t\tpublic BLOB NOT NULL,\n\t\tprivate BLOB NOT NULL\n\t);\n\n\tCREATE TABLE IF NOT EXISTS friend (\n \t\tpublic BLOB PRIMARY KEY NOT NULL,\n \tname TEXT NOT NULL\n\t);\n\n\tCREATE TABLE IF NOT EXISTS prekey (\n\t\tpublic BLOB PRIMARY KEY NOT NULL,\n\t\tprivate BLOB NOT NULL\n\t);\n\n\tCREATE TABLE IF NOT EXISTS onetime (\n\t\tpublic BLOB PRIMARY KEY NOT NUll,\n\t\tprivate BLOB NOT NULL\n\t);\n\t`)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &clientDatabase{db}, nil\n}", "func NewDB(conf configuration.Ledger, opts *badger.Options) (*DB, error) {\n\topts = setOptions(opts)\n\tdir, err := filepath.Abs(conf.Storage.DataDirectory)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\topts.Dir = dir\n\topts.ValueDir = dir\n\n\tbdb, err := badger.Open(*opts)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"local database open failed\")\n\t}\n\n\tdb := &DB{\n\t\tdb: bdb,\n\t\ttxretiries: conf.Storage.TxRetriesOnConflict,\n\t\tidlocker: NewIDLocker(),\n\t\tnodeHistory: map[core.PulseNumber][]core.Node{},\n\t}\n\treturn db, nil\n}", "func New(config string, w io.Writer, wErr io.Writer) (db *Storage, err error) {\n\tif w == nil {\n\t\tw = os.Stdout\n\t}\n\tif wErr == nil {\n\t\twErr = os.Stderr\n\t}\n\tdb = &Storage{\n\t\tlog: alog.New(w, \"SQL: \", 0),\n\t\tlogErr: alog.New(w, \"SQLErr: \", 0),\n\t}\n\n\tif config == \"\" {\n\t\terr = fmt.Errorf(\"Invalid configuration passed (empty)\")\n\t\treturn\n\t}\n\tif db.db, err = sqlx.Open(\"mysql\", config); err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func CreateNew(db *mongo.Database) *DB {\n\treturn &DB{\n\t\tconn: db,\n\t}\n}", "func New(driver string, conStr string) (*gorm.DB, error) {\n\tdb, err := gorm.Open(driver, conStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = db.DB().Ping()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func New(db *leveldb.DB) (Storage, error) {\n\ttx, err := db.OpenTransaction()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error opening leveldb transaction: %v\", err)\n\t}\n\n\treturn &storage{\n\t\tstore: tx,\n\t\tdb: db,\n\t\ttx: tx,\n\t}, nil\n}", "func NewFromFile(fname string) (*DB, error) {\n\tb, err := ioutil.ReadFile(fname)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar (\n\t\tdocs []doc\n\t\tdb = New(len(docs))\n\t\tbcopy []byte\n\t)\n\terr = json.Unmarshal(b, &docs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, d := range docs {\n\t\tbcopy, err = d.Data.MarshalJSON()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdb.Set(d.ID, &bcopy)\n\t}\n\tdb.Lock()\n\tdefer db.Unlock()\n\treturn db, nil\n}", "func New(collection *driver.Collection) *DB {\n\treturn &DB{\n\t\tCollection: collection,\n\t}\n}", "func New(address, recordType string, deletePermanentAfter int64) (*DB, error) {\n\tdb := &DB{\n\t\tpool: &redis.Pool{\n\t\t\tWait: true,\n\t\t\tDialContext: func(ctx context.Context) (redis.Conn, error) {\n\t\t\t\tctx, cancelFn := context.WithTimeout(ctx, 5*time.Second)\n\t\t\t\tdefer cancelFn()\n\t\t\t\tc, err := redis.DialContext(ctx, \"tcp\", address)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(`redis.DialURL(): %w`, err)\n\t\t\t\t}\n\t\t\t\treturn c, nil\n\t\t\t},\n\t\t\tTestOnBorrow: func(c redis.Conn, t time.Time) error {\n\t\t\t\tif time.Since(t) < time.Minute {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\t_, err := c.Do(\"PING\")\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(`c.Do(\"PING\"): %w`, err)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\tdeletePermanentlyAfter: deletePermanentAfter,\n\t\trecordType: recordType,\n\t\tversionSet: recordType + \"_version_set\",\n\t\tdeletedSet: recordType + \"_deleted_set\",\n\t\tlastVersionKey: recordType + \"_last_version\",\n\t}\n\treturn db, nil\n}", "func (m *MongoDBImpl) New(isread bool) (*mgo.Database, *mgo.Session, error) {\n\tm.ml.Lock()\n\tdefer m.ml.Unlock()\n\n\t// if m.master is alive then continue else, reset as empty.\n\tif m.master != nil {\n\t\tif err := m.master.Ping(); err != nil {\n\t\t\tm.master = nil\n\t\t}\n\t}\n\n\tses, err := getSession(m.Config)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tm.master = ses\n\n\tif isread {\n\t\tcopy := m.master.Copy()\n\t\tdb := copy.DB(m.Config.DB)\n\t\treturn db, copy, nil\n\t}\n\n\tclone := m.master.Clone()\n\tdb := clone.DB(m.Config.DB)\n\treturn db, clone, nil\n}", "func New(dbFilename string) (*EdDb, error) {\n\n\t// First, create a hook which will attach a shared memory-only database to\n\t// each connction opened by golang's database/sql connection pool\n\tsql.Register(\"sqlite3ConnectionCatchingDriver\",\n\t\t&sqlite.SQLiteDriver{\n\t\t\tConnectHook: func(newConn *sqlite.SQLiteConn) error {\n\t\t\t\tnewConn.Exec(\"ATTACH DATABASE 'file::memory:?cache=shared&busy_timeout=60000' AS mem\", nil)\n\t\t\t\tfmt.Println(\"Attach Database to \", newConn)\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t)\n\n\t// The hook is now in place, so can create a connection to the disk Db:\n\tdbURI := fmt.Sprintf(\"file:%s?cache=shared&busy_timeout=60000\", dbFilename)\n\tdbConn, err := sqlx.Connect(\"sqlite3ConnectionCatchingDriver\", dbURI)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdbConn.SetMaxIdleConns(10)\n\tdbConn.Exec(`PRAGMA foreign_keys = ON;`)\n\n\tedDb := EdDb{\n\t\tdbConn: dbConn,\n\t\tstatements: map[string]*sqlx.NamedStmt{},\n\t}\n\n\terr = edDb.initDbSchema()\n\tif err != nil {\n\t\tdbConn.Close()\n\t\treturn nil, err\n\t}\n\n\terr = edDb.buildPreparedStatements()\n\tif err != nil {\n\t\tdbConn.Close()\n\t\treturn nil, err\n\t}\n\treturn &edDb, nil\n}", "func New(file string, configBytes []byte, log logging.Logger) (database.Database, error) {\n\tfilter := grocksdb.NewBloomFilter(BitsPerKey)\n\n\tblockOptions := grocksdb.NewDefaultBlockBasedTableOptions()\n\tblockOptions.SetBlockCache(grocksdb.NewLRUCache(BlockCacheSize))\n\tblockOptions.SetBlockSize(BlockSize)\n\tblockOptions.SetFilterPolicy(filter)\n\n\toptions := grocksdb.NewDefaultOptions()\n\toptions.SetCreateIfMissing(true)\n\toptions.OptimizeUniversalStyleCompaction(MemoryBudget)\n\toptions.SetBlockBasedTableFactory(blockOptions)\n\n\tif err := os.MkdirAll(file, perms.ReadWriteExecute); err != nil {\n\t\treturn nil, err\n\t}\n\n\tdb, err := grocksdb.OpenDb(options, file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\titeratorOptions := grocksdb.NewDefaultReadOptions()\n\titeratorOptions.SetFillCache(false)\n\n\treturn &Database{\n\t\tdb: db,\n\t\treadOptions: grocksdb.NewDefaultReadOptions(),\n\t\titeratorOptions: iteratorOptions,\n\t\twriteOptions: grocksdb.NewDefaultWriteOptions(),\n\t\tlog: log,\n\t}, nil\n}", "func NewDB(file string) *DB {\n\tdb, err := sqlite.Open(&sqlite.ConnectionURL{Database: file})\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn &DB{sess: db}\n}", "func CreateNew(dbFile, feeXPub string) error {\n\tlog.Infof(\"Initializing new database at %s\", dbFile)\n\n\tdb, err := bolt.Open(dbFile, 0600, &bolt.Options{Timeout: 1 * time.Second})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to open db file: %w\", err)\n\t}\n\n\tdefer db.Close()\n\n\t// Create all storage buckets of the VSP if they don't already exist.\n\terr = db.Update(func(tx *bolt.Tx) error {\n\t\t// Create parent bucket.\n\t\tvspBkt, err := tx.CreateBucket(vspBktK)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create %s bucket: %w\", string(vspBktK), err)\n\t\t}\n\n\t\t// Initialize with initial database version (1).\n\t\terr = vspBkt.Put(versionK, uint32ToBytes(initialVersion))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.Info(\"Generating ed25519 signing key\")\n\n\t\t// Generate ed25519 key\n\t\t_, signKey, err := ed25519.GenerateKey(rand.Reader)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to generate signing key: %w\", err)\n\t\t}\n\t\terr = vspBkt.Put(privateKeyK, signKey.Seed())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Generate a secret key for initializing the cookie store.\n\t\tlog.Info(\"Generating cookie secret\")\n\t\tsecret := make([]byte, 32)\n\t\t_, err = rand.Read(secret)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = vspBkt.Put(cookieSecretK, secret)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.Info(\"Storing extended public key\")\n\t\t// Store fee xpub\n\t\terr = vspBkt.Put(feeXPubK, []byte(feeXPub))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Create ticket bucket.\n\t\t_, err = vspBkt.CreateBucket(ticketBktK)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create %s bucket: %w\", string(ticketBktK), err)\n\t\t}\n\n\t\t// Create vote change bucket.\n\t\t_, err = vspBkt.CreateBucket(voteChangeBktK)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create %s bucket: %w\", string(voteChangeBktK), err)\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Info(\"Database initialized\")\n\n\treturn nil\n}", "func New() (*DB, error) {\n connStr := fmt.Sprintf(\n \"user=%s password=%s dbname=%s host=%s port=%s\",\n os.Getenv(\"USER_NAME\"),\n os.Getenv(\"USER_PASSWORD\"),\n os.Getenv(\"DB_NAME\"),\n os.Getenv(\"DB_HOST\"),\n os.Getenv(\"DB_PORT\"),\n )\n\n db, err := sql.Open(\"postgres\", connStr)\n if err != nil {\n return nil, err\n }\n if err = db.Ping(); err != nil {\n return nil, err\n }\n return &DB{db}, nil\n}", "func New(db *sql.DB) *Model {\n\treturn &Model{db}\n}", "func NewDatabase() Database {\n\tdb, err := sql.Open(\"postgres\", \"postgresql://root@localhost:26257?sslcert=%2Fhome%2Fubuntu%2Fnode1.cert&sslkey=%2Fhome%2Fubuntu%2Fnode1.key&sslmode=verify-full&sslrootcert=%2Fhome%2Fubuntu%2Fca.cert\")\n\tif err != nil {\n\t\tlog.Fatalln(\"database connection:\", err)\n\t}\n\tif _, err := db.Exec(\"CREATE DATABASE IF NOT EXISTS nfinite\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif _, err := db.Exec(\"SET DATABASE = nfinite\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif _, err = db.Exec(\"CREATE TABLE IF NOT EXISTS PartLookup (id SERIAL PRIMARY KEY, partId INT, ownerId INT);\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif _, err = db.Exec(\"CREATE TABLE IF NOT EXISTS FilePart (parentId INT, name string, id SERIAL PRIMARY KEY, fileIndex INT);\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif _, err = db.Exec(\"CREATE TABLE IF NOT EXISTS Client (id SERIAL, username string PRIMARY KEY, password string);\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif _, err = db.Exec(\"CREATE TABLE IF NOT EXISTS File (id SERIAL PRIMARY KEY, modified INT, name string, ownerId INT);\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn Database{db}\n}", "func NewDB(dbfile string) (*DB, error) {\n\tdb, err := gorm.Open(\"sqlite3\", dbfile)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not connect to db\")\n\t}\n\n\tif err := db.AutoMigrate(&Lease{}).Error; err != nil {\n\t\treturn nil, errors.Wrap(err, \"while migrating database\")\n\t}\n\n\treturn &DB{db: db}, nil\n}", "func New(db *pg.DB) DB {\n\td := DB{DB: db, crcTable: crc64.MakeTable(crc64.ECMA)}\n\n\treturn d\n}", "func (db *DB) newDB(master *sql.DB, workers ...*sql.DB) (*DB, error) {\n\tif err := master.Ping(); err != nil {\n\t\treturn nil, fmt.Errorf(\"Master DB is not reachable\")\n\t}\n\n\tdb.master = master\n\n\tdb.readReplicas = make(map[uint32]*sql.DB)\n\tfor i, readReplica := range workers {\n\t\tif err := readReplica.Ping(); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"ReadReplica DB %d is not reachable\", i+1)\n\t\t}\n\n\t\tdb.readReplicas[uint32(i)] = readReplica\n\t}\n\n\tdb.readReplicasCount = uint32(len(db.readReplicas))\n\tif db.readReplicasCount == 0 {\n\t\treturn nil, fmt.Errorf(\"At least one worker DB is required\")\n\t} else if db.readReplicasCount > math.MaxUint32 {\n\t\treturn nil, fmt.Errorf(\"Number of worker DBs cannot be more than %d\", math.MaxUint32)\n\t}\n\n\tgo db.heartbeatChecker()\n\n\treturn db, nil\n}", "func NewDB(filename string) (*DB, error) {\n\tdb, err := bbolt.Open(filename, 0600, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &DB{db: db}, nil\n}", "func NewDB(filename string) (*DB, error) {\n\tdb, err := bbolt.Open(filename, 0600, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &DB{db: db}, nil\n}", "func New() (*Database, error) {\n\tvar err error\n\tvar db *memdb.MemDB\n\tonce.Do(func() {\n\t\tinstance = &Database{}\n\t\tdb, err = instance.createSchema()\n\t\tinstance.db = db\n\t\tif err == nil {\n\t\t\tinstance.loadDefaults()\n\t\t}\n\t})\n\treturn instance, err\n}", "func NewDB(conf configuration.Ledger, opts *badger.Options) (*DB, error) {\n\topts = setOptions(opts)\n\tdir, err := filepath.Abs(conf.Storage.DataDirectory)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\topts.Dir = dir\n\topts.ValueDir = dir\n\n\tbdb, err := badger.Open(*opts)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"local database open failed\")\n\t}\n\n\tdb := &DB{\n\t\tdb: bdb,\n\t\ttxretiries: conf.Storage.TxRetriesOnConflict,\n\t\tidlocker: NewIDLocker(),\n\t}\n\treturn db, nil\n}", "func New(file string, configBytes []byte, log logging.Logger, namespace string, reg prometheus.Registerer) (database.Database, error) {\n\tparsedConfig := config{\n\t\tBlockCacheCapacity: DefaultBlockCacheSize,\n\t\tDisableSeeksCompaction: true,\n\t\tOpenFilesCacheCapacity: DefaultHandleCap,\n\t\tWriteBuffer: DefaultWriteBufferSize / 2,\n\t\tFilterBitsPerKey: DefaultBitsPerKey,\n\t\tMaxManifestFileSize: DefaultMaxManifestFileSize,\n\t\tMetricUpdateFrequency: DefaultMetricUpdateFrequency,\n\t}\n\tif len(configBytes) > 0 {\n\t\tif err := json.Unmarshal(configBytes, &parsedConfig); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%w: %s\", ErrInvalidConfig, err)\n\t\t}\n\t}\n\n\tlog.Info(\"creating leveldb\",\n\t\tzap.Reflect(\"config\", parsedConfig),\n\t)\n\n\t// Open the db and recover any potential corruptions\n\tdb, err := leveldb.OpenFile(file, &opt.Options{\n\t\tBlockCacheCapacity: parsedConfig.BlockCacheCapacity,\n\t\tBlockSize: parsedConfig.BlockSize,\n\t\tCompactionExpandLimitFactor: parsedConfig.CompactionExpandLimitFactor,\n\t\tCompactionGPOverlapsFactor: parsedConfig.CompactionGPOverlapsFactor,\n\t\tCompactionL0Trigger: parsedConfig.CompactionL0Trigger,\n\t\tCompactionSourceLimitFactor: parsedConfig.CompactionSourceLimitFactor,\n\t\tCompactionTableSize: parsedConfig.CompactionTableSize,\n\t\tCompactionTableSizeMultiplier: parsedConfig.CompactionTableSizeMultiplier,\n\t\tCompactionTotalSize: parsedConfig.CompactionTotalSize,\n\t\tCompactionTotalSizeMultiplier: parsedConfig.CompactionTotalSizeMultiplier,\n\t\tDisableSeeksCompaction: parsedConfig.DisableSeeksCompaction,\n\t\tOpenFilesCacheCapacity: parsedConfig.OpenFilesCacheCapacity,\n\t\tWriteBuffer: parsedConfig.WriteBuffer,\n\t\tFilter: filter.NewBloomFilter(parsedConfig.FilterBitsPerKey),\n\t\tMaxManifestFileSize: parsedConfig.MaxManifestFileSize,\n\t})\n\tif _, corrupted := err.(*errors.ErrCorrupted); corrupted {\n\t\tdb, err = leveldb.RecoverFile(file, nil)\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %s\", ErrCouldNotOpen, err)\n\t}\n\n\twrappedDB := &Database{\n\t\tDB: db,\n\t\tcloseCh: make(chan struct{}),\n\t}\n\tif parsedConfig.MetricUpdateFrequency > 0 {\n\t\tmetrics, err := newMetrics(namespace, reg)\n\t\tif err != nil {\n\t\t\t// Drop any close error to report the original error\n\t\t\t_ = db.Close()\n\t\t\treturn nil, err\n\t\t}\n\t\twrappedDB.metrics = metrics\n\t\twrappedDB.closeWg.Add(1)\n\t\tgo func() {\n\t\t\tt := time.NewTicker(parsedConfig.MetricUpdateFrequency)\n\t\t\tdefer func() {\n\t\t\t\tt.Stop()\n\t\t\t\twrappedDB.closeWg.Done()\n\t\t\t}()\n\n\t\t\tfor {\n\t\t\t\tif err := wrappedDB.updateMetrics(); err != nil {\n\t\t\t\t\tlog.Warn(\"failed to update leveldb metrics\",\n\t\t\t\t\t\tzap.Error(err),\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tselect {\n\t\t\t\tcase <-t.C:\n\t\t\t\tcase <-wrappedDB.closeCh:\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\treturn wrappedDB, nil\n}", "func New(config *Config) (*Database, error) {\n\tdb, err := gorm.Open(\"postgres\", config.DatabaseURI)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to connect to database\")\n\t}\n\treturn &Database{db}, nil\n}", "func NewDB(path string) (*gorm.DB, error) {\n\t// connect to the example sqlite, create if it doesn't exist\n\tdb, err := gorm.Open(\"sqlite3\", path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn db, nil\n}", "func New() *gorm.DB {\n\tvar driver string = viper.GetString(\"database_driver\")\n\tvar user string = viper.GetString(\"database_user\")\n\tvar password string = viper.GetString(\"database_password\")\n\tvar port string = viper.GetString(\"database_port\")\n\tvar host string = viper.GetString(\"database_host\")\n\tvar sslMode string = viper.GetString(\"database_ssl\")\n\tvar databaseName string = viper.GetString(\"database_name\")\n\tvar dbConn string = fmt.Sprintf(\"host=%s port=%s user=%s password=%s dbname=%s sslmode=%s\", host, port, user, password, databaseName, sslMode)\n\n\tvar maxIdleCons int = viper.GetInt(\"database_max_idle_conns\")\n\tvar maxOpenConns int = viper.GetInt(\"database_max_open_conns\")\n\n\tdb, err := gorm.Open(driver, dbConn)\n\tif err != nil {\n\t\tlogrus.Fatalf(\"Error connecting to database %s. %s.\", databaseName, err)\n\t}\n\n\tdb.SetLogger(gormlog.New(logrus.StandardLogger()))\n\tdb.LogMode(true)\n\n\tdb.DB().SetMaxIdleConns(maxIdleCons)\n\tdb.DB().SetMaxOpenConns(maxOpenConns)\n\n\treturn db\n}", "func newDbConnection(connStr string) *sql.DB {\n\tdb, err := sql.Open(\"postgres\", connStr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = db.Ping()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"[es] new db connection established.\")\n\treturn db\n}", "func New() (Store, error) {\n dbUsername := os.Getenv(\"DB_USERNAME\")\n dbPassword := os.Getenv(\"DB_PASSWORD\")\n dbHost := os.Getenv(\"DB_HOST\")\n dbTable := os.Getenv(\"DB_TABLE\")\n dbPort := os.Getenv(\"DB_PORT\")\n dbSSLMode := os.Getenv(\"DB_SSL_MODE\")\n\n connectionString := fmt.Sprintf(\n \"host=%s port=%s user=%s dbname=%s password=%s sslmode=%s\",\n dbHost, dbPort, dbUsername, dbTable, dbPassword, dbSSLMode,\n )\n\n db, err := sqlx.Connect(\"postgres\", connectionString)\n if err != nil {\n return Store{}, err\n }\n\n return Store{\n db: db,\n }, nil\n}", "func New(db *sql.DB, logger log.Logger) (todo.Repository, error) {\n\t// return repository\n\treturn &repository{\n\t\tdb: db,\n\t\tlogger: log.With(logger, \"rep\", \"cockroachdb\"),\n\t}, nil\n}", "func New() *thingsStore {\n\tdb, err := gorm.Open(\"postgres\", \"host=localhost port=5432 user=postgres dbname=gorming sslmode=disable\")\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn &thingsStore{\n\t\tdb: db,\n\t}\n}", "func New(db *sql.DB) *Postgres {\n\tpg := &Postgres{\n\t\tDB: db,\n\t\tmigrator: migrations.New(db),\n\t}\n\n\tbase := BaseStore{\n\t\tDB: db,\n\t\tTxier: pg.Tx,\n\t}\n\n\tpg.download = &DownloadStore{base}\n\tpg.user = &UserStore{base}\n\tpg.file = &FileStore{base}\n\tpg.chat = &ChatStore{base}\n\n\treturn pg\n}", "func NewDB() *MemDB {\n\treturn &MemDB{\n\t\tbtree: btree.New(bTreeDegree),\n\t\tsaved: make(map[uint64]*btree.BTree),\n\t\tvmgr: db.NewVersionManager(nil),\n\t}\n}", "func NewDB(sugar *zap.SugaredLogger, db *sqlx.DB, options ...Option) (*BlockInfoStorage, error) {\n\tconst schemaFMT = `\n\tCREATE TABLE IF NOT EXISTS %[1]s\n(\n\tblock bigint NOT NULL,\n\ttime timestamp NOT NULL,\n\tCONSTRAINT %[1]s_pk PRIMARY KEY(block)\n) ;\nCREATE INDEX IF NOT EXISTS %[1]s_time_idx ON %[1]s (time);\n`\n\tvar (\n\t\tlogger = sugar.With(\"func\", caller.GetCurrentFunctionName())\n\t\ttableNames = map[string]string{blockInfoTable: blockInfoTable}\n\t)\n\ths := &BlockInfoStorage{\n\t\tsugar: sugar,\n\t\tdb: db,\n\t\ttableNames: tableNames,\n\t}\n\tfor _, opt := range options {\n\t\tif err := opt(hs); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tquery := fmt.Sprintf(schemaFMT, hs.tableNames[blockInfoTable])\n\tlogger.Debugw(\"initializing database schema\", \"query\", query)\n\tif _, err := hs.db.Exec(query); err != nil {\n\t\treturn nil, err\n\t}\n\tlogger.Debug(\"database schema initialized successfully\")\n\treturn hs, nil\n}", "func insertNewDB(pool ServerPool, spec db.Specifier) (db.DB, error) {\n\t// If we need to create the db connection, then we need to write-lock\n\t// the DB pool.\n\tpool.Lock()\n\tdefer pool.Unlock()\n\n\tif db, ok := pool.Get(spec); ok {\n\t\t// Someone else may have already come along and added it\n\t\tif db.Spec().NeedsUpdate(spec) {\n\t\t\tif err := db.Update(spec); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\treturn db, nil\n\t}\n\n\tnewDb, err := spec.NewDB()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpool.Put(spec, newDb)\n\tnewDb, ok := pool.Get(spec)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"new database not found for %T\", spec)\n\t}\n\treturn newDb, nil\n}", "func New(rawURL, recordType string, deletePermanentAfter int64, opts ...Option) (*DB, error) {\n\tdb := &DB{\n\t\tdeletePermanentlyAfter: deletePermanentAfter,\n\t\trecordType: recordType,\n\t\tversionSet: recordType + \"_version_set\",\n\t\tdeletedSet: recordType + \"_deleted_set\",\n\t\tlastVersionKey: recordType + \"_last_version\",\n\t\tclosed: make(chan struct{}),\n\t}\n\n\tfor _, o := range opts {\n\t\to(db)\n\t}\n\tdb.pool = &redis.Pool{\n\t\tWait: true,\n\t\tDial: func() (redis.Conn, error) {\n\t\t\tc, err := redis.DialURL(rawURL, redis.DialTLSConfig(db.tlsConfig))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(`redis.DialURL(): %w`, err)\n\t\t\t}\n\t\t\treturn c, nil\n\t\t},\n\t\tTestOnBorrow: func(c redis.Conn, t time.Time) error {\n\t\t\tif time.Since(t) < time.Minute {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t_, err := c.Do(\"PING\")\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(`c.Do(\"PING\"): %w`, err)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\tmetrics.AddRedisMetrics(db.pool.Stats)\n\treturn db, nil\n}", "func New(connectionString string, log *log.Logger) (*Store, error) {\n\tdb, err := gorm.Open(postgres.Open(connectionString), &gorm.Config{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := db.AutoMigrate(&gh.Repository{}, &gh.Commit{}); err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Println(\"db init successful\")\n\treturn &Store{\n\t\tdb: db,\n\t\tlog: log,\n\t}, nil\n}", "func New(db *sqlx.DB) *Model {\n\treturn &Model{db: db}\n}", "func TestNewDatabase(t *testing.T) {\n\tconf := config.GetConfig()\n\tdbClient, err := databases.NewClient(conf)\n\tassert.NoError(t, err)\n\tdb := databases.NewDatabase(conf, dbClient)\n\n\tassert.NotEmpty(t, db)\n}", "func newCache(conf configuration.Conf, fname string) *Cache {\n\tvar err error\n\n\tc := new(Cache)\n\tc.apiKey = conf.APISecretKey\n\tc.DB, err = gorm.Open(\"sqlite3\", fname)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = c.DB.AutoMigrate(&quandl.Record{}, &ref{}).Error\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tc.ref = make(map[string]time.Time)\n\n\t// Restore saved refs if any from the db.\n\t// That will avoid unnecessary refresh, and identify all Tickers.\n\t// Extract tickers from config file as default tickers.\n\tc.restoreRefs(conf.Tickers()...)\n\n\treturn c\n}", "func New(remoteURL string, discriminator string) (*JSONLite, error) { // nolint:gocyclo\n\tdb := &JSONLite{}\n\tif remoteURL[len(remoteURL)-1:] == \"/\" {\n\t\tremoteURL = remoteURL[:len(remoteURL)-1]\n\t}\n\tdb.remoteURL = remoteURL\n\n\tdb.Fs, db.remoteStoreFolder, db.remoteIsLocal = toFS(remoteURL)\n\tdb.remoteDBFile = filepath.Join(db.remoteStoreFolder, \"item.db\")\n\n\tdb.localFS, db.localStoreFolder = db.Fs, db.remoteStoreFolder\n\tif !db.remoteIsLocal {\n\t\ttmpDir, err := ioutil.TempDir(\"\", \"jsonlite\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlocalPath := filepath.Join(tmpDir, filepath.Base(remoteURL))\n\t\tdb.localFS, db.localStoreFolder, _ = toFS(localPath)\n\t}\n\tdb.localDBFile = filepath.Join(db.localStoreFolder, \"item.db\")\n\n\texists, err := afero.Exists(db, db.remoteDBFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdb.NewDB = !exists\n\n\terr = db.localFS.MkdirAll(db.localStoreFolder, 0755)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif db.NewDB {\n\t\tlog.Printf(\"Creating store %s\", db.remoteStoreFolder)\n\t\t_, err := db.Create(db.remoteDBFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else if !db.remoteIsLocal {\n\t\tif err := copy.File(db, db.localFS, db.remoteDBFile, db.localDBFile); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tdb.cursor, err = sql.Open(\"sqlite3\", db.localDBFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// db.options = map[string]interface{}{}\n\t// db.schemas = map[string]*jsonschema.RootSchema{}\n\tdb.schemas = newSchemaMap()\n\n\tif db.NewDB {\n\t\terr = db.createOptionsTable()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdb.SetStrict(true)\n\t\tdb.SetDiscriminator(discriminator)\n\t}\n\n\terr = db.loadSchemas()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdb.tables = newTableMap()\n\n\ttables, err := db.getTables()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor tableName, table := range tables {\n\t\tdb.tables.store(tableName, table)\n\t}\n\n\treturn db, nil\n}" ]
[ "0.7379258", "0.693042", "0.684732", "0.68308365", "0.68118536", "0.666203", "0.66521454", "0.6642036", "0.6638563", "0.660994", "0.6606906", "0.66040975", "0.65959966", "0.65898097", "0.65816885", "0.6578505", "0.65556026", "0.65446734", "0.6541298", "0.6541298", "0.6541125", "0.6534688", "0.65142065", "0.64910996", "0.6461919", "0.64454824", "0.64358294", "0.6421265", "0.64129555", "0.64062315", "0.64001745", "0.6400147", "0.63946474", "0.6388856", "0.63873917", "0.6373354", "0.6360879", "0.6359941", "0.6346989", "0.6333567", "0.62997854", "0.6298841", "0.629248", "0.6288607", "0.6288569", "0.62739754", "0.6272696", "0.62597317", "0.6245775", "0.62449026", "0.6239299", "0.62385607", "0.6235263", "0.6228784", "0.62274206", "0.62274206", "0.6216953", "0.6211798", "0.62085176", "0.62014043", "0.61990297", "0.61988527", "0.61901975", "0.61887324", "0.6188062", "0.6187609", "0.6179387", "0.61750287", "0.61695343", "0.61546504", "0.6150265", "0.61372215", "0.6134473", "0.6125438", "0.6125102", "0.61238", "0.6123197", "0.6121925", "0.6120331", "0.6116583", "0.6116583", "0.61093736", "0.6105266", "0.60946476", "0.60940486", "0.60830516", "0.60804427", "0.60786504", "0.6078418", "0.6076707", "0.607581", "0.6068613", "0.6065748", "0.6065377", "0.6064425", "0.60635036", "0.6052332", "0.60497916", "0.60473907", "0.60446894", "0.60403085" ]
0.0
-1
Sync serves to synchronize the DB
func (db *DB) Sync() error { var dbb, err = New(db.supportedSymbols) if err != nil { err = errors.Wrap(err, "New") log.Printf("Error: %+v\n", err) return err } db.Lock() db.store = dbb.store db.Unlock() return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (db *DB) Sync() error { return fdatasync(db) }", "func (db *DB) Sync() error {\n\t// 刷到 DB\n\treturn fdatasync(db)\n}", "func (db *DB) Sync() error {\n\tdb.mu.Lock()\n\tdefer db.mu.Unlock()\n\treturn db.sync()\n}", "func (mb *metadataBackend) sync() error {\n\treturn mb.db.Sync()\n}", "func (g *Gateway) Sync() {\n\tg.lock.RLock()\n\tdefer g.lock.RUnlock()\n\n\tif g.server == nil || g.info.Role != db.RaftVoter {\n\t\treturn\n\t}\n\n\tclient, err := g.getClient()\n\tif err != nil {\n\t\tlogger.Warnf(\"Failed to get client: %v\", err)\n\t\treturn\n\t}\n\n\tdefer func() { _ = client.Close() }()\n\n\tfiles, err := client.Dump(context.Background(), \"db.bin\")\n\tif err != nil {\n\t\t// Just log a warning, since this is not fatal.\n\t\tlogger.Warnf(\"Failed get database dump: %v\", err)\n\t\treturn\n\t}\n\n\tdir := filepath.Join(g.db.Dir(), \"global\")\n\tfor _, file := range files {\n\t\tpath := filepath.Join(dir, file.Name)\n\t\terr := os.WriteFile(path, file.Data, 0600)\n\t\tif err != nil {\n\t\t\tlogger.Warnf(\"Failed to dump database file %s: %v\", file.Name, err)\n\t\t}\n\t}\n}", "func (s *Store) Sync() error {\n\treturn s.db.Sync()\n}", "func (s *Syncer) Sync() error {\n\treturn nil\n}", "func (server *Server) Sync() {\n\n}", "func (s *Store) sync() {\n\tresult, err := logger.GetAll(local)\n\tif err != nil {\n\t\tlogs.CRITICAL.Println(\"Panic for get all objects\")\n\t}\n\ttotal := len(result)\n\tif total != 0 {\n\t\tlogs.INFO.Println(\"Total of records: \", total)\n\t}\n\tif total == 0 {\n\t\tlog.Println(\"Nothing to sync\")\n\t\tif store.getFile() != \"\" {\n\t\t\tlogs.INFO.Println(\"Initiating clearing....\")\n\t\t\tremoveLines(store.getFile(), 1, -1)\n\t\t}\n\t\tstore.Transaction = nil\n\t\treturn\n\t}\n\tfor i := 0; i < total; i++ {\n\t\tlogs.INFO.Println(\"PUSH -> UserName: \" +\n\t\t\tresult[i].UserName + \" :: DataBase: \" +\n\t\t\tresult[i].DatabaseName + \" :: VirtualTransactionID: \" +\n\t\t\tresult[i].VirtualTransactionID)\n\n\t\tstore.Transaction = append(store.Transaction, result[i].VirtualTransactionID)\n\t\tlogger.Persist(prod, result[i])\n\t\t// Depending on the amount of data and traffic, goroutines that were\n\t\t// first run have already removed the registry, not identifying the\n\t\t// registry in the database at the current execution.\n\t\terr := logger.DeletePerObjectId(local, result[i].ID)\n\t\tif err != nil {\n\t\t\tlogs.INFO.Println(\"ObjectId -> \" + result[i].ID.Hex() + \" removed on the last goroutine\")\n\t\t}\n\t}\n}", "func synchronize(kvsync kvs.Sync) {\n\tc := context.Background()\n\n\t// This is the object to be synchronized\n\tdb := Data{}\n\n\t// Creating a sync object from the provided lower-level kv sync.\n\ts := sync.Sync{\n\t\tSync: kvsync,\n\t}\n\n\t// Registering callback for given object with given format\n\ts.SyncObject(sync.SyncObject{\n\t\tCallback: SyncCallback,\n\t\tObject: &db,\n\t\tFormat: \"/db/stored/here/\",\n\t})\n\n\t// Time wheel to trigger callback notification for successive events\n\tfor {\n\t\te := s.Next(c)\n\t\tif e != nil {\n\t\t\tpanic(e)\n\t\t}\n\t\tif stopTimeWheel {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfmt.Printf(\"Final DB state %v\\n\\n\", &db)\n}", "func (f *File) Sync() error {\n\tif !f.Synced {\n\t\tf.Synced = true\n\n\t\t_, err := dbAccess.Update(f)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (ds *DkStore) Sync() {\n\terr := ds.f.Sync()\n\tcheck(err)\n}", "func (uc *Userclient) Sync() error {\r\n\treturn uc.iSync()\r\n}", "func (c *sentryCore) Sync() error {\n\tc.client.Flush(c.flushTimeout)\n\treturn nil\n}", "func (d *Datastore) Sync(ds.Key) error {\n\treturn nil\n}", "func Sync() error {\n\treturn conf.Sync()\n}", "func (c *Core) Sync() error {\n\treturn c.core.Sync()\n}", "func (s *Server) Sync() {\n\tdefer base.CheckPanic()\n\tbase.Logger().Info(\"start meta sync\", zap.Int(\"meta_timeout\", s.cfg.Master.MetaTimeout))\n\tfor {\n\t\tvar meta *protocol.Meta\n\t\tvar err error\n\t\tif meta, err = s.masterClient.GetMeta(context.Background(), &protocol.RequestInfo{NodeType: protocol.NodeType_ServerNode}); err != nil {\n\t\t\tbase.Logger().Error(\"failed to get meta\", zap.Error(err))\n\t\t\tgoto sleep\n\t\t}\n\n\t\t// load master config\n\t\terr = json.Unmarshal([]byte(meta.Config), &s.cfg)\n\t\tif err != nil {\n\t\t\tbase.Logger().Error(\"failed to parse master config\", zap.Error(err))\n\t\t\tgoto sleep\n\t\t}\n\n\t\t// connect to data store\n\t\tif s.dataAddress != s.cfg.Database.DataStore {\n\t\t\tbase.Logger().Info(\"connect data store\", zap.String(\"database\", s.cfg.Database.DataStore))\n\t\t\tif s.dataStore, err = data.Open(s.cfg.Database.DataStore); err != nil {\n\t\t\t\tbase.Logger().Error(\"failed to connect data store\", zap.Error(err))\n\t\t\t\tgoto sleep\n\t\t\t}\n\t\t\ts.dataAddress = s.cfg.Database.DataStore\n\t\t}\n\n\t\t// connect to cache store\n\t\tif s.cacheAddress != s.cfg.Database.CacheStore {\n\t\t\tbase.Logger().Info(\"connect cache store\", zap.String(\"database\", s.cfg.Database.CacheStore))\n\t\t\tif s.cacheStore, err = cache.Open(s.cfg.Database.CacheStore); err != nil {\n\t\t\t\tbase.Logger().Error(\"failed to connect cache store\", zap.Error(err))\n\t\t\t\tgoto sleep\n\t\t\t}\n\t\t\ts.cacheAddress = s.cfg.Database.CacheStore\n\t\t}\n\n\t\t// check FM version\n\t\ts.latestFMVersion = meta.FmVersion\n\t\tif s.latestFMVersion != s.fmVersion {\n\t\t\tbase.Logger().Info(\"new factorization machine model found\",\n\t\t\t\tzap.Int64(\"old_version\", s.fmVersion),\n\t\t\t\tzap.Int64(\"new_version\", s.latestFMVersion))\n\t\t\ts.syncedChan <- true\n\t\t}\n\tsleep:\n\t\ttime.Sleep(time.Duration(s.cfg.Master.MetaTimeout) * time.Second)\n\t}\n}", "func (s *InMemoryHandler) Sync() error {\n\treturn nil\n}", "func syncDatabase() {\n\tadapter := adapters[db.DriverName()]\n\tdbTables := adapter.tables()\n\t// Create or update existing tables\n\tfor tableName, mi := range modelRegistry.registryByTableName {\n\t\tif _, ok := dbTables[tableName]; !ok {\n\t\t\tcreateDBTable(mi.tableName)\n\t\t}\n\t\tupdateDBColumns(mi)\n\t\tupdateDBIndexes(mi)\n\t}\n\t// Drop DB tables that are not in the models\n\tfor dbTable := range adapter.tables() {\n\t\tvar modelExists bool\n\t\tfor tableName := range modelRegistry.registryByTableName {\n\t\t\tif dbTable != tableName {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmodelExists = true\n\t\t\tbreak\n\t\t}\n\t\tif !modelExists {\n\t\t\tdropDBTable(dbTable)\n\t\t}\n\t}\n}", "func (d *DriveDB) sync() {\n\tvar c *gdrive.ChangeList\n\tfor {\n\t\tc = <-d.changes\n\t\terr := d.processChange(c)\n\t\tif err != nil {\n\t\t\t// TODO: trigger reinit(), unless rate > N, then log.Fatal\n\t\t\tlog.Printf(\"error evaluating change from drive: %v\", err)\n\t\t}\n\t}\n}", "func BeginSync(st o.SyncType) {\n\n\tdbName := c.DBConfig.DBName.StockD1\n\tnames, _ := h.GetCollectionNames(dbName)\n\tcCount := len(names)\n\tvar start, end time.Time\n\tstart = time.Now()\n\tfmt.Println(\"Sync stock base information from database StockD1. SyncType is \", st.ToString())\n\tfmt.Println(\"Begin time: \", start.Format(\"2006-01-02 15:04:05\"))\n\tfor i, name := range names {\n\t\tIncrementSync(name, st)\n\t\tfmt.Printf(\"Stock code: %s (%d/%d) \\r\", name, i+1, cCount)\n\t}\n\tend = time.Now()\n\tfmt.Println(\"Synchronization Completed at \", end.Format(\"2006-01-02 15:04:05\"))\n\tfmt.Println(\"Duration: \", end.Sub(start).String())\n\tfmt.Println()\n}", "func (core *SysLogCore) Sync() error {\n\treturn nil\n}", "func Sync(db *sql.DB, filenames []string, src interface{}) error {\n\tsqls, err := Diff(db, filenames, src)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, sql := range sqls {\n\t\tif _, err := tx.Exec(sql); err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn err\n\t\t}\n\t}\n\treturn tx.Commit()\n}", "func (s *DataNode) Sync() {\n\ts.control.Sync()\n}", "func SyncToSMdb() {\n\n\tdbName := c.DBConfig.DBName.StockMarketRawD1\n\tnames, _ := h.GetCollectionNames(dbName)\n\tcCount := len(names)\n\n\tfor i, name := range names {\n\t\tMergeDMtoMM(name)\n\t\tfmt.Printf(\"Synchronizing daily-bar to monthly-bar. Stock code:%s (%d/%d) \\r\", name, i+1, cCount)\n\t}\n\tfmt.Println()\n}", "func (s *CheckpointManager) Sync() {\n\t_, _, err := s.flushCtrl.Flush(s.indexID, FlushModeForceLocal)\n\tif err != nil {\n\t\tlogutil.BgLogger().Warn(\"flush local engine failed\", zap.String(\"category\", \"ddl-ingest\"), zap.Error(err))\n\t}\n\ts.mu.Lock()\n\ts.progressLocalSyncMinKey()\n\ts.mu.Unlock()\n\twg := sync.WaitGroup{}\n\twg.Add(1)\n\ts.updaterCh <- &wg\n\twg.Wait()\n}", "func (s *SentryWriter) Sync() error {\n\treturn nil\n}", "func (mp *SQLProvider) performFirstSync(sync func(string, string)) error {\n\tperPage := mp.perPage\n\ttables, err := getAllTables(mp.db, mp.dbName)\n\tif err != nil {\n\t\tlog.Printf(\"unable to get dataBases. Error: %+v\", err.Error())\n\t\treturn err\n\t}\n\n\tfor _, table := range tables {\n\n\t\tif table == meta_changelog_table || table == meta_data_table || contains(mp.excludedTables, table) {\n\t\t\tcontinue\n\t\t}\n\n\t\tprimaryKeysList, err := getAllPrimaryKeysInTable(mp.db, table)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\tprimaryKeysCSV := strings.Join(primaryKeysList, \",\")\n\n\t\tcountRow := mp.db.QueryRow(\"select count(*) from \" + table)\n\n\t\tvar count int\n\t\terr = countRow.Scan(&count)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\n\t\tpages := count / perPage\n\t\tfor i := 0; i < pages; i++ {\n\t\t\tstartInt := i * perPage\n\t\t\tstart := strconv.Itoa(startInt)\n\t\t\tend := strconv.Itoa(startInt + perPage)\n\n\t\t\tquery := fmt.Sprintf(`SELECT * FROM (\n \t\t\t\tSELECT *, ROW_NUMBER() OVER (ORDER BY %[4]s) as row FROM %[1]s\n \t\t\t\t\t) a WHERE row > %[2]s and row <= %[3]s`, table, start, end, primaryKeysCSV)\n\n\t\t\ttableJSON, err := getJSON(mp.db, query)\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"unable to convert table data to json. Error: %+v\", err)\n\t\t\t}\n\t\t\tsync(tableJSON, table)\n\t\t}\n\t}\n\treturn nil\n}", "func (instance *Storage) Sync() error {\n\tif dirty {\n\t\tif err := writeToFile(); err != nil {\n\t\t\treturn err\n\t\t} else {\n\t\t\tdirty = false\n\t\t}\n\t}\n\treturn nil\n}", "func CmdSync(c *cli.Context) {\n\t// Enable multi core setting\n\tSetupMultiCore()\n\n\t// Load tomlConfig\n\ttmlconf := LoadTomlConf(c.String(\"config\"))\n\n\t// Create DB Fetcher\n\tfetcher, err := database.CreateFetcher(tmlconf.Database[c.String(\"from\")], tmlconf.SSH[c.String(\"from\")])\n\tif err != nil {\n\t\tpanic(\"Failed to create fetcher instance: \" + err.Error())\n\t}\n\n\tdefer DeleteTmpDir(TMP_DIR_PATH)\n\n\t// Fetch\n\terr = fetcher.Fetch()\n\tif err != nil {\n\t\tpanic(\"Failed to fetch: \" + err.Error())\n\t}\n\n\t// Create DB Inserter\n\tinserter, err := database.CreateInserter(tmlconf.Database[c.String(\"to\")], tmlconf.SSH[c.String(\"to\")])\n\tif err != nil {\n\t\tpanic(\"Failed to create inserter instance: \" + err.Error())\n\t}\n\n\t// Clean up\n\terr = inserter.Clean()\n\tif err != nil {\n\t\tpanic(\"Failed to clean: \" + err.Error())\n\t}\n\n\t// INSERT\n\terr = inserter.Insert()\n\tif err != nil {\n\t\tpanic(\"Failed to insert: \" + err.Error())\n\t}\n}", "func (s *Syncer) Sync() error {\n\ts.called = true\n\treturn s.err\n}", "func Sync(c *SQLConnection) (done []string, err error) {\n\tcount, err := migrate.ExecMax(c.db, c.dialect, c.source, migrate.Up, 0)\n\tif err != nil {\n\t\treturn\n\t}\n\tif count == 0 {\n\t\treturn\n\t}\n\n\trecords, err := migrate.GetMigrationRecords(c.db, c.dialect)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor i := len(records) - count; i < len(records); i++ {\n\t\tdone = append(done, records[i].Id)\n\t}\n\treturn\n}", "func Sync() error {\n\treturn log.Sync()\n}", "func (client *Client) Sync() {\n\t/*go func() {*/\n\tstart := time.Now()\n\t// Fetch\n\tconn, err := net.Dial(\"tcp\", client.address)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t_, _ = fmt.Fprintf(conn, \"fetch \"+strconv.Itoa(client.id))\n\tresponse := make([]byte, 1024)\n\t_, err = conn.Read(response)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tbody := string(response)\n\tif !strings.Contains(body, \"<empty>\") {\n\t\tclient.syncs = body\n\t}\n\t_ = conn.Close()\n\n\t// Then sync\n\tconn, err = net.Dial(\"tcp\", client.address)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Build sync object\n\tdata := \"\"\n\tif len(client.actions) != 0 {\n\t\tfor _, action := range client.actions {\n\t\t\tswitch action.(type) {\n\t\t\tcase *CameraMovementAction:\n\t\t\t\tsync := action.(*CameraMovementAction)\n\t\t\t\tdata += fmt.Sprintf(\"skin %d %f %f %f %f %f %f\",\n\t\t\t\t\tclient.id,\n\t\t\t\t\tsync.position.X(),\n\t\t\t\t\tsync.position.Y(),\n\t\t\t\t\tsync.position.Z(),\n\t\t\t\t\tsync.rotation.X(),\n\t\t\t\t\tsync.rotation.Y(),\n\t\t\t\t\tsync.rotation.Z())\n\t\t\tdefault:\n\t\t\t\tpanic(\"unknown INetworkAction type\")\n\t\t\t}\n\t\t}\n\t} else {\n\t\tdata = \"<empty>\"\n\t}\n\n\t_, _ = fmt.Fprintf(conn, fmt.Sprintf(\"sync %d\\n\", client.id)+data)\n\tresponse = make([]byte, 256)\n\t_, err = conn.Read(response)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif !strings.Contains(string(response), \"good\") {\n\t\tpanic(\"The server is a fucking liar!\")\n\t}\n\t_ = conn.Close()\n\n\t// All modification send\n\t// Clean modifications\n\tclient.actions = []INetworkAction{}\n\t/*}()*/\n\tfmt.Printf(\"ping :%d\\r\", time.Now().Sub(start).Milliseconds())\n}", "func (s *Wal) Sync() {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\ts.log.Sync()\n}", "func BeginSyncRTD() {\n\tdbNameRaw := c.DBConfig.DBName.StockMarketRawD1\n\tnamesRaw, _ := h.GetCollectionNames(dbNameRaw)\n\n\tcCount := len(namesRaw)\n\tvar start, end time.Time\n\tstart = time.Now()\n\tfmt.Println(\"Sync database StockMarketRawD1 to StockD1.\")\n\tfmt.Println(\"Begin time: \", start.Format(\"2006-01-02 15:04:05\"))\n\tfor i, name := range namesRaw {\n\t\tIncrementSyncRTD(name)\n\t\tfmt.Printf(\"Stock code: %s (%d/%d) \\r\", name, i+1, cCount)\n\t}\n\tend = time.Now()\n\tfmt.Println(\"Synchronization Completed at \", end.Format(\"2006-01-02 15:04:05\"))\n\tfmt.Println(\"Duration: \", end.Sub(start).String())\n\tfmt.Println()\n}", "func (m *Mgr) Sync(ctx context.Context) error {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\treturn m.sync(ctx)\n}", "func (db *syncHandle) Sync() error {\n\t// // CPU profiling by default\n\t// defer profile.Start().Stop()\n\tvar err1 error\n\tbaseSeq := db.internal.lastSyncSeq\n\terr := db.timeWindow.foreachTimeWindow(func(timeID int64, wEntries windowEntries) (bool, error) {\n\t\twinEntries := make(map[uint64]windowEntries)\n\t\tfor _, we := range wEntries {\n\t\t\tif we.seq() == 0 {\n\t\t\t\tdb.entriesInvalid++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif we.seq() < baseSeq {\n\t\t\t\tbaseSeq = we.seq()\n\t\t\t}\n\t\t\tif we.seq() > db.internal.upperSeq {\n\t\t\t\tdb.internal.upperSeq = we.seq()\n\t\t\t}\n\t\t\tblockID := startBlockIndex(we.seq())\n\t\t\tmseq := db.cacheID ^ uint64(we.seq())\n\t\t\tmemdata, err := db.mem.Get(uint64(blockID), mseq)\n\t\t\tif err != nil || memdata == nil {\n\t\t\t\tdb.entriesInvalid++\n\t\t\t\tlogger.Error().Err(err).Str(\"context\", \"mem.Get\")\n\t\t\t\terr1 = err\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvar e entry\n\t\t\tif err = e.UnmarshalBinary(memdata[:entrySize]); err != nil {\n\t\t\t\tdb.entriesInvalid++\n\t\t\t\terr1 = err\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ts := slot{\n\t\t\t\tseq: e.seq,\n\t\t\t\ttopicSize: e.topicSize,\n\t\t\t\tvalueSize: e.valueSize,\n\n\t\t\t\tcacheBlock: memdata[entrySize:],\n\t\t\t}\n\t\t\tif s.msgOffset, err = db.dataWriter.append(s.cacheBlock); err != nil {\n\t\t\t\treturn true, err\n\t\t\t}\n\t\t\tif exists, err := db.blockWriter.append(s, db.startBlockIdx); exists || err != nil {\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn true, err\n\t\t\t\t}\n\t\t\t\tdb.freeList.free(s.seq, s.msgOffset, s.mSize())\n\t\t\t\tdb.entriesInvalid++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif _, ok := winEntries[e.topicHash]; ok {\n\t\t\t\twinEntries[e.topicHash] = append(winEntries[e.topicHash], we)\n\t\t\t} else {\n\t\t\t\twinEntries[e.topicHash] = windowEntries{we}\n\t\t\t}\n\n\t\t\tdb.filter.Append(we.seq())\n\t\t\tdb.internal.count++\n\t\t\tdb.internal.inBytes += int64(e.valueSize)\n\t\t}\n\t\tfor h := range winEntries {\n\t\t\ttopicOff, ok := db.trie.getOffset(h)\n\t\t\tif !ok {\n\t\t\t\treturn true, errors.New(\"db.Sync: timeWindow sync error: unable to get topic offset from trie\")\n\t\t\t}\n\t\t\twOff, err := db.windowWriter.append(h, topicOff, winEntries[h])\n\t\t\tif err != nil {\n\t\t\t\treturn true, err\n\t\t\t}\n\t\t\tif ok := db.trie.setOffset(topic{hash: h, offset: wOff}); !ok {\n\t\t\t\treturn true, errors.New(\"db:Sync: timeWindow sync error: unable to set topic offset in trie\")\n\t\t\t}\n\t\t}\n\t\tblockID := startBlockIndex(baseSeq)\n\t\tdb.mem.Free(uint64(blockID), db.cacheID^baseSeq)\n\t\tif err1 != nil {\n\t\t\treturn true, err1\n\t\t}\n\n\t\tif err := db.sync(false); err != nil {\n\t\t\treturn true, err\n\t\t}\n\t\tif db.syncComplete {\n\t\t\tif err := db.wal.SignalLogApplied(timeID); err != nil {\n\t\t\t\tlogger.Error().Err(err).Str(\"context\", \"wal.SignalLogApplied\")\n\t\t\t\treturn true, err\n\t\t\t}\n\t\t}\n\t\t// db.freeList.releaseLease(timeID)\n\t\treturn false, nil\n\t})\n\tif err != nil || err1 != nil {\n\t\tfmt.Println(\"db.Sync: error \", err, err1)\n\t\tdb.syncComplete = false\n\t\tdb.abort()\n\t\t// run db recovery if an error occur with the db sync.\n\t\tif err := db.startRecovery(); err != nil {\n\t\t\t// if unable to recover db then close db.\n\t\t\tpanic(fmt.Sprintf(\"db.Sync: Unable to recover db on sync error %v. Closing db...\", err))\n\t\t}\n\t}\n\n\treturn db.sync(false)\n}", "func TestSync(t *testing.T) {\n\t// Same as TestReorganize() w/r/t no return value, etc.\n\tdb, _ := Open(db_filename, \"c\")\n\tdefer db.Close()\n\tdefer os.Remove(db_filename)\n\n\tdb.Sync()\n}", "func Sync() error {\n\treturn DefaultConfig.Sync()\n}", "func (w *diskTableWriter) sync() error {\n\tif err := w.dataFile.Sync(); err != nil {\n\t\treturn fmt.Errorf(\"failed to sync data file: %w\", err)\n\t}\n\n\tif err := w.indexFile.Sync(); err != nil {\n\t\treturn fmt.Errorf(\"failed to sync index file: %w\", err)\n\t}\n\n\tif err := w.sparseIndexFile.Sync(); err != nil {\n\t\treturn fmt.Errorf(\"failed to sync sparse index file: %w\", err)\n\t}\n\n\treturn nil\n}", "func (ht *HashTable) Sync() (err error) {\n\tif err = ht.DataFile.Sync(); err != nil {\n\t\treturn\n\t}\n\treturn nil\n}", "func Sync(cmd *cobra.Command, args []string) {\n\n\tfdbURL, err := cmd.Flags().GetString(\"doclayer-url\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfDB, err := cmd.Flags().GetString(\"doclayer-database\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdebug, err := cmd.Flags().GetBool(\"debug\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif debug {\n\t\tlog.SetLevel(log.DebugLevel)\n\t}\n\n\tlog.Debugf(\"Creating client for FDB: %v, %v, %v\", fdbURL, fDB, debug)\n\tclientOptions := options.Client().ApplyURI(fdbURL).SetMinPoolSize(10).SetMaxPoolSize(100)\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\tclient, err := NewDocLayerClient(ctx, clientOptions)\n\tif err != nil {\n\t\tlog.Fatalf(\"Can't create client for FoundationDB document layer: %v. URL provided was: %v\", err, fdbURL)\n\t\treturn\n\t}\n\n\tlog.Debugf(\"Client created.\")\n\n\tstartTime := time.Now()\n\t//Close db client after serving request\n\tvar clientKeepAlive = false\n\tauthorizationHeader := os.Getenv(\"AUTHORIZATION_HEADER\")\n\tif err = SyncRepo(client, fDB, args[0], args[1], authorizationHeader, clientKeepAlive); err != nil {\n\t\tlog.Fatalf(\"Can't add chart repository to database: %v\", err)\n\t\treturn\n\t}\n\ttimeTaken := time.Since(startTime).Seconds()\n\tlog.Infof(\"Successfully added the chart repository %s to database in %v seconds\", args[0], timeTaken)\n}", "func (d *specialDevice) sync() error {\n\tif d.toLimb != nil {\n\t\tif err := d.toLimb(d.instance); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif d.mqttClient != nil {\n\t\tif err := d.mqttClient.Publish(mqtt.PublishMessage{Payload: d.instance.Status}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\td.log.V(1).Info(\"Synced\")\n\treturn nil\n}", "func Sync() {\n\tLogger.Sync()\n}", "func (gc *GelfCore) Sync() error {\n\treturn nil\n}", "func (d *Database) Sync() error {\n\tnewStatus := deb822.Document{\n\t\tParagraphs: []deb822.Paragraph{},\n\t}\n\n\t// Sync the /var/lib/dpkg/info directory\n\tfor _, pkg := range d.Packages {\n\t\tnewStatus.Paragraphs = append(newStatus.Paragraphs, pkg.Paragraph)\n\n\t\tif pkg.StatusDirty {\n\t\t\tif err := pkg.Sync(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// Make a new version of /var/lib/dpkg/status\n\tos.Rename(\"/var/lib/dpkg/status\", \"/var/lib/dpkg/status-old\")\n\tformatter := deb822.NewFormatter()\n\tformatter.SetFoldedFields(\"Description\")\n\tformatter.SetMultilineFields(\"Conffiles\")\n\tif err := os.WriteFile(\"/var/lib/dpkg/status\",\n\t\t[]byte(formatter.Format(newStatus)), 0644); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Controller) Sync(ctx context.Context, backup *api.MysqlBackup, ns string) error {\n\tglog.Infof(\"sync backup: %s\", backup.Name)\n\n\tif len(backup.Spec.ClusterName) == 0 {\n\t\treturn fmt.Errorf(\"cluster name is not specified\")\n\t}\n\n\tif backup.Status.Completed {\n\t\t// silence skip it\n\t\tglog.V(2).Infof(\"Backup '%s' already competed, skiping.\", backup.Name)\n\t\treturn nil\n\t}\n\n\tcluster, err := c.clusterLister.MysqlClusters(backup.Namespace).Get(\n\t\tbackup.Spec.ClusterName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cluster not found: %s\", err)\n\t}\n\n\tcopyBackup := backup.DeepCopy()\n\tfactory := bfactory.New(copyBackup, c.k8client, c.myClient, cluster)\n\n\tif err := factory.SetDefaults(); err != nil {\n\t\treturn fmt.Errorf(\"set defaults: %s\", err)\n\t}\n\n\tif err := factory.Sync(ctx); err != nil {\n\t\treturn fmt.Errorf(\"sync: %s\", err)\n\t}\n\n\tif _, err := c.myClient.Mysql().MysqlBackups(ns).Update(copyBackup); err != nil {\n\t\treturn fmt.Errorf(\"backup update: %s\", err)\n\t}\n\n\treturn nil\n}", "func (e *Exhibition) Sync() error {\n\tif err := e.Validate(); err != nil {\n\t\treturn err\n\t}\n\tvar exists bool\n\thashId := e.GetHashId()\n\terr := db.QueryRow(`\n\t\tSELECT EXISTS (\n\t\t\tSELECT 1 FROM exhibition WHERE substring(_byteid, 5) = $1\n\t\t)\n\t`, hashId).Scan(&exists)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tif exists {\n\t\terr = e.Update()\n\t} else {\n\t\terr = e.Create()\n\t}\n\treturn err\n}", "func Sync() error {\n\treturn logger.Sync()\n}", "func (uc *Userclient) iSync() error {\r\n\treturn nil\r\n}", "func (l *LogWriter) Sync() (err error) {\n\treturn\n}", "func (mm *MMapRWManager) Sync() (err error) {\n\treturn mm.m.Flush()\n}", "func (a ReverseHttpFile) Sync() error {\n\treturn nil\n}", "func (f MemFile) Sync() error {\n\treturn nil\n}", "func (l *Logger) Sync() error {\n\treturn l.core.Sync()\n}", "func (wal *seriesWAL) Sync() error {\n\treturn wal.base.sync()\n}", "func (db *TriasDB) SetSync(key []byte, value []byte) {\n\tdb.mtx.Lock()\n\tdefer db.mtx.Unlock()\n\n\tdb.SetNoLock(key, value)\n}", "func (s *Syncable) Sync(ctx context.Context, entry *types.AcceptedProposal) error {\n\tbytes := []byte(entry.Data)\n\tvar jsonData interface{}\n\tjson.Marshal(string(bytes))\n\terr := json.Unmarshal(bytes, &jsonData)\n\tif err != nil {\n\t\tlog.Printf(\"Error Unmarshalling json: %v\", err)\n\t\treturn err\n\t}\n\n\tvar values []interface{}\n\tfor _, path := range s.insert.jsonPath {\n\t\tres, err := jsonpath.JsonPathLookup(jsonData, path)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error while parsing [%v] in [%v]: %v\\n\", path, jsonData, err)\n\t\t\treturn err\n\t\t}\n\t\tvalues = append(values, res)\n\t}\n\n\ttx, err := s.DB.BeginTx(context.Background(), &sql.TxOptions{Isolation: 0, ReadOnly: false})\n\n\tif err != nil {\n\t\tlog.Printf(\"Error while creating transaction: %v\", err)\n\t\treturn err\n\t}\n\t_, err = tx.Stmt(s.insert.stmt).ExecContext(ctx, values...)\n\tif err != nil {\n\t\tlog.Printf(\"Error while executing statement: %v\", err)\n\t\treturn err\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\tlog.Printf(\"Error while executing commit: %v\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func RunSyncdb(name string, force bool, verbose bool) error {\n\tBootStrap()\n\n\tal := getDbAlias(name)\n\tcmd := new(commandSyncDb)\n\tcmd.al = al\n\tcmd.force = force\n\tcmd.noInfo = !verbose\n\tcmd.verbose = verbose\n\tcmd.rtOnError = true\n\treturn cmd.Run()\n}", "func (_Univ2 *Univ2Session) Sync() (*types.Transaction, error) {\n\treturn _Univ2.Contract.Sync(&_Univ2.TransactOpts)\n}", "func (ch *ClickHouse) SyncStore(overriddenDataSchema *schema.BatchHeader, objects []map[string]interface{}, timeIntervalValue string, cacheTable bool) error {\n\treturn syncStoreImpl(ch, overriddenDataSchema, objects, timeIntervalValue, cacheTable)\n}", "func (a *App) Sync(quiet bool) {\n\tbackend := NewBackend()\n\tif !backend.CredsFileExists() {\n\t\tfmt.Println(\"You're not authenticated with ultralist.io yet. Please run `ultralist auth` first.\")\n\t\treturn\n\t}\n\n\ta.load()\n\tif !a.TodoList.IsSynced {\n\t\tfmt.Println(\"This list isn't currently syncing with ultralist.io. Please run `ultralist sync --setup` to set up syncing.\")\n\t\treturn\n\t}\n\n\tvar synchronizer *Synchronizer\n\tif quiet {\n\t\tsynchronizer = NewQuietSynchronizer()\n\t} else {\n\t\tsynchronizer = NewSynchronizer()\n\t}\n\tsynchronizer.Sync(a.TodoList, a.EventLogger.CurrentSyncedList)\n\n\tif synchronizer.WasSuccessful() {\n\t\ta.EventLogger.ClearEventLogs()\n\t\ta.TodoStore.Save(a.TodoList.Data)\n\t}\n}", "func (service *EntriesService) Sync(spaceID string, initial bool, syncToken ...string) *Collection {\n\tpath := fmt.Sprintf(\"/spaces/%s%s/sync\", spaceID, getEnvPath(service.c))\n\tmethod := \"GET\"\n\n\treq, err := service.c.newRequest(method, path, nil, nil)\n\tif err != nil {\n\t\treturn &Collection{}\n\t}\n\n\tcol := NewCollection(&CollectionOptions{})\n\tif initial == true {\n\t\tcol.Query.Initial(\"true\")\n\t}\n\tif len(syncToken) == 1 {\n\t\tcol.SyncToken = syncToken[0]\n\t}\n\tcol.c = service.c\n\tcol.req = req\n\n\treturn col\n}", "func (lb *Elb) Sync() {\n\tlb.syncCh <- 1\n}", "func (c *Contractor) saveSync() error {\n\treturn c.persist.saveSync(c.persistData())\n}", "func (gameCommunication *GameCommunication) Sync() {\n\tgameCommunication.Client.SendSyncRequest()\n}", "func (_Univ2 *Univ2Transactor) Sync(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Univ2.contract.Transact(opts, \"sync\")\n}", "func Sync() {\n\tlog.RLock()\n\tdefer log.RUnlock()\n\tlog.active.Sync()\n}", "func (z *zpoolctl) Sync(ctx context.Context, names ...string) *execute {\n\targs := []string{\"sync\"}\n\tif names != nil {\n\t\tfor _, name := range names {\n\t\t\targs = append(args, name)\n\t\t}\n\t}\n\treturn &execute{ctx: ctx, name: z.cmd, args: args}\n}", "func Sync(ctx context.Context, config *tsbridge.Config) error {\n\tstore, err := LoadStorageEngine(ctx, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer store.Close()\n\n\tmetrics, err := tsbridge.NewMetricConfig(ctx, config, store)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar errSync []error\n\n\tsdClientOnce.Do(func() {\n\t\tsdClient, err = stackdriver.NewAdapter(ctx, config.Options.SDLookBackInterval)\n\t\tif err != nil {\n\t\t\terrSync = append(errSync, fmt.Errorf(\"unable to initialize stackdriver adapter: %v\", err))\n\t\t}\n\t})\n\n\tstatsCollectorOnce.Do(func() {\n\t\tstatsCollector, err = tsbridge.NewCollector(ctx, config.Options.SDInternalMetricsProject, config.Options.MonitoringBackends)\n\t\tif err != nil {\n\t\t\terrSync = append(errSync, fmt.Errorf(\"unable to initialize stats collector: %v\", err))\n\t\t}\n\t})\n\n\t// Process errors from Once.Do blocks since we cannot return in those\n\tif len(errSync) > 0 {\n\t\treturn fmt.Errorf(\"errors occured during sync init: %v\", errSync)\n\t}\n\n\tif errs := tsbridge.UpdateAllMetrics(ctx, metrics, sdClient, config.Options.UpdateParallelism, statsCollector); errs != nil {\n\t\tmsg := strings.Join(errs, \"; \")\n\t\treturn errors.New(msg)\n\t}\n\treturn nil\n}", "func Sync() error {\n\treturn GetZapLogger().Sync()\n}", "func (m *Manager) Sync() error {\n\tlastActionCachePostfix := \"-last-action-date-cache\"\n\n\tstatus := make(map[string]bool)\n\tstatus[\"doneFetch\"] = !m.Fetch\n\tstatus[\"doneEnrich\"] = !m.Enrich\n\n\tfetchCh := m.fetch(m.fetcher, lastActionCachePostfix)\n\n\tvar err error\n\tif status[\"doneFetch\"] == false {\n\t\terr = <-fetchCh\n\t\tif err == nil {\n\t\t\tstatus[\"doneFetch\"] = true\n\t\t}\n\t\ttime.Sleep(5 * time.Second)\n\t}\n\n\tif status[\"doneEnrich\"] == false {\n\t\terr = <-m.enrich(m.enricher, lastActionCachePostfix)\n\t\tif err == nil {\n\t\t\tstatus[\"doneEnrich\"] = true\n\t\t}\n\t\ttime.Sleep(5 * time.Second)\n\t}\n\n\treturn nil\n}", "func (logger MockLogger) Sync() {\n\t_ = logger.Sugar.Sync()\n}", "func (ms *MesosCluster) Sync(tp string) error {\n\n\tblog.Info(\"mesos cluster sync ...\")\n\n\treturn nil\n}", "func (_Univ2 *Univ2TransactorSession) Sync() (*types.Transaction, error) {\n\treturn _Univ2.Contract.Sync(&_Univ2.TransactOpts)\n}", "func (h *Handle) SyncDBs() (IDBList, error) {\n\tdblist := C.alpm_get_syncdbs(h.ptr)\n\tif dblist == nil {\n\t\treturn &DBList{nil, *h}, h.LastError()\n\t}\n\n\treturn &DBList{(*list)(unsafe.Pointer(dblist)), *h}, nil\n}", "func (c ChainSync) Sync(done chan bool) {\n\tprevHeight, prevHash, err := db.GetLastBlock(c.Coin.Symbol)\n\tif err != nil {\n\t\tlog.Printf(\"Could not get last %s block from database: %s\\n\", c.Coin.Symbol, err.Error())\n\t\treturn\n\t}\n\n\tclient := c.Coin.RPCClient()\n\n\theight, hash, err := client.GetLastBlock()\n\tif err != nil {\n\t\tlog.Printf(\"Could not get last block from %s chain: %s.\\n\", c.Coin.Symbol, err.Error())\n\t\treturn\n\t}\n\n\tif prevHeight < height {\n\t\t// @TODO check for reorg\n\t\tlog.Printf(\"Syncing %s chain to block %d (from %d, %d blocks)\\n\", c.Coin.Symbol, height, prevHeight, height-prevHeight)\n\n\t\tc.syncFromHeight(prevHeight, height)\n\n\t} else if prevHash != hash {\n\t\t// @TODO check for reorg or new best\n\t} else {\n\t\t// no new block(s) found\n\t}\n\n\tdone <- true\n}", "func (r *UserRead) sync(q *msg.Request, mr *msg.Result) {\n\tvar (\n\t\tuserID, userName string\n\t\tfirstName, lastName string\n\t\tmailAddr, team string\n\t\temployeeNr int\n\t\tisDeleted bool\n\t\terr error\n\t\trows *sql.Rows\n\t)\n\n\tif rows, err = r.stmtSync.Query(); err != nil {\n\t\tmr.ServerError(err, q.Section)\n\t\treturn\n\t}\n\n\tfor rows.Next() {\n\t\tif err = rows.Scan(\n\t\t\t&userID,\n\t\t\t&userName,\n\t\t\t&firstName,\n\t\t\t&lastName,\n\t\t\t&employeeNr,\n\t\t\t&mailAddr,\n\t\t\t&isDeleted,\n\t\t\t&team,\n\t\t); err != nil {\n\t\t\trows.Close()\n\t\t\tmr.ServerError(err, q.Section)\n\t\t\treturn\n\t\t}\n\n\t\tmr.User = append(mr.User, proto.User{\n\t\t\tID: userID,\n\t\t\tUserName: userName,\n\t\t\tFirstName: firstName,\n\t\t\tLastName: lastName,\n\t\t\tEmployeeNumber: strconv.Itoa(employeeNr),\n\t\t\tMailAddress: mailAddr,\n\t\t\tIsDeleted: isDeleted,\n\t\t\tTeamID: team,\n\t\t})\n\t}\n\tif err = rows.Err(); err != nil {\n\t\tmr.ServerError(err, q.Section)\n\t\treturn\n\t}\n\tmr.OK()\n}", "func Sync(ctx context.Context, config *tsbridge.Config, metrics *tsbridge.Metrics) error {\n\tstore, err := LoadStorageEngine(ctx, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer store.Close()\n\n\tmetricCfg, err := tsbridge.NewMetricConfig(ctx, config, store)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif errs := metrics.UpdateAll(ctx, metricCfg, config.Options.UpdateParallelism); errs != nil {\n\t\tmsg := strings.Join(errs, \"; \")\n\t\treturn errors.New(msg)\n\t}\n\treturn nil\n}", "func Sync(prefix string, backend Backend, logf LogFunc, client *clientv3.Client, wg *sync.WaitGroup) {\n\tctx := context.Background()\n\n\trev := backend.LoadRev()\n\n\tif rev == 0 {\n\t\tlogf(\"initializing\")\n\t\tsync := mirror.NewSyncer(client, prefix, 0)\n\t\tgets, errors := sync.SyncBase(ctx)\n\n\t\tgo func() {\n\t\t\terr, ok := <-errors\n\t\t\tif ok {\n\t\t\t\tlogf(\"error while reading: %v\", err)\n\t\t\t}\n\t\t}()\n\n\t\tfor get := range gets {\n\t\t\tfor _, kv := range get.Kvs {\n\t\t\t\tbackend.Set(string(kv.Key), kv.Value)\n\t\t\t}\n\t\t\trev = get.Header.Revision\n\t\t}\n\n\t\tbackend.SaveRev(rev)\n\t}\n\n\tif wg != nil {\n\t\twg.Done()\n\t}\n\n\tlogf(\"following changes\")\n\tfor {\n\t\tsync := mirror.NewSyncer(client, prefix, rev)\n\t\tfor update := range sync.SyncUpdates(ctx) {\n\t\t\tif err := update.Err(); err != nil {\n\t\t\t\tlogf(\"got error: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor _, event := range update.Events {\n\t\t\t\tif event.Kv == nil {\n\t\t\t\t\tbackend.Delete(string(event.PrevKv.Key), event.PrevKv.Value)\n\t\t\t\t} else {\n\t\t\t\t\tbackend.Set(string(event.Kv.Key), event.Kv.Value)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\trev = update.Header.Revision\n\t\t\tbackend.SaveRev(rev)\n\t\t}\n\n\t\tlogf(\"sync updates ended, restarting\")\n\t}\n}", "func (db *DB) SyncFromMing(serverURL, company, user, password string) error {\n\t// New a session\n\ts, err := ming800.NewSession(serverURL, company, user, password)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"NewSession() error: %v\", err)\n\t}\n\n\t// Login\n\tif err = s.Login(); err != nil {\n\t\treturn fmt.Errorf(\"Login() error: %v\", err)\n\t}\n\n\t// Clear all data before sync.\n\tif err = db.Clear(); err != nil {\n\t\treturn err\n\t}\n\n\t// Walk\n\t// Write your own class and student handler functions.\n\t// Class and student handler will be called while walking ming800.\n\tif err = s.Walk(db); err != nil {\n\t\treturn fmt.Errorf(\"Walk() error: %v\", err)\n\t}\n\n\t// Logout\n\tif err = s.Logout(); err != nil {\n\t\treturn fmt.Errorf(\"Logout() error: %v\", err)\n\t}\n\n\treturn nil\n}", "func (c *BlockCache) Sync() {\n\tc.lengthsFile.Sync()\n\tc.blocksFile.Sync()\n}", "func Sync(t time.Time, log *zap.Logger) {\n\tlog.Info(\"S3 sync begun\")\n\n\tbucket := Config.bucket\n\tregion := Config.bucketRegion\n\n\tsvc := setUpAwsSession(region)\n\tresp, err := listBucket(bucket, region, svc, log)\n\tif err != nil {\n\t\tlog.Error(\"failed to list bucket\",\n\t\t\tzap.Error(err),\n\t\t\tzap.String(\"bucket\", bucket),\n\t\t\tzap.String(\"region\", region),\n\t\t)\n\n\t\treturn\n\t}\n\n\tif err := parseAllFiles(resp, bucket, svc, log); err != nil {\n\t\treturn\n\t}\n\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tUp = true\n\tHealth = true\n\n\tlog.Info(\"S3 sync finished\")\n}", "func (af *archfile) Sync() {\n\tif af.sync && af.last.Add(2*time.Second).Before(time.Now()) {\n\t\taf.mu.Lock()\n\t\taf.buf.Flush()\n\t\taf.mu.Unlock()\n\t}\n}", "func (s *Server) Sync(stream pb.KVStore_SyncServer) error {\n\tfor {\n\t\t// receive a stream of sync requests from another node\n\t\tmsg, err := stream.Recv()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\ts.logger.Error(\"sync connection closed due to EOF\", zap.Error(err))\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tconst msg = \"sync connection closed due to unexpected error\"\n\t\t\ts.logger.Error(msg, zap.Error(err))\n\t\t\treturn fmt.Errorf(msg+\": %w\", err)\n\t\t}\n\n\t\ts.logger.Debug(\"sync_in\", zap.Stringer(\"op\", msg.Operation),\n\t\t\tzap.String(\"key\", msg.Key), zap.Int64(\"ts\", msg.GetTimestamp()))\n\n\t\t// TODO: create a SyncMessage with From & ToProto\n\t\t// insert sync operation into this node's store\n\t\tif err := s.store.SyncIn(msg); err != nil {\n\t\t\tconst msg = \"failed to store sync message\"\n\t\t\ts.logger.Error(msg, zap.Error(err))\n\t\t\treturn fmt.Errorf(msg+\": %w\", err)\n\t\t}\n\t}\n}", "func (esClient *elasticClientAlias) Sync(btcClient bitcoinClientAlias) bool {\n\tinfo, err := btcClient.GetBlockChainInfo()\n\tif err != nil {\n\t\tsugar.Fatal(\"Get info error: \", err.Error())\n\t}\n\n\tvar DBCurrentHeight float64\n\tagg, err := esClient.MaxAgg(\"height\", \"block\", \"block\")\n\tif err != nil {\n\t\tif err.Error() == \"query max agg error\" {\n\t\t\tbtcClient.ReSetSync(info.Headers, esClient)\n\t\t\treturn true\n\t\t}\n\t\tsugar.Warn(strings.Join([]string{\"Query max aggration error:\", err.Error()}, \" \"))\n\t\treturn false\n\t}\n\tDBCurrentHeight = *agg\n\n\theightGap := info.Headers - int32(DBCurrentHeight)\n\tswitch {\n\tcase heightGap > 0:\n\t\tesClient.RollbackAndSync(DBCurrentHeight, int(ROLLBACKHEIGHT), btcClient)\n\tcase heightGap == 0:\n\t\tesBestBlock, err := esClient.QueryEsBlockByHeight(context.TODO(), info.Headers)\n\t\tif err != nil {\n\t\t\tsugar.Fatal(\"Can't query best block in es\")\n\t\t}\n\n\t\tnodeblock, err := btcClient.getBlock(info.Headers)\n\t\tif err != nil {\n\t\t\tsugar.Fatal(\"Can't query block from bitcoind\")\n\t\t}\n\n\t\tif esBestBlock.Hash != nodeblock.Hash {\n\t\t\tesClient.RollbackAndSync(DBCurrentHeight, int(ROLLBACKHEIGHT), btcClient)\n\t\t}\n\tcase heightGap < 0:\n\t\tsugar.Fatal(\"bitcoind best height block less than max block in database , something wrong\")\n\t}\n\treturn true\n}", "func (l *Logger) Sync() error {\n\tif !l.canSafeExec() {\n\t\treturn nil\n\t}\n\n\treturn l.inner.Sync()\n}", "func (l *Logger) Sync() {\n\t_ = l.SugaredLogger.Sync()\n}", "func (oc *Operachain) Sync() {\n\tfor {\n\t\t//requestVersion\n\t\ttime.Sleep(time.Second)\n\n\t\tfor _, node := range oc.KnownAddress {\n\t\t\tif node != oc.MyAddress {\n\t\t\t\tpayload := gobEncode(HeightMsg{oc.KnownHeight, oc.MyAddress})\n\t\t\t\treqeust := append(commandToBytes(\"rstBlocks\"), payload...)\n\t\t\t\toc.sendData(node, reqeust)\n\t\t\t}\n\t\t}\n\t}\n}", "func (w *SegmentWAL) Sync() error {\n\tw.mtx.Lock()\n\tdefer w.mtx.Unlock()\n\n\treturn w.sync()\n}", "func (c *layerCache) Sync() error {\n\tc.sync <- true\n\t<-c.synced\n\treturn nil\n}", "func (ds *RegularStateMachineWrapper) Sync() error {\n\tpanic(\"Sync not suppose to be called on RegularStateMachineWrapper\")\n}", "func (gdb *Gdb) syncRtData() error {\n\tt := time.NewTicker(gdb.rtTimeDuration)\n\tfor {\n\t\tselect {\n\t\tcase <-t.C:\n\t\t\tif err := gdb.rtDb.Sync(); err != nil {\n\t\t\t\tfmt.Println(\"fatal error occurred while synchronizing realTime data:\" + err.Error())\n\t\t\t\ttime.Sleep(time.Minute)\n\t\t\t\tos.Exit(-1)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n}", "func (b *bridge) Sync() error {\n\t// fetch current SP list\n\tspList, err := b.sp.List()\n\tif err != nil {\n\t\treturn err\n\t}\n\tspDns := make([]string, len(spList))\n\tlog.Printf(\"Init: sp list: %+v\", spList)\n\n\t// fetch LDAP list\n\tidpRes, err := b.idp.Search(nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgroup := idpRes.Entries[0]\n\tif group == nil {\n\t\treturn fmt.Errorf(\"LDAP search failed to find group\")\n\t}\n\tmemberDns := group.GetAttributeValues(\"member\")\n\tlog.Printf(\"Init: idp res: %+v\", idpRes)\n\tidpRes.PrettyPrint(2)\n\n\t// update bridge store to reflect what's in the SP\n\tfor _, spUser := range spList {\n\t\tdn, err := b.users.GetDN(spUser.ID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t} else if dn == \"\" {\n\t\t\t// we don't know about this GUID yet\n\t\t\tidpRes, err := b.idp.FetchUID(spUser.UserName)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tidpUser := idpRes[0]\n\t\t\tif idpUser == nil {\n\t\t\t\t// probably should clear this entry from the SP\n\t\t\t}\n\t\t\tb.users.Add(idpUser.DN, spUser)\n\t\t} else if !isMember(memberDns, dn) {\n\t\t\tb.Del(dn)\n\t\t} else {\n\t\t\tspDns = append(spDns, dn)\n\t\t}\n\t}\n\n\t// update the SP with what's in the IdP\n\tfor _, memberDn := range memberDns {\n\t\tguid, err := b.users.GetGUID(memberDn)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t} else if guid == \"\" {\n\t\t\t// if we don't know about this DN already, it's not on the SP\n\t\t\tb.Add(memberDn)\n\t\t} else if !isMember(spDns, memberDn) {\n\t\t\tentry, err := b.idp.Fetch(memberDn)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tuser, err := b.mapEntry(entry)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tb.sp.Add(user)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *Eventer) sync() {\n\tc.syncc <- struct{}{}\n\t<-c.syncDonec\n}", "func (dc *DeploymentController) sync(ctx context.Context, d *apps.Deployment, rsList []*apps.ReplicaSet) error {\n\tnewRS, oldRSs, err := dc.getAllReplicaSetsAndSyncRevision(ctx, d, rsList, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := dc.scale(ctx, d, newRS, oldRSs); err != nil {\n\t\t// If we get an error while trying to scale, the deployment will be requeued\n\t\t// so we can abort this resync\n\t\treturn err\n\t}\n\n\t// Clean up the deployment when it's paused and no rollback is in flight.\n\tif d.Spec.Paused && getRollbackTo(d) == nil {\n\t\tif err := dc.cleanupDeployment(ctx, oldRSs, d); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tallRSs := append(oldRSs, newRS)\n\treturn dc.syncDeploymentStatus(ctx, allRSs, newRS, d)\n}", "func Sync(syncName string) {\n\ts := SyncServiceStatus(syncName)\n\tif s == \"running\" {\n\t\tfmt.Println(syncRunningErr)\n\t\treturn\n\t}\n\n\tfmt.Println()\n\tconsole.Println(\"⚡ Syncing files between your system and the Tokaido environment\", \"\")\n\tutils.StdoutStreamCmdDebug(\"unison\", syncName, \"-watch=false\")\n}", "func (s *DataStore) StartSync(stop <-chan struct{}) {\n\tgo func() {\n\t\tticker := time.NewTicker(1 * time.Minute)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ticker.C:\n\t\t\t\ts.Lock()\n\t\t\t\tif s.dirty {\n\t\t\t\t\tfile, err := os.Create(s.path)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Errorf(\"data not saved. %v\", err)\n\t\t\t\t\t\ts.Unlock()\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\terr = s.Write(file)\n\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Errorf(\"data not saved. %v\", err)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlog.Infoln(\"saved data\")\n\t\t\t\t\t\ts.dirty = false\n\t\t\t\t\t}\n\t\t\t\t\tfile.Close()\n\t\t\t\t}\n\t\t\t\ts.Unlock()\n\t\t\tcase <-stop:\n\t\t\t\tlog.Infoln(\"stopping data sync\")\n\t\t\t\tticker.Stop()\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n}" ]
[ "0.8188382", "0.8057683", "0.7491411", "0.74850833", "0.7468488", "0.73708427", "0.7245399", "0.7215815", "0.7064655", "0.70221335", "0.69176155", "0.6801737", "0.6746114", "0.6639487", "0.6627243", "0.65996397", "0.65704805", "0.6552512", "0.64949656", "0.6485958", "0.6438784", "0.6429561", "0.6420742", "0.6413933", "0.6393879", "0.6393456", "0.6389556", "0.638013", "0.63439476", "0.63356024", "0.632574", "0.6313683", "0.6306848", "0.6301184", "0.62710714", "0.6265231", "0.624086", "0.62175894", "0.6210789", "0.62021405", "0.6191471", "0.6181548", "0.6172484", "0.61563545", "0.61430675", "0.6133596", "0.6133206", "0.6110458", "0.60786736", "0.60708314", "0.6048321", "0.6042032", "0.60239875", "0.60013056", "0.5990975", "0.5985732", "0.59382993", "0.5933089", "0.5928112", "0.5928005", "0.5923416", "0.58982944", "0.5896846", "0.5895748", "0.588497", "0.5883676", "0.5877356", "0.5869204", "0.58660334", "0.58425236", "0.5838918", "0.5825524", "0.5820752", "0.5783516", "0.57694715", "0.576805", "0.5764742", "0.57527333", "0.5747071", "0.5744361", "0.5735702", "0.57289886", "0.572224", "0.5720423", "0.57195973", "0.57181984", "0.5712497", "0.5697282", "0.5693064", "0.5692578", "0.56870764", "0.5673704", "0.5654889", "0.56539875", "0.565", "0.5639872", "0.5632837", "0.56250036", "0.56105953", "0.5607806" ]
0.70090955
10
Dump removes all data from the database
func (db *DB) Dump() { db.Lock() defer db.Unlock() db.store = map[string]*models.Currency{} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *TattooStorage) Dump() {\n\ts.MetadataDB.SaveIndex()\n\ts.ArticleDB.SaveIndex()\n\ts.ArticleHTMLDB.SaveIndex()\n}", "func (db *DB) Dump(fname string) error {\n\tf, err := os.Create(fname)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\t_, err = f.Write(db.All())\n\treturn err\n}", "func (osm *ObjectStoreMapper) Dump(db *types.Database, dst io.Writer) error {\n\tencoded := storage.EncodedDatabase{\n\t\tschemataTableName: db.Schemata,\n\t}\n\tfor name, table := range db.Tables {\n\t\tencodedTable := storage.EncodedTable{}\n\t\tpkCol := table.Primary()\n\t\tfor pk, row := range table.Entries {\n\t\t\t// TODO inconsistent use of entry in types and storage\n\t\t\tencodedEntry := storage.EncodedEntry{}\n\t\t\tfor i, entry := range row {\n\t\t\t\tif i != pkCol {\n\t\t\t\t\tencodedEntry[table.Columns[i]] = entry.Encoded()\n\t\t\t\t}\n\t\t\t}\n\t\t\tencodedTable[pk] = encodedEntry\n\t\t}\n\t\tencoded[name] = encodedTable\n\t}\n\terr := osm.store.Write(dst, encoded)\n\treturn err\n}", "func (c *Cache) Dump() {\n\tvar rr []quandl.Record\n\tvar rfs []ref\n\n\t// dump records\n\terr := c.DB.Find(&rr).Error\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"There are %d records in dbase\\n\", len(rr))\n\tfor i, r := range rr {\n\t\tfmt.Println(r)\n\t\tif i >= 10 {\n\t\t\tfmt.Println(\"... truncated ...\")\n\t\t\tbreak\n\t\t}\n\t}\n\tfmt.Println()\n\n\t// dump refs\n\terr = c.DB.Find(&rfs).Error\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"There are %d refs in dbase\\n\", len(rfs))\n\tfor i, r := range rfs {\n\t\tfmt.Println(r)\n\t\tif i >= 10 {\n\t\t\tfmt.Println(\"... truncated ...\")\n\t\t\tbreak\n\t\t}\n\t}\n\tfmt.Println()\n}", "func (s *server) dump() {\n\t// start connection to redis\n\tclient, err := redis.Dial(\"tcp\", s.redis_host)\n\tif err != nil {\n\t\tlog.Critical(err)\n\t\treturn\n\t}\n\tdefer client.Close()\n\n\t// start connection to mongodb\n\tsess, err := mgo.Dial(s.mongodb_url)\n\tif err != nil {\n\t\tlog.Critical(err)\n\t\treturn\n\t}\n\tdefer sess.Close()\n\t// database is provided in url\n\tdb := sess.DB(\"\")\n\n\t// copy & clean dirty map\n\ts.Lock()\n\tdirty_list := make([]interface{}, 0, len(s.dirty))\n\tfor k := range s.dirty {\n\t\tdirty_list = append(dirty_list, k)\n\t}\n\ts.dirty = make(map[string]bool)\n\ts.Unlock()\n\n\tif len(dirty_list) == 0 { // ignore emtpy dirty list\n\t\tlog.Trace(\"emtpy dirty list\")\n\t\treturn\n\t}\n\n\t// write data in batch\n\tvar sublist []interface{}\n\tfor i := 0; i < len(dirty_list); i += BATCH_SIZE {\n\t\tif (i+1)*BATCH_SIZE > len(dirty_list) { // reach end\n\t\t\tsublist = dirty_list[i*BATCH_SIZE:]\n\t\t} else {\n\t\t\tsublist = dirty_list[i*BATCH_SIZE : (i+1)*BATCH_SIZE]\n\t\t}\n\n\t\t// mget data from redis\n\t\trecords, err := client.Cmd(\"mget\", sublist...).ListBytes()\n\t\tif err != nil {\n\t\t\tlog.Critical(err)\n\t\t\treturn\n\t\t}\n\n\t\t// save to mongodb\n\t\tvar tmp map[string]interface{}\n\t\tfor k, v := range sublist {\n\t\t\terr := bson.Unmarshal(records[k], &tmp)\n\t\t\tif err != nil {\n\t\t\t\tlog.Critical(err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// split key into TABLE NAME and RECORD ID\n\t\t\tstrs := strings.Split(v.(string), \":\")\n\t\t\tif len(strs) != 2 { // log the wrong key\n\t\t\t\tlog.Critical(\"cannot split key\", v)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttblname, id_str := strs[0], strs[1]\n\t\t\t// save data to mongodb\n\t\t\tid, err := strconv.Atoi(id_str)\n\t\t\tif err != nil {\n\t\t\t\tlog.Critical(err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t_, err = db.C(tblname).Upsert(bson.M{\"Id\": id}, tmp)\n\t\t\tif err != nil {\n\t\t\t\tlog.Critical(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\tlog.Info(\"num records saved:\", len(dirty_list))\n\truntime.GC()\n}", "func DumpDB(w io.Writer, db kv.DB) {\n\ttxn := db.NewTxn(false)\n\tdefer txn.Discard()\n\titer := txn.PrefixIterator(nil)\n\tdefer iter.Discard()\n\tcount := 0\n\tfor iter.Seek([]byte{0}); iter.Valid(); iter.Next() {\n\t\tkey := iter.Key()\n\t\tvar value []byte\n\t\terr := iter.Value(func(bs []byte) error {\n\t\t\tvalue = make([]byte, len(bs))\n\t\t\tcopy(value, bs)\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(w, \"%x\\tE: %v\", key, err)\n\t\t\tbreak\n\t\t}\n\t\tfmt.Fprintf(w, \"%x\\t%x\\n\", key, value)\n\t\tcount++\n\t}\n\tfmt.Fprintf(w, \"%v keys\\n\", count)\n}", "func (s *DatabaseService) DatabaseDump(development bool) error {\n\tBUCKETS := []string{\"cards\"}\n\n\tif development {\n\t\tfor i := 0; i < len(BUCKETS); i++ {\n\t\t\tcurrentBucket := BUCKETS[i]\n\n\t\t\tif err := s.DB.View(func(tx *bolt.Tx) error {\n\t\t\t\t// select cards bucket\n\t\t\t\tb := tx.Bucket([]byte(currentBucket))\n\n\t\t\t\tfmt.Printf(\"Bucket: %s\\n\", currentBucket)\n\t\t\t\titems := 0\n\n\t\t\t\tif err := b.ForEach(func(key []byte, val []byte) error {\n\t\t\t\t\titems++\n\n\t\t\t\t\tvar card *golockserver.Card\n\n\t\t\t\t\t// decode card into struct instance\n\t\t\t\t\te := json.Unmarshal(val, card)\n\t\t\t\t\tif e != nil {\n\t\t\t\t\t\treturn e\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Println(card)\n\n\t\t\t\t\tif currentBucket == \"cards\" {\n\t\t\t\t\t\tfmt.Printf(\"Card UID: \")\n\t\t\t\t\t\tcolor.Green(string(key))\n\t\t\t\t\t}\n\n\t\t\t\t\treturn nil\n\t\t\t\t}); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif items == 0 {\n\t\t\t\t\tcolor.Yellow(\"No records found\")\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}); err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tcolor.Red(\"Cannot dump database while server is not running on development mode\")\n\t}\n\n\treturn nil\n}", "func (store KeyValue) Dump() {\n\t// TODO: Dump out debugging information here\n\ttexts := store.database.Stats()\n\tfor key, value := range texts {\n\t\tlog.Debug(\"Stat\", key, value)\n\t}\n\n\titer := store.database.Iterator(nil, nil)\n\tfor ; iter.Valid(); iter.Next() {\n\t\thash := iter.Key()\n\t\tnode := iter.Value()\n\t\tlog.Debug(\"Row\", hash, node)\n\t}\n}", "func (drv *Driver) DumpSchema(db *sql.DB) ([]byte, error) {\n\tpath := ConnectionString(drv.databaseURL)\n\tschema, err := dbutil.RunCommand(\"sqlite3\", path, \".schema --nosys\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmigrations, err := drv.schemaMigrationsDump(db)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tschema = append(schema, migrations...)\n\treturn dbutil.TrimLeadingSQLComments(schema)\n}", "func (s *TattooStorage) DumpComment() {\n\ts.CommentIndexDB.SaveIndex()\n\ts.CommentMetadataDB.SaveIndex()\n\ts.CommentDB.SaveIndex()\n\ts.CommentHTMLDB.SaveIndex()\n}", "func (session KeyValueSession) Dump() {\n\ttexts := session.store.database.Stats()\n\tfor key, value := range texts {\n\t\tlog.Debug(\"Stat\", key, value)\n\t}\n\n\titer := session.store.database.Iterator(nil, nil)\n\tfor ; iter.Valid(); iter.Next() {\n\t\thash := iter.Key()\n\t\tnode := iter.Value()\n\t\tlog.Debug(\"Row\", hash, node)\n\t}\n}", "func dumpDatabase(data *Data) (string, error) {\n\tuserName := data.UserName\n\tpassword := data.Password\n\thostName := data.HostName\n\tport := data.Port\n\tdumpDir := data.DumpDir\n\tnumberOfDatabases := len(data.Databases)\n\n\tfor i := 0; i < numberOfDatabases; i++ {\n\t\tdbName := data.Databases[i].DatabaseName\n\t\tdumpFilenameFormat := fmt.Sprintf(\"%s-backup\", dbName)\n\n\t\t// establish connection to the database\n\t\t// connection format => username:password@tcp(hostname:port)/databaseName\n\t\tconnectionString := fmt.Sprintf(\"%s:%s@tcp(%s:%s)/%s\", userName, password, hostName, port, dbName)\n\t\tdb, err := sql.Open(\"mysql\", connectionString)\n\t\tif err != nil {\n\t\t\t// fmt.Println(\"Error opening database: \", err)\n\t\t\treturn \"error opening database\", err\n\t\t}\n\n\t\t// Register database with mysqldump\n\t\tdumper, err := mysqldump.Register(db, dumpDir, dumpFilenameFormat)\n\t\tif err != nil {\n\t\t\t// fmt.Println(\"Error registering databse:\", err)\n\t\t\treturn \"Error registering databse\", err\n\t\t}\n\n\t\t// Dump database to file\n\t\tresultFilename, err := dumper.Dump()\n\t\tif err != nil {\n\t\t\t// fmt.Println(\"Error dumping:\", err)\n\t\t\treturn \"Error dumping\", err\n\t\t}\n\n\t\tfmt.Printf(\"Database is saved to %s \\n\", resultFilename)\n\n\t\tdumper.Close()\n\t}\n\n\treturn \"Success!\", nil\n}", "func dumpToSQL(filename string, db *sql.DB) error {\n\n\terr := prepareEnv()\n\tif err != nil {\n\n\t\tlog.Fatal(err)\n\t\treturn err\n\t}\n\n\tout, err := exec.Command(\"mdb-tables\", \"-1\", *dir+\"/\"+filename).Output()\n\tif err != nil {\n\t\tlog.Fatalf(\"Can not execute command mdb-tables: %s\", err)\n\t\treturn err\n\t}\n\n\ttables := strings.Split(string(out), \"\\n\")\n\tlog.Printf(\"======== Starting Data Insertion in: %s\", filename)\n\n\tfor _, table := range tables {\n\n\t\tout, err := exec.Command(\"mdb-export\", \"-I\", \"sqlite\", *dir+\"/\"+filename, table).Output()\n\t\tif err != nil {\n\n\t\t\tlog.Fatalf(\"unable to export mdb as Sql queries: %v\", err)\n\t\t\treturn err\n\n\t\t}\n\n\t\tqueries := strings.Split(string(out), \"\\n\")\n\n\t\tfor count, query := range queries {\n\t\t\tif query == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlog.Printf(\"Currently on %s and query number %d\", table, count)\n\n\t\t\t_, err := db.Exec(query)\n\n\t\t\tif err != nil {\n\t\t\t\t// Currently throwing unrecognized token error\n\t\t\t\t//\n\n\t\t\t\tlog.Fatalf(\"Unable to execute query: %v\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n\n}", "func (p *TxPool) Dump() tx.Transactions {\n\treturn p.all.ToTxs()\n}", "func Dump(dbFile string, destination string) error {\n\n\tcmd := exec.Command(\"sqlite3\", dbFile)\n\n\t// Interact with sqlite3 command line tool by sending data to STDIN\n\tstdin, _ := cmd.StdinPipe()\n\tgo func() {\n\t\tdefer stdin.Close()\n\t\tio.WriteString(stdin, \".output \"+destination+\"\\n\")\n\t\tio.WriteString(stdin, \".dump\\n\")\n\t\tio.WriteString(stdin, \".quit\\n\")\n\t}()\n\n\t_, err := cmd.CombinedOutput()\n\n\treturn err\n}", "func (p Postgres) Dump(ctx context.Context, filename string) error {\n\toptions := p.getDumpOptions(filename)\n\tcmd := exec.CommandContext(ctx, pgDump, options...)\n\n\treturn cmd.Run()\n}", "func (dp *Dumper) Dump(dbName string, out *os.File, schemaOnly bool) error {\n\t// pg_dump -d dbName --schema-only\n\tif err := dp.conn.SwitchDatabase(dbName); err != nil {\n\t\treturn err\n\t}\n\n\t// Database statement.\n\tdbStmt := getDatabaseStmt(dbName)\n\tif _, err := out.WriteString(dbStmt); err != nil {\n\t\treturn err\n\t}\n\n\t// Schema statements.\n\tschemas, err := dp.getPgSchemas()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, schema := range schemas {\n\t\tif _, err := out.WriteString(schema.Statement()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Sequence statements.\n\tseqs, err := dp.getSequences()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get sequences from database %q: %s\", dbName, err)\n\t}\n\tfor _, seq := range seqs {\n\t\tif _, err := out.WriteString(seq.Statement()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Table statements.\n\ttables, err := dp.getPgTables()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get tables from database %q: %s\", dbName, err)\n\t}\n\n\tconstraints := make(map[string]bool)\n\tfor _, tbl := range tables {\n\t\tif _, err := out.WriteString(tbl.Statement()); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, constraint := range tbl.constraints {\n\t\t\tkey := fmt.Sprintf(\"%s.%s.%s\", constraint.schemaName, constraint.tableName, constraint.name)\n\t\t\tconstraints[key] = true\n\t\t}\n\t\tif !schemaOnly {\n\t\t\tstmts, err := dp.getTableData(tbl)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfor _, stmt := range stmts {\n\t\t\t\tif _, err := out.WriteString(stmt); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(stmts) > 0 {\n\t\t\t\tif _, err := out.WriteString(\"\\n\"); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// View statements.\n\tviews, err := dp.getViews()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get views from database %q: %s\", dbName, err)\n\t}\n\tfor _, view := range views {\n\t\tif _, err := out.WriteString(view.Statement()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Index statements.\n\tindices, err := dp.getIndices()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get indices from database %q: %s\", dbName, err)\n\t}\n\tfor _, idx := range indices {\n\t\tkey := fmt.Sprintf(\"%s.%s.%s\", idx.schemaName, idx.tableName, idx.name)\n\t\tif constraints[key] {\n\t\t\tcontinue\n\t\t}\n\t\tif _, err := out.WriteString(idx.Statement()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Function statements.\n\tfs, err := dp.getFunctions()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get functions from database %q: %s\", dbName, err)\n\t}\n\tfor _, f := range fs {\n\t\tif _, err := out.WriteString(f.Statement()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Trigger statements.\n\ttriggers, err := dp.getTriggers()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get triggers from database %q: %s\", dbName, err)\n\t}\n\tfor _, tr := range triggers {\n\t\tif _, err := out.WriteString(tr.Statement()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Event statements.\n\tevents, err := dp.getEventTriggers()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get event triggers from database %q: %s\", dbName, err)\n\t}\n\tfor _, evt := range events {\n\t\tif _, err := out.WriteString(evt.Statement()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func DumpDb(gen *Db, out io.Writer) error {\n\tdump := genDump{}\n\n\tvar err error\n\n\tdump.Nodes, err = gen.nodes()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting nodes: %v\", err)\n\t}\n\n\tdump.Edges, err = gen.edges()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting edges: %v\", err)\n\t}\n\n\tdump.Meta = gen.meta\n\n\tencoder := json.NewEncoder(out)\n\tencoder.SetIndent(\"\", \" \")\n\n\terr = encoder.Encode(dump)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error encoding: %v\", err)\n\t}\n\n\treturn nil\n}", "func (d *Dumper) Dump() error {\n\ttables := d.tables\n\tif len(tables) == 0 {\n\t\tvar err error\n\t\ttables, err = d.helper.tableNames(d.db)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfor _, table := range tables {\n\t\tif err := d.dumpTable(table); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (fs *FileSystem) DumpSQL() (err error) {\n\tfs.Lock()\n\tdefer fs.Unlock()\n\tvar dumpFile *os.File\n\tdumpFile, err = os.Create(fs.name + \".sql\")\n\tif err != nil {\n\t\treturn\n\t}\n\terr = sqlite3dump.Dump(fs.name, dumpFile)\n\tdumpFile.Close()\n\treturn\n}", "func (o *IgmpFlowTbl) dumpAll() {\n\n\tvar it core.DListIterHead\n\tcnt := 0\n\tfor it.Init(&o.head); it.IsCont(); it.Next() {\n\t\te := covertToIgmpEntry(it.Val())\n\t\tfmt.Printf(\" %v:%v \\n\", cnt, e.Ipv4)\n\t\tcnt++\n\t}\n}", "func cleanDB(t *testing.T, driver *cmneo4j.Driver) {\n\tqs := make([]*cmneo4j.Query, len(allUUIDs))\n\tfor i, uuid := range allUUIDs {\n\t\tqs[i] = &cmneo4j.Query{\n\t\t\tCypher: `MATCH (a:Thing{uuid:$uuid})\n\t\t\tOPTIONAL MATCH (a)-[:EQUIVALENT_TO]-(t:Thing)\n\t\t\tDETACH DELETE t, a`,\n\t\t\tParams: map[string]interface{}{\n\t\t\t\t\"uuid\": uuid,\n\t\t\t},\n\t\t}\n\t}\n\terr := driver.Write(qs...)\n\tassert.NoError(t, err)\n}", "func (m *Migrator) DumpMigrationSchema(ctx context.Context) error {\n\tc := m.Connection.WithContext(ctx)\n\tschema := \"schema.sql\"\n\tf, err := os.Create(schema) //#nosec:G304) //#nosec:G304\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = c.Dialect.DumpSchema(f)\n\tif err != nil {\n\t\t_ = os.RemoveAll(schema)\n\t\treturn err\n\t}\n\treturn nil\n}", "func DumpSnapshotData(snapshot Snapshot, blockNumber *big.Int) {\n\t//AddColumnWork\n\tinsertStatement := \"INSERT INTO snapshot_data VALUES ($1, $2, $3, $4, $5, $6, $7)\" //AddColumnWork\n\n\tfor address := range snapshot {\n\t\tsnapshotRow := snapshot[address]\n\t\t_, err := connection.DBCLIENT.Exec(insertStatement,\n\t\t\tblockNumber.String(),\n\t\t\taddress,\n\t\t\tsnapshotRow.SkaleTokenBalance.String(),\n\t\t\tsnapshotRow.SkaleTokenLockedBalance.String(),\n\t\t\tsnapshotRow.SkaleTokenDelegatedBalance.String(),\n\t\t\tsnapshotRow.SkaleTokenSlashedBalance.String(),\n\t\t\tsnapshotRow.SkaleTokenRewards.String())\n\t\t//AddColumnWork //Order Matters\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Could not write snapshot to database: %s\\n\", err)\n\t\t}\n\n\t}\n}", "func DumpAll(c *gin.Context) {\n\tc.JSON(200, models.All)\n}", "func (drv ClickHouseDriver) DumpSchema(u *url.URL, db *sql.DB) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tvar err error\n\n\terr = clickhouseSchemaDump(db, &buf, drv.databaseName(u))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = clickhouseSchemaMigrationsDump(db, &buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func (parser *MarpaParser) DumpTable() {\n\tfmt.Println(parser.table)\n}", "func DumpDB(db *sql.DB, out io.Writer) (err error) {\n\ts3d := new(sqlite3dumper)\n\treturn s3d.dumpDB(db, out)\n}", "func (s *cayleyStore) Dump(filter string) string {\n\treturn s.dumpQuads(nil)\n}", "func Dump(dbName string, out io.Writer) (err error) {\n\ts3d := new(sqlite3dumper)\n\treturn s3d.dump(dbName, out)\n}", "func (a SQLDB) DBdump(d Database, tmpdir string) (string, error) {\n\tif dbname == \"\" {\n\t\tdbname = \"-A\"\n\t}\n\ttstamp := time.Now().UTC().Format(time.RFC3339)\n\tobjname := tmpdir + \"/\" + \"CBQD_DB_\" + dbname + tstamp + \".sql\"\n\tgpgname := tmpdir + \"/\" + \"CBQD_DB_\" + dbname + tstamp + \".gpg\"\n\terr := os.Chdir(tmpdir)\n\tif err != nil {\n\t\treturn \"\", BACKUP_FOLDER_ERROR\n\t}\n\tlog.Info(\"initiate database data dump process....\")\n\tif err = exec.Command(MakeCommandString(d), \" > \", objname).Run(); err != nil {\n\t\t_, errm := exec.LookPath(\"mysqldump\")\n\t\tif errm != nil {\n\t\t\treturn \"\", DB_DUMP_ERROR_EXEC\n\t\t}\n\t\treturn \"\", DB_DUMP_ERROR\n\t}\n\tlog.Info(\"database dump complete......begin data encryption process.\")\n\n\terr0 := EncryptDBdump(objname, gpgname)\n\tif err0 == nil {\n\t\tlog.Info(\"data encryption complete\")\n\t} else {\n\t\tlog.Info(\"data encryption could not be completed.\")\n\t}\n\treturn gpgname, err0\n}", "func (x MySQL) Dump() *ExportResult {\n\tresult := &ExportResult{MIME: \"application/sql\"}\n\n\tresult.Path = fmt.Sprintf(`%v_%v.sql`, time.Now().Format(\"2006-01-02\"), time.Now().Unix())\n\n\toptions := append(x.dumpOptions(), fmt.Sprintf(`-r%v`, result.Path))\n\n\t_, err := exec.Command(MysqlDumpCmd, options...).Output()\n\tif err != nil {\n\t\terr = fmt.Errorf(\"failed execute mysqldump command: %v\", err)\n\t\tresult.Error = err\n\t}\n\n\treturn result\n}", "func DumpDatabase(dbfile, to string) (nTables, nViews int, err error) {\n\tdb, err := OpenDb(dbfile, stor.Read, false)\n\tck(err)\n\tdefer db.Close()\n\treturn Dump(db, to)\n}", "func (s *Store) Dump(verbose bool) workloadmeta.WorkloadDumpResponse {\n\tpanic(\"not implemented\")\n}", "func (f *Forest) dump(t *testing.T) {\n\tt.Logf(\"---------------- TRIE BEGIN ------------------\")\n\tchildNodes := make(map[string]*Node, len(f.nodes))\n\tfor _, n := range f.nodes {\n\t\tfor _, childHash := range n.branches {\n\t\t\tif len(childHash) != 0 {\n\t\t\t\tchildNodes[childHash.KeyForMap()] = f.nodes[childHash.KeyForMap()]\n\t\t\t}\n\t\t}\n\t}\n\n\tfor nodeHash := range f.nodes {\n\t\tif _, isChild := childNodes[nodeHash]; !isChild {\n\t\t\tf.nodes[nodeHash].printNode(\" Ω\", 0, f, t)\n\t\t}\n\t}\n\tt.Logf(\"---------------- TRIE END --------------------\")\n}", "func (a *Authorizer) Dump() interface{} {\n\n\troleList := []role{}\n\tif err := a.db.All(&roleList); err != nil {\n\t\treturn \"\"\n\t}\n\n\t// List binding\n\trolebindings := []rolebinding{}\n\tif err := a.db.All(&rolebindings); err != nil {\n\t\treturn \"\"\n\t}\n\n\t// List permissions\n\tpermissions := []permission{}\n\tif err := a.db.All(&permissions); err != nil {\n\t\treturn \"\"\n\t}\n\n\tdata := struct {\n\t\tRoles []role\n\t\tBindings []rolebinding\n\t\tPermissions []permission\n\t}{\n\t\troleList,\n\t\trolebindings,\n\t\tpermissions,\n\t}\n\n\tif len(roleList) == 0 && len(rolebindings) == 0 && len(permissions) == 0 {\n\t\treturn nil\n\t}\n\n\treturn data\n\n}", "func (ColourSketchStore *ColourSketchStore) Dump(path string) error {\n\tb, err := msgpack.Marshal(ColourSketchStore)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(path, b, 0644)\n}", "func (t *Tree) Dump() {\n\tt.Root.Dump(0, \"\")\n}", "func (d *Dumper) DumpDDLs(ctx context.Context) error {\n\tdbPath := fmt.Sprintf(\"projects/%s/instances/%s/databases/%s\", d.project, d.instance, d.database)\n\tresp, err := d.adminClient.GetDatabaseDdl(ctx, &adminpb.GetDatabaseDdlRequest{\n\t\tDatabase: dbPath,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, ddl := range resp.Statements {\n\t\tif len(d.tables) > 0 && !d.tables[parseTableNameFromDDL(ddl)] {\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Fprintf(d.out, \"%s;\\n\", ddl)\n\t}\n\n\treturn nil\n}", "func (r *Row) Dump() []byte {\n\tif r.Data != nil {\n\t\treturn r.Data\n\t}\n\n\tdata := make([]byte, 0, r.dataLength())\n\tif r.isBinary {\n\t\tdata = append(data, OK_HEADER)\n\t\tdata = append(data, r.nullBitmap...)\n\t}\n\tfor _, fv := range r.fieldValuesCache {\n\t\tdata = append(data, fv...)\n\t}\n\tr.Data = data\n\treturn data\n}", "func (kvStore *KVStore) DumpStore() []KVPair {\n els := make([]KVPair, len(kvStore.mapping))\n\n i := 0\n for k, v := range kvStore.mapping {\n els[i] = KVPair{k, *v}\n i++\n }\n\n return els\n}", "func (l *Ledger) Dump() ([][]string, error) {\n\tl.mutex.RLock()\n\tdefer l.mutex.RUnlock()\n\tit := l.baseDB.NewIteratorWithPrefix([]byte(pb.BlocksTablePrefix))\n\tdefer it.Release()\n\tblocks := make([][]string, l.meta.TrunkHeight+1)\n\tfor it.Next() {\n\t\tblock := &pb.InternalBlock{}\n\t\tparserErr := proto.Unmarshal(it.Value(), block)\n\t\tif parserErr != nil {\n\t\t\treturn nil, parserErr\n\t\t}\n\t\theight := block.Height\n\t\tblockid := fmt.Sprintf(\"{ID:%x,TxCount:%d,InTrunk:%v, Tm:%d, Miner:%s}\", block.Blockid, block.TxCount, block.InTrunk, block.Timestamp/1000000000, block.Proposer)\n\t\tblocks[height] = append(blocks[height], blockid)\n\t}\n\treturn blocks, nil\n}", "func Dump(nodes *map[string]storage.Node) {\n\tt := time.Now()\n\tf, _ := os.Create(strings.Join([]string{\"persister/data/dump_\", getTimeStr(t), \".log\"}, \"\"))\n\tdefer f.Close()\n\tfor k, v := range *nodes {\n\t\tf.WriteString(\"key: \" + k + \" \" + v.String() + \"\\n\")\n\t}\n\n}", "func (c *Client) Dump(ctx context.Context, dbname string) ([]File, error) {\n\trequest := protocol.Message{}\n\trequest.Init(16)\n\tresponse := protocol.Message{}\n\tresponse.Init(512)\n\n\tprotocol.EncodeDump(&request, dbname)\n\n\tif err := c.protocol.Call(ctx, &request, &response); err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to send dump request\")\n\t}\n\n\tfiles, err := protocol.DecodeFiles(&response)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to parse files response\")\n\t}\n\tdefer files.Close()\n\n\tdump := make([]File, 0)\n\n\tfor {\n\t\tname, data := files.Next()\n\t\tif name == \"\" {\n\t\t\tbreak\n\t\t}\n\t\tdump = append(dump, File{Name: name, Data: data})\n\t}\n\n\treturn dump, nil\n}", "func DumpMigration(db *sql.DB, out io.Writer) (err error) {\n\ts3d := new(sqlite3dumper)\n\ts3d.migration = true\n\treturn s3d.dumpDB(db, out)\n}", "func Dump(root, keyfile, outfile string) {\n\tpswd := getUserPswd()\n\tk := hashPswd(pswd)\n\n\tf, err := os.OpenFile(outfile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)\n\tif err != nil {\n\t\tFatalError(err, \"could not open outfile\")\n\t}\n\tdefer f.Close()\n\n\twritePswdStore(root, root, keyfile, f)\n\n\tencryptFile(k[:], outfile)\n}", "func (s *Stack) Dump() {\n\tn := s.top\n\tfmt.Print(\"[ \")\n\tfor i := 0; i < s.count; i++ {\n\t\tfmt.Printf(\"%+v \", n.data)\n\t\tn = n.next\n\t}\n\tfmt.Print(\"]\")\n}", "func (self *LSHforest) Dump(path string) error {\n\tif len(self.hashTables[0]) != 0 {\n\t\treturn fmt.Errorf(\"cannot dump the LSH Forest after running the indexing method\")\n\t}\n\tb, err := msgpack.Marshal(self)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(path, b, 0644)\n}", "func DumpTable(dbfile, table, to string) (nrecs int, err error) {\n\tdb, err := OpenDb(dbfile, stor.Read, false)\n\tck(err)\n\tdefer db.Close()\n\treturn DumpDbTable(db, table, to)\n}", "func SchemaDump(dbName string, outputFile string, opt Options) (string, error) {\n\tif err := opt.isValid(dbName); err != nil {\n\t\treturn \"\", err\n\t}\n\tif opt.DBPort == 0 {\n\t\topt.DBPort = 5432\n\t}\n\n\tcmd := fmt.Sprintf(\"PGPASSWORD=%s pg_dump -h %s -p %d -U %s %s --schema-only\",\n\t\topt.DBPassword, opt.DBHost, opt.DBPort, opt.DBUser, dbName)\n\n\tout, err := run(cmd, opt)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tp := script.Echo(out).\n\t\tReject(`ALTER DEFAULT PRIVILEGES`).\n\t\tReject(`OWNER TO`).\n\t\tRejectRegexp(regexp.MustCompile(`^--`)).\n\t\tRejectRegexp(regexp.MustCompile(`^REVOKE`)).\n\t\tRejectRegexp(regexp.MustCompile(`^COMMENT ON`)).\n\t\tRejectRegexp(regexp.MustCompile(`^SET`)).\n\t\tRejectRegexp(regexp.MustCompile(`^GRANT`)).Exec(\"cat -s\")\n\n\tn := p.ExitStatus()\n\tif n > 0 {\n\t\tp.SetError(nil)\n\t\tout, _ := p.String()\n\t\treturn \"\", fmt.Errorf(\"raw error: %s\", out)\n\t}\n\n\tdump, err := p.String()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif outputFile != \"\" {\n\t\tf, err := os.OpenFile(outputFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif _, err := f.WriteString(dump); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\treturn dump, nil\n}", "func (rfs *RootFileSystem) Dump() {\n\trfs.BlockHandler.DumpInfo()\n}", "func (q *SubmitQueue) Dump() {\n\tfor i, item := range q.items {\n\t\tfmt.Printf(\"[%2d] %s:%d %s\\n\", i, item.Repo, item.PRNumber, item.Sha1)\n\t}\n}", "func sqlBackup() {\n\tgodrv.Register(\"SET NAMES utf8\")\n\tdb, err := sql.Open(\"mysql\", fmt.Sprintf(\"%s:%s@tcp(%s:%s)/%s\", username, password, hostname, port, dbname))\n\tif err != nil {\n\t\tfmt.Println(\"Error opening database: \", err)\n\t\treturn\n\t}\n\n\tdefer db.Close()\n\n\trows, err := db.Query(\"Show databases;\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar name string\n\t\terr := rows.Scan(&name)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tif !contains(ingoreSqlTableList, name) {\n\t\t\tlog.Println(\"*******************\")\n\t\t\tlog.Println(name + \" is backuping\")\n\t\t\tdumpFilenameFormat := fmt.Sprintf(\"%s-20060102150405\", name)\n\t\t\tdumper, err := mysqldump.Register(db, backupSqlDir, dumpFilenameFormat)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Error registering databse:\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tresultFilename, err := dumper.Dump()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Error dumping:\", err)\n\t\t\t}\n\t\t\tlog.Println(name + \" is backuped\")\n\t\t\tlog.Printf(\"File is saved to %s \\n\", resultFilename)\n\t\t\tlog.Println(\"*******************\")\n\n\t\t\tdumper.Close()\n\t\t}\n\n\t}\n}", "func (root *TreeNode) dump() (res []interface{}) {\n\tif root == nil {\n\t\treturn res\n\t}\n\tif root.left != nil {\n\t\ttmp := root.left.dump()\n\t\tres = append(res, tmp...)\n\t}\n\tres = append(res, root.Values...)\n\tif root.right != nil {\n\t\ttmp := root.right.dump()\n\t\tres = append(res, tmp...)\n\t}\n\treturn res\n}", "func DumpSystemSnapshotData(ss SystemSnapshot, blockNumber *big.Int) error {\n\n\tinsertStatement := \"INSERT INTO system_snapshot_data VALUES ($1, $2)\" //AddSystemColumnWork\n\n\t_, err := connection.DBCLIENT.Exec(insertStatement,\n\t\tblockNumber.String(),\n\t\tss.SkaleTokenSupply.String())\n\t//AddSystemColumnWork\n\t//Order Matters\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n\n}", "func DumpDatabase(db *sql.DB) func(*Dumper) error {\n\treturn func(d *Dumper) error {\n\t\td.db = db\n\t\treturn nil\n\t}\n}", "func FlushAllSnapshots() {\n\n\t_, err := connection.DBCLIENT.Exec(\"TRUNCATE TABLE snapshot_data\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n}", "func dbFetchDump(w http.ResponseWriter, r *http.Request) {\n\tid := makeGuidString(r.URL.Query().Get(\"id\"))\n\tc := appengine.NewContext(r)\n\tclient, err := newCloudClient(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer client.Close()\n\tbucket := client.Bucket(gcsBucket)\n\n\tfileReader, err := bucket.Object(gcsFilename(kindToBlobType(minidumpKind), id)).NewReader(c)\n\tif err != nil {\n\t\tlog.Errorf(c, \"Unable to read minidump %v/%v: %v\", gcsBucket, gcsFilename(kindToBlobType(minidumpKind), id), err)\n\t\tpanic(err)\n\t}\n\tdefer fileReader.Close()\n\n\tw.Header().Set(\"Content-Disposition\", fmt.Sprintf(\"attachment; filename=\\\"minidump-%v.mdmp\\\"\", id))\n\tw.WriteHeader(http.StatusOK)\n\tio.Copy(w, fileReader)\n}", "func dumpBinlog(dbPath string, bw *blog.BinlogWriter) error {\n\tlog.Debug(\"dbPath \", dbPath)\n\tdb, err := leveldb.OpenFile(dbPath, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer db.Close()\n\n\t// 分三次读取 文件否则会有大量的table map event重复\n\thi, hd, hu := have(db)\n\n\tif hi {\n\t\tif err := dumpData(db, bw, WriteRowsEvent); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif hd {\n\t\tif err := dumpData(db, bw, DeleteRowsEvent); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif hu {\n\t\tif err := dumpData(db, bw, UpdateRowsEvent); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func wipeDB(db *sql.DB, dataType string) (err error) {\n\ttable, err := whatTable(dataType)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t_, err = db.Exec(\"DROP TABLE IF EXISTS \" + table)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"erro ao apagar tabela\")\n\t}\n\n\treturn\n}", "func (s *sequencer) dump() {\n\tif logrus.GetLevel() != logrus.TraceLevel {\n\t\treturn\n\t}\n\n\ts.lock.RLock()\n\tdefer s.lock.RUnlock()\n\n\tfor height := range s.blockPool {\n\t\tblk, err := s.get(height)\n\t\tif err == nil {\n\t\t\tlog.WithField(\"hash\", hex.EncodeToString(blk.Header.Hash)).\n\t\t\t\tWithField(\"height\", blk.Header.Height).\n\t\t\t\tTrace(\"sequencer item\")\n\t\t}\n\t}\n}", "func (p *Pes) Dump() {\n\n}", "func (s *Stash) Flush() error {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\tjsonData, err := json.Marshal(s.data)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to marshal data\")\n\t}\n\n\tcontainer := container{Version: s.version, Data: jsonData}\n\tjsonFileData, err := json.Marshal(container)\n\n\terr = ioutil.WriteFile(s.file, jsonFileData, 0600)\n\treturn errors.WithMessage(err, fmt.Sprintf(\"failed to write database to '%s'\", s.file))\n}", "func (s IntegrationSuite) TestDumperPull(t *testing.T) {\n\ts.setupDirAndDB(t, \"basic\")\n\topts := Options{\n\t\tIncludeAutoInc: true,\n\t\tCountOnly: true,\n\t}\n\tif len(s.statementErrors) != 1 {\n\t\tt.Fatalf(\"Expected one StatementError from test setup; found %d\", len(s.statementErrors))\n\t}\n\topts.IgnoreKeys([]tengo.ObjectKey{s.statementErrors[0].ObjectKey()})\n\n\t// In the fs, rename users table and its file. Expectation is that\n\t// DumpSchema will undo this action.\n\tcontents := fs.ReadTestFile(t, s.testdata(\".scratch\", \"users.sql\"))\n\tcontents = strings.Replace(contents, \"create table users\", \"CREATE table widgets\", 1)\n\tfs.WriteTestFile(t, s.testdata(\".scratch\", \"widgets.sql\"), contents)\n\tfs.RemoveTestFile(t, s.testdata(\".scratch\", \"users.sql\"))\n\ts.reparseScratchDir(t)\n\n\tcount, err := DumpSchema(s.schema, s.scratchDir, opts)\n\texpected := 5 // no reformat needed for fine.sql or invalid.sql, but do for other 4 files, + 1 extra from above manipulations\n\tif count != expected || err != nil {\n\t\tt.Errorf(\"Expected DumpSchema() to return (%d, nil); instead found (%d, %v)\", expected, count, err)\n\t}\n\n\t// Since above run enabled opts.CountOnly, repeated run with it disabled\n\t// should return the same count, and another run after that should return 0 count\n\topts.CountOnly = false\n\tcount, err = DumpSchema(s.schema, s.scratchDir, opts)\n\tif count != expected || err != nil {\n\t\tt.Errorf(\"Expected DumpSchema() to return (%d, nil); instead found (%d, %v)\", expected, count, err)\n\t}\n\ts.reparseScratchDir(t)\n\tcount, err = DumpSchema(s.schema, s.scratchDir, opts)\n\tif expected = 0; count != expected || err != nil {\n\t\tt.Errorf(\"Expected DumpSchema() to return (%d, nil); instead found (%d, %v)\", expected, count, err)\n\t}\n\ts.verifyDumperResult(t, \"basic\")\n}", "func (o UserInfo) DumpToLocal(url string, engine *gorm.DB, mode int) error {\n\ttableName := o.TableName()\n\n\ttran := engine.Begin()\n\tif e := tran.Exec(fmt.Sprintf(\"delete from %s\", tableName)).Error; e != nil {\n\t\ttran.Rollback()\n\t\treturn errorx.Wrap(e)\n\t}\n\n\ttype Result struct {\n\t\tData []UserInfo `json:\"data\"`\n\t\tCount int `json:\"count\"`\n\t}\n\tvar result Result\n\tresp, e := http.Get(url)\n\tif e != nil {\n\t\ttran.Rollback()\n\t\treturn errorx.Wrap(e)\n\t}\n\tif resp == nil || resp.Body == nil {\n\t\ttran.Rollback()\n\t\treturn errorx.NewFromString(\"resp or body nil\")\n\t}\n\tdefer resp.Body.Close()\n\n\tbuf, e := ioutil.ReadAll(resp.Body)\n\tif e != nil {\n\t\ttran.Rollback()\n\t\treturn errorx.Wrap(e)\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\tvar body string\n\t\tif len(buf) < 100 {\n\t\t\tbody = string(buf)\n\t\t} else {\n\t\t\tbody = string(buf[:100])\n\t\t}\n\t\treturn errorx.NewFromStringf(\"status not 200, got %d,body %s\", resp.StatusCode, body)\n\t}\n\n\tif e := json.Unmarshal(buf, &result); e != nil {\n\t\ttran.Rollback()\n\t\treturn errorx.Wrap(e)\n\t}\n\n\tfor i, _ := range result.Data {\n\t\tdata := result.Data[i]\n\t\tif e := tran.Model(&o).Create(&data).Error; e != nil {\n\t\t\ttran.Rollback()\n\t\t\treturn errorx.Wrap(e)\n\t\t}\n\t}\n\ttran.Commit()\n\treturn nil\n}", "func (db *CsvDB) DropAll() error {\r\n\tfor _, g := range db.Groups {\r\n\t\tif err := g.Drop(); err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\t}\r\n\treturn nil\r\n}", "func clearTable() {\n\ta.DB.Exec(\"DELETE FROM snippets\")\n\ta.DB.Exec(\"DELETE FROM users\")\n}", "func (w *WaysMapping) Dump(filePath string, withCSVHeader bool) error {\n\n\tstartTime := time.Now()\n\n\tf, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0755)\n\tdefer f.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Sync()\n\tglog.V(1).Infof(\"open %s succeed.\\n\", filePath)\n\n\twriter := csv.NewWriter(f)\n\tdefer writer.Flush()\n\tif withCSVHeader {\n\t\tif err := writer.Write(strings.Split(outputCSVHeader, \",\")); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvar count int\n\tfor k, v := range *w {\n\t\tif err := writer.Write(formatToWaysMappingRecord(k, v)); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcount++\n\t}\n\n\tglog.Infof(\"Dumped ways mapping to %s, csv header: %t, total count: %d, takes %f seconds\", filePath, withCSVHeader, count, time.Now().Sub(startTime).Seconds())\n\treturn nil\n}", "func (w *ResticWrapper) DumpOnce(dumpOptions DumpOptions) ([]byte, error) {\n\tklog.Infoln(\"Dumping backed up data\")\n\n\targs := []interface{}{\"dump\", \"--quiet\"}\n\tif dumpOptions.Snapshot != \"\" {\n\t\targs = append(args, dumpOptions.Snapshot)\n\t} else {\n\t\targs = append(args, \"latest\")\n\t}\n\tif dumpOptions.FileName != \"\" {\n\t\targs = append(args, dumpOptions.FileName)\n\t} else {\n\t\targs = append(args, \"stdin\")\n\t}\n\tif dumpOptions.Host != \"\" {\n\t\targs = append(args, \"--host\")\n\t\targs = append(args, dumpOptions.SourceHost)\n\t}\n\tif dumpOptions.Path != \"\" {\n\t\targs = append(args, \"--path\")\n\t\targs = append(args, dumpOptions.Path)\n\t}\n\n\targs = w.appendCacheDirFlag(args)\n\targs = w.appendCaCertFlag(args)\n\targs = w.appendMaxConnectionsFlag(args)\n\n\t// first add restic command, then add StdoutPipeCommands\n\tcommands := []Command{\n\t\t{Name: ResticCMD, Args: args},\n\t}\n\tcommands = append(commands, dumpOptions.StdoutPipeCommands...)\n\treturn w.run(commands...)\n}", "func (db *MemoryStorage) Flush() error {\n\treturn nil\n}", "func (d *Dumper) DumpTables(ctx context.Context) error {\n\ttxn := d.client.ReadOnlyTransaction()\n\tif d.timestamp != nil {\n\t\ttxn = txn.WithTimestampBound(spanner.ReadTimestamp(*d.timestamp))\n\t}\n\tdefer txn.Close()\n\n\titer, err := FetchTables(ctx, txn)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn iter.Do(func(t *Table) error {\n\t\tif len(d.tables) > 0 && !d.tables[t.Name] {\n\t\t\treturn nil\n\t\t}\n\t\treturn d.dumpTable(ctx, t, txn)\n\t})\n}", "func (t *Tree) Dump() (res []interface{}) {\n\tif t == nil {\n\t\treturn\n\t}\n\n\tt.lock.RLock()\n\tdefer t.lock.RUnlock()\n\treturn t.root.dump()\n}", "func (me *TCmd) Dump() string {\n\tvar b strings.Builder\n\tme.DumpTo(&b)\n\treturn b.String()\n}", "func cleanDatabase(db *gorm.DB) error {\n\tif err := db.Migrator().DropTable(&model.Report{}); err != nil {\n\t\treturn errors.Wrap(err, \"drop user table failed\")\n\t}\n\tif err := db.Migrator().DropTable(&model.ReportMessage{}); err != nil {\n\t\treturn errors.Wrap(err, \"drop policy table failed\")\n\t}\n\n\treturn nil\n}", "func (l *Log) DumpLog() {\n\tfor _, v := range l.Entries {\n\t\tfmt.Println(v)\n\t}\n}", "func (f *FileUpload) Dump(root string) (err error) {\n\t// Return error if cannot dump file\n\tif err = f.Validate(); err != nil {\n\t\treturn\n\t}\n\n\tdirpath := filepath.Join(root, f.GUID, f.EventHash)\n\n\t// Create directory if doesn't exist\n\tif !fsutil.IsDir(dirpath) {\n\t\tif err = os.MkdirAll(dirpath, utils.DefaultPerms); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn f.write(root)\n}", "func Reset(d *db.DB) {\n\td.Lock(func(tx db.Execer, _ db.Binder) error {\n\t\ttx.Exec(\"DELETE FROM cron\")\n\t\ttx.Exec(\"DELETE FROM logs\")\n\t\ttx.Exec(\"DELETE FROM steps\")\n\t\ttx.Exec(\"DELETE FROM stages\")\n\t\ttx.Exec(\"DELETE FROM latest\")\n\t\ttx.Exec(\"DELETE FROM builds\")\n\t\ttx.Exec(\"DELETE FROM perms\")\n\t\ttx.Exec(\"DELETE FROM repos\")\n\t\ttx.Exec(\"DELETE FROM users\")\n\t\ttx.Exec(\"DELETE FROM orgsecrets\")\n\t\treturn nil\n\t})\n}", "func dumpLoad(refGene string, db *sql.DB) {\n\t/*\n\t\treaderName := \"r\" + strconv.Itoa(rand.Int())\n\t\tmysql.RegisterReaderHandler(readerName,\n\t\t\tfunc() io.Reader {\n\t\t\t\treturn bytes.NewBufferString(refGene)\n\t\t\t})\n\t\tdefer mysql.DeregisterReaderHandler(readerName)\n\t\tcmd := \"LOAD DATA LOCAL INFILE 'Reader::\" + readerName + \"' \" +\n\t\t\t\"IGNORE INTO TABLE chr \"\n\t\t_, err := db.Exec(cmd)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}*/\n}", "func (c *BlockWriterCase) TearDown(db *sql.DB) error {\n\treturn nil\n}", "func (a *App) Clean(dbName string) {\n\tsession := a.Session.Copy()\n\tdefer session.Close()\n\n\terr := a.Session.DB(dbName).DropDatabase()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t// fmt.Printf(\"the database %v has been cleaned\\n\", dbName)\n}", "func (c *Controller) WipeOutDatabase(drmn *api.DormantDatabase) error {\n\tref, rerr := reference.GetReference(clientsetscheme.Scheme, drmn)\n\tif rerr != nil {\n\t\treturn rerr\n\t}\n\n\tif err := c.wipeOutDatabase(drmn.ObjectMeta, drmn.GetDatabaseSecrets(), ref); err != nil {\n\t\treturn errors.Wrap(err, \"error in wiping out database.\")\n\t}\n\n\t// wipe out wall data from backend\n\tif err := c.wipeOutWalData(drmn.ObjectMeta, drmn.Spec.Origin.Spec.Postgres); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (q *UniqueQueue) Dump() string {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\n\td := &dump{\n\t\tClosed: q.doneChanClosed,\n\t\tHead: q.head,\n\t\tTail: q.tail,\n\t\tMaxDepth: q.maxDepth,\n\t\tQueue: make([]string, 0, len(q.queue)),\n\t\tQueuedSet: make(map[string]interface{}, len(q.queuedSet)),\n\t}\n\n\tfor _, entry := range q.queue {\n\t\td.Queue = append(d.Queue, entry.key)\n\t}\n\tfor _, entry := range q.queuedSet {\n\t\td.QueuedSet[entry.key] = entry.val\n\t}\n\n\tout, err := jsonMarshalDumpHook(d)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn string(out)\n}", "func genMysqlTestdata(t *testing.T, dump func()) {\n\tdb, err := gosql.Open(\"mysql\", \"root@/\"+mysqlTestDB)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer db.Close()\n\n\tdropTables := `DROP TABLE IF EXISTS everything, third, second, simple CASCADE`\n\tif _, err := db.Exec(dropTables); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tfor _, schema := range []string{\n\t\t`CREATE TABLE simple (i INT PRIMARY KEY AUTO_INCREMENT, s text, b binary(200))`,\n\t\t`CREATE TABLE SECOND (\n\t\t\ti INT PRIMARY KEY,\n\t\t\tk INT,\n\t\t\tFOREIGN KEY (k) REFERENCES simple (i) ON UPDATE CASCADE,\n\t\t\tUNIQUE KEY ik (i, k),\n\t\t\tKEY ki (k, i)\n\t\t)`,\n\t\t`CREATE TABLE third (\n\t\t\ti INT PRIMARY KEY AUTO_INCREMENT,\n\t\t\ta INT, b INT, C INT,\n\t\t\tFOREIGN KEY (a, b) REFERENCES second (i, k) ON DELETE RESTRICT ON UPDATE RESTRICT,\n\t\t\tFOREIGN KEY (c) REFERENCES third (i) ON UPDATE CASCADE\n\t\t)`,\n\t\t`CREATE TABLE everything (\n\t\t\t\ti INT PRIMARY KEY,\n\n\t\t\t\tc CHAR(10) NOT NULL,\n\t\t\t\ts VARCHAR(100) DEFAULT 'this is s\\'s default value',\n\t\t\t\ttx TEXT,\n\t\t\t\te ENUM('Small', 'Medium', 'Large'),\n\n\t\t\t\tbin BINARY(100) NOT NULL,\n\t\t\t\tvbin VARBINARY(100),\n\t\t\t\tbl BLOB,\n\n\t\t\t\tdt DATETIME NOT NULL DEFAULT '2000-01-01 00:00:00',\n\t\t\t\td DATE,\n\t\t\t\tts TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n\t\t\t\tt TIME,\n\t\t\t\t-- TODO(dt): fix parser: for YEAR's length option\n\t\t\t\t-- y YEAR,\n\n\t\t\t\tde DECIMAL,\n\t\t\t\tnu NUMERIC,\n\t\t\t\td53 DECIMAL(5,3),\n\n\t\t\t\tiw INT(5) NOT NULL,\n\t\t\t\tiz INT ZEROFILL,\n\t\t\t\tti TINYINT DEFAULT 5,\n\t\t\t\tsi SMALLINT,\n\t\t\t\tmi MEDIUMINT,\n\t\t\t\tbi BIGINT,\n\n\t\t\t\tfl FLOAT NOT NULL,\n\t\t\t\trl REAL,\n\t\t\t\tdb DOUBLE,\n\n\t\t\t\tf17 FLOAT(17),\n\t\t\t\tf47 FLOAT(47),\n\t\t\t\tf75 FLOAT(7, 5),\n\t\t\t\tj JSON\n\t\t)`,\n\t} {\n\t\tif _, err := db.Exec(schema); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\n\tfor _, tc := range simpleTestRows {\n\t\ts := &tc.s\n\t\tif *s == injectNull {\n\t\t\ts = nil\n\t\t}\n\t\tif _, err := db.Exec(\n\t\t\t`INSERT INTO simple (s, b) VALUES (?, ?)`, s, tc.b,\n\t\t); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\tfor i := 1; i <= secondTableRows; i++ {\n\t\tif _, err := db.Exec(`INSERT INTO second VALUES (?, ?)`, -i, i); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\n\tfor _, r := range everythingTestRows {\n\t\tif _, err := db.Exec(\n\t\t\t`INSERT INTO everything (\n\t\t\ti, e, c, bin, dt, iz, iw, fl, d53, j\n\t\t) VALUES (\n\t\t\t?, ?, ?, ?, ?, ?, ?, ?, ?, ?\n\t\t)`, r.i, r.e, r.c, r.bin, r.dt, r.iz, r.iw, r.fl, r.d53, r.j); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\n\tdump()\n\n\tif _, err := db.Exec(dropTables); err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func (rbm *RBM) Dump(filename string) error {\n\trbm.PersistentVisibleUnits = nil\n\treturn nnet.DumpAsJson(filename, rbm)\n}", "func (dt *dumpTable) prepareDumpFiles() {\n\n\tif dt.dataLength < dt.d.cfg.FileTargetSize {\n\t\tdf, _ := NewDumpFileSummary(dt, 0, 0) // small table\n\t\tdt.d.dumpFileQueue = append(dt.d.dumpFileQueue, df)\n\t} else {\n\t\tfor i := dt.min; i < dt.max; i += dt.rowsPerFile {\n\t\t\tstart := i\n\t\t\tend := i + dt.rowsPerFile - 1\n\n\t\t\tif i == dt.min {\n\t\t\t\tstart = 0\n\t\t\t}\n\n\t\t\tif end > dt.max {\n\t\t\t\tend = 0\n\t\t\t}\n\n\t\t\tdf, _ := NewDumpFileSummary(dt, start, end)\n\t\t\tdt.d.dumpFileQueue = append(dt.d.dumpFileQueue, df)\n\t\t}\n\t}\n}", "func (sc *Scavenger) Dump() string {\n\tsc.mu.Lock()\n\tdefer sc.mu.Unlock()\n\n\tvar sb strings.Builder\n\tfor _, e := range sc.entries {\n\t\t_, _ = fmt.Fprintf(&sb, \"%s\\t%s\\n\", e.Level, e.Message)\n\t}\n\treturn sb.String()\n}", "func convertDBtoSQL(fileName string) {\n\tdb, err := LoadDBFile(fileName)\n\tif err != nil {\n panic(err)\n }\n defer db.Close()\n\t\n\ttailHeight := lastBlockHeight(db)\n\tdata := convert(db, tailHeight)\n\n\t//fmt.Println(data)\n\n\t// //create new file and write data in the file\n\tfile, err := os.Create(\"dappleyweb.sql\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer file.Close()\n\n\t_, err = file.Write([]byte(data))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (e *Engine) filterDump() {\n\tfConf := conf.GlobalSharedConfig.Filter\n\tif e.filter != nil && fConf.Dump && fConf.DumpPath != \"\" && strings.ToLower(fConf.Name) == \"local\" {\n\t\te.filter.(*filter.LocalFilter).Dump(fConf.DumpPath)\n\t}\n}", "func Dump(ds interface{}, name string, spec *Spec) error {\n\n\tbuf := &bytes.Buffer{}\n\tMap(buf, ds, spec)\n\n\terr := ioutil.WriteFile(path+\"/\"+name+\".dot\", buf.Bytes(), 0644)\n\treturn err\n\n}", "func (d *Decoder) Dump(out io.Writer, indent int) {\n\n\tfmt.Fprintf(out, \"%sCollada version:%s\\n\", sIndent(indent), d.dom.Version)\n\td.dom.Asset.Dump(out, indent+step)\n\td.dom.LibraryAnimations.Dump(out, indent+step)\n\td.dom.LibraryImages.Dump(out, indent+step)\n\td.dom.LibraryLights.Dump(out, indent+step)\n\td.dom.LibraryEffects.Dump(out, indent+step)\n\td.dom.LibraryMaterials.Dump(out, indent+step)\n\td.dom.LibraryGeometries.Dump(out, indent+step)\n\td.dom.LibraryVisualScenes.Dump(out, indent+step)\n\td.dom.Scene.Dump(out, indent+step)\n}", "func (m *Map) Dump() (map[string]interface{}, error) {\n\tvalues := make(map[string]interface{})\n\tfor name, key := range m.schema {\n\t\tvalue, err := m.GetRaw(name)\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithStack(err)\n\t\t}\n\t\tif value != key.Default {\n\t\t\tif key.Hidden {\n\t\t\t\tvalues[name] = true\n\t\t\t} else {\n\t\t\t\tvalues[name] = value\n\t\t\t}\n\t\t}\n\t}\n\treturn values, nil\n}", "func (l *Logstash) Dump() {\n\tfmt.Println(\"Hostname: \", l.Hostname)\n\tfmt.Println(\"Port: \", l.Port)\n\tfmt.Println(\"Connection: \", l.Connection)\n\tfmt.Println(\"Timeout: \", l.Timeout)\n}", "func (w *Wallet) ClearDatabase() error {\n\treturn w.db.Clear()\n}", "func CleanUp(dbName string) error {\n\tsession := connect()\n\tvar err error\n\terr = dropTable(opts{session: session, db: dbName, table: \"posts\"})\n\terr = dropTable(opts{session: session, db: dbName, table: \"addresses\"})\n\terr = dropTable(opts{session: session, db: dbName, table: \"users\"})\n\terr = dropTable(opts{session: session, db: dbName, table: \"feeds\"})\n\terr = dropTable(opts{session: session, db: dbName, table: \"feedAddresses\"})\n\terr = dropDB(opts{session: session, db: dbName})\n\tsession.Close()\n\treturn err\n}", "func (config *Config) DumpToEnv() error {\n\tif err := os.Setenv(\"PGUSER\", config.Username); err != nil {\n\t\treturn err\n\t}\n\tif err := os.Setenv(\"PGPASSWORD\", config.Password); err != nil {\n\t\treturn err\n\t}\n\tif err := os.Setenv(\"PGDATABASE\", config.Database); err != nil {\n\t\treturn err\n\t}\n\tif err := os.Setenv(\"PGHOST\", config.Host); err != nil {\n\t\treturn err\n\t}\n\tif err := os.Setenv(\"PGPORT\", fmt.Sprint(config.Port)); err != nil {\n\t\treturn err\n\t}\n\tif err := os.Setenv(\"PGSSLMODE\", config.SslMode); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (entry *Entry) Dump() ([]byte, error) {\n\tentryBytes := make([]byte, 32+64+32+32+entry.KeySize+entry.ValueSize)\n\tbinary.BigEndian.PutUint64(entryBytes[32:], entry.Timestamp)\n\tbinary.BigEndian.PutUint32(entryBytes[96:], entry.KeySize)\n\tbinary.BigEndian.PutUint32(entryBytes[128:], entry.ValueSize)\n\tcopy(entryBytes[160:], entry.Key)\n\tcopy(entryBytes[160+entry.KeySize:], entry.Value)\n\tentry.Checksum = crc32.ChecksumIEEE(entryBytes[32:])\n\tbinary.BigEndian.PutUint32(entryBytes, entry.Checksum)\n\treturn entryBytes, nil\n}", "func (c *lru) Dump() []engines.Entry {\n\tvar result []engines.Entry\n\tel := c.list.Front()\n\tfor el != nil {\n\t\tentry := el.Value.(engines.Entry)\n\t\tresult = append(result, entry)\n\t\tel = el.Next()\n\t}\n\treturn result\n}", "func DumpDatabase(archivePath string, instance InstanceConfig) (feedback DumpFeedback) {\n dbFileName := fmt.Sprintf(\"%s.db\", instance.Name)\n db, err := sql.Open(\"sqlite3\", dbFileName)\n if err != nil {\n logger.Fatal(err)\n }\n defer db.Close()\n\n stopU:=false\n stopS:=false\n chU := make(chan int)\n chS := make(chan int)\n\n go func() {\n count := DumpUsers(db, archivePath, instance)\n chU<-count\n }()\n\n go func() {\n count := DumpSales(db, archivePath, instance)\n chS<-count\n }()\n\n // wait for success messages from jobs\n for {\n select {\n case countU := <-chU:\n feedback.UsersCount = countU\n stopU = true\n case countS := <-chS:\n feedback.SalesCount = countS\n stopS = true\n }\n if stopU && stopS {\n break\n }\n }\n return\n}", "func (data *Invasion) Dump() {\n spew.Dump(data)\n}", "func (db *FileDB) reset() (err error) {\n\tdb.LockAll()\n\tdefer db.UnlockAll()\n\tif err = os.Remove(db.file); err != nil {\n\t\treturn\n\t}\n\n\t// delete all content files\n\tRemoveDirContents(config.rootPath + \"/static/content/\")\n\tRemoveDirContents(db.dir + \"/temp/\")\n\n\t// reinitialise DB\n\tdb.Published.Files = make(map[string]File)\n\tdb.Uploaded.Files = make(map[string]File)\n\tdb.FileTransactions.Transactions = make([]Transaction, 0, 0)\n\n\tInfo.Log(\"DB has been reset.\")\n\treturn nil\n}" ]
[ "0.72003263", "0.7108479", "0.69024754", "0.64917547", "0.63886833", "0.6344799", "0.6297192", "0.6221337", "0.60932505", "0.60779434", "0.60567117", "0.6032595", "0.59557277", "0.59433293", "0.59412926", "0.5938543", "0.59370035", "0.593607", "0.59191054", "0.5911541", "0.5886597", "0.587446", "0.58533883", "0.5843669", "0.58125764", "0.58053315", "0.5797314", "0.5762722", "0.5699695", "0.568674", "0.5667916", "0.5631442", "0.559434", "0.5591265", "0.5584169", "0.55824953", "0.55500215", "0.55180955", "0.55133605", "0.5510672", "0.55100113", "0.5507845", "0.54963666", "0.5492364", "0.549183", "0.5464455", "0.5458538", "0.54495066", "0.54440266", "0.543739", "0.54240525", "0.538968", "0.53766835", "0.5374707", "0.5369997", "0.5369077", "0.53637046", "0.53627884", "0.53360957", "0.5324407", "0.53233814", "0.5320543", "0.53082913", "0.5307185", "0.530672", "0.52964693", "0.5290076", "0.52722734", "0.5264405", "0.52216285", "0.521989", "0.52159476", "0.521206", "0.5209546", "0.52070177", "0.5194942", "0.5190999", "0.51692104", "0.5164325", "0.51593184", "0.5151719", "0.51501167", "0.5144519", "0.5142216", "0.5140134", "0.5134895", "0.51318616", "0.5122382", "0.5120538", "0.5097169", "0.50926095", "0.50675845", "0.50551623", "0.5054998", "0.50542235", "0.505222", "0.5050211", "0.50372297", "0.5036247", "0.5026174" ]
0.6751204
3
Insert is used to inject new data into the in memory db
func (db *DB) Insert(c *models.Currency) { db.Lock() defer db.Unlock() db.store[c.ID] = c }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *DBMem) Insert(data Person) {\n m.Lock()\n defer m.Unlock()\n\n\tid := len(m.data)\n m.data[id] = data\n m.history.Append(\"INSERT\", id, data)\n}", "func Insert(db gorp.SqlExecutor, i interface{}) error {\n\treturn Mapper.Insert(db, i)\n}", "func (d *Database) Insert(db DB, table string, src interface{}) error {\n\treturn d.InsertContext(context.Background(), db, table, src)\n}", "func Insert(db DB, table string, src interface{}) error {\n\treturn InsertContext(context.Background(), db, table, src)\n}", "func (s *DbRecorder) Insert() error {\n\tswitch s.flavor {\n\tcase \"postgres\":\n\t\treturn s.insertPg()\n\tdefault:\n\t\treturn s.insertStd()\n\t}\n}", "func (d Database) Insert(key string, value string) error {\n\tif d.connection == nil {\n\t\treturn errors.New(\"connection not initialized\")\n\t}\n\t_, err := d.connection.Set(d.ctx, key, value, 0).Result()\n\treturn err\n}", "func (m MariaDB) Insert(ctx context.Context, document entity.PersonalData) (entity.PersonalData, error) {\n\tp := receive(document)\n\tsqlQuery := \"INSERT INTO person (id, name, last_name, phone, email, year_od_birth ) VALUES (?,?,?,?,?,?)\"\n\t_, err := m.Person.ExecContext(ctx, sqlQuery, p.ID, p.Name, p.LastName, p.Phone, p.Email, p.YearOfBirth)\n\tif err != nil {\n\t\treturn entity.PersonalData{}, errors.Wrap(err, \"could not exec query statement\")\n\t}\n\treturn document, nil\n}", "func (q *Queue) insert(entities interface{}, mutex *sync.Mutex) *gorm.DB {\n\tmutex.Lock()\n\tres := q.db.Clauses(clause.OnConflict{DoNothing: true}).Create(entities)\n\tmutex.Unlock()\n\n\treturn res\n}", "func ExampleInsert() {\n\tuser := q.T(\"user\")\n\tins := q.Insert().Into(user).Set(user.C(\"name\"), \"hackme\")\n\tfmt.Println(ins)\n\t// Output:\n\t// INSERT INTO \"user\"(\"name\") VALUES (?) [hackme]\n}", "func Insert(stmt bolt.Stmt, data interface{}) error {\n\n\tm := structs.Map(data)\n\n\tflag := false\n\tfor _, v := range m {\n\t\tif reflect.ValueOf(v).Kind() == reflect.Map {\n\t\t\tflag = true\n\t\t}\n\t}\n\tif flag {\n\t\tm = flatMap(m, \"\")\n\t}\n\n\t// Parses data struct to a map before sending it to ExeNeo()\n\tresult, err := stmt.ExecNeo(m)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnumResult, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"CREATED ROWS: %d\\n\", numResult)\n\treturn nil\n}", "func (db *DB) Insert(table string, data ...map[string]interface{}) (int64, error) {\n\treturn db.doExec(\"INSERT\", table, data...)\n}", "func Insert(db DB, table string, src interface{}) error {\n\treturn Default.Insert(db, table, src)\n}", "func (w *Wrapper) Insert(data interface{}) (err error) {\n\tw.query = w.buildInsert(\"INSERT\", data)\n\tres, err := w.executeQuery()\n\tif err != nil || !w.executable {\n\t\treturn\n\t}\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn\n\t}\n\tw.LastInsertID = int(id)\n\treturn\n}", "func insert(res http.ResponseWriter, req *http.Request) {\n\tstmt, err := db.Prepare(`INSERT INTO customer VALUES (\"james\");`)\n\tcheck(err)\n\tdefer stmt.Close()\n\tr, err := stmt.Exec()\n\tcheck(err)\n\tn, err := r.RowsAffected()\n\tcheck(err)\n\n\tfmt.Fprintln(res, \"INSERTED RECORD\", n)\n}", "func (db *DB) Insert(model ...interface{}) error {\n\treturn db.inner.Insert(model...)\n}", "func insert(nums int) {\n\ttimeStart := util.Microsecond()\n\tfor i := 0; i < nums; i++ {\n\t\tkey := []byte(\"key_\" + strconv.Itoa(i)) // 10 bytes\n\t\tvalue := []byte(\"value_\" + strconv.Itoa(i)) //12 bytes\n\t\tbDB.Update(func(tx *bolt.Tx) error {\n\t\t\tb := tx.Bucket([]byte(\"copernicus\"))\n\t\t\terr := b.Put(key, value)\n\t\t\treturn err\n\t\t})\n\t}\n\tfmt.Println(\"insert time is :\", util.Microsecond()-timeStart)\n}", "func (db *queueDatabase) insert(m *persistence.QueueMessage) {\n\tm.Envelope = cloneEnvelope(m.Envelope)\n\tm.Revision++\n\n\t// Add the new message to the queue.\n\tif db.messages == nil {\n\t\tdb.messages = map[string]*persistence.QueueMessage{}\n\t}\n\tdb.messages[m.ID()] = m\n\n\tdb.addToOrderIndex(m)\n\tdb.addToTimeoutIndex(m)\n}", "func (data *SimpleDbType) Insert(dbMgr *mgr.DBConn) error {\n\tdb := dbMgr.Open()\n\n\tsqlStatement := `INSERT INTO test_table (\"name\", \"number\") VALUES ($1, $2) RETURNING id`\n\tid := 0\n\terr := db.QueryRow(sqlStatement, data.Name, data.Number).Scan(&id)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(\"New record ID is:\", id)\n\tdbMgr.Close()\n\treturn err\n}", "func InsertIntoDb(data []interface{}, dataType interface{}, tableName string, db *sql.DB) error {\n\n\t_, err := db.Exec(InsertQuery(tableName, dataType), data...)\n\tif err != nil {\n\t\t//fmt.Println(err)\n\t\treturn err\n\t}\n\treturn nil\n\n}", "func (d *Database) Insert(db DB, table string, src interface{}) error {\n\tpkName, pkValue, err := d.PrimaryKey(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif pkName != \"\" && pkValue != 0 {\n\t\treturn fmt.Errorf(\"meddler.Insert: primary key must be zero\")\n\t}\n\n\t// gather the query parts\n\tnamesPart, err := d.ColumnsQuoted(src, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvaluesPart, err := d.PlaceholdersString(src, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvalues, err := d.Values(src, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// run the query\n\tq := fmt.Sprintf(\"INSERT INTO %s (%s) VALUES (%s)\", d.quoted(table), namesPart, valuesPart)\n\tif d.UseReturningToGetID && pkName != \"\" {\n\t\tq += \" RETURNING \" + d.quoted(pkName)\n\t\tvar newPk int64\n\t\terr := db.QueryRow(q, values...).Scan(&newPk)\n\t\tif err != nil {\n\t\t\treturn &dbErr{msg: \"meddler.Insert: DB error in QueryRow\", err: err}\n\t\t}\n\t\tif err = d.SetPrimaryKey(src, newPk); err != nil {\n\t\t\treturn fmt.Errorf(\"meddler.Insert: Error saving updated pk: %v\", err)\n\t\t}\n\t} else if pkName != \"\" {\n\t\tresult, err := db.Exec(q, values...)\n\t\tif err != nil {\n\t\t\treturn &dbErr{msg: \"meddler.Insert: DB error in Exec\", err: err}\n\t\t}\n\n\t\t// save the new primary key\n\t\tnewPk, err := result.LastInsertId()\n\t\tif err != nil {\n\t\t\treturn &dbErr{msg: \"meddler.Insert: DB error getting new primary key value\", err: err}\n\t\t}\n\t\tif err = d.SetPrimaryKey(src, newPk); err != nil {\n\t\t\treturn fmt.Errorf(\"meddler.Insert: Error saving updated pk: %v\", err)\n\t\t}\n\t} else {\n\t\t// no primary key, so no need to lookup new value\n\t\t_, err := db.Exec(q, values...)\n\t\tif err != nil {\n\t\t\treturn &dbErr{msg: \"meddler.Insert: DB error in Exec\", err: err}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (d *dbBase) Insert(ctx context.Context, q dbQuerier, mi *modelInfo, ind reflect.Value, tz *time.Location) (int64, error) {\n\tnames := make([]string, 0, len(mi.fields.dbcols))\n\tvalues, autoFields, err := d.collectValues(mi, ind, mi.fields.dbcols, false, true, &names, tz)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tid, err := d.InsertValue(ctx, q, mi, false, names, values)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif len(autoFields) > 0 {\n\t\terr = d.ins.setval(ctx, q, mi, autoFields)\n\t}\n\treturn id, err\n}", "func Insert(key []byte, value []byte) error {\n\tif db == nil {\n\t\treturn errors.New(\"database not initialized\")\n\t}\n\n\tif len(key) == 0 {\n\t\treturn errors.New(\"empty key provided\")\n\t}\n\n\treturn db.Put(key, value, nil)\n}", "func (r *TaskRepository) Insert(db db.DB, Task *entities.Task) error {\n\t_, err := db.NamedExec(`\n\tINSERT INTO tasks (uuid,title,user_id,status,created_at,updated_at)\n\tVALUES (:uuid, :title, :user_id, :status, now(), now())`, Task)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error inserting task to db: %w\", err)\n\t}\n\n\treturn nil\n}", "func Insert(session *mgo.Session, dbName string, collectionName string, query interface{}) error {\n\n\tc := openCollection(session, dbName, collectionName)\n\terr := c.Insert(query)\n\treturn err\n}", "func (Model) Insert(model interface{}) {\n\tdb.Insert(model)\n}", "func (db *DB) Insert(form url.Values, dataFields interface{}) *ResponseMessage {\n\n\t//bucketName := \"master_erp\"\n\t//docID := \"12121\"\n\tbytes := db.ProcessData(form, dataFields)\n\t//db.ProcessData(form, intrfc)\n\t//json.Unmarshal(bytes, intrfc) //***s\n\n\t//fmt.Println(\"DATA>>>>\", intrfc)\n\t//bytes, _ := json.Marshal(intrfc)\n\t//fmt.Println(\"intrfcBytes:\", string(bytes))\n\n\tdocID := form.Get(\"aid\") //docid=aid\n\tbucketName := form.Get(\"bucket\")\n\n\t//json.Unmarshal(bytes, intrfc)\n\tinsertQuery := insertQueryBuilder(bucketName, docID, string(bytes))\n\t//insertQuery := insertQueryBuilder(bucketName, docID, intrfc)\n\n\t//fmt.Println(insertQuery)\n\tnqlInsertStatement := sqlStatementJSON(insertQuery)\n\t//fmt.Println()\n\t//fmt.Println(nqlInsertStatement, form)\n\n\tresponseMessage := db.queryRequest(nqlInsertStatement)\n\t//fmt.Println(responseMessage.Status)\n\tif responseMessage.Status != \"success\" {\n\t\tfmt.Println(nqlInsertStatement)\n\t}\n\n\treturn responseMessage\n}", "func (r *Entity) Insert() (result sql.Result, err error) {\n\treturn Model.Data(r).Insert()\n}", "func (r *Entity) Insert() (result sql.Result, err error) {\n\treturn Model.Data(r).Insert()\n}", "func (r *Entity) Insert() (result sql.Result, err error) {\n\treturn Model.Data(r).Insert()\n}", "func (r *Entity) Insert() (result sql.Result, err error) {\n\treturn Model.Data(r).Insert()\n}", "func (r *Entity) Insert() (result sql.Result, err error) {\n\treturn Model.Data(r).Insert()\n}", "func (r *Entity) Insert() (result sql.Result, err error) {\n\treturn Model.Data(r).Insert()\n}", "func (m *MySQL) Insert(p *packet.Packet, interval time.Duration, t time.Time) {\n\t_, err := m.stmt.Exec(p.Interface, p.Bytes, p.SrcName, p.DstName, p.Hostname, p.Proto, p.SrcPort, p.DstPort, int(interval.Seconds()), t)\n\tif err != nil {\n\t\tlog.Println(\"sql err:\", err)\n\t\tlog.Println(\"Time:\", t.Unix())\n\t\tspew.Dump(p)\n\t}\n}", "func Insert(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tif r.Body == nil {\n\t\thttp.Error(w, http.StatusText(400), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tstnds, err := insertDB(r)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tsjson, err := json.Marshal(stnds)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusCreated) // 201\n\tfmt.Fprintf(w, \"%s\\n\", sjson)\n}", "func (db *DB) Insert(key interface{}, value interface{}) error {\n\treturn db.bolt.Update(func(tx *bolt.Tx) error {\n\t\treturn db.InsertTx(tx, key, value)\n\t})\n}", "func (t *Transaction) Insert(list ...interface{}) error {\n\treturn insert(t.dbmap, t, list...)\n}", "func (d *Dosen) Insert(db *sql.DB) error {\n\tif d.ID == \"\" {\n\t\treturn fmt.Errorf(\"id tidak bolehh kosong\")\n\t}\n\tquery := \"INSERT INTO dosen Values($1, $2)\"\n\t_, err := db.Exec(query, &d.ID, &d.NamaDosen)\n\treturn err\n}", "func (p *Personal) Insert(ctx context.Context, document *PersonalData) (interface{}, error) {\n\ti, err := p.DB.Insert(ctx, document)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not insert personal data\")\n\t}\n\treturn i, nil\n}", "func (s *InstanceBindData) Insert(ibd *internal.InstanceBindData) error {\n\tif ibd == nil {\n\t\treturn errors.New(\"entity may not be nil\")\n\t}\n\n\tif ibd.InstanceID.IsZero() {\n\t\treturn errors.New(\"instance id must be set\")\n\t}\n\n\topKey := s.key(ibd.InstanceID)\n\n\trespGet, err := s.kv.Get(context.TODO(), opKey)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"while calling database on get\")\n\t}\n\tif respGet.Count > 0 {\n\t\treturn alreadyExistsError{}\n\t}\n\n\tdso, err := s.encodeDMToDSO(ibd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := s.kv.Put(context.TODO(), opKey, dso); err != nil {\n\t\treturn errors.Wrap(err, \"while calling database on put\")\n\t}\n\n\treturn nil\n}", "func (p *ProviderDAO) Insert(provider models.Provider) error {\n\terr := db.C(COLLECTION).Insert(&provider)\n\treturn err\n}", "func (o *<%= classedName %>) Insert() error {\n\tif _, err := orm.NewOrm().Insert(o); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (dt *Data) Insert(datum *pb.Datum, config *pb.InsertConfig) error {\n\tif dt.Config != nil && !dt.Config.NoTarget && dt.N >= dt.Config.TargetN {\n\t\treturn errors.New(\"Number of elements is over the target\")\n\t}\n\tvar ttlDuration *time.Duration\n\tif config != nil && config.GetTTL() > 0 {\n\t\t// log.Printf(\"Insert Datum with ttl config: %v\\n\", config.GetTTL())\n\t\td := time.Duration(config.GetTTL()) * time.Second\n\t\tttlDuration = &d\n\t}\n\tkeyByte, err := GetKeyAsBytes(datum)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvalueByte, err := GetValueAsBytes(datum)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = dt.DB.Update(func(txn *badger.Txn) error {\n\t\tif ttlDuration != nil {\n\t\t\t// log.Printf(\"Insert Datum with ttl: %v\\n\", ttlDuration)\n\t\t\te := badger.NewEntry(keyByte, valueByte).WithTTL(*ttlDuration)\n\t\t\treturn txn.SetEntry(e)\n\t\t}\n\t\t// log.Printf(\"Insert Datum: %v ttl: %v\\n\", datum, ttlDuration)\n\t\treturn txn.Set(keyByte, valueByte)\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tdt.Dirty = true\n\tif config == nil {\n\t\tconfig = &pb.InsertConfig{\n\t\t\tTTL: 0,\n\t\t\tCount: 0,\n\t\t}\n\t}\n\tcounter := uint32(1)\n\tif dt.Config.EnforceReplicationOnInsert && config.Count == 0 {\n\t\tconfig.Count++\n\t\t// log.Printf(\"Sending Insert with config.Count: %v ttl: %v\\n\", config.Count, config.TTL)\n\t\tdt.RunOnRandomSources(func(source DataSource) error {\n\t\t\terr := source.Insert(datum, config)\n\t\t\tif err != nil && !strings.Contains(err.Error(), \"Number of elements is over the target\") { // This error occurs frequently and it is normal\n\t\t\t\tlog.Printf(\"Sending Insert error %v\\n\", err.Error())\n\t\t\t}\n\t\t\tif err == nil {\n\t\t\t\tcounter++\n\t\t\t}\n\t\t\tif counter >= dt.Config.ReplicationOnInsert {\n\t\t\t\treturn errors.New(\"Replication number reached\")\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif counter < dt.Config.ReplicationOnInsert {\n\t\t\treturn errors.New(\"Replicas is less then Replication Config\")\n\t\t}\n\t}\n\treturn nil\n}", "func (so *SQLOrderItemStore) Insert(oi *model.OrderItem) (*model.OrderItem, error) {\n\toi.OrderItemID = uuid.NewV4().String()\n\toi.CreatedAt = time.Now().UnixNano()\n\toi.UpdatedAt = oi.CreatedAt\n\terr := so.SQLStore.Tx.Insert(oi)\n\treturn oi, err\n}", "func (b *PgTxRepository) Insert(ctx context.Context, data interface{}, lastInsertedID interface{}) error {\n\tcolumns, values := b.ExtractColumnPairs(data)\n\n\t// Prepare query\n\tqueryBuilder := sq.\n\t\tInsert(b.table).\n\t\tColumns(columns...).\n\t\tValues(values...).\n\t\tSuffix(\"returning \\\"id\\\"\").\n\t\tPlaceholderFormat(sq.Dollar)\n\n\t// Build SQL Query\n\tquery, args, err := queryBuilder.ToSql()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to build query: %w\", err)\n\t}\n\n\t// The statements prepared for a transaction by calling the transaction's Prepare or Stmt methods\n\t// are closed by the call to Commit or Rollback.\n\tstmt, err := b.tx.PreparexContext(ctx, query)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Do the insert query\n\tif lastInsertedID != nil {\n\t\t// We do QueryRowxContext because Postgres doesn't work with lastInsertedID\n\t\terr = stmt.QueryRowxContext(ctx, args...).Scan(lastInsertedID)\n\t} else {\n\t\t// Here we don't need the lastInsertedID\n\t\t_, err = stmt.ExecContext(ctx, args...)\n\t}\n\n\treturn err\n}", "func (s *Session) Insert(dest interface{}) (int64, error) {\n\ts.initStatemnt()\n\ts.statement.Insert()\n\tscanner, err := NewScanner(dest)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer scanner.Close()\n\tif s.statement.table == \"\" {\n\t\ts.statement.From(scanner.GetTableName())\n\t}\n\tinsertFields := make([]string, 0)\n\tfor n, f := range scanner.Model.Fields {\n\t\tif !f.IsReadOnly {\n\t\t\tinsertFields = append(insertFields, n)\n\t\t}\n\t}\n\ts.Columns(insertFields...)\n\tif scanner.entityPointer.Kind() == reflect.Slice {\n\t\tfor i := 0; i < scanner.entityPointer.Len(); i++ {\n\t\t\tval := make([]interface{}, 0)\n\t\t\tsub := scanner.entityPointer.Index(i)\n\t\t\tif sub.Kind() == reflect.Ptr {\n\t\t\t\tsubElem := sub.Elem()\n\t\t\t\tfor _, fn := range insertFields {\n\t\t\t\t\tf, ok := scanner.Model.Fields[fn]\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tfv := subElem.Field(f.idx)\n\t\t\t\t\tval = append(val, fv.Interface())\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tfor _, fn := range insertFields {\n\t\t\t\t\tf, ok := scanner.Model.Fields[fn]\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tfv := sub.Field(f.idx)\n\t\t\t\t\tval = append(val, fv.Interface())\n\t\t\t\t}\n\t\t\t}\n\t\t\ts.statement.Values(val)\n\t\t}\n\n\t} else if scanner.entityPointer.Kind() == reflect.Struct {\n\t\tval := make([]interface{}, 0)\n\t\tfor _, fn := range insertFields {\n\t\t\tf, ok := scanner.Model.Fields[fn]\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfv := scanner.entityPointer.Field(f.idx)\n\t\t\tval = append(val, fv.Interface())\n\t\t}\n\t\ts.statement.Values(val)\n\t} else {\n\t\treturn 0, InsertExpectSliceOrStruct\n\t}\n\tsql, args, err := s.statement.ToSQL()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ts.logger.Debugf(\"[Session Insert] sql: %s, args: %v\", sql, args)\n\ts.initCtx()\n\tsResult, err := s.ExecContext(s.ctx, sql, args...)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn sResult.RowsAffected()\n}", "func (c Client) Insert(entity interface{}, ptrResult interface{}) error {\n\treturn c.InsertInto(entity, ptrResult, reflect.TypeOf(entity).Name())\n}", "func (pg *PGStorage) Insert(a *Address) error {\n\tvar err error\n\terr = pg.con.QueryRow(`\n\t\tINSERT INTO address(hash, income, outcome, ballance)\n\t\tvalues($1, $2, $3, $4)\n\t\tRETURNING ID`,\n\t\ta.Hash,\n\t\ta.Income,\n\t\ta.Outcome,\n\t\ta.Ballance).Scan(\n\t\t&a.ID)\n\treturn err\n}", "func (c *Conn) Insert(ctx context.Context, i Item) (err error) {\n\t_, err = c.db.Exec(ctx, \"INSERT INTO jobs (url) VALUES ($1)\", i.URL)\n\treturn\n}", "func (m *SnippetModel) Insert(title, content, expires string) (int, error) {\n\t// Start a transaction\n\t// Each action that is done is atomic in nature:\n\t// All statements are executed successfully or no statement is executed\n\ttx, err := m.DB.Begin()\n\tif err != nil {\n\t\treturn 0, nil\n\t}\n\n\t// Statement to insert data to the database\n\tstmt := `INSERT INTO snippets (title, content, created, expires)\n\tVALUES(?, ?, UTC_TIMESTAMP(), DATE_ADD(UTC_TIMESTAMP(), INTERVAL ? DAY))`\n\t// Pass in the placeholder parameters aka the ? in the stmt\n\tresult, err := tx.Exec(stmt, title, content, expires)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn 0, err\n\t}\n\t// Return the id of the inserted record in the snippets table\n\tid, err := result.LastInsertId()\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn 0, err\n\t}\n\n\t// id is an int64 to convert it to a int\n\terr = tx.Commit()\n\treturn int(id), err\n\n}", "func (b *Build) Insert() error {\n\treturn db.Insert(Collection, b)\n}", "func Insert(s Session, dbname string, collection string, object interface{}) error {\n\treturn s.DB(dbname).C(collection).Insert(object)\n}", "func (a *adapter) insert(e cloudevents.Event, ctx context.Context) error {\n\tipd := &InsertPayload{}\n\tif err := e.DataAs(ipd); err != nil {\n\t\treturn err\n\t}\n\tcol := a.defaultCollection\n\tdb := a.defaultDatabase\n\n\t// override default collection and database if specified in the event\n\tif ipd.Collection != \"\" {\n\t\tcol = ipd.Collection\n\t}\n\tif ipd.Database != \"\" {\n\t\tdb = ipd.Database\n\t}\n\n\tcollection := a.mclient.Database(db).Collection(col)\n\tif ipd.Document != nil {\n\t\t_, err := collection.InsertOne(ctx, ipd.Document)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"no data to insert\")\n}", "func Insert(r *http.Request, col *tiedot.Col) (id int, err error) {\n\tdata := map[string]interface{}{}\n\tdecoder := json.NewDecoder(r.Body)\n\tdecoder.Decode(&data)\n\n\tid, err = col.Insert(data)\n\treturn\n}", "func (m *SnippetModel) Insert(title, content, expires string) (int, error) {\n\t// Create the SQL statement we want to execute. It's split over several lines\n\t// for readability - so it's surrounded by backquotes instead of normal double quotes\n\tstmt := `INSERT INTO snippets (title, content, created, expires)\n\tvalues (?, ?, UTC_TIMESTAMP(), DATE_ADD(UTC_TIMESTAMP, INTERVAL ? DAY))`\n\n\t// Use the Exec() method on the embedded connection pool to execute the statement.\n\t// The first parameter is the SQL statement followed by the table fields.\n\t// The method returns a sql.Result object which contains some basic information\n\t// about what happened when the statement was executed\n\tresult, err := m.DB.Exec(stmt, title, content, expires)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// Use the LastInsertId() method on the result object to get the ID of our\n\t// newly inserted record in the snippets table.\n\tid, err := result.LastInsertId()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// The ID returned has the type int64 so we convert it to an int type before returning\n\treturn int(id), nil\n}", "func (p *Patch) Insert() error {\n\treturn db.Insert(Collection, p)\n}", "func (p *Patch) Insert() error {\n\treturn db.Insert(Collection, p)\n}", "func (ds *DjangoSession) Insert(ctx context.Context, db DB) error {\n\tswitch {\n\tcase ds._exists: // already exists\n\t\treturn logerror(&ErrInsertFailed{ErrAlreadyExists})\n\tcase ds._deleted: // deleted\n\t\treturn logerror(&ErrInsertFailed{ErrMarkedForDeletion})\n\t}\n\t// insert (manual)\n\tconst sqlstr = `INSERT INTO django.django_session (` +\n\t\t`session_key, session_data, expire_date` +\n\t\t`) VALUES (` +\n\t\t`:1, :2, :3` +\n\t\t`)`\n\t// run\n\tlogf(sqlstr, ds.SessionKey, ds.SessionData, ds.ExpireDate)\n\tif _, err := db.ExecContext(ctx, sqlstr, ds.SessionKey, ds.SessionData, ds.ExpireDate); err != nil {\n\t\treturn logerror(err)\n\t}\n\t// set exists\n\tds._exists = true\n\treturn nil\n}", "func (d *DB) Insert(title string, status string) error {\n\tdb, err := gorm.Open(\"sqlite3\", \"model/DB/test.sqlite3\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdb.Create(&Todo{Title: title, Status: status})\n\tdb.Close()\n\n\treturn err\n}", "func Insert(ctx context.Context, req *proto.CreateRequest) error {\n\tlog.Printf(\"Inside Insert()\\n\")\n\n\ttxn, err := GetDbConn().Begin()\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer txn.Rollback()\n\tlog.Printf(\"Transaction started \\n\")\n\n\tfmt.Printf(\"Creating prepared statement\\n\")\n\tstmtStr, err := txn.Prepare(\"INSERT INTO restaurant_scores(business_id, business_name, business_address, business_city, business_state, business_postal_code, business_latitude, business_longitude, business_location, business_phone_number, inspection_id, inspection_date, inspection_score, inspection_type, violation_id, violation_description, risk_category, neighborhoods_old, police_districts, supervisor_districts, fire_prevention_districts, zip_codes, analysis_neighborhoods) VALUES( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23 )\")\n\t//TODO clean\n\t// stmtStr, err := txn.Prepare(\"INSERT INTO restaurant_scores(business_id, business_name, business_address, business_city, business_state, business_postal_code, business_latitude, business_longitude, business_location, business_phone_number, inspection_id, inspection_date, inspection_score, inspection_type, violation_id, violation_description, risk_category, neighborhoods_old, police_districts, supervisor_districts, fire_prevention_districts, zip_codes, analysis_neighborhoods) VALUES( 1, 2, 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test' )\")\n\tif err != nil {\n\t\tfmt.Printf(\"Error in creating statement %v\", err)\n\t\treturn err\n\t}\n\tdefer stmtStr.Close()\n\tlog.Printf(\"Statement Insertd \\n\")\n\n\tlog.Printf(\"Executing the statement for business_id %v \\n\", req.GetRecord().GetBusinessId())\n\t//Keeping long statement as punch cards time has gone\n\tres, err := stmtStr.Exec(req.GetRecord().GetBusinessId(), req.GetRecord().GetBusinessName(), req.GetRecord().GetBusinessAddress(), req.GetRecord().GetBusinessCity(), req.GetRecord().GetBusinessState(), req.GetRecord().GetBusinessPostalCode(), req.GetRecord().GetBusinessLatitude(), req.GetRecord().GetBusinessLongitude(), req.GetRecord().GetBusinessLocation(), req.GetRecord().GetBusinessPhoneNumber(), req.GetRecord().GetInspectionId(), req.GetRecord().GetInspectionDate(), req.GetRecord().GetInspectionScore(), req.GetRecord().GetInspectionType(), req.GetRecord().GetViolationId(), req.GetRecord().GetViolationDescription(), req.GetRecord().GetRiskCategory(), req.GetRecord().GetNeighborhoodsOld(), req.GetRecord().GetPoliceDistricts(), req.GetRecord().GetSupervisorDistricts(), req.GetRecord().GetFirePreventionDistricts(), req.GetRecord().GetZipCodes(), req.GetRecord().GetAnalysisNeighborhoods())\n\tif err != nil {\n\t\tlog.Printf(\"Error while inserting rows %v\", err)\n\t}\n\tlog.Printf(\"INSERT done with Result = %v\\n doing commit now \\n\", res)\n\n\terr = txn.Commit()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlog.Printf(\"Exiting Insert()\\n\")\n\treturn nil\n}", "func (session *Session) Insert(beans ...interface{}) (int64, error) {\n\treturn HookInsert(func() (int64, error) {\n\t\treturn session.Session.Insert(beans...)\n\t})\n}", "func (model *SnippetModel) Insert(title, content, expires string) (int, error) {\n\tstmt := `INSERT INTO snippets (title, content, created, expires)\n\tVALUES(?, ?, UTC_TIMESTAMP(), DATE_ADD(UTC_TIMESTAMP(), INTERVAL ? DAY))`\n\n\tresult, err := model.DB.Exec(stmt, title, content, expires)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tid, err := result.LastInsertId()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn int(id), nil\n}", "func Insert(table string, data interface{}, soft bool) (string, error) {\n\topts := r.InsertOpts{}\n\tif soft {\n\t\topts.Durability = \"soft\"\n\t} else {\n\t\topts.Durability = \"hard\"\n\t}\n\n\tres, err := r.Table(table).Insert(data, opts).Run(S)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer res.Close()\n\n\tvar result RDict\n\tif err = res.One(&result); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tid := result[\"generated_keys\"].([]interface{})[0].(string)\n\treturn id, nil\n}", "func (instance *TopicTypeRepoImpl) Insert(data *entities.TopicType) (err error) {\n\tpanic(\"implement me\")\n}", "func Insert(db *sql.DB, q Queryer) error {\n\tsql := prepareInsertString(q)\n\tif _, err := db.Exec(sql, prepareInsertArguments(q)...); err != nil {\n\t\treturn fmt.Errorf(\"Failed to insert records: %s\", err)\n\t}\n\treturn nil\n}", "func (ds *Mongostore) Insert(collection string, val interface{}) error {\n\tcol := ds.session.DB(ds.dbspec.Dbname).C(collection)\n\terr := col.Insert(val)\n\treturn err\n}", "func Insert(robo map[string]string, session *mgo.Session, db, collection string) error {\n\tc := session.DB(db).C(collection)\n\terr := c.Insert(robo)\n\treturn err\t\t\n }", "func (page *Page) Insert() error {\n\terr := db.QueryRow(\n\t\t`INSERT INTO pages(name, content, published, created_at, updated_at) \n\t\tVALUES($1,$2,$3,$4,$4) RETURNING id`,\n\t\tpage.Name,\n\t\tpage.Content,\n\t\tpage.Published,\n\t\ttime.Now(),\n\t).Scan(&page.ID)\n\treturn err\n}", "func (t Table) Insert(d Data) error {\n\tdb, err := openDB(t.Config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer db.Close()\n\t_, err = db.Exec(t.getInsertStr(d), d.ColVals...)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn err\n}", "func (journal *txJournal) insert(tx *common.Transaction) error {\n\treturn nil\n}", "func (m *MongoStore) Insert(kitten Kitten) int {\n\ts := m.session.Clone()\n\tdefer s.Close()\n\tm.Lock()\n\ti := m.nextid()\n\tm.Unlock()\n\tkitten.Id = i\n\ts.DB(\"kittenserver\").C(\"kittens\").Insert(kitten)\n\treturn i\n}", "func InsertIntoDB(userinfo types.ThirdPartyResponse) error {\n\tmeta, err := json.Marshal(userinfo.MetaData)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\n\tif userinfo.Name == \"\" {\n\t\tfmt.Println(\"Name is not issued from third party\")\n\t} else if userinfo.Id == 0 {\n\t\tfmt.Println(\"Email is not issued from third party\")\n\t}\n\n\tinsertQuery := `INSERT INTO loggedinuser (id, name, email, meta) VALUES ($1, $2, $3, $4)`\n\t_, err = db.Exec(insertQuery, userinfo.Id, userinfo.Name, userinfo.Email, string(meta))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (impl *EmployeeRepositoryImpl) Insert(employee *domain.Employee) {\n\temployeeRaw := employee.ToEmployeeRaw()\n\temployeeRaw.Id = 0 // setting to 0 will trigger auto increment\n\tquery := \"INSERT INTO employees(id, first_name, last_name, created_at) VALUES (0, ?, ?, ?);\"\n\timpl.db.MustExec(query, employeeRaw.FirstName, employeeRaw.LastName, time.Now().UTC()) //MustExec will panic on error (Exec will not)\n\t// no error returned it will panic on error\n}", "func (s structModel)Insert(table string)(query string, values []interface{}, err error){\n\tif s.err != nil{\n\t\treturn \"\", nil, s.err\n\t}\n\tvar arrQuery, valArr []string\n\tquery = \"INSERT INTO \" + table +\"(\"\n\tqueryForValues := \" VALUES(\"\n\tlistValue := make([]interface{}, 0)\n\n\tfor i, _ := range s.value{\n\t\tarrQuery = append(arrQuery, \" \" + s.key[i])\n\t\tvalArr = append(valArr, \" $\" + strconv.Itoa(i+1))\n\t\tlistValue = append(listValue, s.value[i])\n\t}\n\tquery = query + strings.Join(arrQuery, \",\") + \")\"\n\tqueryForValues = queryForValues + strings.Join(valArr, \",\") + \")\"\n\treturn query + queryForValues, listValue, nil\n}", "func (c *Command) Insert(data interface{}) (interface{}, error) {\n\tclient := c.set.gom.GetClient()\n\n\tcollection := client.Database(c.set.gom.GetDatabase()).Collection(c.set.tableName)\n\n\tdataM, err := c.set.buildData(data, true)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx, cancelFunc := c.set.GetContext()\n\tdefer cancelFunc()\n\n\tres, err := collection.InsertOne(ctx, dataM)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tid := res.InsertedID\n\n\treturn id, nil\n}", "func Insert(tid int, database *sql.DB, entries <-chan MarksStudent, results chan<- MarksStudent) {\n\n\tstatement, _ := database.Prepare(\"INSERT INTO student_marks (uid, name, maths, physics, chemistry) VALUES (?, ?, ?, ?, ?)\")\n\tfor entry := range entries {\n\t\t//fmt.Println(tid, entry)\n\t\tstatement.Exec(entry.UID, entry.Name, entry.Maths,\n\t\t\tentry.Physics, entry.Chem)\n\t\tresults <- entry\n\t}\n\n}", "func InsertIntoDB(p EventCacheParameters) error {\n\tdb, err := getDatabase()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer db.Close()\n\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstmt, err := tx.Prepare(`insert into events(id, event, json, from_user, to_user, transport, timestamp) values(?, ?, ?, ?, ?, ?, ?)`)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\n\t_, err = stmt.Exec(p.ID, p.Event, p.JSON, p.FromUser, p.ToUser, p.Transport, p.Timestamp)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttx.Commit()\n\n\treturn nil\n}", "func (o *Post) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error {\n\tif o == nil {\n\t\treturn errors.New(\"orm: no posts provided for insertion\")\n\t}\n\n\tvar err error\n\tcurrTime := time.Now().In(boil.GetLocation())\n\n\tif o.CreatedAt.IsZero() {\n\t\to.CreatedAt = currTime\n\t}\n\tif o.UpdatedAt.IsZero() {\n\t\to.UpdatedAt = currTime\n\t}\n\n\tif err := o.doBeforeInsertHooks(ctx, exec); err != nil {\n\t\treturn err\n\t}\n\n\tnzDefaults := queries.NonZeroDefaultSet(postColumnsWithDefault, o)\n\n\tkey := makeCacheKey(columns, nzDefaults)\n\tpostInsertCacheMut.RLock()\n\tcache, cached := postInsertCache[key]\n\tpostInsertCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl, returnColumns := columns.InsertColumnSet(\n\t\t\tpostColumns,\n\t\t\tpostColumnsWithDefault,\n\t\t\tpostColumnsWithoutDefault,\n\t\t\tnzDefaults,\n\t\t)\n\n\t\tcache.valueMapping, err = queries.BindMapping(postType, postMapping, wl)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcache.retMapping, err = queries.BindMapping(postType, postMapping, returnColumns)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(wl) != 0 {\n\t\t\tcache.query = fmt.Sprintf(\"INSERT INTO \\\"posts\\\" (\\\"%s\\\") %%sVALUES (%s)%%s\", strings.Join(wl, \"\\\",\\\"\"), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1))\n\t\t} else {\n\t\t\tcache.query = \"INSERT INTO \\\"posts\\\" %sDEFAULT VALUES%s\"\n\t\t}\n\n\t\tvar queryOutput, queryReturning string\n\n\t\tif len(cache.retMapping) != 0 {\n\t\t\tqueryReturning = fmt.Sprintf(\" RETURNING \\\"%s\\\"\", strings.Join(returnColumns, \"\\\",\\\"\"))\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning)\n\t}\n\n\tvalue := reflect.Indirect(reflect.ValueOf(o))\n\tvals := queries.ValuesFromMapping(value, cache.valueMapping)\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, cache.query)\n\t\tfmt.Fprintln(boil.DebugWriter, vals)\n\t}\n\n\tif len(cache.retMapping) != 0 {\n\t\terr = exec.QueryRowContext(ctx, cache.query, vals...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...)\n\t} else {\n\t\t_, err = exec.ExecContext(ctx, cache.query, vals...)\n\t}\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"orm: unable to insert into posts\")\n\t}\n\n\tif !cached {\n\t\tpostInsertCacheMut.Lock()\n\t\tpostInsertCache[key] = cache\n\t\tpostInsertCacheMut.Unlock()\n\t}\n\n\treturn o.doAfterInsertHooks(ctx, exec)\n}", "func Test_Insert(t *testing.T) {\n\n\tt.Parallel()\n\tdailwslice := create_dailyweather()\n\tinserted := dailywdao.Insert(dailwslice)\n\tif inserted == false {\n\t\tt.Error(\"insert failed!!! oops!!\")\n\t}\n\n}", "func (t Table) Insert(document ...interface{}) error {\n\treturn t.collection.Insert(document...)\n}", "func (table *Table) Insert(db DB, record Map) (Result, error) {\n\tc := Context{StateInsert, db, table, table, record, Field{}}\n\treturn table.execAction(c, table.OnInsert, table.DefaultInsert)\n}", "func Insert(insertChan chan Record, conn *sql.DB, writer io.Writer) {\n\n}", "func (bi *BatchInserter) Insert(ctx context.Context, values ...interface{}) error {\n\tif len(values) != bi.numColumns {\n\t\treturn fmt.Errorf(\"expected %d values, got %d\", bi.numColumns, len(values))\n\t}\n\n\tbi.batch = append(bi.batch, values...)\n\n\tif len(bi.batch) >= bi.maxBatchSize {\n\t\t// Flush full batch\n\t\treturn bi.Flush(ctx)\n\t}\n\n\treturn nil\n}", "func insert(ctx context.Context, tx *sqlx.Tx, todo *Todo) error {\n\tres, err := tx.NamedExecContext(ctx, insertTodo, todo)\n\tif err == nil {\n\t\ttodo.ID, err = res.LastInsertId()\n\t}\n\treturn err\n}", "func (c *Company) Insert() error {\n\tresult := initdb.DbInstance.Create(c)\n\tlog.Println(\"Created -> \", result)\n\treturn result.Error\n}", "func (m *Mytable) Insert(ctx context.Context) *spanner.Mutation {\n\treturn spanner.Insert(\"mytable\", MytableColumns(), []interface{}{\n\t\tm.A, m.B,\n\t})\n}", "func (w *dbWrapper) insertMigrationData(version time.Time, appliedAtTs time.Time, executor executor) error {\n\tif executor == nil {\n\t\texecutor = w.db\n\t}\n\n\t_, err := executor.Exec(w.setPlaceholders(fmt.Sprintf(\"INSERT INTO %s (version, applied_at) VALUES (?, ?)\", w.MigrationsTable)),\n\t\tversion.UTC().Format(TimestampFormat), appliedAtTs.UTC().Format(TimestampFormat))\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"can't insert migration\")\n\t}\n\n\treturn nil\n}", "func (e *SqlExecutor) Insert(list ...interface{}) error {\n\thook := e.db.ExecutorHook()\n\tfor _, item := range list {\n\t\tvar qArg queryArgs\n\t\tbuilder, err := buildInsert(e.dbp, item.(Model))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tqArg.query, qArg.args, err = builder.ToSql()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thook.BeforeInsert(e.ctx, qArg.query, qArg.args...)\n\t\terr = e.SqlExecutor.Insert(item)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thook.AfterInsert(e.ctx, qArg.query, qArg.args...)\n\t}\n\treturn nil\n}", "func (m *PersonDAO) Insert(person Person) error {\n\terr := db.C(COLLECTION).Insert(&person)\n\treturn err\n}", "func (o *Transaction) Insert(exec boil.Executor, whitelist ...string) error {\n\tif o == nil {\n\t\treturn errors.New(\"model: no transaction provided for insertion\")\n\t}\n\n\tvar err error\n\n\tnzDefaults := queries.NonZeroDefaultSet(transactionColumnsWithDefault, o)\n\n\tkey := makeCacheKey(whitelist, nzDefaults)\n\ttransactionInsertCacheMut.RLock()\n\tcache, cached := transactionInsertCache[key]\n\ttransactionInsertCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl, returnColumns := strmangle.InsertColumnSet(\n\t\t\ttransactionColumns,\n\t\t\ttransactionColumnsWithDefault,\n\t\t\ttransactionColumnsWithoutDefault,\n\t\t\tnzDefaults,\n\t\t\twhitelist,\n\t\t)\n\n\t\tcache.valueMapping, err = queries.BindMapping(transactionType, transactionMapping, wl)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcache.retMapping, err = queries.BindMapping(transactionType, transactionMapping, returnColumns)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(wl) != 0 {\n\t\t\tcache.query = fmt.Sprintf(\"INSERT INTO `transaction` (`%s`) %%sVALUES (%s)%%s\", strings.Join(wl, \"`,`\"), strmangle.Placeholders(dialect.IndexPlaceholders, len(wl), 1, 1))\n\t\t} else {\n\t\t\tcache.query = \"INSERT INTO `transaction` () VALUES ()\"\n\t\t}\n\n\t\tvar queryOutput, queryReturning string\n\n\t\tif len(cache.retMapping) != 0 {\n\t\t\tcache.retQuery = fmt.Sprintf(\"SELECT `%s` FROM `transaction` WHERE %s\", strings.Join(returnColumns, \"`,`\"), strmangle.WhereClause(\"`\", \"`\", 0, transactionPrimaryKeyColumns))\n\t\t}\n\n\t\tif len(wl) != 0 {\n\t\t\tcache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning)\n\t\t}\n\t}\n\n\tvalue := reflect.Indirect(reflect.ValueOf(o))\n\tvals := queries.ValuesFromMapping(value, cache.valueMapping)\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, cache.query)\n\t\tfmt.Fprintln(boil.DebugWriter, vals)\n\t}\n\n\tresult, err := exec.Exec(cache.query, vals...)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"model: unable to insert into transaction\")\n\t}\n\n\tvar lastID int64\n\tvar identifierCols []interface{}\n\n\tif len(cache.retMapping) == 0 {\n\t\tgoto CacheNoHooks\n\t}\n\n\tlastID, err = result.LastInsertId()\n\tif err != nil {\n\t\treturn ErrSyncFail\n\t}\n\n\to.ID = uint64(lastID)\n\tif lastID != 0 && len(cache.retMapping) == 1 && cache.retMapping[0] == transactionMapping[\"ID\"] {\n\t\tgoto CacheNoHooks\n\t}\n\n\tidentifierCols = []interface{}{\n\t\to.ID,\n\t}\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, cache.retQuery)\n\t\tfmt.Fprintln(boil.DebugWriter, identifierCols...)\n\t}\n\n\terr = exec.QueryRow(cache.retQuery, identifierCols...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"model: unable to populate default values for transaction\")\n\t}\n\nCacheNoHooks:\n\tif !cached {\n\t\ttransactionInsertCacheMut.Lock()\n\t\ttransactionInsertCache[key] = cache\n\t\ttransactionInsertCacheMut.Unlock()\n\t}\n\n\treturn nil\n}", "func (db *Server) Insert(serv *objects.Server) {\n\tdb.servers[serv.Met.GetID().String()] = serv\n}", "func (m *CDatabase) Insert(cluster Cluster) error {\n\terr := db.C(COLLECTION).Insert(&cluster)\n\treturn err\n}", "func (p *postsQueryBuilder) Insert() error {\n\tif p.err != nil {\n\t\treturn p.err\n\t}\n\treturn p.builder.Insert()\n}", "func (a *Article) Insert(db *database.DB) error {\n\tq := `insert into bot.articles (title, link, image, published) values (:title, :link, :image, :published);`\n\n\tstmt, stmtErr := db.PrepareNamed(q)\n\tif stmtErr != nil {\n\t\treturn stmtErr\n\t}\n\tdefer stmt.Close()\n\n\t_, execErr := stmt.Exec(a)\n\n\treturn execErr\n}", "func (md *MapData) InsertNewMapData(session *mgo.Session) {\n\tmd.ID = bson.NewObjectId()\n\n\tsession.DB(\"scratch_map\").C(\"map_data\").Insert(md)\n}", "func (r *love) Insert(boardID uint16, timecode, userID uint32, t time.Time) (err error) {\n\tidBytes := make([]byte, 10)\n\tbinary.BigEndian.PutUint16(idBytes[0:2], boardID)\n\tbinary.BigEndian.PutUint32(idBytes[2:6], userID)\n\tbinary.BigEndian.PutUint32(idBytes[6:10], timecode)\n\tval := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(val[0:4], uint32(t.Unix()))\n\t_, err = r.db.Put(idBytes, \"\", val)\n\treturn\n}", "func (o *Transaction) Insert(exec boil.Executor, whitelist ...string) error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no transactions provided for insertion\")\n\t}\n\n\tvar err error\n\tcurrTime := time.Now().In(boil.GetLocation())\n\n\tif o.UpdatedAt.Time.IsZero() {\n\t\to.UpdatedAt.Time = currTime\n\t\to.UpdatedAt.Valid = true\n\t}\n\n\tnzDefaults := queries.NonZeroDefaultSet(transactionColumnsWithDefault, o)\n\n\tkey := makeCacheKey(whitelist, nzDefaults)\n\ttransactionInsertCacheMut.RLock()\n\tcache, cached := transactionInsertCache[key]\n\ttransactionInsertCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl, returnColumns := strmangle.InsertColumnSet(\n\t\t\ttransactionColumns,\n\t\t\ttransactionColumnsWithDefault,\n\t\t\ttransactionColumnsWithoutDefault,\n\t\t\tnzDefaults,\n\t\t\twhitelist,\n\t\t)\n\n\t\tcache.valueMapping, err = queries.BindMapping(transactionType, transactionMapping, wl)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcache.retMapping, err = queries.BindMapping(transactionType, transactionMapping, returnColumns)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(wl) != 0 {\n\t\t\tcache.query = fmt.Sprintf(\"INSERT INTO `transactions` (`%s`) %%sVALUES (%s)%%s\", strings.Join(wl, \"`,`\"), strmangle.Placeholders(dialect.IndexPlaceholders, len(wl), 1, 1))\n\t\t} else {\n\t\t\tcache.query = \"INSERT INTO `transactions` () VALUES ()\"\n\t\t}\n\n\t\tvar queryOutput, queryReturning string\n\n\t\tif len(cache.retMapping) != 0 {\n\t\t\tcache.retQuery = fmt.Sprintf(\"SELECT `%s` FROM `transactions` WHERE %s\", strings.Join(returnColumns, \"`,`\"), strmangle.WhereClause(\"`\", \"`\", 0, transactionPrimaryKeyColumns))\n\t\t}\n\n\t\tif len(wl) != 0 {\n\t\t\tcache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning)\n\t\t}\n\t}\n\n\tvalue := reflect.Indirect(reflect.ValueOf(o))\n\tvals := queries.ValuesFromMapping(value, cache.valueMapping)\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, cache.query)\n\t\tfmt.Fprintln(boil.DebugWriter, vals)\n\t}\n\n\tresult, err := exec.Exec(cache.query, vals...)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to insert into transactions\")\n\t}\n\n\tvar lastID int64\n\tvar identifierCols []interface{}\n\n\tif len(cache.retMapping) == 0 {\n\t\tgoto CacheNoHooks\n\t}\n\n\tlastID, err = result.LastInsertId()\n\tif err != nil {\n\t\treturn ErrSyncFail\n\t}\n\n\to.TransactionID = int(lastID)\n\tif lastID != 0 && len(cache.retMapping) == 1 && cache.retMapping[0] == transactionMapping[\"TransactionID\"] {\n\t\tgoto CacheNoHooks\n\t}\n\n\tidentifierCols = []interface{}{\n\t\to.TransactionID,\n\t}\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, cache.retQuery)\n\t\tfmt.Fprintln(boil.DebugWriter, identifierCols...)\n\t}\n\n\terr = exec.QueryRow(cache.retQuery, identifierCols...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to populate default values for transactions\")\n\t}\n\nCacheNoHooks:\n\tif !cached {\n\t\ttransactionInsertCacheMut.Lock()\n\t\ttransactionInsertCache[key] = cache\n\t\ttransactionInsertCacheMut.Unlock()\n\t}\n\n\treturn nil\n}", "func Insert(Items Item) error {\n\terr := db.C(\"unit\").Insert(&Items)\n\treturn err\n}", "func (m *MySQL) Insert(i interface{}) (sql.Result, error) {\n\ts, _, vals, err := m.toSQL(i, INSERT)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn m.Exec(s, vals...)\n}", "func (m *MovieModel) Insert(movie *Movie) error {\n\t// Define the SQL query for inserting a new record in the movies table and returning the system generated data\n\tquery := `INSERT INTO movies (title, year, runtime, genres) \n\t\t\t\t\t\tVALUES ($1, $2, $3, $4)\n\t\t\t\t\t\tRETURNING id, created_at, version`\n\n\t// Create an args slice containing the values for the placeholder parameters from the movie struct\n\targs := []interface{}{movie.Title, movie.Year, movie.Runtime, pq.Array(movie.Genres)}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\tdefer cancel()\n\n\t// Execute the query.\n\treturn m.DB.QueryRowContext(ctx, query, args...).Scan(&movie.ID, &movie.CreatedAt, &movie.Version)\n}", "func Insert(token string, query interface{}) (int, interface{}) {\n\tif Auth(token){\n\t\tsession := Connect();\n\t\tif session == nil {\n\t\t\treturn 404, bson.M{\"error\": \"permiso denegado\"}\n\t\t}\n\t\tdefer session.Close()\n\t\tcollection := session.DB(\"my_bank_db\").C(\"MensajesGo\")\n\t\n\t\terr := collection.Insert(query)\n\t\tif err == nil {\n\t\t\treturn 200, \"Mensaje guardado!!!\"\n\t\t}\n\t}\n\treturn 404, bson.M{\"error\": \"permiso denegado\"}\n}" ]
[ "0.72054726", "0.7080304", "0.707169", "0.704247", "0.69866955", "0.68294007", "0.6823468", "0.6797961", "0.6781035", "0.6754751", "0.6718505", "0.6685691", "0.6669439", "0.6668674", "0.66551924", "0.6638359", "0.66332436", "0.66197175", "0.6619512", "0.6614102", "0.6598119", "0.65953374", "0.658149", "0.65493137", "0.6547", "0.6546595", "0.6531655", "0.6531655", "0.6531655", "0.6531655", "0.6531655", "0.6531655", "0.65131223", "0.6512962", "0.6508602", "0.65028477", "0.64972013", "0.6491572", "0.6486958", "0.64842546", "0.64699346", "0.6459523", "0.64501125", "0.6445379", "0.6441033", "0.6436989", "0.64217895", "0.6415543", "0.6409973", "0.639568", "0.6395196", "0.6394149", "0.6392101", "0.6376642", "0.63742274", "0.63742274", "0.6370664", "0.6356057", "0.6352885", "0.6343313", "0.63390565", "0.6326517", "0.6322327", "0.63179314", "0.63161993", "0.6314788", "0.63107216", "0.6309143", "0.630508", "0.6291053", "0.628681", "0.6278676", "0.6266174", "0.6260781", "0.6259069", "0.6256988", "0.62522674", "0.62446266", "0.6242603", "0.62389594", "0.62384623", "0.6237154", "0.6226458", "0.6217653", "0.62042737", "0.6200216", "0.61994195", "0.61985826", "0.6190745", "0.61812025", "0.6180298", "0.6178961", "0.61753815", "0.6174106", "0.6173866", "0.61691827", "0.61641467", "0.6158362", "0.6157756", "0.61510503" ]
0.6308072
68
after that the ForeignCluster is create we can delete the entry in the cache, the cache is clean again for the next discovery (and TTL update)
func (discoveryCache *discoveryCache) delete(key string) { discoveryCache.lock.Lock() defer discoveryCache.lock.Unlock() delete(discoveryCache.discoveredServices, key) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (cc cacheCluster) Del(keys ...string) error {\n\treturn cc.DelCtx(context.Background(), keys...)\n}", "func (iMgr *IPSetManager) modifyCacheForCacheDeletion(set *IPSet, deleteOption util.DeleteOption) {\n\tif set == iMgr.emptySet {\n\t\treturn\n\t}\n\n\tif deleteOption == util.ForceDelete {\n\t\t// If force delete, then check if Set is used by other set or network policy\n\t\t// else delete the set even if it has members\n\t\tif !set.canBeForceDeleted() {\n\t\t\treturn\n\t\t}\n\t} else if !set.canBeDeleted(iMgr.emptySet) {\n\t\treturn\n\t}\n\n\tdelete(iMgr.setMap, set.Name)\n\tmetrics.DeleteIPSet(set.Name)\n\tif iMgr.iMgrCfg.IPSetMode == ApplyAllIPSets {\n\t\tiMgr.modifyCacheForKernelRemoval(set)\n\t}\n\t// if mode is ApplyOnNeed, the set will not be in the kernel (or will be in the delete cache already) since there are no references\n}", "func (dm *DMap) deleteOnCluster(hkey uint64, key string, f *fragment) error {\n\towners := dm.s.primary.PartitionOwnersByHKey(hkey)\n\tif len(owners) == 0 {\n\t\tpanic(\"partition owners list cannot be empty\")\n\t}\n\n\terr := dm.deleteFromPreviousOwners(key, owners)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif dm.s.config.ReplicaCount != 0 {\n\t\terr := dm.deleteBackupOnCluster(hkey, key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = f.storage.Delete(hkey)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// DeleteHits is the number of deletion reqs resulting in an item being removed.\n\tDeleteHits.Increase(1)\n\n\treturn nil\n}", "func (c nullCache) Delete(k string) error {\n\treturn nil\n}", "func (api *clusterAPI) ClearCache(handler ClusterHandler) {\n\tapi.ct.delKind(\"Cluster\")\n}", "func (c *gcLifecycle) Remove(cluster *v3.Cluster) (runtime.Object, error) {\n\tif err := c.waitForNodeRemoval(cluster); err != nil {\n\t\treturn cluster, err // ErrSkip if we still need to wait\n\t}\n\n\tRESTconfig := c.mgmt.RESTConfig\n\t// due to the large number of api calls, temporary raise the burst limit in order to reduce client throttling\n\tRESTconfig.Burst = 25\n\tdynamicClient, err := dynamic.NewForConfig(&RESTconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdecodedMap := resource.GetClusterScopedTypes()\n\t//if map is empty, fall back to checking all Rancher types\n\tif len(decodedMap) == 0 {\n\t\tdecodedMap = resource.Get()\n\t}\n\tvar g errgroup.Group\n\n\tfor key := range decodedMap {\n\t\tactualKey := key // https://golang.org/doc/faq#closures_and_goroutines\n\t\tg.Go(func() error {\n\t\t\tobjList, err := dynamicClient.Resource(actualKey).List(context.TODO(), metav1.ListOptions{})\n\t\t\tif err != nil {\n\t\t\t\tif errors.IsNotFound(err) {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfor _, obj := range objList.Items {\n\t\t\t\t_, err = cleanFinalizers(cluster.Name, &obj, dynamicClient.Resource(actualKey).Namespace(obj.GetNamespace()))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t}\n\tif err = g.Wait(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn nil, nil\n}", "func (c *globalServiceCache) delete(globalService *globalService, clusterName, serviceName string) bool {\n\tscopedLog := log.WithFields(logrus.Fields{\n\t\tlogfields.ServiceName: serviceName,\n\t\tlogfields.ClusterName: clusterName,\n\t})\n\n\tif _, ok := globalService.clusterServices[clusterName]; !ok {\n\t\tscopedLog.Debug(\"Ignoring delete request for unknown cluster\")\n\t\treturn false\n\t}\n\n\tscopedLog.Debugf(\"Deleted service definition of remote cluster\")\n\tdelete(globalService.clusterServices, clusterName)\n\n\t// After the last cluster service is removed, remove the\n\t// global service\n\tif len(globalService.clusterServices) == 0 {\n\t\tscopedLog.Debugf(\"Deleted global service %s\", serviceName)\n\t\tdelete(c.byName, serviceName)\n\t\tc.metricTotalGlobalServices.Set(float64(len(c.byName)))\n\t}\n\n\treturn true\n}", "func deleteElement(col string, clave string) bool {\n\n\t//Get the element collection\n\tcc := collections[col]\n\n\t//Get the element from the map\n\telemento := cc.Mapa[clave]\n\n\t//checks if the element exists in the cache\n\tif elemento != nil {\n\n\t\t//if it is marked as deleted, return a not-found directly without checking the disk\n\t\tif elemento.Value.(*node).Deleted == true {\n\t\t\tfmt.Println(\"Not-Found cached detected on deleting, ID: \", clave)\n\t\t\treturn false\n\t\t}\n\n\t\t//the node was not previously deleted....so exists in the disk\n\n\t\t//if not-found cache is enabled, mark the element as deleted\n\t\tif cacheNotFound == true {\n\n\t\t\t//created a new node and asign it to the element\n\t\t\telemento.Value = &node{nil, false, true}\n\t\t\tfmt.Println(\"Caching Not-found for, ID: \", clave)\n\n\t\t} else {\n\t\t\t//if it is not enabled, delete the element from the memory\n\t\t\tcc.Canal <- 1\n\t\t\tdelete(cc.Mapa, clave)\n\t\t\t<-cc.Canal\n\t\t}\n\n\t\t//In both cases, remove the element from the list and from disk in a separated gorutine\n\t\tgo func() {\n\n\t\t\tlisChan <- 1\n\t\t\tdeleteElementFromLRU(elemento)\n\t\t\t<-lisChan\n\n\t\t\tdeleteJSONFromDisk(col, clave)\n\n\t\t\t//Print message\n\t\t\tif enablePrint {\n\t\t\t\tfmt.Println(\"Delete successfull, ID: \", clave)\n\t\t\t}\n\t\t}()\n\n\t} else {\n\n\t\tfmt.Println(\"Delete element not in memory, ID: \", clave)\n\n\t\t//Create a new element with the key in the cache, to save a not-found if it is enable\n\t\tcreateElement(col, clave, \"\", false, true)\n\n\t\t//Check is the element exist in the disk\n\t\terr := deleteJSONFromDisk(col, clave)\n\n\t\t//if exists, direcly remove it and return true\n\t\t//if it not exist return false (because it was not found)\n\t\tif err == nil {\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\n\t}\n\n\treturn true\n\n}", "func cacheDel(ctx *bm.Context) {\n\tvar (\n\t\tmid int64\n\t\taction string\n\t\tak string\n\t\tsd string\n\t\terr error\n\t)\n\t// res := c.Result()\n\tquery := ctx.Request.Form\n\tmidStr := query.Get(\"mid\")\n\tif mid, err = strconv.ParseInt(midStr, 10, 64); err != nil {\n\t\t// res[\"code\"] = ecode.RequestErr\n\t\tctx.JSON(nil, ecode.RequestErr)\n\t\treturn\n\t}\n\taction = query.Get(\"modifiedAttr\")\n\tak = query.Get(\"access_token\")\n\tsd = query.Get(\"session\")\n\tmemberSvc.DelCache(ctx, mid, action, ak, sd)\n\t// res[\"code\"] = ecode.OK\n\tctx.JSON(nil, nil)\n}", "func (c *Cache) cleanup(ttl time.Duration) {\n\tvalids := map[string]*cacheEntry{}\n\tnow := time.Now()\n\tfor token, entry := range c.entries {\n\t\tif entry.jwt.IsValid(c.leeway) {\n\t\t\tif entry.accessed.Add(ttl).After(now) {\n\t\t\t\t// Everything fine.\n\t\t\t\tvalids[token] = entry\n\t\t\t}\n\t\t}\n\t}\n\tc.entries = valids\n}", "func (c *etcdCache) Delete(key string) {\n c.Lock()\n defer c.Unlock()\n delete(c.props, key)\n}", "func (d *Dao) DelAdvCache(c context.Context, mid, cid int64, mode string) (err error) {\n\tvar (\n\t\tkey = _prefixAdvance + strconv.FormatInt(mid, 10) + \"@\" + strconv.FormatInt(cid, 10) + \".\" + mode\n\t)\n\tconn := d.filterMC.Get(c)\n\terr = conn.Delete(key)\n\tconn.Close()\n\tif err != nil {\n\t\tif err == memcache.ErrNotFound {\n\t\t\terr = nil\n\t\t} else {\n\t\t\tlog.Error(\"memcache.Delete(%s) error(%v)\", key, err)\n\t\t}\n\t}\n\treturn\n}", "func (c *Cache) Delete(ctx Context, key string) error {\n\n\tc.peersOnce.Do(c.initPeers)\n\n\tif c.shards == nil {\n\t\treturn errorf(shardsNotInitializedError, nil)\n\t}\n\n\tif c.peers != nil {\n\t\tif peer, ok := c.peers.PickPeer(key); ok {\n\n\t\t\terr_p := c.deleteFromPeer(ctx, peer, key)\n\n\t\t\tif err_p != nil {\n\t\t\t\treturn err_p\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tshard, err := c.getShard(key)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tshard.Lock()\n\tdefer shard.Unlock()\n\n\tif c.filter != nil {\n\t\tc.filter.delete([]byte(key))\n\t}\n\n\terr_d := shard.delete(key)\n\n\tif err_d != nil {\n\t\treturn err_d\n\t}\n\n\tif c.peers != nil {\n\t\tc.peers.DecrementLoad()\n\t}\n\n\treturn nil\n}", "func (d *Dao) DelPKGCache(c context.Context, mid int64) (err error) {\n\tkey := _pendantPKG + strconv.FormatInt(mid, 10)\n\tconn := d.redis.Get(c)\n\tdefer conn.Close()\n\tif err = conn.Send(\"DEL\", key); err != nil {\n\t\tlog.Error(\"conn.Send(DEL, %s) error(%v)\", key, err)\n\t\treturn\n\t}\n\treturn\n}", "func (s *server) deleteRecordInCacheCname(kv *mvccpb.KeyValue) {\n\tif kv == nil {\n\t\treturn\n\t}\n\trecord, err := s.ParseRecords(kv)\n\tif err != nil {\n\t\tglog.Infof(\"ParseRecords err %s \\n\", err.Error())\n\t\treturn\n\t}\n\tif record.Dnstype != \"CNAME\"{\n\t\treturn\n\t}\n\n\tif ip := net.ParseIP(record.DnsHost); ip == nil{\n\t\tkey := dns.Fqdn(record.DnsHost)\n\t\ts.rcache.DelCachedDataCnameTypeAMap(key,s.getSvcCnameName(record.Key))\n\t}\n\treturn\n}", "func (gc *GarbageCollector) cleanCache() error {\n\n\tcon, err := redis.DialURL(\n\t\tgc.redisURL,\n\t\tredis.DialConnectTimeout(dialConnectionTimeout),\n\t\tredis.DialReadTimeout(dialReadTimeout),\n\t\tredis.DialWriteTimeout(dialWriteTimeout),\n\t)\n\n\tif err != nil {\n\t\tgc.logger.Errorf(\"failed to connect to redis %v\", err)\n\t\treturn err\n\t}\n\tdefer con.Close()\n\n\t// clean all keys in registry redis DB.\n\n\t// sample of keys in registry redis:\n\t// 1) \"blobs::sha256:1a6fd470b9ce10849be79e99529a88371dff60c60aab424c077007f6979b4812\"\n\t// 2) \"repository::library/hello-world::blobs::sha256:4ab4c602aa5eed5528a6620ff18a1dc4faef0e1ab3a5eddeddb410714478c67f\"\n\terr = delKeys(con, blobPrefix)\n\tif err != nil {\n\t\tgc.logger.Errorf(\"failed to clean registry cache %v, pattern blobs::*\", err)\n\t\treturn err\n\t}\n\terr = delKeys(con, repoPrefix)\n\tif err != nil {\n\t\tgc.logger.Errorf(\"failed to clean registry cache %v, pattern repository::*\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (api *clusterAPI) Delete(obj *cluster.Cluster) error {\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = apicl.ClusterV1().Cluster().Delete(context.Background(), &obj.ObjectMeta)\n\t\treturn err\n\t}\n\n\tapi.ct.handleClusterEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Deleted})\n\treturn nil\n}", "func (c *Noncache) Delete(key string) error {\n\treturn nil\n}", "func (instance *Host) Delete(ctx context.Context) (ferr fail.Error) {\n\tdefer fail.OnPanic(&ferr)\n\n\tdefer func() {\n\t\t// drop the cache when we are done creating the cluster\n\t\tif ka, err := instance.Service().GetCache(context.Background()); err == nil {\n\t\t\tif ka != nil {\n\t\t\t\t_ = ka.Clear(context.Background())\n\t\t\t}\n\t\t}\n\t}()\n\n\tif valid.IsNil(instance) {\n\t\treturn fail.InvalidInstanceError()\n\t}\n\tif ctx == nil {\n\t\treturn fail.InvalidParameterCannotBeNilError(\"ctx\")\n\t}\n\n\txerr := instance.Inspect(ctx, func(clonable data.Clonable, props *serialize.JSONProperties) fail.Error {\n\t\t// Do not remove a Host that is a gateway\n\t\treturn props.Inspect(hostproperty.NetworkV2, func(clonable data.Clonable) fail.Error {\n\t\t\thostNetworkV2, ok := clonable.(*propertiesv2.HostNetworking)\n\t\t\tif !ok {\n\t\t\t\treturn fail.InconsistentError(\"'*propertiesv2.HostNetworking' expected, '%s' provided\", reflect.TypeOf(clonable).String())\n\t\t\t}\n\n\t\t\tif hostNetworkV2.IsGateway {\n\t\t\t\treturn fail.NotAvailableError(\"cannot delete Host, it's a gateway that can only be deleted through its Subnet\")\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t})\n\txerr = debug.InjectPlannedFail(xerr)\n\tif xerr != nil {\n\t\treturn xerr\n\t}\n\n\txerr = instance.RelaxedDeleteHost(cleanupContextFrom(ctx))\n\treturn xerr\n}", "func (s *FederationSyncController) delete(obj pkgruntime.Object, kind string, namespacedName types.NamespacedName) error {\n\tglog.V(3).Infof(\"Handling deletion of %s %q\", kind, namespacedName)\n\t_, err := s.deletionHelper.HandleObjectInUnderlyingClusters(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = s.adapter.FedDelete(namespacedName, nil)\n\tif err != nil {\n\t\t// Its all good if the error is not found error. That means it is deleted already and we do not have to do anything.\n\t\t// This is expected when we are processing an update as a result of finalizer deletion.\n\t\t// The process that deleted the last finalizer is also going to delete the resource and we do not have to do anything.\n\t\tif !errors.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (c *MockSource) Del(ctx *Context, next Next) {\n\t// source cache, like mysql/oss/rdb, etc\n\t// do not delete the data in source cache\n}", "func cacheCleanService(t *Cache) {\n\tticker := time.NewTicker(t.cleanupPeriod).C\n\tfor range ticker {\n\t\tt.Lock()\n\t\tt.txnsMaps[1] = t.txnsMaps[0]\n\t\tt.txnsMaps[0] = make(txnsMap)\n\t\tt.Unlock()\n\t}\n}", "func (c *ttlCache) purge() {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tfor key, value := range c.entries {\n\t\tif value.expireTime.Before(time.Now()) {\n\t\t\tdelete(c.entries, key)\n\t\t}\n\t}\n\n}", "func cleanDiscoCache(absolutePath string, filepaths []string, updated map[string]bool, errors *errorlist.Errors) {\n\tfor _, fp := range filepaths {\n\t\t_, filename := filepath.Split(fp)\n\t\tif !updated[filename] {\n\t\t\tfp = path.Join(absolutePath, filename)\n\t\t\tif err := os.Remove(fp); err != nil {\n\t\t\t\terrors.Add(fmt.Errorf(\"Error deleting expired Discovery doc %v: %v\", fp, err))\n\t\t\t}\n\t\t}\n\t}\n}", "func (r *RedisCache) Delete(key string) (err error) {\n\tif _, err = r.do(\"DEL\", r.key(key)); err != nil {\n\t\treturn\n\t}\n\tif r.occupyMode {\n\t\treturn\n\t}\n\n\t_, err = r.do(\"HDEL\", r.key(GC_HASH_KEY), r.key(key))\n\treturn\n}", "func (a *ExistingInfraMachineReconciler) delete(ctx context.Context, c *existinginfrav1.ExistingInfraCluster, machine *clusterv1.Machine, eim *existinginfrav1.ExistingInfraMachine) error {\n\tcontextLog := log.WithFields(log.Fields{\"machine\": machine.Name, \"cluster\": c.Name})\n\tcontextLog.Info(\"deleting machine...\")\n\taddr := a.getMachineAddress(eim)\n\tnode, err := a.findNodeByPrivateAddress(ctx, addr)\n\tif err != nil {\n\t\treturn gerrors.Wrapf(err, \"failed to find node by address: %s\", addr)\n\t}\n\t// Check if there's an adequate number of masters\n\tisMaster := isMaster(node)\n\tmasters, err := a.getMasterNodes(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif isMaster && len(masters) == 1 {\n\t\treturn errors.New(\"there should be at least one master\")\n\t}\n\tif err := drain.Drain(node, a.clientSet, drain.Params{\n\t\tForce: true,\n\t\tDeleteEmptyDirData: true,\n\t\tIgnoreAllDaemonSets: true,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\t//After deleting the k8s resource we need to reset the node so it can be readded later with a clean state.\n\t//best effort attempt to clean up the machine after deleting it.\n\ta.resetMachine(ctx, c, machine, eim)\n\n\tif err := a.Client.Delete(ctx, node); err != nil {\n\t\treturn err\n\t}\n\ta.recordEvent(machine, corev1.EventTypeNormal, \"Delete\", \"deleted machine %s\", machine.Name)\n\treturn nil\n}", "func (p *ClusterProvider) Delete() error {\n\t// This return nil for existing cluster\n\treturn nil\n}", "func (c *Cache) CleanupExpired() {\n\tgo func() {\n\t\tfor {\n\t\t\tfor k, v := range c.Map {\n\t\t\t\tif v.RegTime.Add(time.Minute * 1).Before(time.Now()) {\n\t\t\t\t\tc.Remove(k)\n\t\t\t\t}\n\t\t\t}\n\t\t\ttime.Sleep(time.Second * 10)\n\t\t}\n\t}()\n}", "func (e *EtcdConfig) Delete(key string) error {\n \n rsp, err := e.delete(key)\n if err != nil {\n return err\n }\n \n e.cache.Set(key, rsp)\n return nil\n}", "func (d *Dao) DelCache(c context.Context, mid int64, aids []int64) (err error) {\n\tvar (\n\t\tkey1 = keyIndex(mid)\n\t\tkey2 = keyHistory(mid)\n\t\targs1 = []interface{}{key1}\n\t\targs2 = []interface{}{key2}\n\t)\n\tfor _, aid := range aids {\n\t\targs1 = append(args1, aid)\n\t\targs2 = append(args2, aid)\n\t}\n\tconn := d.redis.Get(c)\n\tdefer conn.Close()\n\tif err = conn.Send(\"ZREM\", args1...); err != nil {\n\t\tlog.Error(\"conn.Send(ZREM %s,%v) error(%v)\", key1, aids, err)\n\t\treturn\n\t}\n\tif err = conn.Send(\"HDEL\", args2...); err != nil {\n\t\tlog.Error(\"conn.Send(HDEL %s,%v) error(%v)\", key2, aids, err)\n\t\treturn\n\t}\n\tif err = conn.Flush(); err != nil {\n\t\tlog.Error(\"conn.Flush() error(%v)\", err)\n\t\treturn\n\t}\n\tfor i := 0; i < 2; i++ {\n\t\tif _, err = conn.Receive(); err != nil {\n\t\t\tlog.Error(\"conn.Receive() error(%v)\", err)\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}", "func (c *Cache) Cleanup() error {\n\treturn c.doSync(func() {\n\t\tif c.entries == nil {\n\t\t\treturn\n\t\t}\n\t\tc.cleanup(c.ttl)\n\t}, defaultTimeout)\n}", "func (ca *myCache) DeleteExpiredData() {\n now := time.Now().UnixNano()\n ca.mu.Lock()\n defer ca.mu.Unlock()\n\n for k,v := range ca.dataBlocks {\n if v.ExpirateTime >0 && now > v.ExpirateTime {\n ca.delete(k)\n }\n }\n}", "func deleteIfExistsClusterScoped(clientHubDynamic dynamic.Interface, gvr schema.GroupVersionResource, name string) {\n\tns := clientHubDynamic.Resource(gvr)\n\tif _, err := ns.Get(context.TODO(), name, metav1.GetOptions{}); err != nil {\n\t\tExpect(errors.IsNotFound(err)).To(Equal(true))\n\t\treturn\n\t}\n\tExpect(func() error {\n\t\t// possibly already got deleted\n\t\terr := ns.Delete(context.TODO(), name, metav1.DeleteOptions{})\n\t\tif err != nil && !errors.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}()).To(BeNil())\n\n\tBy(\"Wait for deletion\")\n\tEventually(func() error {\n\t\tvar err error\n\t\t_, err = ns.Get(context.TODO(), name, metav1.GetOptions{})\n\t\tif err != nil && !errors.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\t\tif err == nil {\n\t\t\treturn fmt.Errorf(\"found non scoped object %s after deletion\", name)\n\t\t}\n\t\treturn nil\n\t}, 10, 1).Should(BeNil())\n}", "func testTtl(t *testing.T) {\n\tfc := &v1.ForeignCluster{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"fc-test-ttl\",\n\t\t},\n\t\tSpec: v1.ForeignClusterSpec{\n\t\t\tClusterID: \"test-cluster-ttl\",\n\t\t\tNamespace: \"default\",\n\t\t\tJoin: false,\n\t\t\tApiUrl: serverCluster.cfg.Host,\n\t\t\tDiscoveryType: v1.LanDiscovery,\n\t\t},\n\t\tStatus: v1.ForeignClusterStatus{\n\t\t\tTtl: 3,\n\t\t},\n\t}\n\n\t_, err := clientCluster.client.Resource(\"foreignclusters\").Create(fc, metav1.CreateOptions{})\n\tassert.NilError(t, err)\n\n\ttime.Sleep(1 * time.Second)\n\ttmp, err := clientCluster.client.Resource(\"foreignclusters\").Get(fc.Name, metav1.GetOptions{})\n\tassert.NilError(t, err)\n\tfc, ok := tmp.(*v1.ForeignCluster)\n\tassert.Equal(t, ok, true)\n\tassert.Equal(t, fc.ObjectMeta.Labels[\"discovery-type\"], string(v1.LanDiscovery), \"discovery-type label not correctly set\")\n\tassert.Equal(t, fc.Status.Ttl, 3, \"TTL not set to default value\")\n\n\terr = clientCluster.discoveryCtrl.UpdateTtl([]*discovery.TxtData{})\n\tassert.NilError(t, err)\n\n\ttime.Sleep(1 * time.Second)\n\ttmp, err = clientCluster.client.Resource(\"foreignclusters\").Get(fc.Name, metav1.GetOptions{})\n\tassert.NilError(t, err)\n\tfc, ok = tmp.(*v1.ForeignCluster)\n\tassert.Equal(t, ok, true)\n\tassert.Equal(t, fc.Status.Ttl, 3-1, \"TTL has not been decreased\")\n\n\ttxts := []*discovery.TxtData{\n\t\t{\n\t\t\tID: fc.Spec.ClusterID,\n\t\t\tNamespace: \"default\",\n\t\t\tApiUrl: \"\",\n\t\t\tAllowUntrustedCA: true,\n\t\t},\n\t}\n\terr = clientCluster.discoveryCtrl.UpdateTtl(txts)\n\tassert.NilError(t, err)\n\n\ttime.Sleep(1 * time.Second)\n\ttmp, err = clientCluster.client.Resource(\"foreignclusters\").Get(fc.Name, metav1.GetOptions{})\n\tassert.NilError(t, err)\n\tfc, ok = tmp.(*v1.ForeignCluster)\n\tassert.Equal(t, ok, true)\n\tassert.Equal(t, fc.Status.Ttl, 3, \"TTL not set to default value\")\n\n\terr = clientCluster.discoveryCtrl.UpdateTtl(txts)\n\tassert.NilError(t, err)\n\ttime.Sleep(100 * time.Millisecond)\n\ttmp, err = clientCluster.client.Resource(\"foreignclusters\").Get(fc.Name, metav1.GetOptions{})\n\tassert.NilError(t, err)\n\tfc, ok = tmp.(*v1.ForeignCluster)\n\tassert.Equal(t, ok, true)\n\tassert.Equal(t, fc.Status.Ttl, 3, \"TTL decrease even if in discovered list\")\n\n\tfor i := 0; i < 3; i++ {\n\t\terr = clientCluster.discoveryCtrl.UpdateTtl([]*discovery.TxtData{})\n\t\tassert.NilError(t, err)\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n\n\t_, err = clientCluster.client.Resource(\"foreignclusters\").Get(fc.Name, metav1.GetOptions{})\n\tassert.Assert(t, errors.IsNotFound(err), \"ForeignCluster not deleted on TTL 0\")\n}", "func (c *cache) Delete(id types.UID) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tdelete(c.pods, id)\n}", "func (c *SimpleMemoryCache) Del(ctx *Context, next Next) {\n\tdelete(c.data, ctx.Key)\n}", "func (gc *GKECluster) Delete() error {\n\tif !gc.NeedCleanup {\n\t\treturn nil\n\t}\n\t// TODO: Perform GKE specific cluster deletion logics\n\treturn nil\n}", "func cleanCluster(req *restful.Request, clusterID string) error {\n\t// 参数\n\tdata := operator.M{\n\t\tclusterIDTag: \"\",\n\t\tupdateTimeTag: time.Now(),\n\t}\n\tcondition := operator.NewLeafCondition(operator.Eq, operator.M{clusterIDTag: clusterID})\n\treturn UpdateMany(req.Request.Context(), tableName, condition, data)\n}", "func (cache *EntryCache) GC() {\n\tcache.oldEntries = cache.entries\n\tcache.entries = make(map[int]*Entry)\n}", "func (api *distributedservicecardAPI) ClearCache(handler DistributedServiceCardHandler) {\n\tapi.ct.delKind(\"DistributedServiceCard\")\n}", "func (c *Cache) purge() {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tif c.onEvicted != nil {\n\t\tfor _, v := range c.getElements() {\n\t\t\tc.onEvicted(v.Value)\n\t\t}\n\t}\n\tc.evictList = list.New()\n}", "func (c *Consistent) remove(elt string) {\n\tfor i := 0; i < c.NumberOfReplicas; i++ {\n\t\tdelete(c.circle, c.hashKey(c.eltKey(elt, i)))\n\t}\n\tdelete(c.members, elt)\n\tc.updateSortedHashes()\n\tc.count--\n}", "func (api *nodeAPI) ClearCache(handler NodeHandler) {\n\tapi.ct.delKind(\"Node\")\n}", "func (w *worker) deleteHost(host *chop.ChiHost) error {\n\tw.a.V(2).M(host).S().Info(host.Address.HostName)\n\tdefer w.a.V(2).M(host).E().Info(host.Address.HostName)\n\n\tw.a.V(1).\n\t\tWithEvent(host.CHI, eventActionDelete, eventReasonDeleteStarted).\n\t\tWithStatusAction(host.CHI).\n\t\tM(host).F().\n\t\tInfo(\"Delete host %s/%s - started\", host.Address.ClusterName, host.Name)\n\n\tif _, err := w.c.getStatefulSet(host); err != nil {\n\t\tw.a.WithEvent(host.CHI, eventActionDelete, eventReasonDeleteCompleted).\n\t\t\tWithStatusAction(host.CHI).\n\t\t\tM(host).F().\n\t\t\tInfo(\"Delete host %s/%s - completed StatefulSet not found - already deleted? err: %v\",\n\t\t\t\thost.Address.ClusterName, host.Name, err)\n\t\treturn nil\n\t}\n\n\t// Each host consists of\n\t// 1. User-level objects - tables on the host\n\t// We need to delete tables on the host in order to clean Zookeeper data.\n\t// If just delete tables, Zookeeper will still keep track of non-existent tables\n\t// 2. Kubernetes-level objects - such as StatefulSet, PVC(s), ConfigMap(s), Service(s)\n\t// Need to delete all these items\n\n\tvar err error\n\terr = w.deleteTables(host)\n\terr = w.c.deleteHost(host)\n\n\t// When deleting the whole CHI (not particular host), CHI may already be unavailable, so update CHI tolerantly\n\thost.CHI.Status.DeletedHostsCount++\n\t_ = w.c.updateCHIObjectStatus(host.CHI, true)\n\n\tif err == nil {\n\t\tw.a.V(1).\n\t\t\tWithEvent(host.CHI, eventActionDelete, eventReasonDeleteCompleted).\n\t\t\tWithStatusAction(host.CHI).\n\t\t\tM(host).F().\n\t\t\tInfo(\"Delete host %s/%s - completed\", host.Address.ClusterName, host.Name)\n\t} else {\n\t\tw.a.WithEvent(host.CHI, eventActionDelete, eventReasonDeleteFailed).\n\t\t\tWithStatusError(host.CHI).\n\t\t\tM(host).F().\n\t\t\tError(\"FAILED Delete host %s/%s - completed\", host.Address.ClusterName, host.Name)\n\t}\n\n\treturn err\n}", "func (gc *GarbageCollector) cleanCache() error {\n\tpool, err := redislib.GetRedisPool(\"GarbageCollector\", gc.redisURL, &redislib.PoolParam{\n\t\tPoolMaxIdle: 0,\n\t\tPoolMaxActive: 1,\n\t\tPoolIdleTimeout: 60 * time.Second,\n\t\tDialConnectionTimeout: dialConnectionTimeout,\n\t\tDialReadTimeout: dialReadTimeout,\n\t\tDialWriteTimeout: dialWriteTimeout,\n\t})\n\tif err != nil {\n\t\tgc.logger.Errorf(\"failed to connect to redis %v\", err)\n\t\treturn err\n\t}\n\tcon := pool.Get()\n\tdefer con.Close()\n\n\t// clean all keys in registry redis DB.\n\n\t// sample of keys in registry redis:\n\t// 1) \"blobs::sha256:1a6fd470b9ce10849be79e99529a88371dff60c60aab424c077007f6979b4812\"\n\t// 2) \"repository::library/hello-world::blobs::sha256:4ab4c602aa5eed5528a6620ff18a1dc4faef0e1ab3a5eddeddb410714478c67f\"\n\t// 3) \"upload:fbd2e0a3-262d-40bb-abe4-2f43aa6f9cda:size\"\n\tpatterns := []string{blobPrefix, repoPrefix, uploadSizePattern}\n\tfor _, pattern := range patterns {\n\t\tif err := delKeys(con, pattern); err != nil {\n\t\t\tgc.logger.Errorf(\"failed to clean registry cache %v, pattern %s\", err, pattern)\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (s *FrontendServer) Del(ctx context.Context, req *pb.DeleteRequest) (*pb.DeleteResponse, error) {\n\tvar returnErr error = nil\n\tvar err error\n\tvar returnRes *pb.DeleteResponse\n\t// var res *clientv3.DeleteResponse\n\tkey := req.GetKey()\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\tswitch req.GetType() {\n\tcase utils.LocalData:\n\t\t_, err = s.localSt.Delete(ctx, key)\n\tcase utils.GlobalData:\n\t\tisHashed := req.GetIsHashed()\n\t\tif s.gateway == nil {\n\t\t\treturn returnRes, fmt.Errorf(\"Del request failed: gateway node not initialized at the edge\")\n\t\t}\n\t\tstate, err := s.gateway.GetStateRPC()\n\t\tif err != nil {\n\t\t\treturn returnRes, fmt.Errorf(\"failed to get state of gateway node\")\n\t\t}\n\t\tif state < dht.Ready { // could happen if gateway node was created but didnt join dht\n\t\t\treturn returnRes, fmt.Errorf(\"edge node %s not connected to dht yet or gateway node not ready\", s.print())\n\t\t}\n\t\tif !isHashed {\n\t\t\tkey = s.gateway.Conf.IDFunc(key)\n\t\t}\n\t\tans, er := s.gateway.CanStoreRPC(key)\n\t\tif er != nil {\n\t\t\tlog.Fatalf(\"Delete request failed: communication with gateway node failed\")\n\t\t}\n\t\tif ans {\n\t\t\t_, err = s.globalSt.Delete(ctx, key)\n\t\t} else {\n\t\t\terr = s.gateway.DelKVRPC(key)\n\t\t}\n\t}\n\t// cancel() // as given in etcd docs, wouldnt do harm anyway\n\treturnErr = checkError(err)\n\tif returnErr == nil {\n\t\treturnRes = &pb.DeleteResponse{Status: utils.KVDeleted}\n\t}\n\t// TODO: we can check these keys to decide if the key was not found or actually deleted\n\t// but not really important for now\n\t// Todo: find out this: can the key be not deleted and returnErr still be nil?\n\t// \tif res.Deleted < 1 {\n\t// \t\treturnRes = &pb.DeleteResponse{Status: utils.KeyNotFound}\n\t// \t} else {\n\t// \t\treturnRes = &pb.DeleteResponse{Status: utils.KVDeleted}\n\t// \t}\n\t// } else {\n\t// \treturnRes = &pb.DeleteResponse{Status: utils.UnknownError}\n\t// }\n\treturn returnRes, returnErr\n}", "func (l *LRUCache) delete(node *Node) {\n\tnode.prev.next = node.next\n\tnode.next.prev = node.prev\n}", "func (c *Cache) Del(key string) error {\n\tc.gc.Delete(key)\n\treturn nil\n}", "func (m *MockCache) Del(key string) error {\n\treturn nil\n}", "func (c *cache) Del(key string) error {\n\terr := c.cacheConn.Del(key).Err()\n\tif err != nil {\n\t\tlogger.Log().Error(\"Error while deleting key\", zap.String(\"key\", key), zap.Error(err))\n\t\treturn err\n\t}\n\treturn nil\n}", "func (mcr *MiddlewareClusterRepo) Delete(id int) error {\n\ttx, err := mcr.Transaction()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\terr = tx.Close()\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"metadata MiddlewareClusterRepo.Delete(): close database connection failed.\\n%s\", err.Error())\n\t\t}\n\t}()\n\n\terr = tx.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tsql := `delete from t_meta_middleware_cluster_info where id = ?;`\n\tlog.Debugf(\"metadata MiddlewareClusterRepo.Delete() update sql: %s\", sql)\n\t_, err = mcr.Execute(sql, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn tx.Commit()\n}", "func cleanupCache(cache *lru.Cache) {\n\tfor {\n\t\tif cache.Len() == 0 {\n\t\t\treturn\n\t\t}\n\n\t\t_, iOldestCommitAnomalyMapCacheEntry, ok := cache.GetOldest()\n\t\tif !ok {\n\t\t\tsklog.Warningf(\"Failed to get the oldest cache item.\")\n\t\t\treturn\n\t\t}\n\n\t\toldestCommitAnomalyMapCacheEntry, ok := iOldestCommitAnomalyMapCacheEntry.(commitAnomalyMapCacheEntry)\n\t\tif oldestCommitAnomalyMapCacheEntry.addTime.Before(time.Now().Add(-cacheItemTTL)) {\n\t\t\tcache.RemoveOldest()\n\t\t\tsklog.Info(\"Cache item %s was removed from anomaly store cache.\", oldestCommitAnomalyMapCacheEntry)\n\t\t} else {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (db *Database) uncache(hash common.Hash) {\n\t// If the node does not exist, we are done on this path\n\tnode, ok := db.dirties[hash]\n\tif !ok {\n\t\treturn\n\t}\n\t// Node still exists, remove it from the flush list\n\tswitch hash {\n\tcase db.oldest:\n\t\tdb.oldest = node.flushNext\n\t\tdb.dirties[node.flushNext].flushPrev = common.Hash{}\n\tcase db.newest:\n\t\tdb.newest = node.flushPrev\n\t\tdb.dirties[node.flushPrev].flushNext = common.Hash{}\n\tdefault:\n\t\tdb.dirties[node.flushPrev].flushNext = node.flushNext\n\t\tdb.dirties[node.flushNext].flushPrev = node.flushPrev\n\t}\n\t// Uncache the node's subtries and remove the node itself too\n\tfor _, child := range node.childs() {\n\t\tdb.uncache(child)\n\t}\n\tdelete(db.dirties, hash)\n\tdb.dirtiesSize -= common.StorageSize(common.HashLength + int(node.size))\n}", "func (c *Cache) Delete(key string) {\n\te := c.entries[key]\n\tif e == nil {\n\t\treturn\n\t}\n\tdelete(c.entries, key)\n\tif len(c.entries) == 0 {\n\t\tc.head = nil\n\t\tc.tail = nil\n\t} else if e == c.head {\n\t\tc.head = c.head.next\n\t\tc.head.prev = nil\n\t} else if e == c.tail {\n\t\tc.tail = c.tail.prev\n\t\tc.tail.next = nil\n\t} else {\n\t\te.prev.next = e.next\n\t\te.next.prev = e.prev\n\t}\n}", "func (d *Dao) DelUpperCache(c context.Context, mid int64, aid int64) (err error) {\n\tconn := d.redis.Get(c)\n\tdefer conn.Close()\n\tif _, err = conn.Do(\"ZREM\", upperKey(mid), aid); err != nil {\n\t\tPromError(\"redis:删除up主\")\n\t\tlog.Error(\"conn.Do(ZERM, %s, %d) error(%+v)\", upperKey(mid), aid, err)\n\t}\n\treturn\n}", "func DeleteStaleDataForEvh(routeIgrObj RouteIngressModel, key string, modelList *[]string, Storedhosts map[string]*objects.RouteIngrhost, hostsMap map[string]*objects.RouteIngrhost) {\n\tutils.AviLog.Debugf(\"key: %s, msg: About to delete stale data EVH Stored hosts: %v, hosts map: %v\", key, utils.Stringify(Storedhosts), utils.Stringify(hostsMap))\n\tvar infraSettingName string\n\tif aviInfraSetting := routeIgrObj.GetAviInfraSetting(); aviInfraSetting != nil {\n\t\tinfraSettingName = aviInfraSetting.Name\n\t}\n\n\tfor host, hostData := range Storedhosts {\n\t\tutils.AviLog.Debugf(\"host to del: %s, data : %s\", host, utils.Stringify(hostData))\n\t\t_, shardVsName := DeriveShardVSForEvh(host, key, routeIgrObj)\n\t\tif hostData.SecurePolicy == lib.PolicyPass {\n\t\t\t_, shardVsName.Name = DerivePassthroughVS(host, key, routeIgrObj)\n\t\t}\n\t\tmodelName := lib.GetModelName(lib.GetTenant(), shardVsName.Name)\n\t\tfound, aviModel := objects.SharedAviGraphLister().Get(modelName)\n\t\tif !found || aviModel == nil {\n\t\t\tutils.AviLog.Warnf(\"key: %s, msg: model not found during delete: %s\", key, modelName)\n\t\t\tcontinue\n\t\t}\n\t\t// By default remove both redirect and fqdn. So if the host isn't transitioning, then we will remove both.\n\t\tremoveFqdn := true\n\t\tremoveRedir := true\n\t\tremoveRouteIngData := true\n\t\tcurrentData, ok := hostsMap[host]\n\t\tutils.AviLog.Debugf(\"key: %s, hostsMap: %s\", key, utils.Stringify(hostsMap))\n\t\t// if route is transitioning from/to passthrough route, then always remove fqdn\n\t\tif ok && hostData.SecurePolicy != lib.PolicyPass && currentData.SecurePolicy != lib.PolicyPass {\n\t\t\tif currentData.InsecurePolicy == lib.PolicyRedirect {\n\t\t\t\tremoveRedir = false\n\t\t\t}\n\t\t\tutils.AviLog.Infof(\"key: %s, host: %s, currentData: %v\", key, host, currentData)\n\t\t\tremoveFqdn = false\n\t\t\tif routeIgrObj.GetType() == utils.OshiftRoute {\n\t\t\t\tdiff := lib.GetDiffPath(hostData.PathSvc, currentData.PathSvc)\n\t\t\t\tif len(diff) == 0 {\n\t\t\t\t\tremoveRouteIngData = false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Delete the pool corresponding to this host\n\t\tisPassthroughVS := false\n\t\tif hostData.SecurePolicy == lib.PolicyEdgeTerm {\n\t\t\taviModel.(*AviObjectGraph).DeletePoolForHostnameForEvh(shardVsName.Name, host, routeIgrObj, hostData.PathSvc, key, infraSettingName, removeFqdn, removeRedir, removeRouteIngData, true)\n\t\t} else if hostData.SecurePolicy == lib.PolicyPass {\n\t\t\tisPassthroughVS = true\n\t\t\taviModel.(*AviObjectGraph).DeleteObjectsForPassthroughHost(shardVsName.Name, host, routeIgrObj, hostData.PathSvc, infraSettingName, key, true, true, true)\n\t\t}\n\t\tif hostData.InsecurePolicy != lib.PolicyNone {\n\t\t\tif isPassthroughVS {\n\t\t\t\taviModel.(*AviObjectGraph).DeletePoolForHostname(shardVsName.Name, host, routeIgrObj, hostData.PathSvc, key, infraSettingName, true, true, false)\n\t\t\t} else {\n\t\t\t\taviModel.(*AviObjectGraph).DeletePoolForHostnameForEvh(shardVsName.Name, host, routeIgrObj, hostData.PathSvc, key, infraSettingName, removeFqdn, removeRedir, removeRouteIngData, false)\n\t\t\t}\n\t\t}\n\t\tchangedModel := saveAviModel(modelName, aviModel.(*AviObjectGraph), key)\n\t\tif !utils.HasElem(modelList, modelName) && changedModel {\n\t\t\t*modelList = append(*modelList, modelName)\n\t\t}\n\t}\n}", "func (ct *CachingTripper) Clear() { ct.cache.Clear() }", "func DeleteRuleset(rulesetMap map[string]string) (err error) {\n uuid := rulesetMap[\"uuid\"]\n name := rulesetMap[\"name\"]\n rulesetFolderName := strings.Replace(name, \" \", \"_\", -1)\n\n localRulesetFiles, err := utils.GetKeyValueString(\"ruleset\", \"localRulesets\")\n if err != nil {\n logs.Error(\"DeleteRuleset Error getting data from main.conf for load data: \" + err.Error())\n return err\n }\n\n //delete LOG for scheduler\n err = ndb.DeleteSchedulerLog(uuid)\n if err != nil {\n logs.Error(\"Error deleting LOG DeleteSchedulerLog: \" + err.Error())\n return err\n }\n\n //delete scheduler\n schedulerUUID, err := ndb.GetSchedulerByValue(uuid)\n if err != nil {\n logs.Error(\"Error getting scheduler uuid GetSchedulerByValue: \" + err.Error())\n return err\n }\n\n err = ndb.DeleteScheduler(schedulerUUID)\n if err != nil {\n logs.Error(\"Error deleting scheduler uuid DeleteSchedulerLog: \" + err.Error())\n return err\n }\n\n //delete ruleset\n err = ndb.DeleteRulesetByUniqueid(uuid)\n if err != nil {\n logs.Error(\"DeleteRulesetByUniqueid -> ERROR deleting ruleset: \" + err.Error())\n return err\n }\n\n //delete a node ruleset\n err = ndb.DeleteRulesetNodeByUniqueid(uuid)\n if err != nil {\n logs.Error(\"DeleteRulesetNodeByUniqueid -> ERROR deleting ruleset: \" + err.Error())\n return err\n }\n\n //select all groups\n groups, err := ndb.GetAllGroups()\n if err != nil {\n logs.Error(\"DeleteRulesetNodeByUniqueid -> ERROR getting all groups: \" + err.Error())\n return err\n }\n groupsRulesets, err := ndb.GetAllGroupRulesets()\n if err != nil {\n logs.Error(\"DeleteRulesetNodeByUniqueid -> ERROR getting all grouprulesets: \" + err.Error())\n return err\n }\n for id := range groups {\n for grid := range groupsRulesets {\n if groupsRulesets[grid][\"groupid\"] == id && groupsRulesets[grid][\"rulesetid\"] == uuid {\n //delete a node ruleset\n err = ndb.DeleteGroupRulesetByValue(\"groupid\", id)\n if err != nil {\n logs.Error(\"DeleteRulesetNodeByUniqueid -> ERROR deleting grouprulesets: \" + err.Error())\n return err\n }\n err = ndb.DeleteGroupRulesetByValue(\"rulesetid\", uuid)\n if err != nil {\n logs.Error(\"DeleteRulesetNodeByUniqueid -> ERROR deleting grouprulesets: \" + err.Error())\n return err\n }\n }\n }\n\n }\n\n //delete ruleset from path\n err = os.RemoveAll(localRulesetFiles + rulesetFolderName)\n if err != nil {\n logs.Error(\"DB DeleteRuleset/rm -> ERROR deleting ruleset from their path...\")\n return errors.New(\"DB DeleteRuleset/rm -> ERROR deleting ruleset from their path...\")\n }\n\n //delete all ruleset source rules for specific uuid\n rules, err := ndb.GetRulesFromRuleset(uuid)\n if err != nil {\n logs.Error(\"GetRulesFromRuleset -> ERROR getting all rule_files for delete local ruleset: \" + err.Error())\n return err\n }\n for sourceUUID := range rules {\n err = ndb.DeleteRuleFilesByUuid(sourceUUID)\n if err != nil {\n logs.Error(\"DeleteRuleFilesByUuid -> ERROR deleting all local ruleset rule files associated: \" + err.Error())\n return err\n }\n }\n\n //update to nil group ruleset\n rulesetsForGroups, err := ndb.GetAllGroupsBValue(uuid)\n if err != nil {\n logs.Error(\"GetAllGroupsBValue -> ERROR getting all groups by ruleset uuid: \" + err.Error())\n return err\n }\n for y := range rulesetsForGroups {\n err = ndb.UpdateGroupValue(y, \"ruleset\", \"\")\n if err != nil {\n logs.Error(\"Error updating to null rulesets into group table: \" + err.Error())\n return err\n }\n err = ndb.UpdateGroupValue(y, \"rulesetID\", \"\")\n if err != nil {\n logs.Error(\"Error updating to null rulesetsID into group table: \" + err.Error())\n return err\n }\n }\n\n return nil\n}", "func (api *clusterAPI) SyncDelete(obj *cluster.Cluster) error {\n\tvar writeErr error\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t_, writeErr = apicl.ClusterV1().Cluster().Delete(context.Background(), &obj.ObjectMeta)\n\t}\n\n\tif writeErr == nil {\n\t\tapi.ct.handleClusterEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Deleted})\n\t}\n\n\treturn writeErr\n}", "func (c *DiskCache) gc(cacheSizeBytes uint64) {\n\tfor cacheSizeBytes > c.maxSizeBytes {\n\t\tlog.Debugf(\"DiskCache.gc cacheSizeBytes %+v > c.maxSizeBytes %+v\\n\", cacheSizeBytes, c.maxSizeBytes)\n\t\tkey, sizeBytes, exists := c.lru.RemoveOldest() // TODO change lru to use strings\n\t\tif !exists {\n\t\t\t// should never happen\n\t\t\tlog.Errorf(\"sizeBytes %v > %v maxSizeBytes, but LRU is empty!? Setting cache size to 0!\\n\", cacheSizeBytes, c.maxSizeBytes)\n\t\t\tatomic.StoreUint64(&c.sizeBytes, 0)\n\t\t\treturn\n\t\t}\n\n\t\tlog.Debugf(\"DiskCache.gc deleting key '\" + key + \"'\")\n\t\terr := c.db.Update(func(tx *bolt.Tx) error {\n\t\t\tb := tx.Bucket([]byte(BucketName))\n\t\t\tif b == nil {\n\t\t\t\treturn errors.New(\"bucket does not exist\")\n\t\t\t}\n\t\t\tb.Delete([]byte(key))\n\n\t\t\treturn b.Delete([]byte(key))\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Errorln(\"removing '\" + key + \"' from cache: \" + err.Error())\n\t\t}\n\n\t\tcacheSizeBytes = atomic.AddUint64(&c.sizeBytes, ^uint64(sizeBytes-1)) // subtract sizeBytes\n\t}\n}", "func (s *storage) cleanExpired(sources pb.SyncMapping, actives pb.SyncMapping) {\nnext:\n\tfor _, entry := range sources {\n\t\tfor _, act := range actives {\n\t\t\tif act.CurInstanceID == entry.CurInstanceID {\n\t\t\t\tcontinue next\n\t\t\t}\n\t\t}\n\n\t\tdelOp := delMappingOp(entry.ClusterName, entry.OrgInstanceID)\n\t\tif _, err := s.engine.Do(context.Background(), delOp); err != nil {\n\t\t\tlog.Errorf(err, \"Delete instance clusterName=%s instanceID=%s failed\", entry.ClusterName, entry.OrgInstanceID)\n\t\t}\n\n\t\ts.deleteInstance(entry.CurInstanceID)\n\t}\n}", "func (ct *ctrlerCtx) diffCluster(apicl apiclient.Services) {\n\topts := api.ListWatchOptions{}\n\n\t// get a list of all objects from API server\n\tobjlist, err := apicl.ClusterV1().Cluster().List(context.Background(), &opts)\n\tif err != nil {\n\t\tct.logger.Errorf(\"Error getting a list of objects. Err: %v\", err)\n\t\treturn\n\t}\n\n\tct.logger.Infof(\"diffCluster(): ClusterList returned %d objects\", len(objlist))\n\n\t// build an object map\n\tobjmap := make(map[string]*cluster.Cluster)\n\tfor _, obj := range objlist {\n\t\tobjmap[obj.GetKey()] = obj\n\t}\n\n\tlist, err := ct.Cluster().List(context.Background(), &opts)\n\tif err != nil && !strings.Contains(err.Error(), \"not found in local cache\") {\n\t\tct.logger.Infof(\"Failed to get a list of objects. Err: %s\", err)\n\t\treturn\n\t}\n\n\t// if an object is in our local cache and not in API server, trigger delete for it\n\tfor _, obj := range list {\n\t\t_, ok := objmap[obj.GetKey()]\n\t\tif !ok {\n\t\t\tct.logger.Infof(\"diffCluster(): Deleting existing object %#v since its not in apiserver\", obj.GetKey())\n\t\t\tevt := kvstore.WatchEvent{\n\t\t\t\tType: kvstore.Deleted,\n\t\t\t\tKey: obj.GetKey(),\n\t\t\t\tObject: &obj.Cluster,\n\t\t\t}\n\t\t\tct.handleClusterEvent(&evt)\n\t\t}\n\t}\n\n\t// trigger create event for all others\n\tfor _, obj := range objlist {\n\t\tct.logger.Infof(\"diffCluster(): Adding object %#v\", obj.GetKey())\n\t\tevt := kvstore.WatchEvent{\n\t\t\tType: kvstore.Created,\n\t\t\tKey: obj.GetKey(),\n\t\t\tObject: obj,\n\t\t}\n\t\tct.handleClusterEvent(&evt)\n\t}\n}", "func (c *Controller) onDelete(obj interface{}) {\n\t//cluster := obj.(*crv1.Pgcluster)\n\t//\tlog.Debugf(\"[Controller] ns=%s onDelete %s\", cluster.ObjectMeta.Namespace, cluster.ObjectMeta.SelfLink)\n\n\t//handle pgcluster cleanup\n\t//\tclusteroperator.DeleteClusterBase(c.PgclusterClientset, c.PgclusterClient, cluster, cluster.ObjectMeta.Namespace)\n}", "func (c *nodePoolCache) removeInstance(nodePoolID, instanceID string) error {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tklog.Infof(\"Deleting instance %q from node pool %q\", instanceID, nodePoolID)\n\t// always try to remove the instance. This call is idempotent\n\tscaleDown := true\n\tresp, err := c.okeClient.DeleteNode(context.Background(), oke.DeleteNodeRequest{\n\t\tNodePoolId: &nodePoolID,\n\t\tNodeId: &instanceID,\n\t\tIsDecrementSize: &scaleDown,\n\t})\n\n\tklog.Infof(\"Delete Node API returned response: %v, err: %v\", resp, err)\n\thttpResp := resp.HTTPResponse()\n\tvar success bool\n\tif httpResp != nil {\n\t\tstatusCode := httpResp.StatusCode\n\t\t// status returned should be a 202, but let's accept any 2XX codes anyway\n\t\tstatusSuccess := statusCode >= 200 && statusCode < 300\n\t\tsuccess = statusSuccess ||\n\t\t\t// 409 means the instance is already going to be processed for deletion\n\t\t\tstatusCode == http.StatusConflict ||\n\t\t\t// 404 means it is probably already deleted and our cache may be stale\n\t\t\tstatusCode == http.StatusNotFound\n\t\tif !success {\n\t\t\tstatus := httpResp.Status\n\t\t\tklog.Infof(\"Received error status %s while deleting node %q\", status, instanceID)\n\n\t\t\t// statuses that we might expect but are still errors:\n\t\t\t// 400s (if cluster still uses TA or is v1 based)\n\t\t\t// 401 unauthorized\n\t\t\t// 412 etag mismatch\n\t\t\t// 429 too many requests\n\t\t\t// 500 internal server errors\n\t\t\treturn errors.Errorf(\"received error status %s while deleting node %q\", status, instanceID)\n\t\t} else if statusSuccess {\n\t\t\t// since delete node endpoint scales down by 1, we need to update the cache's target size by -1 too\n\t\t\tc.targetSize[nodePoolID]--\n\t\t}\n\t}\n\n\tif !success && err != nil {\n\t\treturn err\n\t}\n\n\tnodePool := c.cache[nodePoolID]\n\t// theoretical max number of nodes inside a cluster is 1000\n\t// so at most we'll be copying 1000 nodes\n\tnewNodeSlice := make([]oke.Node, 0, len(nodePool.Nodes))\n\tfor _, node := range nodePool.Nodes {\n\t\tif *node.Id != instanceID {\n\t\t\tnewNodeSlice = append(newNodeSlice, node)\n\t\t} else {\n\t\t\tklog.Infof(\"Deleting instance %q from cache\", instanceID)\n\t\t}\n\t}\n\tnodePool.Nodes = newNodeSlice\n\n\treturn nil\n}", "func (api *tenantAPI) ClearCache(handler TenantHandler) {\n\tapi.ct.delKind(\"Tenant\")\n}", "func (r *RPC) DelArticleCache(c context.Context, arg *model.ArgAidMid, res *struct{}) (err error) {\n\terr = r.s.DelArticleCache(c, arg.Mid, arg.Aid)\n\treturn\n}", "func (d *dataUsageCache) deleteRecursive(h dataUsageHash) {\n\tif existing, ok := d.Cache[h.String()]; ok {\n\t\t// Delete first if there should be a loop.\n\t\tdelete(d.Cache, h.Key())\n\t\tfor child := range existing.Children {\n\t\t\td.deleteRecursive(dataUsageHash(child))\n\t\t}\n\t}\n}", "func (cgCache *consumerGroupCache) manageConsumerGroupCache() {\n\n\tcgCache.logger.Info(`cgCache initialized`)\n\n\tdefer cgCache.shutdownWG.Done()\n\tquit := false\n\n\trefreshTicker := time.NewTicker(metaPollTimeout) // start ticker to refresh metadata\n\tdefer refreshTicker.Stop()\n\n\tunloadTicker := time.NewTicker(unloadTickerTimeout) // start ticker to refresh metadata\n\tdefer unloadTicker.Stop()\n\n\tvar ackMgrUnloadID uint32\n\tfor !quit {\n\t\tselect {\n\t\tcase conn := <-cgCache.notifyConsCloseCh:\n\t\t\tcgCache.extMutex.Lock()\n\t\t\tif _, ok := cgCache.connections[conn]; ok {\n\t\t\t\tcgCache.logger.WithField(`conn`, conn).Info(`removing connection`)\n\t\t\t\tdelete(cgCache.connections, conn)\n\t\t\t\t// decrease the open conn count\n\t\t\t\tcgCache.cgMetrics.Decrement(load.CGMetricNumOpenConns)\n\t\t\t}\n\t\t\t// if all consumers are disconnected, keep the cgCache loaded for\n\t\t\t// some idle time\n\t\t\tif cgCache.getNumOpenConns() <= 0 {\n\t\t\t\tcgCache.lastDisconnectTime = time.Now()\n\t\t\t}\n\t\t\tcgCache.extMutex.Unlock()\n\t\tcase extUUID := <-cgCache.notifyReplicaCloseCh:\n\t\t\t// this means we are done with this extent. remove it from the cache\n\t\t\tcgCache.extMutex.Lock()\n\t\t\tackMgrUnloadID = cgCache.unloadExtentCache(extUUID)\n\t\t\tif len(cgCache.extentCache) == 0 {\n\t\t\t\t// this means all the extents are closed\n\t\t\t\t// no point in keeping the streams to the client open\n\t\t\t\tfor _, conn := range cgCache.connections {\n\t\t\t\t\tgo conn.close()\n\t\t\t\t}\n\t\t\t}\n\t\t\tcgCache.extMutex.Unlock()\n\n\t\t\t// try to unload the ackMgr as well\n\t\t\tif ackMgrUnloadID > 0 {\n\t\t\t\tselect {\n\t\t\t\tcase cgCache.ackMgrUnloadCh <- ackMgrUnloadID:\n\t\t\t\t\tackMgrUnloadID = 0\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-refreshTicker.C:\n\t\t\tcgCache.logger.Debug(\"refreshing all extents\")\n\t\t\tcgCache.extMutex.Lock()\n\t\t\tcgCache.refreshCgCache(nil)\n\t\t\tcgCache.extMutex.Unlock()\n\t\tcase <-unloadTicker.C:\n\t\t\tcgCache.extMutex.Lock()\n\t\t\t// if there are no consumers and we have been idle after the last disconnect\n\t\t\t// for more than the idleTimeout, unload the cgCache\n\t\t\tif cgCache.getNumOpenConns() <= 0 {\n\t\t\t\tif time.Since(cgCache.lastDisconnectTime) > idleTimeout {\n\t\t\t\t\tcgCache.logger.Info(\"unloading empty/idle cache\")\n\t\t\t\t\tgo cgCache.unloadConsumerGroupCache()\n\t\t\t\t}\n\t\t\t}\n\t\t\tcgCache.extMutex.Unlock()\n\t\tcase <-cgCache.closeChannel:\n\t\t\t// stop the delivery cache as well\n\t\t\tcgCache.msgDeliveryCache.stop()\n\t\t\t// wait for the manage routine to go away\n\t\t\tcgCache.manageMsgCacheWG.Wait()\n\t\t\t// at this point, the cg is completely unloaded, close all message channels\n\t\t\t// to cleanup\n\t\t\tcgCache.cleanupChannels()\n\t\t\tcgCache.logger.Info(\"cg is stopped and all channels are cleanedup\")\n\t\t\tquit = true\n\t\t}\n\t}\n}", "func delPatricia(ptr patricia, bucket string, cb db.CachedBatch) {\n\tkey := ptr.hash()\n\tlogger.Debug().Hex(\"key\", key[:8]).Msg(\"del\")\n\tcb.Delete(bucket, key[:], \"failed to delete key = %x\", key)\n}", "func Delete(name string) error {\n\tinstance, err := Get(name)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to find a cluster named '%s': %s\", name, err.Error())\n\t}\n\terr = instance.Delete()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to delete infrastructure of cluster '%s': %s\", name, err.Error())\n\t}\n\n\t// Deletes the network and related stuff\n\tutils.DeleteNetwork(instance.GetNetworkID())\n\n\t// Cleanup Object Storage data\n\treturn instance.RemoveDefinition()\n}", "func (c *CacheTable) Clean() {\r\n\tif nil != c.cleanTime {\r\n\t\tc.cleanTime.Stop()\r\n\t}\r\n\r\n\t//Copy map\r\n\titems := c.pool\r\n\r\n\t//Get min duration\r\n\tminDuration := 0 * time.Second\r\n\tclean_st := time.Now()\r\n\tfor key, item := range items {\r\n\t\tnowTime := time.Now()\r\n\t\tif item.lifeSpan <= nowTime.Sub(item.accessOn) {\r\n\t\t\tc.Delete(key)\r\n\t\t} else {\r\n\t\t\tif 0 == minDuration || item.lifeSpan-nowTime.Sub(item.accessOn) < minDuration {\r\n\t\t\t\tminDuration = item.lifeSpan - nowTime.Sub(item.accessOn)\r\n\t\t\t\t//log.Println(\"innnn %f\", minDuration.Seconds())\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif minDuration <= 0 {\r\n\t\treturn\r\n\t}\r\n\r\n\tlog.Println(\"LoopCost %f\", time.Now().Sub(clean_st).Seconds())\r\n\tc.cleanInterval = minDuration\r\n\t//Check if need do clean\r\n\tc.cleanTime = time.AfterFunc(minDuration, func() {\r\n\t\tgo c.Clean()\r\n\t})\r\n}", "func (instance *cache) MarkAsDeleted(key string) {\n\tif instance == nil {\n\t\treturn\n\t}\n\n\tif key == \"\" {\n\t\treturn\n\t}\n\n\tinstance.lock.Lock()\n\tdefer instance.lock.Unlock()\n\n\tdelete(instance.cache, key)\n}", "func (c cache) Delete(key string) {\n\tc.Delete(c.key(key))\n}", "func (api *hostAPI) Delete(obj *cluster.Host) error {\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = apicl.ClusterV1().Host().Delete(context.Background(), &obj.ObjectMeta)\n\t\treturn err\n\t}\n\n\tapi.ct.handleHostEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Deleted})\n\treturn nil\n}", "func (c *RedisCache) Del(ctx context.Context, key string) error {\n\treturn c.client.Del(ctx, key).Err()\n}", "func (g *GCMMessageHandler) CleanMetadataCache() {\n\tvar deviceToken string\n\tvar hasIndeed bool\n\tfor {\n\t\tg.inflightMessagesMetadataLock.Lock()\n\t\tfor deviceToken, hasIndeed = g.requestsHeap.HasExpiredRequest(); hasIndeed; {\n\t\t\tdelete(g.InflightMessagesMetadata, deviceToken)\n\t\t\tdeviceToken, hasIndeed = g.requestsHeap.HasExpiredRequest()\n\t\t}\n\t\tg.inflightMessagesMetadataLock.Unlock()\n\n\t\tduration := time.Duration(g.CacheCleaningInterval)\n\t\ttime.Sleep(duration * time.Millisecond)\n\t}\n}", "func (d *Dao) DelDMCache(c context.Context, tp int32, oid int64) (err error) {\n\tvar (\n\t\tkey = keyDM(tp, oid)\n\t\tconn = d.dmRds.Get(c)\n\t)\n\tif _, err = conn.Do(\"DEL\", key); err != nil {\n\t\tlog.Error(\"conn.Do(DEL %s) error(%v)\", key, err)\n\t}\n\tconn.Close()\n\treturn\n}", "func (s *RedisClusterStore) Clear(ctx context.Context) error {\n\tif err := s.clusclient.FlushAll(ctx).Err(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *LRUCache) FinishErase(e *LRUHandle) bool {\n if e != nil {\n if !e.in_cache {\n panic(\"FinishErase() error\")\n }\n s.LRU_Remove(e)\n e.in_cache = false\n s.usage_ -= e.charge\n s.Unref(e)\n }\n return e != nil\n}", "func (this *GoCache) Delete(key string) {\n\tthis.Cache.Delete(key)\n\n}", "func (ft *FacadeUnitTest) Test_PoolCacheRemoveHost(c *C) {\n\tft.setupMockDFSLocking()\n\n\tpc := NewPoolCacheEnv()\n\n\tft.hostStore.On(\"FindHostsWithPoolID\", ft.ctx, pc.resourcePool.ID).\n\t\tReturn([]host.Host{pc.firstHost, pc.secondHost}, nil).Once()\n\n\tft.poolStore.On(\"GetResourcePools\", ft.ctx).\n\t\tReturn([]pool.ResourcePool{pc.resourcePool}, nil)\n\n\tft.serviceStore.On(\"GetServicesByPool\", ft.ctx, pc.resourcePool.ID).\n\t\tReturn([]service.Service{pc.firstService, pc.secondService}, nil)\n\n\tft.serviceStore.On(\"GetServiceDetails\", ft.ctx, pc.firstService.ID).\n\t\tReturn(&service.ServiceDetails{\n\t\t\tID: pc.firstService.ID,\n\t\t\tRAMCommitment: pc.firstService.RAMCommitment,\n\t\t}, nil)\n\n\tft.hostStore.On(\"Get\", ft.ctx, host.HostKey(pc.secondHost.ID), mock.AnythingOfType(\"*host.Host\")).\n\t\tReturn(nil).\n\t\tRun(func(args mock.Arguments) {\n\t\t\t*args.Get(2).(*host.Host) = pc.secondHost\n\t\t})\n\n\tft.zzk.On(\"RemoveHost\", &pc.secondHost).Return(nil)\n\tft.zzk.On(\"UnregisterDfsClients\", []host.Host{pc.secondHost}).Return(nil)\n\n\tft.hostkeyStore.On(\"Delete\", ft.ctx, pc.secondHost.ID).Return(nil)\n\tft.hostStore.On(\"Delete\", ft.ctx, host.HostKey(pc.secondHost.ID)).Return(nil)\n\n\tpools, err := ft.Facade.GetReadPools(ft.ctx)\n\tc.Assert(err, IsNil)\n\tc.Assert(pools, Not(IsNil))\n\tc.Assert(len(pools), Equals, 1)\n\n\tp := pools[0]\n\n\tc.Assert(p.ID, Equals, pc.resourcePool.ID)\n\tc.Assert(p.CoreCapacity, Equals, 14)\n\tc.Assert(p.MemoryCapacity, Equals, uint64(22000))\n\n\terr = ft.Facade.RemoveHost(ft.ctx, pc.secondHost.ID)\n\tc.Assert(err, IsNil)\n\n\tft.hostStore.On(\"FindHostsWithPoolID\", ft.ctx, pc.resourcePool.ID).\n\t\tReturn([]host.Host{pc.firstHost}, nil).Once()\n\n\tpools, err = ft.Facade.GetReadPools(ft.ctx)\n\tc.Assert(err, IsNil)\n\tc.Assert(pools, Not(IsNil))\n\tc.Assert(len(pools), Equals, 1)\n\n\tp = pools[0]\n\tc.Assert(p.ID, Equals, pc.resourcePool.ID)\n\tc.Assert(p.CoreCapacity, Equals, 6)\n\tc.Assert(p.MemoryCapacity, Equals, uint64(12000))\n}", "func (p *perfStoreManager) delContainerPerfs() {\n\tp.lock.Lock()\n\tdefer p.lock.Unlock()\n\n\tfor c, cache := range p.caches {\n\t\t// get last elements\n\t\tstats := cache.InTimeRange(time.Now().Add(-10*time.Minute), time.Now(), -1)\n\t\tif len(stats) == 0 {\n\t\t\tklog.Warningf(\"delete container(%s) perf cache for time expired\", c)\n\t\t\tdelete(p.caches, c)\n\t\t}\n\t}\n}", "func (r *RecordCache) remove(response Response) {\n\tkey := response.FormatKey()\n\tLogger.Log(NewLogMessage(\n\t\tDEBUG,\n\t\tLogContext{\n\t\t\t\"what\": \"removing cache entry\",\n\t\t\t\"key\": key,\n\t\t},\n\t\tfunc() string { return fmt.Sprintf(\"resp [%v] cache [%v]\", response, r) },\n\t))\n\tdelete(r.cache, key)\n\tCacheSizeGauge.Set(float64(len(r.cache)))\n}", "func (api *hostAPI) ClearCache(handler HostHandler) {\n\tapi.ct.delKind(\"Host\")\n}", "func (c *MQCache) Delete(key string) {\n\tc.lock.Lock()\n\tc.delete(key)\n\tc.lock.Unlock()\n\tc.adjust(time.Now().UnixNano())\n}", "func (c Cache) gc(shutdown <-chan struct{}, tickerCh <-chan time.Time) bool {\n\tselect {\n\tcase <-shutdown:\n\t\treturn false\n\tcase <-tickerCh:\n\t\t// garbage collect the numberCache\n\t\tfor id, point := range c.numberCache {\n\t\t\tif point.used {\n\t\t\t\t// for points that have been used, mark them as unused\n\t\t\t\tpoint.used = false\n\t\t\t\tc.numberCache[id] = point\n\t\t\t} else {\n\t\t\t\t// for points that have not been used, delete points\n\t\t\t\tdelete(c.numberCache, id)\n\t\t\t}\n\t\t}\n\t\t// garbage collect the summaryCache\n\t\tfor id, point := range c.summaryCache {\n\t\t\tif point.used {\n\t\t\t\t// for points that have been used, mark them as unused\n\t\t\t\tpoint.used = false\n\t\t\t\tc.summaryCache[id] = point\n\t\t\t} else {\n\t\t\t\t// for points that have not been used, delete points\n\t\t\t\tdelete(c.summaryCache, id)\n\t\t\t}\n\t\t}\n\t\t// garbage collect the histogramCache\n\t\tfor id, point := range c.histogramCache {\n\t\t\tif point.used {\n\t\t\t\t// for points that have been used, mark them as unused\n\t\t\t\tpoint.used = false\n\t\t\t\tc.histogramCache[id] = point\n\t\t\t} else {\n\t\t\t\t// for points that have not been used, delete points\n\t\t\t\tdelete(c.histogramCache, id)\n\t\t\t}\n\t\t}\n\t\t// garbage collect the exponentialHistogramCache\n\t\tfor id, point := range c.exponentialHistogramCache {\n\t\t\tif point.used {\n\t\t\t\t// for points that have been used, mark them as unused\n\t\t\t\tpoint.used = false\n\t\t\t\tc.exponentialHistogramCache[id] = point\n\t\t\t} else {\n\t\t\t\t// for points that have not been used, delete points\n\t\t\t\tdelete(c.exponentialHistogramCache, id)\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}", "func (c *CacheMap) GC() {\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(time.Duration(c.gcPercent) * time.Second):\n\t\t\tif keys := c.expiredKeys(); len(keys) != 0 {\n\t\t\t\tfor _, key := range keys {\n\t\t\t\t\tc.Del(key)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (api *hostAPI) SyncDelete(obj *cluster.Host) error {\n\tvar writeErr error\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t_, writeErr = apicl.ClusterV1().Host().Delete(context.Background(), &obj.ObjectMeta)\n\t}\n\n\tif writeErr == nil {\n\t\tapi.ct.handleHostEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Deleted})\n\t}\n\n\treturn writeErr\n}", "func (s *shard) del(h uint64) error {\n\tif s.statsEnabled {\n\t\tatomic.AddUint64(&s.delHits, 1)\n\t}\n\n\ts.rwMutex.Lock()\n\tdefer s.rwMutex.Unlock()\n\tif _, ok := s.entryIndexes[h]; !ok {\n\t\tif s.statsEnabled {\n\t\t\tatomic.AddUint64(&s.delMisses, 1)\n\t\t}\n\t\treturn ErrEntryNotFound\n\t}\n\n\tdelete(s.entryIndexes, h)\n\treturn nil\n}", "func (fdb *fdbSlice) delete(docid []byte, workerId int) {\n\n\tcommon.Tracef(\"ForestDBSlice::delete \\n\\tSliceId %v IndexInstId %v. Delete Key - %s\",\n\t\tfdb.id, fdb.idxInstId, docid)\n\n\tvar oldkey Key\n\tvar err error\n\n\tif oldkey, err = fdb.getBackIndexEntry(docid, workerId); err != nil {\n\t\tfdb.checkFatalDbError(err)\n\t\tcommon.Errorf(\"ForestDBSlice::delete \\n\\tSliceId %v IndexInstId %v. Error locating \"+\n\t\t\t\"backindex entry for Doc %s. Error %v\", fdb.id, fdb.idxInstId, docid, err)\n\t\treturn\n\t}\n\n\t//delete from main index\n\tif err = fdb.main[workerId].DeleteKV(oldkey.EncodedBytes()); err != nil {\n\t\tfdb.checkFatalDbError(err)\n\t\tcommon.Errorf(\"ForestDBSlice::delete \\n\\tSliceId %v IndexInstId %v. Error deleting \"+\n\t\t\t\"entry from main index for Doc %s. Key %v. Error %v\", fdb.id, fdb.idxInstId,\n\t\t\tdocid, oldkey, err)\n\t\treturn\n\t}\n\n\t//delete from the back index\n\tif err = fdb.back[workerId].DeleteKV(docid); err != nil {\n\t\tfdb.checkFatalDbError(err)\n\t\tcommon.Errorf(\"ForestDBSlice::delete \\n\\tSliceId %v IndexInstId %v. Error deleting \"+\n\t\t\t\"entry from back index for Doc %s. Error %v\", fdb.id, fdb.idxInstId, docid, err)\n\t\treturn\n\t}\n\n}", "func (instance *Host) RelaxedDeleteHost(ctx context.Context) (ferr fail.Error) {\n\tdefer fail.OnPanic(&ferr)\n\n\tif valid.IsNil(instance) {\n\t\treturn fail.InvalidInstanceError()\n\t}\n\tif ctx == nil {\n\t\treturn fail.InvalidParameterCannotBeNilError(\"ctx\")\n\t}\n\n\tsvc := instance.Service()\n\ttimings, xerr := svc.Timings()\n\tif xerr != nil {\n\t\treturn xerr\n\t}\n\n\tcache, xerr := instance.Service().GetCache(ctx)\n\tif xerr != nil {\n\t\treturn xerr\n\t}\n\n\tvar shares map[string]*propertiesv1.HostShare\n\txerr = instance.Inspect(ctx, func(_ data.Clonable, props *serialize.JSONProperties) fail.Error {\n\t\t// Do not remove a Host having shared folders that are currently remotely mounted\n\t\tinnerXErr := props.Inspect(hostproperty.SharesV1, func(clonable data.Clonable) fail.Error {\n\t\t\tsharesV1, ok := clonable.(*propertiesv1.HostShares)\n\t\t\tif !ok {\n\t\t\t\treturn fail.InconsistentError(\n\t\t\t\t\t\"'*propertiesv1.HostShares' expected, '%s' provided\", reflect.TypeOf(clonable).String(),\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tshares = sharesV1.ByID\n\t\t\tshareCount := len(shares)\n\t\t\tfor _, hostShare := range shares {\n\t\t\t\tcount := len(hostShare.ClientsByID)\n\t\t\t\tif count > 0 {\n\t\t\t\t\t// clients found, checks if these clients already exists...\n\t\t\t\t\tfor _, hostID := range hostShare.ClientsByID {\n\t\t\t\t\t\tinstance, inErr := LoadHost(ctx, svc, hostID)\n\t\t\t\t\t\tif inErr != nil {\n\t\t\t\t\t\t\tdebug.IgnoreError2(ctx, inErr)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn fail.NotAvailableError(\"Host '%s' exports %d share%s and at least one share is mounted\", instance.GetName(), shareCount, strprocess.Plural(uint(shareCount)))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif innerXErr != nil {\n\t\t\treturn innerXErr\n\t\t}\n\n\t\t// Do not delete a Host with Bucket mounted\n\t\tinnerXErr = props.Inspect(hostproperty.MountsV1, func(clonable data.Clonable) fail.Error {\n\t\t\thostMountsV1, ok := clonable.(*propertiesv1.HostMounts)\n\t\t\tif !ok {\n\t\t\t\treturn fail.InconsistentError(\"'*propertiesv1.HostMounbts' expected, '%s' provided\", reflect.TypeOf(clonable).String())\n\t\t\t}\n\n\t\t\tnMounted := len(hostMountsV1.BucketMounts)\n\t\t\tif nMounted > 0 {\n\t\t\t\treturn fail.NotAvailableError(\"Host '%s' has %d Bucket%s mounted\", instance.GetName(), nMounted, strprocess.Plural(uint(nMounted)))\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif innerXErr != nil {\n\t\t\treturn innerXErr\n\t\t}\n\n\t\t// Do not delete a Host with Volumes attached\n\t\treturn props.Inspect(hostproperty.VolumesV1, func(clonable data.Clonable) fail.Error {\n\t\t\thostVolumesV1, ok := clonable.(*propertiesv1.HostVolumes)\n\t\t\tif !ok {\n\t\t\t\treturn fail.InconsistentError(\n\t\t\t\t\t\"'*propertiesv1.HostVolumes' expected, '%s' provided\", reflect.TypeOf(clonable).String(),\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tnAttached := len(hostVolumesV1.VolumesByID)\n\t\t\tif nAttached > 0 {\n\t\t\t\treturn fail.NotAvailableError(\"Host '%s' has %d Volume%s attached\", instance.GetName(), nAttached,\n\t\t\t\t\tstrprocess.Plural(uint(nAttached)),\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t})\n\txerr = debug.InjectPlannedFail(xerr)\n\tif xerr != nil {\n\t\treturn xerr\n\t}\n\n\thid, err := instance.GetID()\n\tif err != nil {\n\t\treturn fail.ConvertError(err)\n\t}\n\n\thname := instance.GetName()\n\n\tvar (\n\t\tsingle bool\n\t\tsingleSubnetID string\n\t)\n\txerr = instance.Alter(ctx, func(_ data.Clonable, props *serialize.JSONProperties) fail.Error {\n\t\t// If Host has mounted shares, unmounts them before anything else\n\t\tvar mounts []*propertiesv1.HostShare\n\t\tinnerXErr := props.Inspect(hostproperty.MountsV1, func(clonable data.Clonable) fail.Error {\n\t\t\thostMountsV1, ok := clonable.(*propertiesv1.HostMounts)\n\t\t\tif !ok {\n\t\t\t\treturn fail.InconsistentError(\"'*propertiesv1.HostMounts' expected, '%s' provided\", reflect.TypeOf(clonable).String())\n\t\t\t}\n\n\t\t\tfor _, i := range hostMountsV1.RemoteMountsByPath {\n\t\t\t\t// Retrieve Share data\n\t\t\t\tshareInstance, loopErr := LoadShare(ctx, svc, i.ShareID)\n\t\t\t\tif loopErr != nil {\n\t\t\t\t\tif _, ok := loopErr.(*fail.ErrNotFound); !ok { // nolint\n\t\t\t\t\t\treturn loopErr\n\t\t\t\t\t}\n\t\t\t\t\tdebug.IgnoreError2(ctx, loopErr)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Retrieve data about the server serving the Share\n\t\t\t\thostServer, loopErr := shareInstance.GetServer(ctx)\n\t\t\t\tif loopErr != nil {\n\t\t\t\t\treturn loopErr\n\t\t\t\t}\n\n\t\t\t\t// Retrieve data about v from its server\n\t\t\t\titem, loopErr := hostServer.GetShare(ctx, i.ShareID)\n\t\t\t\tif loopErr != nil {\n\t\t\t\t\treturn loopErr\n\t\t\t\t}\n\n\t\t\t\tmounts = append(mounts, item)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif innerXErr != nil {\n\t\t\treturn innerXErr\n\t\t}\n\n\t\t// Unmounts tier shares mounted on Host (done outside the previous Host.properties.Reading() section, because\n\t\t// Unmount() have to lock for write, and won't succeed while Host.properties.Reading() is running,\n\t\t// leading to a deadlock)\n\t\tfor _, v := range mounts {\n\t\t\tshareInstance, loopErr := LoadShare(ctx, svc, v.ID)\n\t\t\tif loopErr != nil {\n\t\t\t\tif _, ok := loopErr.(*fail.ErrNotFound); !ok { // nolint\n\t\t\t\t\treturn loopErr\n\t\t\t\t}\n\t\t\t\tdebug.IgnoreError2(ctx, loopErr)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tloopErr = shareInstance.Unmount(ctx, instance)\n\t\t\tif loopErr != nil {\n\t\t\t\treturn loopErr\n\t\t\t}\n\t\t}\n\n\t\t// if Host exports shares, delete them\n\t\tfor _, v := range shares {\n\t\t\tshareInstance, loopErr := LoadShare(ctx, svc, v.Name)\n\t\t\tif loopErr != nil {\n\t\t\t\tif _, ok := loopErr.(*fail.ErrNotFound); !ok { // nolint\n\t\t\t\t\treturn loopErr\n\t\t\t\t}\n\t\t\t\tdebug.IgnoreError2(ctx, loopErr)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tloopErr = shareInstance.Delete(ctx)\n\t\t\tif loopErr != nil {\n\t\t\t\treturn loopErr\n\t\t\t}\n\t\t}\n\n\t\t// Walk through property propertiesv1.HostNetworking to remove the reference to the Host in Subnets\n\t\tinnerXErr = props.Inspect(hostproperty.NetworkV2, func(clonable data.Clonable) fail.Error {\n\t\t\thostNetworkV2, ok := clonable.(*propertiesv2.HostNetworking)\n\t\t\tif !ok {\n\t\t\t\treturn fail.InconsistentError(\"'*propertiesv2.HostNetworking' expected, '%s' provided\", reflect.TypeOf(clonable).String())\n\t\t\t}\n\t\t\thostID, err := instance.GetID()\n\t\t\tif err != nil {\n\t\t\t\treturn fail.ConvertError(err)\n\t\t\t}\n\n\t\t\tsingle = hostNetworkV2.Single\n\t\t\tif single {\n\t\t\t\tsingleSubnetID = hostNetworkV2.DefaultSubnetID\n\t\t\t}\n\n\t\t\tif !single {\n\t\t\t\tvar errs []error\n\t\t\t\tfor k := range hostNetworkV2.SubnetsByID {\n\t\t\t\t\tif !hostNetworkV2.IsGateway && k != hostNetworkV2.DefaultSubnetID {\n\t\t\t\t\t\tsubnetInstance, loopErr := LoadSubnet(ctx, svc, \"\", k)\n\t\t\t\t\t\tif loopErr != nil {\n\t\t\t\t\t\t\tlogrus.WithContext(ctx).Errorf(loopErr.Error())\n\t\t\t\t\t\t\terrs = append(errs, loopErr)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tloopErr = subnetInstance.DetachHost(ctx, hostID)\n\t\t\t\t\t\tif loopErr != nil {\n\t\t\t\t\t\t\tlogrus.WithContext(ctx).Errorf(loopErr.Error())\n\t\t\t\t\t\t\terrs = append(errs, loopErr)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif len(errs) > 0 {\n\t\t\t\t\treturn fail.Wrap(fail.NewErrorList(errs), \"failed to update metadata for Subnets of Host\")\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif innerXErr != nil {\n\t\t\treturn innerXErr\n\t\t}\n\n\t\t// Unbind Security Groups from Host\n\t\tinnerXErr = props.Alter(hostproperty.SecurityGroupsV1, func(clonable data.Clonable) fail.Error {\n\t\t\thsgV1, ok := clonable.(*propertiesv1.HostSecurityGroups)\n\t\t\tif !ok {\n\t\t\t\treturn fail.InconsistentError(\"'*propertiesv1.HostSecurityGroups' expected, '%s' provided\", reflect.TypeOf(clonable).String())\n\t\t\t}\n\n\t\t\t// Unbind Security Groups from Host\n\t\t\tvar errs []error\n\t\t\tfor _, v := range hsgV1.ByID {\n\t\t\t\tsgInstance, rerr := LoadSecurityGroup(ctx, svc, v.ID)\n\t\t\t\tif rerr != nil {\n\t\t\t\t\tswitch rerr.(type) {\n\t\t\t\t\tcase *fail.ErrNotFound:\n\t\t\t\t\t\t// Consider that a Security Group that cannot be loaded or is not bound as a success\n\t\t\t\t\t\tdebug.IgnoreError2(ctx, rerr)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\terrs = append(errs, rerr)\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\trerr = sgInstance.UnbindFromHost(ctx, instance)\n\t\t\t\tif rerr != nil {\n\t\t\t\t\tswitch rerr.(type) {\n\t\t\t\t\tcase *fail.ErrNotFound:\n\t\t\t\t\t\t// Consider that a Security Group that cannot be loaded or is not bound as a success\n\t\t\t\t\t\tdebug.IgnoreError2(ctx, rerr)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\terrs = append(errs, rerr)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(errs) > 0 {\n\t\t\t\treturn fail.Wrap(fail.NewErrorList(errs), \"failed to unbind some Security Groups\")\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t\tif innerXErr != nil {\n\t\t\treturn fail.Wrap(innerXErr, \"failed to unbind Security Groups from Host\")\n\t\t}\n\n\t\t// Unbind labels from Host\n\t\tinnerXErr = props.Alter(hostproperty.LabelsV1, func(clonable data.Clonable) fail.Error {\n\t\t\thlV1, ok := clonable.(*propertiesv1.HostLabels)\n\t\t\tif !ok {\n\t\t\t\treturn fail.InconsistentError(\"'*propertiesv1.HostLabels' expected, '%s' provided\", reflect.TypeOf(clonable).String())\n\t\t\t}\n\n\t\t\t// Unbind Security Groups from Host\n\t\t\tvar errs []error\n\t\t\tfor k := range hlV1.ByID {\n\t\t\t\tlabelInstance, rerr := LoadLabel(ctx, svc, k)\n\t\t\t\tif rerr != nil {\n\t\t\t\t\tswitch rerr.(type) {\n\t\t\t\t\tcase *fail.ErrNotFound:\n\t\t\t\t\t\t// Consider that a Security Group that cannot be loaded or is not bound as a success\n\t\t\t\t\t\tdebug.IgnoreError2(ctx, rerr)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\terrs = append(errs, rerr)\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\trerr = labelInstance.UnbindFromHost(cleanupContextFrom(ctx), instance)\n\t\t\t\tif rerr != nil {\n\t\t\t\t\tswitch rerr.(type) {\n\t\t\t\t\tcase *fail.ErrNotFound:\n\t\t\t\t\t\t// Consider that a Security Group that cannot be loaded or is not bound as a success\n\t\t\t\t\t\tdebug.IgnoreError2(ctx, rerr)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\terrs = append(errs, rerr)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(errs) > 0 {\n\t\t\t\treturn fail.Wrap(fail.NewErrorList(errs), \"failed to unbind some Security Groups\")\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t\tif innerXErr != nil {\n\t\t\treturn fail.Wrap(innerXErr, \"failed to unbind Security Groups from Host\")\n\t\t}\n\n\t\t// Delete Host\n\t\twaitForDeletion := true\n\t\tinnerXErr = retry.WhileUnsuccessful(\n\t\t\tfunc() error {\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn retry.StopRetryError(ctx.Err())\n\t\t\t\tdefault:\n\t\t\t\t}\n\n\t\t\t\tif rerr := svc.DeleteHost(ctx, hid); rerr != nil {\n\t\t\t\t\tswitch rerr.(type) {\n\t\t\t\t\tcase *fail.ErrNotFound:\n\t\t\t\t\t\t// A Host not found is considered as a successful deletion\n\t\t\t\t\t\tlogrus.WithContext(ctx).Tracef(\"Host not found, deletion considered as a success\")\n\t\t\t\t\t\tdebug.IgnoreError2(ctx, rerr)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\treturn fail.Wrap(rerr, \"cannot delete Host\")\n\t\t\t\t\t}\n\t\t\t\t\twaitForDeletion = false\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\ttimings.SmallDelay(),\n\t\t\ttimings.HostCleanupTimeout(),\n\t\t)\n\t\tif innerXErr != nil {\n\t\t\tswitch innerXErr.(type) {\n\t\t\tcase *retry.ErrStopRetry:\n\t\t\t\treturn fail.Wrap(fail.Cause(innerXErr), \"stopping retries\")\n\t\t\tcase *retry.ErrTimeout:\n\t\t\t\treturn fail.Wrap(fail.Cause(innerXErr), \"timeout\")\n\t\t\tdefault:\n\t\t\t\treturn innerXErr\n\t\t\t}\n\t\t}\n\n\t\t// wait for effective Host deletion\n\t\tif waitForDeletion {\n\t\t\tinnerXErr = retry.WhileUnsuccessfulWithHardTimeout(\n\t\t\t\tfunc() error {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t\treturn retry.StopRetryError(ctx.Err())\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\n\t\t\t\t\tstate, stateErr := svc.GetHostState(ctx, hid)\n\t\t\t\t\tif stateErr != nil {\n\t\t\t\t\t\tswitch stateErr.(type) {\n\t\t\t\t\t\tcase *fail.ErrNotFound:\n\t\t\t\t\t\t\t// If Host is not found anymore, consider this as a success\n\t\t\t\t\t\t\tdebug.IgnoreError2(ctx, stateErr)\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn stateErr\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif state == hoststate.Error {\n\t\t\t\t\t\treturn fail.NotAvailableError(\"Host is in state Error\")\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t},\n\t\t\t\ttimings.NormalDelay(),\n\t\t\t\ttimings.OperationTimeout(),\n\t\t\t)\n\t\t\tif innerXErr != nil {\n\t\t\t\tswitch innerXErr.(type) {\n\t\t\t\tcase *retry.ErrStopRetry:\n\t\t\t\t\tinnerXErr = fail.ConvertError(fail.Cause(innerXErr))\n\t\t\t\t\tif _, ok := innerXErr.(*fail.ErrNotFound); !ok || valid.IsNil(innerXErr) {\n\t\t\t\t\t\treturn innerXErr\n\t\t\t\t\t}\n\t\t\t\t\tdebug.IgnoreError2(ctx, innerXErr)\n\t\t\t\tcase *fail.ErrNotFound:\n\t\t\t\t\tdebug.IgnoreError2(ctx, innerXErr)\n\t\t\t\tdefault:\n\t\t\t\t\treturn innerXErr\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\txerr = debug.InjectPlannedFail(xerr)\n\tif xerr != nil {\n\t\treturn xerr\n\t}\n\n\tif single {\n\t\t// delete its dedicated Subnet\n\t\tsingleSubnetInstance, xerr := LoadSubnet(ctx, svc, \"\", singleSubnetID)\n\t\txerr = debug.InjectPlannedFail(xerr)\n\t\tif xerr != nil {\n\t\t\treturn xerr\n\t\t}\n\n\t\txerr = singleSubnetInstance.Delete(ctx)\n\t\txerr = debug.InjectPlannedFail(xerr)\n\t\tif xerr != nil {\n\t\t\treturn xerr\n\t\t}\n\t}\n\n\ttheID, _ := instance.GetID()\n\n\t// Deletes metadata from Object Storage\n\txerr = instance.MetadataCore.Delete(ctx)\n\txerr = debug.InjectPlannedFail(xerr)\n\tif xerr != nil {\n\t\t// If entry not found, considered as a success\n\t\tif _, ok := xerr.(*fail.ErrNotFound); !ok || valid.IsNil(xerr) {\n\t\t\treturn xerr\n\t\t}\n\t\tdebug.IgnoreError2(ctx, xerr)\n\t\tlogrus.WithContext(ctx).Tracef(\"core instance not found, deletion considered as a success\")\n\t}\n\n\tif ka, err := instance.Service().GetCache(ctx); err == nil {\n\t\tif ka != nil {\n\t\t\tif theID != \"\" {\n\t\t\t\t_ = ka.Delete(ctx, fmt.Sprintf(\"%T/%s\", instance, theID))\n\t\t\t}\n\t\t}\n\t}\n\n\tif cache != nil {\n\t\t_ = cache.Delete(ctx, hid)\n\t\t_ = cache.Delete(ctx, hname)\n\t}\n\n\treturn nil\n}", "func (r *ClusterReconciler) deleteExternalResources(cluster clusterv1.Cluster, ctx context.Context) error {\n\t//\n\t// delete any external resources associated with the cluster\n\t//\n\t// Ensure that delete implementation is idempotent and safe to invoke\n\t// multiple types for same object.\n\n\t// get target memberCluster client\n\tmClient := clients.Interface().Kubernetes(cluster.Name)\n\n\t// delete internal cluster and release goroutine inside\n\terr := multicluster.Interface().Del(cluster.Name)\n\tif err != nil {\n\t\tclog.Error(\"delete internal cluster %v failed\", err)\n\t\treturn err\n\t}\n\tclog.Debug(\"delete internal cluster %v success\", cluster.Name)\n\n\t// delete kubecube-system of cluster\n\tns := corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: constants.CubeNamespace}}\n\terr = mClient.Direct().Delete(ctx, &ns)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\tclog.Warn(\"namespace %v of cluster %v not failed, delete skip\", constants.CubeNamespace, cluster.Name)\n\t\t}\n\t\tclog.Error(\"delete namespace %v of cluster %v failed: %v\", constants.CubeNamespace, cluster.Name, err)\n\t\treturn err\n\t}\n\tclog.Debug(\"delete kubecube-system of cluster %v success\", cluster.Name)\n\n\treturn nil\n}", "func (c *ChainCache[T]) Delete(ctx context.Context, key any) error {\n\tfor _, cache := range c.caches {\n\t\tcache.Delete(ctx, key)\n\t}\n\n\treturn nil\n}", "func (e *EndpointIndex) clearCacheForService(svc, ns string) {\n\te.cache.Clear(sets.Set[ConfigKey]{{\n\t\tKind: kind.ServiceEntry,\n\t\tName: svc,\n\t\tNamespace: ns,\n\t}: {}})\n}", "func (s *Store) GC() {\n\tlog.Println(\"[mssql]GC begin....\")\n\n\ttm := time.Now()\n\tlog.Println(\"[mssql]GC tm=\", tm)\n\n\titem := &Item{\n\t\tTable: s.Sql.table,\n\t\tSplit: s.Sql.split,\n\t}\n\tcount, err := s.Sql.engine.Where(\"expiresAt < ?\", tm).Delete(item)\n\tif err != nil {\n\t\tlog.Println(\"[mssql]GC: err=\", err)\n\t\treturn\n\t}\n\n\tlog.Printf(\"[mssql]GC end...[del=%v]\\n\", count)\n}", "func (h *HotRegionStorage) backgroundDelete() {\n\tdefer logutil.LogPanic()\n\n\t// make delete happened in defaultDeleteTime clock.\n\tnow := time.Now()\n\tnext := time.Date(now.Year(), now.Month(), now.Day(), defaultDeleteTime, 0, 0, 0, now.Location())\n\td := next.Sub(now)\n\tif d < 0 {\n\t\td += 24 * time.Hour\n\t}\n\tisFirst := true\n\tticker := time.NewTicker(d)\n\tdefer func() {\n\t\tticker.Stop()\n\t\th.hotRegionLoopWg.Done()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\th.updateReservedDays()\n\t\t\tcurReservedDays := h.getCurReservedDays()\n\t\t\tif isFirst {\n\t\t\t\tticker.Reset(24 * time.Hour)\n\t\t\t\tisFirst = false\n\t\t\t}\n\t\t\tif curReservedDays == 0 {\n\t\t\t\tlog.Warn(`hot region reserved days is 0, if previous reserved days is non 0,\n\t\t\t\t there may be residual hot regions, you can remove it manually, [pd-dir]/data/hot-region.`)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\th.delete(int(curReservedDays))\n\t\tcase <-h.hotRegionInfoCtx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func (m *Manager) cleanUp(ctx context.Context, p *models.Project) {\n\t// clean index by id\n\tidIdx, err := m.keyBuilder.Format(\"id\", p.ProjectID)\n\tif err != nil {\n\t\tlog.Errorf(\"format project id key error: %v\", err)\n\t} else {\n\t\t// retry to avoid dirty data\n\t\tif err = retry.Retry(func() error { return m.CacheClient(ctx).Delete(ctx, idIdx) }); err != nil {\n\t\t\tlog.Errorf(\"delete project cache key %s error: %v\", idIdx, err)\n\t\t}\n\t}\n\n\t// clean index by name\n\tnameIdx, err := m.keyBuilder.Format(\"name\", p.Name)\n\tif err != nil {\n\t\tlog.Errorf(\"format project name key error: %v\", err)\n\t} else {\n\t\tif err = retry.Retry(func() error { return m.CacheClient(ctx).Delete(ctx, nameIdx) }); err != nil {\n\t\t\tlog.Errorf(\"delete project cache key %s error: %v\", nameIdx, err)\n\t\t}\n\t}\n}", "func (agg *CompositionHandler) purgeCacheEntries(results []*FetchResult) {\n\tif agg.cache != nil {\n\t\thashes := []string{}\n\t\tfor _, r := range results {\n\t\t\thashes = append(hashes, r.Hash)\n\t\t}\n\t\tagg.cache.PurgeEntries(hashes)\n\t}\n}", "func (c *Cache) startCleanExpireOldestCache() {\n\tif c.TTL <= 1 {\n\t\treturn\n\t}\n\ttimer := time.NewTimer(time.Second)\n\tgo func(timer *time.Timer) {\n\t\tc.cleanExpireOldestCacheByTTL(time.Now().UnixNano())\n\t\t<-timer.C\n\t}(timer)\n\ttimer.Reset(0 * time.Second)\n\ttime.Sleep(time.Second * time.Duration(c.TTL))\n}", "func (p *PCache) Delete(kind string, in interface{}) error {\n\t// Deletes from cache and statemgr\n\tobj, err := runtime.GetObjectMeta(in)\n\tkey := obj.GetKey()\n\tif err != nil {\n\t\treturn fmt.Errorf((\"Object is not an apiserver object\"))\n\t}\n\tp.Log.Debugf(\"delete for %s %s\", kind, key)\n\n\terr = p.DeletePcache(kind, in)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp.RLock()\n\tkindInfo := p.kindOptsMap[kind]\n\tp.RUnlock()\n\n\tif kindInfo.WriteToApiserver {\n\t\tp.Log.Debugf(\"%s %s attempting to delete from statemgr\", kind, key)\n\t\treturn p.deleteStatemgr(in, kindInfo)\n\t}\n\treturn nil\n}" ]
[ "0.59239215", "0.5893977", "0.5852919", "0.57557946", "0.5753789", "0.57387537", "0.5660528", "0.56358516", "0.5580647", "0.55107117", "0.5499004", "0.5466926", "0.5453181", "0.5448278", "0.5439637", "0.54331803", "0.54274124", "0.5405689", "0.5400262", "0.5375354", "0.5371388", "0.5363747", "0.53605866", "0.53589517", "0.53414065", "0.5335511", "0.5334247", "0.53308874", "0.53254724", "0.5318388", "0.5315852", "0.5314884", "0.5297649", "0.5289876", "0.5282364", "0.52819544", "0.52773225", "0.5268844", "0.526493", "0.52606994", "0.5259667", "0.52580553", "0.5255546", "0.5241674", "0.5238326", "0.5231318", "0.5224867", "0.5223102", "0.52004", "0.51944613", "0.5193795", "0.51933944", "0.51889247", "0.5170484", "0.51638055", "0.5163715", "0.5163575", "0.51632625", "0.5159143", "0.51586485", "0.5158162", "0.5146748", "0.51462793", "0.51378584", "0.51374793", "0.51358026", "0.5135368", "0.5131487", "0.5126854", "0.51170075", "0.5113539", "0.5113039", "0.5111012", "0.5105696", "0.50937235", "0.50908154", "0.50898594", "0.5089283", "0.50825995", "0.508161", "0.50777215", "0.5077525", "0.5076167", "0.5074775", "0.50567627", "0.5049755", "0.50475", "0.50448483", "0.5044384", "0.5034357", "0.50301325", "0.5027039", "0.5025329", "0.5023219", "0.5022629", "0.5021018", "0.50185925", "0.50180495", "0.50174886", "0.50137395" ]
0.5960881
0
NewDinnerHostPtr creates a new, initialized DinnerHost object and returns a pointer to it.
func NewDinnerHostPtr(tableCount, maxParallel, maxDinner int) *DinnerHost { host := new(DinnerHost) host.Init(tableCount, maxParallel, maxDinner) return host }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func New(tb testing.TB, settings hostdb.HostSettings, wm host.Wallet, tpool host.TransactionPool) *Host {\n\ttb.Helper()\n\tl, err := net.Listen(\"tcp\", \":0\")\n\tif err != nil {\n\t\ttb.Fatal(err)\n\t}\n\ttb.Cleanup(func() { l.Close() })\n\tsettings.NetAddress = modules.NetAddress(l.Addr().String())\n\tsettings.UnlockHash, err = wm.Address()\n\tif err != nil {\n\t\ttb.Fatal(err)\n\t}\n\tkey := ed25519.NewKeyFromSeed(frand.Bytes(ed25519.SeedSize))\n\th := &Host{\n\t\tPublicKey: hostdb.HostKeyFromPublicKey(ed25519hash.ExtractPublicKey(key)),\n\t\tSettings: settings,\n\t\tl: l,\n\t}\n\tcs := newEphemeralContractStore(key)\n\tss := newEphemeralSectorStore()\n\tsh := host.NewSessionHandler(key, (*constantHostSettings)(&h.Settings), cs, ss, wm, tpool, nopMetricsRecorder{})\n\tgo listen(sh, l)\n\th.cw = host.NewChainWatcher(tpool, wm, cs, ss)\n\treturn h\n}", "func NewDeleteHost(rt *runtime.Runtime) operations.DeleteHostHandler {\n\treturn &deleteHost{rt: rt}\n}", "func NewHost(addr Address, peerCount, channelLimit uint64, incomingBandwidth, outgoingBandwidth uint32) (Host, error) {\n\tvar cAddr *C.struct__ENetAddress\n\tif addr != nil {\n\t\tcAddr = &(addr.(*enetAddress)).cAddr\n\t}\n\n\thost := C.enet_host_create(\n\t\tcAddr,\n\t\t(C.size_t)(peerCount),\n\t\t(C.size_t)(channelLimit),\n\t\t(C.enet_uint32)(incomingBandwidth),\n\t\t(C.enet_uint32)(outgoingBandwidth),\n\t)\n\n\tif host == nil {\n\t\treturn nil, errors.New(\"unable to create host\")\n\t}\n\n\treturn &enetHost{\n\t\tcHost: host,\n\t}, nil\n}", "func NewMockhost(ctrl *gomock.Controller) *Mockhost {\n\tmock := &Mockhost{ctrl: ctrl}\n\tmock.recorder = &MockhostMockRecorder{mock}\n\treturn mock\n}", "func NewMockHost(ctrl *gomock.Controller) *MockHost {\n\tmock := &MockHost{ctrl: ctrl}\n\tmock.recorder = &MockHostMockRecorder{mock}\n\treturn mock\n}", "func NewPerHost(defaultDialer, bypass Dialer) *PerHost {\n\treturn &PerHost{\n\t\tdef: defaultDialer,\n\t\tbypass: bypass,\n\t}\n}", "func New(me protocol.PeerAddress, codec protocol.PeerAddressCodec, store kv.Table, bootstrapAddrs ...protocol.PeerAddress) (DHT, error) {\n\t// Validate input parameters\n\tif me == nil {\n\t\tpanic(\"pre-condition violation: self PeerAddress cannot be nil\")\n\t}\n\tif codec == nil {\n\t\tpanic(\"pre-condition violation: PeerAddressCodec cannot be nil\")\n\t}\n\n\t// Create a in-memory store if user doesn't provide one.\n\tif store == nil {\n\t\tstore = kv.NewTable(kv.NewMemDB(kv.GobCodec), \"dht\")\n\t}\n\n\tdht := &dht{\n\t\tme: me,\n\t\tcodec: codec,\n\t\tstore: store,\n\n\t\tgroupsMu: new(sync.RWMutex),\n\t\tgroups: map[protocol.GroupID]protocol.PeerIDs{},\n\n\t\tinMemCacheMu: new(sync.RWMutex),\n\t\tinMemCache: map[string]protocol.PeerAddress{},\n\t}\n\n\tif err := dht.fillInMemCache(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn dht, dht.addBootstrapNodes(bootstrapAddrs)\n}", "func NewHost(host string) Host {\n\treturn Host(host)\n}", "func New(opts ...Option) (*DHTClient, error) {\n\tvar err error\n\tdhtClient := &DHTClient{}\n\n\tfor _, opt := range opts {\n\t\tif err := opt(dhtClient); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tdhtClient.closing = make(chan struct{})\n\n\t/* check correct configuration */\n\n\t// private key\n\tif dhtClient.key == nil {\n\t\treturn nil, errors.New(\"private key must be provided\")\n\t}\n\n\t// agent address is mandatory\n\tif dhtClient.myAgentAddress == \"\" {\n\t\treturn nil, errors.New(\"missing agent address\")\n\t}\n\n\t// agent record is mandatory\n\tif dhtClient.myAgentRecord == nil {\n\t\treturn nil, errors.New(\"missing agent record\")\n\t}\n\n\t// check if the PoR is delivered for my public key\n\tmyPublicKey, err := utils.FetchAIPublicKeyFromPubKey(dhtClient.publicKey)\n\tstatus, errPoR := dhtnode.IsValidProofOfRepresentation(\n\t\tdhtClient.myAgentRecord,\n\t\tdhtClient.myAgentRecord.Address,\n\t\tmyPublicKey,\n\t)\n\tif err != nil || errPoR != nil || status.Code != acn.SUCCESS {\n\t\tmsg := \"Invalid AgentRecord\"\n\t\tif err != nil {\n\t\t\tmsg += \" - \" + err.Error()\n\t\t}\n\t\tif errPoR != nil {\n\t\t\tmsg += \" - \" + errPoR.Error()\n\t\t}\n\t\treturn nil, errors.New(msg)\n\t}\n\n\t// bootstrap peers\n\tif len(dhtClient.bootstrapPeers) < 1 {\n\t\treturn nil, errors.New(\"at least one boostrap peer should be provided\")\n\t}\n\n\t// select a relay node randomly from entry peers\n\trand.Seed(time.Now().Unix())\n\tindex := rand.Intn(len(dhtClient.bootstrapPeers))\n\tdhtClient.relayPeer = dhtClient.bootstrapPeers[index].ID\n\n\tdhtClient.setupLogger()\n\t_, _, linfo, ldebug := dhtClient.GetLoggers()\n\tlinfo().Msg(\"INFO Using as relay\")\n\n\t/* setup libp2p node */\n\tctx := context.Background()\n\n\t// libp2p options\n\tlibp2pOpts := []libp2p.Option{\n\t\tlibp2p.ListenAddrs(),\n\t\tlibp2p.Identity(dhtClient.key),\n\t\tlibp2p.DefaultTransports,\n\t\tlibp2p.DefaultMuxers,\n\t\tlibp2p.DefaultSecurity,\n\t\tlibp2p.NATPortMap(),\n\t\tlibp2p.EnableNATService(),\n\t\tlibp2p.EnableRelay(),\n\t}\n\n\t// create a basic host\n\tbasicHost, err := libp2p.New(ctx, libp2pOpts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create the dht\n\tdhtClient.dht, err = kaddht.New(ctx, basicHost, kaddht.Mode(kaddht.ModeClient))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// make the routed host\n\tdhtClient.routedHost = routedhost.Wrap(basicHost, dhtClient.dht)\n\tdhtClient.setupLogger()\n\n\t// connect to the booststrap nodes\n\terr = dhtClient.bootstrapLoopUntilTimeout()\n\tif err != nil {\n\t\tdhtClient.Close()\n\t\treturn nil, err\n\t}\n\n\t// bootstrap the host\n\terr = dhtClient.dht.Bootstrap(ctx)\n\tif err != nil {\n\t\tdhtClient.Close()\n\t\treturn nil, err\n\t}\n\n\t// register my address to relay peer\n\terr = dhtClient.registerAgentAddress()\n\tif err != nil {\n\t\tdhtClient.Close()\n\t\treturn nil, err\n\t}\n\n\tdhtClient.routedHost.Network().Notify(&Notifee{\n\t\tmyRelayPeer: dhtClient.bootstrapPeers[index],\n\t\tmyHost: dhtClient.routedHost,\n\t\tlogger: dhtClient.logger,\n\t\tclosing: dhtClient.closing,\n\t})\n\n\t/* setup DHTClient message handlers */\n\n\t// aea address lookup\n\tldebug().Msg(\"DEBUG Setting /aea-address/0.1.0 stream...\")\n\tdhtClient.routedHost.SetStreamHandler(dhtnode.AeaAddressStream,\n\t\tdhtClient.handleAeaAddressStream)\n\n\t// incoming envelopes stream\n\tldebug().Msg(\"DEBUG Setting /aea/0.1.0 stream...\")\n\tdhtClient.routedHost.SetStreamHandler(dhtnode.AeaEnvelopeStream,\n\t\tdhtClient.handleAeaEnvelopeStream)\n\n\treturn dhtClient, nil\n}", "func NewHostHandler() *HostHandler {\n\th := &HostHandler{\n\t\teligibleHosts: make(map[string]*http.ServeMux),\n\t}\n\n\treturn h\n}", "func (p *Proxy) NewHost(c *exec.Cmd) (*Host, error) {\n\th := &Host{\n\t\tcmd: c,\n\t\tproxy: p,\n\t}\n\tvar err error\n\th.httpTransfer, h.httpsTransfer, err = h.setupCmd(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn h, nil\n}", "func newTestingHost(testdir string, cs modules.ConsensusSet, tp modules.TransactionPool) (modules.Host, error) {\n\tg, err := gateway.New(\"localhost:0\", false, filepath.Join(testdir, modules.GatewayDir), false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tw, err := newTestingWallet(testdir, cs, tp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\th, err := host.New(cs, g, tp, w, \"localhost:0\", filepath.Join(testdir, modules.HostDir))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// configure host to accept contracts\n\tsettings := h.InternalSettings()\n\tsettings.AcceptingContracts = true\n\terr = h.SetInternalSettings(settings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// add storage to host\n\tstorageFolder := filepath.Join(testdir, \"storage\")\n\terr = os.MkdirAll(storageFolder, 0700)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = h.AddStorageFolder(storageFolder, modules.SectorSize*64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn h, nil\n}", "func NewHost(clusterName string, mainCfg conf.Main, hostCfg conf.Host, lg *zap.Logger, ms *metrics.Prom) *Host {\n\ttargetPort := mainCfg.TargetPort\n\tif hostCfg.Port != 0 {\n\t\ttargetPort = hostCfg.Port\n\t}\n\n\tpromLabels := prometheus.Labels{\n\t\t\"cluster\": clusterName,\n\t\t\"upstream_host\": hostCfg.Name,\n\t}\n\treturn &Host{\n\t\tName: hostCfg.Name,\n\t\tPort: targetPort,\n\t\tCh: make(chan *rec.Rec, mainCfg.HostQueueSize),\n\t\tLg: lg,\n\t\tstop: make(chan int),\n\n\t\tSendTimeoutSec: mainCfg.SendTimeoutSec,\n\t\tConnTimeoutSec: mainCfg.OutConnTimeoutSec,\n\t\tTCPOutBufFlushPeriodSec: mainCfg.TCPOutBufFlushPeriodSec,\n\t\toutRecs: ms.OutRecs.With(promLabels),\n\t\tthrottled: ms.ThrottledHosts.With(promLabels),\n\t\tprocessingDuration: ms.ProcessingDuration,\n\t\tbufSize: mainCfg.TCPOutBufSize,\n\t\tMaxReconnectPeriodMs: mainCfg.MaxHostReconnectPeriodMs,\n\t\tReconnectPeriodDeltaMs: mainCfg.MaxHostReconnectPeriodMs,\n\t}\n}", "func NewHost(address string) (*Host, error) {\n\taddr, err := NewAddress(address)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Failed to create Host\")\n\t}\n\treturn &Host{Address: addr}, nil\n}", "func newDHT(r *Router) *dht {\n\td := &dht{\n\t\tr: r,\n\t\tfinger: make(map[types.PublicKey]dhtEntry),\n\t}\n\treturn d\n}", "func makeRandomHost() (host.Host, *kaddht.IpfsDHT) {\n\tctx := context.Background()\n\tport := 10000 + rand.Intn(10000)\n\n\thost, err := libp2p.New(ctx,\n\t\tlibp2p.ListenAddrStrings(fmt.Sprintf(\"/ip4/0.0.0.0/tcp/%d\", port)),\n\t\tlibp2p.EnableRelay(circuit.OptHop, circuit.OptDiscovery))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Bootstrap the DHT. In the default configuration, this spawns a Background\n\t// thread that will refresh the peer table every five minutes.\n\tdht, err := kaddht.New(ctx, host)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = dht.Bootstrap(ctx)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn host, dht\n}", "func ConfigHostNew() *ConfigHost {\n\th := ConfigHost{\n\t\tTLS: regclient.TLSEnabled,\n\t}\n\treturn &h\n}", "func NewHostNode(ctx context.Context, config Config, blockchain chain.Blockchain) (HostNode, error) {\n\tps := pstoremem.NewPeerstore()\n\tdb, err := NewDatabase(config.Path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = db.Initialize()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpriv, err := db.GetPrivKey()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// get saved hostnode\n\tsavedAddresses, err := db.GetSavedPeers()\n\tif err != nil {\n\t\tconfig.Log.Errorf(\"error retrieving saved hostnode: %s\", err)\n\t}\n\n\tnetAddr, err := net.ResolveTCPAddr(\"tcp\", \"0.0.0.0:\"+config.Port)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlisten, err := mnet.FromNetAddr(netAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlistenAddress := []multiaddr.Multiaddr{listen}\n\n\t//append saved addresses\n\tlistenAddress = append(listenAddress, savedAddresses...)\n\n\th, err := libp2p.New(\n\t\tctx,\n\t\tlibp2p.ListenAddrs(listenAddress...),\n\t\tlibp2p.Identity(priv),\n\t\tlibp2p.EnableRelay(),\n\t\tlibp2p.Peerstore(ps),\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taddrs, err := peer.AddrInfoToP2pAddrs(&peer.AddrInfo{\n\t\tID: h.ID(),\n\t\tAddrs: listenAddress,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, a := range addrs {\n\t\tconfig.Log.Infof(\"binding to address: %s\", a)\n\t}\n\n\t// setup gossip sub protocol\n\tg, err := pubsub.NewGossipSub(ctx, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnode := &hostNode{\n\t\tprivateKey: config.PrivateKey,\n\t\thost: h,\n\t\tgossipSub: g,\n\t\tctx: ctx,\n\t\ttimeoutInterval: timeoutInterval,\n\t\theartbeatInterval: heartbeatInterval,\n\t\tlog: config.Log,\n\t\ttopics: map[string]*pubsub.Topic{},\n\t\tdb: db,\n\t}\n\n\tdiscovery, err := NewDiscoveryProtocol(ctx, node, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnode.discoveryProtocol = discovery\n\n\tsyncProtocol, err := NewSyncProtocol(ctx, node, config, blockchain)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnode.syncProtocol = syncProtocol\n\n\treturn node, nil\n}", "func NewPhilosopherPtr(name string) *Philosopher {\n\tphi := new(Philosopher)\n\tphi.Init(name)\n\treturn phi\n}", "func NewHostN(address string, nodeID core.RecordRef) (*Host, error) {\n\th, err := NewHost(address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\th.NodeID = nodeID\n\treturn h, nil\n}", "func newPeer(host topology.Host, dialer client.PeerConnDialer) *peer {\n\treturn &peer{\n\t\thost: host,\n\t\tdialer: dialer,\n\t}\n}", "func NewHost(config v2.Host, clusterInfo types.ClusterInfo) types.Host {\n\taddr, _ := net.ResolveTCPAddr(\"tcp\", config.Address)\n\n\treturn &host{\n\t\thostInfo: newHostInfo(addr, config, clusterInfo),\n\t\tweight: config.Weight,\n\t}\n}", "func NewCandidateHost(config *CandidateHostConfig) (*CandidateHost, error) {\n\tcandidateID := config.CandidateID\n\n\tif candidateID == \"\" {\n\t\tcandidateID = globalCandidateIDGenerator.Generate()\n\t}\n\n\tc := &CandidateHost{\n\t\tcandidateBase: candidateBase{\n\t\t\tid: candidateID,\n\t\t\taddress: config.Address,\n\t\t\tcandidateType: CandidateTypeHost,\n\t\t\tcomponent: config.Component,\n\t\t\tport: config.Port,\n\t\t\ttcpType: config.TCPType,\n\t\t\tfoundationOverride: config.Foundation,\n\t\t\tpriorityOverride: config.Priority,\n\t\t\tremoteCandidateCaches: map[AddrPort]Candidate{},\n\t\t},\n\t\tnetwork: config.Network,\n\t}\n\n\tif !strings.HasSuffix(config.Address, \".local\") {\n\t\tip := net.ParseIP(config.Address)\n\t\tif ip == nil {\n\t\t\treturn nil, ErrAddressParseFailed\n\t\t}\n\n\t\tif err := c.setIP(ip); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\t// Until mDNS candidate is resolved assume it is UDPv4\n\t\tc.candidateBase.networkType = NetworkTypeUDP4\n\t}\n\n\treturn c, nil\n}", "func newVHostTrie() *vhostTrie {\n\treturn &vhostTrie{edges: make(map[string]*vhostTrie), fallbackHosts: []string{\"0.0.0.0\", \"\"}}\n}", "func New(address string, port int) *Host {\n\thost := Host{\n\t\taddress: address,\n\t\tport: port,\n\t}\n\treturn &host\n}", "func NewMockDHTKeeper(ctrl *gomock.Controller) *MockDHTKeeper {\n\tmock := &MockDHTKeeper{ctrl: ctrl}\n\tmock.recorder = &MockDHTKeeperMockRecorder{mock}\n\treturn mock\n}", "func NewHost(ip net.IP, hostname string, aliases ...string) Host {\n\treturn Host{\n\t\tIP: ip,\n\t\tHostname: hostname,\n\t\tAliases: aliases,\n\t}\n}", "func NewHost(uri string) Host {\n\t// no need to decompose uri using net/url package\n\treturn Host{uri: uri, client: http.Client{}}\n}", "func NewHost(hostLine string) (*Host, error) {\n\tptn := regexp.MustCompile(HostLineFmtRegexp)\n\tdata := ptn.FindStringSubmatch(hostLine)\n\tif len(data) != 3 {\n\t\treturn nil, errors.New(\"Parse failed\")\n\t}\n\n\treturn &Host{data[1], data[2]}, nil\n}", "func NewHosts(hosts ...Host) *Hosts {\n\treturn &Hosts{\n\t\thosts: hosts,\n\t\tstopped: make(chan struct{}),\n\t}\n}", "func NewHost(ctx *pulumi.Context,\n\tname string, args *HostArgs, opts ...pulumi.ResourceOption) (*Host, error) {\n\tif args == nil || args.Hostname == nil {\n\t\treturn nil, errors.New(\"missing required argument 'Hostname'\")\n\t}\n\tif args == nil || args.Password == nil {\n\t\treturn nil, errors.New(\"missing required argument 'Password'\")\n\t}\n\tif args == nil || args.Username == nil {\n\t\treturn nil, errors.New(\"missing required argument 'Username'\")\n\t}\n\tif args == nil {\n\t\targs = &HostArgs{}\n\t}\n\tvar resource Host\n\terr := ctx.RegisterResource(\"vsphere:index/host:Host\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewDHTModule(cfg *config.AppConfig, dht dht2.DHT) *DHTModule {\n\treturn &DHTModule{cfg: cfg, dht: dht}\n}", "func createHost(port int) (core.Host, error) {\n\t// Producing private key\n\tprvKey, _ := ecdsa.GenerateKey(btcec.S256(), rand.Reader)\n\tsk := (*crypto.Secp256k1PrivateKey)(prvKey)\n\n\t// Starting a peer with default configs\n\topts := []libp2p.Option{\n\t\tlibp2p.ListenAddrStrings(fmt.Sprintf(\"/ip4/0.0.0.0/tcp/%d\", port)),\n\t\tlibp2p.Identity(sk),\n\t\tlibp2p.DefaultTransports,\n\t\tlibp2p.DefaultMuxers,\n\t\tlibp2p.DefaultSecurity,\n\t}\n\n\th, err := libp2p.New(context.Background(), opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn h, nil\n}", "func NewHost(conf Config, middlewares ...Middleware) (host *Host) {\n\thost = &Host{\n\t\thandlers: map[string]*endpoint{},\n\t\tconf: conf,\n\n\t\tbasepath: \"\",\n\t\tmstack: middlewares,\n\t}\n\tif !conf.DisableAutoReport {\n\t\tos.Stdout.WriteString(\"Registration Info:\\r\\n\")\n\t}\n\thost.initCheck()\n\treturn\n}", "func NewHostNS(address string, nodeID core.RecordRef, shortID core.ShortNodeID) (*Host, error) {\n\th, err := NewHostN(address, nodeID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\th.ShortID = shortID\n\treturn h, nil\n}", "func NewDHT(store Store, options *Options) (*DHT, error) {\n\t// validate the options, if it's invalid, set them to default value\n\tif options.IP == \"\" {\n\t\toptions.IP = defaultNetworkAddr\n\t}\n\tif options.Port <= 0 {\n\t\toptions.Port = defaultNetworkPort\n\t}\n\n\ts := &DHT{\n\t\tstore: store,\n\t\toptions: options,\n\t\tdone: make(chan struct{}),\n\t}\n\t// new a hashtable with options\n\tht, err := NewHashTable(options)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"new hashtable: %v\", err)\n\t}\n\ts.ht = ht\n\n\t// new network service for dht\n\tnetwork, err := NewNetwork(s, ht.self)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"new network: %v\", err)\n\t}\n\ts.network = network\n\n\treturn s, nil\n}", "func NewHandle() *Handle {\n\n\tvar handle C.cudnnHandle_t\n\n\terr := Status(C.cudnnCreate(&handle)).error(\"NewHandle\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tvar handler = &Handle{x: handle}\n\truntime.SetFinalizer(handler, destroyhandle)\n\treturn handler\n}", "func NewHostNetworkMock(t minimock.Tester) *HostNetworkMock {\n\tm := &HostNetworkMock{t: t}\n\n\tif controller, ok := t.(minimock.MockController); ok {\n\t\tcontroller.RegisterMocker(m)\n\t}\n\n\tm.BuildResponseMock = mHostNetworkMockBuildResponse{mock: m}\n\tm.GetNodeIDMock = mHostNetworkMockGetNodeID{mock: m}\n\tm.NewRequestBuilderMock = mHostNetworkMockNewRequestBuilder{mock: m}\n\tm.PublicAddressMock = mHostNetworkMockPublicAddress{mock: m}\n\tm.RegisterRequestHandlerMock = mHostNetworkMockRegisterRequestHandler{mock: m}\n\tm.SendRequestMock = mHostNetworkMockSendRequest{mock: m}\n\tm.StartMock = mHostNetworkMockStart{mock: m}\n\tm.StopMock = mHostNetworkMockStop{mock: m}\n\n\treturn m\n}", "func (c *Libp2pPubSub) CreatePeer(nodeId int, port int) *core.Host {\n\t// Creating a node\n\th, err := createHost(port)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Printf(\"Node %v is %s\\n\", nodeId, GetLocalhostAddress(h))\n\n\treturn &h\n}", "func NewHostportManager(iptables utiliptables.Interface) HostPortManager {\n\th := &hostportManager{\n\t\thostPortMap: make(map[hostport]closeable),\n\t\tiptables: iptables,\n\t\tportOpener: openLocalPort,\n\t}\n\n\treturn h\n}", "func CreateDinner(date string, venue string, hostName string, attendeeNames []string) (model.Dinner, error) {\n\tdateTime, err := time.Parse(model.DateFormat, date)\n\tif err != nil {\n\t\treturn model.Dinner{}, err\n\t}\n\n\trow, err := database.InsertDinner(dateTime, venue, hostName)\n\tif err != nil {\n\t\treturn model.Dinner{}, err\n\t}\n\n\tdinner, err := model.NewDinnerFromMap(row)\n\tif err != nil {\n\t\treturn dinner, err\n\t}\n\n\tdinner.Attended, err = database.InsertGuests(dinner.ID, attendeeNames)\n\treturn dinner, err\n}", "func New() provider.Provider {\n\treturn &hostingdeProvider{}\n}", "func NewHostDevCni(typeOfVlan string, logger logr.Logger) *HostDevCni {\n\treturn &HostDevCni{VlanType: typeOfVlan,\n\t\tLog: logger}\n}", "func NewDedicatedHostsClient(con *armcore.Connection, subscriptionID string) *DedicatedHostsClient {\n\treturn &DedicatedHostsClient{con: con, subscriptionID: subscriptionID}\n}", "func NewNode(port int) dhtNode {\n\t// Todo: create a node and then return it.\n\treturn dht.NewSurface(port)\n}", "func NewNode(port int) (host.Host, error) {\n\n\topts := []libp2p.Option{\n\t\tlibp2p.ListenAddrStrings(fmt.Sprintf(\"/ip4/127.0.0.1/tcp/%d\", port)),\n\t}\n\n\th, err := libp2p.New(context.Background(), opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taddr := h.Addrs()[0]\n\tmaAddr, _ := ma.NewMultiaddr(fmt.Sprintf(\"/%s/%s\", protocolVersion, h.ID().Pretty()))\n\tfullAddr := addr.Encapsulate(maAddr)\n\tfmt.Println(\"I am running at addr: \", maAddr)\n\tfmt.Println(\"The full addr is: \", fullAddr)\n\treturn h, err\n}", "func NewHostAddress(host string, port uint16) *HostAddress {\n\treturn &HostAddress{host: host, port: port}\n}", "func newVdpaDpdkServer() *vdpaDpdkServer {\n\ts := &vdpaDpdkServer{\n\t\tgrpcServer: grpc.NewServer(),\n\t}\n\ts.loadInterfaces(*socketlist)\n\treturn s\n}", "func NewNodeHostWithMasterClientFactory(nhConfig config.NodeHostConfig,\n\tfactory MasterClientFactoryFunc) *NodeHost {\n\tlogBuildTagsAndVersion()\n\tif err := nhConfig.Validate(); err != nil {\n\t\tplog.Panicf(\"invalid nodehost config, %v\", err)\n\t}\n\tnh := &NodeHost{\n\t\tserverCtx: server.NewContext(nhConfig),\n\t\tnhConfig: nhConfig,\n\t\tstopper: syncutil.NewStopper(),\n\t\tduStopper: syncutil.NewStopper(),\n\t\tnodes: transport.NewNodes(streamConnections),\n\t\tinitializedC: make(chan struct{}),\n\t\ttransportLatency: newSample(),\n\t}\n\tnh.snapshotStatus = newSnapshotFeedback(nh.pushSnapshotStatus)\n\tnh.msgHandler = newNodeHostMessageHandler(nh)\n\tnh.clusterMu.requests = make(map[uint64]*server.MessageQueue)\n\tnh.createPools()\n\tnh.createTransport()\n\tif nhConfig.MasterMode() {\n\t\tplog.Infof(\"master servers specified, creating the master client\")\n\t\tnh.masterClient = newMasterClient(nh, factory)\n\t\tplog.Infof(\"master client type: %s\", nh.masterClient.Name())\n\t} else {\n\t\tplog.Infof(\"no master server specified, running in standalone mode\")\n\t\tdid := unmanagedDeploymentID\n\t\tif nhConfig.DeploymentID == 0 {\n\t\t\tplog.Warningf(\"DeploymentID not set in NodeHostConfig\")\n\t\t\tnh.transport.SetUnmanagedDeploymentID()\n\t\t} else {\n\t\t\tdid = nhConfig.DeploymentID\n\t\t\tnh.transport.SetDeploymentID(nhConfig.DeploymentID)\n\t\t}\n\t\tplog.Infof(\"DeploymentID set to %d\", unmanagedDeploymentID)\n\t\tnh.deploymentID = did\n\t\tnh.createLogDB(nhConfig, did)\n\t}\n\tctx, cancel := context.WithCancel(context.Background())\n\tnh.cancel = cancel\n\tinitializeFn := func() {\n\t\tif err := nh.initialize(ctx, nhConfig); err != nil {\n\t\t\tif err != context.Canceled && err != ErrCanceled {\n\t\t\t\tplog.Panicf(\"nh.initialize failed %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\tif nh.masterMode() {\n\t\tplog.Infof(\"master mode, nh.initialize() invoked in new goroutine\")\n\t\tnh.stopper.RunWorker(func() {\n\t\t\tinitializeFn()\n\t\t})\n\t} else {\n\t\tplog.Infof(\"standalone mode, nh.initialize() directly invoked\")\n\t\tinitializeFn()\n\t}\n\tnh.stopper.RunWorker(func() {\n\t\tnh.masterRequestHandler(ctx)\n\t})\n\t// info reporting worker is using a different stopper as we need to stop it\n\t// separately during monkey test\n\tnh.duStopper.RunWorker(func() {\n\t\tnh.reportingWorker(ctx)\n\t})\n\tnh.stopper.RunWorker(func() {\n\t\tnh.nodeMonitorMain(ctx, nhConfig)\n\t})\n\tnh.stopper.RunWorker(func() {\n\t\tnh.tickWorkerMain()\n\t})\n\tif nh.masterMode() {\n\t\tnh.waitUntilInitialized()\n\t}\n\tnh.logNodeHostDetails()\n\treturn nh\n}", "func createHostWithIp(nodeId int, ip string, port int) (core.Host, error) {\n\t// Producing private key using nodeId\n\tr := mrand.New(mrand.NewSource(int64(nodeId)))\n\n\tprvKey, _ := ecdsa.GenerateKey(btcec.S256(), r)\n\tsk := (*crypto.Secp256k1PrivateKey)(prvKey)\n\n\t// Starting a peer with default configs\n\topts := []libp2p.Option{\n\t\tlibp2p.ListenAddrStrings(fmt.Sprintf(\"/ip4/0.0.0.0/tcp/%s\", strconv.Itoa(port))),\n\t\tlibp2p.Identity(sk),\n\t\tlibp2p.DefaultTransports,\n\t\tlibp2p.DefaultMuxers,\n\t\tlibp2p.DefaultSecurity,\n\t}\n\n\th, err := libp2p.New(context.Background(), opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn h, nil\n}", "func createHostWebSocket(port int) (core.Host, error) {\n\n\t// Starting a peer with QUIC transport\n\topts := []libp2p.Option{\n\t\tlibp2p.ListenAddrStrings(fmt.Sprintf(\"/ip4/0.0.0.0/udp/%d/quic\", port)),\n\t\tlibp2p.ListenAddrStrings(fmt.Sprintf(\"/ip4/0.0.0.0/tcp/%d/ws\", port)),\n\t\tlibp2p.Transport(ws.New),\n\t\tlibp2p.DefaultMuxers,\n\t\tlibp2p.DefaultSecurity,\n\t}\n\n\th, err := libp2p.New(context.Background(), opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn h, nil\n}", "func IpRemoteHost_NewServer(s IpRemoteHost_Server, policy *server.Policy) *server.Server {\n\tc, _ := s.(server.Shutdowner)\n\treturn server.New(IpRemoteHost_Methods(nil, s), s, c, policy)\n}", "func NewHandle(ctx *cuda.Context) (*Handle, error) {\n\tres := &Handle{ctx: ctx, ptrMode: Host}\n\terr := newError(\"cublasCreate\", C.cublasCreate(&res.handle))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\truntime.SetFinalizer(res, func(obj *Handle) {\n\t\tgo obj.ctx.Run(func() error {\n\t\t\tC.cublasDestroy(obj.handle)\n\t\t\treturn nil\n\t\t})\n\t})\n\treturn res, nil\n}", "func (cfg *SshegoConfig) NewEsshd() *Esshd {\n\tp(\"top of SshegoConfig.NewEsshd()...\")\n\tsrv := &Esshd{\n\t\tcfg: cfg,\n\t\tHalt: *idem.NewHalter(),\n\t\taddUserToDatabase: make(chan *User),\n\t\treplyWithCreatedUser: make(chan *User),\n\t\tdelUserReq: make(chan *User),\n\t\treplyWithDeletedDone: make(chan bool),\n\t\tupdateHostKey: make(chan ssh.Signer),\n\t}\n\tif srv.cfg.HostDb == nil {\n\t\terr := srv.cfg.NewHostDb()\n\t\tpanicOn(err)\n\t}\n\tcfg.Esshd = srv\n\treturn srv\n}", "func NewHost(conf config.Config) CurrentHost {\n\treturn &currentHostInfo{\n\t\thostName: conf.HostName,\n\t\tnextHostAddress: conf.NextHostAddress,\n\t\tnextHostPort: conf.NextHostPort,\n\t}\n}", "func NewHostMonitor(duration time.Duration) (pkg.HostMonitor, error) {\n\tif duration == 0 {\n\t\tduration = 2 * time.Second\n\t}\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to initialize fs watcher\")\n\t}\n\n\t// the file can not exist if the system was booted from overlay\n\tif _, err := os.Stat(upgrade.FlistInfoFile); err == nil {\n\t\tif err := watcher.Add(upgrade.FlistInfoFile); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to watch '%s'\", upgrade.FlistInfoFile)\n\t\t}\n\t}\n\n\treturn &hostMonitor{\n\t\tduration: duration,\n\t}, nil\n}", "func NewDoHClient(nameserver string, allowInsecure bool) (*DoHClient, error) {\n\tnsURL, err := url.Parse(nameserver)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif nsURL.Scheme != \"https\" {\n\t\terr = fmt.Errorf(\"DoH name server must be HTTPS\")\n\t\treturn nil, err\n\t}\n\n\ttr := &http.Transport{\n\t\tMaxIdleConns: 1,\n\t\tIdleConnTimeout: 30 * time.Second,\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tInsecureSkipVerify: allowInsecure,\n\t\t},\n\t}\n\n\tcl := &DoHClient{\n\t\taddr: nsURL,\n\t\theaders: http.Header{\n\t\t\t\"accept\": []string{\n\t\t\t\t\"application/dns-message\",\n\t\t\t},\n\t\t},\n\t\tquery: nsURL.Query(),\n\t\tconn: &http.Client{\n\t\t\tTransport: tr,\n\t\t\tTimeout: clientTimeout,\n\t\t},\n\t}\n\n\tcl.req = &http.Request{\n\t\tMethod: http.MethodGet,\n\t\tURL: nsURL,\n\t\tProto: \"HTTP/2\",\n\t\tProtoMajor: 2,\n\t\tProtoMinor: 0,\n\t\tHeader: cl.headers,\n\t\tBody: nil,\n\t\tHost: nsURL.Hostname(),\n\t}\n\n\treturn cl, nil\n}", "func New(apiKey, apiSecret string) *Hbdm {\n\tclient := NewHttpClient(apiKey, apiSecret)\n\treturn &Hbdm{client, sync.Mutex{}}\n}", "func NewNodeHost(nhConfig config.NodeHostConfig) *NodeHost {\n\treturn NewNodeHostWithMasterClientFactory(nhConfig, nil)\n}", "func New(hc *hydra.Client) *EchoGK {\n\treturn &EchoGK{\n\t\thc: hc,\n\t}\n}", "func newPeer(server *server, name string, connectionString string, heartbeatInterval time.Duration) *Peer {\n\treturn &Peer{\n\t\tserver: server,\n\t\tName: name,\n\t\tConnectionString: connectionString,\n\t\theartbeatInterval: heartbeatInterval,\n\t}\n}", "func newPhilosopherDataPtr(respChannel chan string) *philosopherData {\n\tpd := new(philosopherData)\n\tpd.Init(respChannel)\n\treturn pd\n}", "func New(\n\tdatabaseContext model.DBReader,\n\tdagTopologyManager model.DAGTopologyManager,\n\tghostdagDataStore model.GHOSTDAGDataStore,\n\theaderStore model.BlockHeaderStore,\n\tk model.KType) model.GHOSTDAGManager {\n\n\treturn &ghostdagHelper{\n\t\tdbAccess: databaseContext,\n\t\tdagTopologyManager: dagTopologyManager,\n\t\tdataStore: ghostdagDataStore,\n\t\theaderStore: headerStore,\n\t\tk: k,\n\t}\n}", "func NewDisableHostOK() *DisableHostOK {\n\treturn &DisableHostOK{}\n}", "func NewDedicatedHostsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) *DedicatedHostsClient {\n\tcp := arm.ClientOptions{}\n\tif options != nil {\n\t\tcp = *options\n\t}\n\tif len(cp.Host) == 0 {\n\t\tcp.Host = arm.AzurePublicCloud\n\t}\n\treturn &DedicatedHostsClient{subscriptionID: subscriptionID, ep: string(cp.Host), pl: armruntime.NewPipeline(module, version, credential, &cp)}\n}", "func NewPinner(dstore ds.ThreadSafeDatastore, serv mdag.DAGService) Pinner {\n\n\t// Load set from given datastore...\n\trcset := set.NewSimpleBlockSet()\n\n\tdirset := set.NewSimpleBlockSet()\n\n\treturn &pinner{\n\t\trecursePin: rcset,\n\t\tdirectPin: dirset,\n\t\tindirPin: newIndirectPin(),\n\t\tdserv: serv,\n\t\tdstore: dstore,\n\t}\n}", "func NewPeer(server *Server, name string, heartbeatTimeout time.Duration) *Peer {\n\tp := &Peer{\n\t\tserver: server,\n\t\tname: name,\n\t\theartbeatTimer: NewTimer(heartbeatTimeout, heartbeatTimeout),\n\t}\n\n\t// Start the heartbeat timeout.\n\tgo p.heartbeatTimeoutFunc()\n\n\treturn p\n}", "func setupKadDHT(ctx context.Context, nodehost host.Host) *dht.IpfsDHT {\n\t// Create DHT server mode option\n\tdhtmode := dht.Mode(dht.ModeServer)\n\t// Rertieve the list of boostrap peer addresses\n\tbootstrappeers := dht.GetDefaultBootstrapPeerAddrInfos()\n\t// Create the DHT bootstrap peers option\n\tdhtpeers := dht.BootstrapPeers(bootstrappeers...)\n\n\t// Trace log\n\tlogrus.Traceln(\"Generated DHT Configuration.\")\n\n\t// Start a Kademlia DHT on the host in server mode\n\tkaddht, err := dht.New(ctx, nodehost, dhtmode, dhtpeers)\n\t// Handle any potential error\n\tif err != nil {\n\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t}).Fatalln(\"Failed to Create the Kademlia DHT!\")\n\t}\n\n\t// Return the KadDHT\n\treturn kaddht\n}", "func NewMockHostEvent(ctrl *gomock.Controller) *MockHostEvent {\n\tmock := &MockHostEvent{ctrl: ctrl}\n\tmock.recorder = &MockHostEventMockRecorder{mock}\n\treturn mock\n}", "func NewNode(host string, size int) Node {\n\treturn node{host: host, size: size}\n}", "func NewHdd() *Hdd {\n\tthis := Hdd{}\n\treturn &this\n}", "func NewDfdd(context *Context, timeSource common.TimeSource) Dfdd {\n\tdfdd := &dfddImpl{\n\t\tcontext: context,\n\t\ttimeSource: timeSource,\n\t\tshutdownC: make(chan struct{}),\n\t\tinputListenerCh: make(chan *common.RingpopListenerEvent, listenerChannelSize),\n\t\tstoreListenerCh: make(chan *common.RingpopListenerEvent, listenerChannelSize),\n\t}\n\tdfdd.inputHosts.Store(make(map[string]dfddHost, 8))\n\tdfdd.storeHosts.Store(make(map[string]dfddHost, 8))\n\treturn dfdd\n}", "func New(instName string, stdout io.Writer, sigintCh chan os.Signal, opts ...Opt) (*HostAgent, error) {\n\tvar o options\n\tfor _, f := range opts {\n\t\tif err := f(&o); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tinst, err := store.Inspect(instName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ty, err := inst.LoadYAML()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// y is loaded with FillDefault() already, so no need to care about nil pointers.\n\n\tsshLocalPort, err := determineSSHLocalPort(y, instName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar udpDNSLocalPort, tcpDNSLocalPort int\n\tif *y.HostResolver.Enabled {\n\t\tudpDNSLocalPort, err = findFreeUDPLocalPort()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttcpDNSLocalPort, err = findFreeTCPLocalPort()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif err := cidata.GenerateISO9660(inst.Dir, instName, y, udpDNSLocalPort, tcpDNSLocalPort, o.nerdctlArchive); err != nil {\n\t\treturn nil, err\n\t}\n\n\tsshOpts, err := sshutil.SSHOpts(inst.Dir, *y.SSH.LoadDotSSHPubKeys, *y.SSH.ForwardAgent, *y.SSH.ForwardX11, *y.SSH.ForwardX11Trusted)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err = writeSSHConfigFile(inst, sshLocalPort, sshOpts); err != nil {\n\t\treturn nil, err\n\t}\n\tsshConfig := &ssh.SSHConfig{\n\t\tAdditionalArgs: sshutil.SSHArgsFromOpts(sshOpts),\n\t}\n\n\trules := make([]limayaml.PortForward, 0, 3+len(y.PortForwards))\n\t// Block ports 22 and sshLocalPort on all IPs\n\tfor _, port := range []int{sshGuestPort, sshLocalPort} {\n\t\trule := limayaml.PortForward{GuestIP: net.IPv4zero, GuestPort: port, Ignore: true}\n\t\tlimayaml.FillPortForwardDefaults(&rule, inst.Dir)\n\t\trules = append(rules, rule)\n\t}\n\trules = append(rules, y.PortForwards...)\n\t// Default forwards for all non-privileged ports from \"127.0.0.1\" and \"::1\"\n\trule := limayaml.PortForward{GuestIP: guestagentapi.IPv4loopback1}\n\tlimayaml.FillPortForwardDefaults(&rule, inst.Dir)\n\trules = append(rules, rule)\n\n\tlimaDriver := driverutil.CreateTargetDriverInstance(&driver.BaseDriver{\n\t\tInstance: inst,\n\t\tYaml: y,\n\t\tSSHLocalPort: sshLocalPort,\n\t})\n\n\ta := &HostAgent{\n\t\ty: y,\n\t\tsshLocalPort: sshLocalPort,\n\t\tudpDNSLocalPort: udpDNSLocalPort,\n\t\ttcpDNSLocalPort: tcpDNSLocalPort,\n\t\tinstDir: inst.Dir,\n\t\tinstName: instName,\n\t\tsshConfig: sshConfig,\n\t\tportForwarder: newPortForwarder(sshConfig, sshLocalPort, rules),\n\t\tdriver: limaDriver,\n\t\tsigintCh: sigintCh,\n\t\teventEnc: json.NewEncoder(stdout),\n\t}\n\treturn a, nil\n}", "func New(minEph uint16) *Porter {\n\tports := make(map[uint16]struct{})\n\tports[0] = struct{}{} // port 0 is invalid\n\n\treturn &Porter{\n\t\teph: minEph,\n\t\tminEph: minEph,\n\t\tports: ports,\n\t}\n}", "func New(lDs, gDs Placeholder, dfn DriverNotifyFunc, ifn Placeholder, pg plugingetter.PluginGetter) (*DrvRegistry, error) {\n\treturn &DrvRegistry{\n\t\tNetworks: Networks{Notify: dfn},\n\t\tpluginGetter: pg,\n\t}, nil\n}", "func NewEC2Host(properties EC2HostProperties, deps ...interface{}) EC2Host {\n\treturn EC2Host{\n\t\tType: \"AWS::EC2::Host\",\n\t\tProperties: properties,\n\t\tDependsOn: deps,\n\t}\n}", "func NewBindHostOK() *BindHostOK {\n\treturn &BindHostOK{}\n}", "func NewPeer(server *Server, name string, heartbeatTimeout time.Duration) *Peer {\n\tp := &Peer{\n\t\tserver: server,\n\t\tname: name,\n\t\theartbeatTimer: NewTimer(heartbeatTimeout, heartbeatTimeout),\n\t}\n\n\t// Start the heartbeat timeout and wait for the goroutine to start.\n\tc := make(chan bool)\n\tgo p.heartbeatTimeoutFunc(c)\n\t<-c\n\n\treturn p\n}", "func NewEtherHostPort(classId string, objectType string) *EtherHostPort {\n\tthis := EtherHostPort{}\n\tthis.ClassId = classId\n\tthis.ObjectType = objectType\n\treturn &this\n}", "func NewHiveMind(pid, nrProc, nrBarriers, nrLocks uint8, nrPages, pageSize int, ipcType string) *HM {\n\t// If procAddr is not specified then we plan to use tipc for testing locally\n\thm := new(HM)\n\tif ipcType == \"ipc\" || ipcType == \"\" {\n\t\tmyip := ipc.GetOutboundIPKvm()\n\t\tlocConf, err := configs.ReadConfig()\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Config Read Error: \", err)\n\t\t\treturn nil\n\t\t}\n\t\tnrProc = uint8(len(locConf.Drones) + 1)\n\t\tfmt.Println(locConf, hm.nrProc)\n\t\tif locConf.DroneList != nil {\n\t\t\t// I am not the first drone\n\t\t\tnrProc = uint8(len(locConf.DroneList) + 1)\n\t\t\tfor _, drone := range locConf.DroneList {\n\t\t\t\tif myip == drone.Address {\n\t\t\t\t\t//It's me\n\t\t\t\t\tpid = drone.PID\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// null DroneList means I am the first drone, drone 0\n\t\t\tpid = uint8(0)\n\t\t}\n\n\t}\n\n\thm.nrLocks = nrLocks\n\thm.nrProc = nrProc\n\thm.nrBarriers = nrBarriers\n\thm.VC = *NewVectorClock(nrProc)\n\thm.pid = pid\n\thm.dirtyList = make(map[int]bool, 0)\n\thm.dlMutex = new(sync.RWMutex)\n\thm.shm = shm.NewShm(pageSize, nrPages)\n\thm.shm.InstallSEGVHandler(hm.pageFaultHandler)\n\thm.procArray = NewProcArray(nrProc)\n\thm.pageArray = NewPageArray(nrPages, pageSize, pid, nrProc)\n\thm.waitChan = make(chan bool, 1)\n\thm.barrierReq = make([]*BarrierRequest, nrProc)\n\thm.locks = make([]*Lock, nrLocks)\n\thm.start = time.Now()\n\tfmt.Println(\"Hivemind Successfully Initiated\")\n\treturn hm\n}", "func GetVirtualDedicatedHostService(sess *session.Session) Virtual_DedicatedHost {\n\treturn Virtual_DedicatedHost{Session: sess}\n}", "func createHost() (context.Context, host.Host, error) {\n\tctx, _ /* cancel */ := context.WithCancel(context.Background())\n\t// defer cancel()\n\n\tprvKey, _, err := crypto.GenerateKeyPairWithReader(crypto.RSA, 2048, rand.Reader)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tport, err := freeport.GetFreePort()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\thost, err := libp2p.New(\n\t\tctx,\n\t\tlibp2p.Identity(prvKey),\n\t\tlibp2p.ListenAddrStrings(fmt.Sprintf(\"/ip4/0.0.0.0/tcp/%v\", port)),\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn ctx, host, nil\n}", "func NewDbZk(host []string) store.Dbdrvier {\n\tzk := dbZk{\n\t\tZkHost: host[:],\n\t\tZkCli: zkclient.NewZkClient(host),\n\t}\n\n\treturn &zk\n}", "func (d *Device) CreateHost(ctx context.Context, hostname string) (*Host, error) {\n\tspath := \"/host\"\n\tparam := struct {\n\t\tNAME string `json:\"NAME\"`\n\t\tTYPE string `json:\"TYPE\"`\n\t\tOPERATIONSYSTEM string `json:\"OPERATIONSYSTEM\"`\n\t\tDESCRIPTION string `json:\"DESCRIPTION\"`\n\t}{\n\t\tNAME: encodeHostName(hostname),\n\t\tTYPE: strconv.Itoa(TypeHost),\n\t\tOPERATIONSYSTEM: \"0\",\n\t\tDESCRIPTION: hostname,\n\t}\n\tjb, err := json.Marshal(param)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(ErrCreatePostValue+\": %w\", err)\n\t}\n\treq, err := d.newRequest(ctx, \"POST\", spath, bytes.NewBuffer(jb))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(ErrCreateRequest+\": %w\", err)\n\t}\n\n\thost := &Host{}\n\tif err = d.requestWithRetry(req, host, DefaultHTTPRetryCount); err != nil {\n\t\treturn nil, fmt.Errorf(ErrRequestWithRetry+\": %w\", err)\n\t}\n\n\treturn host, nil\n}", "func NewHostDiscovery() HostDiscovery {\n\treturn &hostDiscovery{}\n}", "func NewDClient(stdClient *http.Client, username string, password string) *DClient {\n\treturn &DClient{\n\t\tclient: stdClient,\n\t\tusername: username,\n\t\tpassword: password,\n\t}\n}", "func NewHostSet(hkr renter.HostKeyResolver, currentHeight types.BlockHeight) *HostSet {\n\treturn &HostSet{\n\t\thkr: hkr,\n\t\tcurrentHeight: currentHeight,\n\t\tsessions: make(map[hostdb.HostPublicKey]*lockedHost),\n\t\tlockTimeout: 10 * time.Second,\n\t\tonConnect: func(*proto.Session) {},\n\t}\n}", "func Create() *dht {\n\treturn &dht{}\n}", "func (plugin *azureDataDiskPlugin) NewAttacher() (volume.Attacher, error) {\n\tazure, err := getAzureCloudProvider(plugin.host.GetCloudProvider())\n\tif err != nil {\n\t\tglog.V(4).Infof(\"failed to get azure provider\")\n\t\treturn nil, err\n\t}\n\n\treturn &azureDiskAttacher{\n\t\thost: plugin.host,\n\t\tazureProvider: azure,\n\t}, nil\n}", "func NewBot(name, prefix, token string, hmm *HMM) (*Bot, error) {\n\tdg, err := discordgo.New(\"Bot \" + token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// This step is kinda expensive. Instead of doing this in messageCreateHandler() every time we\n\t// handle a bot invocation, we do this once when the bot is created.\n\treg, err := regexp.Compile(\"[^a-zA-Z0-9 ]+\") // Filtering for alphanumeric values only\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Bot{\n\t\tdg: dg,\n\t\tpostFN: postDiscordMessage,\n\t\tname: name,\n\t\tprefix: prefix,\n\t\thmm: hmm,\n\t\tcontentRegexp: reg,\n\t}, nil\n}", "func New(provider PayloadEncoderDecoderProvider, cluster Cluster) messageprocessors.PayloadEncoderDecoder {\n\treturn &host{\n\t\tcluster: cluster,\n\t\tprovider: provider,\n\n\t\tcache: gcache.New(cacheSize).LFU().Build(),\n\t}\n}", "func createHostonlyAdapter(vbox VBoxManager) (*hostOnlyNetwork, error) {\n\tout, err := vbox.vbmOut(\"hostonlyif\", \"create\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := reHostOnlyAdapterCreated.FindStringSubmatch(string(out))\n\tif res == nil {\n\t\treturn nil, errors.New(\"Failed to create host-only adapter\")\n\t}\n\n\treturn &hostOnlyNetwork{Name: res[1]}, nil\n}", "func NewDiscovery(hwaddr net.HardwareAddr, modifiers ...Modifier) (*DHCPv4, error) {\n\treturn New(PrependModifiers(modifiers,\n\t\tWithHwAddr(hwaddr),\n\t\tWithRequestedOptions(\n\t\t\tOptionSubnetMask,\n\t\t\tOptionRouter,\n\t\t\tOptionDomainName,\n\t\t\tOptionDomainNameServer,\n\t\t),\n\t\tWithMessageType(MessageTypeDiscover),\n\t)...)\n}", "func New(\n\tdatabaseContext model.DBReader,\n\tdagTopologyManager model.DAGTopologyManager,\n\tghostdagDataStore model.GHOSTDAGDataStore,\n\theaderStore model.BlockHeaderStore,\n\tk externalapi.KType,\n\tgenesisHash *externalapi.DomainHash) model.GHOSTDAGManager {\n\n\treturn &ghostdagManager{\n\t\tdatabaseContext: databaseContext,\n\t\tdagTopologyManager: dagTopologyManager,\n\t\tghostdagDataStore: ghostdagDataStore,\n\t\theaderStore: headerStore,\n\t\tk: k,\n\t\tgenesisHash: genesisHash,\n\t}\n}", "func (r Virtual_Guest) GetDedicatedHost() (resp datatypes.Virtual_DedicatedHost, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getDedicatedHost\", nil, &r.Options, &resp)\n\treturn\n}", "func MakeBasicHost(listenPort int, protocolID string, randseed int64) (host.Host, error) {\n\n\t// If the seed is zero, use real cryptographic randomness. Otherwise, use a\n\t// deterministic randomness source to make generated keys stay the same\n\t// across multiple runs\n\tvar r io.Reader\n\tif randseed == 0 {\n\t\tr = rand.Reader\n\t} else {\n\t\tr = mrand.New(mrand.NewSource(randseed))\n\t}\n\n\t// Generate a key pair for this host. We will use it at least\n\t// to obtain a valid host ID.\n\tpriv, _, err := crypto.GenerateKeyPairWithReader(crypto.RSA, 2048, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\topts := []libp2p.Option{\n\t\tlibp2p.ListenAddrStrings(fmt.Sprintf(\"/ip4/127.0.0.1/tcp/%d\", listenPort)),\n\t\tlibp2p.Identity(priv),\n\t\tlibp2p.DisableRelay(),\n\t}\n\n\tif protocolID == plaintext.ID {\n\t\topts = append(opts, libp2p.NoSecurity)\n\t} else if protocolID == noise.ID {\n\t\ttpt, err := noise.New(priv)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\topts = append(opts, libp2p.Security(protocolID, tpt))\n\t} else if protocolID == secio.ID {\n\t\ttpt, err := secio.New(priv)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\topts = append(opts, libp2p.Security(protocolID, tpt))\n\t} else {\n\t\treturn nil, fmt.Errorf(\"security protocolID '%s' is not supported\", protocolID)\n\t}\n\n\tbasicHost, err := libp2p.New(context.Background(), opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Build host multiaddress\n\thostAddr, _ := ma.NewMultiaddr(fmt.Sprintf(\"/ipfs/%s\", basicHost.ID().Pretty()))\n\n\t// Now we can build a full multiaddress to reach this host\n\t// by encapsulating both addresses:\n\taddr := basicHost.Addrs()[0]\n\tfullAddr := addr.Encapsulate(hostAddr)\n\tlog.Printf(\"I am %s\\n\", fullAddr)\n\tlog.Printf(\"Now run \\\"./echo -l %d -d %s -security %s\\\" on a different terminal\\n\", listenPort+1, fullAddr, protocolID)\n\n\treturn basicHost, nil\n}", "func New() *d.Client {\n\tvar err error\n\tif os.Getenv(\"DOCKER_HOST\") != \"\" {\n\t\tclient, err = d.NewClient(os.Getenv(\"DOCKER_HOST\"))\n\t} else {\n\t\tclient, err = d.NewClient(\"DEFAULTHERE\")\n\t}\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn nil\n\t}\n\n\treturn client\n}", "func NewDaddy() *Daddy {\n\treturn &Daddy{\n\t\tSon: make(map[string]*Assassin),\n\t\tSibling: make(map[string]*Sibling),\n\t}\n}", "func (e *EdgeSwitchClient) newClient() (*ssh.Client, error) {\n\tsshConfig := &ssh.ClientConfig{\n\t\tUser: DEFAULT_USER,\n\t\tAuth: []ssh.AuthMethod{ssh.Password(DEFAULT_USER)},\n\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t}\n\n\tclient, err := ssh.Dial(\"tcp\", e.ipaddress, sshConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn client, nil\n}", "func NewEmulatedBTPeerDevice(ctx context.Context, deviceRPC cbt.BluezPeripheral) (*EmulatedBTPeerDevice, error) {\n\td := &EmulatedBTPeerDevice{\n\t\trpc: deviceRPC,\n\t}\n\tif err := d.initializeEmulatedBTPeerDevice(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\treturn d, nil\n}" ]
[ "0.5937202", "0.56524247", "0.5622617", "0.5549057", "0.554061", "0.54582804", "0.53811127", "0.53612816", "0.5348876", "0.53129005", "0.53107387", "0.52896184", "0.52111804", "0.5205387", "0.51967883", "0.5183881", "0.51309884", "0.5129728", "0.51117593", "0.50693804", "0.5046912", "0.50213486", "0.49973094", "0.49965", "0.49626806", "0.49467725", "0.48831132", "0.48745552", "0.4831677", "0.48212934", "0.48204452", "0.48181525", "0.4798018", "0.47844687", "0.47588983", "0.47463012", "0.47325182", "0.46643525", "0.46630093", "0.4636842", "0.4635206", "0.4632883", "0.4583429", "0.45757848", "0.4574888", "0.45698208", "0.45693007", "0.45624357", "0.45549282", "0.45485935", "0.4541043", "0.4537036", "0.45289603", "0.4523371", "0.45226115", "0.4518621", "0.45155022", "0.4511344", "0.44925556", "0.44696116", "0.44649166", "0.44632486", "0.44513255", "0.4450578", "0.4439841", "0.4439675", "0.44394264", "0.4437902", "0.44364443", "0.44270468", "0.44184747", "0.44165197", "0.44033778", "0.43960285", "0.4392687", "0.4389953", "0.43755537", "0.43733236", "0.43720797", "0.43653554", "0.435257", "0.43518886", "0.43494734", "0.4343143", "0.43402913", "0.43002397", "0.42966926", "0.42958713", "0.42903915", "0.42896503", "0.4281234", "0.428035", "0.42755058", "0.42751145", "0.42645815", "0.42556313", "0.42541283", "0.425366", "0.42525226", "0.42446113" ]
0.86870915
0
Init is used to initialize the DinnerHost. Note: seats are randomized.
func (host *DinnerHost) Init(tableCount, maxParallel, maxDinner int) { host.phiData = make(map[string]*philosopherData) host.requestChannel = make(chan string) host.finishChannel = make(chan string) host.maxParallel = maxParallel if host.maxParallel > tableCount { host.maxParallel = tableCount } host.maxDinner = maxDinner host.currentlyEating = 0 host.tableCount = tableCount host.chopsticksFree = make([]bool, 5) for i := range host.chopsticksFree { host.chopsticksFree[i] = true } rand.Seed(time.Now().Unix()) host.freeSeats = rand.Perm(tableCount) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t *Topology) Init() {\n\tt.l.Lock()\n\tdefer t.l.Unlock()\n\tif t.initialized {\n\t\treturn\n\t}\n\tt.initialized = true\n\n\tt.serversLock.Lock()\n\tfor _, a := range t.cfg.seedList {\n\t\taddress := addr.Addr(a).Canonicalize()\n\t\tt.fsm.Servers = append(t.fsm.Servers, description.Server{Addr: address})\n\t\tt.addServer(address)\n\t}\n\tt.serversLock.Unlock()\n\n\tgo t.update()\n}", "func Init() {\n\n\t// ---------------------------------\n\t// Logger initialization\n\n\tlogger.Setup(`%{color}▶ %{level:.4s} %{id:03d}%{color:reset} %{message}`, 5)\n\tmlog := logger.GetLogger()\n\n\t// ---------------------------------\n\t// Config initialization\n\n\tcfg, err := config.ReadFromEnv()\n\tif err != nil {\n\t\tmlog.Fatalf(\"failed reading config from environment: %s\", err.Error())\n\t}\n\n\tlogger.SetLogLevel(cfg.LogLevel)\n\n\t// ---------------------------------\n\t// Disgord initialization\n\n\tdc := disgord.New(&disgord.Config{\n\t\tBotToken: cfg.DiscordBotToken,\n\t})\n\n\tdefer dc.StayConnectedUntilInterrupted()\n\n\tdc.Ready(handler.NewReady(dc).Handler)\n}", "func (s *Spyfall) Init(id, code string) {\n\ts.Id = id\n\ts.Code = code\n\ts.cmds = make(chan *lib.PlayerCmd)\n\ts.Players = []*Player{}\n\n\ts.timer = time.NewTimer(1 * time.Minute)\n\tif !s.timer.Stop() {\n\t\t<-s.timer.C\n\t}\n\tlog.Println(\"New game initialized\", s)\n\t// TODO: save to mongo\n}", "func init() {\n\t// This function will be executed before everything else.\n\t// Do some initialization here.\n\tSBC = data.NewBlockChain()\n\t// When server works\n\t// Peers = data.NewPeerList(Register(), 32)\n\t// While server doesn't work -> use port as id\n\tid, _ := strconv.ParseInt(os.Args[1], 10, 64)\n\tPeers = data.NewPeerList(int32(id), 32)\n\tifStarted = true\n}", "func (b *TestDriver) Init() (err error) {\n\tlog.Println(\"Init Drone\")\n\treturn\n}", "func (n *Node) Init() {\n\tn.NodeNet.Init()\n\n\tn.NodeNet.Logger = n.Logger\n\tn.NodeBC.Logger = n.Logger\n\n\tn.NodeBC.MinterAddress = n.MinterAddress\n\n\tn.NodeBC.DBConn = n.DBConn\n\n\t// Nodes list storage\n\tn.NodeNet.SetExtraManager(NodesListStorage{n.DBConn, n.SessionID})\n\t// load list of nodes from config\n\tn.NodeNet.SetNodes([]net.NodeAddr{}, true)\n\n\tn.InitClient()\n\n\trand.Seed(time.Now().UTC().UnixNano())\n}", "func (host *Host) Init() {\n\n\tmaxCache := host.MaxCache\n\tif maxCache == 0 {\n\t\tmaxCache = 1 << 20\n\t}\n\n\t// Create a new group cache with a max cache size of 3MB\n\thost.Cache = groupcache.NewGroup(host.Hostname, maxCache, groupcache.GetterFunc(\n\n\t\tfunc(ctx context.Context, id string, dest groupcache.Sink) error {\n\t\t\tv := ctx.Value(requestContextKey(\"request\"))\n\n\t\t\tr, ok := v.(ContentContextValue)\n\n\t\t\tif ok {\n\n\t\t\t\tcontent, err := r.Content.Render(r.Site, r.ContextData)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Error: %v - '%+v'\\n\", err, r.Content)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tttl, err := time.ParseDuration(r.Content.CacheTTL)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Error parsing TTL duration: '%v' for key '%s' defaulting to a TTL of one minute\\n\", err, id)\n\t\t\t\t\tttl = time.Minute * 1\n\t\t\t\t}\n\n\t\t\t\tif err := dest.SetString(content, time.Now().Add(ttl)); err != nil {\n\t\t\t\t\tlog.Println(\"SetString\", err)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t))\n}", "func Init() {\n\tlog.Debug().Caller().Msg(\"initialize server\")\n\tr := router()\n\tr.Run()\n}", "func (r *Ricochet) Init() {\n\tr.newconns = make(chan *OpenConnection)\n\tr.networkResolver = utils.NetworkResolver{}\n\tr.rni = new(utils.RicochetNetwork)\n}", "func Init() {\n\trand.Seed(time.Now().Unix())\n}", "func (pd *philosopherData) Init(respChannel chan string) {\n\tpd.respChannel = respChannel\n\tpd.eating = false\n\tpd.dinnersSpent = 0\n\tpd.seat = -1\n\tpd.leftChopstick = -1\n\tpd.rightChopstick = -1\n}", "func Init() {\n\trand.Seed(time.Now().UnixNano())\n}", "func Init(seed int) {\n\tif seed <= 0 {\n\t\tseed = int(time.Now().Unix())\n\t}\n\trand.Seed(int64(seed))\n}", "func Init() {\n\tr := router()\n\tr.Run(\":3001\")\n}", "func (s *DiscordState) Init() error {\n\ts.Session = new(discordgo.Session)\n\t\n\tfmt.Printf(\"\\nConnecting…\")\n\n\tdg, err := discordgo.New(Config.Username, Config.Password)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Open the websocket and begin listening.\n\tdg.Open()\n\n\t//Retrieve GuildID's from current User\n\t//need index of Guilds[] rather than UserGuilds[] (maybe)\n\tGuilds, err := dg.UserGuilds(0, \"\", \"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.Guilds = Guilds\n\n\ts.Session = dg\n\n\ts.User, _ = s.Session.User(\"@me\")\n\n\tfmt.Printf(\" PASSED!\\n\")\n\n\treturn nil\n}", "func dInit() error {\n\tvar err error\n\tdial, err = grpc.Dial(address, grpc.WithInsecure(), grpc.WithTimeout(10*time.Second))\n\tif err != nil {\n\t\tgrpclog.Printf(\"Fail to dial: %v\", err)\n\t\treturn err\n\t}\n\n\tdemoClient = NewDemonstratorClient(dial)\n\treturn nil\n}", "func (s *Solo) Init(state *state.State, service *service.Service) error {\n\n\ts.logger.Debug(\"INIT\")\n\n\ts.state = state\n\ts.service = service\n\n\treturn nil\n}", "func (bs *BatchSession) Init(host string) {\n\tbs.Host = host\n\trc := rabbit.ConnectToRabbitMQ(host) // intiates the connection to rabbitmq\n\tif (!rc.IsConnected()) {\n\t\tlog.Fatalf(\"We are not connected, aborting\")\n\t\treturn\n\t}\n\tu, _ := uuid.NewV4() // generate a new random V4 UUID\n\tbs.UUID = u.String()\n\tbs.Started = time.Now()\n\tbs._rc = rc\n\tq := bs._rc.DeclareQ(bs.UUID) // declare the new rabbitmq using the newly created uuid\n\tbs._q = &q\n\tbs._done = make(chan bool) // initializing the _done channel\n}", "func (d *Config) Init() {\n\td.Type = \"SRV\"\n\td.RefreshInterval = toml.Duration(30 * time.Second)\n}", "func (as *ArgocdServer) Init() error {\n\tfor _, f := range []func() error{\n\t\tas.initClientSet,\n\t\tas.initTLSConfig,\n\t\tas.initRegistry,\n\t\tas.initDiscovery,\n\t\tas.initMicro,\n\t\tas.initHTTPService,\n\t\tas.initProxyAgent,\n\t\t//as.initMetric,\n\t} {\n\t\tif err := f(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func Init(c *conf.Config, s *service.Service) {\n\tsrv = s\n\t// init inner router\n\teng := bm.DefaultServer(c.BM)\n\tinitRouter(eng)\n\t// init inner server\n\tif err := eng.Start(); err != nil {\n\t\tlog.Error(\"bm.DefaultServer error(%v)\", err)\n\t\tpanic(err)\n\t}\n}", "func (dc *Client) Init() error {\n\tdc.GenericServicePool = make(map[string]*dg.GenericService, 4)\n\n\tcls := config.GetBootstrap().StaticResources.Clusters\n\n\t// dubbogo comsumer config\n\tdgCfg = dg.ConsumerConfig{\n\t\tCheck: new(bool),\n\t\tRegistries: make(map[string]*dg.RegistryConfig, 4),\n\t}\n\tdgCfg.ApplicationConfig = defaultApplication\n\tfor i := range cls {\n\t\tc := cls[i]\n\t\tdgCfg.Request_Timeout = c.RequestTimeoutStr\n\t\tdgCfg.Connect_Timeout = c.ConnectTimeoutStr\n\t\tfor k, v := range c.Registries {\n\t\t\tif len(v.Protocol) == 0 {\n\t\t\t\tlogger.Warnf(\"can not find registry protocol config, use default type 'zookeeper'\")\n\t\t\t\tv.Protocol = defaultDubboProtocol\n\t\t\t}\n\t\t\tdgCfg.Registries[k] = &dg.RegistryConfig{\n\t\t\t\tProtocol: v.Protocol,\n\t\t\t\tAddress: v.Address,\n\t\t\t\tTimeoutStr: v.Timeout,\n\t\t\t\tUsername: v.Username,\n\t\t\t\tPassword: v.Password,\n\t\t\t}\n\t\t}\n\t}\n\n\tinitDubbogo()\n\n\treturn nil\n}", "func (c *Client) Init() error {\n\treturn nil\n}", "func (c *Client) Init() error {\n\treturn nil\n}", "func Init() {\n\terr := regenerateEphemeral()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tticker := time.NewTicker(60 * time.Second)\n\tgo func() {\n\t\tfor {\n\t\t\t<-ticker.C\n\t\t\terr := regenerateEphemeral()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t}()\n}", "func Init(port int, in <-chan messages.LocalMsg, out chan<- messages.LocalMsg) {\n\t//golog.SetAllLoggers(golog.LevelDebug)\n\tgob.Register(blockchain.Block{})\n\tgob.Register(helloData{})\n\tgob.Register(peerData{})\n\tserver = newTCPServer(port, in, out)\n\tgossipNdxs = make([]int, gossipSize)\n\tserver.start()\n}", "func (s *Hipchat) Init(c *config.Config) error {\n\turl := c.Handler.Hipchat.Url\n\troom := c.Handler.Hipchat.Room\n\ttoken := c.Handler.Hipchat.Token\n\n\tif token == \"\" {\n\t\ttoken = os.Getenv(\"KW_HIPCHAT_TOKEN\")\n\t}\n\n\tif room == \"\" {\n\t\troom = os.Getenv(\"KW_HIPCHAT_ROOM\")\n\t}\n\n\tif url == \"\" {\n\t\turl = os.Getenv(\"KW_HIPCHAT_URL\")\n\t}\n\n\ts.Token = token\n\ts.Room = room\n\ts.Url = url\n\n\treturn checkMissingHipchatVars(s)\n}", "func (zk *ZookeeperMaster) Init() error {\n\tzk.isMaster = false\n\t//create connection to zookeeper\n\tzk.client = zkclient.NewZkClient(zk.zkHosts)\n\tif err := zk.client.ConnectEx(time.Second * 10); err != nil {\n\t\treturn fmt.Errorf(\"Init failed when connect zk, %s\", err.Error())\n\t}\n\treturn nil\n}", "func (r *Raft) Init(config *ClusterConfig, thisServerId int) {\n\tgo r.AcceptConnection(r.ClusterConfigV.Servers[thisServerId].ClientPort) // done\n\tgo r.AcceptRPC(r.ClusterConfigV.Servers[thisServerId].LogPort)\t//\n\tgo SendHeartbeat() // NOT Done TODO\n\tgo Evaluator()\t//\n\tgo AppendCaller()\n\tgo CommitCaller()\n\tgo DataWriter()\n\tr.SetElectionTimer()\n\tgo Loop() //if he is not leader TODO\n}", "func (c *ClickHouse) Init() error {\n\treturn c.initAll()\n}", "func Init(c *conf.Config, s *service.Service) {\n\trelationSvc = s\n\tverify = v.New(c.Verify)\n\tanti = antispam.New(c.Antispam)\n\taddFollowingRate = rate.New(c.AddFollowingRate)\n\t// init inner router\n\tengine := bm.DefaultServer(c.BM)\n\tsetupInnerEngine(engine)\n\tif err := engine.Start(); err != nil {\n\t\tlog.Error(\"engine.Start() error(%v)\", err)\n\t\tpanic(err)\n\t}\n}", "func Init(c *conf.Config) {\n\tinitService(c)\n\t// init inner router\n\tengine := bm.DefaultServer(c.HTTPServer)\n\tinnerRouter(engine)\n\t// init inner server\n\tif err := engine.Start(); err != nil {\n\t\tlog.Error(\"engine.Start error(%v)\", err)\n\t\tpanic(err)\n\t}\n}", "func (client *Client) Init() {\n\tclient.coAckChannel = make(chan CoAck)\n\n\tclient.Tag = true\n\n\tif client.Id == \"\" {\n\t\tclient.Id = uuid.New()\n\t}\n\tclient.RWMutex.Init(\"client_\" + client.Id)\n\n\tif client.RegTime.IsZero() {\n\t\tclient.RegTime = time.Now()\n\t}\n\tif client.Apps == nil {\n\t\tclient.Apps = []string{}\n\t}\n\tif client.Skip_work == nil {\n\t\tclient.Skip_work = []string{}\n\t}\n\n\tclient.Assigned_work.Init(\"Assigned_work\")\n\n\tclient.Current_work.Init(\"Current_work\")\n\n}", "func (d *Deck) Init() {\n\td.Cards = []*Card{}\n\tfor _, s := range Suits {\n\t\tfor _, r := range Ranks {\n\t\t\td.Cards = append(d.Cards, &Card{r, s, true})\n\t\t}\n\t}\n}", "func Init() {\n\tl, err := net.ListenPacket(\"udp\", \":\"+util.LISTEN_PORT)\n\tif err != nil {\n\t\tlog.Exit(err)\n\t}\n\tLocalServer = &Server{\n\t\tServer: l,\n\t\tFriends: Settings.Friends}\n\tLocalServer.Sender, err = netchan.NewExporter(\"tcp\", \":0\")\n\tif err != nil {\n\t\tlog.Exit(err)\n\t}\n\tsAdd := LocalServer.Sender.Addr().String()\n\tsPort, err := strconv.Atoi(sAdd[strings.LastIndex(sAdd, \":\"):])\n\tif strings.LastIndex(sAdd, \":\") == -1 || err != nil {\n\t\tlog.Exit(\"address binding failure\")\n\t}\n\tMe = &database.Friend{\n\t\tName: Settings.ProfileName,\n\t\tTempHashKey: crypt.Md5(crypt.GenerateKey(util.SECRET_KEY_SIZE)),\n\t\tSenderPort: sPort}\n}", "func (e *Environment) Init(port, id int) {\n\te.port = port\n\te.active = false\n\te.occupied = false\n\te.addr = \"http://localhost:\" + strconv.Itoa(port)\n\te.id = id\n}", "func Init(r chi.Router) {\n\tr.Route(\"/auction\", auctioneer.Init)\n\tr.Route(\"/bidder\", bidder.Init)\n}", "func (obj *ECDSCluster) Init() {\n\tif obj.Status.ActualState == \"\" {\n\t\tobj.Status.ActualState = StateUninitialized\n\t}\n\tif obj.Spec.TargetState == \"\" {\n\t\tobj.Spec.TargetState = StateUninitialized\n\t}\n\tobj.Status.Satisfied = (obj.Spec.TargetState == obj.Status.ActualState)\n}", "func (e *Pusher) Initialize(id string) {\n\te.ServerID = id\n\te.Watchers = make(map[string]Watcher, maxClients)\n}", "func Init() (err error) {\n\n\tbot, er := newBot(\"config.json\")\n\tif er != nil {\n\t\terr = er\n\t\treturn\n\t}\n\n\ts, er := discordgo.New(\"Bot \" + bot.Token)\n\tif er != nil {\n\t\terr = er\n\t\treturn\n\t}\n\n\ts.AddHandler(bot.MessageHandler)\n\n\ter = s.Open()\n\tif er != nil {\n\t\terr = er\n\t\treturn\n\t}\n\treturn\n}", "func (rndr *Renderer) Init(snatOnly bool) error {\n\trndr.snatOnly = snatOnly\n\trndr.natGlobalCfg = &vpp_nat.Nat44Global{\n\t\tForwarding: true,\n\t}\n\tif rndr.Config == nil {\n\t\trndr.Config = config.DefaultConfig()\n\t}\n\treturn nil\n}", "func (d *DB) Init() {\n\td.NumCell = 1024 // set num cell first!\n\td.root = d.NewNode()\n\t//log.Printf(\"+d.root: %v\\n\", d.root)\n}", "func Init(c *conf.Config) {\n\t// service\n\tinitService(c)\n\t// init grpc\n\tgrpcSvr = grpc.New(nil, arcSvc, newcomerSvc)\n\tengineOuter := bm.DefaultServer(c.BM.Outer)\n\t// init outer router\n\touterRouter(engineOuter)\n\tif err := engineOuter.Start(); err != nil {\n\t\tlog.Error(\"engineOuter.Start() error(%v) | config(%v)\", err, c)\n\t\tpanic(err)\n\t}\n}", "func init() {\n\trand.Seed(time.Now().UnixNano())\n}", "func init() {\n\trand.Seed(time.Now().UnixNano())\n}", "func init() {\n\trand.Seed(time.Now().UnixNano())\n}", "func init() {\n\trand.Seed(time.Now().UnixNano())\n}", "func init() {\n\trand.Seed(time.Now().UnixNano())\n}", "func init() {\n\trand.Seed(time.Now().UnixNano())\n}", "func init() {\n\trand.Seed(time.Now().UnixNano())\n}", "func (d *Default) Init() error {\n\treturn nil\n}", "func (s *Session) Init() {\n\ts.setEthereumRPCPath()\n\ts.setPayloadRPCPath()\n}", "func Init() {\n\tdocker.Init()\n\thost.Init()\n\tlabel.Init()\n\tospackages.Init()\n\tdiff.Init()\n\tcontainer.Init()\n}", "func (s *Server) Init() {\n\ts.initPrometheus()\n\tgo s.listen()\n\n\tif s.StateFileName != \"\" {\n\t\tsimulationState, err := LoadSimulationState(filepath.Join(statesFolderName, s.StateFileName))\n\t\tif err != nil {\n\t\t\tfmt.Println(\"\\nLoading state from filepath failed, exiting now\", err)\n\t\t\tpanic(err)\n\t\t}\n\t\ts.SimulationState = simulationState\n\t\treturn\n\t}\n\n\tif s.LoadLatestState {\n\t\tsimulationState, err := LoadLatestSimulationState()\n\t\tif err != nil {\n\t\t\tfmt.Println(\"\\nLoading latest state failed, exiting now\", err)\n\t\t\tpanic(err)\n\t\t}\n\t\ts.SimulationState = simulationState\n\t\treturn\n\t}\n\n\ts.fetchBigBang()\n}", "func (svr *Server) Init(maxConns int) (err error) {\n\tsvr.LineMgr, err = NewMLLineMgr(maxConns)\n\tif err != nil {\n\t\tutils.Logger.Error(\"New Magline Connection Pool Error!\")\n\t\treturn\n\t}\n\treturn\n}", "func (m *Driver) Init(metadata mq.Metadata) error {\n\tmqttMeta, err := parseMQTTMetaData(metadata)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.metadata = mqttMeta\n\tclient, err := m.connect()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm.client = client\n\treturn nil\n\n}", "func (rem *Remote) Init() error {\n\trem.StateDirtyChan = make(chan *State, 10)\n\tif err := rem.LoadFromDb(); err != nil {\n\t\treturn err\n\t}\n\tif err := rem.LoadComponentTree(); err != nil {\n\t\treturn err\n\t}\n\tif rem.RemoteList.reporter.enableRemotes {\n\t\trem.Manager.Start()\n\t} else {\n\t\tglog.Infof(\"Not starting remote manager for %s due to noremotes flag.\", rem.Data.Id)\n\t}\n\treturn nil\n}", "func init() {\n\trand.Seed(time.Now().UTC().UnixNano())\n}", "func init() {\n\trand.Seed(time.Now().UTC().UnixNano())\n}", "func init() {\n\trand.Seed(time.Now().UTC().UnixNano())\n}", "func init() {\n\trand.Seed(time.Now().UTC().UnixNano())\n}", "func init() {\n\t\n\t\t// note:\n\t\t// Each time you set the same seed, you get the same sequence\n\t\t// You have to set the seed only once\n\t\t// you simply call Intn to get the next random integer\n\t\trand.Seed(time.Now().UTC().UnixNano())\n\t}", "func (p *pingChannelServer) Init(msg []byte) ([]byte, HandleMessage, error) {\n\tlogging.Println(\"server init \" + string(msg))\n\tsend := map[string]string{}\n\tsend[\"dummy\"] = \"dummy\"\n\ts, err := json.Marshal(send)\n\tp.st.CanPinged = true\n\treturn s, nil, err\n}", "func (m *Meow) Init(_ context.Context) error {\n\tm.SetBorder(true)\n\tm.SetScrollable(true).SetWrap(true).SetRegions(true)\n\tm.SetDynamicColors(true)\n\tm.SetHighlightColor(tcell.ColorOrange)\n\tm.SetTitleColor(tcell.ColorAqua)\n\tm.SetInputCapture(m.keyboard)\n\tm.SetBorderPadding(0, 0, 1, 1)\n\tm.updateTitle()\n\tm.SetTextAlign(tview.AlignCenter)\n\n\tm.app.Styles.AddListener(m)\n\tm.StylesChanged(m.app.Styles)\n\n\tm.bindKeys()\n\tm.SetInputCapture(m.keyboard)\n\tm.talk()\n\n\treturn nil\n}", "func init() {\n\tos.RemoveAll(DataPath)\n\n\tdc := DatabaseConfig{\n\t\tDataPath: DataPath,\n\t\tIndexDepth: 4,\n\t\tPayloadSize: 16,\n\t\tBucketDuration: 3600000000000,\n\t\tResolution: 60000000000,\n\t\tSegmentSize: 100000,\n\t}\n\n\tcfg := &ServerConfig{\n\t\tVerboseLogs: true,\n\t\tRemoteDebug: true,\n\t\tListenAddress: Address,\n\t\tDatabases: map[string]DatabaseConfig{\n\t\t\tDatabase: dc,\n\t\t},\n\t}\n\n\tdbs := map[string]kdb.Database{}\n\tdb, err := dbase.New(dbase.Options{\n\t\tDatabaseName: Database,\n\t\tDataPath: dc.DataPath,\n\t\tIndexDepth: dc.IndexDepth,\n\t\tPayloadSize: dc.PayloadSize,\n\t\tBucketDuration: dc.BucketDuration,\n\t\tResolution: dc.Resolution,\n\t\tSegmentSize: dc.SegmentSize,\n\t})\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdbs[\"test\"] = db\n\td = db\n\to = dc\n\n\ts = NewServer(dbs, cfg)\n\tgo s.Listen()\n\n\t// wait for the server to start\n\ttime.Sleep(time.Second * 2)\n\n\tc = NewClient(Address)\n\tif err := c.Connect(); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (m *Mosn) Init(c *v2.MOSNConfig) error {\n\tif c.CloseGraceful {\n\t\tc.DisableUpgrade = true\n\t}\n\tif err := m.inheritConfig(c); err != nil {\n\t\treturn err\n\t}\n\n\tlog.StartLogger.Infof(\"[mosn start] init the members of the mosn\")\n\n\t// after inherit config,\n\t// since metrics need the isFromUpgrade flag in Mosn\n\tm.initializeMetrics()\n\tm.initClusterManager()\n\tm.initServer()\n\n\t// set the mosn config finally\n\tconfigmanager.SetMosnConfig(m.Config)\n\treturn nil\n}", "func (c *Client) Init() (err error) {\n\tc.initOnce.Do(func() {\n\t\terr = c.init()\n\t})\n\n\treturn\n}", "func init() {\n\tSBC = data.NewBlockChain()\n\tid, _ := strconv.ParseInt(os.Args[1], 10, 32)\n\tPeers = data.NewPeerList( /*Register()*/ int32(id), 32) // Uses port number as ID since TA server is down\n\tprivateKey, publicKey = client.GenerateKeyPair()\n\tifStarted = false\n\tmpt.Initial()\n\tclientBalanceMap = make(map[string]int32)\n\tpendingTransaction = make(map[string]string)\n\ttransactionMpt.Initial()\n\tclientBalanceMap[string(client.PublicKeyToBytes(publicKey))] = 1000\n\thighestblockTransaction = 0\n}", "func (t *Ticker) Init() {\n\tt.ticker = time.NewTicker(t.UpdateInterval)\n}", "func Init() error {\n\tDg, err := discordgo.New(\"Bot \" + os.Getenv(\"DISCORD_TOKEN\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tDg.AddHandler(messageCreate)\n\n\treturn Dg.Open()\n}", "func init() {\n\thostifService = &HostifService{\n\t\tinstances: make(map[string]*HostifInstance),\n\t\tdone: make(chan struct{}),\n\t\tport: -1,\n\t}\n\n\tif l, err := vlog.New(moduleName); err == nil {\n\t\tlog = l\n\t} else {\n\t\tlog.Fatalf(\"Can't create logger: %s\", moduleName)\n\t}\n\n\trp := &vswitch.RingParam{\n\t\tCount: C.MAX_HOSTIF_MBUFS,\n\t\tSocketId: dpdk.SOCKET_ID_ANY,\n\t}\n\n\tif err := vswitch.RegisterModule(moduleName, newHostifInstance, rp, vswitch.TypeOther); err != nil {\n\t\tlog.Fatalf(\"Failed to register hostif: %v\", err)\n\t}\n}", "func (p *P2PServerV1) Init(ctx *nctx.NetCtx) error {\n\tpool, err := NewConnPool(ctx)\n\tif err != nil {\n\t\tp.log.Error(\"Init P2PServerV1 NewConnPool error\", \"error\", err)\n\t\treturn err\n\t}\n\n\tp.ctx = ctx\n\tp.log = ctx.GetLog()\n\tp.config = ctx.P2PConf\n\tp.pool = pool\n\tp.dispatcher = p2p.NewDispatcher(ctx)\n\n\t// address\n\tp.address, err = multiaddr.NewMultiaddr(ctx.P2PConf.Address)\n\tif err != nil {\n\t\tlog.Printf(\"network address error: %v\", err)\n\t\treturn ErrAddressIllegal\n\t}\n\n\t_, _, err = manet.DialArgs(p.address)\n\tif err != nil {\n\t\tlog.Printf(\"network address error: %v\", err)\n\t\treturn ErrAddressIllegal\n\t}\n\n\t// account\n\tkeyPath := ctx.EnvCfg.GenDataAbsPath(ctx.EnvCfg.KeyDir)\n\tp.account, err = xaddress.LoadAddress(keyPath)\n\tif err != nil {\n\t\tp.log.Error(\"load account error\", \"path\", keyPath)\n\t\treturn ErrLoadAccount\n\t}\n\tp.accounts = cache.New(cache.NoExpiration, cache.NoExpiration)\n\n\tp.bootNodes = make([]string, 0)\n\tp.staticNodes = make(map[string][]string, 0)\n\tp.dynamicNodes = make([]string, 0)\n\n\treturn nil\n}", "func Init(c *conf.Config) {\n\t// service\n\tinitService(c)\n\tSvc.InitCron()\n\t// init inner router\n\teng := bm.DefaultServer(c.BM.Outer)\n\tinnerRouter(eng)\n\tif err := eng.Start(); err != nil {\n\t\tlog.Error(\"bm.DefaultServer error(%v)\", err)\n\t\tpanic(err)\n\t}\n}", "func Init() {\n\tbtc()\n\tbch()\n\teth()\n\tltc()\n\tusdt()\n\n\tada()\n}", "func init() {\n\t// Seed the random number generator.\n\trand.Seed(time.Now().UnixNano())\n}", "func (mod *EthModule) Init() error {\n\tm := mod.eth\n\t// if didn't call NewEth\n\tif m.config == nil {\n\t\tm.config = DefaultConfig\n\t}\n\n\t//ethdoug.Adversary = mod.Config.Adversary\n\n\t// if no ethereum instance\n\tif m.ethereum == nil {\n\t\tm.ethConfig()\n\t\tm.newEthereum()\n\t}\n\n\t// public interface\n\tpipe := xeth.New(m.ethereum)\n\t// load keys from file. genesis block keys. convenient for testing\n\n\tm.pipe = pipe\n\tm.keyManager = m.ethereum.KeyManager()\n\t//m.reactor = m.ethereum.Reactor()\n\n\t// subscribe to the new block\n\tm.chans = make(map[string]chan types.Event)\n\t//m.reactchans = make(map[string]chan ethreact.Event)\n\tm.Subscribe(\"newBlock\", \"newBlock\", \"\")\n\n\tlog.Println(m.ethereum.Port)\n\n\treturn nil\n}", "func Init() {\n\t// r := router.Get()\n\t// r.GET(\"/publishOffers\", func(ctx *gin.Context) {\n\t// \tctx.JSON(200, offersController.PublishOffers(ctx))\n\t// })\n}", "func (n *natsBroker) Init(opts broker.Options) error {\n\tn.options = opts\n\treturn nil\n}", "func (d *Default) Init(c *viper.Viper) error {\n\tlog.Println(\"Init called\")\n\treturn nil\n}", "func Init() {\n\tr := Router()\n\tr.Run()\n}", "func init() {\n\tconfig.Read()\n\n\tdao.Server = config.Server\n\tdao.Database = config.Database\n\tdao.Connect()\n}", "func init() {\n\tconfig.Read()\n\n\tdao.Server = config.Server\n\tdao.Database = config.Database\n\tdao.Connect()\n}", "func (g *Gorc) Init() {\n\tg.Lock()\n\tg.count = 0\n\tg.waitMillis = 100 * time.Millisecond\n\tg.Unlock()\n}", "func (cs Cluster) Init(ctx context.Context, out, errOut io.Writer) {\n\t// this retries until it succeeds, it won't return unless it does\n\te2e.Run(ctx, out, errOut, \"./cockroach\",\n\t\t\"init\",\n\t\t\"--insecure\",\n\t\t\"--host=\"+cs[0].Addr,\n\t)\n}", "func (connection *SSEConnection) Init() {\n\tconnection.isClosed = false\n\tconnection.messageSendChannel = make(chan []byte, 5)\n}", "func (sp *Subnetworks) Init(ip *IpAddress) {\n\tsp.SubnetMask = make([]byte, 4)\n\tsp.Ip = ip\n\tsp.THosts = 1\n\tsp.NHosts = 1\n\n}", "func (c *Consumer) Init() error {\n\tif err := c.Connect(); err != nil {\n\t\treturn err\n\t}\n\n\t// Producer and Consumer dec\n\tif err := c.ChannelDeclare(); err != nil {\n\t\treturn err\n\t}\n\tif err := c.ExchangeDeclare(); err != nil {\n\t\treturn err\n\t}\n\n\t// Consumer specific actions.\n\tif err := c.QueueDeclare(); err != nil {\n\t\treturn err\n\t}\n\tif err := c.QueueBind(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *CentralCacheTestImpl) Init(conf Config) {\n\tc.baseUrl = conf.Host\n\tc.keyPrefix = conf.KeyPrefix\n\tc.dumpFilePath = conf.DumpFilePath\n\tc.expirySec = conf.ExpirySec\n\tc.file = nil\n}", "func (c *Cafe) Init() {\n\tc.Name = \"Happy Coffee\"\n\tc.Drinks = []Drink{\n\t\t{\"Americano\", 3},\n\t\t{\"Cappuccino\", 5},\n\t\t{\"Latte\", 5},\n\t}\n\tc.CafeFood = []Food{\n\t\t{\"chocolate chip cookies\", 5, 78},\n\t\t{\"blueberry muffin\", 5, 467},\n\t\t{\"fruit cup\", 7, 124},\n\t}\n}", "func (s *Server) Initialize(log logging.Logger, factory logging.Factory, host string, port uint16) {\n\ts.log = log\n\ts.factory = factory\n\ts.listenAddress = fmt.Sprintf(\"%s:%d\", host, port)\n\ts.router = newRouter()\n}", "func (s *Server) Init(dbconf, env, esurl, fluentHost string) {\n\tcs, err := db.NewConfigsFromFile(dbconf)\n\tif err != nil {\n\t\tlog.Fatalf(\"cannot open database configuration. exit. %s\", err)\n\t}\n\tdb, err := cs.Open(env)\n\tif err != nil {\n\t\tlog.Fatalf(\"db initialization failed: %s\", err)\n\t}\n\ts.db = db\n\n\tclient, err := elastic.NewClient(\n\t\telastic.SetURL(esurl),\n\t\telastic.SetMaxRetries(5),\n\t\telastic.SetSniff(false))\n\tif err != nil {\n\t\tlog.Fatalf(\"initialize Elasticsearch client failed: %s\", err)\n\t}\n\ts.es = client\n\n\tfor {\n\t\tlogger, err := fluent.New(fluent.Config{\n\t\t\tFluentHost: fluentHost,\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Printf(\"initialize fluentd client failed: %s\", err)\n\t\t\ttime.Sleep(time.Second)\n\t\t\tcontinue\n\t\t}\n\t\ts.fluent = logger\n\t\tbreak\n\t}\n\n\t// NOTE: define helper func to use from templates here.\n\tt := template.Must(template.New(\"\").Funcs(template.FuncMap{\n\t\t\"LoggedIn\": controller.LoggedIn,\n\t\t\"CurrentName\": controller.CurrentName,\n\t\t\"nl2br\": func(text string) template.HTML {\n\t\t\treturn template.HTML(strings.Replace(template.HTMLEscapeString(text), \"\\n\", \"<br>\", -1))\n\t\t},\n\t}).ParseGlob(\"templates/*\"))\n\ts.Engine.SetHTMLTemplate(t)\n\n\tstore := sessions.NewCookieStore([]byte(\"secretkey\"))\n\ts.Engine.Use(sessions.Sessions(\"blogsession\", store))\n\ts.Engine.Use(csrf.Middleware(csrf.Options{\n\t\tSecret: \"secretkey\",\n\t\tErrorFunc: func(c *gin.Context) {\n\t\t\tc.String(400, \"CSRF token mismach\")\n\t\t\tc.Abort()\n\t\t},\n\t}))\n\n\ts.Route()\n}", "func (node_p *Node) Init(addr *string, gway_addr *string) error {\n\tvar rnum_str string = strconv.FormatInt(int64(rand.Int()), 10)\n\tnode_p.hash = utils.HashStr([]byte(rnum_str))\n\n\tnode_p.omap = &objmap.ObjMap{}\n\tnode_p.nmap = &nbrmap.NbrMap{}\n\n\tnode_p.omap.Init()\n\tnode_p.nmap.Init()\n\n\tnode_p.conn = &connector.Connector{}\n\tif err := node_p.conn.Init(addr, node_p.nchan); err != nil {\n\t\treturn err\n\t}\n\n\tnode_p.nchan = make(chan pkt.Envelope)\n\tnode_p.wg = &sync.WaitGroup{}\n\n\tnode_p.wg.Add(1)\n\tgo func() { node_p.collector(); node_p.wg.Done() }()\n\n\treturn nil\n}", "func (ks *KerbServer) Init(srv string) error {\n\tservice := C.CString(srv)\n\tdefer C.free(unsafe.Pointer(service))\n\n\tresult := 0\n\n\tks.state = C.new_gss_server_state()\n\tif ks.state == nil {\n\t\treturn errors.New(\"Failed to allocate memory for gss_server_state\")\n\t}\n\n\tresult = int(C.authenticate_gss_server_init(service, ks.state))\n\n\tif result == C.AUTH_GSS_ERROR {\n\t\treturn ks.GssError()\n\t}\n\n\treturn nil\n}", "func (h *facts) Init(output chan<- *plugin.SlackResponse, bot *plugin.Bot) {\n\th.sink = output\n\th.bot = bot\n\th.configuration = viper.New()\n\th.configuration.AddConfigPath(\"/etc/slackhal/\")\n\th.configuration.AddConfigPath(\"$HOME/.slackhal\")\n\th.configuration.AddConfigPath(\".\")\n\th.configuration.SetConfigName(\"plugin-facts\")\n\th.configuration.SetConfigType(\"yaml\")\n\terr := h.configuration.ReadInConfig()\n\tif err != nil {\n\t\tzap.L().Error(\"Not able to read configuration for facts plugin.\", zap.Error(err))\n\t\th.Disabled = true\n\t\treturn\n\t}\n\tdbPath := h.configuration.GetString(\"database.path\")\n\th.factDB = new(stormDB)\n\terr = h.factDB.Connect(dbPath)\n\tif err != nil {\n\t\tzap.L().Error(\"Error while opening the facts database!\", zap.Error(err))\n\t\th.Disabled = true\n\t\treturn\n\t}\n}", "func init() {\n\tShCache = &ShareCache{\n\t\tLRPC: &LeaderRpcAddr{\n\t\t\tAddr: \"\",\n\t\t\tPort: \"\",\n\t\t},\n\t}\n}", "func Init() *Server {\n\ts := &Server{\n\t\t&goserver.GoServer{},\n\t\t0,\n\t}\n\treturn s\n}", "func Init(b *thinkbot.BotConfig) {\n\tinitCommands(b.Commands())\n\tinitChat(b)\n}", "func Init(s *session.Session) {\n\tEC2Client(ec2.New(s))\n\tRDSClient(rds.New(s))\n\tS3Client(s3.New(s))\n\tIAMClient(iam.New(s))\n}", "func (a *App) Init() {\n\tvar connectionString = \"user:password@tcp(127.0.0.1:3306)/sports_betting_db\"\n\targs := os.Args[1:]\n\tif len(args) > 0 {\n\t\tconnectionString = args[0]\n\t}\n\ta.BetsRepo = betsrepo.NewMysqlRepo(connectionString)\n\ta.Validator = validator.New()\n\ta.Router = chi.NewRouter()\n\ta.initializeRoutes()\n}", "func init() {\n\tinitDebug = sshd.InitDebug\n}" ]
[ "0.62318414", "0.6002665", "0.59760803", "0.59645134", "0.59495103", "0.58841854", "0.58765775", "0.5870722", "0.5869919", "0.58451617", "0.5822587", "0.5807598", "0.58051634", "0.5801144", "0.5784549", "0.5766516", "0.57660747", "0.5739402", "0.5733225", "0.5726329", "0.57076824", "0.5673344", "0.5672071", "0.5672071", "0.5666379", "0.5653408", "0.56520396", "0.5644767", "0.5643053", "0.56107485", "0.5591061", "0.55774456", "0.5575241", "0.5553579", "0.5549148", "0.5546096", "0.55277044", "0.551216", "0.55108774", "0.5507034", "0.5501492", "0.55006456", "0.54833305", "0.5480743", "0.5480743", "0.5480743", "0.5480743", "0.5480743", "0.5480743", "0.5480743", "0.54802597", "0.54768795", "0.5470111", "0.54681724", "0.5457353", "0.54514533", "0.54506946", "0.5448395", "0.5448395", "0.5448395", "0.5448395", "0.54425585", "0.5441364", "0.54387265", "0.54337925", "0.54311585", "0.54304945", "0.54290205", "0.54240996", "0.5420426", "0.54195994", "0.5419472", "0.5416404", "0.54115766", "0.5398903", "0.5396534", "0.53898567", "0.5380353", "0.5378875", "0.5358629", "0.5358398", "0.5358398", "0.5357906", "0.53576523", "0.5348737", "0.5344784", "0.534322", "0.53354657", "0.53318995", "0.53291756", "0.53280914", "0.532543", "0.53241324", "0.5323008", "0.53225595", "0.53201425", "0.53139395", "0.5309129", "0.53002656", "0.52998793" ]
0.79313505
0
newPhilosopherDataPtr creates and initializes a philosopherData object and returns a pointer to it.
func newPhilosopherDataPtr(respChannel chan string) *philosopherData { pd := new(philosopherData) pd.Init(respChannel) return pd }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewPhilosopherPtr(name string) *Philosopher {\n\tphi := new(Philosopher)\n\tphi.Init(name)\n\treturn phi\n}", "func (L *State) NewUserdata(size uintptr) unsafe.Pointer {\n\treturn unsafe.Pointer(C.lua_newuserdata(L.s, C.size_t(size)))\n}", "func NewData() *Data {\n d := &Data{}\n d.hashMap = make(map[int]string)\n return d\n}", "func (pd *philosopherData) Init(respChannel chan string) {\n\tpd.respChannel = respChannel\n\tpd.eating = false\n\tpd.dinnersSpent = 0\n\tpd.seat = -1\n\tpd.leftChopstick = -1\n\tpd.rightChopstick = -1\n}", "func NewNewData() *NewData {\n\tthis := NewData{}\n\treturn &this\n}", "func NewData(ctx *gin.Context) Data {\n\treturn Data{\n\t\tData: webbase.NewData(\"Golinks\", ctx),\n\t}\n}", "func NewData() Data {\n\treturn Data(\"GO\")\n}", "func NewData() *Data {\n\treturn &Data{}\n}", "func DataGenFromPtr(ptr unsafe.Pointer) *DataGen {\n\treturn (*DataGen)(ptr)\n}", "func NewData() *Data {\n\treturn new(Data)\n}", "func (w *World) NewData() {\n\tw.Data = &ScenarioData{}\n\tw.Client = NewClient(w.serverUrl)\n}", "func NewData(name, datadir string) (*Data, error) {\n\tdata := &Data{}\n\tdata.name = name\n\tdata.datadir = datadir\n\tdata.mutex = new(sync.Mutex)\n\terr := data.init()\n\tif err != nil {\n\t\tlog.Printf(\"data.init Error : %+v\", err)\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}", "func NewData(g func(ctx context.Context) (*grpc.ClientConn, error)) *Data {\n\treturn &Data{g}\n}", "func NewData() *Data {\n\tnmap := make(map[interface{}]int)\n\treturn &Data{\n\t\tm: nmap,\n\t}\n\t// return make(Data)\n}", "func NewWebPartData()(*WebPartData) {\n m := &WebPartData{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func NewGenData() *GenData {\n\tgd := &GenData{}\n\treturn gd\n}", "func newDataStore() *dataStore {\n\tds := dataStore{\n\t\tdata: make(map[string]Info),\n\t}\n\treturn &ds\n}", "func New() *Data {\n\treturn &Data{\n\t\tValues: make(map[string]DataType),\n\t\tData: make(map[string]interface{}),\n\t\tunexportedData: make(map[string]interface{}),\n\t\tcache: make(map[string]interface{}),\n\t}\n}", "func NewUserData() *UserData {\r\n\treturn &UserData{\r\n\t\tdata: New(),\r\n\t\tcoll: data.DBCollection(UserColletion),\r\n\t}\r\n\r\n}", "func NewPrivilegedData(type_ Secrettypes) *PrivilegedData {\n\tthis := PrivilegedData{}\n\tthis.Type = type_\n\treturn &this\n}", "func NewData(title string, ginctx *gin.Context) Data {\n\tdata := Data{\n\t\tTitle: title,\n\t\tBinVersion: version.Version(),\n\t}\n\torg, err := ctx.GetOrg(ginctx)\n\tif err == nil {\n\t\tdata.Ctx.Org = org.Name\n\t}\n\tuser, err := ctx.GetUser(ginctx)\n\tif err == nil {\n\t\tdata.Ctx.User = user.Email\n\t\tdata.Ctx.LoggedIn = true\n\t}\n\tdata.Ctx.AuthEnabled = ctx.IsAuthEnabled(ginctx)\n\treturn data\n}", "func NewHOTP() *HOTP { return &HOTP{} }", "func newpcdataprog(prog *obj.Prog, index int32) *obj.Prog {\n\tvar from Node\n\tvar to Node\n\n\tNodconst(&from, Types[TINT32], obj.PCDATA_StackMapIndex)\n\tNodconst(&to, Types[TINT32], int64(index))\n\tpcdata := unlinkedprog(obj.APCDATA)\n\tpcdata.Lineno = prog.Lineno\n\tNaddr(&pcdata.From, &from)\n\tNaddr(&pcdata.To, &to)\n\treturn pcdata\n}", "func (pb *PhilosopherBase) LeftPhilosopher() Philosopher {\n\t// Add NPhils to avoid a negative index\n\tindex := (pb.ID + NPhils - 1) % NPhils\n\treturn Philosophers[index]\n}", "func newDataHandler(prices []DataPoint) *DataHandler {\n\treturn &DataHandler{\n\t\tPrices: prices,\n\t}\n}", "func newPiholeClient(cfg PiholeConfig) (piholeAPI, error) {\n\tif cfg.Server == \"\" {\n\t\treturn nil, ErrNoPiholeServer\n\t}\n\n\t// Setup a persistent cookiejar for storing PHP session information\n\tjar, err := cookiejar.New(&cookiejar.Options{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Setup an HTTP client using the cookiejar\n\thttpClient := &http.Client{\n\t\tJar: jar,\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tInsecureSkipVerify: cfg.TLSInsecureSkipVerify,\n\t\t\t},\n\t\t},\n\t}\n\tcl := instrumented_http.NewClient(httpClient, &instrumented_http.Callbacks{})\n\n\tp := &piholeClient{\n\t\tcfg: cfg,\n\t\thttpClient: cl,\n\t}\n\n\tif cfg.Password != \"\" {\n\t\tif err := p.retrieveNewToken(context.Background()); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn p, nil\n}", "func newProxy(pType ProxyType) (proxy, error) {\n\tswitch pType {\n\tcase NoopProxyType:\n\t\treturn &noopProxy{}, nil\n\tcase CCProxyType:\n\t\treturn &ccProxy{}, nil\n\tdefault:\n\t\treturn &noopProxy{}, nil\n\t}\n}", "func newGreetingRepository(db *sql.DB) engine.GreetingRepository {\n\treturn &greetingRepository{db}\n}", "func NewPomeloPacketDecoder() *PomeloPacketDecoder {\n\treturn &PomeloPacketDecoder{}\n}", "func NewDataProvider(filePath string, skipHeader bool) *DataProvider {\n\treturn &DataProvider{\n\t\tfilePath: filePath,\n\t\tskipHeader: skipHeader,\n\t}\n}", "func NewP2P() *P2P {\n\t// Setup a background context\n\tctx := context.Background()\n\n\t// Setup a P2P Host Node\n\tnodehost, kaddht := setupHost(ctx)\n\t// Debug log\n\tlogrus.Debugln(\"Created the P2P Host and the Kademlia DHT.\")\n\n\t// Bootstrap the Kad DHT\n\tbootstrapDHT(ctx, nodehost, kaddht)\n\t// Debug log\n\tlogrus.Debugln(\"Bootstrapped the Kademlia DHT and Connected to Bootstrap Peers\")\n\n\t// Create a peer discovery service using the Kad DHT\n\troutingdiscovery := discovery.NewRoutingDiscovery(kaddht)\n\t// Debug log\n\tlogrus.Debugln(\"Created the Peer Discovery Service.\")\n\n\t// Create a PubSub handler with the routing discovery\n\tpubsubhandler := setupPubSub(ctx, nodehost, routingdiscovery)\n\t// Debug log\n\tlogrus.Debugln(\"Created the PubSub Handler.\")\n\n\t// Return the P2P object\n\treturn &P2P{\n\t\tCtx: ctx,\n\t\tHost: nodehost,\n\t\tKadDHT: kaddht,\n\t\tDiscovery: routingdiscovery,\n\t\tPubSub: pubsubhandler,\n\t}\n}", "func NewFPGADevicePlugin() *FPGADevicePlugin {\n\tlog.Debugf(\"create FPGA device plugin\")\n\tupdateChan := make(chan map[string]map[string]Device)\n\tplugin := FPGADevicePlugin{\n\t\tdevices: make(map[string]map[string]Device),\n\t\tservers: make(map[string]*FPGADevicePluginServer),\n\t\tupdateChan: updateChan,\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\tdevices, err := GetDevices()\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Error to get FPGA devices: %v\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tdevMap := make(map[string]map[string]Device)\n\t\t\tfor _, device := range devices {\n\t\t\t\tDSAtype := device.shellVer + \"-\" + device.timestamp\n\t\t\t\tid := device.DBDF\n\t\t\t\tif subMap, ok := devMap[DSAtype]; ok {\n\t\t\t\t\tsubMap = devMap[DSAtype]\n\t\t\t\t\tsubMap[id] = device\n\t\t\t\t} else {\n\t\t\t\t\tsubMap = make(map[string]Device)\n\t\t\t\t\tdevMap[DSAtype] = subMap\n\t\t\t\t\tsubMap[id] = device\n\t\t\t\t}\n\t\t\t}\n\t\t\t//log.Debugf(\"newly reported FPGA device list: %v\", devMap)\n\t\t\tupdateChan <- devMap\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t}\n\t\tclose(updateChan)\n\t}()\n\n\treturn &plugin\n}", "func NewDataInstance(aad []byte, hash [32]byte, note []byte) Data {\n\treturn Data{\n\t\tAAD: aad,\n\t\tHash: hash,\n\t\tNote: note,\n\t}\n}", "func NewDinnerHostPtr(tableCount, maxParallel, maxDinner int) *DinnerHost {\n\thost := new(DinnerHost)\n\thost.Init(tableCount, maxParallel, maxDinner)\n\treturn host\n}", "func NewUserData() *UserData {\n\tud := &UserData{GetConnIns()}\n\tif err := ud.conn.Sync2(new(User)); err != nil {\n\t\tlog.Panic(err)\n\t}\n\treturn ud\n}", "func (host *DinnerHost) Add(newPhilosopher Philosopher) bool {\n\tnewName := newPhilosopher.Name()\n\tfmt.Println(newName + \" WANTS TO JOIN THE TABLE.\")\n\tif len(host.phiData) >= host.tableCount {\n\t\tfmt.Println(newName + \" CANNOT JOIN: THE TABLE IS FULL.\")\n\t\tfmt.Println()\n\t\treturn false\n\t}\n\tif host.phiData[newName] != nil {\n\t\tfmt.Println(newName + \" CANNOT JOIN: ALREADY ON THE HOST'S LIST.\")\n\t\tfmt.Println()\n\t\treturn false\n\t}\n\thost.phiData[newName] = newPhilosopherDataPtr(newPhilosopher.RespChannel())\n\thost.phiData[newName].TakeSeat(host.freeSeats[0])\n\thost.freeSeats = host.freeSeats[1:]\n\tfmt.Println(newName + \" JOINED THE TABLE.\")\n\tfmt.Println()\n\treturn true\n}", "func NewTokenData(t Token) TokenData {\n\tret := TokenData{\n\t\tID: t.ID,\n\t\tStart: t.Start,\n\t\tEnd: t.End,\n\t\tSurface: t.Surface,\n\t\tClass: t.Class.String(),\n\t\tPOS: t.POS(),\n\t\tFeatures: t.Features(),\n\t}\n\tif ret.POS == nil {\n\t\tret.POS = []string{}\n\t}\n\tif ret.Features == nil {\n\t\tret.Features = []string{}\n\t}\n\tret.BaseForm, _ = t.BaseForm()\n\tret.Reading, _ = t.Reading()\n\tret.Pronunciation, _ = t.Pronunciation()\n\treturn ret\n}", "func newMeasurementData(role uint8) MeasurementData {\n\treturn MeasurementData{\n\t\tMeasurementHeaderData{\n\t\t\t0, // latencySpin\n\t\t\ttrue, // latencyValid\n\t\t\tfalse, // blocking\n\t\t\tstatusInvalid, // latencyStatus\n\t\t\tfalse, // loss\n\t\t\ttrue, // latencyValidEdge\n\t\t},\n\t\t0, // maxPacketNumber\n\t\trole, // role\n\t\ttime.Now(), // latencyRxEdgeTime\n\t\t0xff, // lastRxLatencySpin\n\t\tfalse, // generatingEdge\n\t\tstatusInvalid, // incommingLatencyStatus\n }\n}", "func newProtonInstance(proton core.Protoner) reflect.Value {\n\tbaseValue := reflect.ValueOf(proton)\n\n\t// try to create new value of proton\n\tmethod := baseValue.MethodByName(\"New\")\n\tif method.IsValid() {\n\t\treturns := method.Call(emptyParameters)\n\t\tif len(returns) <= 0 {\n\t\t\tpanic(fmt.Sprintf(\"Method New must has at least 1 returns. now %d\", len(returns)))\n\t\t}\n\t\treturn returns[0]\n\t} else {\n\t\t// return reflect.New(reflect.TypeOf(proton).Elem())\n\t\treturn newInstance(reflect.TypeOf(proton))\n\t}\n}", "func NewProcTable() *ProcTableImpl {\n\treturn &ProcTableImpl{procTable: make(map[string]ProcEntry)}\n}", "func NewPHCInfo() *PHCInfo {\n\treturn &PHCInfo{\n\t\tParamInfos: nil,\n\t\tMinSaltLength: -1,\n\t\tMaxSaltLength: -1,\n\t\tMinHashLength: -1,\n\t\tMaxHashLength: -1,\n\t}\n}", "func NewDataService(vm *otto.Otto, context *Context, stub shim.ChaincodeStubInterface) (result *DataService) {\n\tlogger.Debug(\"Entering NewDataService\", vm, context, stub)\n\tdefer func() { logger.Debug(\"Exiting NewDataService\", result) }()\n\n\t// Create a new instance of the JavaScript chaincode class.\n\ttemp, err := vm.Call(\"new concerto.DataService\", nil, context.This)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Failed to create new instance of DataService JavaScript class: %v\", err))\n\t} else if !temp.IsObject() {\n\t\tpanic(\"New instance of DataService JavaScript class is not an object\")\n\t}\n\tobject := temp.Object()\n\n\t// Add a pointer to the Go object into the JavaScript object.\n\tresult = &DataService{This: temp.Object(), Stub: stub}\n\terr = object.Set(\"$this\", result)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Failed to store Go object in DataService JavaScript object: %v\", err))\n\t}\n\n\t// Bind the methods into the JavaScript object.\n\tresult.This.Set(\"_createCollection\", result.createCollection)\n\tresult.This.Set(\"_deleteCollection\", result.deleteCollection)\n\tresult.This.Set(\"_getCollection\", result.getCollection)\n\tresult.This.Set(\"_existsCollection\", result.existsCollection)\n\treturn result\n\n}", "func New(L *lua.LState, rootDir, cacheDir, pluginName, host, dbname, user, password string, port int, params map[string]string) error {\n\tpool := plugins.NewPool(rootDir, cacheDir)\n\tconn := &plugins.Connection{\n\t\tHost: host,\n\t\tDBName: dbname,\n\t\tPort: port,\n\t\tUserName: user,\n\t\tPassword: password,\n\t\tParams: params,\n\t}\n\tconnections := make(map[string]*plugins.Connection)\n\tconnections[`target`] = conn\n\tconnections[`storage`] = conn\n\tf := &framework{\n\t\tpool: pool,\n\t\tpluginName: pluginName,\n\t\thost: pluginName,\n\t\tsecrets: secrets.New(``),\n\t}\n\tpool.RegisterHost(f.host, connections)\n\tud := L.NewUserData()\n\tud.Value = f\n\tL.SetMetatable(ud, L.GetTypeMetatable(`testing_framework_ud`))\n\tL.SetGlobal(\"tested_plugin\", ud)\n\treturn nil\n}", "func (phi *Philosopher) Init(name string) {\n\tphi.name = name\n\tphi.respChannel = make(chan string)\n}", "func NewData(uuid dvid.UUID, id dvid.InstanceID, name dvid.InstanceName, c dvid.Config) (*Data, error) {\n\t// Initialize the Data for this data type\n\tbasedata, err := datastore.NewDataService(dtype, uuid, id, name, c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdata := &Data{\n\t\tData: basedata,\n\t\tProperties: Properties{},\n\t}\n\treturn data, nil\n}", "func NewFakeProcTable() *FakeProcTableImpl {\n\treturn &FakeProcTableImpl{realTable: NewProcTable()}\n}", "func (t ObjectType) NewData(baseType interface{}, sliceLen, bufSize int) ([]*Data, error) {\n\treturn t.conn.NewData(baseType, sliceLen, bufSize)\n}", "func NewDataManager(cfg config.Config, logger *zap.Logger, dbc DBCreator) (*DataManager, error) {\n\topdb := dbc(\"genesisop.db\")\n\tqdb := dbc(\"genesisquery.db\")\n\n\t// GetInitSQLs has nothing to do with specific instances, so use opdb or qdb are both ok\n\topt, opi, qt, qi := opdb.GetInitSQLs()\n\terr := opdb.PrepareTables(opt, opi)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = qdb.PrepareTables(qt, qi)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdm := &DataManager{\n\t\topdb: opdb,\n\t\tqdb: qdb,\n\t}\n\tswitch cfg.GetString(\"db_type\") {\n\tcase database.DBTypeSQLite3:\n\t\tdm.opNeedLock = true\n\t\tdm.qNeedLock = true\n\tdefault:\n\t\tdm.opNeedLock = true\n\t\tdm.qNeedLock = true\n\t}\n\n\treturn dm, nil\n}", "func NewHelloWorld(pid uint8) *HelloWorld {\n\tp := &HelloWorld{\n\t\tpid: pid,\n\t}\n\treturn p\n}", "func (p *ProviderData) Data() *ProviderData { return p }", "func newHypothesis() (hyp [cityCount]int) {\n\tfor i := 0; i < len(hyp); i++ {\n\t\thyp[i] = i\n\t}\n\t//Initial travel path is shuffled\n\trand.Shuffle(len(hyp), func(i, j int) {\n\t\thyp[i], hyp[j] = hyp[j], hyp[i]\n\t})\n\treturn hyp\n}", "func (pb *PhilosopherBase) GetID() int {\n\treturn pb.ID\n}", "func newPebbleDB(conf store.Conf) (store.DB, error) {\n\terr := os.MkdirAll(conf.Path, 0755)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\tdb, err := pebble.Open(conf.Path, &pebble.Options{})\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\treturn &pebbleDB{\n\t\tDB: db,\n\t\tconf: conf,\n\t}, nil\n}", "func newWithDatastorer(name string, datastorer datastorer) (dsdb *DatastoreDB, err error) {\n\tdsdb = new(DatastoreDB)\n\tdsdb.kind = name\n\tdsdb.datastorer = datastorer\n\n\terr = dsdb.connect()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = dsdb.testDB()\n\tif err = dsdb.testDB(); err != nil {\n\t\tdsdb.Close()\n\t\treturn nil, err\n\t}\n\n\treturn dsdb, nil\n}", "func NewPGConnector() *PGConnector { return &PGConnector{} }", "func NewPGConnector() *PGConnector { return &PGConnector{} }", "func NewGenericData(code OP_CODE, length int, data []byte) *GenericData {\n gc := &GenericData{OpCode: code}\n switch code {\n case CR_OP_INC_BYTE:\n if length == 0 || len(data) == 0 {\n panic(\"Missing length or data for CR_OP_INC_BYTE\")\n }\n if len(data) > 1 {\n panic(\"Too much data for CR_OP_INC_BYTE\")\n }\n gc.Length = length\n gc.Data = data\n\n case CR_OP_RLE:\n if length == 0 || len(data) == 0 {\n panic(\"Missing length or data for CR_OP_RLE\")\n }\n if len(data) > 1 {\n panic(\"Too much data for CR_OP_RLE\")\n }\n gc.Length = length\n gc.Data = data\n\n case CR_OP_BYTE_LIST:\n if len(data) == 0 {\n panic(\"Missing data for CR_OP_BYTE_LIST\")\n }\n gc.Length = len(data)\n gc.Data = data\n\n case CR_OP_ATTR:\n if len(data) == 0 {\n panic(\"Missing data for CR_OP_ATTR\")\n }\n if len(data) > 1 {\n panic(\"Too much data for CR_OP_ATTR\")\n }\n gc.Data = data\n }\n return gc\n}", "func newPseudoProfile(k int, p float64) FracProfile {\n\ta := make(FracProfile, k)\n\tp4 := [4]float64{p, p, p, p}\n\tfor i := range a {\n\t\ta[i] = p4\n\t}\n\treturn a\n}", "func NewPier(repoRoot string, config *repo.Config) (*Pier, error) {\n\tstore, err := leveldb.New(filepath.Join(config.RepoRoot, \"store\"))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"read from datastaore %w\", err)\n\t}\n\n\tlogger := loggers.Logger(loggers.App)\n\tprivateKey, err := repo.LoadPrivateKey(repoRoot)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"repo load key: %w\", err)\n\t}\n\n\taddr, err := privateKey.PublicKey().Address()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"get address from private key %w\", err)\n\t}\n\n\tnodePrivKey, err := repo.LoadNodePrivateKey(repoRoot)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"repo load node key: %w\", err)\n\t}\n\n\tvar (\n\t\tck checker.Checker\n\t\tcryptor txcrypto.Cryptor\n\t\tex exchanger.IExchanger\n\t\tlite lite.Lite\n\t\tpierHA agency.PierHA\n\t\tsync syncer.Syncer\n\t\tapiServer *api.Server\n\t\tmeta *pb.Interchain\n\t\t//chain *appchainmgr.Appchain\n\t\tpeerManager peermgr.PeerManager\n\t)\n\n\tswitch config.Mode.Type {\n\tcase repo.DirectMode: //直链模式\n\t\tpeerManager, err = peermgr.New(config, nodePrivKey, privateKey, 1, loggers.Logger(loggers.PeerMgr))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"peerMgr create: %w\", err)\n\t\t}\n\n\t\truleMgr, err := rulemgr.New(store, peerManager, loggers.Logger(loggers.RuleMgr))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"ruleMgr create: %w\", err)\n\t\t}\n\n\t\tappchainMgr, err := appchain.NewManager(config.Appchain.DID, store, peerManager, loggers.Logger(loggers.AppchainMgr))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"ruleMgr create: %w\", err)\n\t\t}\n\n\t\tapiServer, err = api.NewServer(appchainMgr, peerManager, config, loggers.Logger(loggers.ApiServer))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"gin service create: %w\", err)\n\t\t}\n\n\t\tck = checker.NewDirectChecker(ruleMgr, appchainMgr)\n\n\t\tcryptor, err = txcrypto.NewDirectCryptor(appchainMgr, privateKey)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cryptor create: %w\", err)\n\t\t}\n\n\t\tmeta = &pb.Interchain{}\n\t\tlite = &direct_lite.MockLite{}\n\tcase repo.RelayMode: //中继链架构模式。\n\t\tck = &checker.MockChecker{}\n\n\t\t// pier register to bitxhub and got meta infos about its related\n\t\t// appchain from bitxhub\n\t\topts := []rpcx.Option{\n\t\t\trpcx.WithLogger(logger),\n\t\t\trpcx.WithPrivateKey(privateKey),\n\t\t}\n\t\tnodesInfo := make([]*rpcx.NodeInfo, 0, len(config.Mode.Relay.Addrs))\n\t\tfor _, addr := range config.Mode.Relay.Addrs {\n\t\t\tnodeInfo := &rpcx.NodeInfo{Addr: addr}\n\t\t\tif config.Security.EnableTLS {\n\t\t\t\tnodeInfo.CertPath = filepath.Join(config.RepoRoot, config.Security.Tlsca)\n\t\t\t\tnodeInfo.EnableTLS = config.Security.EnableTLS\n\t\t\t\tnodeInfo.CommonName = config.Security.CommonName\n\t\t\t}\n\t\t\tnodesInfo = append(nodesInfo, nodeInfo)\n\t\t}\n\t\topts = append(opts, rpcx.WithNodesInfo(nodesInfo...), rpcx.WithTimeoutLimit(config.Mode.Relay.TimeoutLimit))\n\t\tclient, err := rpcx.New(opts...)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"create bitxhub client: %w\", err)\n\t\t}\n\n\t\t// agent queries appchain info from bitxhub\n\t\tmeta, err = getInterchainMeta(client, config.Appchain.DID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t//chain, err = getAppchainInfo(client)\n\t\t//if err != nil {\n\t\t//\treturn nil, err\n\t\t//}\n\n\t\tcryptor, err = txcrypto.NewRelayCryptor(client, privateKey)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cryptor create: %w\", err)\n\t\t}\n\n\t\tlite, err = bxh_lite.New(client, store, loggers.Logger(loggers.BxhLite))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"lite create: %w\", err)\n\t\t}\n\n\t\tsync, err = syncer.New(addr.String(), config.Appchain.DID, repo.RelayMode,\n\t\t\tsyncer.WithClient(client), syncer.WithLite(lite),\n\t\t\tsyncer.WithStorage(store), syncer.WithLogger(loggers.Logger(loggers.Syncer)),\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"syncer create: %w\", err)\n\t\t}\n\t\tpierHAConstructor, err := agency.GetPierHAConstructor(config.HA.Mode)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"pier ha constructor not found\")\n\t\t}\n\t\tpierHA = pierHAConstructor(client, config.Appchain.DID)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported mode\")\n\t}\n\n\t//use meta info to instantiate monitor and executor module\n\textra, err := json.Marshal(meta.InterchainCounter)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"marshal interchain meta: %w\", err)\n\t}\n\n\tvar cli plugins.Client\n\tvar grpcPlugin *plugin.Client\n\terr = retry.Retry(func(attempt uint) error {\n\t\tcli, grpcPlugin, err = plugins.CreateClient(config.Appchain.DID, config.Appchain, extra)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(\"client plugin create:%s\", err)\n\t\t}\n\t\treturn err\n\t}, strategy.Wait(3*time.Second))\n\tif err != nil {\n\t\tlogger.Panic(err)\n\t}\n\n\tmnt, err := monitor.New(cli, cryptor, loggers.Logger(loggers.Monitor))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"monitor create: %w\", err)\n\t}\n\n\texec, err := executor.New(cli, config.Appchain.DID, store, cryptor, loggers.Logger(loggers.Executor))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"executor create: %w\", err)\n\t}\n\n\tex, err = exchanger.New(config.Mode.Type, config.Appchain.DID, meta,\n\t\texchanger.WithChecker(ck),\n\t\texchanger.WithExecutor(exec),\n\t\texchanger.WithMonitor(mnt),\n\t\texchanger.WithPeerMgr(peerManager),\n\t\texchanger.WithSyncer(sync),\n\t\texchanger.WithAPIServer(apiServer),\n\t\texchanger.WithStorage(store),\n\t\texchanger.WithLogger(loggers.Logger(loggers.Exchanger)),\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"exchanger create: %w\", err)\n\t}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\n\treturn &Pier{\n\t\tprivateKey: privateKey,\n\t\tplugin: cli,\n\t\tgrpcPlugin: grpcPlugin,\n\t\t// appchain: chain,\n\t\tmeta: meta,\n\t\tmonitor: mnt,\n\t\texchanger: ex,\n\t\texec: exec,\n\t\tlite: lite,\n\t\tpierHA: pierHA,\n\t\tlogger: logger,\n\t\tstorage: store,\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\tconfig: config,\n\t}, nil\n}", "func (test *singleFileTest) newDeclData(shortName, fullIdentifier string) *mojom_types.DeclarationData {\n\treturn &mojom_types.DeclarationData{\n\t\tShortName: &shortName,\n\t\tFullIdentifier: &fullIdentifier,\n\t\tDeclaredOrdinal: -1,\n\t\tDeclarationOrder: -1,\n\t\tSourceFileInfo: &mojom_types.SourceFileInfo{\n\t\t\tFileName: test.fileName(),\n\t\t}}\n}", "func New(tstore plugins.TstoreClient, settings []backend.PluginSetting, dataDir string) (*usermdPlugin, error) {\n\t// Create plugin data directory\n\tdataDir = filepath.Join(dataDir, usermd.PluginID)\n\terr := os.MkdirAll(dataDir, 0700)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &usermdPlugin{\n\t\ttstore: tstore,\n\t\tdataDir: dataDir,\n\t}, nil\n}", "func NewDataNode(ctx context.Context, factory dependency.Factory) *DataNode {\n\trand.Seed(time.Now().UnixNano())\n\tctx2, cancel2 := context.WithCancel(ctx)\n\tnode := &DataNode{\n\t\tctx: ctx2,\n\t\tcancel: cancel2,\n\t\tRole: typeutil.DataNodeRole,\n\n\t\trootCoord: nil,\n\t\tdataCoord: nil,\n\t\tfactory: factory,\n\t\tsegmentCache: newCache(),\n\t\tcompactionExecutor: newCompactionExecutor(),\n\n\t\teventManagerMap: typeutil.NewConcurrentMap[string, *channelEventManager](),\n\t\tflowgraphManager: newFlowgraphManager(),\n\t\tclearSignal: make(chan string, 100),\n\n\t\treportImportRetryTimes: 10,\n\t}\n\tnode.UpdateStateCode(commonpb.StateCode_Abnormal)\n\treturn node\n}", "func (gen *DataGen) Ptr() unsafe.Pointer {\n\treturn unsafe.Pointer(gen)\n}", "func NewPageData(tokens oauth2.Tokens, session sessions.Session) *PageData {\n\tpd := &PageData{}\n\n\tpd.User = CurrentUser(tokens)\n\n\tpd.GravatarImage = fmt.Sprintf(\n\t\t\"https://secure.gravatar.com/avatar/%x?s=50&d=https%%3A%%2F%%2Fwww.synkee.com%%2Fapp%%2Fstatic%%2Fdist%%2Fimg%%2Fuser.png\",\n\t\tmd5.Sum([]byte(pd.User.Email)))\n\n\tpd.AppUrl = config.AppUrl\n\tpd.Errors = &binding.Errors{}\n\n\tpd.SuccessFlash = session.Flashes(\"success\")\n\tpd.ErrorFlash = session.Flashes(\"error\")\n\n\tpd.Config = config\n\n\tpd.Settings = &Setting{}\n\tdb.Where(&Setting{UserID: int(pd.User.ID)}).First(pd.Settings)\n\n\t// log.Printf(\"[NewPageData] settings: %s\", pd.Settings)\n\n\treturn pd\n}", "func NewFHIPEFromParams(params *FHIPEParams) *FHIPE {\n\treturn &FHIPE{\n\t\tParams: params,\n\t}\n}", "func NewProvider(conf *pvtdatastorage.PrivateDataConfig, ledgerconfig *ledger.Config) (xstorageapi.PrivateDataProvider, error) {\n\tif config.GetPrivateDataStoreDBType() == config.CouchDBType {\n\t\tlogger.Info(\"Using CouchDB private data storage provider\")\n\n\t\treturn xpvtdatastorage.NewProvider(conf, ledgerconfig)\n\t}\n\n\tlogger.Info(\"Using default private data storage provider\")\n\n\treturn pvtdatastorage.NewProvider(conf)\n}", "func NewProcessUserdata(service *userdataprocess.Service) *ProcessUserdata {\n\treturn &ProcessUserdata{\n\t\tService: service,\n\t}\n}", "func New() *Data {\n\treturn &Data{Values: make(map[Key][]byte)}\n}", "func NewPharse(pharse string) (*Pharse, error) {\n\tvar p Pharse\n\tp.Pharse = pharse\n\tp.Translations = make(map[string]Translate, 0)\n\n\tsum, err := sha1sum(pharse)\n\tp.Sum = sum\n\n\treturn &p, err\n}", "func NewPiPanelGTK() *pipanel.Frontend {\n\treturn &pipanel.Frontend{\n\t\tAlerter: gtkttsalerter.New(),\n\t\tAudioPlayer: beeper.New(),\n\t\tDisplayManager: pitouch.New(),\n\t\tPowerManager: systemdpwr.New(),\n\t}\n}", "func NewDataHandler() *DataHandler {\n\th := &DataHandler{DataHandler: http.NewDataHandler()}\n\th.DataHandler.CabService = &h.CabService\n\treturn h\n}", "func NewFHIPE(l int, boundX, boundY *big.Int) (*FHIPE, error) {\n\tboundXY := new(big.Int).Mul(boundX, boundY)\n\tprod := new(big.Int).Mul(big.NewInt(int64(2*l)), boundXY)\n\tif prod.Cmp(bn256.Order) > 0 {\n\t\treturn nil, fmt.Errorf(\"2 * l * boundX * boundY should be smaller than group order\")\n\t}\n\n\treturn &FHIPE{\n\t\tParams: &FHIPEParams{\n\t\t\tL: l,\n\t\t\tBoundX: boundX,\n\t\t\tBoundY: boundY}}, nil\n}", "func NewSharedDataService() *Service {\n\tsmartcontractService, err := factory.GetSmartContractService(tee.ImplementPlatform)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn &Service{smartcontractService}\n}", "func NewDatapointRepo(database *db.Datastore) *PostgresDatapointRepo {\n\treturn &PostgresDatapointRepo{\n\t\tdatabase,\n\t}\n}", "func NewLanguageData() *LanguageData {\n\tdata := make(map[string]*LanguageItem)\n\n\treturn &LanguageData{\n\t\tlanguages: data,\n\t\tsum: 0,\n\t}\n}", "func NewProvider(conf *pvtdatastorage.PrivateDataConfig, ledgerconfig *ledger.Config) (*PvtDataProvider, error) {\n\t// create couchdb pvt date store provider\n\tstorageProvider, err := cdbpvtdatastore.NewProvider(conf, ledgerconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// create cache pvt date store provider\n\tcacheProvider := cachedpvtdatastore.NewProvider()\n\n\tp := PvtDataProvider{\n\t\tstorageProvider: storageProvider,\n\t\tcacheProvider: cacheProvider,\n\t}\n\treturn &p, nil\n}", "func New(size int) Perceptron {\n\tsize++\n\tp := make(Perceptron, size)\n\tp.init()\n\treturn p\n}", "func NewPluginState() *lua.LState {\n\tstate := lua.NewState()\n\tPreloadAll(state)\n\treturn state\n}", "func CreateFromData(spawnID int32, life nx.Life) Data {\n\treturn Data{id: life.ID,\n\t\tspawnID: spawnID,\n\t\tpos: pos.New(life.X, life.Y, life.Foothold),\n\t\tfaceLeft: life.FaceLeft,\n\t\trx0: life.Rx0,\n\t\trx1: life.Rx1}\n}", "func (pb *PhilosopherBase) RightPhilosopher() Philosopher {\n\tindex := (pb.ID + 1) % NPhils\n\treturn Philosophers[index]\n}", "func newParametizer(z []byte) *parametizer {\n\tp := parametizerPool.Get().(*parametizer)\n\tp.z = z\n\n\treturn p\n}", "func NewFileData(filename string) (*FileData, error) {\n\tnewData, err := importFile(filename)\n\treturn &newData, err\n}", "func NewProtoHandler(\n\tusernamePasswordHandler *UsernamePasswordProtoHandler,\n\ttokenHandler *TokenProtoHandler,\n) *ProtoHandler {\n\treturn &ProtoHandler{\n\t\tUsernamePasswordHandler: usernamePasswordHandler,\n\t\tTokenHandler: tokenHandler,\n\t}\n}", "func (pow *ProofOfWork) CreateData(nonce int) []byte {\n\tnonceBytes, err := util.NumToBytes(int64(nonce))\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tdifficultyBytes, err := util.NumToBytes(Difficulty)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\ttimestampBytes, err := util.NumToBytes(pow.Block.Timestamp.Unix())\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tdata := bytes.Join(\n\t\t[][]byte{\n\t\t\tpow.Block.PrevHash,\n\t\t\tpow.Block.Data,\n\t\t\tnonceBytes,\n\t\t\tdifficultyBytes,\n\t\t\ttimestampBytes,\n\t\t},\n\t\t[]byte{},\n\t)\n\treturn data\n}", "func NewDB(\n\tregionName string,\n\tsnapshotter *snap.Snapshotter,\n\tproposeC chan []byte,\n\tcommitC chan []byte,\n\terrorC chan error,\n\tstableStore StableStore,\n\tcommandHander CommandHandler,\n) DB {\n\tdb := &phananxDB{\n\t\tregionName: regionName,\n\t\tproposeC: proposeC,\n\t\tstableStore: stableStore,\n\t\tcommandHander: commandHander,\n\t\tsnapshotter: snapshotter,\n\t}\n\t// replay log into key-value map\n\tdb.readCommits(commitC, errorC)\n\t// read commits from raft into kvStore map until error\n\tgo db.readCommits(commitC, errorC)\n\n\treturn db\n}", "func NewPopulatedProtoPeerID(_ randyNet) *ProtoPeerID {\n\tid, _ := pt.RandPeerID()\n\treturn &ProtoPeerID{ID: id}\n}", "func newDataset(epoch uint64) interface{} {\n\tds := &dataset{\n\t\tepoch: epoch,\n\t\tdateInit: 0,\n\t\tdataset: make([]uint64, TBLSIZE*DATALENGTH*PMTSIZE*32),\n\t}\n\t//truehashTableInit(ds.evenDataset)\n\n\treturn ds\n}", "func New(data arrow.ArrayData, shape, strides []int64, names []string) Interface {\n\tdt := data.DataType()\n\tswitch dt.ID() {\n\tcase arrow.INT8:\n\t\treturn NewInt8(data, shape, strides, names)\n\tcase arrow.INT16:\n\t\treturn NewInt16(data, shape, strides, names)\n\tcase arrow.INT32:\n\t\treturn NewInt32(data, shape, strides, names)\n\tcase arrow.INT64:\n\t\treturn NewInt64(data, shape, strides, names)\n\tcase arrow.UINT8:\n\t\treturn NewUint8(data, shape, strides, names)\n\tcase arrow.UINT16:\n\t\treturn NewUint16(data, shape, strides, names)\n\tcase arrow.UINT32:\n\t\treturn NewUint32(data, shape, strides, names)\n\tcase arrow.UINT64:\n\t\treturn NewUint64(data, shape, strides, names)\n\tcase arrow.FLOAT32:\n\t\treturn NewFloat32(data, shape, strides, names)\n\tcase arrow.FLOAT64:\n\t\treturn NewFloat64(data, shape, strides, names)\n\tcase arrow.DATE32:\n\t\treturn NewDate32(data, shape, strides, names)\n\tcase arrow.DATE64:\n\t\treturn NewDate64(data, shape, strides, names)\n\tdefault:\n\t\tpanic(fmt.Errorf(\"arrow/tensor: invalid data type %s\", dt.Name()))\n\t}\n}", "func newPtrFromSlice(basics interface{}) reflect.Value {\n\tany := reflect.ValueOf(basics)\n\treturn reflect.New(any.Type().Elem())\n}", "func NewValueFromPtr(val unsafe.Pointer) (*Value, error) {\n\tif val == nil {\n\t\treturn nil, fmt.Errorf(\"Cannot create value from 'nil' pointer\")\n\t}\n\n\tv, err := C.value_new((*C.zval)(val))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to create PHP value from pointer\")\n\t}\n\n\treturn &Value{value: v}, nil\n}", "func newPerson(name string) *person {\n p := person{name: name}\n p.age = 42\n\n // you can safely return a pointer to local variable as a local\n // variable will survive the scope of the function\n return &p\n}", "func NewDataWare() Dataware {\n\tconf := config.MyConfig()\n\tif conf.Develop.DatawareFake {\n\t\tlogrus.Info(\"in dataware fake mode so use faked dataware\")\n\t\treturn newDwFake()\n\t}\n\n\tinitGorm()\n\tdialect, dsn := conf.Database.Dsn()\n\tdb, err := gorm.Open(dialect, dsn)\n\tif err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n\tinitDB(db)\n\tlogrus.Infof(\"connect database(%s) by dsn: %s\", dialect, dsn)\n\n\treturn newDwGorm(db)\n}", "func newPerson(name string) *person {\n\tp := person{name: name}\n\tp.age = 42\n\t// you may safely return a pointer to a local variable as local variable will survive\n\t// the scope of the function\n\treturn &p\n}", "func newPlayer(seat int, shoe *Shoe, cfg *Config, strategy Strategy, betAmount int) *Player {\n\tvar p Player\n\t// fmt.Println(\"in newPlayer\")\n\tp.seat = seat\n\tp.shoe = shoe\n\tp.cfg = cfg\n\tp.strategy = strategy\n\tp.betAmount = betAmount\n\treturn &p\n}", "func NewUsersData(address common.Address, backend bind.ContractBackend) (*UsersData, error) {\n\tcontract, err := bindUsersData(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &UsersData{UsersDataCaller: UsersDataCaller{contract: contract}, UsersDataTransactor: UsersDataTransactor{contract: contract}, UsersDataFilterer: UsersDataFilterer{contract: contract}}, nil\n}", "func newPprofHandler(svr *server.Server, rd *render.Render) *pprofHandler {\n\treturn &pprofHandler{\n\t\tsvr: svr,\n\t\trd: rd,\n\t}\n}", "func newPeer(server *server, name string, connectionString string, heartbeatInterval time.Duration) *Peer {\n\treturn &Peer{\n\t\tserver: server,\n\t\tName: name,\n\t\tConnectionString: connectionString,\n\t\theartbeatInterval: heartbeatInterval,\n\t}\n}", "func NewPlugin(proto, path string, params ...string) *Plugin {\n\tif proto != \"unix\" && proto != \"tcp\" {\n\t\tpanic(\"Invalid protocol. Specify 'unix' or 'tcp'.\")\n\t}\n\tp := &Plugin{\n\t\texe: path,\n\t\tproto: proto,\n\t\tparams: params,\n\t\tinitTimeout: 2 * time.Second,\n\t\texitTimeout: 2 * time.Second,\n\t\thandler: NewDefaultErrorHandler(),\n\t\tmeta: meta(\"pingo\" + randstr(5)),\n\t\tobjsCh: make(chan *objects),\n\t\tconnCh: make(chan *conn),\n\t\tkillCh: make(chan *waiter),\n\t\texitCh: make(chan struct{}),\n\t}\n\treturn p\n}", "func NewInjector(values ...interface{}) *Injector {\n\tinj := &Injector{\n\t\tdata: make(map[string]reflect.Value),\n\t}\n\tinj.Set(values...)\n\treturn inj\n}", "func NewPopTable(h SQLHandle) *PopTable {\n\treturn &PopTable{h}\n}" ]
[ "0.6925413", "0.54921985", "0.5336811", "0.5186926", "0.5178499", "0.5169362", "0.5147895", "0.49286178", "0.48740306", "0.48372763", "0.48115495", "0.48056304", "0.47917417", "0.4747126", "0.47438258", "0.47403672", "0.47364557", "0.47297642", "0.46949512", "0.46925366", "0.46603557", "0.4613781", "0.4594363", "0.45864213", "0.45583993", "0.45367202", "0.45032412", "0.44881278", "0.44830894", "0.44616675", "0.44584098", "0.44319895", "0.44268918", "0.44262734", "0.4412245", "0.44068116", "0.44017094", "0.44009322", "0.43905443", "0.43901053", "0.43867418", "0.43851882", "0.43727943", "0.43726644", "0.43652683", "0.43334147", "0.43293354", "0.43219292", "0.4319118", "0.43085206", "0.43078586", "0.43049043", "0.42944556", "0.42920643", "0.42831373", "0.42831373", "0.4273116", "0.42684624", "0.42552662", "0.42507908", "0.4250472", "0.42449567", "0.4241108", "0.42375538", "0.4233972", "0.42322403", "0.42278552", "0.42259866", "0.4225389", "0.42193705", "0.4215139", "0.42010063", "0.41969436", "0.41947606", "0.41900933", "0.41877967", "0.41875225", "0.41860822", "0.41859898", "0.41853076", "0.41844356", "0.4180394", "0.41783097", "0.41778758", "0.4175538", "0.41742763", "0.41714275", "0.4157875", "0.41556194", "0.41544718", "0.4143674", "0.41425234", "0.41420555", "0.41354808", "0.41325286", "0.41314235", "0.41299874", "0.41281462", "0.41264597", "0.41218528" ]
0.898251
0
Init is used to initialize the philosopherData.
func (pd *philosopherData) Init(respChannel chan string) { pd.respChannel = respChannel pd.eating = false pd.dinnersSpent = 0 pd.seat = -1 pd.leftChopstick = -1 pd.rightChopstick = -1 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (phi *Philosopher) Init(name string) {\n\tphi.name = name\n\tphi.respChannel = make(chan string)\n}", "func (host *DinnerHost) Init(tableCount, maxParallel, maxDinner int) {\n\thost.phiData = make(map[string]*philosopherData)\n\thost.requestChannel = make(chan string)\n\thost.finishChannel = make(chan string)\n\thost.maxParallel = maxParallel\n\tif host.maxParallel > tableCount {\n\t\thost.maxParallel = tableCount\n\t}\n\thost.maxDinner = maxDinner\n\thost.currentlyEating = 0\n\thost.tableCount = tableCount\n\thost.chopsticksFree = make([]bool, 5)\n\tfor i := range host.chopsticksFree {\n\t\thost.chopsticksFree[i] = true\n\t}\n\trand.Seed(time.Now().Unix())\n\thost.freeSeats = rand.Perm(tableCount)\n}", "func newPhilosopherDataPtr(respChannel chan string) *philosopherData {\n\tpd := new(philosopherData)\n\tpd.Init(respChannel)\n\treturn pd\n}", "func (m *Main) Init() error {\n\n\tlog.Printf(\"Loading GeoCode data ...\")\n\t//u.LoadGeoCodes()\n\n\tvar err error\n\tm.indexer, err = pdk.SetupPilosa(m.Hosts, m.IndexName, u.Frames, m.BufferSize)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error setting up Pilosa '%v'\", err)\n\t}\n\t//m.client = m.indexer.Client()\n\n\t// Initialize S3 client\n\tsess, err2 := session.NewSession(&aws.Config{\n\t\tRegion: aws.String(m.AWSRegion)},\n\t)\n\n\tif err2 != nil {\n\t\treturn fmt.Errorf(\"Creating S3 session: %v\", err2)\n\t}\n\n\t// Create S3 service client\n\tm.S3svc = s3.New(sess)\n\n\treturn nil\n}", "func (h *facts) Init(output chan<- *plugin.SlackResponse, bot *plugin.Bot) {\n\th.sink = output\n\th.bot = bot\n\th.configuration = viper.New()\n\th.configuration.AddConfigPath(\"/etc/slackhal/\")\n\th.configuration.AddConfigPath(\"$HOME/.slackhal\")\n\th.configuration.AddConfigPath(\".\")\n\th.configuration.SetConfigName(\"plugin-facts\")\n\th.configuration.SetConfigType(\"yaml\")\n\terr := h.configuration.ReadInConfig()\n\tif err != nil {\n\t\tzap.L().Error(\"Not able to read configuration for facts plugin.\", zap.Error(err))\n\t\th.Disabled = true\n\t\treturn\n\t}\n\tdbPath := h.configuration.GetString(\"database.path\")\n\th.factDB = new(stormDB)\n\terr = h.factDB.Connect(dbPath)\n\tif err != nil {\n\t\tzap.L().Error(\"Error while opening the facts database!\", zap.Error(err))\n\t\th.Disabled = true\n\t\treturn\n\t}\n}", "func (s *Speaker) Init() error { return nil }", "func (c *pvtDataStore) Init(btlPolicy pvtdatapolicy.BTLPolicy) {\n\tc.cachePvtDataStore.Init(btlPolicy)\n\tc.pvtDataDBStore.Init(btlPolicy)\n}", "func (s *Hipchat) Init(c *config.Config) error {\n\turl := c.Handler.Hipchat.Url\n\troom := c.Handler.Hipchat.Room\n\ttoken := c.Handler.Hipchat.Token\n\n\tif token == \"\" {\n\t\ttoken = os.Getenv(\"KW_HIPCHAT_TOKEN\")\n\t}\n\n\tif room == \"\" {\n\t\troom = os.Getenv(\"KW_HIPCHAT_ROOM\")\n\t}\n\n\tif url == \"\" {\n\t\turl = os.Getenv(\"KW_HIPCHAT_URL\")\n\t}\n\n\ts.Token = token\n\ts.Room = room\n\ts.Url = url\n\n\treturn checkMissingHipchatVars(s)\n}", "func (hem *GW) Init(rootURL string, username string, password string) {\n\them.rootURL = rootURL\n\them.username = username\n\them.password = password\n\them.loadSmartMeterAttribute()\n}", "func (a *amqpPubSub) Init(ctx context.Context, metadata pubsub.Metadata) error {\n\tamqpMeta, err := parseAMQPMetaData(metadata, a.logger)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ta.metadata = amqpMeta\n\n\ts, err := a.connect(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ta.session = s\n\n\treturn err\n}", "func (h *Handler) Init(dbManager database.Manager, cacheManager cache.Manager, mqManager messagingqueue.Manager) {\n\th.dbManager = dbManager\n\th.cacheManager = cacheManager\n\th.mqManager = mqManager\n}", "func (s *Session) Init() {\n\ts.setEthereumRPCPath()\n\ts.setPayloadRPCPath()\n}", "func init(){\n\n\tcustomers = loadAllCustomers()\n\tBuildRank()\n\tBuildTable()\n\n}", "func (plugin *ExamplePlugin) Init() error {\n\t// Read public key\n\tpublicKey, err := readPublicKey(\"../cryptodata-lib/key-pub.pem\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Create ETCD connection\n\tplugin.db, err = plugin.newEtcdConnection(\"etcd.conf\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Prepare data\n\tdata, err := plugin.encryptData(\"hello-world\", publicKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\tencryptedJSON := fmt.Sprintf(JSONData, data)\n\tplugin.Log.Infof(\"Putting value %v\", encryptedJSON)\n\n\t// Prepare path for storing the data\n\tkey := plugin.etcdKey(\"value\")\n\n\t// Put JSON data to ETCD\n\terr = plugin.db.Put(key, []byte(encryptedJSON))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// WrapBytes ETCD connection with crypto layer\n\tdbWrapped := plugin.CryptoData.WrapBytes(plugin.db, cryptodata.NewDecrypterJSON())\n\tbroker := dbWrapped.NewBroker(keyval.Root)\n\n\t// Get JSON data from ETCD and decrypt them with crypto layer\n\tdecryptedJSON, _, _, err := broker.GetValue(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tplugin.Log.Infof(\"Got value %v\", string(decryptedJSON))\n\n\t// Close agent and example\n\tclose(plugin.exampleFinished)\n\n\treturn nil\n}", "func (p *Noise) Init() error {\n\tfieldFilter, err := filter.NewIncludeExcludeFilter(p.IncludeFields, p.ExcludeFields)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating fieldFilter failed: %w\", err)\n\t}\n\tp.fieldFilter = fieldFilter\n\n\tswitch p.NoiseType {\n\tcase \"\", \"laplacian\":\n\t\tp.generator = &distuv.Laplace{Mu: p.Mu, Scale: p.Scale}\n\tcase \"uniform\":\n\t\tp.generator = &distuv.Uniform{Min: p.Min, Max: p.Max}\n\tcase \"gaussian\":\n\t\tp.generator = &distuv.Normal{Mu: p.Mu, Sigma: p.Scale}\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown distribution type %q\", p.NoiseType)\n\t}\n\treturn nil\n}", "func (p *AbstractProvider) Init() error {\n\treturn nil\n}", "func (s *Solo) Init(state *state.State, service *service.Service) error {\n\n\ts.logger.Debug(\"INIT\")\n\n\ts.state = state\n\ts.service = service\n\n\treturn nil\n}", "func (pd *pymtData) Init(p payment.PymtUpsert) {\n\tpd.Type = p.Type\n\tpd.Attrs = p.Attributes\n}", "func (p *provider) Init(ctx servicehub.Context) error {\n\tp.cache = make(map[uint64]aggregate)\n\tp.rulers = make([]*ruler, len(p.Cfg.Rules))\n\tfor idx, r := range p.Cfg.Rules {\n\t\trr, err := newRuler(r)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"newRuler err: %w\", err)\n\t\t}\n\t\tp.rulers[idx] = rr\n\t}\n\treturn nil\n}", "func (c *ClusterManager) Init(zl instances.ZoneLister, pp backends.ProbeProvider) {\n\tc.instancePool.Init(zl)\n\tc.backendPool.Init(pp)\n\t// TODO: Initialize other members as needed.\n}", "func (Operator *Operators) Init(stub shim.ChaincodeStubInterface) peer.Response {\n\t// Simply print a message\n\tfmt.Println(\"Initialize voting contract\")\n\n\t// Init lists\n\tvoter_list, _ := json.Marshal([]Operators{})\n\tvotes, _ := json.Marshal([]Votes{})\n\tclosedVotes, _ := json.Marshal([]Votes{})\n\n\t// Put states to level DB\n\tstub.PutState(\"Operators\", voter_list)\n\tstub.PutState(\"Votes\", votes)\n\tstub.PutState(\"closedVotes\", closedVotes)\n\n\t// Return success\n\treturn shim.Success([]byte(\"true\"))\n}", "func Init() {\n\t// default :\n\t// micro health go.micro.api.gin call this function.\n\tModules.Router.POST(\"/\", NoModules)\n\tModules.Router.GET(\"/\", NoModules)\n\n\t// Examples Begin:micro api --handler=http as proxy, default is rpc .\n\t// Base module router for rest full, Preferences is name of table or tables while Module equals database.\n\t// Call url:curl \"http://localhost:8004/Preferences/GetPreference?user=1\"\n\te := new( examples )\n\tclient.DefaultClient = client.NewClient( client.Registry(etcdv3.DefaultEtcdRegistry) )\n\te.cl = example.NewPreferencesService(conf.ApiConf.SrvName, client.DefaultClient)\n\tModules.Router.GET(\"/Preferences/*action\", e.Preferences)\n\t// Examples End\n\n\t// register other handlers here, each request run in goroutine.\n\t// To register others...\n\n\tlog.Info(\"Modules init finished.\")\n}", "func (s *Flattener) Init(conf map[string]string) error {\n\treturn nil\n}", "func (s *Store) Init(sessionID []byte, defaultExpiration time.Duration) {\n\ts.sessionID = sessionID\n\ts.defaultExpiration = defaultExpiration\n\n\tif s.data == nil { // Ensure the store always has a valid pointer of Dict\n\t\ts.data = new(Dict)\n\t}\n}", "func (d *SQLike) Init(tk *destination.Toolkit) error {\n\twh, err := d.AsWarehouse()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.wh = wh\n\treturn nil\n}", "func (s *Store) Init(ctx context.Context, metadataRaw secretstores.Metadata) error {\n\tmetadata, err := s.parseSecretManagerMetadata(metadataRaw)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient, err := s.getClient(ctx, metadata)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to setup secretmanager client: %s\", err)\n\t}\n\n\ts.client = client\n\ts.ProjectID = metadata.ProjectID\n\n\treturn nil\n}", "func (sys *BucketMetadataSys) Init(ctx context.Context, buckets []BucketInfo, objAPI ObjectLayer) error {\n\tif objAPI == nil {\n\t\treturn errServerNotInitialized\n\t}\n\n\t// In gateway mode, we don't need to load the policies\n\t// from the backend.\n\tif globalIsGateway {\n\t\treturn nil\n\t}\n\n\t// Load PolicySys once during boot.\n\treturn sys.load(ctx, buckets, objAPI)\n}", "func (o *CloudTidesAPI) Init() {\n\tif len(o.handlers) == 0 {\n\t\to.initHandlerCache()\n\t}\n}", "func (c *Collector) Init() error { return nil }", "func Init(c common.AresServerConfig, l common.Logger, ql common.Logger, s tally.Scope) {\n\tconfig = c\n\tlogger = l\n\tqueryLogger = ql\n\treporterFactory = NewReporterFactory(s)\n}", "func (impl *Impl) Init(conf core.ImplConf, space core.Space) (core.Clust, error) {\n\tvar mcmcConf = conf.(Conf)\n\t_ = impl.buffer.Apply()\n\timpl.iter = 0\n\treturn impl.initializer(mcmcConf.InitK, impl.buffer.Data(), space, mcmcConf.RGen)\n}", "func (sys *BucketMetadataSys) Init(ctx context.Context, buckets []BucketInfo, objAPI ObjectLayer) error {\n\tif objAPI == nil {\n\t\treturn errServerNotInitialized\n\t}\n\n\t// In gateway mode, we don't need to load the policies\n\t// from the backend.\n\tif globalIsGateway {\n\t\treturn nil\n\t}\n\n\t// Load bucket metadata sys in background\n\tgo sys.load(ctx, buckets, objAPI)\n\treturn nil\n}", "func (r *Ricochet) Init() {\n\tr.newconns = make(chan *OpenConnection)\n\tr.networkResolver = utils.NetworkResolver{}\n\tr.rni = new(utils.RicochetNetwork)\n}", "func (g *grpc) Init(gen *generator.Generator) {\n\tg.gen = gen\n}", "func (src *DataSrc) Init(conf *viper.Viper) error {\n\t//initial DataSrc.DB from the confing passed to it\n\terrDB := src.InitDB(conf)\n\tif errDB != nil {\n\t\treturn errDB\n\t}\n\t//initial DataSrc.Cache from the confing passed to it\n\n\terrCache := src.InitCache(conf)\n\tif errCache != nil {\n\t\treturn errCache\n\t}\n\t//initial DataSrc.Search from the confing passed to it\n\terrSearch := src.InitSearch(conf)\n\tif errSearch != nil {\n\t\treturn errSearch\n\t}\n\treturn nil\n}", "func (d *Data) Init() {\n\t// (X) d = NewData()\n\t// This only updates its pointer\n\t// , not the Data itself\n\t//\n\t*d = *NewData()\n}", "func (h *Handler) Init(c *config.Config) {\n\th.gatewayAddr = c.GatewaySvc\n\th.allowedLanguages = c.AllowedLanguages\n\tif len(h.allowedLanguages) == 0 {\n\t\th.allowedLanguages = []string{\"cs\", \"de\", \"en\", \"es\", \"fr\", \"it\", \"gl\"}\n\t}\n}", "func (gosh *Goshell) Init(ctx context.Context) error {\n\tgosh.ctx = ctx\n\treturn gosh.loadCommands()\n}", "func (s *InMemoryHandler) Init() error {\n\ts.logger = log.WithFields(log.Fields{\"app\": \"inmemory-db\"})\n\ts.functions = make(map[string]model.FunctionConfig)\n\treturn nil\n}", "func Init(r *Rope) {\n\tr.Head = knot{\n\t\theight: 1,\n\t\tnexts: make([]skipknot, MaxHeight),\n\t}\n}", "func (eng *Engine) Init(cfg string) error {\n\treturn nil\n}", "func (g *Glutton) Init() (err error) {\n\n\tctx := context.Background()\n\tg.ctx, g.cancel = context.WithCancel(ctx)\n\n\tgluttonServerPort := uint(g.conf.GetInt(\"glutton_server\"))\n\n\t// Initiate the freki processor\n\tg.processor, err = freki.New(viper.GetString(\"interface\"), g.rules, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Initiating glutton server\n\tg.processor.AddServer(freki.NewUserConnServer(gluttonServerPort))\n\t// Initiating log producer\n\tif g.conf.GetBool(\"enableGollum\") {\n\t\tg.producer = producer.Init(g.id.String(), g.conf.GetString(\"gollumAddress\"))\n\t}\n\t// Initiating protocol handlers\n\tg.mapProtocolHandlers()\n\tg.registerHandlers()\n\n\terr = g.processor.Init()\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn nil\n}", "func (gcm *GClientManager) Init() {\n\tgcm.smp = make(map[int32]int32, 128)\n\tgcm.HashTable.Init()\n}", "func (s *Service) Init() {\n\ts.Comments = make([]string, 0)\n\ts.Attributes = make([]*Attribute, 0)\n\ts.Methods = make([]*Method, 0)\n}", "func (s *GCPCKMSSeal) Init(_ context.Context) error {\n\treturn nil\n}", "func (tp *SystemTaskParams) Init(response *models.BaseResponse, db *system.DB) {\n\ttp.response = response\n\ttp.db = db\n\n}", "func (o *DataPlaneAPI) Init() {\n\tif len(o.handlers) == 0 {\n\t\to.initHandlerCache()\n\t}\n}", "func (pb *PhilosopherBase) Start() {\n\tpb.State = philstate.Thinking\n\tpb.StartThinking()\n}", "func (sdb *SolarDb) Init() error {\n\tlogger.Infof(\"Open db connection (db: %q)\", sdb.dbConfig.Name)\n\tdb, err := sql.Open(\"mysql\", fmt.Sprintf(\"%s:%s@tcp(127.0.0.1:3306)/%s\", sdb.dbConfig.User, sdb.dbConfig.Password, sdb.dbConfig.Name))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// construct a gorp DbMap\n\tsdb.dbMap = &gorp.DbMap{Db: db, Dialect: gorp.MySQLDialect{Engine: \"InnoDB\", Encoding: \"UTF8\"}}\n\n\tsdb.dbMap.AddTableWithName(models.ChargeControllerMeasurement{}, config.ChargeControllerMeasurementsTable).SetKeys(false, \"Id\")\n\tsdb.dbMap.AddTableWithName(models.ShuntMeasurement{}, config.ShuntMeasurementsTable).SetKeys(false, \"Id\")\n\tsdb.dbMap.AddTableWithName(models.TemperatureMeasurement{}, config.TemperatureMeasurementsTable).SetKeys(false, \"Id\")\n\tsdb.dbMap.AddTableWithName(models.HumidityMeasurement{}, config.HumidityMeasurementsTable).SetKeys(false, \"Id\")\n\n\treturn nil\n}", "func Init(c *conf.Config, s *service.Service) {\n\trelationSvc = s\n\tverify = v.New(c.Verify)\n\tanti = antispam.New(c.Antispam)\n\taddFollowingRate = rate.New(c.AddFollowingRate)\n\t// init inner router\n\tengine := bm.DefaultServer(c.BM)\n\tsetupInnerEngine(engine)\n\tif err := engine.Start(); err != nil {\n\t\tlog.Error(\"engine.Start() error(%v)\", err)\n\t\tpanic(err)\n\t}\n}", "func (p *HelloWorld) Init(reg *types.Register, pm types.ProcessManager, cn types.Provider) error {\n\tp.pm = pm\n\tp.cn = cn\n\tif vp, err := pm.ProcessByName(\"fleta.vault\"); err != nil {\n\t\treturn err\n\t} else if v, is := vp.(*vault.Vault); !is {\n\t\treturn types.ErrInvalidProcess\n\t} else {\n\t\tp.vault = v\n\t}\n\n\treg.RegisterTransaction(1, &Hello{})\n\n\treturn nil\n}", "func Init() {\n\t// default ..\n\t// micro health go.micro.api.gin call this function..\n\tModules.Router.POST(\"/\", NoModules)\n\tModules.Router.GET(\"/gin\", NoModules)\n\t// Modules.Router.GET(\"/gin\", NoModules)\n\t// Modules.Router.GET(\"/dbservice\", NoModules)\n\n\t// Examples Begin:micro api --handler=http as proxy, default is rpc .\n\t// Base module router for rest full, Preferences is name of table or tables while Module equals database.\n\t// Call url:curl \"http://localhost:8004/Preferences/GetPreference?user=1\"\n\te := new(examples)\n\t// Init Preferences Server Client\n\te.cl = go_micro_srv_dbservice.NewPreferencesService(conf2.AppConf.SrvName, client.DefaultClient)\n\tModules.Router.GET(\"/Preferences/*action\", e.Preferences)\n\t// Examples End\n\n\t// register other handlers here, each request run in goroutine.\n\n\t// To register others...\n\n\tfmt.Println(\"Modules init finished.\")\n}", "func Init() {\n\tbarray := []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F}\n\tFChainID = new(common.Hash)\n\tFChainID.SetBytes(barray)\n\n\tCreditsPerChain = 10 // Entry Credits to create a chain\n\n\t// Shouldn't set this, but we are for now.\n\tFactoshisPerCredit = 666667 // .001 / .15 * 100000000 (assuming a Factoid is .15 cents, entry credit = .1 cents\n\n}", "func (P *Parser) Init(g Grammar) {\n\tP.p = g.compile()\n}", "func (c *HelloWorld) Init(ctx contract.Context, req *types.HelloRequest) error {\n\treturn nil\n}", "func init() {\n\t// TODO: set logger\n\t// TODO: register storage plugin to plugin manager\n}", "func (d *Database) Init() {\n\t//initialize Directory\n\td.Directory.Param = d.Param\n\td.Directory.Init()\n}", "func (p *ExamplePlugin) Init() error {\n\treturn nil\n}", "func (p *ExamplePlugin) Init() error {\n\treturn nil\n}", "func init() {\n\t// Compila i templates e li inserisce nella mappa templates.\n\tgo istantiateInternalTemplates()\n\t// key must be 16, 24 or 32 bytes long (AES-128, AES-192 or AES-256)\n\ttoken := make([]byte, 32)\n\tkey := []byte(fmt.Sprint(rand.Read(token)))\n\tstore = sessions.NewCookieStore(key)\n\tfooterData.Anno = Anno\n\tfooterData.Versione = Version\n\tfooterData.Autore = Autore\n}", "func (pgs *PGStorage) Init() error {\n\tdb, err := sqlx.Open(\"pgx\", pgs.URI)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpgs.DB = db\n\treturn nil\n}", "func Init() http.HandlerFunc {\n\trootQuery := graphql.NewObject(graphql.ObjectConfig{\n\t\tName: \"Query\",\n\t\tFields: fields.HandleQuery(),\n\t})\n\n\trootMutation := graphql.NewObject(graphql.ObjectConfig{\n\t\tName: \"Mutation\",\n\t\tFields: fields.HandleMutation(),\n\t})\n\n\tschema, _ := graphql.NewSchema(graphql.SchemaConfig{\n\t\tQuery: rootQuery,\n\t\tMutation: rootMutation,\n\t})\n\n\th := handler.New(&handler.Config{\n\t\tSchema: &schema,\n\t\tPretty: true,\n\t})\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\th.ContextHandler(r.Context(), w, r)\n\t}\n}", "func (s *Sim) Init() {\n\ts.System = make([]*poly.Chain,0)\n\ts.solver = new(solver.RK4)\n\ts.solver.Mods = make([]solver.Modifier,0)\n\ts.solverInit = false\n}", "func (g *Guessit) Init(p []byte) error {\n\tif g.configured {\n\t\treturn nil\n\t}\n\n\tparams := &Params{}\n\tif err := yaml.Unmarshal(p, params); err != nil {\n\t\treturn err\n\t}\n\n\treturn g.InitWithParams(params)\n}", "func (l *LightningLoader) Init(ctx context.Context) (err error) {\n\ttctx := tcontext.NewContext(ctx, l.logger)\n\tcheckpoint, err := newRemoteCheckPoint(tctx, l.cfg, l.checkpointID())\n\tfailpoint.Inject(\"ignoreLoadCheckpointErr\", func(_ failpoint.Value) {\n\t\tl.logger.Info(\"\", zap.String(\"failpoint\", \"ignoreLoadCheckpointErr\"))\n\t\terr = nil\n\t})\n\tl.checkPoint = checkpoint\n\tl.toDB, l.toDBConns, err = createConns(tctx, l.cfg, 1)\n\treturn err\n}", "func Init() {\n\tEngine = gin.Default()\n}", "func (o *ParamsReg) Init(nFeatures int) {\n\to.theta = la.NewVector(nFeatures)\n\to.bkpTheta = la.NewVector(nFeatures)\n}", "func (d *Database) Init() error {\n\tif _, err := d.db.Exec(\"CREATE TABLE IF NOT EXISTS leaves (id INTEGER PRIMARY KEY, data BLOB)\"); err != nil {\n\t\treturn err\n\t}\n\tif _, err := d.db.Exec(\"CREATE TABLE IF NOT EXISTS tiles (height INTEGER, level INTEGER, offset INTEGER, hashes BLOB, PRIMARY KEY (height, level, offset))\"); err != nil {\n\t\treturn err\n\t}\n\t_, err := d.db.Exec(\"CREATE TABLE IF NOT EXISTS leafMetadata (id INTEGER PRIMARY KEY, module TEXT, version TEXT, fileshash TEXT, modhash TEXT)\")\n\treturn err\n}", "func Init() {\n\tonce.Do(initialize)\n}", "func (m *Mixtape) init() {\n\tm.Users = []User{}\n\tm.Playlists = []Playlist{}\n\tm.Songs = []Song{}\n}", "func (s *Layer) Init() {\n\ts.Delete()\n\n\ts.entities = []IEntity{}\n}", "func (c *Context) Init() {\n\tc.Logger = zerolog.New(zerolog.ConsoleWriter{Out: os.Stdout}).With().Timestamp().Logger()\n\tc.Logger = c.Logger.Hook(zerolog.HookFunc(c.getMemoryUsage))\n\n\tc.inShutdownMutex.Lock()\n\tc.inShutdown = false\n\tc.inShutdownMutex.Unlock()\n\n\tc.RandomSource = rand.New(rand.NewSource(time.Now().Unix()))\n\n\tc.Logger.Info().Msgf(\"LBTDS v. %s is starting...\", VERSION)\n}", "func (m *Driver) Init(metadata mq.Metadata) error {\n\tmqttMeta, err := parseMQTTMetaData(metadata)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.metadata = mqttMeta\n\tclient, err := m.connect()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm.client = client\n\treturn nil\n\n}", "func (mod *EthModule) Init() error {\n\tm := mod.eth\n\t// if didn't call NewEth\n\tif m.config == nil {\n\t\tm.config = DefaultConfig\n\t}\n\n\t//ethdoug.Adversary = mod.Config.Adversary\n\n\t// if no ethereum instance\n\tif m.ethereum == nil {\n\t\tm.ethConfig()\n\t\tm.newEthereum()\n\t}\n\n\t// public interface\n\tpipe := xeth.New(m.ethereum)\n\t// load keys from file. genesis block keys. convenient for testing\n\n\tm.pipe = pipe\n\tm.keyManager = m.ethereum.KeyManager()\n\t//m.reactor = m.ethereum.Reactor()\n\n\t// subscribe to the new block\n\tm.chans = make(map[string]chan types.Event)\n\t//m.reactchans = make(map[string]chan ethreact.Event)\n\tm.Subscribe(\"newBlock\", \"newBlock\", \"\")\n\n\tlog.Println(m.ethereum.Port)\n\n\treturn nil\n}", "func (g *gcp) Init() error {\n\treturn nil\n}", "func (h *Histogram) Init() {\n\t*h = map[rune]int{\n\t\t'A': 0,\n\t\t'C': 0,\n\t\t'T': 0,\n\t\t'G': 0,\n\t}\n}", "func Init(\n\tctx context.Context,\n\tobservationCtx *observation.Context,\n\tdb database.DB,\n\t_ codeintel.Services,\n\t_ conftypes.UnifiedWatchable,\n\tenterpriseServices *enterprise.Services,\n) error {\n\tenterpriseServices.OwnResolver = resolvers.New()\n\n\treturn nil\n}", "func (o *DynCoefs) Init(dat *inp.SolverData) {\n\n\t// hmin\n\to.hmin = dat.DtMin\n\n\t// HHT\n\to.HHT = dat.HHT\n\n\t// θ-method\n\to.θ = dat.Theta\n\tif o.θ < 1e-5 || o.θ > 1.0 {\n\t\tchk.Panic(\"θ-method requires 1e-5 <= θ <= 1.0 (θ = %v is incorrect)\", o.θ)\n\t}\n\n\t// HHT method\n\tif dat.HHT {\n\t\to.α = dat.HHTalp\n\t\tif o.α < -1.0/3.0 || o.α > 0.0 {\n\t\t\tchk.Panic(\"HHT method requires: -1/3 <= α <= 0 (α = %v is incorrect)\", o.α)\n\t\t}\n\t\to.θ1 = (1.0 - 2.0*o.α) / 2.0\n\t\to.θ2 = (1.0 - o.α) * (1.0 - o.α) / 2.0\n\n\t\t// Newmark's method\n\t} else {\n\t\to.θ1, o.θ2 = dat.Theta1, dat.Theta2\n\t\tif o.θ1 < 0.0001 || o.θ1 > 1.0 {\n\t\t\tchk.Panic(\"θ1 must be between 0.0001 and 1.0 (θ1 = %v is incorrect)\", o.θ1)\n\t\t}\n\t\tif o.θ2 < 0.0001 || o.θ2 > 1.0 {\n\t\t\tchk.Panic(\"θ2 must be between 0.0001 and 1.0 (θ2 = %v is incorrect)\", o.θ2)\n\t\t}\n\t}\n}", "func (h *Handler) Init() (err error) {\n\n\terr = h.Crypto.Init()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error during crypto init: %w\", err)\n\t}\n\n\terr = h.FileHandler.Init()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error during file handler init: %w\", err)\n\t}\n\n\terr = h.Maskinporten.Init()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error during maskinporten init: %w\", err)\n\t}\n\n\tif h.LogLevel != \"\" {\n\t\tlvl, err := logrus.ParseLevel(h.LogLevel)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to parse log level: %w\", err)\n\t\t}\n\n\t\tlog.Logger.SetLevel(lvl)\n\t}\n\n\th.Sender.Maskinporten = h.Maskinporten\n\n\treturn nil\n}", "func (self *TStatement) Init() {\r\n\tself.domain = domain.NewDomainNode()\r\n\tself.Sets = nil // 不预先创建添加GC负担\r\n\tself.IdParam = make([]interface{}, 0)\r\n\tself.Fields = make(map[string]bool) // TODO 优化\r\n\tself.NullableFields = make(map[string]bool) // TODO 优化\r\n\tself.FromClause = \"\"\r\n\tself.OrderByClause = \"\"\r\n\tself.AscFields = nil\r\n\tself.DescFields = nil\r\n\tself.LimitClause = 0\r\n\tself.OffsetClause = 0\r\n\tself.IsCount = false\r\n\tself.Params = make([]interface{}, 0)\r\n}", "func (c *Cassandra) Init(_ context.Context, metadata state.Metadata) error {\n\tmeta, err := getCassandraMetadata(metadata)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcluster, err := c.createClusterConfig(meta)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating cluster config: %w\", err)\n\t}\n\tc.cluster = cluster\n\n\tsession, err := cluster.CreateSession()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating session: %w\", err)\n\t}\n\tc.session = session\n\n\terr = c.tryCreateKeyspace(meta.Keyspace, meta.ReplicationFactor)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating keyspace %s: %w\", meta.Keyspace, err)\n\t}\n\n\terr = c.tryCreateTable(meta.Table, meta.Keyspace)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating table %s: %w\", meta.Table, err)\n\t}\n\n\tc.table = meta.Keyspace + \".\" + meta.Table\n\n\treturn nil\n}", "func (p Polynomial) Init(s []ed25519.Scalar) {\n\tcopy(p.coeffs, s)\n}", "func Init(r chi.Router) {\n\tr.Route(\"/cities\", cities.Init)\n\tr.Route(\"/temperatures\", temperatures.Init)\n\tr.Route(\"/forecasts\", forecasts.Init)\n\tr.Route(\"/webhooks\", webhooks.Init)\n}", "func (t *DiamondChaincode) Init(stub shim.ChaincodeStubInterface) peer.Response {\n\t// Get the args from the transaction proposal\n\targs := stub.GetStringArgs()\n\tif len(args) != 2 {\n\t\treturn shim.Error(\"Incorrect arguments. Expecting a key and a value\")\n\t}\n\n\t// Set up any variables or assets here by calling stub.PutState()\n\n\n\t// We store the key and the value on the ledger\n\terr := stub.PutState(args[0], []byte(args[1]))\n\tif err != nil {\n\t\treturn shim.Error(fmt.Sprintf(\"Failed to create asset: %s\", args[0]))\n\t}\n\treturn shim.Success(nil)\n}", "func (h *MessageHandler) Init(ctx context.Context) error {\n\tm := newMiddleware(h)\n\th.middleware = m\n\n\th.jetTreeUpdater = jet.NewFetcher(h.Nodes, h.JetStorage, h.Bus, h.JetCoordinator)\n\n\th.setHandlersForLight(m)\n\n\treturn nil\n}", "func Init(schemes []SchemeLoader) Loader {\n\treturn &loaderImpl{root: emptyRoot, schemes: schemes}\n}", "func (p *Postgres) Init(ctx context.Context, meta bindings.Metadata) error {\n\tif p.closed.Load() {\n\t\treturn errors.New(\"cannot initialize a previously-closed component\")\n\t}\n\n\tm := psqlMetadata{}\n\terr := m.InitWithMetadata(meta.Properties)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpoolConfig, err := m.GetPgxPoolConfig()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error opening DB connection: %w\", err)\n\t}\n\n\t// This context doesn't control the lifetime of the connection pool, and is\n\t// only scoped to postgres creating resources at init.\n\tp.db, err = pgxpool.NewWithConfig(ctx, poolConfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to connect to the DB: %w\", err)\n\t}\n\n\treturn nil\n}", "func (m *PooledWrapper) Init(context.Context, ...wrapping.Option) error {\n\treturn nil\n}", "func (p *PipelineProvisioner) Init(opts ...grpc.DialOption) error {\n\treturn nil\n}", "func (r *Egress) Init(op egress.Options) error {\n\t// the manager use dests to init, so must init after dests\n\tif err := initEgressManager(); err != nil {\n\t\treturn err\n\t}\n\treturn refresh()\n}", "func (pp *PolicyProcessor) Init() error {\n\tpp.podIPAddressMap = make(map[podmodel.ID]net.IP)\n\tpp.Cache.Watch(pp)\n\treturn nil\n}", "func (t *Handler) Init() error {\n\tlog.Info(\"Handler.Init\")\n\treturn nil\n}", "func (t *Tangle) Init(o Options) error {\n\tt.tips = make(map[hash.Hash]bool)\n\tt.store = o.Store\n\tif store.Empty(t.store) {\n\t\tgen1 := &site.Site{Content: hash.Hash{24, 67, 68, 72, 132, 181}, Nonce: 373, Type: \"genesis\"}\n\t\tgen2 := &site.Site{Content: hash.Hash{24, 67, 68, 72, 132, 182}, Nonce: 510, Type: \"genesis\"}\n\t\terr := t.store.Add(gen1)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = t.store.Add(gen2)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tt.store.SetTips(gen1.Hash(), nil)\n\t\tt.store.SetTips(gen2.Hash(), nil)\n\t}\n\tfor _, tip := range t.store.GetTips() {\n\t\tt.tips[tip] = true\n\t}\n\treturn nil\n}", "func (g *Gorc) Init() {\n\tg.Lock()\n\tg.count = 0\n\tg.waitMillis = 100 * time.Millisecond\n\tg.Unlock()\n}", "func Init() {\n\tC.yices_init()\n}", "func (fashion *FashionChaincode) Init(stub shim.ChaincodeStubInterface) peer.Response {\n\tfmt.Println(\"init executed\")\n\t//logger.Debug(\"Init executed for log\")\n\n\treturn shim.Success(nil)\n}", "func (g *generator) InitData(kt *kit.Kit) error {\n\theader := http.Header{}\n\theader.Set(constant.UserKey, constant.BKUserForTestPrefix+\"gen-data\")\n\theader.Set(constant.RidKey, kt.Rid)\n\theader.Set(constant.AppCodeKey, \"test\")\n\theader.Add(\"Cookie\", \"bk_token=\"+constant.BKTokenForTest)\n\n\tg.data = make(AppReleaseMeta, 0)\n\n\t//if err := g.initApp1(kt.Ctx, header); err != nil {\n\t//\treturn err\n\t//}\n\n\tif err := g.initApp2(kt.Ctx, header); err != nil {\n\t\treturn err\n\t}\n\n\t//if err := g.initApp3(kt.Ctx, header); err != nil {\n\t//\treturn err\n\t//}\n\n\treturn nil\n}", "func (e *DepositedEvent) Init(data *eventstore.EventData) {\n\te.StreamID = data.StreamID\n\te.EventNumber = data.EventNumber\n\te.Timestamp = data.Timestamp\n\n\tvar eventData depositedEventData\n\terr := json.Unmarshal([]byte(data.Data), &eventData)\n\tif err != nil {\n\t\tfmt.Printf(\"Error parsing eventstore data: %v\", err)\n\t}\n\te.Amount = eventData.Amount\n}", "func (plugin *Plugin) Init() error {\n\tplugin.Log.Debug(\"Initializing interface plugin\")\n\n\tplugin.fixNilPointers()\n\n\tplugin.ifStateNotifications = plugin.Deps.IfStatePub\n\tconfig, err := plugin.retrieveDPConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif config != nil {\n\t\tplugin.ifMtu = config.Mtu\n\t\tplugin.Log.Infof(\"Mtu read from config us set to %v\", plugin.ifMtu)\n\t\tplugin.enableStopwatch = config.Stopwatch\n\t\tif plugin.enableStopwatch {\n\t\t\tplugin.Log.Infof(\"stopwatch enabled for %v\", plugin.PluginName)\n\t\t} else {\n\t\t\tplugin.Log.Infof(\"stopwatch disabled for %v\", plugin.PluginName)\n\t\t}\n\t} else {\n\t\tplugin.ifMtu = defaultMtu\n\t\tplugin.Log.Infof(\"MTU set to default value %v\", plugin.ifMtu)\n\t\tplugin.Log.Infof(\"stopwatch disabled for %v\", plugin.PluginName)\n\t}\n\n\t// all channels that are used inside of publishIfStateEvents or watchEvents must be created in advance!\n\tplugin.ifStateChan = make(chan *intf.InterfaceStateNotification, 100)\n\tplugin.bdStateChan = make(chan *l2plugin.BridgeDomainStateNotification, 100)\n\tplugin.resyncConfigChan = make(chan datasync.ResyncEvent)\n\tplugin.resyncStatusChan = make(chan datasync.ResyncEvent)\n\tplugin.changeChan = make(chan datasync.ChangeEvent)\n\tplugin.ifIdxWatchCh = make(chan ifaceidx.SwIfIdxDto, 100)\n\tplugin.bdIdxWatchCh = make(chan bdidx.ChangeDto, 100)\n\tplugin.linuxIfIdxWatchCh = make(chan ifaceidx2.LinuxIfIndexDto, 100)\n\tplugin.errorChannel = make(chan ErrCtx, 100)\n\n\t// create plugin context, save cancel function into the plugin handle\n\tvar ctx context.Context\n\tctx, plugin.cancel = context.WithCancel(context.Background())\n\n\t//FIXME run following go routines later than following init*() calls - just before Watch()\n\n\t// run event handler go routines\n\tgo plugin.publishIfStateEvents(ctx)\n\tgo plugin.publishBdStateEvents(ctx)\n\tgo plugin.watchEvents(ctx)\n\n\t// run error handler\n\tgo plugin.changePropagateError()\n\n\terr = plugin.initIF(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = plugin.initACL(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = plugin.initL2(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = plugin.initL3(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = plugin.initErrorHandler()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = plugin.subscribeWatcher()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgPlugin = plugin\n\n\treturn nil\n}", "func Init() {\n\tdb = etc.Database\n\n\t// table init\n\tdb.CreateTableStruct(cTableSettings, Setting{})\n\tdb.CreateTableStruct(cTableUsers, User{})\n\tdb.CreateTableStruct(cTableChannels, Channel{})\n\tdb.CreateTableStruct(cTableRoles, Role{})\n\tdb.CreateTableStruct(cTableInvites, Invite{})\n\tdb.DropTable(cTableChannelPerms)\n\tdb.CreateTableStruct(cTableAudits, Audit{})\n\n\t// load server properties\n\tProps.SetDefault(\"name\", idata.Name)\n\tProps.SetDefault(\"owner\", \"\")\n\tProps.SetDefault(\"public\", \"1\")\n\tProps.SetDefault(\"description\", \"The new easy and effective communication platform for any successful team or community that's independently hosted and puts users, privacy, and effiecency first.\")\n\tProps.SetDefault(\"cover_photo\", \"data:,\")\n\tProps.SetDefault(\"profile_photo\", \"https://avatars.discourse.org/v4/letter/m/ec9cab/90.png\")\n\n\tpromkey := util.RandomString(64)\n\tProps.SetDefault(\"prometheus_key\", promkey)\n\tpromkeyF := etc.DataRoot() + \"/prometheus_key.txt\"\n\tif !util.DoesFileExist(promkeyF) {\n\t\tioutil.WriteFile(promkeyF, []byte(promkey), os.ModePerm)\n\t}\n\n\tProps.SetDefaultInt64(\"count_users_members\", 0)\n\tProps.SetDefaultInt64(\"count_users_banned\", 0)\n\tProps.SetDefaultInt64(\"count_users_members_max\", 0)\n\tProps.SetDefaultInt64(\"count_users_online\", 0)\n\n\tfor _, item := range ResourceTables {\n\t\tProps.SetDefaultInt64(\"count_\"+item, 0)\n\t}\n\tfor _, item := range (Channel{}.All()) {\n\t\ttn := cTableMessagesPrefix + item.UUID.String()\n\t\tProps.SetDefaultInt64(\"count_\"+tn, 0)\n\t\tProps.SetDefaultInt64(\"count_\"+tn+\"_edits\", 0)\n\t\tProps.SetDefaultInt64(\"count_\"+tn+\"_deletes\", 0)\n\t}\n\tfor i := 1; i < ActionLen(); i++ {\n\t\tis := strconv.Itoa(i)\n\t\tProps.SetDefaultInt64(\"count_\"+cTableAudits+\"_action_\"+is, queryCount(db.Build().Se(\"*\").Fr(cTableAudits).Wh(\"action\", is).Exe()))\n\t}\n\n\tProps.Init()\n\tProps.Set(\"version\", etc.Version)\n\n\t// for loop create channel message tables\n\t_chans := (Channel{}.All())\n\tfor _, item := range _chans {\n\t\titem.AssertMessageTableExists()\n\t}\n\n\t// add default channel, if none exist\n\tif len(_chans) == 0 {\n\t\tCreateChannel(\"general\")\n\t}\n}" ]
[ "0.7283833", "0.6657144", "0.6125424", "0.5870512", "0.58396035", "0.580803", "0.57953733", "0.5782265", "0.5777742", "0.56794196", "0.5673942", "0.56022596", "0.5583332", "0.5568376", "0.5543641", "0.5535632", "0.55293", "0.5492888", "0.54744464", "0.5467763", "0.54667914", "0.5457255", "0.5455273", "0.54533964", "0.545276", "0.54524505", "0.5447025", "0.5431202", "0.54258573", "0.54213554", "0.54048866", "0.5394116", "0.539119", "0.538698", "0.5382915", "0.5371628", "0.5365958", "0.5339368", "0.53389007", "0.5335468", "0.53326595", "0.533116", "0.53294885", "0.5327913", "0.53204477", "0.531431", "0.52981347", "0.5293245", "0.5291985", "0.5289575", "0.5289311", "0.5286584", "0.52776414", "0.5267545", "0.5266248", "0.5263578", "0.5257169", "0.5244643", "0.5244643", "0.5240224", "0.52308077", "0.5222101", "0.52174664", "0.52132547", "0.5210619", "0.52081496", "0.5204", "0.5201815", "0.5197611", "0.51935834", "0.51930207", "0.51830024", "0.5180486", "0.51794744", "0.51764774", "0.5158507", "0.51557857", "0.5150958", "0.51470107", "0.5145808", "0.513424", "0.5132638", "0.51293874", "0.5124564", "0.5121604", "0.5120879", "0.51168853", "0.51164484", "0.5116012", "0.5112479", "0.51071966", "0.5106999", "0.51007235", "0.5092337", "0.50908744", "0.5086169", "0.50803673", "0.5078337", "0.5077625", "0.50742835" ]
0.7873576
0
===== DinnerHost methods ===== AskChannels can be used to obtain two common channels of the host, the first used to request dinner, the second used to indicate that someone finished eating.
func (host *DinnerHost) AskChannels() (chan string, chan string) { return host.requestChannel, host.finishChannel }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (host *DinnerHost) Listen() {\n\tname := \"\"\n\tfor {\n\t\tselect {\n\t\tcase name = <-host.requestChannel:\n\t\t\tfmt.Println(name + \" WOULD LIKE TO EAT.\")\n\n\t\t\tresponse := host.AllowEating(name)\n\t\t\tkickOut := false\n\t\t\tswitch response {\n\t\t\tcase \"OK\":\n\t\t\t\tfmt.Println(name + \" STARTS EATING.\")\n\t\t\tcase \"E:CHOPSTICKS\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: REQUIRED CHOPSTICKS ARE NOT AVAILABLE.\")\n\t\t\tcase \"E:FULL\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: TWO OTHER PHILOSOPHERS ARE ALREADY EATING.\")\n\t\t\tcase \"E:JUSTFINISHED\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: JUST FINISHED THE PREVIOUS MEAL.\")\n\t\t\tcase \"E:EATING\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: ALREADY EATING.\")\n\t\t\tcase \"E:LIMIT\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: ALREADY HAD THREE DINNERS; MUST LEAVE.\")\n\t\t\t\thost.freeSeats = append(host.freeSeats, host.phiData[name].Seat())\n\t\t\t\tkickOut = true\n\t\t\t}\n\t\t\tfmt.Println()\n\n\t\t\thost.phiData[name].RespChannel() <- response\n\n\t\t\tif kickOut {\n\t\t\t\tdelete(host.phiData, name)\n\t\t\t}\n\t\tcase name = <-host.finishChannel:\n\t\t\thost.SomeoneFinished(name)\n\t\t}\n\t\thost.PrintReport(false)\n\t}\n}", "func (c *clientImpl) QueryChannels(peer sdkApi.Peer) ([]string, error) {\n\tresponses, err := c.client.QueryChannels(peer)\n\n\tif err != nil {\n\t\treturn nil, errors.Errorf(errors.GeneralError, \"Error querying channels on peer %+v : %s\", peer, err)\n\t}\n\tchannels := []string{}\n\n\tfor _, response := range responses.GetChannels() {\n\t\tchannels = append(channels, response.ChannelId)\n\t}\n\n\treturn channels, nil\n}", "func (txs *TxServiceImpl) QueryChannels(targetPeer sdkApi.Peer) ([]string, error) {\n\tchannels, err := txs.FcClient.QueryChannels(targetPeer)\n\tif err != nil {\n\t\treturn nil, errors.Errorf(errors.GeneralError, \"Error querying channels on %v: %s\", targetPeer, err)\n\t}\n\treturn channels, nil\n}", "func (phi *Philosopher) GoToDinner(waitGrp *sync.WaitGroup, requestChannel, finishChannel chan string) {\n\tdefer waitGrp.Done()\n\n\tretryInterval := time.Duration(2000) * time.Millisecond\n\teatingDuration := time.Duration(5000) * time.Millisecond\n\n\tfor {\n\t\trequestChannel <- phi.name\n\t\tswitch <-phi.respChannel {\n\t\tcase \"OK\":\n\t\t\ttime.Sleep(eatingDuration)\n\t\t\tfinishChannel <- phi.name\n\t\tcase \"E:LIMIT\":\n\t\t\tfmt.Println(strings.ToUpper(\"----- \" + phi.name + \" LEFT THE TABLE. -----\"))\n\t\t\tfmt.Println()\n\t\t\treturn\n\t\tdefault:\n\t\t\ttime.Sleep(retryInterval)\n\t\t}\n\t}\n}", "func (_TokensNetwork *TokensNetworkCallerSession) Channels(arg0 [32]byte) (struct {\n\tSettleTimeout uint64\n\tSettleBlockNumber uint64\n\tOpenBlockNumber uint64\n\tState uint8\n}, error) {\n\treturn _TokensNetwork.Contract.Channels(&_TokensNetwork.CallOpts, arg0)\n}", "func Connect(token string) error {\n\tdg, err := discordgo.New(\"Bot \" + token)\n\tif err != nil {\n\t\tfmt.Println(\"error creating Discord session,\", err)\n\t\treturn err\n\t}\n\tdg.AddHandler(manager)\n\tchannels, _ := dg.GuildChannels(\"675106841436356628\")\n\n\tfor _, v := range channels {\n\t\tfmt.Printf(\"Channel id: %s Channel name: %s\\n\", v.ID, v.Name)\n\t}\n\n\t// This function sends message every hour concurrently.\n\tgo func() {\n\t\tfor range time.NewTicker(time.Hour).C {\n\t\t\t_, err := dg.ChannelMessageSend(\"675109890204762143\", \"dont forget washing ur hands!\")\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"couldn't send ticker message\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\terr = dg.Open()\n\tif err != nil {\n\t\tfmt.Println(\"error opening connection,\", err)\n\t\treturn err\n\t}\n\t// Wait here until CTRL-C or other term signal is received.\n\tfmt.Println(\"Bot is now running. Press CTRL-C to exit.\")\n\tsc := make(chan os.Signal, 1)\n\tsignal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)\n\t<-sc\n\t// Cleanly close down the Discord session.\n\tdg.Close()\n\treturn nil\n}", "func DAHDIShowChannels(client Client, actionID, channel string) ([]Response, error) {\n\treturn requestList(client, \"DAHDIShowChannels\", actionID, \"DAHDIShowChannels\", \"DAHDIShowChannelsComplete\", map[string]string{\n\t\t\"DAHDIChannel\": channel,\n\t})\n}", "func (_TokensNetwork *TokensNetworkCaller) Channels(opts *bind.CallOpts, arg0 [32]byte) (struct {\n\tSettleTimeout uint64\n\tSettleBlockNumber uint64\n\tOpenBlockNumber uint64\n\tState uint8\n}, error) {\n\tret := new(struct {\n\t\tSettleTimeout uint64\n\t\tSettleBlockNumber uint64\n\t\tOpenBlockNumber uint64\n\t\tState uint8\n\t})\n\tout := ret\n\terr := _TokensNetwork.contract.Call(opts, out, \"channels\", arg0)\n\treturn *ret, err\n}", "func (_TokensNetwork *TokensNetworkSession) Channels(arg0 [32]byte) (struct {\n\tSettleTimeout uint64\n\tSettleBlockNumber uint64\n\tOpenBlockNumber uint64\n\tState uint8\n}, error) {\n\treturn _TokensNetwork.Contract.Channels(&_TokensNetwork.CallOpts, arg0)\n}", "func DAHDIShowChannels(ctx context.Context, client Client, actionID, channel string) ([]Response, error) {\n\treturn requestList(ctx, client, \"DAHDIShowChannels\", actionID, \"DAHDIShowChannels\", \"DAHDIShowChannelsComplete\", map[string]string{\n\t\t\"DAHDIChannel\": channel,\n\t})\n}", "func FindMatchingKnocks() {\n\tfor key1, knock1 := range recvdKnocks.Knocks {\n\t\tfor key2, knock2 := range recvdKnocks.Knocks {\n\t\t\tif knock1 != knock2 && knock1.Id != knock2.Id {\n\t\t\t\tt1 := knock1.TimeSend\n\t\t\t\tt2 := knock2.TimeSend\n\t\t\t\tdelaybetweenKnocks := time.Duration(time.Second)\n\t\t\t\tif t1.Before(t2) {\n\t\t\t\t\tdelaybetweenKnocks = t2.Sub(t1)\n\t\t\t\t} else {\n\t\t\t\t\tdelaybetweenKnocks = t1.Sub(t2)\n\t\t\t\t}\n\t\t\t\tif delaybetweenKnocks < goodDurKnock {\n\t\t\t\t\tCKPCMux.Lock()\n\t\t\t\t\tConfirmedKnockPairCount += 1\n\n\t\t\t\t\tknock1ChanG, found := confirmedKnockChanList.Load(knock1.Id)\n\t\t\t\t\tif !found {\n\t\t\t\t\t\tlog.Println(\"knockedChan chan not found for ID\", knock1.Id)\n\t\t\t\t\t}\n\t\t\t\t\tknock1Chan := knock1ChanG.(chan confirmedKnock)\n\n\t\t\t\t\tknock2ChanG, found := confirmedKnockChanList.Load(knock2.Id)\n\t\t\t\t\tif !found {\n\t\t\t\t\t\tlog.Println(\"knockedChan chan not found for ID\", knock2.Id)\n\t\t\t\t\t}\n\t\t\t\t\tknock2Chan := knock2ChanG.(chan confirmedKnock)\n\n\t\t\t\t\tknock1Chan <- confirmedKnock{knock1.Id, knock1.Loc, ConfirmedKnockPairCount}\n\t\t\t\t\tknock2Chan <- confirmedKnock{knock2.Id, knock2.Loc, ConfirmedKnockPairCount}\n\t\t\t\t\t//Adding neighbours to each other\n\t\t\t\t\tvar thisKnock, NeighbourKnock knock = knock1, knock2\n\n\t\t\t\t\tthis_deviceG, found := conctdDevices.Load(thisKnock.Id)\n\t\t\t\t\tif !found {\n\t\t\t\t\t\tlog.Println(\"ERR device not found with \", thisKnock.Id)\n\t\t\t\t\t}\n\t\t\t\t\tthis_device := this_deviceG.(*Device)\n\n\t\t\t\t\tNeigbour_deviceG, found := conctdDevices.Load(NeighbourKnock.Id)\n\t\t\t\t\tif !found {\n\t\t\t\t\t\tlog.Println(\"ERR device not found with \", NeighbourKnock.Id)\n\t\t\t\t\t}\n\t\t\t\t\tNeigbour_device := Neigbour_deviceG.(*Device)\n\n\t\t\t\t\tthis_device.AddNighbour(thisKnock.Loc, Neigbour_device)\n\t\t\t\t\tNeigbour_device.AddNighbour(NeighbourKnock.Loc, this_device)\n\n\t\t\t\t\tfmt.Println(\"After adding nighbours =================\")\n\t\t\t\t\tprintConctdDevices()\n\n\t\t\t\t\tCKPCMux.Unlock()\n\n\t\t\t\t\t//\tRemoving knock1 and knock2\n\t\t\t\t\tdelete(recvdKnocks.Knocks, key1)\n\t\t\t\t\tdelete(recvdKnocks.Knocks, key2)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n}", "func Dial(ctx context.Context, token string) (*Client, error) {\n\tc := &Client{\n\t\ttoken: token,\n\t\tpingError: make(chan error, 1),\n\t\tpollError: make(chan error, 1),\n\t\tchannels: make(map[string]*channel),\n\t\tusers: make(map[chat.UserID]chat.User),\n\t\tmedia: make(map[string]File),\n\t}\n\n\tvar resp struct {\n\t\tResponseHeader\n\t\tURL string `json:\"url\"`\n\t\tSelf struct {\n\t\t\tID string `json:\"id\"`\n\t\t} `json:\"self\"`\n\t\tTeam struct {\n\t\t\tDomain string `json:\"domain\"`\n\t\t} `json:\"team\"`\n\t\tUsers []User `json:\"users\"`\n\t}\n\tif err := rpc(ctx, c, &resp, \"rtm.start\"); err != nil {\n\t\treturn nil, err\n\t}\n\twebSock, err := websocket.Dial(resp.URL, \"\", api.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.webSock = webSock\n\tfor _, u := range resp.Users {\n\t\tif u.ID == resp.Self.ID {\n\t\t\tc.me = &u\n\t\t}\n\t\tc.users[chat.UserID(u.ID)] = chatUser(&u)\n\t}\n\tif c.me == nil {\n\t\treturn nil, fmt.Errorf(\"self user %s not in users list\", resp.Self.ID)\n\t}\n\tc.domain = resp.Team.Domain\n\n\tswitch event, err := c.next(ctx); {\n\tcase err != nil:\n\t\treturn nil, err\n\tcase event.Type != \"hello\":\n\t\treturn nil, fmt.Errorf(\"expected hello, got %v\", event)\n\t}\n\n\tbkg := context.Background()\n\tbkg, c.cancel = context.WithCancel(bkg)\n\tgo ping(bkg, c)\n\tgo poll(bkg, c)\n\n\treturn c, nil\n}", "func channelFromHost(host string, workers uint) uint32 {\n\th := fnv.New32a()\n\th.Write([]byte(host))\n\treturn h.Sum32() % uint32(workers)\n}", "func (c *Client) Channels(ctx context.Context, r ChannelsRequest) (*ChannelsReply, error) {\r\n\treq, err := http.NewRequestWithContext(\r\n\t\tctx,\r\n\t\thttp.MethodGet,\r\n\t\tfmt.Sprintf(\"%s/%s/channel/list\", c.getChanelBaseEndpoint(), r.AccountID),\r\n\t\tnil,\r\n\t)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\tres := ChannelsReply{}\r\n\tif err := c.sendRequest(req, &res); err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\treturn &res, nil\r\n}", "func QueryChannel(\n\tclientCtx client.Context, portID, channelID string, prove bool,\n) (*types.QueryChannelResponse, error) {\n\tif prove {\n\t\treturn queryChannelABCI(clientCtx, portID, channelID)\n\t}\n\n\tqueryClient := types.NewQueryClient(clientCtx)\n\treq := &types.QueryChannelRequest{\n\t\tPortId: portID,\n\t\tChannelId: channelID,\n\t}\n\n\treturn queryClient.Channel(context.Background(), req)\n}", "func (w *FabricSDKWrapper) Query(channelID string, userName string,orgName string, chaincodeID string, ccFunctionName string, args []string, targetEndpoints ...string) (channel.Response, error) {\n\tchannelClient, err := w.createChannelClient(channelID, userName, orgName)\n\n\tif err != nil {\n\t\treturn channel.Response{}, err\n\t}\n\n\tresponse, err := channelClient.Query(\n\t\tchannel.Request{\n\t\t\tChaincodeID: chaincodeID,\n\t\t\tFcn: ccFunctionName,\n\t\t\tArgs: utils.AsBytes(args),\n\t\t},\n\t\tchannel.WithRetry(retry.DefaultChannelOpts),\n\t\tchannel.WithTargetEndpoints(targetEndpoints...),\n\t\t)\n\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\treturn response, nil\n}", "func (c *Client) Channels(guildID discord.GuildID) ([]discord.Channel, error) {\n\tvar chs []discord.Channel\n\treturn chs, c.RequestJSON(&chs, \"GET\", EndpointGuilds+guildID.String()+\"/channels\")\n}", "func handleServerChannels(t *testing.T, ctx context.Context, wg *sync.WaitGroup, sshCn ssh.Conn, chans <-chan ssh.NewChannel) {\n\tdefer wg.Done()\n\tfor nc := range chans {\n\t\tif nc.ChannelType() != \"direct-tcpip\" {\n\t\t\tnc.Reject(ssh.UnknownChannelType, \"not implemented\")\n\t\t\tcontinue\n\t\t}\n\t\tvar args struct {\n\t\t\tDstHost string\n\t\t\tDstPort uint32\n\t\t\tSrcHost string\n\t\t\tSrcPort uint32\n\t\t}\n\t\tif !unmarshalData(nc.ExtraData(), &args) {\n\t\t\tnc.Reject(ssh.Prohibited, \"invalid request\")\n\t\t\tcontinue\n\t\t}\n\n\t\t// Open a connection for both sides.\n\t\tcn, err := net.Dial(\"tcp\", net.JoinHostPort(args.DstHost, strconv.Itoa(int(args.DstPort))))\n\t\tif err != nil {\n\t\t\tnc.Reject(ssh.ConnectionFailed, err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tch, reqs, err := nc.Accept()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"accept channel error: %v\", err)\n\t\t\tcn.Close()\n\t\t\tcontinue\n\t\t}\n\t\tgo ssh.DiscardRequests(reqs)\n\n\t\twg.Add(1)\n\t\tgo bidirCopyAndClose(t, ctx, wg, cn, ch)\n\t}\n}", "func (s *Switch) askForMorePeers(ctx context.Context) {\n\t// check how much peers needed\n\ts.outpeersMutex.RLock()\n\tnumpeers := len(s.outpeers)\n\ts.outpeersMutex.RUnlock()\n\treq := s.config.SwarmConfig.RandomConnections - numpeers\n\tif req <= 0 {\n\t\t// If 0 connections are required, the condition above is always true,\n\t\t// so gossip needs to be considered ready in this case.\n\t\tif s.config.SwarmConfig.RandomConnections == 0 {\n\t\t\tselect {\n\t\t\tcase <-s.initial:\n\t\t\t\t// Nothing to do if channel is closed.\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\t// Close channel if it is not closed.\n\t\t\t\tclose(s.initial)\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\n\t// try to connect eq peers\n\ts.getMorePeers(ctx, req)\n\n\t// check number of peers after\n\ts.outpeersMutex.RLock()\n\tnumpeers = len(s.outpeers)\n\ts.outpeersMutex.RUnlock()\n\n\t// announce if initial number of peers achieved\n\t// todo: better way then going in this every time?\n\tif numpeers >= s.config.SwarmConfig.RandomConnections {\n\t\ts.initOnce.Do(func() {\n\t\t\ts.logger.WithContext(ctx).With().Info(\"gossip connected to initial required neighbors\",\n\t\t\t\tlog.Int(\"n\", len(s.outpeers)))\n\t\t\ts.closeInitial()\n\t\t\ts.outpeersMutex.RLock()\n\t\t\tvar strs []string\n\t\t\tfor pk := range s.outpeers {\n\t\t\t\tstrs = append(strs, pk.String())\n\t\t\t}\n\t\t\ts.logger.WithContext(ctx).With().Debug(\"neighbors list\",\n\t\t\t\tlog.String(\"neighbors\", strings.Join(strs, \",\")))\n\t\t\ts.outpeersMutex.RUnlock()\n\t\t})\n\t\treturn\n\t}\n\n\ts.logger.With().Warning(\"needs more peers\",\n\t\tlog.Int(\"count_needed\", s.config.SwarmConfig.RandomConnections-numpeers))\n\n\t// if we couldn't get any maybe we're initializing\n\t// wait a little bit before trying again\n\ttmr := time.NewTimer(NoResultsInterval)\n\tdefer tmr.Stop()\n\tselect {\n\tcase <-s.shutdownCtx.Done():\n\t\treturn\n\tcase <-tmr.C:\n\t\ts.morePeersReq <- struct{}{}\n\t}\n}", "func DiscoverChannels(conn *NetworkConnection, options ...DiscoverOptionFunc) map[string]string {\n\t// map[channelID]endpointURL\n\tchannelIDMap := make(map[string]string)\n\n\t//opt := generateOption(options...)\n\t// Get all channels.\n\t// The network peers are corresponding to the config in yaml organizations/<org>/peers.\n\t// They will be blank if no peers defined. But acutally all the peers can be found by discover service.\n\t// TODO if the endpoint config is nil, that means the identity is not found, the error should be return.\n\tif conn.Client.EndpointConfig() != nil {\n\t\tfor _, endpoint := range conn.Client.EndpointConfig().NetworkPeers() {\n\t\t\t// It doesn't work now, since we still need to retrieve channels from the endpoint configured.\n\t\t\t// if !opt.isTarget(endpoint.URL) {\n\t\t\t// \tcontinue\n\t\t\t// }\n\n\t\t\t//if endpoint.MSPID == conn.Participant.MSPID\n\t\t\tchannels, err := GetJoinedChannels(conn, endpoint.URL, options...)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(\"Getting joined channels got failed for endpoint %s: %s\", endpoint.URL, err.Error())\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Only the first endpoint will be processed if they are duplicated.\n\t\t\t// TODO to get and use all peers of the channel.\n\t\t\tfor _, channel := range channels {\n\t\t\t\tif _, ok := channelIDMap[channel.GetChannelId()]; !ok {\n\t\t\t\t\tchannelIDMap[channel.GetChannelId()] = endpoint.URL\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tlogger.Infof(\"Found channels and only corresponding endpoints %v.\", channelIDMap)\n\treturn channelIDMap\n}", "func (m *TeamItemRequestBuilder) Channels()(*id463d65124ba412b3980ec713bebe8eb90e4a925515f5f993cd79d5b01b70907.ChannelsRequestBuilder) {\n return id463d65124ba412b3980ec713bebe8eb90e4a925515f5f993cd79d5b01b70907.NewChannelsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func Channels(mods ...qm.QueryMod) channelQuery {\n\tmods = append(mods, qm.From(\"\\\"channels\\\"\"))\n\treturn channelQuery{NewQuery(mods...)}\n}", "func (cm *ConnectionManager) JoinChannel(partnerAddress common.Address, partnerDepost *big.Int) {\n\tif cm.funds.Cmp(utils.BigInt0) <= 0 {\n\t\treturn\n\t}\n\tif cm.leaveState() {\n\t\treturn\n\t}\n\tcm.lock.Lock()\n\tdefer cm.lock.Unlock()\n\tremaining := cm.fundsRemaining()\n\tinitial := cm.initialFundingPerPartner()\n\tjoiningFunds := partnerDepost\n\tif joiningFunds.Cmp(remaining) > 0 {\n\t\tjoiningFunds = remaining\n\t}\n\tif joiningFunds.Cmp(initial) > 0 {\n\t\tjoiningFunds = initial\n\t}\n\tif joiningFunds.Cmp(utils.BigInt0) <= 0 {\n\t\treturn\n\t}\n\t_, err := cm.api.Deposit(cm.tokenAddress, partnerAddress, joiningFunds, params.DefaultPollTimeout)\n\tlog.Debug(\"joined a channel funds=%d,me=%s,partner=%s err=%s\", joiningFunds, utils.APex(cm.raiden.NodeAddress), utils.APex(partnerAddress), err)\n\treturn\n}", "func (h *hub) run() {\n for {\n select{\n case s := <- h.register:\n // fmt.Println(\"wild client has appeared in the brush!\")\n clients := h.channels[s.channel]\n if clients == nil {\n clients = make(map[*client]bool)\n h.channels[s.channel] = clients\n }\n h.channels[s.channel][s.client] = true\n //send the latest data for room (empty string if new room)\n //s.client.send <- []byte(contents[s.channel])\n case s := <- h.unregister:\n clients := h.channels[s.channel]\n if clients != nil {\n if _, ok := clients[s.client]; ok{\n delete(clients, s.client)\n close(s.client.send)\n if len(clients) == 0 {\n delete(h.channels, s.channel)\n if len(contents[s.channel]) != 0 {\n //delete contents for channel if no more clients using it.\n delete(contents, s.channel)\n }\n }\n }\n }\n case m := <- h.broadcast:\n clients := h.channels[m.channel]\n // fmt.Println(\"broadcasting message to \", clients, \"data is: \", string(m.data))\n for c := range clients {\n fmt.Println(\"broadcasting message to \", c, \"data is: \", string(m.data))\n select {\n case c.send <- m.data:\n contents[m.channel] = string(m.data)\n default:\n close(c.send)\n delete(clients, c)\n if len(clients) == 0 {\n delete(h.channels, m.channel)\n if len(contents[m.channel]) != 0 {\n //delete contents for channel if no more clients using it.\n delete(contents, m.channel)\n }\n }\n }\n }\n }\n }\n}", "func (sdkClient *SDKClient) GetChannel(client fab.FabricClient, channelID string, orgs []string) (fab.Channel, error) {\n\n\tchannel, err := client.NewChannel(channelID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"NewChannel return error: %v\", err)\n\t}\n\n\tordererConfig, err := client.Config().RandomOrdererConfig()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"RandomOrdererConfig() return error: %s\", err)\n\t}\n\tserverHostOverride := \"\"\n\tif str, ok := ordererConfig.GRPCOptions[\"ssl-target-name-override\"].(string); ok {\n\t\tserverHostOverride = str\n\t}\n\torderer, err := orderer.NewOrderer(ordererConfig.URL, ordererConfig.TLSCACerts.Path, serverHostOverride, client.Config())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"NewOrderer return error: %v\", err)\n\t}\n\n\terr = channel.AddOrderer(orderer)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error adding orderer: %v\", err)\n\t}\n\n\tfor _, org := range orgs {\n\n\t\tpeerConfig, err := client.Config().PeersConfig(org)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error reading peer config: %v\", err)\n\t\t}\n\t\tfor _, p := range peerConfig {\n\t\t\tfmt.Println(\"Parsing peer \", p.EventURL)\n\t\t\tserverHostOverride = \"\"\n\t\t\tif str, ok := p.GRPCOptions[\"ssl-target-name-override\"].(string); ok {\n\t\t\t\tserverHostOverride = str\n\t\t\t}\n\t\t\tendorser, err := deffab.NewPeer(p.URL, p.TLSCACerts.Path, serverHostOverride, client.Config())\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"NewPeer return error: %v\", err)\n\t\t\t}\n\t\t\terr = channel.AddPeer(endorser)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"Error adding peer: %v\", err)\n\t\t\t}\n\n\t\t}\n\t}\n\n\treturn channel, nil\n}", "func testChannel(t *testing.T, src, dst *Chain) {\n\tchans, err := src.QueryChannels(1, 1000)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 1, len(chans))\n\trequire.Equal(t, chans[0].GetOrdering().String(), \"ORDERED\")\n\trequire.Equal(t, chans[0].GetState().String(), \"OPEN\")\n\trequire.Equal(t, chans[0].GetCounterparty().GetChannelID(), dst.PathEnd.ChannelID)\n\trequire.Equal(t, chans[0].GetCounterparty().GetPortID(), dst.PathEnd.PortID)\n\n\th, err := src.Client.Status()\n\trequire.NoError(t, err)\n\n\tch, err := src.QueryChannel(h.SyncInfo.LatestBlockHeight)\n\trequire.NoError(t, err)\n\trequire.Equal(t, ch.Channel.GetOrdering().String(), \"ORDERED\")\n\trequire.Equal(t, ch.Channel.GetState().String(), \"OPEN\")\n\trequire.Equal(t, ch.Channel.GetCounterparty().GetChannelID(), dst.PathEnd.ChannelID)\n\trequire.Equal(t, ch.Channel.GetCounterparty().GetPortID(), dst.PathEnd.PortID)\n}", "func (_WandappETH *WandappETHCaller) GetChannelInfo(opts *bind.CallOpts, user common.Address) (*big.Int, *big.Int, *big.Int, *big.Int, uint64, uint64, *big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t\tret1 = new(*big.Int)\n\t\tret2 = new(*big.Int)\n\t\tret3 = new(*big.Int)\n\t\tret4 = new(uint64)\n\t\tret5 = new(uint64)\n\t\tret6 = new(*big.Int)\n\t)\n\tout := &[]interface{}{\n\t\tret0,\n\t\tret1,\n\t\tret2,\n\t\tret3,\n\t\tret4,\n\t\tret5,\n\t\tret6,\n\t}\n\terr := _WandappETH.contract.Call(opts, out, \"getChannelInfo\", user)\n\treturn *ret0, *ret1, *ret2, *ret3, *ret4, *ret5, *ret6, err\n}", "func actSelectHost(data *interface{}, client *wserver.Client) {\n\tname, _ := (*data).(string)\n\thost, ok := hostConnections.GetByLogin(name)\n\tif !ok {\n\t\tclient.SendJson(&Action{\"SELECT_FAIL\", \"host not exist\"})\n\t\treturn\n\t}\n\thost.Lock()\n\tdefer func() {\n\t\thost.Unlock()\n\t\tlog.Println(\"-----------UNLOCK\")\n\t}()\n\n\tif host.Active {\n\t\tclient.SendJson(&Action{\"SELECT_FAIL\", \"host busy\"})\n\t\treturn\n\t}\n\thost.Active = true\n\n\thost.Conn.SendJson(&Action{\"CLIENT_CONNECT\", \"\"})\n\tlog.Println(\"-----------LOCKED1\")\n\thost.Wait()\n\tlog.Println(\"-----------LOCKED2\")\n\tif host.Active == false {\n\t\tclient.SendJson(&Action{\"SELECT_FAIL\", \"denied\"})\n\t\treturn\n\t}\n\n\thost.Conn.SetOnmessage(copyMessage(client))\n\tclient.SetOnmessage(copyMessage(host.Conn))\n\n\tchRelay.Add(client, host)\n\tclient.SendJson(&Action{\"SELECT_SUCCESS\", \"\"})\n}", "func (_WandappETH *WandappETHSession) GetChannelInfo(user common.Address) (*big.Int, *big.Int, *big.Int, *big.Int, uint64, uint64, *big.Int, error) {\n\treturn _WandappETH.Contract.GetChannelInfo(&_WandappETH.CallOpts, user)\n}", "func getChannelsOfKind(guildID string, s *discordgo.Session, kind string) []*discordgo.Channel {\n\tguild, err := s.State.Guild(guildID)\n\tchannels := []*discordgo.Channel{}\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn channels\n\t}\n\tfor _, c := range guild.Channels {\n\t\tif c.Type == kind {\n\t\t\tchannels = append(channels, c)\n\t\t}\n\t}\n\treturn channels\n}", "func EasyQuery(ch chan RCONQuery) func(string) []byte {\n\treturn func(cmd string) []byte {\n\t\tres := make(chan []byte)\n\t\tch <- RCONQuery{Command: cmd, Response: res}\n\n\t\treturn <-res\n\t}\n}", "func (suite KeeperTestSuite) TestGetAllChannels() {\n\tpath := ibctesting.NewPath(suite.chainA, suite.chainB)\n\tsuite.coordinator.Setup(path)\n\t// channel0 on first connection on chainA\n\tcounterparty0 := types.Counterparty{\n\t\tPortId: path.EndpointB.ChannelConfig.PortID,\n\t\tChannelId: path.EndpointB.ChannelID,\n\t}\n\n\t// path1 creates a second channel on first connection on chainA\n\tpath1 := ibctesting.NewPath(suite.chainA, suite.chainB)\n\tpath1.SetChannelOrdered()\n\tpath1.EndpointA.ClientID = path.EndpointA.ClientID\n\tpath1.EndpointB.ClientID = path.EndpointB.ClientID\n\tpath1.EndpointA.ConnectionID = path.EndpointA.ConnectionID\n\tpath1.EndpointB.ConnectionID = path.EndpointB.ConnectionID\n\n\tsuite.coordinator.CreateMockChannels(path1)\n\tcounterparty1 := types.Counterparty{\n\t\tPortId: path1.EndpointB.ChannelConfig.PortID,\n\t\tChannelId: path1.EndpointB.ChannelID,\n\t}\n\n\tpath2 := ibctesting.NewPath(suite.chainA, suite.chainB)\n\tsuite.coordinator.SetupConnections(path2)\n\n\t// path2 creates a second channel on chainA\n\terr := path2.EndpointA.ChanOpenInit()\n\tsuite.Require().NoError(err)\n\n\t// counterparty channel id is empty after open init\n\tcounterparty2 := types.Counterparty{\n\t\tPortId: path2.EndpointB.ChannelConfig.PortID,\n\t\tChannelId: \"\",\n\t}\n\n\tchannel0 := types.NewChannel(\n\t\ttypes.OPEN, types.UNORDERED,\n\t\tcounterparty0, []string{path.EndpointA.ConnectionID}, path.EndpointA.ChannelConfig.Version,\n\t)\n\tchannel1 := types.NewChannel(\n\t\ttypes.OPEN, types.ORDERED,\n\t\tcounterparty1, []string{path1.EndpointA.ConnectionID}, path1.EndpointA.ChannelConfig.Version,\n\t)\n\tchannel2 := types.NewChannel(\n\t\ttypes.INIT, types.UNORDERED,\n\t\tcounterparty2, []string{path2.EndpointA.ConnectionID}, path2.EndpointA.ChannelConfig.Version,\n\t)\n\n\texpChannels := []types.IdentifiedChannel{\n\t\ttypes.NewIdentifiedChannel(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, channel0),\n\t\ttypes.NewIdentifiedChannel(path1.EndpointA.ChannelConfig.PortID, path1.EndpointA.ChannelID, channel1),\n\t\ttypes.NewIdentifiedChannel(path2.EndpointA.ChannelConfig.PortID, path2.EndpointA.ChannelID, channel2),\n\t}\n\n\tctxA := suite.chainA.GetContext()\n\n\tchannels := suite.chainA.App.GetIBCKeeper().ChannelKeeper.GetAllChannels(ctxA)\n\tsuite.Require().Len(channels, len(expChannels))\n\tsuite.Require().Equal(expChannels, channels)\n}", "func (l *loopInSwapSuggestion) channels() []lnwire.ShortChannelID {\n\treturn nil\n}", "func (server *OpencxServer) GetQchansByPeerParam(pubkey *koblitz.PublicKey, param *coinparam.Params) (qchans []*qln.Qchan, err error) {\n\n\t// get the peer idx\n\tvar peerIdx uint32\n\tif peerIdx, err = server.GetPeerFromPubkey(pubkey); err != nil {\n\t\treturn\n\t}\n\n\t// get the peer\n\tvar peer *lnp2p.Peer\n\tif peer = server.ExchangeNode.PeerMan.GetPeerByIdx(int32(peerIdx)); err != nil {\n\t\treturn\n\t}\n\n\t// lock this so we can be in peace\n\tserver.ExchangeNode.PeerMapMtx.Lock()\n\t// get the remote peer from the qchan\n\tvar remotePeer *qln.RemotePeer\n\tvar found bool\n\tif remotePeer, found = server.ExchangeNode.PeerMap[peer]; !found {\n\t\terr = fmt.Errorf(\"Could not find remote peer that peer manager is tracking, there's something wrong with the lit node\")\n\t\t// unlock because we have to before we return or else we deadlock\n\t\tserver.ExchangeNode.PeerMapMtx.Unlock()\n\t\treturn\n\t}\n\tserver.ExchangeNode.PeerMapMtx.Unlock()\n\n\t// populate qchans just to be safe -- this might not be necessary and makes this function very inefficient\n\tif err = server.ExchangeNode.PopulateQchanMap(remotePeer); err != nil {\n\t\treturn\n\t}\n\n\t// get qchans from peer\n\tfor _, qchan := range remotePeer.QCs {\n\t\t// if this is the same coin then return the idx\n\t\tif qchan.Coin() == param.HDCoinType {\n\t\t\tqchans = append(qchans, qchan)\n\t\t}\n\t}\n\n\treturn\n}", "func (suite *KeeperTestSuite) TestChanCloseConfirm() {\n\tvar (\n\t\tpath *ibctesting.Path\n\t\tchannelCap *capabilitytypes.Capability\n\t\theightDiff uint64\n\t)\n\n\ttestCases := []testCase{\n\t\t{\"success\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\terr := path.EndpointA.SetChannelClosed()\n\t\t\tsuite.Require().NoError(err)\n\t\t}, true},\n\t\t{\"channel doesn't exist\", func() {\n\t\t\t// any non-nil values work for connections\n\t\t\tpath.EndpointA.ChannelID = ibctesting.FirstChannelID\n\t\t\tpath.EndpointB.ChannelID = ibctesting.FirstChannelID\n\n\t\t\t// ensure channel capability check passes\n\t\t\tsuite.chainB.CreateChannelCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\t\t}, false},\n\t\t{\"channel state is CLOSED\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\terr := path.EndpointB.SetChannelClosed()\n\t\t\tsuite.Require().NoError(err)\n\t\t}, false},\n\t\t{\"connection not found\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\t// set the channel's connection hops to wrong connection ID\n\t\t\tchannel := path.EndpointB.GetChannel()\n\t\t\tchannel.ConnectionHops[0] = \"doesnotexist\"\n\t\t\tsuite.chainB.App.GetIBCKeeper().ChannelKeeper.SetChannel(suite.chainB.GetContext(), path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, channel)\n\t\t}, false},\n\t\t{\"connection is not OPEN\", func() {\n\t\t\tsuite.coordinator.SetupClients(path)\n\n\t\t\terr := path.EndpointB.ConnOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\t// create channel in init\n\t\t\tpath.SetChannelOrdered()\n\t\t\terr = path.EndpointB.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\t// ensure channel capability check passes\n\t\t\tsuite.chainB.CreateChannelCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\t\t}, false},\n\t\t{\"consensus state not found\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\terr := path.EndpointA.SetChannelClosed()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\theightDiff = 3\n\t\t}, false},\n\t\t{\"channel verification failed\", func() {\n\t\t\t// channel not closed\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\t\t}, false},\n\t\t{\"channel capability not found\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\terr := path.EndpointA.SetChannelClosed()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = capabilitytypes.NewCapability(3)\n\t\t}, false},\n\t}\n\n\tfor _, tc := range testCases {\n\t\ttc := tc\n\t\tsuite.Run(fmt.Sprintf(\"Case %s\", tc.msg), func() {\n\t\t\tsuite.SetupTest() // reset\n\t\t\theightDiff = 0 // must explicitly be changed\n\t\t\tpath = ibctesting.NewPath(suite.chainA, suite.chainB)\n\n\t\t\ttc.malleate()\n\n\t\t\tchannelKey := host.ChannelKey(path.EndpointA.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\t\t\tproof, proofHeight := suite.chainA.QueryProof(channelKey)\n\n\t\t\terr := suite.chainB.App.GetIBCKeeper().ChannelKeeper.ChanCloseConfirm(\n\t\t\t\tsuite.chainB.GetContext(), path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID, channelCap,\n\t\t\t\tproof, malleateHeight(proofHeight, heightDiff),\n\t\t\t)\n\n\t\t\tif tc.expPass {\n\t\t\t\tsuite.Require().NoError(err)\n\t\t\t} else {\n\t\t\t\tsuite.Require().Error(err)\n\t\t\t}\n\t\t})\n\t}\n}", "func (_TokensNetwork *TokensNetworkCaller) GetChannelInfo(opts *bind.CallOpts, token common.Address, participant1 common.Address, participant2 common.Address) ([32]byte, uint64, uint64, uint8, uint64, error) {\n\tvar (\n\t\tret0 = new([32]byte)\n\t\tret1 = new(uint64)\n\t\tret2 = new(uint64)\n\t\tret3 = new(uint8)\n\t\tret4 = new(uint64)\n\t)\n\tout := &[]interface{}{\n\t\tret0,\n\t\tret1,\n\t\tret2,\n\t\tret3,\n\t\tret4,\n\t}\n\terr := _TokensNetwork.contract.Call(opts, out, \"getChannelInfo\", token, participant1, participant2)\n\treturn *ret0, *ret1, *ret2, *ret3, *ret4, err\n}", "func (cm *ConnectionManager) receivingChannels() (chs []*channeltype.Serialization) {\n\tfor _, c := range cm.openChannels() {\n\t\tif c.PartnerBalanceProof != nil && c.PartnerBalanceProof.Nonce > 0 {\n\t\t\tchs = append(chs, c)\n\t\t}\n\t}\n\treturn\n}", "func (this *Peer) askForPeers(num int) []PeerId {\n\tsharedPeerIds := this.protocol.askForPeers(this.id, num)\n\t// Insert peer handler here if necesssay.\n\treturn sharedPeerIds\n}", "func (client *Client) Channels() []*Channel {\n\ttargets := client.Targets(\"channel\")\n\tchannels := make([]*Channel, len(targets))\n\n\tfor i := range targets {\n\t\tchannels[i] = targets[i].(*Channel)\n\t}\n\n\treturn channels\n}", "func (a *action) Query(chaincodeID, fctn string, args [][]byte) ([]byte, error) {\n\tchannelClient, err := a.ChannelClient()\n\tif err != nil {\n\t\treturn nil, errors.Errorf(errors.GeneralError, \"Error getting channel client: %s\", err)\n\t}\n\n\tresp, err := channelClient.Query(\n\t\tchannel.Request{\n\t\t\tChaincodeID: chaincodeID,\n\t\t\tFcn: fctn,\n\t\t\tArgs: args,\n\t\t},\n\t\tchannel.WithTargets(a.peers...),\n\t\tchannel.WithRetry(retry.DefaultChannelOpts),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp.Payload, nil\n}", "func (c *Client) Join(channels ...*irc.Channel) (err error) {\n\tfor _, ch := range channels {\n\t\tif err = c.Raw(\"chanserv INVITE %s\", ch.Name); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif len(ch.Key) > 0 {\n\t\t\terr = c.Raw(\"JOIN %s %s\", ch.Name, ch.Key)\n\t\t} else {\n\t\t\terr = c.Raw(\"JOIN %s\", ch.Name)\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif len(ch.ChanservPassword) > 0 {\n\t\t\terr = c.PrivMsg(\"chanserv\", \"IDENTIFY %s %s\", ch.Name, ch.ChanservPassword)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}", "func (d *Discord) Channel(channelID string) (channel *discordgo.Channel, err error) {\n\tfor _, s := range d.Sessions {\n\t\tchannel, err = s.State.Channel(channelID)\n\t\tif err == nil {\n\t\t\treturn channel, nil\n\t\t}\n\t}\n\treturn\n}", "func (d *Demo) TickChannel(network, channel string) {\n\tscope := data.Scope{\n\t\tNet: network,\n\t\tName: channel,\n\t}\n\td.ensureChannel(scope)\n\n\tch := d.chans[scope]\n\tch.Mode = nextMode(ch.Mode)\n\tch.Presence = nextPresence(ch.Presence)\n\tch.Topic = nextTopic(ch.Topic)\n\tch.Members++\n\n\tgo d.updateAll()\n}", "func (_WandappETH *WandappETHCallerSession) GetChannelInfo(user common.Address) (*big.Int, *big.Int, *big.Int, *big.Int, uint64, uint64, *big.Int, error) {\n\treturn _WandappETH.Contract.GetChannelInfo(&_WandappETH.CallOpts, user)\n}", "func (_TokensNetwork *TokensNetworkCallerSession) GetChannelInfo(token common.Address, participant1 common.Address, participant2 common.Address) ([32]byte, uint64, uint64, uint8, uint64, error) {\n\treturn _TokensNetwork.Contract.GetChannelInfo(&_TokensNetwork.CallOpts, token, participant1, participant2)\n}", "func (sdkClient *SDKClient) JoinChannel() error {\n\tfoundChannel := false\n\tfor _, peer := range sdkClient.Channel.Peers() {\n\n\t\t_LOGGER.Printf(\"Checking peer %s\\n\", peer.URL())\n\t\tresponse, err := sdkClient.Client.QueryChannels(peer)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error querying channel for primary peer: %s\", err)\n\t\t}\n\n\t\tfor _, responseChannel := range response.Channels {\n\t\t\tif responseChannel.ChannelId == sdkClient.Channel.Name() {\n\t\t\t\tfoundChannel = true\n\t\t\t\t_LOGGER.Printf(\"Peer %s already joined \\n\", peer.URL())\n\t\t\t\t_LOGGER.Printf(\"Peer reponse %v \\n\", responseChannel)\n\t\t\t}\n\t\t}\n\n\t}\n\tif !foundChannel {\n\t\t_LOGGER.Printf(\"Going to join to channel %s \\n\", sdkClient.ChannelID)\n\t\terr := admin.JoinChannel(sdkClient.Client, sdkClient.AdminUser, sdkClient.Channel)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"JoinChannel returned error: %v\", err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *SwitchTicker) Channel() <-chan time.Time {\n\tfailCount := atomic.LoadInt64(&c.failCount)\n\tif failCount > c.threshold {\n\t\treturn c.fastTicker.C\n\t}\n\treturn c.slowTicker.C\n}", "func (_TokensNetwork *TokensNetworkSession) GetChannelInfo(token common.Address, participant1 common.Address, participant2 common.Address) ([32]byte, uint64, uint64, uint8, uint64, error) {\n\treturn _TokensNetwork.Contract.GetChannelInfo(&_TokensNetwork.CallOpts, token, participant1, participant2)\n}", "func GetOffers(stopchan chan struct{}) bool {\n\tutil.Info.Println(\"GetOffers started\")\n\tl := len(linkBridges.unconnected)\n\tgetOffers := make(chan dynamic.DHTGetReturn, l)\n\tfor _, link := range linkBridges.unconnected {\n\t\tif link.State == StateNew || link.State == StateWaitForAnswer {\n\t\t\tvar linkBridge = NewLinkBridge(link.LinkAccount, link.MyAccount, accounts)\n\t\t\tdynamicd.GetLinkRecord(linkBridge.LinkAccount, linkBridge.MyAccount, getOffers)\n\t\t\tutil.Info.Println(\"GetOffer for\", link.LinkAccount)\n\t\t} else {\n\t\t\tutil.Info.Println(\"GetOffers skipped\", link.LinkAccount)\n\t\t\tl--\n\t\t}\n\t}\n\tfor i := 0; i < l; i++ {\n\t\tselect {\n\t\tdefault:\n\t\t\toffer := <-getOffers\n\t\t\tlinkBridge := NewLinkBridge(offer.Sender, offer.Receiver, accounts)\n\t\t\tlink := linkBridges.unconnected[linkBridge.LinkID()]\n\t\t\tif link.Get.GetValue != offer.GetValue {\n\t\t\t\tif offer.GetSeq > link.Get.GetSeq {\n\t\t\t\t\tlink.Get = offer.DHTGetJSON\n\t\t\t\t\tif link.Get.NullRecord == \"true\" {\n\t\t\t\t\t\tutil.Info.Println(\"GetOffers null\", offer.Sender, offer.Receiver)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif link.Get.Minutes() <= OfferExpireMinutes && link.Get.GetValueSize > MinimumOfferValueLength {\n\t\t\t\t\t\tpc, err := ConnectToIceServices(config)\n\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\terr = util.DecodeObject(offer.GetValue, &link.Offer)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tutil.Info.Println(\"GetOffers error with DecodeObject\", link.LinkAccount, link.LinkID(), err)\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tlink.PeerConnection = pc\n\t\t\t\t\t\t\tlink.State = StateSendAnswer\n\t\t\t\t\t\t\tutil.Info.Println(\"GetOffers: Offer found for\", link.LinkAccount, link.LinkID())\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if link.Get.Minutes() > OfferExpireMinutes && link.Get.GetValueSize > MinimumOfferValueLength {\n\t\t\t\t\t\tutil.Info.Println(\"GetOffers: Stale offer found for\", link.LinkAccount, link.LinkID(), \"minutes\", link.Get.Minutes())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-stopchan:\n\t\t\tutil.Info.Println(\"GetOffers stopped\")\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (this *Protocol) askForPeers(peerId PeerId, num int) []PeerId {\n\targs := &ShareNewPeersArgs{}\n\tvar reply ShareNewPeersReply\n\targs.Me = this.GetMe()\n\targs.Num = num\n\tsuccess := this.call(peerId, \"ShareNewPeers\", args, &reply)\n\tif success {\n\t\treturn reply.SharedPeers\n\t}\n\treturn nil\n}", "func (q QueryFunc) Query(ctx context.Context, req Request) (tg.ChannelsChannelParticipantsClass, error) {\n\treturn q(ctx, req)\n}", "func QueryChannelClientState(\n\tclientCtx client.Context, portID, channelID string, prove bool,\n) (*types.QueryChannelClientStateResponse, error) {\n\n\tqueryClient := types.NewQueryClient(clientCtx)\n\treq := &types.QueryChannelClientStateRequest{\n\t\tPortId: portID,\n\t\tChannelId: channelID,\n\t}\n\n\tres, err := queryClient.ChannelClientState(context.Background(), req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif prove {\n\t\tclientStateRes, err := clientutils.QueryClientStateABCI(clientCtx, res.IdentifiedClientState.ClientId)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// use client state returned from ABCI query in case query height differs\n\t\tidentifiedClientState := clienttypes.IdentifiedClientState{\n\t\t\tClientId: res.IdentifiedClientState.ClientId,\n\t\t\tClientState: clientStateRes.ClientState,\n\t\t}\n\t\tres = types.NewQueryChannelClientStateResponse(identifiedClientState, clientStateRes.Proof, clientStateRes.ProofHeight)\n\t}\n\n\treturn res, nil\n}", "func (c *ConnectionMock) Channels() []string {\n\targs := c.Called()\n\treturn args.Get(0).([]string)\n}", "func (tsd *Demuxer) Where(tester PacketTester) PacketChannel {\n\tchannel := make(chan *Packet)\n\ttsd.registeredChannels = append(tsd.registeredChannels, conditionalChannel{tester, channel})\n\treturn channel\n}", "func Dial(addr *net.UDPAddr) (c *CurveCPConn, err error) {\n\tc = new(CurveCPConn)\n\tc.client = new(curveCPClient)\n\t\n\tc.ephPublicKey, c.ephPrivateKey, err = box.GenerateKey(rand.Reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// TODO: fetch server and client long-term keys\n\tvar sPublicKey [32]byte\n\tvar cPrivateKey [32]byte\n\t\n\tbox.Precompute(&c.client.sharedHelloKey, &sPublicKey, c.ephPrivateKey)\n\tbox.Precompute(&c.client.sharedVouchKey, &sPublicKey, &cPrivateKey)\n\t\n\tnonceInt, err := rand.Int(rand.Reader, big.NewInt(1<<48)) // start incrementing at random [0,2^48)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.nonce = nonceInt.Int64()\n\t\n\tc.conn, err = net.DialUDP(\"udp\", nil, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.sendHello()\n\tdeadline := 1000 // TODO: add to connection struct\n\tconnectionTimeout := time.NewTimer(min(deadline, 60 * time.Second))\n\n\tcookies := make(chan bool)\n\tgo c.cookieReceiver(cookies)\n\t\n\tfor {\n\t\tselect {\n\t\tcase <-cookies:\n\t\t\tbreak\n\t\tcase <-time.After(time.Second): // repeat Hello; TODO: fuzz + backoff\n\t\t\tc.sendHello()\n\t\tcase <-connectionTimeout.C:\n\t\t\treturn nil, ConnectionTimeoutError\n\t\t}\n\t}\n\n\tgo c.clientReactor()\n\n\treturn c, nil\n}", "func (k *ChannelKeeper) Confirm() <-chan amqp.Confirmation {\n\treturn k.confirmCh\n}", "func getChannel(client fab.Resource, channelID string) (fab.Channel, error) {\n\n\tchannel, err := client.NewChannel(channelID)\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"NewChannel failed\")\n\t}\n\n\tchCfg, err := client.Config().ChannelConfig(channel.Name())\n\tif err != nil || chCfg == nil {\n\t\treturn nil, errors.Errorf(\"reading channel config failed: %s\", err)\n\t}\n\n\tchOrderers, err := client.Config().ChannelOrderers(channel.Name())\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"reading channel orderers failed\")\n\t}\n\n\tfor _, ordererCfg := range chOrderers {\n\n\t\torderer, err := orderer.New(client.Config(), orderer.FromOrdererConfig(&ordererCfg))\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithMessage(err, \"creating orderer failed\")\n\t\t}\n\t\terr = channel.AddOrderer(orderer)\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithMessage(err, \"adding orderer failed\")\n\t\t}\n\t}\n\n\treturn channel, nil\n}", "func (cm *ConnectionManager) openAndDeposit(partner common.Address, fundingAmount *big.Int) error {\n\t_, err := cm.api.Open(cm.tokenAddress, partner, cm.raiden.Config.SettleTimeout, cm.raiden.Config.RevealTimeout)\n\tif err != nil {\n\t\treturn err\n\t}\n\tch, err := cm.raiden.db.GetChannel(cm.tokenAddress, partner)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif ch == nil {\n\t\terr = fmt.Errorf(\"Opening new channel failed; channel already opened, but partner not in channelgraph ,partner=%s,tokenaddress=%s\", utils.APex(partner), utils.APex(cm.tokenAddress))\n\t\tlog.Error(err.Error())\n\t\treturn err\n\t}\n\t_, err = cm.api.Deposit(cm.tokenAddress, partner, fundingAmount, params.DefaultPollTimeout)\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t}\n\treturn err\n}", "func (s *SlackService) GetChannels() []Channel {\n\tvar chans []Channel\n\n\t// Channel\n\tslackChans, err := s.Client.GetChannels(true)\n\tif err != nil {\n\t\tchans = append(chans, Channel{})\n\t}\n\tfor _, chn := range slackChans {\n // fmt.Println(chn.Name)\n if chn.Name == \"time\" {\n s.SlackChannels = append(s.SlackChannels, chn)\n chans = append(chans, Channel{chn.ID, chn.Name, chn.Topic.Value})\n }\n\t}\n\n // Just return after finding a specific channel\n s.Channels = chans\n return chans\n\n // Uncomment this to see all the channels\n // os.Exit(1)\n\n\t// Groups\n\tslackGroups, err := s.Client.GetGroups(true)\n\tif err != nil {\n\t\tchans = append(chans, Channel{})\n\t}\n\tfor _, grp := range slackGroups {\n\t\ts.SlackChannels = append(s.SlackChannels, grp)\n\t\tchans = append(chans, Channel{grp.ID, grp.Name, grp.Topic.Value})\n\t}\n\n\t// IM\n\tslackIM, err := s.Client.GetIMChannels()\n\tif err != nil {\n\t\tchans = append(chans, Channel{})\n\t}\n\tfor _, im := range slackIM {\n\n\t\t// Uncover name, when we can't uncover name for\n\t\t// IM channel this is then probably a deleted\n\t\t// user, because we wont add deleted users\n\t\t// to the UserCache, so we skip it\n\t\tname, ok := s.UserCache[im.User]\n\t\tif ok {\n\t\t\tchans = append(chans, Channel{im.ID, name, \"\"})\n\t\t\ts.SlackChannels = append(s.SlackChannels, im)\n\t\t}\n\t}\n\n\ts.Channels = chans\n\n\treturn chans\n}", "func (d *WSDialer) Dial() (mproto.Connection, error) {\n\tconn, _, err := websocket.DefaultDialer.Dial(d.url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnickCommand := proto.NickCommand{\n\t\tName: \"MaiMai.v3\",\n\t}\n\tnickPayload, err := json.Marshal(nickCommand)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := conn.WriteJSON(&proto.Packet{\n\t\tType: proto.NickType,\n\t\tData: nickPayload,\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &WSConnection{\n\t\tctx: d.ctx.Fork(),\n\t\tconn: conn,\n\t}, nil\n}", "func main() {\n\tch1 := make(chan int)\n\tch2 := make(chan int)\n\tgo func() {\n\t\ttime.Sleep(5 * time.Second)\n\t\tfor i := 0; i < 4; i++ {\n\t\t\tch1 <- i\n\t\t}\n\t\tclose(ch1)\n\t}()\n\tgo func() {\n\t\tfor i := 10; i < 13; i++ {\n\t\t\tch2 <- i\n\t\t}\n\t\tclose(ch2)\n\t}()\n\tfor n := range ch1 {\n\t\tfmt.Println(\"From channel 1\", n)\n\t}\n\tfor m := range ch2 {\n\t\tfmt.Println(\"From channel 2\", m)\n\t}\n}", "func (l *loopOutSwapSuggestion) channels() []lnwire.ShortChannelID {\n\tchannels := make(\n\t\t[]lnwire.ShortChannelID, len(l.OutRequest.OutgoingChanSet),\n\t)\n\n\tfor i, id := range l.OutRequest.OutgoingChanSet {\n\t\tchannels[i] = lnwire.NewShortChanIDFromInt(id)\n\t}\n\n\treturn channels\n}", "func (n *Notifier) NotifyChannels() {\n\tif int(time.Now().Weekday()) == 6 || int(time.Now().Weekday()) == 0 {\n\t\treturn\n\t}\n\tchannels, err := n.db.GetChannels()\n\tif err != nil {\n\t\tlogrus.Errorf(\"notifier: ListAllStandupTime failed: %v\\n\", err)\n\t\treturn\n\t}\n\t// For each standup time, if standup time is now, start reminder\n\tfor _, channel := range channels {\n\t\tif channel.StandupTime == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tstandupTime := time.Unix(channel.StandupTime, 0)\n\t\twarningTime := time.Unix(channel.StandupTime-n.conf.ReminderTime*60, 0)\n\t\tif time.Now().Hour() == warningTime.Hour() && time.Now().Minute() == warningTime.Minute() {\n\t\t\tn.SendWarning(channel.ChannelID)\n\t\t}\n\t\tif time.Now().Hour() == standupTime.Hour() && time.Now().Minute() == standupTime.Minute() {\n\t\t\tgo n.SendChannelNotification(channel.ChannelID)\n\t\t}\n\t}\n}", "func (b *hereNowBuilder) Channels(ch []string) *hereNowBuilder {\n\tb.opts.Channels = ch\n\n\treturn b\n}", "func SearchChannels(q string) []myyoutube.Channel {\n\tservice := myyoutube.NewYoutubeService()\n\tcall := service.Search.List(\"snippet\").\n\t\tType(\"channel\").\n\t\tQ(q).\n\t\tOrder(\"relevance\").\n\t\tMaxResults(12)\n\tresponse, err := call.Do()\n\tif err != nil {\n\t\tlog.Fatalf(\"%v\", err)\n\t}\n\n\tchannels := []myyoutube.Channel{}\n\tfor _, item := range response.Items {\n\t\tchannelID := item.Snippet.ChannelId\n\t\ttitle := item.Snippet.Title\n\t\tdescription := item.Snippet.Description\n\t\tthumbnailURL := item.Snippet.Thumbnails.High.Url\n\n\t\tchannel := myyoutube.Channel{\n\t\t\tChannelID: channelID,\n\t\t\tName: title,\n\t\t\tDescription: description,\n\t\t\tThumbnailURL: thumbnailURL,\n\t\t}\n\t\tchannel.SetDetailInfo()\n\t\tchannel.ExistsChannel = channel.Exists()\n\n\t\tchannels = append(channels, channel)\n\t}\n\tlog.Printf(\"Get %v channels\\n\", len(channels))\n\n\treturn channels\n}", "func distributeFood() {\n\n\tfor {\n\t\tselect {\n\t\tcase food := <-FoodChan:\n\t\t\tif pickCook(food) == false {\n\t\t\t\tFoodChan <- food\n\t\t\t}\n\t\tdefault:\n\t\t}\n\t}\n}", "func (s *TestSuite) TestGetChannels(c *C) {\n\tsvc := s.serviceGroup.UserService\n\tteam, _ := s.serviceGroup.TeamService.SaveTeam(msgcore.NewTeam(1, \"org\", \"team\"))\n\n\tusers := make([]*msgcore.User, 0, 0)\n\tchannels := make([]*msgcore.Channel, 0, 0)\n\tfor i := 1; i <= 10; i++ {\n\t\tcreator := msgcore.NewUser(int64(i), fmt.Sprintf(\"%d\", i), team)\n\t\t_ = svc.SaveUser(&msgcore.SaveUserRequest{nil, creator, false})\n\t\tusers = append(users, creator)\n\t\tchannel := msgcore.NewChannel(team, creator, int64(i), fmt.Sprintf(\"channel%d\", i))\n\t\tchannel, err := s.serviceGroup.ChannelService.CreateChannel(&msgcore.CreateChannelRequest{channel, nil, true})\n\t\tif err != nil {\n\t\t\tlog.Println(\"CreateChannel Error: \", err)\n\t\t}\n\t\tchannels = append(channels, channel)\n\t}\n\n\tfor i := 1; i <= 10; i++ {\n\t\t// add the creator and 4 next users as members\n\t\tmembers := make([]string, 0, 4)\n\t\tfor j := 0; j < 5; j++ {\n\t\t\tmembers = append(members, users[(i+j-1)%len(users)].Username)\n\t\t}\n\t\ts.serviceGroup.ChannelService.AddChannelMembers(&msgcore.InviteMembersRequest{nil, channels[i-1], members})\n\t}\n\n\t// Test owner filter\n\trequest := &msgcore.GetChannelsRequest{team, users[0], \"\", nil, true}\n\tresult, _ := s.serviceGroup.ChannelService.GetChannels(request)\n\tc.Assert(len(result.Channels), Equals, 1)\n\tc.Assert(len(result.Members), Equals, 1)\n\t// ensure all users have the same creator\n\tc.Assert(result.Channels[0].Creator.Id, Equals, users[0].Id)\n\tc.Assert(len(result.Members[0]), Equals, 5)\n\n\t// Test participants\n\trequest = &msgcore.GetChannelsRequest{team, nil, \"\", []*msgcore.User{users[1], users[2]}, true}\n\tresult, _ = s.serviceGroup.ChannelService.GetChannels(request)\n\tc.Assert(len(result.Channels), Equals, 4)\n\tfor i := 0; i < 4; i++ {\n\t\tc.Assert(len(result.Members[i]), Equals, 5)\n\t}\n}", "func (host *DinnerHost) Init(tableCount, maxParallel, maxDinner int) {\n\thost.phiData = make(map[string]*philosopherData)\n\thost.requestChannel = make(chan string)\n\thost.finishChannel = make(chan string)\n\thost.maxParallel = maxParallel\n\tif host.maxParallel > tableCount {\n\t\thost.maxParallel = tableCount\n\t}\n\thost.maxDinner = maxDinner\n\thost.currentlyEating = 0\n\thost.tableCount = tableCount\n\thost.chopsticksFree = make([]bool, 5)\n\tfor i := range host.chopsticksFree {\n\t\thost.chopsticksFree[i] = true\n\t}\n\trand.Seed(time.Now().Unix())\n\thost.freeSeats = rand.Perm(tableCount)\n}", "func (r *reconciler) getChannel(ctx context.Context, b *v1alpha1.Broker, ls labels.Selector) (*v1alpha1.Channel, error) {\n\tlist := &v1alpha1.ChannelList{}\n\topts := &runtimeclient.ListOptions{\n\t\tNamespace: b.Namespace,\n\t\tLabelSelector: ls,\n\t\t// Set Raw because if we need to get more than one page, then we will put the continue token\n\t\t// into opts.Raw.Continue.\n\t\tRaw: &metav1.ListOptions{},\n\t}\n\n\terr := r.client.List(ctx, opts, list)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, c := range list.Items {\n\t\tif metav1.IsControlledBy(&c, b) {\n\t\t\treturn &c, nil\n\t\t}\n\t}\n\n\treturn nil, k8serrors.NewNotFound(schema.GroupResource{}, \"\")\n}", "func GetAllOffers(stopchan chan struct{}, links dynamic.ActiveLinks, accounts []dynamic.Account) bool {\n\tgetOffers := make(chan dynamic.DHTGetReturn, len(links.Links))\n\tfor _, link := range links.Links {\n\t\tvar linkBridge = NewBridge(link, accounts)\n\t\tdynamicd.GetLinkRecord(linkBridge.LinkAccount, linkBridge.MyAccount, getOffers)\n\t}\n\tutil.Info.Println(\"GetAllOffers started\")\n\tfor i := 0; i < len(links.Links); i++ {\n\t\tselect {\n\t\tdefault:\n\t\t\toffer := <-getOffers\n\t\t\tlinkBridge := NewLinkBridge(offer.Sender, offer.Receiver, accounts)\n\t\t\tlinkBridge.Get = offer.DHTGetJSON\n\t\t\tlinkBridge.SessionID = i\n\t\t\tif offer.DHTGetJSON.NullRecord == \"true\" {\n\t\t\t\tutil.Info.Println(\"GetAllOffers null offer found for\", offer.Sender, offer.Receiver)\n\t\t\t\tlinkBridges.unconnected[linkBridge.LinkID()] = &linkBridge\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif offer.GetValueSize > MinimumOfferValueLength && offer.Minutes() <= OfferExpireMinutes {\n\t\t\t\tpc, err := ConnectToIceServices(config)\n\t\t\t\tif err == nil {\n\t\t\t\t\terr = util.DecodeObject(offer.GetValue, &linkBridge.Offer)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tutil.Info.Println(\"GetAllOffers error with DecodeObject\", linkBridge.LinkAccount, linkBridge.LinkID(), err)\n\t\t\t\t\t\tlinkBridges.unconnected[linkBridge.LinkID()] = &linkBridge\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tlinkBridge.PeerConnection = pc\n\t\t\t\t\tlinkBridge.State = StateSendAnswer\n\t\t\t\t\tutil.Info.Println(\"Offer found for\", linkBridge.LinkAccount, linkBridge.LinkID())\n\t\t\t\t\tlinkBridges.unconnected[linkBridge.LinkID()] = &linkBridge\n\t\t\t\t} else {\n\t\t\t\t\tlinkBridges.unconnected[linkBridge.LinkID()] = &linkBridge\n\t\t\t\t}\n\t\t\t} else if offer.Minutes() > OfferExpireMinutes && offer.GetValueSize > MinimumOfferValueLength {\n\t\t\t\tutil.Info.Println(\"Stale Offer found for\", linkBridge.LinkAccount, linkBridge.LinkID(), \"minutes\", offer.Minutes())\n\t\t\t\tlinkBridges.unconnected[linkBridge.LinkID()] = &linkBridge\n\t\t\t} else {\n\t\t\t\tutil.Info.Println(\"Offer NOT found for\", linkBridge.LinkAccount, linkBridge.LinkID())\n\t\t\t\tlinkBridges.unconnected[linkBridge.LinkID()] = &linkBridge\n\t\t\t}\n\t\tcase <-stopchan:\n\t\t\tutil.Info.Println(\"GetAllOffers stopped\")\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (t *targetrunner) broadcastNeighbors(path string, query url.Values, method string, body []byte,\n\tsmap *Smap, timeout ...time.Duration) chan callResult {\n\n\tif len(smap.Tmap) < 2 {\n\t\t// no neighbor, returns empty channel, so caller doesnt have to check channel is nil\n\t\tch := make(chan callResult)\n\t\tclose(ch)\n\t\treturn ch\n\t}\n\n\tvar servers []*daemonInfo\n\tfor _, s := range smap.Tmap {\n\t\tif s.DaemonID != t.si.DaemonID {\n\t\t\tservers = append(servers, s)\n\t\t}\n\t}\n\n\treturn t.broadcast(path, query, method, body, servers, timeout...)\n}", "func (c *Client) join(ctx context.Context, channel string) (*channel, error) {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tchannels, err := c.channelsList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, ch := range channels {\n\t\tif ch.Name() == channel || ch.ID == channel {\n\t\t\tc.channels[ch.ID] = ch // use ID b/c other incoming messages will do so\n\t\t\treturn ch, nil\n\t\t}\n\t}\n\treturn nil, errors.New(\"channel not found\")\n}", "func (vs *Viewers) Channels() []string {\n\tvs.lock.Lock()\n\tdefer vs.lock.Unlock()\n\tdefer util.TimeElapsed(time.Now(), \"Channels\")\n\n\tchannels := make([]string, 0)\n\tfor channel := range vs.views {\n\t\tchannels = append(channels, channel)\n\t}\n\treturn channels\n}", "func pollConn(s *discordgo.Session) {\n\tc := config.Get()\n\tfor {\n\t\ttime.Sleep(10 * time.Second)\n\t\tfound := false\n\t\tguilds, err := s.UserGuilds()\n\t\tfor _, g := range guilds {\n\t\t\tif g.ID == c.Guild {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\tlog.Warningf(\"Could not find membership matching guild ID. %s\", c.Guild)\n\t\t\tlog.Warningf(\"Maybe I need a new invite? Using code %s\", c.InviteID)\n\t\t\tif s.Token != \"\" {\n\t\t\t\ts.Close()\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlog.Warningf(\"Could not fetch guild info %v\", err)\n\t\t\tif s.Token != \"\" {\n\t\t\t\ts.Close()\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n}", "func (s *SocketModeAdapter) GetPresentChannels() ([]*adapter.ChannelInfo, error) {\n\tallChannels, _, err := s.client.GetConversations(&slack.GetConversationsParameters{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tchannels := make([]*adapter.ChannelInfo, 0)\n\tfor _, ch := range allChannels {\n\t\t// Is this user in this channel?\n\t\tif ch.IsMember {\n\t\t\tchannels = append(channels, newChannelInfoFromSlackChannel(&ch))\n\t\t}\n\t}\n\n\treturn channels, nil\n}", "func (m *TeamItemRequestBuilder) IncomingChannels()(*i1e6cfda39bf71ff6c49bf501ccb56055e496f12dd4a459a4c9f832017b3ed495.IncomingChannelsRequestBuilder) {\n return i1e6cfda39bf71ff6c49bf501ccb56055e496f12dd4a459a4c9f832017b3ed495.NewIncomingChannelsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (c *connection) Channel() (amqpChannel, error) {\n\tch, err := c.conn.Channel()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := ch.Confirm(wait); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &channel{ch}, nil\n}", "func (ticker *PausableTicker) GetChannel() <-chan time.Time {\n\treturn ticker.channel\n}", "func ListenForQueries(queryChan <-chan Query, resultChan chan<- Result) {\n\n}", "func ChannelWorker(id int, channel chan domain.ChannelEl, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\n\tstart := utils.GetCurrentTime()\n\ttime.Sleep(time.Second)\n\tend := utils.GetCurrentTime()\n\tchannel <- domain.ChannelEl{ID: id, Time: end - start}\n}", "func clientDisconnected(authKey string,authExtra map[string]interface{}){\t\n\tv,ok := authExtra[\"client-type\"]\n\t\n\tif ok && (v == \"musicBox-v1\" || v == \"testClient-v1\"){\t\n\t\tlog.Print(\"Box Disconnected: \",authExtra)\n\t\t\n\t\tsetMusicBoxPlaying(authExtra[\"client-id\"].(string),OFFLINE)\n\t\t\n\t\t//Send message that device paused\n\t\tb,err := lookupMusicBox(authExtra[\"client-id\"].(string))\n\t\t\n\t\tif err == nil{\n\t\t\t//Create paused command\n\t\t\tmsg := map[string]interface{}{\n\t\t\t\t\"command\":\"boxDisconnected\",\n\t\t\t}\n\t\t\t\n\t\t\tserver.PublishEvent(baseURL+b.User+\"/\"+b.ID, msg)\n\t\t}\n\t}else{\n\t\tlog.Print(\"Client Disconnected: \",authKey)\n\t}\n\t\n}", "func (cm *ConnectionManager) WantsMoreChannels() bool {\n\t_, ok := cm.raiden.MessageHandler.blockedTokens[cm.tokenAddress]\n\tif ok {\n\t\treturn false\n\t}\n\treturn cm.fundsRemaining().Cmp(utils.BigInt0) > 0 && len(cm.openChannels()) < int(cm.initChannelTarget)\n}", "func (c *IrcBot) connected() irc.HandlerFunc {\n return func(conn *irc.Conn, line *irc.Line) {\n for _,channel := range c.channels {\n c.connection.Join(channel)\n }\n }\n}", "func (n *Notifier) NotifyChannels() {\n\tif int(time.Now().Weekday()) == 6 || int(time.Now().Weekday()) == 0 {\n\t\tlogrus.Info(\"It is Weekend!!! No standups!!!\")\n\t\treturn\n\t}\n\tstandupTimes, err := n.DB.ListAllStandupTime()\n\tif err != nil {\n\t\tlogrus.Errorf(\"notifier: ListAllStandupTime failed: %v\\n\", err)\n\t\treturn\n\t}\n\t// For each standup time, if standup time is now, start reminder\n\tfor _, st := range standupTimes {\n\t\tstandupTime := time.Unix(st.Time, 0)\n\t\twarningTime := time.Unix(st.Time-n.Config.ReminderTime*60, 0)\n\t\tif time.Now().Hour() == warningTime.Hour() && time.Now().Minute() == warningTime.Minute() {\n\t\t\tn.SendWarning(st.ChannelID)\n\t\t}\n\t\tif time.Now().Hour() == standupTime.Hour() && time.Now().Minute() == standupTime.Minute() {\n\t\t\tgo n.SendChannelNotification(st.ChannelID)\n\t\t}\n\t}\n}", "func AbandonCanceledChannels(matchedOrders map[order.Nonce][]*order.MatchedOrder,\n\tbatchTx *wire.MsgTx, wallet lndclient.WalletKitClient,\n\tbaseClient BaseClient, fetchOrder order.Fetcher) error {\n\n\t// Since we support partial matches, a given bid of ours could've been\n\t// matched with multiple asks, so we'll iterate through all those to\n\t// ensure we remove all channels that never made it to chain.\n\tctxb := context.Background()\n\ttxHash := batchTx.TxHash()\n\tfor ourOrderNonce, matchedOrders := range matchedOrders {\n\t\tourOrder, err := fetchOrder(ourOrderNonce)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// For each ask order that was matched with this bid, we'll\n\t\t// locate the channel outpoint then abandon it from lnd's\n\t\t// channel database.\n\t\tfor _, matchedOrder := range matchedOrders {\n\t\t\t_, idx, err := order.ChannelOutput(\n\t\t\t\tbatchTx, wallet, ourOrder, matchedOrder,\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error locating channel \"+\n\t\t\t\t\t\"outpoint: %v\", err)\n\t\t\t}\n\n\t\t\tchannelPoint := &lnrpc.ChannelPoint{\n\t\t\t\tOutputIndex: idx,\n\t\t\t\tFundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{\n\t\t\t\t\tFundingTxidBytes: txHash[:],\n\t\t\t\t},\n\t\t\t}\n\t\t\t_, err = baseClient.AbandonChannel(\n\t\t\t\tctxb, &lnrpc.AbandonChannelRequest{\n\t\t\t\t\tChannelPoint: channelPoint,\n\t\t\t\t\tPendingFundingShimOnly: true,\n\t\t\t\t},\n\t\t\t)\n\t\t\tconst notFoundErr = \"unable to find closed channel\"\n\t\t\tif err != nil {\n\t\t\t\t// If the channel was never created in the first\n\t\t\t\t// place, it might just not exist. Therefore we\n\t\t\t\t// ignore the \"not found\" error but fail on any\n\t\t\t\t// other error.\n\t\t\t\tif !strings.Contains(err.Error(), notFoundErr) {\n\t\t\t\t\tlog.Errorf(\"Unexpected error when \"+\n\t\t\t\t\t\t\"trying to clean up pending \"+\n\t\t\t\t\t\t\"channels: %v\", err)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tlog.Debugf(\"Cleaning up incomplete/replaced \"+\n\t\t\t\t\t\"pending channel in lnd was \"+\n\t\t\t\t\t\"unsuccessful for order=%v \"+\n\t\t\t\t\t\"(channel_point=%v:%d), assuming \"+\n\t\t\t\t\t\"timeout when funding: %v\",\n\t\t\t\t\tourOrderNonce.String(), txHash, idx,\n\t\t\t\t\terr)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (suite *KeeperTestSuite) TestQuerierChannelClientState() {\n\tpath := []string{types.SubModuleName, types.QueryChannelClientState}\n\n\tvar (\n\t\tclientID string\n\t\treq *types.QueryChannelClientStateRequest\n\t)\n\n\ttestCases := []struct {\n\t\tname string\n\t\tsetup func()\n\t\texpPass bool\n\t}{\n\t\t{\n\t\t\t\"channel not found\",\n\t\t\tfunc() {\n\t\t\t\tclientA, err := suite.coordinator.CreateClient(suite.chainA, suite.chainB, clientexported.Tendermint)\n\t\t\t\tsuite.Require().NoError(err)\n\n\t\t\t\tclientID = clientA\n\t\t\t\treq = types.NewQueryChannelClientStateRequest(\"doesnotexist\", \"doesnotexist\")\n\t\t\t},\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"connection for channel not found\",\n\t\t\tfunc() {\n\t\t\t\t// connection for channel is deleted from state\n\t\t\t\tclientA, _, _, _, channelA, _ := suite.coordinator.Setup(suite.chainA, suite.chainB)\n\n\t\t\t\tchannel := suite.chainA.GetChannel(channelA)\n\t\t\t\tchannel.ConnectionHops[0] = \"doesnotexist\"\n\n\t\t\t\t// set connection hops to wrong connection ID\n\t\t\t\tsuite.chainA.App.IBCKeeper.ChannelKeeper.SetChannel(suite.chainA.GetContext(), channelA.PortID, channelA.ID, channel)\n\n\t\t\t\tclientID = clientA\n\t\t\t\treq = types.NewQueryChannelClientStateRequest(channelA.PortID, channelA.ID)\n\n\t\t\t},\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"client state for channel's connection not found\",\n\t\t\tfunc() {\n\t\t\t\tclientA, _, connA, _, channelA, _ := suite.coordinator.Setup(suite.chainA, suite.chainB)\n\n\t\t\t\t// setting connection to empty results in wrong clientID used\n\t\t\t\tsuite.chainA.App.IBCKeeper.ConnectionKeeper.SetConnection(suite.chainA.GetContext(), connA.ID, connectiontypes.ConnectionEnd{})\n\n\t\t\t\tclientID = clientA\n\t\t\t\treq = types.NewQueryChannelClientStateRequest(channelA.PortID, channelA.ID)\n\t\t\t},\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"success\",\n\t\t\tfunc() {\n\t\t\t\tclientA, _, _, _, channelA, _ := suite.coordinator.Setup(suite.chainA, suite.chainB)\n\n\t\t\t\tclientID = clientA\n\t\t\t\treq = types.NewQueryChannelClientStateRequest(channelA.PortID, channelA.ID)\n\t\t\t},\n\t\t\ttrue,\n\t\t},\n\t}\n\n\tfor i, tc := range testCases {\n\t\tsuite.SetupTest() // reset\n\t\ttc.setup()\n\n\t\tdata, err := suite.chainA.App.AppCodec().MarshalJSON(req)\n\t\tsuite.Require().NoError(err)\n\n\t\tquery := abci.RequestQuery{\n\t\t\tPath: \"\",\n\t\t\tData: data,\n\t\t}\n\n\t\tclientState, found := suite.chainA.App.IBCKeeper.ClientKeeper.GetClientState(suite.chainA.GetContext(), clientID)\n\t\tbz, err := suite.chainA.Querier(suite.chainA.GetContext(), path, query)\n\n\t\tif tc.expPass {\n\t\t\t// set expected result\n\t\t\texpRes, merr := codec.MarshalJSONIndent(suite.chainA.App.AppCodec(), clientState)\n\t\t\tsuite.Require().NoError(merr)\n\t\t\tsuite.Require().True(found, \"test case %d failed: %s\", i, tc.name)\n\t\t\tsuite.Require().NoError(err, \"test case %d failed: %s\", i, tc.name)\n\t\t\tsuite.Require().Equal(string(expRes), string(bz), \"test case %d failed: %s\", i, tc.name)\n\t\t} else {\n\t\t\tsuite.Require().Error(err, \"test case %d passed: %s\", i, tc.name)\n\t\t\tsuite.Require().Nil(bz, \"test case %d passed: %s\", i, tc.name)\n\t\t}\n\t}\n}", "func Dial(rawurl string, confirmHeight int64, sPub string) (*Client, error) {\n\treturn DialContext(context.Background(), rawurl, confirmHeight, sPub)\n}", "func (suite *KeeperTestSuite) TestChanOpenConfirm() {\n\tvar (\n\t\tpath *ibctesting.Path\n\t\tchannelCap *capabilitytypes.Capability\n\t\theightDiff uint64\n\t)\n\ttestCases := []testCase{\n\t\t{\"success\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointA.ChanOpenAck()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\t\t}, true},\n\t\t{\"channel doesn't exist\", func() {}, false},\n\t\t{\"channel state is not TRYOPEN\", func() {\n\t\t\t// create fully open channels on both cahins\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\t\t}, false},\n\t\t{\"connection not found\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointA.ChanOpenAck()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\t// set the channel's connection hops to wrong connection ID\n\t\t\tchannel := path.EndpointB.GetChannel()\n\t\t\tchannel.ConnectionHops[0] = \"doesnotexist\"\n\t\t\tsuite.chainB.App.GetIBCKeeper().ChannelKeeper.SetChannel(suite.chainB.GetContext(), path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, channel)\n\t\t}, false},\n\t\t{\"connection is not OPEN\", func() {\n\t\t\tsuite.coordinator.SetupClients(path)\n\n\t\t\terr := path.EndpointB.ConnOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tsuite.chainB.CreateChannelCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\t\t}, false},\n\t\t{\"consensus state not found\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointA.ChanOpenAck()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\theightDiff = 3\n\t\t}, false},\n\t\t{\"channel verification failed\", func() {\n\t\t\t// chainA is INIT, chainB in TRYOPEN\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\t\t}, false},\n\t\t{\"channel capability not found\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointA.ChanOpenAck()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = capabilitytypes.NewCapability(6)\n\t\t}, false},\n\t}\n\n\tfor _, tc := range testCases {\n\t\ttc := tc\n\t\tsuite.Run(fmt.Sprintf(\"Case %s\", tc.msg), func() {\n\t\t\tsuite.SetupTest() // reset\n\t\t\theightDiff = 0 // must be explicitly changed\n\t\t\tpath = ibctesting.NewPath(suite.chainA, suite.chainB)\n\n\t\t\ttc.malleate()\n\n\t\t\tif path.EndpointB.ClientID != \"\" {\n\t\t\t\t// ensure client is up to date\n\t\t\t\terr := path.EndpointB.UpdateClient()\n\t\t\t\tsuite.Require().NoError(err)\n\n\t\t\t}\n\n\t\t\tchannelKey := host.ChannelKey(path.EndpointA.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\t\t\tproof, proofHeight := suite.chainA.QueryProof(channelKey)\n\n\t\t\terr := suite.chainB.App.GetIBCKeeper().ChannelKeeper.ChanOpenConfirm(\n\t\t\t\tsuite.chainB.GetContext(), path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID,\n\t\t\t\tchannelCap, proof, malleateHeight(proofHeight, heightDiff),\n\t\t\t)\n\n\t\t\tif tc.expPass {\n\t\t\t\tsuite.Require().NoError(err)\n\t\t\t} else {\n\t\t\t\tsuite.Require().Error(err)\n\t\t\t}\n\t\t})\n\t}\n}", "func (a *EtherApiService) GetEtherPortChannelByMoid(ctx context.Context, moid string) ApiGetEtherPortChannelByMoidRequest {\n\treturn ApiGetEtherPortChannelByMoidRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tmoid: moid,\n\t}\n}", "func (d *Dao) Channels(c context.Context, arg *model.ArgChannels) (res []*model.Channel, err error) {\n\trows, err := d.db.Query(c, _channelsSQL, arg.LastID, arg.Size)\n\tif err != nil {\n\t\tlog.Error(\"d.dao.Channels(%v) error(%v)\", arg, err)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\tres = make([]*model.Channel, 0, arg.Size)\n\tfor rows.Next() {\n\t\tt := &model.Channel{}\n\t\tif err = rows.Scan(&t.ID, &t.Rank, &t.TopRank, &t.Type, &t.Operator, &t.State, &t.Attr, &t.CTime, &t.MTime); err != nil {\n\t\t\tlog.Error(\"d.dao.Channels(%v) rows.Scan() error(%v)\", arg, err)\n\t\t\treturn\n\t\t}\n\t\tres = append(res, t)\n\t}\n\treturn\n}", "func (cm *ConnectionManager) Connect(funds *big.Int, initialChannelTarget int64, joinableFundsTarget float64) error {\n\tif funds.Cmp(utils.BigInt0) <= 0 {\n\t\treturn errors.New(\"connecting needs a positive value for `funds`\")\n\t}\n\t_, ok := cm.raiden.MessageHandler.blockedTokens[cm.tokenAddress]\n\tif ok { //first leave ,then connect to cm token network\n\t\tdelete(cm.raiden.MessageHandler.blockedTokens, cm.tokenAddress)\n\t}\n\tcm.initChannelTarget = initialChannelTarget\n\tcm.joinableFundsTarget = joinableFundsTarget\n\topenChannels := cm.openChannels()\n\tif len(openChannels) > 0 {\n\t\tlog.Debug(fmt.Sprintf(\"connect() called on an already joined token network tokenaddress=%s,openchannels=%d,sumdeposits=%d,funds=%d\", utils.APex(cm.tokenAddress), len(openChannels), cm.sumDeposits(), cm.funds))\n\t}\n\tchs, err := cm.raiden.db.GetChannelList(cm.tokenAddress, utils.EmptyAddress)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(chs) == 0 {\n\t\tlog.Debug(\"bootstrapping token network.\")\n\t\tcm.lock.Lock()\n\t\t_, err2 := cm.api.Open(cm.tokenAddress, cm.BootstrapAddr, cm.raiden.Config.SettleTimeout, cm.raiden.Config.RevealTimeout)\n\t\tif err2 != nil {\n\t\t\tlog.Error(fmt.Sprintf(\"open channel between %s and %s error:%s\", utils.APex(cm.tokenAddress), utils.APex(cm.BootstrapAddr), err2))\n\t\t}\n\t\tcm.lock.Unlock()\n\t}\n\tcm.lock.Lock()\n\tcm.funds = funds\n\terr = cm.addNewPartners()\n\tcm.lock.Unlock()\n\treturn err\n}", "func (r *HistoryRouter) GetChannels() (chan<- Trade, <-chan HistoryUpdMsg) {\n\tr.RLock()\n\tdefer r.RUnlock()\n\n\treturn r.tradeIn, r.tradeOut\n}", "func (s *sessionManager) manageChannels() {\n\tfor {\n\t\tselect {\n\t\tcase cID := <-s.exit:\n\t\t\ts.doExit(cID)\n\t\t\tcontinue\n\t\tcase u := <-s.requeue:\n\t\t\ts.manageUpdate(u)\n\t\tdefault:\n\t\t}\n\t\tselect {\n\t\tcase cID := <-s.exit:\n\t\t\ts.doExit(cID)\n\t\t\tcontinue\n\t\tcase u := <-s.requeue:\n\t\t\ts.manageUpdate(u)\n\t\tcase u := <-s.update:\n\t\t\ts.manageUpdate(u)\n\t\t}\n\t}\n}", "func Deposit2ChannelTest(url string) {\n\tvar err error\n\tvar ChannelAddress string\n\tvar Status string\n\tvar Balance int32\n\tvar i int\n\tstart := time.Now()\n\tShowTime()\n\tlog.Println(\"Start Deposit2Channel\")\n\tBalance = 100\n\tlog.Println(\"Deposit to a not exist Channel\")\n\t//deposit to the channel that doesn't exist\n\tChannelAddress = \"0xffffffffffffffffffffffffffffffffffffffff\"\n\tStatus, err = Deposit2Channel(url, ChannelAddress, Balance)\n\tShowError(err)\n\t//display the details of the error\n\tShowDeposit2ChannelMsgDetail(Status)\n\tif Status == \"409 Conflict\" {\n\t\tlog.Println(\"Test pass:Deposit to a not exist Channel\")\n\t} else {\n\t\tlog.Println(\"Test failed:Deposit to a not exist Channel\")\n\t\tif HalfLife {\n\t\t\tlog.Fatal(\"HalfLife,exit\")\n\t\t}\n\t}\n\n\tlog.Println(\"Deposit to a opened Channel\")\n\t//query all channels of the node\n\tChannels, _, _ := QueryingNodeAllChannels(url)\n\t//deposit to the opened channel\n\tfor i = 0; i < len(Channels); i++ {\n\t\tif Channels[i].State == \"opened\" {\n\t\t\tChannelAddress = Channels[i].ChannelAddress\n\t\t\tStatus, err = Deposit2Channel(url, ChannelAddress, Balance)\n\t\t\tShowError(err)\n\t\t\t//display the details of the error\n\t\t\tShowDeposit2ChannelMsgDetail(Status)\n\t\t\tif Status == \"200 OK\" {\n\t\t\t\tfmt.Printf(\"Test pass:Deposit to a open Channel:%s\\n\", ChannelAddress)\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"Test failed:Deposit to a open Channel:%s\\n\", ChannelAddress)\n\t\t\t\tif HalfLife {\n\t\t\t\t\tlog.Fatal(\"HalfLife,exit\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tlog.Println(\"Deposit to a closed Channel\")\n\t// deposit the closed channel\n\tfor i = 0; i < len(Channels); i++ {\n\t\tif Channels[i].State == \"closed\" {\n\t\t\tChannelAddress = Channels[i].ChannelAddress\n\t\t\tStatus, err = Deposit2Channel(url, ChannelAddress, Balance)\n\t\t\tShowError(err)\n\t\t\t//display the details of the error\n\t\t\tShowDeposit2ChannelMsgDetail(Status)\n\t\t\tif Status == \"408 Request Timeout\" {\n\t\t\t\tfmt.Printf(\"Test pass:Deposit to a closed Channel:%s\\n\", ChannelAddress)\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"Test failed:Deposit to a closed Channel:%s\\n\", ChannelAddress)\n\t\t\t\tif HalfLife {\n\t\t\t\t\tlog.Fatal(\"HalfLife,exit\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tlog.Println(\"Deposit to a settled Channel\")\n\t// deposit the settled channel\n\tfor i = 0; i < len(Channels); i++ {\n\t\tif Channels[i].State == \"settled\" {\n\t\t\tChannelAddress = Channels[i].ChannelAddress\n\t\t\tStatus, err = Deposit2Channel(url, ChannelAddress, Balance)\n\t\t\tShowError(err)\n\t\t\t//display the details of the error\n\t\t\tShowDeposit2ChannelMsgDetail(Status)\n\t\t\tif Status == \"408 Request Timeout\" {\n\t\t\t\tfmt.Printf(\"Test pass:Deposit to a settled Channel:%s\\n\", ChannelAddress)\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"Test failed:Deposit to a settled Channel:%s\\n\", ChannelAddress)\n\t\t\t\tif HalfLife {\n\t\t\t\t\tlog.Fatal(\"HalfLife,exit\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tduration := time.Since(start)\n\tShowTime()\n\tlog.Println(\"time used:\", duration.Nanoseconds()/1000000, \" ms\")\n}", "func Tick(d Doner) <-chan struct{} {\n\tcq := make(chan struct{})\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-d.Done():\n\t\t\t\tclose(cq)\n\t\t\t\treturn\n\t\t\tcase cq <- struct{}{}:\n\t\t\t}\n\t\t}\n\t}()\n\treturn cq\n}", "func coin(srvChan chan string, channel, nick, hostname string, args []string) {\n\tmessage := \"NOTICE \" + channel + \" :\"\n\tif rand.Intn(2) == 0 {\n\t\tmessage += \"Heads.\"\n\t} else {\n\t\tmessage += \"Tails.\"\n\t}\n\tlog.Println(message)\n\tsrvChan <- message\n}", "func (r *Readiness) GetChannel() chan ReadinessMessage {\n\treturn r.channel\n}", "func (b *presenceBuilder) Channels(ch []string) *presenceBuilder {\n\tb.opts.channels = ch\n\n\treturn b\n}", "func (m *TeamItemRequestBuilder) AllChannels()(*ic08a09e622b3f3279dad3fb1dc0d9adf50886e9a08f52205e44e27965d46190a.AllChannelsRequestBuilder) {\n return ic08a09e622b3f3279dad3fb1dc0d9adf50886e9a08f52205e44e27965d46190a.NewAllChannelsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (p *LightningPool) Channel(ctx context.Context) (*amqp.Channel, error) {\n\tvar (\n\t\tk *amqp.Channel\n\t\terr error\n\t)\n\n\tp.mx.Lock()\n\tlast := len(p.set) - 1\n\tif last >= 0 {\n\t\tk = p.set[last]\n\t\tp.set = p.set[:last]\n\t}\n\tp.mx.Unlock()\n\n\t// If pool is empty create new channel\n\tif last < 0 {\n\t\tk, err = p.new(ctx)\n\t\tif err != nil {\n\t\t\treturn k, errors.Wrap(err, \"failed to create new\")\n\t\t}\n\t}\n\n\treturn k, nil\n}" ]
[ "0.5655222", "0.5343324", "0.53272516", "0.5199894", "0.508557", "0.5064791", "0.5031212", "0.5016926", "0.50126225", "0.49460906", "0.4912904", "0.4851788", "0.479862", "0.47982407", "0.47920403", "0.4678017", "0.46685356", "0.46649447", "0.46471307", "0.4627099", "0.4624417", "0.46154824", "0.46089506", "0.45498714", "0.45357025", "0.45235938", "0.45222357", "0.44952536", "0.4482369", "0.44819662", "0.44791046", "0.44722053", "0.44658405", "0.44638216", "0.44587064", "0.44580576", "0.44555423", "0.44537988", "0.4452674", "0.44507346", "0.4437647", "0.4430718", "0.44214907", "0.44170317", "0.44035652", "0.44021928", "0.44017413", "0.43873352", "0.43800902", "0.43753725", "0.43734902", "0.43708575", "0.43520606", "0.4348944", "0.4346814", "0.43429253", "0.43412468", "0.4329877", "0.43258616", "0.43202814", "0.4318257", "0.43165785", "0.43130702", "0.43121147", "0.43073297", "0.42930526", "0.4292528", "0.4285643", "0.42807296", "0.42794052", "0.42712662", "0.4265426", "0.42524728", "0.425202", "0.4248074", "0.4241122", "0.42407078", "0.42394662", "0.42341268", "0.4223061", "0.4220595", "0.42192933", "0.42113915", "0.42035198", "0.4203131", "0.4202277", "0.4199784", "0.41964015", "0.41897538", "0.4189024", "0.41658416", "0.41581306", "0.41574863", "0.4156804", "0.41324386", "0.41311738", "0.4130119", "0.41285565", "0.41281474", "0.41220585" ]
0.76768476
0
Add registers the philosopher at the host. It first checks if they can join (table full, already at the table), then creates a new philosopher data record and assigns a seat to the
func (host *DinnerHost) Add(newPhilosopher Philosopher) bool { newName := newPhilosopher.Name() fmt.Println(newName + " WANTS TO JOIN THE TABLE.") if len(host.phiData) >= host.tableCount { fmt.Println(newName + " CANNOT JOIN: THE TABLE IS FULL.") fmt.Println() return false } if host.phiData[newName] != nil { fmt.Println(newName + " CANNOT JOIN: ALREADY ON THE HOST'S LIST.") fmt.Println() return false } host.phiData[newName] = newPhilosopherDataPtr(newPhilosopher.RespChannel()) host.phiData[newName].TakeSeat(host.freeSeats[0]) host.freeSeats = host.freeSeats[1:] fmt.Println(newName + " JOINED THE TABLE.") fmt.Println() return true }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newPhilosopherDataPtr(respChannel chan string) *philosopherData {\n\tpd := new(philosopherData)\n\tpd.Init(respChannel)\n\treturn pd\n}", "func (s *session) addParty(p *party) error {\n\tif s.login != p.login {\n\t\treturn trace.AccessDenied(\n\t\t\t\"can't switch users from %v to %v for session %v\",\n\t\t\ts.login, p.login, s.id)\n\t}\n\n\ts.parties[p.id] = p\n\t// write last chunk (so the newly joined parties won't stare\n\t// at a blank screen)\n\tgetRecentWrite := func() []byte {\n\t\ts.writer.Lock()\n\t\tdefer s.writer.Unlock()\n\t\tdata := make([]byte, 0, 1024)\n\t\tfor i := range s.writer.recentWrites {\n\t\t\tdata = append(data, s.writer.recentWrites[i]...)\n\t\t}\n\t\treturn data\n\t}\n\tp.Write(getRecentWrite())\n\n\t// register this party as one of the session writers\n\t// (output will go to it)\n\ts.writer.addWriter(string(p.id), p, true)\n\tp.ctx.AddCloser(p)\n\ts.term.AddParty(1)\n\n\t// update session on the session server\n\tstorageUpdate := func(db rsession.Service) {\n\t\tdbSession, err := db.GetSession(s.getNamespace(), s.id)\n\t\tif err != nil {\n\t\t\ts.log.Errorf(\"Unable to get session %v: %v\", s.id, err)\n\t\t\treturn\n\t\t}\n\t\tdbSession.Parties = append(dbSession.Parties, rsession.Party{\n\t\t\tID: p.id,\n\t\t\tUser: p.user,\n\t\t\tServerID: p.serverID,\n\t\t\tRemoteAddr: p.site,\n\t\t\tLastActive: p.getLastActive(),\n\t\t})\n\t\tdb.UpdateSession(rsession.UpdateRequest{\n\t\t\tID: dbSession.ID,\n\t\t\tParties: &dbSession.Parties,\n\t\t\tNamespace: s.getNamespace(),\n\t\t})\n\t}\n\tif s.registry.srv.GetSessionServer() != nil {\n\t\tgo storageUpdate(s.registry.srv.GetSessionServer())\n\t}\n\n\ts.log.Infof(\"New party %v joined session: %v\", p.String(), s.id)\n\n\t// this goroutine keeps pumping party's input into the session\n\tgo func() {\n\t\tdefer s.term.AddParty(-1)\n\t\t_, err := io.Copy(s.term.PTY(), p)\n\t\tif err != nil {\n\t\t\ts.log.Errorf(\"Party member %v left session %v due an error: %v\", p.id, s.id, err)\n\t\t}\n\t\ts.log.Infof(\"Party member %v left session %v.\", p.id, s.id)\n\t}()\n\treturn nil\n}", "func (s *Storage) AddGopher(g adding.Gopher) error {\n\n\texistingGophers := s.GetAllGophers()\n\tfor _, e := range existingGophers {\n\t\tif g.Name == e.Name {\n\t\t\treturn adding.ErrDuplicate\n\t\t}\n\t}\n\n\tnewG := Gopher{\n\t\tID: len(existingGophers) + 1,\n\t\tCreated: time.Now(),\n\t\tName: g.Name,\n\t\tShortDesc: g.ShortDesc,\n\t}\n\n\tresource := strconv.Itoa(newG.ID)\n\tif err := s.db.Write(CollectionGopher, resource, newG); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *server) AddGopher(w http.ResponseWriter, r *http.Request) {\n\tdecoder := json.NewDecoder(r.Body)\n\n\tvar g addGopherRequest\n\terr := decoder.Decode(&g)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t_ = json.NewEncoder(w).Encode(\"Error unmarshalling request body\")\n\t\treturn\n\t}\n\tif err := s.adding.AddGopher(r.Context(), g.ID, g.Fixedacidity, g.Volatileacidity, g.Citricacid, g.Residualsugar, g.Chlorides, g.Freesulfurdioxide, g.Totalsulfurdioxide, g.Density, g.pH, g.Sulphates, g.Alcohol, g.Quality); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t_ = json.NewEncoder(w).Encode(\"Can't create a gopher\")\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusCreated)\n}", "func (d *Dao) Add(ctx context.Context, h *model.History) error {\n\tvalueByte, err := json.Marshal(h)\n\tif err != nil {\n\t\tlog.Error(\"json.Marshal(%v) error(%v)\", h, err)\n\t\treturn err\n\t}\n\tfValues := make(map[string][]byte)\n\tcolumn := d.column(h.Aid, h.TP)\n\tfValues[column] = valueByte\n\tkey := hashRowKey(h.Mid)\n\tvalues := map[string]map[string][]byte{family: fValues}\n\tctx, cancel := context.WithTimeout(ctx, time.Duration(d.conf.Info.WriteTimeout))\n\tdefer cancel()\n\tif _, err = d.info.PutStr(ctx, tableInfo, key, values); err != nil {\n\t\tlog.Error(\"info.PutStr error(%v)\", err)\n\t}\n\treturn nil\n}", "func (host *DinnerHost) Init(tableCount, maxParallel, maxDinner int) {\n\thost.phiData = make(map[string]*philosopherData)\n\thost.requestChannel = make(chan string)\n\thost.finishChannel = make(chan string)\n\thost.maxParallel = maxParallel\n\tif host.maxParallel > tableCount {\n\t\thost.maxParallel = tableCount\n\t}\n\thost.maxDinner = maxDinner\n\thost.currentlyEating = 0\n\thost.tableCount = tableCount\n\thost.chopsticksFree = make([]bool, 5)\n\tfor i := range host.chopsticksFree {\n\t\thost.chopsticksFree[i] = true\n\t}\n\trand.Seed(time.Now().Unix())\n\thost.freeSeats = rand.Perm(tableCount)\n}", "func addGod(db *gorm.DB) {\n\tphone, password, username, email, firstname, lastname := os.Getenv(\"GOD_PHONE\"),\n\t\tos.Getenv(\"GOD_PASSWORD\"),\n\t\tos.Getenv(\"GOD_USERNAME\"),\n\t\tos.Getenv(\"GOD_EMAIL\"),\n\t\tos.Getenv(\"GOD_FIRSTNAME\"),\n\t\tos.Getenv(\"GOD_LASTNAME\")\n\tpersonnelNum, err := strconv.Atoi(os.Getenv(\"GOD_PERSONNELNUM\"))\n\tif err != nil {\n\t\te.Logger.Error(\"GOD_PERSONNELNUM is not valid\")\n\t}\n\tlevel := domains.Level{\n\t\tTitle: \"کاربر\",\n\t\tColor: \"#ffffff\",\n\t}\n\trole := domains.Role{\n\t\tTitle: \"genesis\",\n\t\tPermissions: constants.Permissions,\n\t}\n\tuser := domains.User{\n\t\tModel: gorm.Model{\n\t\t\tID: 1,\n\t\t},\n\t\tPhone: phone,\n\t\tPassword: crypto.GenerateSha256(password),\n\t\tPersonnelNum: personnelNum,\n\t\tUsername: username,\n\t\tEmail: email,\n\t\tFirstName: firstname,\n\t\tLastName: lastname,\n\t\tRoles: []domains.Role{role},\n\t\tLevel: level,\n\t}\n\tif err := db.Where(\"phone = ?\", user.Phone).FirstOrCreate(&user).Error; err != nil {\n\t\te.Logger.Error(err)\n\t}\n\tvar profile domains.Profile\n\tprofile.UserID = user.Model.ID\n\tif err := db.FirstOrCreate(&profile).Error; err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func philosopherPonderanceGoroutine(id int) {\n\tfor {\n\t\tif rand.Float64() < PHILSWITCHCHANCE {\n\t\t\tphilIn[id] <- 2\n\t\t\tisEating := <- philOut[id] == 1\n\t\t\t// Switch: Thinking <-> Eating.\n\t\t\tif isEating {\n\t\t\t\t// Drop forks and return to positing on the nature of the universe.\n\t\t\t\tphilIn[id] <- 1\n\t\t\t} else {\n\t\t\t\t// Attempt to begin eating. Return to postulating, if missing fork.\n\t\t\t\tphilIn[id] <- 0\n\t\t\t}\n\t\t\t<- philOut[id]\n\t\t}\n\t}\n}", "func (b *Bus) add(p Passenger) {\n\tif b.passengers == nil {\n\t\tb.passengers = make(map[string]Passenger)\n\t}\n\tb.passengers[p.SSN] = p\n\tfmt.Printf(\"%s: boarded passenger with SSN %q\\n\", b.name, p.SSN)\n}", "func (h *Heartbeat) createTable() error {\n\ttableName := fmt.Sprintf(\"`%s`.`%s`\", h.schema, h.table)\n\tcreateTableStmt := fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %s (\n ts varchar(26) NOT NULL,\n server_id int(10) unsigned NOT NULL,\n PRIMARY KEY (server_id)\n)`, tableName)\n\n\t_, err := h.master.Exec(createTableStmt)\n\th.logger.Info(\"create heartbeat table\", zap.String(\"sql\", createTableStmt))\n\treturn terror.WithScope(terror.DBErrorAdapt(err, terror.ErrDBDriverError), terror.ScopeUpstream)\n}", "func (b *DatabaseConnection) AddHeart(h *hearts.Heart) error {\n\tsqlStatement := `\n\tINSERT INTO hearts (userid, current, max, rate)\n\tVALUES ($1, $2, $3,$4)`\n\t_, err := b.db.Exec(sqlStatement, h.UserID, h.Current, h.Max, h.Rate)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (hpc *HashPeersCache) add(hash types.Hash32, peer p2p.Peer) {\n\tpeers, exists := hpc.get(hash)\n\tif !exists {\n\t\thpc.Cache.Add(hash, HashPeers{peer: {}})\n\t\treturn\n\t}\n\n\tpeers[peer] = struct{}{}\n\thpc.Cache.Add(hash, peers)\n}", "func (s *server) addPeer(p *peer) {\n\tif p == nil {\n\t\treturn\n\t}\n\n\t// Ignore new peers if we're shutting down.\n\tif atomic.LoadInt32(&s.shutdown) != 0 {\n\t\tp.Disconnect()\n\t\treturn\n\t}\n\n\t// Track the new peer in our indexes so we can quickly look it up either\n\t// according to its public key, or it's peer ID.\n\t// TODO(roasbeef): pipe all requests through to the\n\t// queryHandler/peerManager\n\ts.peersMtx.Lock()\n\n\tpubStr := string(p.addr.IdentityKey.SerializeCompressed())\n\n\ts.peersByID[p.id] = p\n\ts.peersByPub[pubStr] = p\n\n\tif p.inbound {\n\t\ts.inboundPeers[pubStr] = p\n\t} else {\n\t\ts.outboundPeers[pubStr] = p\n\t}\n\n\ts.peersMtx.Unlock()\n\n\t// Launch a goroutine to watch for the termination of this peer so we\n\t// can ensure all resources are properly cleaned up and if need be\n\t// connections are re-established.\n\tgo s.peerTerminationWatcher(p)\n\n\t// Once the peer has been added to our indexes, send a message to the\n\t// channel router so we can synchronize our view of the channel graph\n\t// with this new peer.\n\tgo s.discoverSrv.SynchronizeNode(p.addr.IdentityKey)\n}", "func Add(s Spot) {\n\tpersist(s, add)\n}", "func (set *HostSet) AddHost(c renter.Contract) {\n\tlh := new(lockedHost)\n\t// lazy connection function\n\tvar lastSeen time.Time\n\tlh.reconnect = func() error {\n\t\tif lh.s != nil && !lh.s.IsClosed() {\n\t\t\t// if it hasn't been long since the last reconnect, assume the\n\t\t\t// connection is still open\n\t\t\tif time.Since(lastSeen) < 2*time.Minute {\n\t\t\t\tlastSeen = time.Now()\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t// otherwise, the connection *might* still be open; test by sending\n\t\t\t// a \"ping\" RPC\n\t\t\t//\n\t\t\t// NOTE: this is somewhat inefficient; it means we might incur an\n\t\t\t// extra roundtrip when we don't need to. Better would be for the\n\t\t\t// caller to handle the reconnection logic after calling whatever\n\t\t\t// RPC it wants to call; that way, we only do extra work if the host\n\t\t\t// has actually disconnected. But that feels too burdensome.\n\t\t\tif _, err := lh.s.Settings(); err == nil {\n\t\t\t\tlastSeen = time.Now()\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t// connection timed out, or some other error occurred; close our\n\t\t\t// end (just in case) and fallthrough to the reconnection logic\n\t\t\tlh.s.Close()\n\t\t}\n\t\thostIP, err := set.hkr.ResolveHostKey(c.HostKey)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not resolve host key: %w\", err)\n\t\t}\n\t\t// create and lock the session manually so that we can use our custom\n\t\t// lock timeout\n\t\tlh.s, err = proto.NewUnlockedSession(hostIP, c.HostKey, set.currentHeight)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := lh.s.Lock(c.ID, c.RenterKey, set.lockTimeout); err != nil {\n\t\t\tlh.s.Close()\n\t\t\treturn err\n\t\t} else if _, err := lh.s.Settings(); err != nil {\n\t\t\tlh.s.Close()\n\t\t\treturn err\n\t\t}\n\t\tset.onConnect(lh.s)\n\t\tlastSeen = time.Now()\n\t\treturn nil\n\t}\n\tset.sessions[c.HostKey] = lh\n}", "func (s *PeerStore) PutSeeder(infoHash bittorrent.InfoHash, p bittorrent.Peer) error {\n\tselect {\n\tcase <-s.closed:\n\t\tpanic(\"attempted to interact with closed store\")\n\tdefault:\n\t}\n\n\tpeer := makePeer(p, peerFlagSeeder, uint16(timecache.NowUnix()))\n\tih := infohash(infoHash)\n\n\ts.putPeer(ih, peer, p.IP.AddressFamily)\n\n\treturn nil\n}", "func (s *PeerStore) PutLeecher(infoHash bittorrent.InfoHash, p bittorrent.Peer) error {\n\tselect {\n\tcase <-s.closed:\n\t\tpanic(\"attempted to interact with closed store\")\n\tdefault:\n\t}\n\n\tpeer := makePeer(p, peerFlagLeecher, uint16(timecache.NowUnix()))\n\tih := infohash(infoHash)\n\n\ts.putPeer(ih, peer, p.IP.AddressFamily)\n\n\treturn nil\n}", "func (s *server) AddGopher(w http.ResponseWriter, r *http.Request) {\n\tdecoder := json.NewDecoder(r.Body)\n\n\tvar g addGopherRequest\n\terr := decoder.Decode(&g)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t_ = json.NewEncoder(w).Encode(\"Error unmarshalling request body\")\n\t\treturn\n\t}\n\tif err := s.adding.AddGopher(r.Context(), g.ID, g.Name, g.Image, g.Age); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t_ = json.NewEncoder(w).Encode(\"Can't create a gopher\")\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusCreated)\n}", "func (g *Group) introduce() {\n\tprotoMember := g.Member().ProtoMember()\n\tintroMsg := &IntroMessage{Member: protoMember}\n\tprotoIntroMsg, err := ptypes.MarshalAny(introMsg)\n\tif err != nil {\n\t\tlog.Fatal(\"Unable to create introduction message\")\n\t\treturn\n\t}\n\n\tmsg := &Message{\n\t\tMessageType: Message_ADD,\n\t\tAddr: g.Addr,\n\t\tDetails: protoIntroMsg,\n\t}\n\tfor _, coordinator := range g.coordinators {\n\t\tSendTCP(coordinator, msg)\n\t}\n\tg.broadcaster.Broadcast(msg)\n}", "func addHandshake(hs handshakes, c, r [16]byte) {\n\t/* Make sure there's a map for the challenge */\n\tif _, ok := hs[c]; !ok {\n\t\ths[c] = make(map[[16]byte]struct{})\n\t}\n\ths[c][r] = struct{}{}\n}", "func (philosopher *Philosopher) Eat(wg *sync.WaitGroup, host Host) {\n\tfor i := 0; i < 3; i++ {\n\t\thost.GiveMePermission()\n\t\tphilosopher.leftChopstick.Lock()\n\t\tphilosopher.rightChopstick.Lock()\n\t\tfmt.Printf(\"Starting to eat %d\\n\", philosopher.id)\n\t\ttime.Sleep(500 * time.Millisecond)\n\t\tfmt.Printf(\"Finishing eating %d. (time: %d)\\n\", philosopher.id, i+1)\n\t\tphilosopher.rightChopstick.Unlock()\n\t\tphilosopher.leftChopstick.Unlock()\n\t\thost.Done()\n\t}\n\twg.Done()\n}", "func (c *Cuckoo) addTable(growFactor float64) {\n\t//fmt.Printf(\"table: %d\\n\", c.Ntables)\n\tc.Ntables++\n\tbuckets := int(float64(c.Nbuckets) * growFactor)\n\tslots := c.Nslots\n\tc.Size += buckets * slots\n\tc.MaxElements = int(float64(c.Size) * c.MaxLoadFactor)\n\tt := new(Table)\n\tt.buckets = make([]Slots, buckets, buckets)\n\t// we should do this lazily\n\tfor b, _ := range t.buckets {\n\t\tif len(t.buckets[b]) == 0 {\n\t\t\tt.buckets[b] = makeSlots(t.buckets[b], slots)\n\t\t\tfor s, _ := range t.buckets[b] {\n\t\t\t\tt.buckets[b][s].val = c.emptyValue // ???\n\t\t\t}\n\t\t}\n\t}\n\tt.seed = uint64(len(c.tables) + 1)\n\tt.hfs = c.getHash(c.HashName, t.seed)\n\tt.Nbuckets = c.Nbuckets\n\tt.Nslots = c.Nslots\n\tt.Size = t.Nbuckets * t.Nslots\n\tt.MaxElements = int(float64(t.Size) * c.MaxLoadFactor)\n\tt.c = c\n\tc.tables = append(c.tables, t)\n\n\t// perhaps reset the stats ???\n}", "func (pr *Playroom) AddTable(name, gametype string, numseats int) (string, error) {\n\n\tt, err := NewTable(name, gametype, numseats)\n\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Table could not be created %s\", err)\n\t}\n\n\t(*pr).Tables = append((*pr).Tables, t)\n\t(*pr).TableMap[t.ID] = &t\n\n\t//start broadcasting table states from the moment it is created\n\tt.BroadcastTable()\n\n\treturn t.ID, nil\n}", "func (h *Heartbeat) AddTask(name string) error {\n\th.lock <- struct{}{} // send to chan, acquire the lock\n\tdefer func() {\n\t\t<-h.lock // read from the chan, release the lock\n\t}()\n\tif _, ok := h.slavesTs[name]; ok {\n\t\treturn terror.ErrSyncerUnitHeartbeatRecordExists.Generate(name)\n\t}\n\tif h.master == nil {\n\t\t// open DB\n\t\tdbCfg := h.cfg.masterCfg\n\t\tdbDSN := fmt.Sprintf(\"%s:%s@tcp(%s:%d)/?charset=utf8&interpolateParams=true&readTimeout=1m\", dbCfg.User, dbCfg.Password, dbCfg.Host, dbCfg.Port)\n\t\tmaster, err := sql.Open(\"mysql\", dbDSN)\n\t\tif err != nil {\n\t\t\treturn terror.WithScope(terror.DBErrorAdapt(err, terror.ErrDBDriverError), terror.ScopeUpstream)\n\t\t}\n\t\th.master = master\n\n\t\t// init table\n\t\terr = h.init()\n\t\tif err != nil {\n\t\t\th.master.Close()\n\t\t\th.master = nil\n\t\t\treturn terror.WithScope(terror.DBErrorAdapt(err, terror.ErrDBDriverError), terror.ScopeUpstream)\n\t\t}\n\n\t\t// run work\n\t\tif h.cancel != nil {\n\t\t\th.cancel()\n\t\t\th.cancel = nil\n\t\t\th.wg.Wait()\n\t\t}\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\th.cancel = cancel\n\n\t\th.wg.Add(1)\n\t\tgo func() {\n\t\t\tdefer h.wg.Done()\n\t\t\th.run(ctx)\n\t\t}()\n\t}\n\th.slavesTs[name] = 0 // init to 0\n\treturn nil\n}", "func (lm0 *level0Maintainer) addTable(h *hashMap, fd uint32) {\n\t// use bloom filter to record every key-value pair\n\tslots := h.Len()\n\tfilter := bbloom.New(float64(slots), 0.001)\n\t//var buf bytes.Buffer\n\t//buf.Grow(4)\n\tfor key := range h.concurrentMap {\n\t\tbuf := make([]byte, 4)\n\t\tbinary.BigEndian.PutUint32(buf, key)\n\t\tfilter.Add(buf)\n\t}\n\tlm0.Lock()\n\tdefer lm0.Unlock()\n\tlm0.filter[fd] = filter\n}", "func (_SimpleSavingsWallet *SimpleSavingsWalletSession) SetHeir(newHeir common.Address) (*types.Transaction, error) {\n\treturn _SimpleSavingsWallet.Contract.SetHeir(&_SimpleSavingsWallet.TransactOpts, newHeir)\n}", "func (_SimpleSavingsWallet *SimpleSavingsWalletTransactorSession) SetHeir(newHeir common.Address) (*types.Transaction, error) {\n\treturn _SimpleSavingsWallet.Contract.SetHeir(&_SimpleSavingsWallet.TransactOpts, newHeir)\n}", "func (hc *LegacyHealthCheckImpl) AddTablet(tablet *topodatapb.Tablet, name string) {\n\tctx, cancelFunc := context.WithCancel(context.Background())\n\tkey := TabletToMapKey(tablet)\n\thcc := &legacyHealthCheckConn{\n\t\tctx: ctx,\n\t\ttabletStats: LegacyTabletStats{\n\t\t\tKey: key,\n\t\t\tTablet: tablet,\n\t\t\tName: name,\n\t\t\tTarget: &querypb.Target{},\n\t\t\tUp: true,\n\t\t},\n\t}\n\thc.mu.Lock()\n\tif hc.addrToHealth == nil {\n\t\t// already closed.\n\t\thc.mu.Unlock()\n\t\tcancelFunc()\n\t\treturn\n\t}\n\tif th, ok := hc.addrToHealth[key]; ok {\n\t\t// Something already exists at this key.\n\t\t// If it's the same tablet, something is wrong.\n\t\tif topoproto.TabletAliasEqual(th.latestTabletStats.Tablet.Alias, tablet.Alias) {\n\t\t\thc.mu.Unlock()\n\t\t\tlog.Warningf(\"refusing to add duplicate tablet %v for %v: %+v\", name, tablet.Alias.Cell, tablet)\n\t\t\tcancelFunc()\n\t\t\treturn\n\t\t}\n\t\t// If it's a different tablet, then we trust this new tablet that claims\n\t\t// it has taken over the host:port that the old tablet used to be on.\n\t\t// Remove the old tablet to clear the way.\n\t\thc.deleteConnLocked(key, th)\n\t}\n\thc.addrToHealth[key] = &legacyTabletHealth{\n\t\tcancelFunc: cancelFunc,\n\t\tlatestTabletStats: hcc.tabletStats,\n\t}\n\thc.initialUpdatesWG.Add(1)\n\thc.connsWG.Add(1)\n\thc.mu.Unlock()\n\n\tgo hc.checkConn(hcc, name)\n}", "func (gs *GreetingService) Add(c endpoints.Context, g *Greeting) error {\n\tk := datastore.NewIncompleteKey(c, \"Greeting\", nil)\n\t_, err := datastore.Put(c, k, g)\n\treturn err\n}", "func (o *Shelf) InsertP(exec boil.Executor, whitelist ...string) {\n\tif err := o.Insert(exec, whitelist...); err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (hb *dsHeadBook) AddHeads(t thread.ID, p peer.ID, heads []cid.Cid) error {\n\ttxn, err := hb.ds.NewTransaction(false)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error when creating txn in datastore: %w\", err)\n\t}\n\tdefer txn.Discard()\n\tkey := dsLogKey(t, p, hbBase)\n\thr := pb.HeadBookRecord{}\n\tv, err := txn.Get(key)\n\tif err == nil {\n\t\tif err := proto.Unmarshal(v, &hr); err != nil {\n\t\t\treturn fmt.Errorf(\"error unmarshaling headbookrecord proto: %w\", err)\n\t\t}\n\t}\n\tif err != nil && err != ds.ErrNotFound {\n\t\treturn fmt.Errorf(\"error when getting current heads from log %v: %w\", key, err)\n\t}\n\n\tset := make(map[cid.Cid]struct{})\n\tfor i := range hr.Heads {\n\t\tset[hr.Heads[i].Cid.Cid] = struct{}{}\n\t}\n\tfor i := range heads {\n\t\tif !heads[i].Defined() {\n\t\t\tlog.Warnf(\"ignoring head %s is is undefined for %s\", heads[i], key)\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := set[heads[i]]; !ok {\n\t\t\tentry := &pb.HeadBookRecord_HeadEntry{Cid: &pb.ProtoCid{Cid: heads[i]}}\n\t\t\thr.Heads = append(hr.Heads, entry)\n\t\t}\n\t}\n\tdata, err := proto.Marshal(&hr)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error when marshaling headbookrecord proto for %v: %w\", key, err)\n\t}\n\tif err = txn.Put(key, data); err != nil {\n\t\treturn fmt.Errorf(\"error when saving new head record in datastore for %v: %v\", key, err)\n\t}\n\treturn txn.Commit()\n}", "func (pb *PhilosopherBase) Eat() {\n\n\tpb.State = philstate.Eating\n\tpb.StartEating()\n}", "func (controller *ServiceController) AddHost(host *Host) (err error){\n con, err := sql.Open(\"mymysql\", controller.connection_string)\n if err != nil {\n return err\n }\n defer con.Close()\n\n _, err = con.Exec(\"INSERT INTO host ( hostid, hostname, private_network, cores, memory, last_updated) VALUES (?, ?, ?, ?, ?, ?)\",\n host.HostId().String(), host.Hostname(), host.PrivateNetwork(), host.Cores(), host.Memory(), host.LastUpdated())\n return err\n}", "func (o *Node) AddHeartbeats(ctx context.Context, exec boil.ContextExecutor, insert bool, related ...*Heartbeat) error {\n\tvar err error\n\tfor _, rel := range related {\n\t\tif insert {\n\t\t\trel.NodeID = o.Address\n\t\t\tif err = rel.Insert(ctx, exec, boil.Infer()); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"failed to insert into foreign table\")\n\t\t\t}\n\t\t} else {\n\t\t\tupdateQuery := fmt.Sprintf(\n\t\t\t\t\"UPDATE \\\"heartbeat\\\" SET %s WHERE %s\",\n\t\t\t\tstrmangle.SetParamNames(\"\\\"\", \"\\\"\", 1, []string{\"node_id\"}),\n\t\t\t\tstrmangle.WhereClause(\"\\\"\", \"\\\"\", 2, heartbeatPrimaryKeyColumns),\n\t\t\t)\n\t\t\tvalues := []interface{}{o.Address, rel.Timestamp, rel.NodeID}\n\n\t\t\tif boil.IsDebug(ctx) {\n\t\t\t\twriter := boil.DebugWriterFrom(ctx)\n\t\t\t\tfmt.Fprintln(writer, updateQuery)\n\t\t\t\tfmt.Fprintln(writer, values)\n\t\t\t}\n\t\t\tif _, err = exec.ExecContext(ctx, updateQuery, values...); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"failed to update foreign table\")\n\t\t\t}\n\n\t\t\trel.NodeID = o.Address\n\t\t}\n\t}\n\n\tif o.R == nil {\n\t\to.R = &nodeR{\n\t\t\tHeartbeats: related,\n\t\t}\n\t} else {\n\t\to.R.Heartbeats = append(o.R.Heartbeats, related...)\n\t}\n\n\tfor _, rel := range related {\n\t\tif rel.R == nil {\n\t\t\trel.R = &heartbeatR{\n\t\t\t\tNode: o,\n\t\t\t}\n\t\t} else {\n\t\t\trel.R.Node = o\n\t\t}\n\t}\n\treturn nil\n}", "func Add(t *testing.T, tp *Tapestry) {\n\ttp.Lock()\n\tnode, _, err := tp.RandNode()\n\taddr := \"\"\n\tif err == nil {\n\t\t// if RandNode found, connect it to newNode\n\t\taddr = node.node.Address\n\t}\n\n\tn, err := Start(0, addr)\n\tif err != nil {\n\t\tOut.Printf(\"%v while trying to connect new node to address %v\", err, node.node.Address)\n\t\tt.Errorf(\"%v while trying to connect new node to address %v\", err, node.node.Address)\n\t} else {\n\t\tif node != nil {\n\t\t\tOut.Printf(\"node %v connected to node %v\", n.node.Id.String(), node.node.Id.String())\n\t\t} else {\n\t\t\tOut.Printf(\"node %v connected as new tapestry\", n.node.Id.String())\n\t\t}\n\n\t\t// add Node to list\n\t\ttp.Nodes = append(tp.Nodes, n)\n\t}\n\ttp.Unlock()\n}", "func (self *LSHforest) Add(key string, sig []uint64) {\n\t// split the signature into the right number of bands and then hash each one\n\thashedSignature := make([]string, self.L)\n\tfor i := 0; i < self.L; i++ {\n\t\thashedSignature[i] = self.hashedSignatureFunc(sig[i*self.K : (i+1)*self.K])\n\t}\n\t// iterate over each band in the LSH forest\n\tfor i := 0; i < len(self.InitialHashTables); i++ {\n\t\t// if the current band in the signature isn't in the current band in the LSH forest, add it\n\t\tif _, ok := self.InitialHashTables[i][hashedSignature[i]]; !ok {\n\t\t\tself.InitialHashTables[i][hashedSignature[i]] = make(graphKeys, 1)\n\t\t\tself.InitialHashTables[i][hashedSignature[i]][0] = key\n\t\t\t// if it is, append the current key (graph location) to this hashed signature band\n\t\t} else {\n\t\t\tself.InitialHashTables[i][hashedSignature[i]] = append(self.InitialHashTables[i][hashedSignature[i]], key)\n\t\t}\n\t}\n}", "func addEntry(t *testing.T, key string, keyspace uint) {\n\t// Insert at least one event to make sure db exists\n\tc, err := rd.Dial(\"tcp\", host)\n\tif err != nil {\n\t\tt.Fatal(\"connect\", err)\n\t}\n\t_, err = c.Do(\"SELECT\", keyspace)\n\tif err != nil {\n\t\tt.Fatal(\"select\", err)\n\t}\n\tdefer c.Close()\n\t_, err = c.Do(\"SET\", key, \"bar\", \"EX\", \"360\")\n\tif err != nil {\n\t\tt.Fatal(\"SET\", err)\n\t}\n}", "func (node *Node) gossip(db *DB) {\n\tgo node.updateHB()\n\tfor{\n\t\ttime.Sleep(Y * time.Second)\n\t\t//send table to neighbors\n\t\tneighbors := getRandNeighbors(node.id)\n\t\tdb.nodes[neighbors[0]].tableInput <- node.table\n\t\tdb.nodes[neighbors[1]].tableInput <- node.table\n\t\t//read tables sent from neighbors and update\n\t\tfor len(node.tableInput) > 0 {\n\t\t\tneighborTable := <- node.tableInput\n\t\t\tnode.table[node.id].mux.RLock()\n\t\t\tcurrTime := node.table[node.id].t \n\t\t\tnode.table[node.id].mux.RUnlock()\n\t\t\tfor i := 0; i < NUM_NODES; i++ {\n\t\t\t\tneighborTable[i].mux.RLock()\n\t\t\t\ttNeighbor := neighborTable[i].t\n\t\t\t\thbNeighbor := neighborTable[i].hb\n\t\t\t\tneighborTable[i].mux.RUnlock()\n\t\t\t\tnode.table[i].mux.Lock()\n\t\t\t\tif tNeighbor >= node.table[i].t && hbNeighbor > node.table[i].hb && node.table[i].hb != -1 {\n\t\t\t\t\tnode.table[i].t = currTime\n\t\t\t\t\tnode.table[i].hb = hbNeighbor\n\t\t\t\t}\n\t\t\t\tnode.table[i].mux.Unlock()\n\t\t\t}\n\t\t}\n\t\t//check for failures\n\t\tfor i := 0; i < NUM_NODES; i++ {\n\t\t\tnode.table[node.id].mux.RLock()\n\t\t\tcurrTime := node.table[node.id].t \n\t\t\tnode.table[node.id].mux.RUnlock()\n\t\t\tnode.table[i].mux.Lock()\n\t\t\tif currTime - node.table[i].t > t_fail && node.table[i].hb != -1 && node.table[i].t != 0 {\n\t\t\t\tnode.table[i].hb = -1\t\n\t\t\t}\n\t\t\tnode.table[i].mux.Unlock()\n\t\t}\n\t}\n}", "func AddOrUpdatePeer(p *Peer) error {\n\tjson, err := json.Marshal(p)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tidStr := p.ID.String()\n\n\tif err := context.Store.Put(peerPrefix+idStr, json, nil); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (pd *philosopherData) Init(respChannel chan string) {\n\tpd.respChannel = respChannel\n\tpd.eating = false\n\tpd.dinnersSpent = 0\n\tpd.seat = -1\n\tpd.leftChopstick = -1\n\tpd.rightChopstick = -1\n}", "func AddSnowflake(id string) *Snowflake {\n\tsnowflake := new(Snowflake)\n\tsnowflake.id = id\n\tsnowflake.clients = 0\n\tsnowflake.offerChannel = make(chan []byte)\n\tsnowflake.answerChannel = make(chan []byte)\n\theap.Push(snowflakes, snowflake)\n\tsnowflakeMap[id] = snowflake\n\treturn snowflake\n}", "func (_SimpleSavingsWallet *SimpleSavingsWalletTransactor) SetHeir(opts *bind.TransactOpts, newHeir common.Address) (*types.Transaction, error) {\n\treturn _SimpleSavingsWallet.contract.Transact(opts, \"setHeir\", newHeir)\n}", "func (h *HostsManager) add(ip, hostname string) error {\n\th.Lock()\n\tdefer h.Unlock()\n\th.hosts[ip] = hostname\n\tif err := OverwriteFile(h.path, h.String()); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (o *Shelf) InsertGP(whitelist ...string) {\n\tif err := o.Insert(boil.GetDB(), whitelist...); err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (kv *KV) Register(table []byte) error {\n\tif len(table) == 0 {\n\t\treturn gkv.ErrTableName\n\t}\n\tkv.table = table\n\t_, err := kv.db.Exec(fmt.Sprintf(`\nPRAGMA foreign_keys = FALSE;\nCREATE TABLE IF NOT EXISTS %s (\n\tid VARCHAR(34) NOT NULL,\n\tk TEXT NOT NULL,\n\tv TEXT NOT NULL,\n\tPRIMARY KEY (id)\n);\nPRAGMA foreign_keys = TRUE;\n`, string(table)))\n\treturn err\n}", "func (s *Streamer) addStreamer(ctx context.Context, strum *types.StreamerSetRequest) error {\r\n\t_, err := s.Data.ExecContext(ctx, \"select * from public.insertstreamer($1, $2)\", strum.StreamerOne, strum.StreamerTwo)\r\n\treturn err\r\n}", "func Insert(writer http.ResponseWriter, request *http.Request) {\n\tvar sp SanPham\n\tsp.TenSanPham = request.FormValue(\"TenSanPham\")\n\tvar Gia int\n\tfmt.Sscanf(request.FormValue(\"Gia\"), \"%d\", &Gia)\n\tsp.Gia = Gia\n\n\tcreate(sp)\n\tvar listSP []SanPham\n\tlistSP = getAll()\n\ttemplate_html.ExecuteTemplate(writer, \"Home\", listSP)\n}", "func addTank(gamestate *gamestate, client uint32, team string) {\n\tgamestate.Tanks[client] = initTank(team, gamestate.Terrain)\n\tgamestate.AliveTanks++\n}", "func MakePool(server string) {\n\n hivePool = make(chan *HiveConnection, 100)\n\n for i := 0; i < 100; i++ {\n // add empty values to the pool\n hivePool <- &HiveConnection{Server: server, Id: i}\n }\n\n}", "func AddPromoter(w http.ResponseWriter, r *http.Request) {\n\tctx := appengine.NewContext(r)\n\n\t// Create the Promoter object\n\tp1 := Promoter{\n\t\tName: r.FormValue(\"name\"),\n\t\tURL: r.FormValue(\"url\"),\n\t}\n\n\t// Add the promoter to the Datastore\n\tk, err := p1.Store(ctx)\n\tif err != nil {\n\t\tJSONError(&w, err.Error())\n\t\treturn\n\t}\n\n\tp1.DatastoreKey = *k\n\treturn\n}", "func (d *Service) TeamAddPoker(ctx context.Context, TeamID string, PokerID string) error {\n\t_, err := d.DB.ExecContext(ctx,\n\t\t`UPDATE thunderdome.poker SET team_id = $1 WHERE id = $2;`,\n\t\tTeamID,\n\t\tPokerID,\n\t)\n\n\tif err != nil {\n\t\td.Logger.Ctx(ctx).Error(\"team_poker add query error\", zap.Error(err))\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func CreateInitialEngineerProfile() {\n\tEngineers = make([]Engineer, 0)\n\tengineer := Engineer{\n\t\tUsername: \"masud\",\n\t\tFirstName: \"Masudur\",\n\t\tLastName: \"Rahman\",\n\t\tCity: \"Madaripur\",\n\t\tDivision: \"Dhaka\",\n\t\tPosition: \"Software Engineer\",\n\t}\n\tEngineers = append(Engineers, engineer)\n\n\tengineer = Engineer{\n\t\tUsername: \"fahim\",\n\t\tFirstName: \"Fahim\",\n\t\tLastName: \"Abrar\",\n\t\tCity: \"Chittagong\",\n\t\tDivision: \"Chittagong\",\n\t\tPosition: \"Software Engineer\",\n\t}\n\tEngineers = append(Engineers, engineer)\n\n\tengineer = Engineer{\n\t\tUsername: \"tahsin\",\n\t\tFirstName: \"Tahsin\",\n\t\tLastName: \"Rahman\",\n\t\tCity: \"Chittagong\",\n\t\tDivision: \"Chittagong\",\n\t\tPosition: \"Software Engineer\",\n\t}\n\tEngineers = append(Engineers, engineer)\n\n\tengineer = Engineer{\n\t\tUsername: \"jenny\",\n\t\tFirstName: \"Jannatul\",\n\t\tLastName: \"Ferdows\",\n\t\tCity: \"Chittagong\",\n\t\tDivision: \"Chittagong\",\n\t\tPosition: \"Software Engineer\",\n\t}\n\tEngineers = append(Engineers, engineer)\n\n\tif exist, _ := engine.IsTableExist(new(Engineer)); !exist {\n\t\tif err := engine.CreateTables(new(Engineer)); err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t}\n\n\tsession := engine.NewSession()\n\tdefer session.Close()\n\n\tif err := session.Begin(); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tfor _, user := range Engineers {\n\t\tif _, err := session.Insert(&user); err != nil {\n\t\t\tif err = session.Rollback(); err != nil {\n\t\t\t\tlog.Fatalln(err)\n\t\t\t}\n\t\t}\n\t}\n\tif err := session.Commit(); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tauthUser[\"masud\"] = \"pass\"\n\tauthUser[\"admin\"] = \"admin\"\n\n}", "func (store *StatisticStore) Add(statistic *Statistic) {\n\tif statistic.PeerId == \"\" {\n\t\tfmt.Printf(\"Unknown peerId\\n\")\n\t\tstatistic.PeerId = \"Unknown\"\n\t}\n\t_, ok := store.data[statistic.PeerId]\n\tif !ok {\n\t\tstore.data[statistic.PeerId] = statistic\n\t} else {\n\t\tstore.data[statistic.PeerId] = MergeTwoStatistics(store.data[statistic.PeerId], statistic)\n\t}\n}", "func (follower *Follower) Register(leaderHost string) (err error) {\n\tlog.Printf(\"Registring with Leader...\\n\")\n\tconn, err := net.Dial(\"tcp\", leaderHost)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmessage := &Message{\n\t\tAction: Message_REGISTER.Enum(),\n\n\t\tId: follower.id[:],\n\t\tHost: proto.String(follower.host),\n\t}\n\n\tdata, err := proto.Marshal(message)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := conn.Write(data); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (hpc *HashPeersCache) Add(hash types.Hash32, peer p2p.Peer) {\n\thpc.mu.Lock()\n\tdefer hpc.mu.Unlock()\n\n\thpc.add(hash, peer)\n}", "func (joinSession *JoinSession) pushMaliciousInfo(missedPeers []uint32) {\n\n\tjoinSession.mu.Lock()\n\tdefer joinSession.mu.Unlock()\n\tlog.Debug(\"Number malicious\", len(missedPeers))\n\tmalicious := &pb.MaliciousPeers{}\n\tfor _, Id := range missedPeers {\n\t\tjoinSession.removePeer(Id)\n\t}\n\tmalicious.PeerIds = missedPeers\n\n\tif len(joinSession.Peers) == 0 {\n\t\tlog.Info(\"All peers not sending data in time, join session terminates\")\n\t\treturn\n\t}\n\n\t// Re-generate the session id and peer id\n\tmalicious.SessionId = GenId()\n\tnewPeers := make(map[uint32]*PeerInfo, 0)\n\tlog.Debug(\"Remaining peers in join session: \", joinSession.Peers)\n\tif len(joinSession.Peers) > 0 {\n\t\tfor _, peer := range joinSession.Peers {\n\t\t\tmalicious.PeerId = GenId()\n\t\t\t// Update new id generated.\n\t\t\tpeer.ResetData(malicious.PeerId, malicious.SessionId)\n\t\t\tdata, _ := proto.Marshal(malicious)\n\t\t\tpeer.TmpData = data\n\t\t\tnewPeers[peer.Id] = peer\n\t\t}\n\t}\n\tjoinSession.Peers = newPeers\n\tjoinSession.JoinedTx = nil\n\tjoinSession.PeersMsgInfo = []*pb.PeerInfo{}\n\tjoinSession.Id = malicious.SessionId\n\tjoinSession.State = StateKeyExchange\n\tjoinSession.TotalMsg = 0\n\n\t// After all change updated, inform clients for malicious information.\n\tlog.Debug(\"len of joinSession.Peers to push malicious \", len(joinSession.Peers))\n\tfor _, peer := range joinSession.Peers {\n\t\tmsg := messages.NewMessage(messages.S_MALICIOUS_PEERS, peer.TmpData).ToBytes()\n\t\tpeer.writeChan <- msg\n\t}\n\n\tlog.Debug(\"Remaining peers in join session after updated: \", joinSession.Peers)\n}", "func MakeNewTableAndStart(game models.Game) {\n\tGameTableMap[game.GameID] = &GameTable{\n\t\tJoin: make(chan *GamePlayer),\n\t\tLeave: make(chan *GamePlayer),\n\t\tBroadcast: make(chan models.SocketData),\n\t\tActivePlayers: make(map[*GamePlayer]bool),\n\t\tEnd: make(chan models.Game),\n\t}\n\tgo runTable(game)\n}", "func (ct *ClusterTopology) AddTwinAndStepbrother(node *ClusterTopologyNode) {\n\tct.addNode(node)\n\tct.buildHashcode()\n\tcurrentNode.Twins = append(currentNode.Twins, node.Node.Name)\n\tcurrentNode.Stepbrothers = append(currentNode.Stepbrothers, node.Node.Name)\n\tcurrentNode.UpdateDate = time.Now()\n}", "func (m *RegistryKeyState) SetHive(value *RegistryHive)() {\n m.hive = value\n}", "func (ps *PeerStore) Add(p *Peer) {\n\tps.lock.Lock()\n\tdefer ps.lock.Unlock()\n\tps.peers[p.ListenAddr] = p\n}", "func (peer *Peer) Add(db *sql.DB) {\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tstmt, err := tx.Prepare(\"insert or replace into peer(ip, port, lastSeen) values(?, ?, ?)\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer stmt.Close()\n\n\t_, err = stmt.Exec(peer.IP, peer.Port, peer.LastSeen)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ttx.Commit()\n}", "func (h *hashRing) Add(host string, size int) {\n\thlen := h.Size()\n\tcap := hlen + size\n\n\t// resize node list\n\tnodes := make([]node, cap)\n\tcopy(nodes, h.nodes)\n\th.nodes = nodes\n\n\t// insert new nodes at the end\n\tfor i := hlen; i < cap; i++ {\n\t\t// hash: 0:localhost:7000:0\n\t\t// adding the index at the start and end seemed to give better distribution\n\t\thasher.Write([]byte(fmt.Sprint(i, \":\", host, \":\", i)))\n\n\t\t// hash value\n\t\tvalue := hasher.Sum64()\n\n\t\t// create node\n\t\tn := node{hash: value, host: host, size: size}\n\n\t\t// insert node\n\t\th.nodes[i] = n\n\n\t\t// reset hash\n\t\thasher.Reset()\n\t}\n\n\t// sort nodes around ring based on hash\n\th.nodes.sort()\n}", "func (pd *philosopherData) StartedEating() {\n\tpd.eating = true\n\tpd.dinnersSpent++\n}", "func (p Philosopher) dine(wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\tp.leftFork.Lock()\n\tp.rightFork.Lock()\n\n\tfmt.Println(p.id, \" is eating\")\n\t//used pause values to minimise.\n\ttime.Sleep(2 * time.Second)\n\tp.rightFork.Unlock()\n\tp.leftFork.Unlock()\n\n}", "func CreateSegment(db *sql.DB, schema string, count, segmentID, percent int) {\n\tvar add func(string, []int)\n\n\tadd = func(schema string, people []int) {\n\t\tif len(people) == 0 {\n\t\t\treturn\n\t\t}\n\n\t\ttx, err := db.Begin()\n\t\texitIf(\"start transaction\", err)\n\n\t\tquery := `\n\t\t UPDATE ` + schema + `.people\n\t\t\tSET memberships = memberships || myvalues.hash::hstore\n\t\t\tFROM (\n\t\t\t\tVALUES `\n\n\t\tend := `) AS myvalues (id, hash)\n\t\t WHERE ` + schema + `.people.id = myvalues.id::integer`\n\n\t\targs := make([]interface{}, 0, len(people)*2)\n\n\t\tfor i, id := range people {\n\t\t\tquery += fmt.Sprint(\"($\", i*2+1, \", $\", i*2+2, \")\")\n\t\t\tif i != len(people)-1 {\n\t\t\t\tquery += \", \"\n\t\t\t}\n\n\t\t\tstatus := \"left|\"\n\n\t\t\tif rand.Intn(100) <= percent {\n\t\t\t\tstatus = \"entered|\"\n\t\t\t}\n\n\t\t\tkey := status + strconv.Itoa(segmentID)\n\t\t\tvalue := sql.NullString{strconv.Itoa(int(time.Now().Unix())), true}\n\n\t\t\targs = append(args, id, hstore.Hstore{map[string]sql.NullString{key: value}})\n\t\t}\n\n\t\tquery += end\n\n\t\tr, err := db.Exec(query, args...)\n\t\texitIf(\"updating people\", err)\n\n\t\tif num, _ := r.RowsAffected(); num != int64(len(people)) {\n\t\t\tlog.Fatal(\"update didn't update?\", r)\n\t\t}\n\n\t\texitIf(\"commit transaction\", tx.Commit())\n\t}\n\n\tstart := time.Now()\n\tbatch := make([]int, 0, 100)\n\n\tfor i := 0; i < count; i++ {\n\t\tid := i + 1\n\n\t\tif i%10000 == 0 {\n\t\t\tlog.Println(\"adding to person\", id)\n\t\t}\n\n\t\tbatch = append(batch, id)\n\n\t\tif len(batch) >= 100 {\n\t\t\tadd(schema, batch)\n\t\t\tbatch = make([]int, 0, 100)\n\t\t}\n\t}\n\n\tadd(schema, batch)\n\n\tlog.Println(\"updated\", count, \"persons in\", time.Since(start))\n}", "func (cache *SimTradingDBCache) addSimTrading(params *tradingpb.SimTradingParams, hash string, buf []byte, node *tradingpb.SimTradingCacheNode) error {\n\thashHeader := hash[:2]\n\tv, isok := cache.mapHashHeader[hashHeader]\n\tif !isok {\n\t\treturn nil\n\t}\n\n\thashCache, err := cache.hashParams2(params, hash, buf)\n\tif err != nil {\n\t\ttradingdb2utils.Warn(\"SimTradingDBCache.addSimTrading:hashParams2\",\n\t\t\tzap.Error(err))\n\n\t\treturn err\n\t}\n\n\tcache.mutexCache.Lock()\n\n\tcache.mapCache[hashCache] = node\n\n\tv.Nodes = append(v.Nodes, node)\n\tcache.mapHashHeader[hashHeader] = v\n\n\tcache.mutexCache.Unlock()\n\n\treturn nil\n}", "func (t *MedChain) addHospital(stub shim.ChaincodeStubInterface, args []string) peer.Response {\n\t\t// ==== Input sanitation ====\n\t\tfmt.Println(\"- start addHospital\")\n\n\t\t// check if all the args are send\n\t\tif len(args) != 3 {\n\t\t\tfmt.Println(\"Incorrect number of arguments, Required 3 arguments\")\n\t\t\treturn shim.Error(\"Incorrect number of arguments, Required 3 arguments\")\n\t\t}\n\n\t\t// check if the args are empty\n\t\tfor i := 0; i < len(args); i++ {\n\t\t\tif len(args[i]) <= 0 {\n\t\t\t\tfmt.Println(\"argument \"+ string(i+1) + \" must be a non-empty string\")\n\t\t\t\treturn shim.Error(\"argument \"+ string(i+1) + \" must be a non-empty string\")\n\t\t\t}\n\t\t}\n\n\t\t// get timestamp\n\t\ttxTimeAsPtr, errTx := t.GetTxTimestampChannel(stub)\n\t\tif errTx != nil {\n\t\t\treturn shim.Error(\"Returning time error\")\n\t\t}\n\n\t\t// create the object\n\t\tvar obj = Hospital{}\n\n\t\tobj.Hospital_ID = ComputeHashKey(args[0]+(txTimeAsPtr.String()))\n\t\tobj.HospitalName = args[0]\n\t\tobj.HospitalAddress = args[1]\n\t\tobj.HospitalPhone = args[2]\n\t\tobj.AssetType = \"Hospital\"\n\n\t\t// convert to bytes\n\t\tassetAsBytes, errMarshal := json.Marshal(obj)\n\t\t\n\t\t// show error if failed\n\t\tif errMarshal != nil {\n\t\t\treturn shim.Error(fmt.Sprintf(\"Marshal Error: %s\", errMarshal))\n\t\t}\n\n\t\t// save data in blockchain\n\t\terrPut := stub.PutState(obj.Hospital_ID, assetAsBytes)\n\n\t\tif errPut != nil {\n\t\t\treturn shim.Error(fmt.Sprintf(\"Failed to save file data : %s\", obj.Hospital_ID))\n\t\t}\n\n\t\tfmt.Println(\"Success in saving file data %v\", obj)\n\n\n\t\treturn shim.Success(assetAsBytes)\n\t}", "func (t *Table) AddPlayer(u *User) {\n\n\t//id := uuid.New().String()\n\n}", "func Add(db sql.Executor, ref types.PoetProofRef, poet, serviceID []byte, roundID string) error {\n\tenc := func(stmt *sql.Statement) {\n\t\tstmt.BindBytes(1, ref[:])\n\t\tstmt.BindBytes(2, poet)\n\t\tstmt.BindBytes(3, serviceID)\n\t\tstmt.BindBytes(4, []byte(roundID))\n\t}\n\t_, err := db.Exec(`\n\t\tinsert into poets (ref, poet, service_id, round_id) \n\t\tvalues (?1, ?2, ?3, ?4);`, enc, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"exec: %w\", err)\n\t}\n\n\treturn nil\n}", "func persist(s Spot, op string) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tdefer save()\n\tif op == add {\n\t\tstore[s.Key()] = s\n\t}\n\tif op == drop {\n\t\tdelete(store, s.Key())\n\t}\n}", "func (p *BoxPeer) AddToPeerstore(maddr multiaddr.Multiaddr) error {\n\thaddr, pid, err := DecapsulatePeerMultiAddr(maddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tptype, _ := p.Type(pid)\n\tp.table.peerStore.Put(pid, pstore.PTypeSuf, uint8(ptype))\n\t// TODO, we must consider how long the peer should be in the peerstore,\n\t// PermanentAddrTTL should only be for peer configured by user.\n\t// Peer that is connected or observed from other peers should have different TTL.\n\tp.host.Peerstore().AddAddr(pid, haddr, peerstore.PermanentAddrTTL)\n\tp.table.routeTable.Update(pid)\n\treturn nil\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"hive-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr.(*ReconcileHive).kubeClient, err = kubernetes.NewForConfig(mgr.GetConfig())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr.(*ReconcileHive).deploymentClient, err = appsclientv1.NewForConfig(mgr.GetConfig())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource Hive\n\terr = c.Watch(&source.Kind{Type: &hivev1alpha1.Hive{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// TODO: need to watch resources that we have created through code\n\treturn nil\n}", "func (c *connection) addHost(conn *net.TCPConn) {\n\tmsg := read(conn)\n\tvar buf bytes.Buffer\n\tid := int(msg[1])\n\tport := int(msg[2])*256 + int(msg[3])\n\tif id == 0 {\n\t\tid = len(c.peers)\n\t\tbuf.Write([]byte{byte(id), byte(c.myId)})\n\t\tfor i := range c.peers {\n\t\t\tif i != c.myId {\n\t\t\t\tbuf.WriteByte(byte(i))\n\t\t\t\tbuf.Write(addrToBytes(c.peers[i].ip, c.peers[i].port))\n\t\t\t}\n\t\t}\n\t\twrite(conn, buf.Bytes())\n\n\t}\n\tc.addPeer(id, conn, port)\n\tgo c.receive(c.peers[id])\n}", "func (o *Shelf) Insert(exec boil.Executor, whitelist ...string) error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no shelf provided for insertion\")\n\t}\n\to.whitelist = whitelist\n\to.operation = \"INSERT\"\n\n\tvar err error\n\n\tif err := o.doBeforeInsertHooks(exec); err != nil {\n\t\treturn err\n\t}\n\n\tnzDefaults := queries.NonZeroDefaultSet(shelfColumnsWithDefault, o)\n\n\tkey := makeCacheKey(whitelist, nzDefaults)\n\tshelfInsertCacheMut.RLock()\n\tcache, cached := shelfInsertCache[key]\n\tshelfInsertCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl, returnColumns := strmangle.InsertColumnSet(\n\t\t\tshelfColumns,\n\t\t\tshelfColumnsWithDefault,\n\t\t\tshelfColumnsWithoutDefault,\n\t\t\tnzDefaults,\n\t\t\twhitelist,\n\t\t)\n\n\t\tcache.valueMapping, err = queries.BindMapping(shelfType, shelfMapping, wl)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcache.retMapping, err = queries.BindMapping(shelfType, shelfMapping, returnColumns)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcache.query = fmt.Sprintf(\"INSERT INTO `shelf` (`%s`) VALUES (%s)\", strings.Join(wl, \"`,`\"), strmangle.Placeholders(dialect.IndexPlaceholders, len(wl), 1, 1))\n\n\t\tif len(cache.retMapping) != 0 {\n\t\t\tcache.retQuery = fmt.Sprintf(\"SELECT `%s` FROM `shelf` WHERE %s\", strings.Join(returnColumns, \"`,`\"), strmangle.WhereClause(\"`\", \"`\", 0, shelfPrimaryKeyColumns))\n\t\t}\n\t}\n\n\tvalue := reflect.Indirect(reflect.ValueOf(o))\n\tvals := queries.ValuesFromMapping(value, cache.valueMapping)\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, cache.query)\n\t\tfmt.Fprintln(boil.DebugWriter, vals)\n\t}\n\n\tresult, err := exec.Exec(cache.query, vals...)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to insert into shelf\")\n\t}\n\n\tvar lastID int64\n\tvar identifierCols []interface{}\n\n\tif len(cache.retMapping) == 0 {\n\t\tgoto CacheNoHooks\n\t}\n\n\tlastID, err = result.LastInsertId()\n\tif err != nil {\n\t\treturn ErrSyncFail\n\t}\n\n\to.ID = int64(lastID)\n\tif lastID != 0 && len(cache.retMapping) == 1 && cache.retMapping[0] == shelfMapping[\"ID\"] {\n\t\tgoto CacheNoHooks\n\t}\n\n\tidentifierCols = []interface{}{\n\t\to.ID,\n\t}\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, cache.retQuery)\n\t\tfmt.Fprintln(boil.DebugWriter, identifierCols...)\n\t}\n\n\terr = exec.QueryRow(cache.retQuery, identifierCols...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to populate default values for shelf\")\n\t}\n\nCacheNoHooks:\n\tif !cached {\n\t\tshelfInsertCacheMut.Lock()\n\t\tshelfInsertCache[key] = cache\n\t\tshelfInsertCacheMut.Unlock()\n\t}\n\n\treturn o.doAfterInsertHooks(exec)\n}", "func setupHost(ctx context.Context) (host.Host, *dht.IpfsDHT) {\n\t// Set up the host identity options\n\tprvkey, _, err := crypto.GenerateKeyPairWithReader(crypto.RSA, 2048, rand.Reader)\n\tidentity := libp2p.Identity(prvkey)\n\t// Handle any potential error\n\tif err != nil {\n\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t}).Fatalln(\"Failed to Generate P2P Identity Configuration!\")\n\t}\n\n\t// Trace log\n\tlogrus.Traceln(\"Generated P2P Identity Configuration.\")\n\n\t// Set up TCP, QUIC transport and options\n\ttlstransport, err := tls.New(prvkey)\n\tsecurity := libp2p.Security(tls.ID, tlstransport)\n\ttcpTransport := libp2p.Transport(tcp.NewTCPTransport)\n\tquicTransport := libp2p.Transport(libp2pquic.NewTransport)\n\t// Handle any potential error\n\tif err != nil {\n\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t}).Fatalln(\"Failed to Generate P2P Security and Transport Configurations!\")\n\t}\n\n\t// Trace log\n\tlogrus.Traceln(\"Generated P2P Security and Transport Configurations.\")\n\n\t// Set up host listener address options\n\ttcpMuladdr4, err := multiaddr.NewMultiaddr(\"/ip4/0.0.0.0/tcp/0\")\n\ttcpMuladdr6, err1 := multiaddr.NewMultiaddr(\"/ip6/::/tcp/0\")\n\tquicMuladdr4, err2 := multiaddr.NewMultiaddr(\"/ip4/0.0.0.0/udp/0/quic\")\n\tquicMuladdr6, err3 := multiaddr.NewMultiaddr(\"/ip6/::/udp/0/quic\")\n\tlisten := libp2p.ListenAddrs(quicMuladdr6, quicMuladdr4, tcpMuladdr6, tcpMuladdr4)\n\t// Handle any potential error\n\tcheckErr(err)\n\tcheckErr(err1)\n\tcheckErr(err2)\n\tcheckErr(err3)\n\n\t// Trace log\n\tlogrus.Traceln(\"Generated P2P Address Listener Configuration.\")\n\n\t// Set up the stream multiplexer and connection manager options\n\tmuxer := libp2p.Muxer(\"/yamux/1.0.0\", yamux.DefaultTransport)\n\tconn := libp2p.ConnectionManager(connmgr.NewConnManager(100, 400, time.Minute))\n\n\t// Trace log\n\tlogrus.Traceln(\"Generated P2P Stream Multiplexer, Connection Manager Configurations.\")\n\n\t// Setup NAT traversal and relay options\n\tnat := libp2p.NATPortMap()\n\trelay := libp2p.EnableAutoRelay()\n\n\t// Trace log\n\tlogrus.Traceln(\"Generated P2P NAT Traversal and Relay Configurations.\")\n\n\t// Declare a KadDHT\n\tvar kaddht *dht.IpfsDHT\n\t// Setup a routing configuration with the KadDHT\n\trouting := libp2p.Routing(func(h host.Host) (routing.PeerRouting, error) {\n\t\tkaddht = setupKadDHT(ctx, h)\n\t\treturn kaddht, err\n\t})\n\n\t// Trace log\n\tlogrus.Traceln(\"Generated P2P Routing Configurations.\")\n\n\topts := libp2p.ChainOptions(identity, listen, security, tcpTransport, quicTransport, muxer, conn, nat, routing, relay)\n\n\t// Construct a new libP2P host with the created options\n\tlibhost, err := libp2p.New(ctx, opts)\n\t// Handle any potential error\n\tif err != nil {\n\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t}).Fatalln(\"Failed to Create the P2P Host!\")\n\t}\n\n\t// Return the created host and the kademlia DHT\n\treturn libhost, kaddht\n}", "func newSession(g Game, sessId int, host *HostUser) (*Session, error) {\n\tsession := Session{\n\t\tsessionId: sessId,\n\t\tgame: g,\n\t\tLobbyHost: host,\n\t\tuserMap: make(map[string]*AnonUser),\n\t\tPlayerMap: make([]User, 0, g.MaxUsers() + 1),\n\t\t//PlayerMap: make(map[int]*User, g.MaxUsers() + 1),\n\t\tSend: make(chan []byte),\n\t\tReceive: make(chan interface{}),\n\t\tData: make(chan interface{}),\n\t\tExit: make(chan bool, 1),\n\t}\n\thost.SetSession(&session)\n\thost.SetPlayer(0)\n\tsession.PlayerMap = append(session.PlayerMap, session.LobbyHost) //set index 0 as host\n\t//session.PlayerMap[0] = session.LobbyHost\n\n\tgo session.dataHandler()\n\treturn &session, nil\n}", "func (client *Client) AddHpHost(request *AddHpHostRequest) (response *AddHpHostResponse, err error) {\n\tresponse = CreateAddHpHostResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func (g *Gateway) addPeer(p *peer) {\n\tg.peers[p.addr] = p\n\tg.addNode(p.addr)\n\tgo g.listenPeer(p)\n}", "func (s *BasePlSqlParserListener) EnterSupplemental_table_logging(ctx *Supplemental_table_loggingContext) {\n}", "func AddRecover(h Hellor) Hellor {\n\treturn &helloRecover{h}\n}", "func Join(existingNodeIP string, existingNodePort string, myIp string, myPort string) error {\n\tfmt.Println(\"Joining chord ring...\")\n\tfmt.Println(\"Making RPC call to: \", existingNodeIP, \":\", existingNodePort)\n\n\t// Init the pointer to ourself\n\tFingerTable[SELF].IpAddress = myIp\n\tFingerTable[SELF].Port = myPort\n\tFingerTable[SELF].ChordID = GetChordID(myIp + \":\" + myPort)\n\n\tvar findSuccessorReply FindSuccessorReply\n\tvar args ChordIDArgs\n\targs.Id = FingerTable[SELF].ChordID\n\n\tvar chordNodePtrToExistingNode ChordNodePtr\n\tchordNodePtrToExistingNode.IpAddress = existingNodeIP\n\tchordNodePtrToExistingNode.Port = existingNodePort\n\tchordNodePtrToExistingNode.ChordID = GetChordID(existingNodeIP + \":\" + existingNodePort)\n\n\tfor CallRPC(\"Requested.FindSuccessor\", &args, &findSuccessorReply, &chordNodePtrToExistingNode) != nil {\n\t\tDelay(\"3s\")\n\t}\n\n\t// Set our fingers to point to the successor.\n\tFingerTable[1].IpAddress = findSuccessorReply.ChordNodePtr.IpAddress\n\tFingerTable[1].Port = findSuccessorReply.ChordNodePtr.Port\n\tFingerTable[1].ChordID = findSuccessorReply.ChordNodePtr.ChordID\n\n\t// call TransferKeys on the node that we just discovered is our new successor\n\t// we need to tell the new successor about ourself (IP, Port, and ChordID) so it\n\t// knows where/what are the approrpiate keys to insert on us\n\tfmt.Println(\"Calling TransferKeys on node (my newly discovered successor): \", FingerTable[1].ChordID)\n\tvar transferKeysReply TransferKeysReply\n\tvar argsXfer TransferKeysArgs\n\targsXfer.ChordNodePtr.IpAddress = FingerTable[SELF].IpAddress\n\targsXfer.ChordNodePtr.Port = FingerTable[SELF].Port\n\targsXfer.ChordNodePtr.ChordID = FingerTable[SELF].ChordID\n\terr := CallRPC(\"Requested.TransferKeys\", &argsXfer, &transferKeysReply, &FingerTable[1])\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Persist(g Guest) {\n\tdt := time.Now()\n\tr := rp.Get()\n\tdefer r.Close()\n\tlog.Println(\"Persist\", g)\n\tr.Do(\"SADD\", \"domains\", g.Source)\n\tr.Do(\"INCR\", g.Source+\"_\"+dt.Format(\"20060102\"))\n\tr.Do(\"EXPIRE\", g.Source+\"_\"+dt.Format(\"20060102\"), counterHistory*86400)\n\tr.Do(\"SET\", g.Source+\":\"+g.Xid, g.Host+\"±\"+g.Agent, \"EX\", sessionTimeout*60)\n}", "func (w *Witness) setSTH(tx *sql.Tx, logID string, sth []byte) error {\n\tif _, err := tx.Exec(`INSERT OR REPLACE INTO sths (logID, sth) VALUES (?, ?)`, logID, sth); err != nil {\n\t\treturn fmt.Errorf(\"failed to update STH; %v\", err)\n\t}\n\treturn tx.Commit()\n}", "func Pha(c *CPU) {\n\tc.PushStack(c.A)\n}", "func insertRelationEdges(conn types.TGConnection, gof types.TGGraphObjectFactory, houseMemberTable map[string]types.TGNode) {\n\tfmt.Println(\">>>>>>> Entering InsertRelationEdges: Insert Few Family Relations with individual properties <<<<<<<\")\n\n\t// Insert edge data into database\n\t// Two edge types defined in ancestry-initdb.conf.\n\t// Added year of marriage and place of marriage edge attributes for spouseEdge desc\n\t// Added Birth order edge attribute for offspringEdge desc\n\n\tgmd, err := conn.GetGraphMetadata(true)\n\tif err != nil {\n\t\tfmt.Println(\">>>>>>> Returning from InsertRelationEdges - error during conn.GetGraphMetadata <<<<<<<\")\n\t\treturn\n\t}\n\n\tspouseEdgeType, err := gmd.GetEdgeType(\"spouseEdge\")\n\tif err != nil {\n\t\tfmt.Println(\">>>>>>> Returning from InsertRelationEdges - error during conn.GetEdgeType('spouseEdge') <<<<<<<\")\n\t\treturn\n\t}\n\tif spouseEdgeType != nil {\n\t\tfmt.Printf(\">>>>>>> 'spouseEdge' is found with %d attributes <<<<<<<\\n\", len(spouseEdgeType.GetAttributeDescriptors()))\n\t} else {\n\t\tfmt.Println(\">>>>>>> 'spouseEdge' is not found from meta data fetch <<<<<<<\")\n\t\treturn\n\t}\n\n\toffspringEdgeType, err := gmd.GetEdgeType(\"offspringEdge\")\n\tif err != nil {\n\t\tfmt.Println(\">>>>>>> Returning from InsertRelationEdges - error during conn.GetEdgeType('offspringEdge') <<<<<<<\")\n\t\treturn\n\t}\n\tif offspringEdgeType != nil {\n\t\tfmt.Printf(\">>>>>>> 'offspringEdgeType' is found with %d attributes <<<<<<<\\n\", len(offspringEdgeType.GetAttributeDescriptors()))\n\t} else {\n\t\tfmt.Println(\">>>>>>> 'spouseEdge' is not found from meta data fetch <<<<<<<\")\n\t\treturn\n\t}\n\n\tfor _, houseRelation := range HouseRelationData {\n\t\thouseMemberFrom := houseMemberTable[houseRelation.FromMemberName]\n\t\thouseMemberTo := houseMemberTable[houseRelation.ToMemberName]\n\t\trelationName := houseRelation.RelationDesc\n\t\tfmt.Printf(\">>>>>>> Inside InsertRelationEdges: trying to create edge('%s'): From '%s' To '%s' <<<<<<<\\n\", relationName, houseRelation.FromMemberName, houseRelation.ToMemberName)\n\t\t//var relationDirection types.TGDirectionType\n\t\tif relationName == \"spouse\" {\n\t\t\t//relationDirection = types.DirectionTypeUnDirected\n\t\t\tspouseEdgeType.GetFromNodeType()\n\t\t\tedge1, err := gof.CreateEdgeWithEdgeType(houseMemberFrom, houseMemberTo, spouseEdgeType)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\">>>>>>> Returning from InsertRelationEdges - error during gof.CreateEdgeWithEdgeType(spouseEdgeType) <<<<<<<\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\t_ = edge1.SetOrCreateAttribute(\"yearMarried\", houseRelation.Attribute1)\n\t\t\t_ = edge1.SetOrCreateAttribute(\"placeMarried\", houseRelation.Attribute2)\n\t\t\t_ = edge1.SetOrCreateAttribute(\"relType\", relationName)\n\t\t\terr = conn.InsertEntity(edge1)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\">>>>>>> Returning from InsertRelationEdges - error during conn.InsertEntity(edge1) <<<<<<<\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t_, err = conn.Commit()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\">>>>>>> Returning from InsertRelationEdges w/ error during conn.Commit() <<<<<<<\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfmt.Printf(\">>>>>>> Inside InsertRelationEdges: Successfully added edge(spouse): From '%+v' To '%+v' <<<<<<<\\n\", houseRelation.FromMemberName, houseRelation.ToMemberName)\n\t\t} else {\n\t\t\t//relationDirection = types.DirectionTypeDirected\n\t\t\tedge1, err := gof.CreateEdgeWithEdgeType(houseMemberFrom, houseMemberTo, offspringEdgeType)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\">>>>>>> Returning from InsertRelationEdges - error during gof.CreateEdgeWithEdgeType(offspringEdgeType) <<<<<<<\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\t_ = edge1.SetOrCreateAttribute(\"birthOrder\", houseRelation.Attribute1)\n\t\t\t_ = edge1.SetOrCreateAttribute(\"relType\", relationName)\n\t\t\terr = conn.InsertEntity(edge1)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\">>>>>>> Returning from InsertRelationEdges - error during conn.InsertEntity(edge1) <<<<<<<\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t_, err = conn.Commit()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\">>>>>>> Returning from InsertRelationEdges w/ error during conn.Commit() <<<<<<<\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfmt.Printf(\">>>>>>> Inside InsertRelationEdges: Successfully added edge: From '%+v' To '%+v' <<<<<<<\\n\", houseRelation.FromMemberName, houseRelation.ToMemberName)\n\t\t}\n\t} // End of for loop\n\n\tfmt.Println(\">>>>>>> Successfully added edges w/ NO ERRORS !!! <<<<<<<\")\n\tfmt.Println(\">>>>>>> Returning from InsertRelationEdges w/ NO ERRORS !!! <<<<<<<\")\n}", "func addBlockedHost(host string) bool {\n\tdm := host2Domain(host)\n\tif isHostAlwaysDirect(host) || hostIsIP(host) || dm == \"localhost\" {\n\t\treturn false\n\t}\n\tif chouDs[dm] {\n\t\t// Record blocked time for chou domain, this marks a chou domain as\n\t\t// temporarily blocked\n\t\tnow := time.Now()\n\t\tchou.Lock()\n\t\tchou.time[dm] = now\n\t\tchou.Unlock()\n\t\tdebug.Printf(\"chou domain %s blocked at %v\\n\", dm, now)\n\t} else if !blockedDs.has(dm) {\n\t\tblockedDs.add(dm)\n\t\tblockedDomainChanged = true\n\t\tdebug.Printf(\"%s added to blocked list\\n\", dm)\n\t\t// Delete this domain from direct domain set\n\t\tdelDirectDomain(dm)\n\t}\n\treturn true\n}", "func (h *Hosts) AddHost(host ...Host) {\n\th.mux.Lock()\n\tdefer h.mux.Unlock()\n\n\th.hosts = append(h.hosts, host...)\n}", "func (s *SharemeService) Add(c *gae.Context, session *Session, key string) (stat Share) {\n\tstat = s.Stat(c, key)\n\tif stat.IsError() {\n\t\treturn\n\t}\n\tsession.Set(fmt.Sprintf(\"%s%s\", KeySessionPrefix, key), stat.Name)\n\treturn\n}", "func (chatRoom *ChatRoom) addGuest(guest Guest) {\n if chatRoom.wasInvited(&guest) {\n chatRoom.connectionCount++\n chatRoom.guests[guest.getUsername()] = guest\n }\n}", "func (ghost *Ghost) Register() error {\n\tfor _, addr := range ghost.addrs {\n\t\tvar (\n\t\t\tconn net.Conn\n\t\t\terr error\n\t\t)\n\n\t\tlog.Printf(\"Trying %s ...\\n\", addr)\n\t\tghost.Reset()\n\n\t\t// Check if server has TLS enabled.\n\t\t// Only control channel needs to determine if TLS is enabled. Other mode\n\t\t// should use the tlsSettings passed in when it was spawned.\n\t\tif ghost.mode == ModeControl {\n\t\t\tvar enabled bool\n\n\t\t\tswitch ghost.tlsMode {\n\t\t\tcase TLSDetect:\n\t\t\t\tenabled, err = ghost.tlsEnabled(addr)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\tcase TLSForceEnable:\n\t\t\t\tenabled = true\n\t\t\tcase TLSForceDisable:\n\t\t\t\tenabled = false\n\t\t\t}\n\n\t\t\tghost.tls.SetEnabled(enabled)\n\t\t}\n\n\t\tconn, err = net.DialTimeout(\"tcp\", addr, connectTimeout)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Println(\"Connection established, registering...\")\n\t\tif ghost.tls.Enabled {\n\t\t\tcolonPos := strings.LastIndex(addr, \":\")\n\t\t\tconfig := ghost.tls.Config\n\t\t\tconfig.ServerName = addr[:colonPos]\n\t\t\tconn = tls.Client(conn, config)\n\t\t}\n\n\t\tghost.Conn = conn\n\t\treq := NewRequest(\"register\", map[string]interface{}{\n\t\t\t\"mid\": ghost.mid,\n\t\t\t\"sid\": ghost.sid,\n\t\t\t\"mode\": ghost.mode,\n\t\t\t\"properties\": ghost.properties,\n\t\t})\n\n\t\tregistered := func(res *Response) error {\n\t\t\tif res == nil {\n\t\t\t\tghost.reset = true\n\t\t\t\treturn errors.New(\"Register request timeout\")\n\t\t\t} else if res.Response != Success {\n\t\t\t\tlog.Println(\"Register:\", res.Response)\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Registered with Overlord at %s\", addr)\n\t\t\t\tghost.connectedAddr = addr\n\t\t\t\tif err := ghost.Upgrade(); err != nil {\n\t\t\t\t\tlog.Println(err)\n\t\t\t\t}\n\t\t\t\tghost.pauseLanDisc = true\n\t\t\t}\n\t\t\tghost.RegisterStatus = res.Response\n\t\t\treturn nil\n\t\t}\n\n\t\tvar handler ResponseHandler\n\t\tswitch ghost.mode {\n\t\tcase ModeControl:\n\t\t\thandler = registered\n\t\tcase ModeTerminal:\n\t\t\thandler = ghost.SpawnTTYServer\n\t\tcase ModeShell:\n\t\t\thandler = ghost.SpawnShellServer\n\t\tcase ModeFile:\n\t\t\thandler = ghost.InitiatefileOperation\n\t\tcase ModeForward:\n\t\t\thandler = ghost.SpawnPortModeForwardServer\n\t\t}\n\t\terr = ghost.SendRequest(req, handler)\n\t\treturn nil\n\t}\n\n\treturn errors.New(\"Cannot connect to any server\")\n}", "func (o *FeatureRelationship) InsertP(exec boil.Executor, whitelist ...string) {\n\tif err := o.Insert(exec, whitelist...); err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func addDoH(ipStr, base string) {\n\tip := netip.MustParseAddr(ipStr)\n\tdohOfIP[ip] = base\n\tdohIPsOfBase[base] = append(dohIPsOfBase[base], ip)\n}", "func (g *Server) Add(registration Registration) {\n\tg.registrars = append(g.registrars, registration)\n}", "func NewPhilosopherPtr(name string) *Philosopher {\n\tphi := new(Philosopher)\n\tphi.Init(name)\n\treturn phi\n}", "func SeedShoutTable(db *gorm.DB) error {\n\tshoutSeeds := seedShouts()\n\n\tfor _, shout := range shoutSeeds {\n\t\terr := db.Create(&shout).Error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func AddMultiHop(exec executor.Executor, execnet, tonet, routingTable string, ref map[string]NetworkSettings) error {\n\tlocalNetGW, ok := ref[execnet]\n\tif !ok {\n\t\treturn fmt.Errorf(\"network %s not found in %v\", execnet, ref)\n\t}\n\texternalNet, ok := ref[tonet]\n\tif !ok {\n\t\treturn fmt.Errorf(\"network %s not found in %v\", tonet, ref)\n\t}\n\n\terr := routes.Add(exec, fmt.Sprintf(\"%s/%d\", externalNet.IPAddress, externalNet.IPPrefixLen), localNetGW.IPAddress, routingTable)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = routes.Add(exec, fmt.Sprintf(\"%s/%d\", externalNet.GlobalIPv6Address, externalNet.GlobalIPv6PrefixLen), localNetGW.GlobalIPv6Address, routingTable)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (w *World) Add(h Hitable) {\n\tw.elements = append(w.elements, h)\n}", "func (db *Server) Insert(serv *objects.Server) {\n\tdb.servers[serv.Met.GetID().String()] = serv\n}", "func (h *HamtFunctional) persist(oldTable, newTable tableI, path tableStack) {\n\t// Removed the case where path.len() == 0 on the first call to nh.perist(),\n\t// because that case is handled in Put & Del now. It is handled in Put & Del\n\t// because otherwise we were allocating an extraneous fixedTable for the\n\t// old h.root.\n\t_ = assertOn && assert(path.len() != 0,\n\t\t\"path.len()==0; This case should be handled directly in Put & Del.\")\n\n\tvar depth = uint(path.len()) //guaranteed depth > 0\n\tvar parentDepth = depth - 1\n\n\tvar parentIdx = oldTable.Hash().Index(parentDepth)\n\n\tvar oldParent = path.pop()\n\n\tvar newParent tableI\n\tif path.len() == 0 {\n\t\t// This condition and the last if path.len() > 0; shaves off one call\n\t\t// to persist and one fixed table allocation (via oldParent.copy()).\n\t\th.root = *oldParent.(*fixedTable)\n\t\tnewParent = &h.root\n\t} else {\n\t\tnewParent = oldParent.copy()\n\t}\n\n\tif newTable == nil {\n\t\tnewParent.remove(parentIdx)\n\t} else {\n\t\tnewParent.replace(parentIdx, newTable)\n\t}\n\n\tif path.len() > 0 {\n\t\th.persist(oldParent, newParent, path)\n\t}\n\n\treturn\n}", "func Add(db sql.Executor, epoch types.EpochID, beacon types.Beacon) error {\n\tenc := func(stmt *sql.Statement) {\n\t\tstmt.BindInt64(1, int64(epoch))\n\t\tstmt.BindBytes(2, beacon.Bytes())\n\t}\n\t_, err := db.Exec(\"insert into beacons (epoch, beacon) values (?1, ?2);\", enc, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"insert epoch %v, beacon %v: %w\", epoch, beacon, err)\n\t}\n\n\treturn nil\n}" ]
[ "0.5219672", "0.5129547", "0.49024424", "0.48906705", "0.46489275", "0.4642735", "0.46202862", "0.4610928", "0.46090752", "0.45943037", "0.45698857", "0.45681417", "0.45659956", "0.45559785", "0.45418945", "0.45342994", "0.45327252", "0.45237312", "0.44821578", "0.44794598", "0.44559488", "0.44476038", "0.4442459", "0.44368082", "0.4436229", "0.44266593", "0.4426153", "0.44049597", "0.43824774", "0.43810135", "0.4375716", "0.43688905", "0.4366034", "0.4344833", "0.43221086", "0.43019608", "0.43016866", "0.4293303", "0.42918915", "0.42656958", "0.42516816", "0.42345595", "0.42301032", "0.42291397", "0.42285725", "0.4220658", "0.42100352", "0.42055357", "0.4197851", "0.4197705", "0.4193884", "0.41748604", "0.4173534", "0.41726565", "0.41693664", "0.41669273", "0.41642863", "0.4157163", "0.4146499", "0.41445938", "0.4137624", "0.41356128", "0.41300485", "0.4119808", "0.41160497", "0.41140476", "0.41097543", "0.41094127", "0.40989724", "0.4098571", "0.40903467", "0.40892968", "0.4082931", "0.40737525", "0.40709114", "0.40702283", "0.40660763", "0.4059018", "0.4059012", "0.4058841", "0.40551123", "0.4044349", "0.4041156", "0.4037713", "0.40353477", "0.4035288", "0.40311626", "0.4027782", "0.40244666", "0.40228936", "0.40217185", "0.40213197", "0.40205827", "0.40174836", "0.4013223", "0.40044957", "0.40043566", "0.40018493", "0.4000579", "0.39995053" ]
0.73144776
0
Listen is the main function of the host, which handles dinner requests and finish indications coming from the philosophers on _requestChannel_ and _finishChannel_. Dinner request is authorized with a proper reply to a philosopher on its own dedicated response channel.
func (host *DinnerHost) Listen() { name := "" for { select { case name = <-host.requestChannel: fmt.Println(name + " WOULD LIKE TO EAT.") response := host.AllowEating(name) kickOut := false switch response { case "OK": fmt.Println(name + " STARTS EATING.") case "E:CHOPSTICKS": fmt.Println(name + " CANNOT EAT: REQUIRED CHOPSTICKS ARE NOT AVAILABLE.") case "E:FULL": fmt.Println(name + " CANNOT EAT: TWO OTHER PHILOSOPHERS ARE ALREADY EATING.") case "E:JUSTFINISHED": fmt.Println(name + " CANNOT EAT: JUST FINISHED THE PREVIOUS MEAL.") case "E:EATING": fmt.Println(name + " CANNOT EAT: ALREADY EATING.") case "E:LIMIT": fmt.Println(name + " CANNOT EAT: ALREADY HAD THREE DINNERS; MUST LEAVE.") host.freeSeats = append(host.freeSeats, host.phiData[name].Seat()) kickOut = true } fmt.Println() host.phiData[name].RespChannel() <- response if kickOut { delete(host.phiData, name) } case name = <-host.finishChannel: host.SomeoneFinished(name) } host.PrintReport(false) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (d *Daemon) Listen() {\n\tdefer d.Socket.Close()\n\trpc.RegisterHandler()\n\n\tfor {\n\t\tconn, err := d.Socket.Accept()\n\t\tif err != nil {\n\t\t\tutils.LogFatalf(\"Socket connection error: %+v\\n\", err)\n\t\t}\n\n\t\tutils.LogInfof(\"New socket connection from %s\\n\", conn.RemoteAddr().String())\n\t\tgo rpc.HandleConnection(conn)\n\t}\n}", "func (s *Server) Listen() (cancel func()) {\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\terr := s.srv.ListenAndServeTLS(s.certPath, s.keyPath)\n\t\tif err != nil && err != http.ErrServerClosed {\n\t\t\ts.t.Fatalf(\"ListenFederationServer: ListenAndServeTLS failed: %s\", err)\n\t\t}\n\t}()\n\n\treturn func() {\n\t\terr := s.srv.Shutdown(context.Background())\n\t\tif err != nil {\n\t\t\ts.t.Fatalf(\"ListenFederationServer: failed to shutdown server: %s\", err)\n\t\t}\n\t\twg.Wait() // wait for the server to shutdown\n\t}\n}", "func (s *Server) Listen() error {\n\tln, err := net.Listen(\"tcp\", s.bind)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgs := grpc.NewServer()\n\tyages.RegisterEchoServer(gs, s)\n\treflection.Register(gs)\n\tif release == \"\" {\n\t\trelease = \"dev\"\n\t}\n\tlog.Printf(\"YAGES in version %v serving on %v is ready for gRPC clients …\", release, s.bind)\n\treturn gs.Serve(ln)\n}", "func (l *Listener) Listen() {\n\tfor {\n\t\tvar client net.Conn\n\t\tvar err error\n\t\tif client, err = util.Accept(l); err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Serve the first Handler which is attached to this listener\n\t\tif len(l.HandlerConfigs) > 0 {\n\t\t\toptions := plugin_v1.HandlerOptions{\n\t\t\t\tClientConnection: client,\n\t\t\t\tHandlerConfig: l.HandlerConfigs[0],\n\t\t\t\tEventNotifier: l.EventNotifier,\n\t\t\t\tResolver: l.Resolver,\n\t\t\t\tShutdownNotifier: func(handler plugin_v1.Handler) {},\n\t\t\t}\n\n\t\t\tl.RunHandlerFunc(\"example-handler\", options)\n\t\t} else {\n\t\t\tclient.Write([]byte(\"Error - no handlers were defined!\"))\n\t\t}\n\t}\n}", "func Listen() {\n\tgo listenForIncomingSessions()\n}", "func (s *Socket) Listen() {\n\n\ts.conn.SetReadLimit(maxMessageSize)\n\ts.conn.SetReadDeadline(time.Now().Add(pongWait))\n\ts.conn.SetPongHandler(func(string) error { s.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })\n\n\tdefer s.Close()\n\n\tgo s.handlePing()\n\n\tfor {\n\n\t\t_, message, err := s.conn.ReadMessage()\n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif !s.ready {\n\n\t\t\t// Look for authorization token as the first message\n\t\t\tu, err := db.GetUserForToken(string(message))\n\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ts.User = u\n\t\t\ts.ready = true\n\n\t\t\ts.Send(Message{Header: \"hello\"})\n\n\t\t\tcontinue\n\n\t\t}\n\n\t\ts.hub.Parse(s, message)\n\n\t}\n\n}", "func (s *Server) Listen(\n\taddr string,\n\tcertPath string,\n\tkeyPath string,\n) (err error) {\n\tlogger := logger.Logger()\n\tif err = s.init(); err != nil {\n\t\treturn\n\t}\n\n\topts := []grpc.ServerOption{}\n\ttlsFlag := false\n\n\tif certPath != \"\" && keyPath != \"\" {\n\t\tcreds, err := credentials.NewServerTLSFromFile(certPath, keyPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\topts = append(opts, grpc.Creds(creds))\n\t\ttlsFlag = true\n\t}\n\n\ts.grpcServer = grpc.NewServer(opts...)\n\tpb.RegisterEchoServer(s.grpcServer, s)\n\n\thttpMux := http.NewServeMux()\n\thttpMux.HandleFunc(\"/\", s.httpEchoPing)\n\n\trootMux := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tif req.ProtoMajor == 2 && strings.Contains(req.Header.Get(\"Content-Type\"), \"application/grpc\") {\n\t\t\ts.grpcServer.ServeHTTP(w, req)\n\t\t} else {\n\t\t\thttpMux.ServeHTTP(w, req)\n\t\t}\n\t})\n\n\ts.httpServer = &http.Server{\n\t\tAddr: addr,\n\t\tHandler: h2c.NewHandler(rootMux, &http2.Server{}),\n\t}\n\n\tlogger.Printf(\"grpc listen address: %q tls: %v\", addr, tlsFlag)\n\tif tlsFlag {\n\t\treturn s.httpServer.ListenAndServeTLS(certPath, keyPath)\n\t}\n\treturn s.httpServer.ListenAndServe()\n}", "func (s *Server) Listen() (cancel func()) {\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\n\tln, err := net.Listen(\"tcp\", s.srv.Addr)\n\tif err != nil {\n\t\ts.t.Fatalf(\"ListenFederationServer: net.Listen failed: %s\", err)\n\t}\n\n\tgo func() {\n\t\tdefer ln.Close()\n\t\tdefer wg.Done()\n\t\terr := s.srv.ServeTLS(ln, s.certPath, s.keyPath)\n\t\tif err != nil && err != http.ErrServerClosed {\n\t\t\ts.t.Logf(\"ListenFederationServer: ServeTLS failed: %s\", err)\n\t\t\t// Note that running s.t.FailNow is not allowed in a separate goroutine\n\t\t\t// Tests will likely fail if the server is not listening anyways\n\t\t}\n\t}()\n\n\treturn func() {\n\t\terr := s.srv.Shutdown(context.Background())\n\t\tif err != nil {\n\t\t\ts.t.Fatalf(\"ListenFederationServer: failed to shutdown server: %s\", err)\n\t\t}\n\t\twg.Wait() // wait for the server to shutdown\n\t}\n}", "func Listen(outputDirectory string) error {\n\t// Create listener\n\taddrStr := fmt.Sprintf(\":%v\", port)\n\tlistener, listenErr := net.Listen(\"tcp\", addrStr)\n\tif listenErr != nil {\n\t\treturn listenErr\n\t}\n\n\t// Prepare output directory path\n\toutputDirectory = strings.TrimRight(outputDirectory, \"/\")\n\n\t// Listen forever\n\tfor {\n\t\t// Accept connection\n\t\tconn, connErr := listener.Accept()\n\t\tif connErr != nil {\n\t\t\tlog.Printf(\"Encountered error while accepting from %s: %s\", conn.RemoteAddr().String(), connErr)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Check if we should restrict connections from peers\n\t\thandleConnection := true\n\t\tif restrictToPeers {\n\t\t\tfound := false\n\t\t\t// Loop over peers\n\t\t\tfor _, p := range peers {\n\t\t\t\t// Check if we found the remote address in our peers list\n\t\t\t\tif p.Address == conn.RemoteAddr().String() {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Handle connection only if its a peer\n\t\t\thandleConnection = found\n\t\t}\n\n\t\tif handleConnection {\n\t\t\t// Handle in a separate thread\n\t\t\tgo handle(conn, outputDirectory)\n\t\t}\n\t}\n}", "func Listen(conf *config.Config, speaker twitspeak.TwitterSpeaker, resource database.Resource, logger *logrus.Logger, simLock *simulation.SimLock, simulator simulation.Simulator) {\n\t// check for webhooks id in database\n\twebhooksID, err := resource.GetWebhooksID(context.TODO())\n\tif err != nil {\n\t\tlogger.WithError(err).Panic(\"failed querying database for webhook id\")\n\t}\n\n\t// check twitter for webhooks id\n\twebhooksID, err = speaker.GetWebhook()\n\tif err != nil {\n\t\tlogger.WithError(err).Panic(\"failed querying twitter for webhook id\")\n\t}\n\n\t// autocert manager\n\tmanager := &autocert.Manager{\n\t\tPrompt: autocert.AcceptTOS,\n\t\tHostPolicy: autocert.HostWhitelist(conf.Domains...),\n\t\tCache: autocert.DirCache(\"certs\"),\n\t}\n\n\t// auto cert challenge server\n\tchallengeServer := &http.Server{\n\t\tHandler: manager.HTTPHandler(nil),\n\t\tAddr: \":http\",\n\t}\n\n\t// run challenge server\n\tgo func() {\n\t\tlogger.Info(\"starting autocert challenge server\")\n\t\terr := challengeServer.ListenAndServe()\n\t\tif err != nil {\n\t\t\tlogger.WithError(err).Panic(\"autocert challenge server died\")\n\t\t}\n\t}()\n\n\t// build the twitter webhooks server\n\tdmParser := input.NewDMParser(resource, speaker, logger, simulator)\n\ttwitterHandler := newHandler(conf, logger, dmParser, speaker, simLock)\n\tserver := &http.Server{\n\t\tReadTimeout: 5 * time.Second,\n\t\tWriteTimeout: 5 * time.Second,\n\t\tIdleTimeout: 120 * time.Second,\n\t\tHandler: twitterHandler,\n\t\tAddr: \":https\",\n\t}\n\n\t// start listening on https socket\n\ttlsConf := &tls.Config{\n\t\tGetCertificate: manager.GetCertificate,\n\t}\n\tlistener, err := tls.Listen(\"tcp\", \":https\", tlsConf)\n\tif err != nil {\n\t\tlogger.WithError(err).Panic(\"failed listening on https socket\")\n\t}\n\n\tif webhooksID != \"\" {\n\t\t// trigger a CRC manually\n\t\tgo func() {\n\t\t\terr = speaker.TriggerCRC(webhooksID)\n\t\t\tif err != nil {\n\t\t\t\tlogger.WithError(err).Panic(\"error while triggering crc\")\n\t\t\t}\n\t\t}()\n\t} else {\n\t\t// register the webhook\n\t\tgo func(handler *handler) {\n\t\t\tid, err := speaker.RegisterWebhook()\n\t\t\tif err != nil || id == \"\" {\n\t\t\t\tlogger.WithError(err).Panic(\"error while registering webhooks url\")\n\t\t\t}\n\n\t\t\terr = resource.SetWebhooksID(context.TODO(), webhooksID)\n\t\t\tif err != nil {\n\t\t\t\tlogger.WithError(err).Panic(\"error while setting webhooks id in database\")\n\t\t\t}\n\t\t\thandler.WebhooksID = webhooksID\n\t\t}(twitterHandler.(*handler))\n\t}\n\n\t// start serving on the twitter webhooks listener\n\tlogger.Info(\"starting twitter listener\")\n\terr = server.Serve(listener)\n\tif err != nil {\n\t\tlogger.WithError(err).Panic(\"twitter listener server died\")\n\t}\n}", "func (o *GrpcServer) Listen() (err error) {\n\turi := fmt.Sprintf(\"%s:%d\", o.host, o.port)\n\to.listener, err = net.Listen(\"tcp\", uri)\n\tif err != nil {\n\t\to.State = Error\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\to.State = Listen\n\tlog.Printf(\"[GRPC] services started, listen on %s\\n\", uri)\n\treturn err\n}", "func Listen(lis net.Listener, grpcServer *grpc.Server) (clientChan chan *grpc.ClientConn, shutdownChan chan int, err error) {\n\t// create channels\n\tclientChan = make(chan *grpc.ClientConn)\n\tshutdownChan = make(chan int)\n\n\tgo func() {\n\t\t// start listenLoop - blocks until some error occurs\n\t\tlistenLoop(lis, grpcServer, clientChan)\n\t\tclose(shutdownChan)\n\t}()\n\n\treturn clientChan, shutdownChan, nil\n}", "func Listen(peers *Node, addr string, errChan chan error, stopChan chan struct{}, msgChan chan<- *Message) {\n\tln, err := listen(addr)\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(errChan)\n\t\treturn\n\t}\n\n\tdefer func() {\n\t\terrChan <- ln.Close()\n\t\tclose(errChan)\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase <-stopChan:\n\t\t\t// Recieved signal to close. Get out of here.\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\t// Set deadline before Accept() so we periodically check stopChan\n\t\tif err := ln.SetDeadline(time.Now().Add(1 * time.Second)); err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\tif opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {\n\t\t\t\t// Accept deadline hit, loop\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\n\t\tgo Handle(peers.ID, peers.AddPeer(conn), peers.DropPeer, peers.GetKey, stopChan, msgChan)\n\t}\n}", "func (c *Chain) Listen() {\n\tfor {\n\t\tselect {\n\t\tcase certMsg := <-c.certificateChan:\n\t\t\tc.handleCertificateMessage(certMsg)\n\t\tcase height := <-c.highestSeenChan:\n\t\t\tc.highestSeen = height\n\t\tcase r := <-c.getLastBlockChan:\n\t\t\tc.provideLastBlock(r)\n\t\tcase r := <-c.verifyCandidateBlockChan:\n\t\t\tc.processCandidateVerificationRequest(r)\n\t\tcase r := <-c.getLastCertificateChan:\n\t\t\tc.provideLastCertificate(r)\n\t\tcase r := <-c.getRoundResultsChan:\n\t\t\tc.provideRoundResults(r)\n\t\tcase r := <-c.getSyncProgressChan:\n\t\t\tc.provideSyncProgress(r)\n\t\tcase r := <-c.rebuildChainChan:\n\t\t\tc.rebuild(r)\n\t\t}\n\t}\n}", "func (e *Endpoint) Listen() error {\r\n\tvar err error\r\n\te.listener, err = net.Listen(\"tcp\", Port)\r\n\tif err != nil {\r\n\t\treturn errors.Wrapf(err, \"Unable to listen on port %s\\n\", Port)\r\n\t}\r\n\tlog.Println(\"Listen on\", e.listener.Addr().String())\r\n\tfor {\r\n\t\tlog.Println(\"Accept a connection request.\")\r\n\t\tconn, err := e.listener.Accept()\r\n\t\tif err != nil {\r\n\t\t\tlog.Println(\"Failed accepting a connection request:\", err)\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\tlog.Println(\"Handle incoming messages.\")\r\n\t\tgo e.handleMessages(conn)\r\n\t}\r\n}", "func (s *Server) Listen() error {\n\tdefer s.cancel()\n\ts.log.Infof(\"grpc-gateway server listening on port %d\", s.port)\n\treturn http.ListenAndServe(fmt.Sprintf(\":%d\", s.port), s.mux)\n}", "func (s *Server) listen() {\n\tdefer (Track(\"listen\", s.log))()\n\tvar err error\n\ts.listener, err = net.Listen(\"tcp\", s.port)\n\tif err != nil {\n\t\ts.log(\"listen() failed to start per error: %+v\", err)\n\t\tpanic(err)\n\t}\n\ts.log(\"listening at %s\", s.port)\n\tfor {\n\t\tconn, err := s.listener.Accept()\n\t\tif err != nil {\n\t\t\ts.log(\"failed to accept client per error: %+v\", err)\n\t\t} else {\n\t\t\tclient := NewClient(conn, s.clientInput)\n\t\t\ts.log(\"accepted %s\", client.ID)\n\t\t\ts.newClients <- client\n\t\t}\n\t}\n}", "func (l *HostIPListener) Listen(cancel <-chan interface{}, conn client.Connection) {\n\tzzk.Listen2(cancel, conn, l)\n}", "func Listen(connectionService *ConnectionService) {\n\tinbound := make(chan UDPPacket)\n\tpacketConn, err := net.ListenPacket(\"udp\", \"127.0.0.1:69\")\n\tif err != nil {\n\t\tlog.Fatal(\"Error listening:\", err)\n\t\treturn\n\t}\n\tdefer packetConn.Close()\n\n\tgo read(packetConn, inbound)\n\tgo process(packetConn, inbound, connectionService)\n\tlog.Println(\"Server listening on port 69\")\n\tfor {\n\t}\n}", "func Listen(network, laddr string, config *tls.Config,) (net.Listener, error)", "func (s *Server) listen(listener net.Listener) {\n\tfor {\n\t\t// Accept a connection\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tif s.shutdown {\n\t\t\t\treturn\n\t\t\t}\n\t\t\ts.logger.Printf(\"[ERR] consul.rpc: failed to accept RPC conn: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgo s.handleConn(conn, false)\n\t\tmetrics.IncrCounter([]string{\"rpc\", \"accept_conn\"}, 1)\n\t}\n}", "func (h *Handler) Listen() {\n\tdefer func() {\n\t\th.closed <- true // send to dispatcher, that connection is closed\n\t\th.conn.Close()\n\t\tif h.s != nil && h.s.CurrentWorker != nil {\n\t\t\t// delete a worker record when a session disconnections\n\t\t\th.s.CurrentWorker.deleteWorkerRecord()\n\t\t\t// when we shut down the pool we get an error here because the log\n\t\t\t// is already closed... TODO\n\t\t\th.s.log.Printf(\"Closed worker: %d\\n\", h.s.CurrentWorker.wr.workerID)\n\t\t}\n\t}()\n\terr := h.p.tg.Add()\n\tif err != nil {\n\t\t// If this goroutine is not run before shutdown starts, this\n\t\t// codeblock is reachable.\n\t\treturn\n\t}\n\tdefer h.p.tg.Done()\n\n\th.log.Println(\"New connection from \" + h.conn.RemoteAddr().String())\n\th.mu.Lock()\n\th.s, _ = newSession(h.p, h.conn.RemoteAddr().String())\n\th.mu.Unlock()\n\th.log.Println(\"New session: \" + sPrintID(h.s.SessionID))\n\tfor {\n\t\tm, err := h.parseRequest()\n\t\th.conn.SetReadDeadline(time.Time{})\n\t\t// if we timed out\n\t\tif m == nil && err == nil {\n\t\t\tcontinue\n\t\t\t// else if we got a request\n\t\t} else if m != nil {\n\t\t\terr = h.handleRequest(m)\n\t\t\tif err != nil {\n\t\t\t\th.log.Println(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// else if we got an error\n\t\t} else if err != nil {\n\t\t\th.log.Println(err)\n\t\t\treturn\n\t\t}\n\t}\n}", "func Listen(h host.Host, tag protocol.ID) (net.Listener, error) {\n\tctx, cancel := context.WithCancel(context.Background())\n\n\tl := &listener{\n\t\thost: h,\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\ttag: tag,\n\t\tstreamCh: make(chan network.Stream),\n\t}\n\n\th.SetStreamHandler(tag, func(s network.Stream) {\n\t\tselect {\n\t\tcase l.streamCh <- s:\n\t\tcase <-ctx.Done():\n\t\t\ts.Reset()\n\t\t}\n\t})\n\n\treturn l, nil\n}", "func (handler *Handler) Listen() error {\n\treturn handler.engine.Start(g.GetConfig().ListenAddr)\n}", "func (server *Server) Listen(port string) {\n\tlog.Println(\"Starting server...\")\n\tlistener, err := net.Listen(\"tcp\", \":\"+port)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tserver.listener = listener\n\tserver.wg.Add(1)\n\tdefer server.wg.Done()\n\t\n\t// create socket socketClient manager\n\tsocketClientManager := SocketClientManager{\n\t\tclients: make(map[*SocketClient]bool),\n\t\tregister: make(chan *SocketClient),\n\t\tunregister: make(chan *SocketClient),\n\t}\n\n\tgo socketClientManager.Start()\n\n\tlog.Println(\"Server listening on port \" + port + \"!\")\n\n\tfor {\n\t\tconnection, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tselect {\n\t\t\tcase <-server.quit:\n\t\t\t return\n\t\t\tdefault:\n\t\t\t log.Println(\"Accept error:\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tserver.wg.Add(1)\n\t\t\tsocketClient := &SocketClient{Socket: connection, Data: make(chan []byte)}\n\t\t\tsocketClientManager.register <- socketClient\n\t\t\tgo func() {\n\t\t\t\tsocketClientManager.receive(socketClient, server)\n\t\t\t\tserver.wg.Done()\n\t\t\t}()\n\t\t\tgo socketClientManager.send(socketClient)\n\t\n\t\t\tsocketClientResponses := server.handleSendToHome(socketClient)\n\t\t\tfor _, socketClientResponse := range socketClientResponses {\n\t\t\t\tgo socketClientResponse.send()\n\t\t\t}\n\t\t}\n\t}\n}", "func (d *Daemon) Listen() (err error) {\n\tl, err := net.Listen(\"unix\", filepath.Join(d.supDir, \"immortal.sock\"))\n\tif err != nil {\n\t\treturn\n\t}\n\trouter := violetear.New()\n\trouter.Verbose = false\n\trouter.HandleFunc(\"/\", d.HandleStatus)\n\trouter.HandleFunc(\"/signal/*\", d.HandleSignal)\n\t// close socket when process finishes (after cmd.Wait())\n\tsrv := &http.Server{Handler: router}\n\td.wg.Add(1)\n\tgo func() {\n\t\tdefer d.wg.Done()\n\t\terr := srv.Serve(l)\n\t\tlog.Printf(\"removing [%s/immortal.sock] %v\\n\", d.supDir, err)\n\t}()\n\tgo func(quit chan struct{}) {\n\t\t<-quit\n\t\tif err := srv.Close(); err != nil {\n\t\t\tlog.Printf(\"HTTP socket close error: %v\", err)\n\t\t}\n\t}(d.quit)\n\treturn\n}", "func (bot *Bot) Listen() error {\n\tfmt.Println(\"Listening for messages...\")\n\n\tfor {\n\t\tm, err := bot.receive()\n\t\tif err != nil {\n\t\t\tfmt.Println(err.Error())\n\t\t\tbot.reply(m, err.Error())\n\t\t\tcontinue\n\t\t}\n\n\t\tif m == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\thandler, ok := bot.handlers[m.Command]\n\t\tif !ok {\n\t\t\tbot.reply(m, fmt.Sprintf(\"No handler for %s\", m.Command))\n\t\t\tcontinue\n\t\t}\n\n\t\t// TODO: Don't let this blow up\n\t\tresp := handler.Fn(m)\n\n\t\tbot.reply(m, resp)\n\t}\n}", "func Listen(_port int) {\n\tgameserver.port = _port\n\n\tlog.Info(\"GameServer\", \"Listen\", \"Listening for connections on port: %d\", _port)\n\n\thttp.Handle(\"/puserver\", websocket.Handler(clientConnection))\n\terr := http.ListenAndServe(fmt.Sprintf(\":%d\", _port), nil)\n\tif err != nil {\n\t\tpanic(\"ListenAndServe: \" + err.Error())\n\t}\n}", "func Listen(settings args.NetworkConfig) {\n\tfmt.Printf(\"Server Listening on %s\\n\", settings.Port)\n\tport := \":\" + settings.Port\n\tserver, err := net.Listen(\"tcp\", port)\n\n\tif err != nil {\n\t\tlog.Print(err)\n\t\treturn\n\t}\n\n\tdefer server.Close()\n\n\tfor {\n\t\tclient, err := server.Accept()\n\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t\treturn\n\t\t}\n\n\t\t// TODO limit number of goroutines\n\t\tgo onClient(client)\n\t}\n}", "func (z *Zipkin) Listen(ln net.Listener, acc telegraf.Accumulator) {\n\tif err := z.server.Serve(ln); err != nil {\n\t\t// Because of the clean shutdown in `(*Zipkin).Stop()`\n\t\t// We're expecting a server closed error at some point\n\t\t// So we don't want to display it as an error.\n\t\t// This interferes with telegraf's internal data collection,\n\t\t// by making it appear as if a serious error occurred.\n\t\tif err != http.ErrServerClosed {\n\t\t\tacc.AddError(fmt.Errorf(\"error listening: %w\", err))\n\t\t}\n\t}\n}", "func (h *Handler) Listen() error {\n\treturn h.engine.Run(util.GetConfig().ListenAddr)\n}", "func (broker *Broker) Listen() {\n\tfor {\n\t\tselect {\n\t\tcase s := <-broker.newClients:\n\n\t\t\t// A new client has connected.\n\t\t\t// Register their message channel\n\t\t\tbroker.clients[s] = struct{}{}\n\t\t\tlog.Printf(\"Client added. %d registered clients\", len(broker.clients))\n\t\tcase s := <-broker.closingClients:\n\n\t\t\t// A client has dettached and we want to\n\t\t\t// stop sending them messages.\n\t\t\tdelete(broker.clients, s)\n\t\t\tlog.Printf(\"Removed client. %d registered clients\", len(broker.clients))\n\t\tcase event := <-broker.Notifier:\n\n\t\t\t// We got a new event from the outside!\n\t\t\t// Send event to all connected clients\n\t\t\tfor clientMessageChan := range broker.clients {\n\t\t\t\tselect {\n\t\t\t\tcase clientMessageChan <- event:\n\t\t\t\tcase <-time.After(patience):\n\t\t\t\t\tlog.Print(\"Skipping client.\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (observer *Observer) Listen() {\n\tobserver.connector.Listen(int(define.ObserverPort))\n}", "func (s *Service) Listen() (err error) {\n\t// Initialize error channel\n\terrC := make(chan error, 2)\n\t// Listen to HTTP (if needed)\n\tgo s.listenHTTP(errC)\n\t// Listen to HTTPS (if needed)\n\tgo s.listenHTTPS(errC)\n\t// Return any error which may come down the error channel\n\treturn <-errC\n}", "func (s *Server) Listen(protoFunc ...socket.ProtoFunc) error {\n\treturn s.peer.Listen(protoFunc...)\n}", "func (l *Listener) Listen(messenger Messenger) error {\r\n\tl.Lock()\r\n\tif l.isRunning == true {\r\n\t\tlog.Println(\"[ERROR] Attempt to start listener while running\")\r\n\t\tl.Unlock()\r\n\t\treturn errors.New(\"Alreading running!\")\r\n\t}\r\n\tl.isRunning = true\r\n\tl.Unlock()\r\n\tlog.Println(\"[DEBUG] Starting listener\")\r\n\r\n\trecvChan := make(chan Message)\r\n\tfor {\r\n\t\tgo messenger.Recv(recvChan)\r\n\t\tstopped := l.waitForRecvOrStop(recvChan)\r\n\t\tif stopped == true {\r\n\t\t\tlog.Println(\"[DEBUG] Stop received for listener\")\r\n\t\t\tclose(recvChan)\r\n\t\t\treturn nil\r\n\t\t}\r\n\t}\r\n}", "func Listen(port int) Probes {\n\tif port <= 0 {\n\t\treturn new(nullListener)\n\t}\n\n\tp := &listener{\n\t\talive: new(atomic.Value),\n\t\tready: new(atomic.Value),\n\t\tserver: &http.Server{\n\t\t\tAddr: fmt.Sprintf(\":%d\", port),\n\t\t},\n\t}\n\tp.alive.Store(true)\n\tp.ready.Store(false)\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"/healthz\", newHandler(p.alive))\n\tmux.HandleFunc(\"/readyz\", newHandler(p.ready))\n\tp.server.Handler = mux\n\n\tp.wg.Add(1)\n\tgo func() {\n\t\tdefer p.wg.Done()\n\t\tp.server.ListenAndServe()\n\t}()\n\n\treturn p\n}", "func (s *LocalServer) Listen() error {\n\tif err := s.fs.MkdirAll(filepath.Dir(s.sockPath), 0700); err != nil {\n\t\treturn err\n\t}\n\n\tgorrentReadWriter := gorrent.NewReadWriter()\n\thandler := handlers.NewLocalHTTP(s.store, gorrentReadWriter)\n\n\trouter := mux.NewRouter()\n\trouter.HandleFunc(\"/add\", handler.Add).Methods(\"POST\")\n\trouter.HandleFunc(\"/remove/{hash}\", handler.Remove).Methods(\"GET\")\n\trouter.HandleFunc(\"/info/{hash}\", handler.Info).Methods(\"GET\")\n\trouter.HandleFunc(\"/\", handler.List).Methods(\"GET\")\n\n\tlogger := peer.NewLoggerMiddleware()\n\trouter.Use(logger.Handle)\n\n\tlocalServer := http.Server{\n\t\tHandler: router,\n\t}\n\n\ts.fs.Remove(s.sockPath)\n\tconn, err := net.Listen(\"unix\", s.sockPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\t// Start local peer server\n\tlog.Printf(\"local server listening on unix://%s\", s.sockPath)\n\n\treturn localServer.Serve(conn)\n}", "func (notifee *Notifee) Listen(network.Network, multiaddr.Multiaddr) {}", "func (c *Client) Listen() {\n\tc.conn.SetReadLimit(maxMessageSize)\n\tc.conn.SetReadDeadline(time.Now().Add(pongWait))\n\tc.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })\n\n\tdefer func() {\n\t\tdelete(c.server.clients, c)\n\t\tc.conn.Close()\n\t}()\n\n\tfor {\n\t\t_, message, err := c.conn.ReadMessage()\n\t\tif err != nil {\n\t\t\tif websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {\n\t\t\t\tlog.Printf(\"error: %v\", err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tmessage = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))\n\n\t\tsite := &checker.Site{\n\t\t\tURL: string(message),\n\t\t}\n\t\tsite.Validate()\n\t\tif \"\" != site.Error {\n\t\t\tc.send <- site.Marshal()\n\t\t} else {\n\t\t\tc.sites[site] = true\n\t\t}\n\t}\n}", "func (s *Server) Listen() error {\n\treturn s.hs.Serve(s.ln)\n}", "func (s *Server) Listen() {\n\tif s.logs != nil {\n\t\ts.logs.Info(fmt.Sprintf(\"Listening at %s\", s.addr))\n\t}\n\n\ts.httpServer.ListenAndServe()\n}", "func (h *Host) threadedListen(closeChan chan struct{}) {\n\tdefer close(closeChan)\n\n\t// Receive connections until an error is returned by the listener. When an\n\t// error is returned, there will be no more calls to receive.\n\tfor {\n\t\t// Block until there is a connection to handle.\n\t\tconn, err := h.listener.Accept()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tgo h.threadedHandleConn(conn)\n\n\t\t// Soft-sleep to ratelimit the number of incoming connections.\n\t\tselect {\n\t\tcase <-h.tg.StopChan():\n\t\tcase <-time.After(rpcRatelimit):\n\t\t}\n\t}\n}", "func (ds *DrawServer) Listen() error {\n\tgo ds.listenUDP()\n\thttp.HandleFunc(\"/\", ds.canvas)\n\thttp.Handle(\"/static/\", http.StripPrefix(\"/static/\", http.FileServer(http.Dir(\"static\"))))\n\thttp.HandleFunc(\"/ws\", ds.newWs)\n\thttp.HandleFunc(\"/lines\", ds.getLines)\n\treturn http.ListenAndServe(fmt.Sprintf(\":%s\", ds.port), nil)\n}", "func Listen(senderId, apiKey string, h MessageHandler, stop <-chan bool) error {\n\tcl, err := newXmppFcmClient(senderId, apiKey)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating xmpp client>%v\", err)\n\t}\n\treturn cl.listen(h, stop)\n}", "func (s *Server) Run() error {\n\tlogging.Server(fmt.Sprintf(\"Starting %s Listener at %s:%d\", s.Protocol, s.Interface, s.Port))\n\n\ttime.Sleep(45 * time.Millisecond) // Sleep to allow the shell to start up\n\tif s.psk == \"reaper\" {\n\t\tfmt.Println()\n\t\tmessage(\"warn\", \"Listener was started using \\\"reaper\\\" as the Pre-Shared Key (PSK) allowing anyone\"+\n\t\t\t\" decrypt message traffic.\")\n\t\tmessage(\"note\", \"Consider changing the PSK by using the -psk command line flag.\")\n\t}\n\tmessage(\"note\", fmt.Sprintf(\"Starting %s listener on %s:%d\", s.Protocol, s.Interface, s.Port))\n\n\tif s.Protocol == \"h2\" {\n\t\tserver := s.Server.(*http.Server)\n\n\t\tdefer func() {\n\t\t\terr := server.Close()\n\t\t\tif err != nil {\n\t\t\t\tm := fmt.Sprintf(\"There was an error starting the %s server:\\r\\n%s\", s.Protocol, err.Error())\n\t\t\t\tlogging.Server(m)\n\t\t\t\tmessage(\"warn\", m)\n\t\t\t\treturn\n\t\t\t}\n\t\t}()\n\t\tgo logging.Server(server.ListenAndServeTLS(s.Certificate, s.Key).Error())\n\t\treturn nil\n\t} else if s.Protocol == \"hq\" {\n\t\tserver := s.Server.(*h2quic.Server)\n\n\t\tdefer func() {\n\t\t\terr := server.Close()\n\t\t\tif err != nil {\n\t\t\t\tm := fmt.Sprintf(\"There was an error starting the hq server:\\r\\n%s\", err.Error())\n\t\t\t\tlogging.Server(m)\n\t\t\t\tmessage(\"warn\", m)\n\t\t\t\treturn\n\t\t\t}\n\t\t}()\n\t\tgo logging.Server(server.ListenAndServeTLS(s.Certificate, s.Key).Error())\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"%s is an invalid server protocol\", s.Protocol)\n}", "func (c *MiningClient) Listen(cancel context.CancelFunc) {\n\tfLog := log.WithField(\"func\", \"MiningClient.Listen()\")\n\tfor {\n\t\tvar m NetworkMessage\n\t\terr := c.decoder.Decode(&m)\n\t\tif err != nil {\n\t\t\tc.ConnectionLost(fmt.Errorf(\"decode: %s\", err.Error()))\n\t\t}\n\n\t\tswitch m.NetworkCommand {\n\t\tcase CoordinatorError:\n\t\t\t// Any non-regular error message we want to send to the clients comes here.\n\t\t\tevt, ok := m.Data.(ErrorMessage)\n\t\t\tif ok && evt.Error != \"\" {\n\t\t\t\tfLog.WithField(\"evt\", \"error\").WithError(fmt.Errorf(evt.Error)).Error(\"error from coordinator\")\n\t\t\t}\n\t\tcase FactomEvent:\n\t\t\tevt := m.Data.(common.MonitorEvent)\n\n\t\t\t// Drain anything that was left over\n\t\t\tif evt.Minute == 1 {\n\t\t\t\tc.OPRMaker.Drain()\n\t\t\t}\n\n\t\t\tc.Monitor.FakeNotifyEvt(evt)\n\t\t\tfLog.WithField(\"evt\", \"factom\").\n\t\t\t\tWithFields(log.Fields{\n\t\t\t\t\t\"height\": evt.Dbht,\n\t\t\t\t\t\"minute\": evt.Minute,\n\t\t\t\t}).Debug(\"network received alert\")\n\t\tcase GraderEvent:\n\t\t\tevt := m.Data.(opr.OPRs)\n\t\t\tc.Grader.EmitFakeEvent(evt)\n\t\tcase ConstructedOPR:\n\t\t\tdevt, ok := m.Data.(opr.OraclePriceRecord)\n\t\t\tif !ok {\n\t\t\t\t// An error has occurred\n\t\t\t\tc.OPRMaker.RecOPR(nil)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tevt := &devt\n\n\t\t\t// We need to put our data in it\n\t\t\tid, _ := c.config.String(\"Miner.IdentityChain\")\n\t\t\tevt.FactomDigitalID = id\n\n\t\t\taddr, _ := c.config.String(common.ConfigCoinbaseAddress)\n\t\t\tevt.CoinbaseAddress = addr\n\t\t\tevt.OPRHash = nil // Reset the oprhash since we changed some fields\n\n\t\t\tc.OPRMaker.RecOPR(evt)\n\t\tcase Ping:\n\t\t\terr := c.encoder.Encode(NewNetworkMessage(Pong, nil))\n\t\t\tif err != nil {\n\t\t\t\tfLog.WithField(\"evt\", \"ping\").WithError(err).Error(\"failed to pong\")\n\t\t\t}\n\t\tcase SecretChallenge:\n\t\t\t// Respond to the challenge with our secret\n\t\t\tchallenge, ok := m.Data.(AuthenticationChallenge)\n\t\t\tif !ok {\n\t\t\t\tfLog.Errorf(\"server did not send a proper challenge\")\n\t\t\t\tcancel() // Cancel mining\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tsecret, err := c.config.String(common.ConfigCoordinatorSecret)\n\t\t\tif err != nil {\n\t\t\t\t// Do not return here, let the empty secret fail the challenge.\n\t\t\t\tfLog.WithError(err).Errorf(\"client is missing coordinator secret\")\n\t\t\t}\n\n\t\t\t// Challenge Resp is sha256(secret+challenge)\n\t\t\tresp := sha256.Sum256([]byte(secret + challenge.Challenge))\n\t\t\tchallenge.Response = fmt.Sprintf(\"%x\", resp)\n\t\t\terr = c.encoder.Encode(NewNetworkMessage(SecretChallenge, challenge))\n\t\t\tif err != nil {\n\t\t\t\tfLog.WithError(err).Errorf(\"failed to respond to challenge\")\n\t\t\t\tcancel()\n\t\t\t\treturn\n\t\t\t}\n\t\tcase RejectedConnection:\n\t\t\t// This means the server rejected us. Probably due to a failed challenge\n\t\t\tfLog.Errorf(\"Our connection to the coordinator was rejected. This is most likely due to failing the \" +\n\t\t\t\t\"authentication challenge. Ensure this miner has the same secret as the coordinator, and try again.\")\n\t\t\tcancel()\n\t\t\treturn\n\t\tcase Pong:\n\t\t\t// Do nothing\n\t\tdefault:\n\t\t\tfLog.WithField(\"evt\", \"??\").WithField(\"cmd\", m.NetworkCommand).Warn(\"unrecognized message\")\n\t\t}\n\n\t}\n}", "func (b *Bootstrapper) Listen(cfgs ...iris.Configurator) {\n\t// Type asserting host address and applying default if not provided\n\taddr := b.Application.ConfigurationReadOnly().GetOther()[\"host\"].(string)\n\n\tb.Run(iris.Addr(addr), cfgs...)\n}", "func (srv *RPCService) Listen(req *rpc.ListenRequest, stream rpc.StripeCLI_ListenServer) error {\n\tdeviceName, err := srv.cfg.UserCfg.Profile.GetDeviceName()\n\tif err != nil {\n\t\treturn status.Error(codes.Unauthenticated, err.Error())\n\t}\n\n\tkey, err := srv.cfg.UserCfg.Profile.GetAPIKey(req.Live)\n\tif err != nil {\n\t\treturn status.Error(codes.Unauthenticated, err.Error())\n\t}\n\tapiBase, _ := url.Parse(stripe.DefaultAPIBaseURL)\n\n\tlogger := log.StandardLogger()\n\tproxyVisitor := createProxyVisitor(&stream)\n\tproxyOutCh := make(chan websocket.IElement)\n\n\tctx, cancel := context.WithCancel(stream.Context())\n\tdefer cancel()\n\n\tp, err := createProxy(ctx, &proxy.Config{\n\t\tClient: &stripe.Client{\n\t\t\tAPIKey: key,\n\t\t\tBaseURL: apiBase,\n\t\t},\n\t\tDeviceName: deviceName,\n\t\tForwardURL: req.ForwardTo,\n\t\tForwardHeaders: req.Headers,\n\t\tForwardConnectURL: req.ForwardConnectTo,\n\t\tForwardConnectHeaders: req.ConnectHeaders,\n\t\tUseConfiguredWebhooks: req.UseConfiguredWebhooks,\n\t\tWebSocketFeature: webhooksWebSocketFeature,\n\t\tUseLatestAPIVersion: req.Latest,\n\t\tSkipVerify: req.SkipVerify,\n\t\tLog: logger,\n\t\tEvents: req.Events,\n\t\tOutCh: proxyOutCh,\n\n\t\t// Hidden for debugging\n\t\tNoWSS: false,\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo p.Run(ctx)\n\n\tfor {\n\t\tselect {\n\t\tcase e := <-proxyOutCh:\n\t\t\terr := e.Accept(proxyVisitor)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase <-stream.Context().Done():\n\t\t\treturn stream.Context().Err()\n\t\t}\n\t}\n}", "func (h *RouterHandle) Listen(in *api.ListenRequest, stream api.Router_ListenServer) error {\n\tvar (\n\t\ttoken = (*token)(in.GetToken())\n\t)\n\n\tdesc, ok := token.getDesc()\n\tif !ok {\n\t\tlog.Warn(errInvTkn)\n\t\treturn nil\n\t}\n\n\tlogger := log.WithFields(log.Fields{\n\t\t\"token\": ((*api.Token)(token)).ToShort(),\n\t\t\"user\": desc.userID,\n\t\t\"image\": desc.image,\n\t})\n\n\tlogger.Info(\"Listen is requested\")\n\n\tbody, ok := desc.getBody()\n\tif !ok {\n\t\tlogger.Fatal(errNExists)\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-stream.Context().Done():\n\t\t\t\treturn\n\t\t\tcase sig := <-body.transmit:\n\t\t\t\tstream.Send(&sig)\n\t\t\t}\n\t\t}\n\t}()\n\n\t<-stream.Context().Done()\n\tlogger.Info(\"stops listening\")\n\treturn nil\n}", "func (a *Agent) listen() {\n\t// // fmt.Println(\"[INFO] agent.listen()\")\n\n\tdefer a.listener.Close()\n\tfor {\n\t\tconn, err := a.listener.Accept()\n\t\tif err != nil {\n\t\t\t// warn := fmt.Sprintf(\"listener failed to accept new connection : %v\", err)\n\t\t\t// a.warningCh <- warn\n\t\t\tcontinue\n\t\t}\n\t\ta.logger.Printf(\"[INFO] node '%v' : recieved an incomming connection from peer with address %v\", a.ID(), conn.LocalAddr().String())\n\t\terr = a.swarm.Handshake(conn)\n\t\tif err != nil {\n\t\t\t// a.warningCh <- err.Error()\n\t\t\t// closing connection\n\t\t\tconn.Close()\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func (trans *HTTPTransport) Listen() error {\n\ttrans.mux.HandleFunc(RPCPath, trans.handle)\n\tip, err := utils.GetExternalIP()\n\tif err != nil {\n\t\treturn err\n\t}\n\tlistner, err := net.Listen(\"tcp\", fmt.Sprintf(\"%s:0\", ip))\n\tif err != nil {\n\t\treturn err\n\t}\n\ttrans.addr = fmt.Sprintf(\"http://%s\", listner.Addr().String())\n\tlog.Info(\"Listening on \", trans.addr)\n\tgo http.Serve(listner, trans.mux)\n\ttrans.listening = true\n\treturn nil\n}", "func Listen(addr string, privateKeyPath string) (net.Listener, error) {\n\tlistener, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfig, err := serverConfig(privateKeyPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &server{listener: listener, config: config}, nil\n}", "func (s *Server) Run(ctx context.Context) {\n\tlog.Trace(\"Starting Eco server\")\n\n\tgo func() {\n\t\t<-ctx.Done()\n\t\ts.listener.Close()\n\t}()\n\n\ts.ctx = ctx\n\t// Start serving.\n\tlog.Infof(\"Eco server running\")\n\tfor {\n\t\tconn, err := s.listener.Accept()\n\t\tif err != nil {\n\t\t\tvar opErr *net.OpError\n\t\t\tif errors.As(err, &opErr) && strings.Contains(opErr.Error(), \"use of closed network connection\") {\n\t\t\t\t// Probably a normal shutdown\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Errorf(\"Accept error: %v\", err)\n\t\t\treturn\n\t\t}\n\t\tif ctx.Err() != nil {\n\t\t\treturn\n\t\t}\n\t\tgo s.handleRequest(conn)\n\t}\n}", "func (s *Cluster) Listen() {\n\n\t// Every few seconds, attempt to reinforce our cluster structure by\n\t// initiating connections with all of our peers.\n\ttools.Repeat(s.update, 5*time.Second, s.closing)\n\n\t// Start the router\n\ts.router.Start()\n}", "func Listen(laddr net.Addr, raddr string, config *Config) (net.Listener, <-chan error, error) {\n\treturn ListenContext(context.Background(), laddr, raddr, config)\n}", "func (handler *BotHandler) listen() {\n\thandler.McRunner.WaitGroup.Add(1)\n\tdefer handler.McRunner.WaitGroup.Done()\n\tfor {\n\t\tselect {\n\t\tdefault:\n\t\t\theader := new(header)\n\t\t\terr := handler.sock.ReadJSON(header)\n\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tfmt.Println(\"Killing websocket handler goroutines due to error.\")\n\t\t\t\thandler.killChannel <- true\n\t\t\t\thandler.killChannel <- true\n\t\t\t\thandler.killChannel <- true\n\t\t\t\thandler.sock.Close()\n\t\t\t\thandler.connectionAlive = false\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tswitch header.Type {\n\t\t\tcase \"cmd\":\n\t\t\t\tcommand := new(command)\n\t\t\t\terr := json.Unmarshal(header.Data, command)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\thandler.McRunner.CommandChannel <- command.Command\n\t\t\t}\n\t\tcase <-handler.killChannel:\n\t\t\treturn\n\t\t}\n\n\t}\n}", "func listenLoop(lis net.Listener, grpcServer *grpc.Server, clientChan chan *grpc.ClientConn) {\n\tfor {\n\t\t// accept a new connection and set up a yamux session on it\n\t\tconn, err := lis.Accept()\n\t\tif err != nil {\n\t\t\treturn // chan is prob shut down\n\t\t}\n\n\t\t// server session will be used to multiplex both clients & servers\n\t\tsession, err := yamux.Server(conn, nil)\n\t\tif err != nil {\n\t\t\tconn.Close() // close conn and retry\n\t\t\tcontinue\n\t\t}\n\n\t\t// start grpc server using yamux session (which implements net.Listener)\n\t\tgo grpcServer.Serve(session)\n\n\t\t// create new client connection and dialer for this session\n\t\tdialer := NewYamuxDialer()\n\t\tdialer.SetSession(session)\n\t\tgconn, _ := grpc.Dial(\"localhost:50000\", grpc.WithInsecure(), grpc.WithDialer(dialer.Dial))\n\n\t\tgo func() {\n\t\t\t// wait for session close and close related gconn\n\t\t\t<-session.CloseChan()\n\t\t\tgconn.Close()\n\t\t}()\n\n\t\tgo func() {\n\t\t\t// close session if gconn is closed for any reason\n\t\t\tstate := gconn.GetState()\n\t\t\tfor {\n\t\t\t\tswitch state {\n\t\t\t\tcase connectivity.Shutdown:\n\t\t\t\t\tgconn.Close()\n\t\t\t\t\tsession.Close()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tgconn.WaitForStateChange(context.Background(), gconn.GetState())\n\t\t\t\tstate = gconn.GetState()\n\t\t\t}\n\t\t}()\n\n\t\tclientChan <- gconn // publish gconn\n\t}\n}", "func (r *EndpointRegistry) Listen(listener Listener) {\n\tif !r.OnCloseAlways(func() {\n\t\tif err := listener.Close(); err != nil {\n\t\t\tr.Log().Debugf(\"EndpointRegistry.Listen: closing listener OnClose: %v\", err)\n\t\t}\n\t}) {\n\t\treturn\n\t}\n\n\t// Start listener and accept all incoming peer connections, writing them to\n\t// the registry.\n\tfor {\n\t\tconn, err := listener.Accept(r.ser)\n\t\tif err != nil {\n\t\t\tr.Log().Debugf(\"EndpointRegistry.Listen: Accept() loop: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\tr.Log().Debug(\"EndpointRegistry.Listen: setting up incoming connection\")\n\t\t// setup connection in a separate routine so that new incoming\n\t\t// connections can immediately be handled.\n\t\tgo func() {\n\t\t\tif err := r.setupConn(conn); err != nil {\n\t\t\t\tlog.WithError(err).Error(\"EndpointRegistry could not setup wire/net.Conn\")\n\t\t\t}\n\t\t}()\n\t}\n}", "func (c *SocketClient) Listen(requestCh chan *Message) {\n\tgo c.listenWrite()\n\tc.listenRead(requestCh)\n}", "func Listen(laddr string, keyPair *pubkeycrypto.KeyPair) (*Listener, error) {\n\ttcpListener, err := net.Listen(\"tcp\", laddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlistener := &Listener{\n\t\ttcpListener: tcpListener,\n\t\tkeyPair: keyPair,\n\t\testablishedConnectionsChan: make(chan *Connection),\n\t\tshutdownChan: make(chan struct{}),\n\t}\n\tgo listener.beginAcceptingConnections()\n\treturn listener, nil\n}", "func (s Server) Listen() error {\n\tlog.WithField(\"address\", s.opts.ListenAddress).Info(\"Now serving.\")\n\treturn http.ListenAndServeTLS(s.opts.ListenAddress, secrets.FilenameTLSCertificate, secrets.FilenameTLSKey, nil)\n}", "func (server *TcpBridgeServer) Listen(callbacks ...func(manager *ConnectionManager)) error {\n\n\tif server.Port <= 0 || server.Port > 65535 {\n\t\treturn errors.New(\"invalid port range: \" + strconv.Itoa(server.Port))\n\t}\n\n\tlistener, e1 := net.Listen(\"tcp\", \":\"+strconv.Itoa(server.Port))\n\tif e1 != nil {\n\t\tpanic(e1)\n\t\treturn nil\n\t}\n\tlogger.Info(\"server listening on port:\", server.Port)\n\t// keep accept connections.\n\tfor {\n\t\tconn, e1 := listener.Accept()\n\t\tmanager := &ConnectionManager{\n\t\t\tConn: conn,\n\t\t\tSide: ServerSide,\n\t\t}\n\t\tif e1 != nil {\n\t\t\tlogger.Error(\"accept new conn error:\", e1)\n\t\t\tmanager.Destroy()\n\t\t} else {\n\t\t\tlogger.Debug(\"accept a new connection from remote addr:\", conn.RemoteAddr().String())\n\t\t\tconnectionPool.Exec(func() {\n\t\t\t\tmanager.State = StateConnected\n\t\t\t\tcommon.Try(func() {\n\t\t\t\t\tServe(manager, callbacks...)\n\t\t\t\t}, func(i interface{}) {\n\t\t\t\t})\n\t\t\t})\n\t\t}\n\t}\n\treturn nil\n}", "func (bs *NpvizServer) Listen(port uint) {\n\thttp.Handle(\"/\", bs.router)\n\tserverAddr := fmt.Sprintf(\"0.0.0.0:%d\", port)\n\tlogrus.Info(fmt.Sprintf(\"Starting HTTP server at %s\", serverAddr))\n\tlogrus.Info(http.ListenAndServe(serverAddr, bs.router))\n}", "func (ln *Listener) Listen(t string, addr string) {\n\n\t// Declare TCP listening server\n\tlis, err := net.Listen(t, addr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"Listening to %s-%s\\n\", t, addr)\n\n\t// Main loop\n\tfor {\n\t\t// Accept incoming connection\n\t\tc, err := lis.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t} else {\n\t\t\t// Connection accepted, create client and spawn associated goroutines\n\t\t\tclt := NewClient(c, ln.core)\n\t\t\tgo clt.jsonIn()\n\t\t\tgo clt.jsonOut()\n\t\t}\n\t}\n}", "func (c *Client) Listen() {\n\tgo c.listenWrite()\n\tc.listenRead()\n}", "func (c *Channel) listen() {\n\tfor {\n\t\tselect {\n\t\tcase msg := <-c.in:\n\t\t\tc.sendToChannel(msg)\n\t\tcase j := <-c.join:\n\t\t\tc.addUser(j)\n\t\tcase p := <-c.part:\n\t\t\tc.removeUser(p)\n\t\t}\n\t}\n}", "func (bs *BackendServer) Listen() (err error) {\n\t//var tempDelay time.Duration // how long to sleep on accept failure\n\n\taddr, err := ParseAddr(bs.Addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tutils.Logger.Info(\"net is %s and ipport %s\", addr.Network, addr.IPPort)\n\n\tif addr.Network != \"unix\" {\n\t\tutils.Logger.Error(\"Error Inner Address, Should be unix://\")\n\t\terr = ErrAddr\n\t\treturn\n\t}\n\tos.Remove(addr.IPPort)\n\tl, err := net.Listen(\"unix\", addr.IPPort)\n\tif err != nil {\n\t\tutils.Logger.Error(err.Error())\n\t\treturn\n\t}\n\tln := l.(*net.UnixListener)\n\tgo bs.AcceptAndServe(ln)\n\treturn\n}", "func (g *Gateway) listen() {\n\tfor {\n\t\tconn, err := g.listener.Accept()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tgo g.acceptConn(conn)\n\t}\n}", "func (cg *CandlesGroup) listen() {\n\tgo func() {\n\t\tfor msg := range cg.bus.dch {\n\t\t\tcg.parseMessage(msg)\n\t\t}\n\t}()\n\tgo func() {\n\t\tfor err := range cg.bus.ech {\n\t\t\tlog.Printf(\"[BITFINEX] Error listen: %+v\", err)\n\t\t\tcg.restart()\n\t\t\treturn\n\t\t}\n\t}()\n}", "func (self *Client) Listen() {\n\tgo self.listenWrite()\n\tself.listenRead()\n}", "func (me *Server) Listen() {\n\taddress := net.TCPAddr{IP: net.ParseIP(\"127.0.0.1\"), Port: me.port}\n\tlistener, err := net.ListenTCP(\"tcp\", &address)\n\tdefer listener.Close()\n\tif err != nil {\n\t\tif strings.Index(err.Error(), \"in use\") == -1 {\n\t\t\tpanic(err)\n\t\t}\n\t\tlog.Printf(\"Already listening\")\n\t\treturn\n\t}\n\tlog.Printf(\"Listening on port %d\", me.port)\n\tgo func() {\n\t\tfor {\n\t\t\tconn, err := listener.AcceptTCP()\n\t\t\tif err != nil {\n\t\t\t\tif strings.Index(err.Error(), \"closed network connection\") == -1 {\n\t\t\t\t\tlog.Printf(\"Error accept: %s\", err.Error())\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Printf(\"Connected: %v\", conn)\n\t\t\tgo me.handleConnection(conn)\n\t\t}\n\t}()\n\tsigs := make(chan os.Signal, 1)\n\tsignal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)\n\t<-sigs\n}", "func (s *Service) DoListen(ctx context.Context, timeout time.Duration) error {\n\tvar wg sync.WaitGroup\n\tdefer func() { s.teardown(); wg.Wait() }()\n\n\ts.mutex.Lock()\n\tl := s.listener\n\ts.mutex.Unlock()\n\n\tif l == nil {\n\t\treturn fmt.Errorf(\"No listener set\")\n\t}\n\n\ts.mutex.Lock()\n\ts.running = true\n\ts.mutex.Unlock()\n\n\tfor s.running {\n\t\tif timeout != 0 {\n\t\t\tif err := s.refreshTimeout(timeout); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tconn, err := l.Accept()\n\t\tif err != nil {\n\t\t\tif err.(net.Error).Timeout() {\n\t\t\t\ts.mutex.Lock()\n\t\t\t\tif s.conncounter == 0 {\n\t\t\t\t\ts.mutex.Unlock()\n\t\t\t\t\treturn ServiceTimeoutError{}\n\t\t\t\t}\n\t\t\t\ts.mutex.Unlock()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !s.running {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\ts.mutex.Lock()\n\t\ts.conncounter++\n\t\ts.mutex.Unlock()\n\t\twg.Add(1)\n\t\tgo s.handleConnection(ctx, conn, &wg)\n\t}\n\n\treturn nil\n}", "func (l *Listener) Listen(received chan<- *StorageRequest, done <-chan TerminationRequest, shutdownTimeout time.Duration) (uintptr, error) {\n\tlog.Printf(\"listening: %s\", l.Socket)\n\n\twaitGroup := new(sync.WaitGroup)\n\tacceptFinished := make(chan bool, 0)\n\n\t// Accept connections in a goroutine, and add them to the WaitGroup.\n\tgo func() {\n\t\tfor {\n\t\t\tconn, err := l.Socket.Accept()\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"error accepting connection: %s\", err)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tl.conns += 1\n\n\t\t\t// Handle each incoming connection in its own goroutine.\n\t\t\tlog.Printf(\"handling new connection from %s\", conn.RemoteAddr())\n\t\t\twaitGroup.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer waitGroup.Done()\n\t\t\t\tl.handleConnection(conn, received)\n\t\t\t\tlog.Printf(\"done handling new connection from %s\", conn.RemoteAddr())\n\t\t\t}()\n\t\t}\n\t\t// When we've broken out of the loop for any reason (errors, limit),\n\t\t// signal that we're done via the channel.\n\t\tacceptFinished <- true\n\t}()\n\n\tnewFd := 0\n\n\t// Wait for either a shutdown/reload request, or for the Accept() loop to\n\t// break on its own (from error or a limit).\n\tselect {\n\tcase req := <-done:\n\n\t\t// If we got a reload request, set up a file descriptor to pass to the\n\t\t// reloaded process.\n\t\tif req == Reload {\n\t\t\tfd, err := l.Socket.Fd()\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\n\t\t\t// If we don't dup the fd, closing it below (to break the Accept()\n\t\t\t// loop) will prevent us from being able to use it as a socket in\n\t\t\t// the child process.\n\t\t\tnewFd, err = syscall.Dup(int(fd))\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\n\t\t\t// If we don't mark the new fd as CLOEXEC, the child process will\n\t\t\t// inherit it twice (the second one being the one passed to\n\t\t\t// ExtraFiles).\n\t\t\tsyscall.CloseOnExec(newFd)\n\t\t}\n\n\t\tlog.Printf(\"closing listening socket\")\n\t\tif err := l.Socket.Close(); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\t// Wait for the Close() to break us out of the Accept() loop.\n\t\t<-acceptFinished\n\n\tcase <-acceptFinished:\n\t\t// If the accept loop is done on its own (e.g. not from a reload\n\t\t// request), fall through to do some cleanup.\n\t}\n\n\t// Wait for any open sesssions to finish, or time out.\n\tlog.Printf(\"waiting %s for open connections to finish\", shutdownTimeout)\n\tWaitWithTimeout(waitGroup, shutdownTimeout)\n\n\tclose(received)\n\n\treturn uintptr(newFd), nil\n}", "func (w *Worker) Listen() (err error) {\n\tif w.WorkerID == \"\" || w.RequestID == \"\" {\n\t\treturn errors.Errorf(\"workerID and requestID required\")\n\t}\n\tstream, err := w.eventStream()\n\tif err == nil {\n\t\tif err = stream.Start(); err != nil {\n\t\t\treturn\n\t\t}\n\t\tdefer stream.Stop()\n\t\tstream.Send(&rpc.StreamingMessage{\n\t\t\tContent: &rpc.StreamingMessage_StartStream{\n\t\t\t\tStartStream: &rpc.StartStream{\n\t\t\t\t\tWorkerId: w.WorkerID,\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t\tch := w.getChannel(stream)\n\t\tmsg, ok := stream.Recv()\n\t\tfor ok {\n\t\t\tswitch msgT := msg.Content.(type) {\n\t\t\tcase *rpc.StreamingMessage_StartStream:\n\t\t\t\tch.StartStream(msg.RequestId, msgT.StartStream)\n\t\t\tcase *rpc.StreamingMessage_WorkerInitRequest:\n\t\t\t\tch.InitRequest(msg.RequestId, msgT.WorkerInitRequest)\n\t\t\tcase *rpc.StreamingMessage_WorkerHeartbeat:\n\t\t\t\tch.Heartbeat(msg.RequestId, msgT.WorkerHeartbeat)\n\t\t\tcase *rpc.StreamingMessage_WorkerTerminate:\n\t\t\t\tch.Terminate(msg.RequestId, msgT.WorkerTerminate)\n\t\t\tcase *rpc.StreamingMessage_WorkerStatusRequest:\n\t\t\t\tch.StatusRequest(msg.RequestId, msgT.WorkerStatusRequest)\n\t\t\tcase *rpc.StreamingMessage_FileChangeEventRequest:\n\t\t\t\tch.FileChangeEventRequest(msg.RequestId, msgT.FileChangeEventRequest)\n\t\t\tcase *rpc.StreamingMessage_FunctionLoadRequest:\n\t\t\t\tch.FunctionLoadRequest(msg.RequestId, msgT.FunctionLoadRequest)\n\t\t\tcase *rpc.StreamingMessage_InvocationRequest:\n\t\t\t\tch.InvocationRequest(msg.RequestId, msgT.InvocationRequest)\n\t\t\tcase *rpc.StreamingMessage_InvocationCancel:\n\t\t\t\tch.InvocationCancel(msg.RequestId, msgT.InvocationCancel)\n\t\t\tcase *rpc.StreamingMessage_FunctionEnvironmentReloadRequest:\n\t\t\t\tch.FunctionEnvironmentReloadRequest(msg.RequestId, msgT.FunctionEnvironmentReloadRequest)\n\t\t\t}\n\t\t\tmsg, ok = stream.Recv()\n\t\t}\n\t}\n\treturn\n}", "func Listen(sc ServerConfig) {\n\tlistenSocket, er := zmq.NewSocket(zmq.DEALER)\n\tif er != nil {\n\t\tpanic (\"Unable to open socket for listening\")\n\t}\n\tdefer listenSocket.Close()\n\tlistenSocket.Bind(\"tcp://\" + sc.Url)\n\tlistenSocket.SetRcvtimeo(2*time.Second)\n\tfor {\n\t\tmsg, err := listenSocket.Recv(0)\n\t\tif err != nil {\n\t\t\tclose(sc.Input)\n\t\t\treturn\n\t\t} else {\n\t\t\tsc.N_msgRcvd++\n\t\t}\n\t\t\n\t\tmessage := new(Envelope)\n\t\tjson.Unmarshal([]byte(msg), message)\n\t\tsc.Input <- message\n\t}\n}", "func (s *Server) Listen() error {\n\tif s.hasListeners { // already done this\n\t\treturn nil\n\t}\n\n\tlistener, err := net.Listen(\"tcp\", fmt.Sprintf(\"%s:%d\", s.Host, s.Port))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\th, p, err := swag.SplitHostPort(listener.Addr().String())\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Host = h\n\ts.Port = p\n\ts.httpServerL = listener\n\n\ts.hasListeners = true\n\treturn nil\n}", "func (client *Client) Listen() {\n\tgo client.Read()\n\tgo client.Write()\n}", "func (g *Gatekeeper) Listen() error {\n\tmux := bone.New()\n\n\tmux.Post(\"/v0/machine/aws\", routes.AWSBootstrapRoute(g.defaults.Org, g.defaults.Team, g.api))\n\n\tg.s.Handler = loggingHandler(mux)\n\th := httpdown.HTTP{}\n\n\tvar err error\n\tg.hd, err = h.ListenAndServe(g.s)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn g.hd.Wait()\n}", "func (c *connection) listen() {\n\tc.group.Add(1)\n\n\tfor c.running {\n\t\tc.listener.SetDeadline(time.Now().Add(time.Millisecond * 500))\n\t\tconn, err := c.listener.AcceptTCP()\n\t\tif err == nil {\n\t\t\tc.addHost(conn)\n\t\t} else if !strings.HasSuffix(err.Error(), \"i/o timeout\") {\n\t\t\tpanic(\"Something crashed when we were accepting: \" + err.Error())\n\t\t}\n\t}\n\tc.listener.Close()\n\tc.group.Done()\n}", "func (s *service) Listen(req *pb.ListenRequest, server pb.API_ListenServer) error {\n\tlog.Debugf(\"received listen request for entity %s\", req.EntityID)\n\n\tstore, err := s.getStore(req.StoreID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmodel := store.GetModel(req.ModelName)\n\tif model == nil {\n\t\treturn status.Error(codes.NotFound, \"model not found\")\n\t}\n\n\tl, err := store.Listen(es.ListenOption{Model: req.ModelName, ID: core.EntityID(req.EntityID)})\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer l.Close()\n\n\tfor {\n\t\tselect {\n\t\tcase <-server.Context().Done():\n\t\t\treturn nil\n\t\tcase _, ok := <-l.Channel():\n\t\t\tif !ok {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\terr := model.ReadTxn(func(txn *es.Txn) error {\n\t\t\t\tvar res string\n\t\t\t\tif err := txn.FindByID(core.EntityID(req.EntityID), &res); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn server.Send(&pb.ListenReply{\n\t\t\t\t\tEntity: res,\n\t\t\t\t})\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n}", "func (res *respondent) Listen(path string) error {\n\treturn nil\n}", "func (c *Client) Listen() error {\n\n\tlog.Println(\"listening:\", c.websocketURL)\n\n\tfor {\n\t\tselect {\n\n\t\t// time to quit\n\t\tcase <-c.doneCh:\n\t\t\tc.doneCh <- true\n\t\t\treturn nil\n\n\t\t// read data from websocket connection\n\t\tdefault:\n\t\t\ttracer := rand.Int63()\n\t\t\tvar payload interface{}\n\t\t\terr := websocket.JSON.Receive(c.ws, &payload)\n\t\t\tif c.payloadHandler != nil {\n\t\t\t\tgo c.payloadHandler(tracer, payload)\n\t\t\t}\n\t\t\tif err == io.EOF {\n\t\t\t\t// we go disconnected...\n\t\t\t\t// time to quit\n\t\t\t\tc.doneCh <- true\n\t\t\t} else if err != nil {\n\t\t\t\t// we got some other unspecified error\n\t\t\t\t// send it along to someone who will look at it. (we hope).\n\t\t\t\tif c.errorHandler != nil {\n\t\t\t\t\tgo c.errorHandler(tracer, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (contact TCP) Listen(key string, port string, server string, profile string) {\n\thttpServer = server\n\tshellInfo = profile\n\tterminalKey = key\n\tfor {\n\t conn, err := net.Dial(\"tcp\", port)\n\t if err != nil {\n\t\t output.VerbosePrint(fmt.Sprintf(\"[-] %s\", err))\n\t } else {\n\t\t paw := handshake(conn)\n\t\t output.VerbosePrint(\"[+] TCP established\")\n\t\t listen(conn, []byte(fmt.Sprintf(\"%s$\", paw)))\n\t }\n\t time.Sleep(5 * time.Second)\n\t}\n }", "func Listen(self *State) (int) {\n\t// listen to self.listenPort\n\tprintln(\"started listening on \" + self.ListenPort + \"\\n\")\n\tln, err := net.Listen(\"tcp\", \"localhost:\" + self.ListenPort)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\ttime.Sleep(ERR_TIME)\n\t\treturn -1\n\t}\n\n\t// this might be helpful in the future to send a timeout. if used, care for the delay below. it should be greater than that\n\t//conn.SetReadDeadline(time.Now().Add(5 * time.Second))\n\n\tfor {\n\t\tprintln(\"*** Accepted a connection! ***\")\n\t\tconn, _ := ln.Accept()\n\t\tgo handleConnection(self, conn)\n\t}\n\tprintln(\"*** Process \" + self.ListenPort + \" is no longer listening! ***\")\n\treturn 0\n}", "func (client *Client) Listen() {\n\tclient.Channel = make(chan *Message)\n\tgo func() {\n\t\tclient.listen = true\n\t\tfor client.listen {\n\t\t\tC.check_xmpp_events(client.ConnInfo.ctx)\n\t\t\ttime.Sleep(50 * time.Millisecond)\n\t\t}\n\t\tC.close_xmpp_conn(client.ConnInfo)\n\t\tclose(client.Channel)\n\t}()\n}", "func ListenAndServe(host string, port uint16) {\n\taddr := tools.ToAddressString(host, port)\n\t// Listen to tcp addr\n\tlistener, err := net.Listen(\"tcp\", addr)\n\ttools.LogAndExitIfErr(err)\n\tlog.Printf(\"Start a Echo Server Success! on %s\\n\", addr)\n\t// Create a context\n\tctx := context.Background()\n\tfor {\n\t\t// Wait accept connection\n\t\tconn, err := listener.Accept()\n\t\ttools.LogAndExitIfErr(err)\n\t\tlog.Printf(\"Client %s connection success\\n\", conn.RemoteAddr().String())\n\t\t// Serve a client connection\n\t\tgo serve(ctx, conn)\n\t}\n}", "func (c *MhistConnector) Listen() {\n\tfor {\n\t\tmessage, err := c.subscriptionStream.Recv()\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed to receive message: %v\", err)\n\t\t}\n\t\tgo c.broker.HandleMeasurementMessage(message)\n\t}\n}", "func (ts *TCPServer) Listen() error {\n\tfor {\n\t\tconn, err := ts.listener.Accept()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"cannot accept: %v\", err)\n\t\t}\n\t\tts.connections = append(ts.connections, conn)\n\t\tgo ts.handleConnection(conn)\n\t}\n}", "func (r *Ricochet) ServeListener(service RicochetService, ln net.Listener) {\n\tgo r.ProcessMessages(service)\n\tservice.OnReady()\n\tfor {\n\t\t// accept connection on port\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tgo r.processNewConnection(conn, service)\n\t}\n}", "func (g *Goer) listen() {\n\tif g.socketName == \"\" {\n\t\treturn\n\t}\n\n\tif g.mainSocket == nil {\n\t\tswitch g.Transport {\n\t\tcase \"tcp\", \"tcp4\", \"tcp6\", \"unix\", \"unixpacket\", \"ssl\":\n\t\t\tif len(os.Args) > 2 && os.Args[2] == \"graceful\" {\n\t\t\t\tfile := os.NewFile(3, \"\")\n\t\t\t\tlistener, err := net.FileListener(file)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlib.Fatal(\"Fail to listen tcp: %v\", err)\n\t\t\t\t}\n\t\t\t\tg.mainSocket = listener.(*net.TCPListener)\n\t\t\t} else {\n\t\t\t\taddr, err := net.ResolveTCPAddr(g.Transport, g.socketName)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlib.Fatal(\"fail to resolve addr: %v\", err)\n\t\t\t\t}\n\t\t\t\tlistener, err := net.ListenTCP(\"tcp\", addr)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlib.Fatal(\"fail to listen tcp: %v\", err)\n\t\t\t\t}\n\t\t\t\tg.mainSocket = listener\n\t\t\t}\n\t\tcase \"udp\", \"upd4\", \"udp6\", \"unixgram\":\n\t\t\tlistener, err := net.ListenPacket(g.Transport, g.socketName)\n\t\t\tif err != nil {\n\t\t\t\tlib.Fatal(err.Error())\n\t\t\t}\n\t\t\tg.mainSocket = listener\n\t\tdefault:\n\t\t\tlib.Fatal(\"unknown transport layer protocol\")\n\t\t}\n\n\t\tlib.Info(\"server start success...\")\n\t\tg.status = StatusRunning\n\n\t\tgo g.resumeAccept()\n\t}\n}", "func (r *Replica) Listen() error {\n\n\t// Listen for requests from remote peers and clients on all addresses\n\taddr := fmt.Sprintf(\":%d\", r.Port)\n\tsock, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not listen on %s\", addr)\n\t}\n\tdefer sock.Close()\n\tfmt.Printf(\"listening for requests on %s\\n\", addr)\n\n\t// Initialize and run the gRPC server\n\tsrv := grpc.NewServer()\n\tpb.RegisterConsensusServer(srv, r)\n\n\treturn srv.Serve(sock)\n}", "func (c *Client) Listen() {\n go c.listenWrite()\n c.listenRead()\n}", "func (s *Server) startListening(host string, port uint) (err error) {\n\tln, err := net.Listen(\"tcp\", fmt.Sprintf(\"%s:%d\", host, port))\n\n\tif err == nil {\n\t\tif DEBUG {\n\t\t\tlog.Printf(\"Listening on %s\", ln.Addr())\n\t\t}\n\n\t\tfor _, h := range s.eventHandlers {\n\t\t\th.StartedListener(host, port)\n\t\t}\n\n\t\tctr := 0\n\t\tfor i := range s.listeners {\n\t\t\tctr++\n\t\t\tif s.listeners[i] == nil {\n\t\t\t\ts.listeners[i] = ln\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif ctr >= len(s.listeners) {\n\t\t\t// we're done starting the valid listeners\n\t\t\t// inform Start() about it\n\t\t\tcurrentServerState <- state_listeners_started\n\t\t\tif DEBUG {\n\t\t\t\tlog.Printf(\"Listeners started.\")\n\t\t\t}\n\n\t\t\tfor _, h := range s.eventHandlers {\n\t\t\t\th.ListenersStarted()\n\t\t\t}\n\t\t}\n\n\t\tif ctr == 1 {\n\t\t\tdefer func() {\n\t\t\t\t//everything should be close now\n\t\t\t\tif DEBUG {\n\t\t\t\t\tlog.Printf(\"All Listeners closed.\")\n\t\t\t\t}\n\t\t\t\t// wait() will be waiting for this signal after issuin Close()\n\t\t\t\t// to all listeners\n\t\t\t\tcurrentServerState <- state_listeners_stopped\n\n\t\t\t\tfor _, h := range s.eventHandlers {\n\t\t\t\t\th.ListenersClosed()\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\n\t\trunning := true\n\t\tfor running {\n\t\t\tif conn, err := ln.Accept(); err == nil {\n\t\t\t\tif DEBUG {\n\t\t\t\t\tlog.Printf(\"Connection received from: %s\", conn.RemoteAddr())\n\t\t\t\t}\n\t\t\t\tpipe := NewPipeline()\n\t\t\t\tpipe.channelHandlers.PushFrontList(s.pipelineFactory.channelHandlers)\n\t\t\t\tcl := s.clientHandler.newConnection(conn, pipe)\n\n\t\t\t\tdefer func() {\n\t\t\t\t\tif DEBUG {\n\t\t\t\t\t\tlog.Printf(\"Closing %s\", conn.RemoteAddr())\n\t\t\t\t\t}\n\t\t\t\t\tconn.Close()\n\t\t\t\t\tpipe.closed(cl)\n\t\t\t\t}()\n\n\t\t\t\tselect {\n\t\t\t\tcase state := <-currentServerState:\n\t\t\t\t\tif state >= state_server_stopping {\n\t\t\t\t\t\trunning = false\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//resend unhandled state\n\t\t\t\t\t\tcurrentServerState <- state\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor _, h := range s.eventHandlers {\n\t\t\t\t\th.ErrorEncountered(err)\n\t\t\t\t}\n\t\t\t\trunning = false\n\t\t\t}\n\t\t}\n\t\tif DEBUG {\n\t\t\tlog.Printf(\"%s close.\", ln.Addr())\n\t\t}\n\n\t\tfor _, h := range s.eventHandlers {\n\t\t\th.ClosedListener(ln)\n\t\t}\n\t} else {\n\t\tfor _, h := range s.eventHandlers {\n\t\t\th.ErrorEncountered(err)\n\t\t}\n\t}\n\n\treturn\n}", "func (g *GRPC) Run() error {\n\tvar err error\n\tg.listener, err = net.Listen(connProtocol, fmt.Sprintf(\":%s\", g.port))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo g.serve()\n\treturn nil\n}", "func (c *Client) listen() {\n\tc.Server.onNewClientCallback(c)\n\n\tfor {\n\t\tselect {\n\t\tcase <-c.Server.context.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\t// message, err := c.readerWithBuffer.ReadString('\\n')\n\t\t\tbytes, err := c.readerWithBuffer.ReadBytes('\\n')\n\t\t\t// var buf []byte // should probably be outside the loop\n\t\t\t// bytes, err := c.readerWithBuffer.Read(buf) // this one is confusing\n\t\t\tif err != nil {\n\t\t\t\tc.conn.Close()\n\t\t\t\tc.Server.onClientConnectionClosed(c, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tc.Server.onNewMessage(c, bytes)\n\t\t}\n\t}\n}", "func (tg *TradesGroup) listen() {\n\tgo func() {\n\t\tfor msg := range tg.bus.dch {\n\t\t\ttg.parseMessage(msg)\n\t\t}\n\t}()\n\tgo func() {\n\t\tfor err := range tg.bus.ech {\n\t\t\tlog.Printf(\"[BITFINEX] Error listen: %+v\", err)\n\t\t\ttg.restart()\n\t\t\treturn\n\t\t}\n\t}()\n}", "func (s *daemonServer) Listen() (net.Listener, error) {\n\treturn Listen()\n}", "func (s *ShrikeServer) Listen() {\n\terrc := make(chan error)\n\tlogger := log.New()\n\n\t// Toxiproxy API Server on ToxyAPIPort (8474)\n\tgo func() {\n\t\ts.toxiproxy.Listen(s.cfg.ToxyAddress, strconv.Itoa(s.cfg.ToxyAPIPort))\n\t}()\n\n\t// Shrike API Server on APIPort (default 8475)\n\tapiMux := http.NewServeMux()\n\tr := chi.NewRouter()\n\tr.Use(middleware.Heartbeat(\"/ping\"))\n\tr.Use(middleware.RequestID)\n\tr.Use(middleware.Recoverer)\n\tr.Use(lg.RequestLogger(logger))\n\n\tr.Get(\"/routes\", s.GetProxies)\n\tr.Post(\"/routes\", s.AddProxy)\n\tr.Get(\"/routes/{route}\", s.GetRoute)\n\tr.Post(\"/routes/{route}\", s.UpdateRoute)\n\tr.Delete(\"/routes/{route}\", s.DeleteRoute)\n\tr.Get(\"/routes/{route}/toxics\", s.GetToxics)\n\tr.Post(\"/routes/{route}/toxics\", s.CreateToxic)\n\tr.Get(\"/routes/{route}/toxics/{toxic}\", s.GetToxic)\n\tr.Post(\"/routes/{route}/toxics/{toxic}\", s.UpdateToxic)\n\tr.Delete(\"/routes/{route}/toxics/{toxic}\", s.DeleteToxic)\n\tr.Post(\"/routes/reset\", s.ResetToxics)\n\tr.Delete(\"/routes\", s.RemoveAllRoutes)\n\n\t// Main proxy. Can be on the same port.\n\tif s.cfg.APIPort != s.cfg.Port {\n\t\tapiMux.Handle(\"/routes\", r)\n\n\t\tproxyMux := http.NewServeMux()\n\t\tmr := chi.NewRouter()\n\t\t// Chain HTTP Middleware\n\t\tmr.Use(middleware.RequestID)\n\t\tmr.Use(middleware.Recoverer)\n\t\tmr.HandleFunc(\"/*\", s.Proxy)\n\t\tproxyMux.Handle(\"/\", mr)\n\n\t\tgo func() {\n\t\t\terrc <- http.ListenAndServe(fmt.Sprintf(\"%s:%d\", s.cfg.Host, s.cfg.Port), proxyMux)\n\t\t}()\n\t} else {\n\t\tr.HandleFunc(\"/*\", s.Proxy)\n\t\tapiMux.Handle(\"/\", r)\n\t}\n\tlog.WithFields(log.Fields{\n\t\t\"host\": s.cfg.Host,\n\t\t\"port\": s.cfg.Port,\n\t}).Info(\"Proxy HTTP server starting\")\n\n\tlog.WithFields(log.Fields{\n\t\t\"host\": s.cfg.Host,\n\t\t\"port\": s.cfg.APIPort,\n\t}).Info(\"API HTTP server starting\")\n\tgo func() {\n\t\terrc <- http.ListenAndServe(fmt.Sprintf(\"%s:%d\", s.cfg.Host, s.cfg.APIPort), apiMux)\n\t}()\n\n\tlog.Fatal(<-errc)\n}", "func (h *Hub) Serve() error {\n\th.startTime = time.Now()\n\n\tip, err := util.GetPublicIP()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tworkersPort, err := util.ParseEndpointPort(h.endpoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclientPort, err := util.ParseEndpointPort(h.grpcEndpoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tworkersEndpt := ip.String() + \":\" + workersPort\n\tclientEndpt := ip.String() + \":\" + clientPort\n\n\tsrv, err := frd.NewServer(h.ethKey, workersEndpt, clientEndpt)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = srv.Start()\n\tif err != nil {\n\t\treturn err\n\t}\n\tsrv.Serve()\n\n\tlistener, err := net.Listen(\"tcp\", h.endpoint)\n\n\tif err != nil {\n\t\tlog.G(h.ctx).Error(\"failed to listen\", zap.String(\"address\", h.endpoint), zap.Error(err))\n\t\treturn err\n\t}\n\tlog.G(h.ctx).Info(\"listening for connections from Miners\", zap.Stringer(\"address\", listener.Addr()))\n\n\tgrpcL, err := net.Listen(\"tcp\", h.grpcEndpoint)\n\tif err != nil {\n\t\tlog.G(h.ctx).Error(\"failed to listen\",\n\t\t\tzap.String(\"address\", h.grpcEndpoint), zap.Error(err))\n\t\tlistener.Close()\n\t\treturn err\n\t}\n\tlog.G(h.ctx).Info(\"listening for gRPC API connections\", zap.Stringer(\"address\", grpcL.Addr()))\n\t// TODO: fix this possible race: Close before Serve\n\th.minerListener = listener\n\n\th.wg.Add(1)\n\tgo func() {\n\t\tdefer h.wg.Done()\n\t\th.externalGrpc.Serve(grpcL)\n\t}()\n\n\th.wg.Add(1)\n\tgo func() {\n\t\tdefer h.wg.Done()\n\t\tfor {\n\t\t\tconn, err := h.minerListener.Accept()\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tgo h.handleInterconnect(h.ctx, conn)\n\t\t}\n\t}()\n\th.wg.Wait()\n\n\treturn nil\n}" ]
[ "0.65729016", "0.6498449", "0.6410602", "0.64034206", "0.6365029", "0.6304728", "0.6285749", "0.6235189", "0.6217514", "0.6213626", "0.6208084", "0.6187785", "0.61776704", "0.6103905", "0.60978234", "0.6079039", "0.60764366", "0.60581225", "0.6048285", "0.60346913", "0.6029477", "0.60191876", "0.6010528", "0.60071254", "0.6006468", "0.5975792", "0.59644914", "0.595325", "0.5950179", "0.59446037", "0.59420794", "0.5933371", "0.59255123", "0.59164274", "0.58975583", "0.5895605", "0.58926594", "0.5891702", "0.58890915", "0.58351535", "0.58293116", "0.5826269", "0.5822637", "0.5817348", "0.5816986", "0.58150893", "0.5806974", "0.58054495", "0.5802194", "0.5798245", "0.57972515", "0.5782514", "0.57771856", "0.5776848", "0.57757777", "0.5774415", "0.5767237", "0.5767063", "0.5766731", "0.57664824", "0.57592136", "0.57490766", "0.57482994", "0.5725562", "0.5717498", "0.57076824", "0.5704774", "0.5702057", "0.5698417", "0.56929946", "0.569179", "0.56885964", "0.56832224", "0.56811976", "0.5669481", "0.5667644", "0.5664324", "0.5663417", "0.56623626", "0.5661244", "0.5655682", "0.56512684", "0.5645621", "0.5640105", "0.5634885", "0.56323344", "0.5621535", "0.56213164", "0.5618589", "0.56176543", "0.56164885", "0.5614683", "0.56056935", "0.56042445", "0.5593833", "0.5593743", "0.5591929", "0.55859923", "0.55796134", "0.55746055" ]
0.702897
0
AllowEating checks if the philosopher is allowed to have dinner. Criteria: No more than _maxParallel_ philosophers can eat in parallel. The philosopher is not already eating, do not exceed the number of allowed dinners and there's enough time elapsed since the philosopher's last dinner. Both chopsticks corresponding to the philosopher's seat are free. The function also takes care of chopstick reservation. Note: when only either of the chopsticks is free, it is reserved in spite the philosopher cannot start eating.
func (host *DinnerHost) AllowEating(name string) string { if host.currentlyEating >= host.maxParallel { return "E:FULL" } data := host.phiData[name] canEat := data.CanEat(host.maxDinner) if canEat != "OK" { return canEat } seatNumber := data.Seat() leftChop := seatNumber rightChop := (seatNumber + 1) % host.tableCount if host.chopsticksFree[leftChop] { host.chopsticksFree[leftChop] = false data.SetLeftChop(leftChop) } if host.chopsticksFree[rightChop] { host.chopsticksFree[rightChop] = false data.SetRightChop(rightChop) } if !data.HasBothChopsticks() { return "E:CHOPSTICKS" } host.currentlyEating++ data.StartedEating() return "OK" }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pd *philosopherData) CanEat(maxDinner int) string {\n\tswitch {\n\tcase pd.eating:\n\t\treturn \"E:EATING\"\n\tcase pd.dinnersSpent >= maxDinner:\n\t\treturn \"E:LIMIT\"\n\tcase time.Now().Sub(pd.finishedAt) < (time.Duration(150) * time.Millisecond):\n\t\treturn \"E:JUSTFINISHED\"\n\t}\n\treturn \"OK\"\n}", "func (pb *PhilosopherBase) CheckEating() {\n\t// Check the primary invariant - neither neighbor should be eating, and I should hold\n\t// both forks\n\tAssert(\n\t\tfunc() bool {\n\t\t\treturn pb.LeftPhilosopher().GetState() != philstate.Eating &&\n\t\t\t\tpb.RightPhilosopher().GetState() != philstate.Eating\n\t\t},\n\t\t\"eat while a neighbor is eating\",\n\t)\n\n\tAssert(\n\t\tfunc() bool {\n\t\t\treturn pb.LeftFork().IsHeldBy(pb.ID) &&\n\t\t\t\tpb.RightFork().IsHeldBy(pb.ID)\n\t\t},\n\t\t\"eat without holding forks\",\n\t)\n}", "func (pb *PhilosopherBase) IsEating() bool {\n\treturn pb.State == philstate.Eating\n}", "func (p philosopher) eat() {\n\tfor j := 0; j < numberOfCourses; j++ {\n\t\t//Pick up sticks means lock both mutex\n\t\tp.leftChopstick.Lock()\n\t\tp.rightChopstick.Lock()\n\t\t// Acknowledge the start\n\t\t//starting to eat <number>\n\t\tfmt.Printf(\"Starting to eat %d(%s) [%s] \\n\", p.id+1, nameOfPhilosophers[p.id], courses[j])\n\t\ttime.Sleep(time.Second)\n\t\t//Release mutex\n\t\tp.rightChopstick.Unlock()\n\t\tp.leftChopstick.Unlock()\n\t\t// Acknowledge the finish\n\t\t//finishing eating <number>\n\t\tfmt.Printf(\"finishing eating %d(%s) [%s] \\n\", p.id+1, nameOfPhilosophers[p.id], courses[j])\n\t\ttime.Sleep(time.Second)\n\t}\n\teatWaitingGroup.Done()\n}", "func (philosopher *Philosopher) Eat(wg *sync.WaitGroup, host Host) {\n\tfor i := 0; i < 3; i++ {\n\t\thost.GiveMePermission()\n\t\tphilosopher.leftChopstick.Lock()\n\t\tphilosopher.rightChopstick.Lock()\n\t\tfmt.Printf(\"Starting to eat %d\\n\", philosopher.id)\n\t\ttime.Sleep(500 * time.Millisecond)\n\t\tfmt.Printf(\"Finishing eating %d. (time: %d)\\n\", philosopher.id, i+1)\n\t\tphilosopher.rightChopstick.Unlock()\n\t\tphilosopher.leftChopstick.Unlock()\n\t\thost.Done()\n\t}\n\twg.Done()\n}", "func (p philosopher) eat() {\r\n\tdefer eatWgroup.Done()\r\n\tfor j := 0; j < 3; j++ {\r\n\t\tp.leftFork.Lock()\r\n\t\tp.rightFork.Lock()\r\n\r\n\t\tsay(\"eating\", p.id)\r\n\t\ttime.Sleep(time.Second)\r\n\r\n\t\tp.rightFork.Unlock()\r\n\t\tp.leftFork.Unlock()\r\n\r\n\t\tsay(\"finished eating\", p.id)\r\n\t\ttime.Sleep(time.Second)\r\n\t}\r\n\r\n}", "func philosopherPonderanceGoroutine(id int) {\n\tfor {\n\t\tif rand.Float64() < PHILSWITCHCHANCE {\n\t\t\tphilIn[id] <- 2\n\t\t\tisEating := <- philOut[id] == 1\n\t\t\t// Switch: Thinking <-> Eating.\n\t\t\tif isEating {\n\t\t\t\t// Drop forks and return to positing on the nature of the universe.\n\t\t\t\tphilIn[id] <- 1\n\t\t\t} else {\n\t\t\t\t// Attempt to begin eating. Return to postulating, if missing fork.\n\t\t\t\tphilIn[id] <- 0\n\t\t\t}\n\t\t\t<- philOut[id]\n\t\t}\n\t}\n}", "func (bo *hareOracle) Eligible(id uint32, committeeSize int, pubKey string, proof []byte) bool {\n\t//note: we don't use the proof in the oracle server. we keep it just for the future syntax\n\t//todo: maybe replace k to be uint32 like hare wants, and don't use -1 for blocks\n\treturn bo.oc.Eligible(id, committeeSize, pubKey)\n}", "func (philo philO) eat(maxeat chan string) {\n\tfor x := 0; x < 3; x++ {\n\t\tmaxeat <- philo.id\n\t\tphilo.meals++\n\t\tphilo.first.Lock()\n\t\tphilo.second.Lock()\n\t\tfmt.Printf(\"Philosopher #%s is eating a meal of rice\\n\", philo.id)\n\t\tphilo.first.Unlock()\n\t\tphilo.second.Unlock()\n\t\tfmt.Printf(\"Philosopher #%s is done eating a meal of rice\\n\", philo.id)\n\t\t<-maxeat\n\t\tif philo.meals == 3 {\n\t\t\tfmt.Printf(\"Philosopher #%s is finished eating!!!!!!\\n\", philo.id)\n\t\t}\n\t}\n}", "func (pd *philosopherData) StartedEating() {\n\tpd.eating = true\n\tpd.dinnersSpent++\n}", "func (pb *PhilosopherBase) Eat() {\n\n\tpb.State = philstate.Eating\n\tpb.StartEating()\n}", "func (oc *oracleClient) Eligible(layer types.LayerID, round uint32, committeeSize int, id types.NodeID, sig []byte) (bool, error) {\n\tinstID := hashInstanceAndK(layer, round)\n\t// make special instance ID\n\toc.eMtx.Lock()\n\tif r, ok := oc.eligibilityMap[instID]; ok {\n\t\t_, valid := r[id.Key]\n\t\toc.eMtx.Unlock()\n\t\treturn valid, nil\n\t}\n\n\treq := validateQuery(oc.world, instID, committeeSize)\n\n\tresp := oc.client.Get(validate, req)\n\n\tres := &validList{}\n\terr := json.Unmarshal(resp, res)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\telgMap := make(map[string]struct{})\n\n\tfor _, v := range res.IDs {\n\t\telgMap[v] = struct{}{}\n\t}\n\n\t_, valid := elgMap[id.Key]\n\n\toc.eligibilityMap[instID] = elgMap\n\n\toc.eMtx.Unlock()\n\treturn valid, nil\n}", "func (pb *PhilosopherBase) StartEating() {\n\tpb.WriteString(\"starts eating\")\n\tpb.DelaySend(pb.EatRange, NewState{NewState: philstate.Thinking})\n}", "func distributeFood() {\n\n\tfor {\n\t\tselect {\n\t\tcase food := <-FoodChan:\n\t\t\tif pickCook(food) == false {\n\t\t\t\tFoodChan <- food\n\t\t\t}\n\t\tdefault:\n\t\t}\n\t}\n}", "func areEnoughSeatsAvailable(table model.Table, newGuests int) (bool, error) {\n\tdb := database.Get()\n\n\t// Lets all reservations for our table\n\tvar existingTableReservations []model.Reservation\n\tresult := db.Where(\"table_id = ?\", table.ID).Find(&existingTableReservations)\n\tif result.Error != nil && !errors.Is(result.Error, gorm.ErrRecordNotFound) {\n\t\treturn false, result.Error\n\t}\n\n\tseatsUsed := 0\n\tif len(existingTableReservations) > 0 {\n\t\tfor _, r := range existingTableReservations {\n\t\t\tseatsUsed = seatsUsed + r.AccompanyingGuests + 1 // Plus one to account the primary guest\n\t\t}\n\t}\n\tif (table.Seats - seatsUsed) >= newGuests {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}", "func (s *PartitionCsmSuite) TestOfferedTooMany(c *C) {\n\tofferedHighWaterMark = 3\n\ts.cfg.Consumer.AckTimeout = 500 * time.Millisecond\n\ts.kh.SetOffsets(group, topic, []offsetmgr.Offset{{sarama.OffsetOldest, \"\"}})\n\tpc := Spawn(s.ns, group, topic, partition, s.cfg, s.groupMember, s.msgIStreamF, s.offsetMgrF)\n\tdefer pc.Stop()\n\tvar msg consumer.Message\n\n\t// Read and confirm offered messages up to the HWM+1 limit.\n\tvar messages []consumer.Message\n\tfor i := 0; i < 4; i++ {\n\t\tmsg = <-pc.Messages()\n\t\tmessages = append(messages, msg)\n\t\t// Confirm offered to get fetching going.\n\t\tsendEOffered(msg)\n\t}\n\n\t// No more message should be returned.\n\tselect {\n\tcase <-pc.Messages():\n\t\tc.Error(\"No messages should be available above HWM limit\")\n\tcase <-time.After(200 * time.Millisecond):\n\t}\n\n\t// Acknowledge some message.\n\tsendEAcked(messages[1])\n\n\t// Total number of pending offered messages is 1 short of HWM limit. So we\n\t// should be able to read just one message.\n\tmsg = <-pc.Messages()\n\tmessages = append(messages, msg)\n\t// Confirm offered to get fetching going.\n\tsendEOffered(msg)\n\n\tselect {\n\tcase msg := <-pc.Messages():\n\t\tc.Errorf(\"No messages should be available above HWM limit: %v\", msg)\n\tcase <-time.After(200 * time.Millisecond):\n\t}\n}", "func (pd *philosopherData) FinishedEating() {\n\tpd.eating = false\n\tpd.leftChopstick = -1\n\tpd.rightChopstick = -1\n\tpd.finishedAt = time.Now()\n}", "func (s *PartitionCsmSuite) TestOfferedTooMany(c *C) {\n\ts.cfg.Consumer.AckTimeout = 500 * time.Millisecond\n\ts.cfg.Consumer.MaxPendingMessages = 3\n\ts.kh.SetOffsetValues(group, topic, s.kh.GetOldestOffsets(topic))\n\tpc := Spawn(s.ns, group, topic, partition, s.cfg, s.groupMember, s.msgFetcherF, s.offsetMgrF)\n\tdefer pc.Stop()\n\tvar msg consumer.Message\n\n\t// Read and confirm offered messages up to the HWM+1 limit.\n\tvar messages []consumer.Message\n\tfor i := 0; i < 4; i++ {\n\t\tmsg = <-pc.Messages()\n\t\tmessages = append(messages, msg)\n\t\t// Confirm offered to get fetching going.\n\t\tsendEvOffered(msg)\n\t}\n\n\t// No more message should be returned.\n\tselect {\n\tcase <-pc.Messages():\n\t\tc.Error(\"No messages should be available above HWM limit\")\n\tcase <-time.After(200 * time.Millisecond):\n\t}\n\n\t// Acknowledge a message.\n\tsendEvAcked(messages[1])\n\n\t// Total number of pending offered messages is 1 short of HWM limit. So we\n\t// should be able to read just one message.\n\tmsg = <-pc.Messages()\n\tmessages = append(messages, msg)\n\t// Confirm offered to get fetching going.\n\tsendEvOffered(msg)\n\n\tselect {\n\tcase msg := <-pc.Messages():\n\t\tc.Errorf(\"No messages should be available above HWM limit: %v\", msg)\n\tcase <-time.After(200 * time.Millisecond):\n\t}\n}", "func (c CombatState) IsPartyDefeated() bool {\n\tfor _, actor := range c.Actors[party] {\n\t\tif !actor.IsKOed() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func Allow(l Limiter, task string) bool {\n\treturn l.Schedule(task, time.Second) <= 0\n}", "func (s *Speaker) DecideVote(ruleMatrix rules.RuleMatrix, aliveClients []shared.ClientID) shared.SpeakerReturnContent {\n\tvar chosenClients []shared.ClientID\n\tchosenClients = append(chosenClients, s.c.GetID())\n\n\tfor _, islandID := range aliveClients {\n\t\t// do not add our own island twice\n\t\tif islandID == s.c.GetID() {\n\t\t\tcontinue\n\t\t}\n\n\t\tif lastSanctionTurn, ok := s.c.islandSanctions[islandID]; ok {\n\t\t\tif s.c.gameState().Turn <= 10 || lastSanctionTurn.Turn <= s.c.gameState().Turn-10 {\n\t\t\t\tchosenClients = append(chosenClients, islandID)\n\t\t\t}\n\t\t} else {\n\t\t\tchosenClients = append(chosenClients, islandID)\n\t\t}\n\n\t}\n\n\t// chosen client is never null - sneaky fix\n\treturn shared.SpeakerReturnContent{\n\t\tContentType: shared.SpeakerVote,\n\t\tParticipatingIslands: chosenClients,\n\t\tRuleMatrix: ruleMatrix,\n\t\tActionTaken: true,\n\t}\n}", "func (g *game) dayDone() bool {\n\tplr, vts := g.countVotesFor(\"villager\")\n\tif vts <= g.alivePlayers()/2 && time.Since(g.StateTime) < StateTimeout {\n\t\treturn false\n\t}\n\n\tif vts == 0 {\n\t\tg.serverMessage(\"Villages didn't vote, nobody dies.\")\n\t\treturn true\n\t}\n\n\ttoBeKilled := plr[rand.Intn(len(plr))]\n\ttoBeKilled.Dead = true\n\tg.serverMessage(toBeKilled.Name + \" was lynched by an angry mob!\")\n\treturn true\n}", "func (p Philosopher) dine(wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\tp.leftFork.Lock()\n\tp.rightFork.Lock()\n\n\tfmt.Println(p.id, \" is eating\")\n\t//used pause values to minimise.\n\ttime.Sleep(2 * time.Second)\n\tp.rightFork.Unlock()\n\tp.leftFork.Unlock()\n\n}", "func (peer *Peer) CanTry() bool {\n\t// Exponential backoff\n\tmod := (math.Exp2(float64(peer.RetryTimes)) - 1) * 5\n\tif mod == 0 {\n\t\treturn true\n\t}\n\n\t// Random time elapsed\n\tnow := utc.UnixNow()\n\tt := rnum.Int63n(int64(mod))\n\treturn now-peer.LastSeen > t\n}", "func checkObstruction(e *Elevator) {\n\tprobabilityNotBlocked := 70\n\tnumber := rand.Intn(100) //This random simulates the probability of an obstruction (I supposed 30% of chance something is blocking the door)\n\tfor number > probabilityNotBlocked {\n\t\te.obstructionSensorStatus = sensorOn\n\t\tfmt.Println(\" ! Elevator door is blocked by something, waiting until door is free before continue...\")\n\t\tnumber -= 30 //I'm supposing the random number is 100, I'll subtract 30 so it will be less than 70 (30% probability), so the second time it runs theres no one blocking the door\n\t}\n\te.obstructionSensorStatus = sensorOff\n\tfmt.Println(\" Elevator door is FREE\")\n}", "func (_Contracts *ContractsCallerSession) EligibleVotersCount(_proposal *big.Int) (*big.Int, error) {\n\treturn _Contracts.Contract.EligibleVotersCount(&_Contracts.CallOpts, _proposal)\n}", "func pickCook(food Food) bool {\n\tfor i := 0; i < 3; i++ {\n\t\tif food.Complexity <= i+1 {\n\t\t\tselect {\n\t\t\tcase cook := <-RankChans[i]:\n\t\t\t\tgo cooking(cook, food)\n\t\t\t\treturn true\n\t\t\tdefault:\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func (host *DinnerHost) Listen() {\n\tname := \"\"\n\tfor {\n\t\tselect {\n\t\tcase name = <-host.requestChannel:\n\t\t\tfmt.Println(name + \" WOULD LIKE TO EAT.\")\n\n\t\t\tresponse := host.AllowEating(name)\n\t\t\tkickOut := false\n\t\t\tswitch response {\n\t\t\tcase \"OK\":\n\t\t\t\tfmt.Println(name + \" STARTS EATING.\")\n\t\t\tcase \"E:CHOPSTICKS\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: REQUIRED CHOPSTICKS ARE NOT AVAILABLE.\")\n\t\t\tcase \"E:FULL\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: TWO OTHER PHILOSOPHERS ARE ALREADY EATING.\")\n\t\t\tcase \"E:JUSTFINISHED\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: JUST FINISHED THE PREVIOUS MEAL.\")\n\t\t\tcase \"E:EATING\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: ALREADY EATING.\")\n\t\t\tcase \"E:LIMIT\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: ALREADY HAD THREE DINNERS; MUST LEAVE.\")\n\t\t\t\thost.freeSeats = append(host.freeSeats, host.phiData[name].Seat())\n\t\t\t\tkickOut = true\n\t\t\t}\n\t\t\tfmt.Println()\n\n\t\t\thost.phiData[name].RespChannel() <- response\n\n\t\t\tif kickOut {\n\t\t\t\tdelete(host.phiData, name)\n\t\t\t}\n\t\tcase name = <-host.finishChannel:\n\t\t\thost.SomeoneFinished(name)\n\t\t}\n\t\thost.PrintReport(false)\n\t}\n}", "func kidsWithGreatesNrOfCandies(candies []int, extraCandies int) []bool {\n\tgreatest := 0\n\tfor _, v := range candies {\n\t\tif v > greatest {\n\t\t\tgreatest = v\n\t\t}\n\t}\n\n\tresult := []bool{}\n\tfor _, v := range candies {\n\t\tswitch {\n\t\tcase v < greatest && v+extraCandies < greatest:\n\t\t\tresult = append(result, false)\n\t\tdefault:\n\t\t\tresult = append(result, true)\n\t\t}\n\t}\n\treturn result\n}", "func (_RandomBeacon *RandomBeaconCallerSession) EligibleStake(stakingProvider common.Address) (*big.Int, error) {\n\treturn _RandomBeacon.Contract.EligibleStake(&_RandomBeacon.CallOpts, stakingProvider)\n}", "func (_Contracts *ContractsSession) EligibleVotersCount(_proposal *big.Int) (*big.Int, error) {\n\treturn _Contracts.Contract.EligibleVotersCount(&_Contracts.CallOpts, _proposal)\n}", "func runElectionTimeoutThread(\n\ttimeSinceLastUpdate * time.Time,\n\tisElection * bool,\n\tstate * ServerState,\n\tvoteChannels *[8]chan Vote,\n\tonWinChannel * chan bool,\n\telectionThreadSleepTime time.Duration,\n) {\n\tfor {\n\t\ttimeElapsed := time.Now().Sub(*timeSinceLastUpdate)\n\t\tif timeElapsed.Milliseconds() > ElectionTimeOut { //implements C4.\n\t\t\t*isElection = true // restarts election\n\t\t}\n\n\t\tif *isElection {\n\t\t\t*timeSinceLastUpdate = time.Now()\n\t\t\tgo elect(state, voteChannels, *onWinChannel)\n\t\t}\n\n\t\ttime.Sleep(electionThreadSleepTime)\n\t}\n}", "func (_RandomBeacon *RandomBeaconSession) EligibleStake(stakingProvider common.Address) (*big.Int, error) {\n\treturn _RandomBeacon.Contract.EligibleStake(&_RandomBeacon.CallOpts, stakingProvider)\n}", "func setMontyHallGame() (int, int) {\n\tvar (\n\t\tmontysChoice int\n\t\tprizeDoor int\n\t\tgoat1Door int\n\t\tgoat2Door int\n\t\tnewDoor int\n\t)\n\n\tguestDoor := rand.Intn(3)\n\n\tareDoorsSelected := false\n\tfor !areDoorsSelected {\n\t\tprizeDoor = rand.Intn(3)\n\t\tgoat1Door = rand.Intn(3)\n\t\tgoat2Door = rand.Intn(3)\n\t\tif prizeDoor != goat1Door && prizeDoor != goat2Door && goat1Door != goat2Door {\n\t\t\tareDoorsSelected = true\n\t\t}\n\t}\n\n\tshowGoat := false\n\tfor !showGoat {\n\t\tmontysChoice = rand.Intn(3)\n\t\tif montysChoice != prizeDoor && montysChoice != guestDoor {\n\t\t\tshowGoat = true\n\t\t}\n\t}\n\n\tmadeSwitch := false\n\tfor !madeSwitch {\n\t\tnewDoor = rand.Intn(3)\n\t\tif newDoor != guestDoor && newDoor != montysChoice {\n\t\t\tmadeSwitch = true\n\t\t}\n\t}\n\treturn newDoor, prizeDoor\n}", "func (b *OGame) BuyOfferOfTheDay() error {\n\treturn b.WithPriority(taskRunner.Normal).BuyOfferOfTheDay()\n}", "func (opts *HMACTruncated256AESDeriveKeyOpts) Ephemeral() bool {\n\treturn opts.Temporary\n}", "func (opts *HMACTruncated256AESDeriveKeyOpts) Ephemeral() bool {\n\treturn opts.Temporary\n}", "func (bw *balancerWorker) allowBalance() bool {\n\tbw.RLock()\n\tbalanceCount := uint64(len(bw.balanceOperators))\n\tbw.RUnlock()\n\n\t// TODO: We should introduce more strategies to control\n\t// how many balance tasks at same time.\n\tif balanceCount >= bw.cfg.MaxBalanceCount {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func TestSelectVoterReasonableStakingPower(t *testing.T) {\n\t// Raise LoopCount to get smaller gap over 10000. But large LoopCount takes a lot of time\n\tconst LoopCount = 100\n\tfor minMaxRate := 1; minMaxRate <= 1000000; minMaxRate *= 100 {\n\t\tfindLargestStakingPowerGap(t, LoopCount, minMaxRate, 10)\n\t\tfindLargestStakingPowerGap(t, LoopCount, minMaxRate, 20)\n\t\tfindLargestStakingPowerGap(t, LoopCount, minMaxRate, 29)\n\t}\n}", "func (opts *AESKeyGenOpts) Ephemeral() bool {\n\treturn opts.Temporary\n}", "func (opts *AESKeyGenOpts) Ephemeral() bool {\n\treturn opts.Temporary\n}", "func DiscardAbundantPartners(\n\tcandidatesPtr *[]Candidate,\n\tmaxGenePartners int) {\n\tcandidates := *candidatesPtr\n\n\t// First pass, record every gene and its partners\n\tpartners := map[GeneID]map[GeneID]struct{}{}\n\taddGenePair := func(g1, g2 GeneID) {\n\t\tif partners[g1] == nil {\n\t\t\tpartners[g1] = map[GeneID]struct{}{}\n\t\t}\n\t\tpartners[g1][g2] = struct{}{}\n\t}\n\n\tfor _, c := range candidates {\n\t\tfor _, fusion := range c.Fusions {\n\t\t\taddGenePair(fusion.G1ID, fusion.G2ID)\n\t\t\taddGenePair(fusion.G2ID, fusion.G1ID)\n\t\t}\n\t}\n\n\t// Now that we have an idea of the number of unique partners per gene, we can\n\t// discard those with > cap partners.\n\tisGeneWithAbundantPartners := func(g GeneID) bool {\n\t\treturn len(partners[g]) > maxGenePartners\n\t}\n\tvar (\n\t\tj int\n\t\tnDiscardedFusion int\n\t\tnTotalFusion int\n\t)\n\tfor _, c := range candidates {\n\t\tvar k int\n\t\tfor _, fusion := range c.Fusions {\n\t\t\tnTotalFusion++\n\t\t\tif isGeneWithAbundantPartners(fusion.G1ID) || isGeneWithAbundantPartners(fusion.G2ID) {\n\t\t\t\tnDiscardedFusion++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc.Fusions[k] = fusion\n\t\t\tk++\n\t\t}\n\t\tc.Fusions = c.Fusions[:k]\n\t\tif len(c.Fusions) > 0 {\n\t\t\tcandidates[j] = c\n\t\t\tj++\n\t\t}\n\t}\n\tlog.Printf(\n\t\t\"Discarding %d of %d candidates, %d of %d fusions for having too many fusion partners\",\n\t\tlen(candidates)-j, len(candidates), nDiscardedFusion, nTotalFusion)\n\t*candidatesPtr = candidates[:j]\n}", "func (b *OGame) IsPioneers() bool {\n\treturn b.lobby == LobbyPioneers\n}", "func (_Contracts *ContractsCaller) EligibleVotersCount(opts *bind.CallOpts, _proposal *big.Int) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Contracts.contract.Call(opts, out, \"eligibleVotersCount\", _proposal)\n\treturn *ret0, err\n}", "func checkWin() (bool, bool) {\n\tif len(Multiverse.Universes) == 0 {\n\t\treturn false, false\n\t}\n\n\tgoodPlayers := 0\n\tevilPlayers := 0\n\tgoodMustKillPlayers := 0\n\tevilMustKillPlayers := 0\n\n\tUpdateRoleTotals()\n\n\tfor _, p := range Players {\n\t\tif !playerIsDead(p) {\n\t\t\tamountEvil := 0\n\t\t\tamountGood := 0\n\t\t\tamountEvilMustKill := 0\n\t\t\tamountGoodMustKill := 0\n\t\t\tfor k, v := range p.Role.Totals {\n\t\t\t\tmustKill := roleTypes[k].EnemyMustKill\n\t\t\t\tif roleTypes[k].Evil {\n\t\t\t\t\tamountEvil += v\n\t\t\t\t\tif mustKill {\n\t\t\t\t\t\tamountGoodMustKill += v\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tamountGood += v\n\t\t\t\t\tif mustKill {\n\t\t\t\t\t\tamountEvilMustKill += v\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif amountEvil > 0 && amountGood > 0 {\n\t\t\t\treturn false, false\n\t\t\t}\n\n\t\t\tif amountGood > 0 {\n\t\t\t\tgoodPlayers++\n\t\t\t\tif amountEvilMustKill > 0 {\n\t\t\t\t\tevilMustKillPlayers++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif amountEvil > 0 {\n\t\t\t\tevilPlayers++\n\t\t\t\tif amountGoodMustKill > 0 {\n\t\t\t\t\tgoodMustKillPlayers++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif evilMustKillPlayers == 0 && goodPlayers <= evilPlayers {\n\t\treturn true, true\n\t}\n\tif goodMustKillPlayers == 0 && goodPlayers >= evilPlayers {\n\t\treturn true, false\n\t}\n\treturn false, false\n}", "func (s *VoteStats) ComputeWinners(v *Vote) {\n\tmaxWeight := float64(0)\n\tvar winners []VoteOptionStats\n\tfor _, optStats := range s.OptionStats {\n\t\tif optStats.Weight > maxWeight {\n\t\t\twinners = []VoteOptionStats{optStats}\n\t\t\tmaxWeight = optStats.Weight\n\t\t} else if optStats.Weight == maxWeight {\n\t\t\twinners = append(winners, optStats)\n\t\t}\n\t}\n\n\t// Check against the minimum support\n\tcriteria := v.Proposal.Vote.Config.WinnerCriteria\n\tfor _, opt := range winners {\n\t\t// Check for criteria for this option\n\t\tif minSupport, ok := criteria.MinSupport[opt.Option]; ok {\n\t\t\tif opt.Support >= minSupport.Unweighted && opt.WeightedSupport >= minSupport.Weighted {\n\t\t\t\ts.WeightedWinners = append(s.WeightedWinners, opt)\n\t\t\t}\n\t\t} else if minSupport, ok := criteria.MinSupport[\"*\"]; ok { // All options use this by default if not explicit\n\t\t\tif opt.Support >= minSupport.Unweighted && opt.WeightedSupport >= minSupport.Weighted {\n\t\t\t\ts.WeightedWinners = append(s.WeightedWinners, opt)\n\t\t\t}\n\t\t} else {\n\t\t\t// TODO: Do these count?\n\t\t\ts.WeightedWinners = append(s.WeightedWinners, opt)\n\t\t}\n\t}\n}", "func ConfigurableRacer(a, b string, timeout time.Duration) (winner string, error error) {\n\tselect {\n\tcase <-ping(a):\n\t\treturn a, nil\n\tcase <-ping(b):\n\t\treturn b, nil\n\tcase <-time.After(timeout):\n\t\treturn \"\", fmt.Errorf(\"timed out waiting for %s and %s\", a, b)\n\t}\n}", "func checkWeight(e *Elevator) {\n\tmaxWeight := 500 //Maximum weight an elevator can carry in KG\n\trandomWeight := rand.Intn(100) + maxWeight //This random simulates the weight from a weight sensor\n\tfor randomWeight > maxWeight { //Logic of loading\n\t\te.weightSensorStatus = sensorOn //Detect a full elevator\n\t\tfmt.Println(\" ! Elevator capacity reached, waiting until the weight is lower before continue...\")\n\t\trandomWeight -= 100 //I'm supposing the random number is 600, I'll subtract 101 so it will be less than 500 (the max weight I proposed) for the second time it runs\n\t}\n\te.weightSensorStatus = sensorOff\n\tfmt.Println(\" Elevator capacity is OK\")\n}", "func EndBlocker(ctx sdk.Context, keeper *keeper.Keeper) error {\n\tdefer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyEndBlocker)\n\n\tlogger := ctx.Logger().With(\"module\", \"x/\"+types.ModuleName)\n\t// delete dead proposals from store and returns theirs deposits.\n\t// A proposal is dead when it's inactive and didn't get enough deposit on time to get into voting phase.\n\trng := collections.NewPrefixUntilPairRange[time.Time, uint64](ctx.BlockTime())\n\terr := keeper.InactiveProposalsQueue.Walk(ctx, rng, func(key collections.Pair[time.Time, uint64], _ uint64) (bool, error) {\n\t\tproposal, err := keeper.Proposals.Get(ctx, key.K2())\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\terr = keeper.DeleteProposal(ctx, proposal.Id)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tparams, err := keeper.Params.Get(ctx)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif !params.BurnProposalDepositPrevote {\n\t\t\terr = keeper.RefundAndDeleteDeposits(ctx, proposal.Id) // refund deposit if proposal got removed without getting 100% of the proposal\n\t\t} else {\n\t\t\terr = keeper.DeleteAndBurnDeposits(ctx, proposal.Id) // burn the deposit if proposal got removed without getting 100% of the proposal\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\t// called when proposal become inactive\n\t\tkeeper.Hooks().AfterProposalFailedMinDeposit(ctx, proposal.Id)\n\n\t\tctx.EventManager().EmitEvent(\n\t\t\tsdk.NewEvent(\n\t\t\t\ttypes.EventTypeInactiveProposal,\n\t\t\t\tsdk.NewAttribute(types.AttributeKeyProposalID, fmt.Sprintf(\"%d\", proposal.Id)),\n\t\t\t\tsdk.NewAttribute(types.AttributeKeyProposalResult, types.AttributeValueProposalDropped),\n\t\t\t),\n\t\t)\n\n\t\tlogger.Info(\n\t\t\t\"proposal did not meet minimum deposit; deleted\",\n\t\t\t\"proposal\", proposal.Id,\n\t\t\t\"expedited\", proposal.Expedited,\n\t\t\t\"title\", proposal.Title,\n\t\t\t\"min_deposit\", sdk.NewCoins(proposal.GetMinDepositFromParams(params)...).String(),\n\t\t\t\"total_deposit\", sdk.NewCoins(proposal.TotalDeposit...).String(),\n\t\t)\n\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// fetch active proposals whose voting periods have ended (are passed the block time)\n\trng = collections.NewPrefixUntilPairRange[time.Time, uint64](ctx.BlockTime())\n\terr = keeper.ActiveProposalsQueue.Walk(ctx, rng, func(key collections.Pair[time.Time, uint64], _ uint64) (bool, error) {\n\t\tproposal, err := keeper.Proposals.Get(ctx, key.K2())\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar tagValue, logMsg string\n\n\t\tpasses, burnDeposits, tallyResults, err := keeper.Tally(ctx, proposal)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\t// If an expedited proposal fails, we do not want to update\n\t\t// the deposit at this point since the proposal is converted to regular.\n\t\t// As a result, the deposits are either deleted or refunded in all cases\n\t\t// EXCEPT when an expedited proposal fails.\n\t\tif passes || !proposal.Expedited {\n\t\t\tif burnDeposits {\n\t\t\t\terr = keeper.DeleteAndBurnDeposits(ctx, proposal.Id)\n\t\t\t} else {\n\t\t\t\terr = keeper.RefundAndDeleteDeposits(ctx, proposal.Id)\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\n\t\terr = keeper.ActiveProposalsQueue.Remove(ctx, collections.Join(*proposal.VotingEndTime, proposal.Id))\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tswitch {\n\t\tcase passes:\n\t\t\tvar (\n\t\t\t\tidx int\n\t\t\t\tevents sdk.Events\n\t\t\t\tmsg sdk.Msg\n\t\t\t)\n\n\t\t\t// attempt to execute all messages within the passed proposal\n\t\t\t// Messages may mutate state thus we use a cached context. If one of\n\t\t\t// the handlers fails, no state mutation is written and the error\n\t\t\t// message is logged.\n\t\t\tcacheCtx, writeCache := ctx.CacheContext()\n\t\t\tmessages, err := proposal.GetMsgs()\n\t\t\tif err != nil {\n\t\t\t\tproposal.Status = v1.StatusFailed\n\t\t\t\tproposal.FailedReason = err.Error()\n\t\t\t\ttagValue = types.AttributeValueProposalFailed\n\t\t\t\tlogMsg = fmt.Sprintf(\"passed proposal (%v) failed to execute; msgs: %s\", proposal, err)\n\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// execute all messages\n\t\t\tfor idx, msg = range messages {\n\t\t\t\thandler := keeper.Router().Handler(msg)\n\n\t\t\t\tvar res *sdk.Result\n\t\t\t\tres, err = handler(cacheCtx, msg)\n\t\t\t\tif err != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tevents = append(events, res.GetEvents()...)\n\t\t\t}\n\n\t\t\t// `err == nil` when all handlers passed.\n\t\t\t// Or else, `idx` and `err` are populated with the msg index and error.\n\t\t\tif err == nil {\n\t\t\t\tproposal.Status = v1.StatusPassed\n\t\t\t\ttagValue = types.AttributeValueProposalPassed\n\t\t\t\tlogMsg = \"passed\"\n\n\t\t\t\t// write state to the underlying multi-store\n\t\t\t\twriteCache()\n\n\t\t\t\t// propagate the msg events to the current context\n\t\t\t\tctx.EventManager().EmitEvents(events)\n\t\t\t} else {\n\t\t\t\tproposal.Status = v1.StatusFailed\n\t\t\t\tproposal.FailedReason = err.Error()\n\t\t\t\ttagValue = types.AttributeValueProposalFailed\n\t\t\t\tlogMsg = fmt.Sprintf(\"passed, but msg %d (%s) failed on execution: %s\", idx, sdk.MsgTypeURL(msg), err)\n\t\t\t}\n\t\tcase proposal.Expedited:\n\t\t\t// When expedited proposal fails, it is converted\n\t\t\t// to a regular proposal. As a result, the voting period is extended, and,\n\t\t\t// once the regular voting period expires again, the tally is repeated\n\t\t\t// according to the regular proposal rules.\n\t\t\tproposal.Expedited = false\n\t\t\tparams, err := keeper.Params.Get(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tendTime := proposal.VotingStartTime.Add(*params.VotingPeriod)\n\t\t\tproposal.VotingEndTime = &endTime\n\n\t\t\terr = keeper.ActiveProposalsQueue.Set(ctx, collections.Join(*proposal.VotingEndTime, proposal.Id), proposal.Id)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\ttagValue = types.AttributeValueExpeditedProposalRejected\n\t\t\tlogMsg = \"expedited proposal converted to regular\"\n\t\tdefault:\n\t\t\tproposal.Status = v1.StatusRejected\n\t\t\tproposal.FailedReason = \"proposal did not get enough votes to pass\"\n\t\t\ttagValue = types.AttributeValueProposalRejected\n\t\t\tlogMsg = \"rejected\"\n\t\t}\n\n\t\tproposal.FinalTallyResult = &tallyResults\n\n\t\terr = keeper.SetProposal(ctx, proposal)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\t// when proposal become active\n\t\tkeeper.Hooks().AfterProposalVotingPeriodEnded(ctx, proposal.Id)\n\n\t\tlogger.Info(\n\t\t\t\"proposal tallied\",\n\t\t\t\"proposal\", proposal.Id,\n\t\t\t\"status\", proposal.Status.String(),\n\t\t\t\"expedited\", proposal.Expedited,\n\t\t\t\"title\", proposal.Title,\n\t\t\t\"results\", logMsg,\n\t\t)\n\n\t\tctx.EventManager().EmitEvent(\n\t\t\tsdk.NewEvent(\n\t\t\t\ttypes.EventTypeActiveProposal,\n\t\t\t\tsdk.NewAttribute(types.AttributeKeyProposalID, fmt.Sprintf(\"%d\", proposal.Id)),\n\t\t\t\tsdk.NewAttribute(types.AttributeKeyProposalResult, tagValue),\n\t\t\t\tsdk.NewAttribute(types.AttributeKeyProposalLog, logMsg),\n\t\t\t),\n\t\t)\n\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func CheckObstacles(party structs.Party, room *structs.Room) (structs.Party, *structs.Room) {\n\t//\n\troll := rand.Intn(20) + 1\n\tfmt.Println(\"TEST\")\n\tbonus := 0\n\tobstaclesPassed := 0\n\n\tfor _, obstacle := range room.Obstacles {\n\t\tif obstacle.ObstaclePassed {\n\t\t\tobstaclesPassed++\n\t\t\tcontinue\n\t\t}\n\t\t// Loop through party\n\t\tfor _, player := range party.Members {\n\t\t\tif player.Condition == \"Dead\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif obstacle.ObstacleType == \"Door\" {\n\t\t\t\t// Locked door -- lockpick it\n\t\t\t\tbonus = BonusAllocation(player.Proficiencies.Stealth)\n\t\t\t} else if obstacle.ObstacleType == \"Rubble\" || obstacle.ObstacleType == \"GiantMachine\" || obstacle.ObstacleType == \"Boulder\" {\n\t\t\t\t// Physique check\n\t\t\t\tbonus = BonusAllocation(player.Proficiencies.Fisticuffs)\n\t\t\t} else if obstacle.ObstacleType == \"Inactive Machine\" {\n\t\t\t\tbonus = BonusAllocation(player.Proficiencies.Engineering)\n\t\t\t}\n\n\t\t\tif roll+bonus > obstacle.ObstacleRequirement || roll == 20 {\n\t\t\t\t// Obstacle passed\n\t\t\t\tobstacle.ObstaclePassed = true\n\t\t\t\tobstaclesPassed++\n\t\t\t\tplayer.Stats.ObstaclesOvercome++\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif obstaclesPassed == len(room.Obstacles) {\n\t\t\t// Break Locks on Room\n\t\t\troom.Locked = false\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn party, room\n}", "func (host *DinnerHost) Init(tableCount, maxParallel, maxDinner int) {\n\thost.phiData = make(map[string]*philosopherData)\n\thost.requestChannel = make(chan string)\n\thost.finishChannel = make(chan string)\n\thost.maxParallel = maxParallel\n\tif host.maxParallel > tableCount {\n\t\thost.maxParallel = tableCount\n\t}\n\thost.maxDinner = maxDinner\n\thost.currentlyEating = 0\n\thost.tableCount = tableCount\n\thost.chopsticksFree = make([]bool, 5)\n\tfor i := range host.chopsticksFree {\n\t\thost.chopsticksFree[i] = true\n\t}\n\trand.Seed(time.Now().Unix())\n\thost.freeSeats = rand.Perm(tableCount)\n}", "func TestRecommendConfigEtcd_CheckProviderProbability_SponsoredProductsOn(t *testing.T) {\n\tcfg := &recommendConfigEtcd{\n\t\trecommendEnabled: true,\n\t\trecommendMainPageEnabled: true,\n\t\trecommendDataScience: 0,\n\t\trecommendSponsoredProducts: 100,\n\t\trecommendTaobao: 0,\n\t\trandomizer: rand.New(rand.NewSource(time.Now().UnixNano())),\n\t}\n\n\tassert.Equal(t, false, cfg.CheckProviderProbability(ProviderTB))\n\tassert.Equal(t, false, cfg.CheckProviderProbability(ProviderTBPlacement))\n\tassert.Equal(t, false, cfg.CheckProviderProbability(ProviderTBWidget))\n\tassert.Equal(t, false, cfg.CheckProviderProbability(ProviderDS))\n\tassert.Equal(t, true, cfg.CheckProviderProbability(ProviderSP))\n}", "func (r *RaftNode) CandidateLooksEligible(candLastLogIdx LogIndex, candLastLogTerm Term) bool {\n\tourLastLogTerm := r.getLastLogTerm()\n\tourLastLogIdx := r.getLastLogIndex()\n\tif r.verbose {\n\t\tlog.Printf(\"We have: lastLogTerm=%d, lastLogIdx=%d. They have: lastLogTerm=%d, lastLogIdx=%d\", ourLastLogTerm, ourLastLogIdx, candLastLogTerm, candLastLogIdx)\n\t}\n\n\tif ourLastLogTerm == candLastLogTerm {\n\t\treturn candLastLogIdx >= ourLastLogIdx\n\t}\n\treturn candLastLogTerm >= ourLastLogTerm\n}", "func (a *aquarium) spawn() {\n\t// FIXME: do something with fish food\n\tfor _, spawner := range a.spawners {\n\t\tif rand.Float64() > 1-spawner.chance {\n\t\t\ta.fish = append(a.fish, spawner.spawn(a.bounds))\n\t\t}\n\t}\n}", "func TestRecommendConfigEtcd_CheckProviderProbability_On(t *testing.T) {\n\tcfg := &recommendConfigEtcd{\n\t\trecommendEnabled: true,\n\t\trecommendMainPageEnabled: true,\n\t\trecommendDataScience: 100,\n\t\trecommendSponsoredProducts: 100,\n\t\trecommendTaobao: 100,\n\t\trandomizer: rand.New(rand.NewSource(time.Now().UnixNano())),\n\t}\n\n\tassert.Equal(t, true, cfg.CheckProviderProbability(ProviderTB))\n\tassert.Equal(t, true, cfg.CheckProviderProbability(ProviderTBPlacement))\n\tassert.Equal(t, true, cfg.CheckProviderProbability(ProviderTBWidget))\n\tassert.Equal(t, true, cfg.CheckProviderProbability(ProviderDS))\n\tassert.Equal(t, true, cfg.CheckProviderProbability(ProviderSP))\n}", "func (a *_Atom) isElectronDonating() bool {\n\tif a.unsatEwNbrCount > 0 || a.satEwNbrCount > 0 ||\n\t\ta.unsaturation != cmn.UnsaturationNone {\n\t\treturn false\n\t}\n\n\tswitch a.atNum {\n\tcase 7, 15:\n\t\treturn a.bonds.Count() <= 3\n\tcase 8, 16:\n\t\treturn a.bonds.Count() <= 2\n\t}\n\n\treturn false\n}", "func (r *Room) Participate(p Player, x, y int, color string) bool {\n\tif r.Status != Waiting {\n\t\treturn false\n\t}\n\treturn r.board.Add(p, x, y, color)\n}", "func (ec *EthereumChain) IsEligibleForApplication(application common.Address) (bool, error) {\n\treturn ec.bondedECDSAKeepFactoryContract.IsOperatorEligible(\n\t\tec.Address(),\n\t\tapplication,\n\t)\n}", "func kidsWithCandies(candies []int, extraCandies int) []bool {\n max := candies[0]\n var res []bool\n for _, value := range candies {\n if value >= max {\n max = value\n }\n }\n for _, value := range candies {\n if value+extraCandies >= max {\n res = append(res, true)\n } else {\n res = append(res, false)\n }\n }\n return res\n}", "func testParallelismWithBeverages(bm *BeverageMachine, beverageNames []string) {\n\n\tfmt.Printf(\"\\nstarting test: testParallelismWithBeverages\\n\\n\")\n\n\twg := sync.WaitGroup{}\n\tfor i, beverageName := range beverageNames {\n\t\twg.Add(1)\n\t\tgo func(i int, beverageName string) {\n\t\t\tdefer wg.Done()\n\n\t\t\tfmt.Printf(\"thread %d-> start\\n\", i+1)\n\n\t\t\t//1. get an idle dispenser\n\t\t\tdispenser, err := bm.GetIdleDispenser()\n\t\t\tfor err != nil {\n\t\t\t\tfmt.Printf(\"thread %d-> %s, retrying in 2 seconds...\\n\", i+1, err.Error())\n\t\t\t\ttime.Sleep(2 * time.Second)\n\t\t\t\tdispenser, err = bm.GetIdleDispenser()\n\t\t\t}\n\t\t\tfmt.Printf(\"thread %d-> acquired dispenser %d\\n\", i+1, dispenser.GetId())\n\n\t\t\tfmt.Printf(\"thread %d-> starting to prepare %s on dispenser %d...\\n\", i+1, beverageName, dispenser.GetId())\n\n\t\t\t//2. request the beverage from the dispenser\n\t\t\tbeverage, err := bm.RequestBeverage(dispenser, beverageName)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"thread %d-> dispenser %d says: %s\\n\", i+1, dispenser.GetId(), err.Error())\n\t\t\t\tfmt.Printf(\"thread %d-> end\\n\", i+1)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfmt.Printf(\"thread %d-> successfully served %s on dispenser %d\\n\", i+1, beverage.GetName(), dispenser.GetId())\n\t\t\tfmt.Printf(\"thread %d-> end\\n\", i+1)\n\t\t}(i, beverageName)\n\t}\n\twg.Wait()\n\n\tfmt.Println(\"\\ncompleted test: testParallelismWithBeverages\\n\")\n}", "func (g *Game) isSpare(rollIndex int) bool {\n\treturn g.rolls[rollIndex]+g.rolls[rollIndex+1] == cleanPinNumber\n}", "func (b *picnicBasket) happy() bool {\n\treturn b.nServings > 1 && b.corkscrew\n}", "func electionTimeout() int64 {\n\treturn int64(rand.Intn(MAXELECTIMEOUT- MINELECTIMEOUT) + MINELECTIMEOUT)\n}", "func (cb *CircuitBreaker) Allow() bool {\n\t// force open the circuit, link is break so this is not allowed.\n\tif cb.forceOpen {\n\t\treturn false\n\t}\n\t// force close the circuit, link is not break so this is allowed.\n\tif cb.forceClose {\n\t\treturn true\n\t}\n\n\tvar now_ms int64\n\tnow_ms = NowInMs()\n\tcb.CalcStat(now_ms)\n\n\tif cb.circuitStatus == kCircuitClose {\n\t\treturn true\n\t} else {\n\t\tif cb.IsAfterSleepWindow(now_ms) {\n\t\t\tcb.lastCircuitOpenTime = now_ms\n\t\t\tcb.circuitStatus = kCircuitHalfOpen\n\t\t\t// sleep so long time, try ones, and set status to half-open\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func Test_TaskOption_LeadershipTimeout(t *testing.T) {\n\t// given\n\toption := crontask.LeadershipTimeout(time.Second)\n\toptions := &crontask.TaskOptions{LeadershipTimeout: time.Hour}\n\n\t// when\n\toption(options)\n\n\t// then\n\tif options.LeadershipTimeout != time.Second {\n\t\tt.Errorf(\"leadership timeout not correctly applied, got %s\", options.LeadershipTimeout)\n\t}\n}", "func (o *MicrosoftGraphTeamFunSettings) SetAllowStickersAndMemes(v bool) {\n\to.AllowStickersAndMemes = &v\n}", "func (l *RateLimiter) AllowN(now time.Time, tenantID string, n int) (bool, Reservation) {\n\n\t// Using ReserveN allows cancellation of the reservation, but\n\t// the semantics are subtly different to AllowN.\n\tr := l.getTenantLimiter(now, tenantID).ReserveN(now, n)\n\tif !r.OK() {\n\t\treturn false, nil\n\t}\n\n\t// ReserveN will still return OK if the necessary tokens are\n\t// available in the future, and tells us this time delay. In\n\t// order to mimic the semantics of AllowN, we must check that\n\t// there is no delay before we can use them.\n\tif r.DelayFrom(now) > 0 {\n\t\t// Having decided not to use the reservation, return the\n\t\t// tokens to the rate limiter.\n\t\tr.CancelAt(now)\n\t\treturn false, nil\n\t}\n\n\treturn true, r\n}", "func (s *BaseSpeaker) DecideNextJudge(winner shared.ClientID) shared.ClientID {\n\treturn winner\n}", "func TestElectVotersNonDupDeterministic(t *testing.T) {\n\tcandidates1 := newValidatorSet(100, func(i int) int64 { return int64(i + 1) })\n\tcandidates2 := newValidatorSet(100, func(i int) int64 { return int64(i + 1) })\n\tfor i := 1; i <= 100; i++ {\n\t\twinners1 := electVotersNonDup(candidates1.Validators, uint64(i), 24, 0)\n\t\twinners2 := electVotersNonDup(candidates2.Validators, uint64(i), 24, 0)\n\t\tsameVoters(winners1, winners2)\n\t\tresetPoints(candidates1)\n\t\tresetPoints(candidates2)\n\t}\n}", "func kidsWithGreatesNrOfCandies2(candies []int, extraCandies int) []bool {\n\tgreatest := 0\n\tresult := make([]bool, len(candies))\n\n\tfor _, v := range candies {\n\t\tif v > greatest {\n\t\t\tgreatest = v\n\t\t}\n\t}\n\tfor i, v := range candies {\n\t\tif v+extraCandies >= greatest {\n\t\t\tresult[i] = true\n\t\t}\n\t}\n\treturn result\n}", "func TestRecommendConfigEtcd_CheckProviderProbability_DataScienceOn(t *testing.T) {\n\tcfg := &recommendConfigEtcd{\n\t\trecommendEnabled: true,\n\t\trecommendMainPageEnabled: true,\n\t\trecommendDataScience: 100,\n\t\trecommendSponsoredProducts: 0,\n\t\trecommendTaobao: 0,\n\t\trandomizer: rand.New(rand.NewSource(time.Now().UnixNano())),\n\t}\n\n\tassert.Equal(t, false, cfg.CheckProviderProbability(ProviderTB))\n\tassert.Equal(t, false, cfg.CheckProviderProbability(ProviderTBPlacement))\n\tassert.Equal(t, false, cfg.CheckProviderProbability(ProviderTBWidget))\n\tassert.Equal(t, true, cfg.CheckProviderProbability(ProviderDS))\n\tassert.Equal(t, false, cfg.CheckProviderProbability(ProviderSP))\n}", "func (w *pollWorker) handleVoteForElectingPeer(voter net.Addr, vote VoteMsg) bool {\n\n\t// compare the round. When there are electing peers, they will eventually\n\t// converge to the same round when quorum is reached. This implies that\n\t// an established ensemble should share the same round, and this value\n\t// remains stable for the ensemble.\n\tcompareRound := w.compareRound(vote)\n\n\t// if the incoming vote has a greater round, re-ballot.\n\tif compareRound == common.GREATER {\n\n\t\t// update the current round. This need to be done\n\t\t// before updateProposed() is called.\n\t\tw.site.master.setCurrentRound(vote.GetRound())\n\n\t\tif w.compareVoteWithCurState(vote) == common.GREATER {\n\t\t\t// Update my vote if the incoming vote is larger.\n\t\t\tw.ballot.resetAndUpdateProposed(vote, w.site)\n\t\t} else {\n\t\t\t// otherwise udpate my vote using lastLoggedTxid\n\t\t\tw.ballot.resetAndUpdateProposed(w.site.createVoteFromCurState(), w.site)\n\t\t}\n\n\t\t// notify that our new vote\n\t\tw.site.messenger.Multicast(w.cloneProposedVote(), w.site.ensemble)\n\n\t\t// if we reach quorum with this vote, announce the result\n\t\t// and stop election\n\t\treturn w.acceptAndCheckQuorum(voter, vote)\n\n\t} else if compareRound == common.EQUAL {\n\t\t// if it is the same round and the incoming vote has higher epoch or txid,\n\t\t// update myself to the incoming vote and broadcast my new vote\n\t\tswitch w.compareVoteWithProposed(vote) {\n\t\tcase common.GREATER:\n\t\t\t// update and notify that our new vote\n\t\t\tw.ballot.updateProposed(vote, w.site)\n\t\t\tw.site.messenger.Multicast(w.cloneProposedVote(), w.site.ensemble)\n\n\t\t\t// Add this vote to the received list. Note that even if\n\t\t\t// the peer went down there is network partition after the\n\t\t\t// vote is being sent by peer, we still count this vote.\n\t\t\t// If somehow we got the wrong leader because of this, we\n\t\t\t// not be able to finish in the discovery/sync phase anyway,\n\t\t\t// and a new election will get started.\n\n\t\t\t// If I believe I am chosen as a leader in the election\n\t\t\t// and the network is partitioned afterwards. The\n\t\t\t// sychonization phase will check if I do get a majorty\n\t\t\t// of followers connecting to me before proceeding. So\n\t\t\t// for now, I can return as long as I reach quorum and\n\t\t\t// let subsequent phase to do more checking.\n\n\t\t\treturn w.acceptAndCheckQuorum(voter, vote)\n\t\tcase common.EQUAL:\n\t\t\treturn w.acceptAndCheckQuorum(voter, vote)\n\t\t}\n\t} else {\n\t\t// My round is higher. Send back the notification to the sender with my round\n\t\tw.site.messenger.Send(w.cloneProposedVote(), voter)\n\t}\n\n\treturn false\n}", "func BenchmarkElectVotersNonDupEquity(b *testing.B) {\n\tloopCount := 10000\n\n\t// good condition\n\tcandidates := newValidatorSet(100, func(i int) int64 { return 1000000 + rand.Int64()&0xFFFFF })\n\ttotalStaking := int64(0)\n\tfor _, c := range candidates.Validators {\n\t\ttotalStaking += c.StakingPower\n\t}\n\n\taccumulatedRewards := make(map[string]int64, 100)\n\ttotalAccumulateRewards := int64(0)\n\tfor i := 0; i < loopCount; i++ {\n\t\twinners := electVotersNonDup(candidates.Validators, uint64(i), 20, 0)\n\t\ttotalAccumulateRewards += accumulateAndResetReward(winners, accumulatedRewards)\n\t}\n\tfor i := 0; i < 99; i++ {\n\t\trewardRate := float64(accumulatedRewards[candidates.Validators[i].Address.String()]) /\n\t\t\tfloat64(totalAccumulateRewards)\n\t\tstakingRate := float64(candidates.Validators[i].StakingPower) / float64(totalStaking)\n\t\trate := rewardRate / stakingRate\n\t\trewardPerStakingDiff := math.Abs(1 - rate)\n\t\tb.Log(\"rewardPerStakingDiff\", rewardPerStakingDiff)\n\t\t//\n\t\t// rewardPerStakingDiff: guarantees the fairness of rewards\n\t\t// if false, then we should consider `rewardPerStakingDiff` value\n\t\t//\n\t\tassert.True(b, rewardPerStakingDiff < 0.02)\n\t}\n\n\t// =======================================================================================================\n\t// The codes below are not test codes to verify logic,\n\t// but codes to find out what parameters are that weaken the equity of rewards.\n\n\t// violation of condition 1\n\tcandidates = newValidatorSet(100, func(i int) int64 { return rand.Int64() & 0xFFFFFFFFF })\n\taccumulatedRewards = make(map[string]int64, 100)\n\tfor i := 0; i < loopCount; i++ {\n\t\twinners := electVotersNonDup(candidates.Validators, uint64(i), 20, 0)\n\t\taccumulateAndResetReward(winners, accumulatedRewards)\n\t}\n\tmaxRewardPerStakingDiff := float64(0)\n\tfor i := 0; i < 99; i++ {\n\t\trewardPerStakingDiff :=\n\t\t\tmath.Abs(float64(accumulatedRewards[candidates.Validators[i].Address.String()])/\n\t\t\t\tfloat64(candidates.Validators[i].StakingPower)/float64(loopCount) - 1)\n\t\tif maxRewardPerStakingDiff < rewardPerStakingDiff {\n\t\t\tmaxRewardPerStakingDiff = rewardPerStakingDiff\n\t\t}\n\t}\n\tb.Logf(\"[! condition 1] max reward per staking difference: %f\", maxRewardPerStakingDiff)\n\n\t// violation of condition 2\n\tcandidates = newValidatorSet(100, func(i int) int64 { return rand.Int64() & 0xFFFFF })\n\taccumulatedRewards = make(map[string]int64, 100)\n\tfor i := 0; i < loopCount; i++ {\n\t\twinners := electVotersNonDup(candidates.Validators, uint64(i), 20, 0)\n\t\taccumulateAndResetReward(winners, accumulatedRewards)\n\t}\n\tmaxRewardPerStakingDiff = float64(0)\n\tfor i := 0; i < 99; i++ {\n\t\trewardPerStakingDiff :=\n\t\t\tmath.Abs(float64(accumulatedRewards[candidates.Validators[i].Address.String()])/\n\t\t\t\tfloat64(candidates.Validators[i].StakingPower)/float64(loopCount) - 1)\n\t\tif maxRewardPerStakingDiff < rewardPerStakingDiff {\n\t\t\tmaxRewardPerStakingDiff = rewardPerStakingDiff\n\t\t}\n\t}\n\tb.Logf(\"[! condition 2] max reward per staking difference: %f\", maxRewardPerStakingDiff)\n\n\t// violation of condition 3\n\tcandidates = newValidatorSet(100, func(i int) int64 { return 1000000 + rand.Int64()&0xFFFFF })\n\taccumulatedRewards = make(map[string]int64, 100)\n\tfor i := 0; i < loopCount; i++ {\n\t\twinners := electVotersNonDup(candidates.Validators, uint64(i), 20, 0)\n\t\taccumulateAndResetReward(winners, accumulatedRewards)\n\t}\n\tmaxRewardPerStakingDiff = float64(0)\n\tfor i := 0; i < 99; i++ {\n\t\trewardPerStakingDiff :=\n\t\t\tmath.Abs(float64(accumulatedRewards[candidates.Validators[i].Address.String()])/\n\t\t\t\tfloat64(candidates.Validators[i].StakingPower)/float64(loopCount) - 1)\n\t\tif maxRewardPerStakingDiff < rewardPerStakingDiff {\n\t\t\tmaxRewardPerStakingDiff = rewardPerStakingDiff\n\t\t}\n\t}\n\tb.Logf(\"[! condition 3] max reward per staking difference: %f\", maxRewardPerStakingDiff)\n\n\t// violation of condition 4\n\tloopCount = 100\n\tcandidates = newValidatorSet(100, func(i int) int64 { return 1000000 + rand.Int64()&0xFFFFF })\n\taccumulatedRewards = make(map[string]int64, 100)\n\tfor i := 0; i < loopCount; i++ {\n\t\twinners := electVotersNonDup(candidates.Validators, uint64(i), 33, 0)\n\t\taccumulateAndResetReward(winners, accumulatedRewards)\n\t}\n\tmaxRewardPerStakingDiff = float64(0)\n\tfor i := 0; i < 99; i++ {\n\t\trewardPerStakingDiff :=\n\t\t\tmath.Abs(float64(accumulatedRewards[candidates.Validators[i].Address.String()])/\n\t\t\t\tfloat64(candidates.Validators[i].StakingPower)/float64(loopCount) - 1)\n\t\tif maxRewardPerStakingDiff < rewardPerStakingDiff {\n\t\t\tmaxRewardPerStakingDiff = rewardPerStakingDiff\n\t\t}\n\t}\n\tb.Logf(\"[! condition 4] max reward per staking difference: %f\", maxRewardPerStakingDiff)\n}", "func (l *LimitRate) Allow() bool {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\n\tif l.count >= l.rate - 1 {\n\t\tnow := time.Now()\n\t\tif now.Sub(l.begin) >= l.cycle {\n\t\t\tl.Reset(now)\n\t\t\treturn true\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t} else {\n\t\tl.count++\n\t\treturn true\n\t}\n}", "func checkKingSafety(file int, pawns []engine.Square) float64 {\n\tpawnarray := [8]int{}\n\tfor _, p := range pawns {\n\t\tpawnarray[p.X-1] += 1\n\t}\n\tvar score float64\n\tfor i := -1; i < 2; i++ {\n\t\tif location := file + i; location > -1 && location < 8 {\n\t\t\tif pawnarray[location] == 0 {\n\t\t\t\tscore += KINGONOPENFILE\n\t\t\t} else {\n\t\t\t\tscore += KINGPROTECTED\n\t\t\t}\n\t\t}\n\t}\n\tif file == 1 || file == 2 || file == 7 || file == 8 {\n\t\tscore += KINGINCORNER\n\t} else {\n\t\tscore -= KINGINCORNER\n\t}\n\treturn score\n}", "func updateSeatNonBidsFloors(seatNonBids *nonBids, rejectedBids []*entities.PbsOrtbSeatBid) {\n\tfor _, pbsRejSeatBid := range rejectedBids {\n\t\tfor _, pbsRejBid := range pbsRejSeatBid.Bids {\n\t\t\tvar rejectionReason = openrtb3.LossBidBelowAuctionFloor\n\t\t\tif pbsRejBid.Bid.DealID != \"\" {\n\t\t\t\trejectionReason = openrtb3.LossBidBelowDealFloor\n\t\t\t}\n\t\t\tseatNonBids.addBid(pbsRejBid, int(rejectionReason), pbsRejSeatBid.Seat)\n\t\t}\n\t}\n}", "func TestOccupyOnlyWithOneFleet(t *testing.T) {\n\tspace := state.EmptySpace()\n\te1 := space.CreateEmpire()\n\te2 := space.CreateEmpire()\n\n\tp1 := space.CreatePlanet(e1)\n\tp2 := space.CreatePlanet(e2)\n\n\tp1.Connected = append(p1.Connected, p2)\n\tp1.Control = 0.1\n\n\tf1 := space.CreateFleet(p1, e1)\n\tf1.LightSquads = 1\n\tf2 := space.CreateFleet(p1, e1)\n\tf2.LightSquads = 1\n\n\tstrat := Distributed{}\n\tstrat.Init(e1)\n\n\tcmds := strat.Commands(&space)\n\tcmds[0].Execute(&space)\n\tif len(cmds) != 1 || len(p1.Fleets) != 1 || len(p2.Fleets) != 1 {\n\t\tt.Error(\"Fleet did not move to next planet\")\n\t\treturn\n\t}\n}", "func (a *Attacker) Attack(tr Targeter, p Pacer, du time.Duration, name string) <-chan *Result {\n\tvar wg sync.WaitGroup\n\n\tworkers := a.workers\n\tif workers > a.maxWorkers {\n\t\tworkers = a.maxWorkers\n\t}\n\n\tresults := make(chan *Result)\n\tticks := make(chan struct{})\n\tfor i := uint64(0); i < workers; i++ {\n\t\twg.Add(1)\n\t\tgo a.attack(tr, name, &wg, ticks, results)\n\t}\n\n\tgo func() {\n\t\tdefer close(results)\n\t\tdefer wg.Wait()\n\t\tdefer close(ticks)\n\n\t\tbegan, count := time.Now(), uint64(0)\n\t\tfor {\n\t\t\telapsed := time.Since(began)\n\t\t\tif du > 0 && elapsed > du {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\twait, stop := p.Pace(elapsed, count)\n\t\t\tif stop {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ttime.Sleep(wait)\n\n\t\t\tif workers < a.maxWorkers {\n\t\t\t\tselect {\n\t\t\t\tcase ticks <- struct{}{}:\n\t\t\t\t\tcount++\n\t\t\t\t\tcontinue\n\t\t\t\tcase <-a.stopch:\n\t\t\t\t\treturn\n\t\t\t\tdefault:\n\t\t\t\t\t// all workers are blocked. start one more and try again\n\t\t\t\t\tworkers++\n\t\t\t\t\twg.Add(1)\n\t\t\t\t\tgo a.attack(tr, name, &wg, ticks, results)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tselect {\n\t\t\tcase ticks <- struct{}{}:\n\t\t\t\tcount++\n\t\t\tcase <-a.stopch:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn results\n}", "func (p *Player) CanProceed(head, tail int) bool {\n\tfor _, domino := range p.GetDominos() {\n\t\tif domino.half[0] == head || domino.half[0] == tail ||\n\t\t\tdomino.half[1] == head || domino.half[1] == tail {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (opts *RSA3072KeyGenOpts) Ephemeral() bool {\n\treturn opts.Temporary\n}", "func (opts *ED25519ReRandKeyOpts) Ephemeral() bool {\n\treturn opts.Temporary\n}", "func shouldIPing() bool {\n\treturn !initialElection &&\n\t\t!bullyImpl.EnCours() &&\n\t\t!bullyImpl.IsCoordinator()\n}", "func (_Contracts *ContractsSession) GetEligibleVoters(_proposal *big.Int, _voterAddr common.Address) (struct {\n\tVoterId *big.Int\n\tVoterAddr common.Address\n\tPositionId *big.Int\n\tIsVerified bool\n\tIsVoted bool\n}, error) {\n\treturn _Contracts.Contract.GetEligibleVoters(&_Contracts.CallOpts, _proposal, _voterAddr)\n}", "func (_Contracts *ContractsCallerSession) GetEligibleVoters(_proposal *big.Int, _voterAddr common.Address) (struct {\n\tVoterId *big.Int\n\tVoterAddr common.Address\n\tPositionId *big.Int\n\tIsVerified bool\n\tIsVoted bool\n}, error) {\n\treturn _Contracts.Contract.GetEligibleVoters(&_Contracts.CallOpts, _proposal, _voterAddr)\n}", "func distributeLockedAmount(ctx coretypes.Sandbox, bets []*BetInfo, totalLockedAmount int64) bool {\n\tsumsByPlayers := make(map[coretypes.AgentID]int64)\n\ttotalWinningAmount := int64(0)\n\tfor _, bet := range bets {\n\t\tif _, ok := sumsByPlayers[bet.Player]; !ok {\n\t\t\tsumsByPlayers[bet.Player] = 0\n\t\t}\n\t\tsumsByPlayers[bet.Player] += bet.Sum\n\t\ttotalWinningAmount += bet.Sum\n\t}\n\n\t// NOTE 1: float64 was avoided for determinism reasons\n\t// NOTE 2: beware overflows\n\n\tfor player, sum := range sumsByPlayers {\n\t\tsumsByPlayers[player] = (totalLockedAmount * sum) / totalWinningAmount\n\t}\n\n\t// make deterministic sequence by sorting. Eliminate possible rounding effects\n\tseqPlayers := make([]coretypes.AgentID, 0, len(sumsByPlayers))\n\tresultSum := int64(0)\n\tfor player, sum := range sumsByPlayers {\n\t\tseqPlayers = append(seqPlayers, player)\n\t\tresultSum += sum\n\t}\n\tsort.Slice(seqPlayers, func(i, j int) bool {\n\t\treturn bytes.Compare(seqPlayers[i][:], seqPlayers[j][:]) < 0\n\t})\n\n\t// ensure we distribute not more than totalLockedAmount iotas\n\tif resultSum > totalLockedAmount {\n\t\tsumsByPlayers[seqPlayers[0]] -= resultSum - totalLockedAmount\n\t}\n\n\t// filter out those who proportionally got 0\n\tfinalWinners := seqPlayers[:0]\n\tfor _, player := range seqPlayers {\n\t\tif sumsByPlayers[player] <= 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfinalWinners = append(finalWinners, player)\n\t}\n\t// distribute iotas\n\tfor i := range finalWinners {\n\n\t\tavailable := ctx.Balance(balance.ColorIOTA)\n\t\tctx.Event(fmt.Sprintf(\"sending reward iotas %d to the winner %s. Available iotas: %d\",\n\t\t\tsumsByPlayers[finalWinners[i]], finalWinners[i].String(), available))\n\n\t\t//if !ctx.MoveTokens(finalWinners[i], balance.ColorIOTA, sumsByPlayers[finalWinners[i]]) {\n\t\t//\treturn false\n\t\t//}\n\t}\n\treturn true\n}", "func canShovelSoftlock(g graph.Graph) error {\n\t// first check if the gift has been reached\n\tgift := g[\"shovel gift\"]\n\tif gift.Mark != graph.MarkTrue {\n\t\treturn nil\n\t}\n\n\tshovel := g[\"shovel\"]\n\tparents := shovel.Parents\n\n\t// if the slot hasn't been assigned yet or it *is* the shovel, it's fine\n\tif len(gift.Children) > 0 &&\n\t\t!graph.IsNodeInSlice(gift, shovel.Parents) {\n\t\t// check whether gift is reachable if shovel is unreachable\n\t\tshovel.ClearParents()\n\t\tdefer shovel.AddParents(parents...)\n\t\tg.ClearMarks()\n\t\tif gift.GetMark(gift, nil) == graph.MarkTrue {\n\t\t\treturn errors.New(\"shovel softlock\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func lotteryWon(slot int, d *big.Int, seed int, n *big.Int) bool {\n\n\tvar draw = getSignatureDraw(Draw{\"LOTTERY\", seed, slot}, d, n)\n\tvar a = big.NewInt(int64(1000000))\n\n\tvar val = a.Mul(a, calculateH(\"LOTTERY\", seed, slot, n, draw))\n\n\t// setup hardness\n\tvar bytes = []byte{14, 254, 25, 47, 168, 142, 151, 44, 64, 169, 66, 22, 115, 60, 181, 27, 3, 168, 232, 247, 103, 64, 178, 132, 83, 129, 11, 233, 218, 9, 131, 94, 12, 43, 4}\n\tvar hardness = new(big.Int)\n\thardness = hardness.SetBytes(bytes[:])\n\n\t// lottery won\n\tif val.Cmp(hardness) == 1 {\n\t\treturn true\n\t}\n\treturn false\n}", "func (pp Points) SimulatedAnnealing(cooling float64, iterations int) PointsSolution {\r\n\tvar solution PointsSolution\r\n\tpp.Shuffle()\r\n\r\n\t// Bounds and default values\r\n\tif cooling < 0.85 || cooling > 0.99 {\r\n\t\tcooling = 0.98\r\n\t}\r\n\r\n\tif iterations < 1 || iterations < 500 {\r\n\t\titerations = 200\r\n\t}\r\n\r\n\t// Acceptance probability\r\n\tap := func(last float64, current float64, t float64) float64 {\r\n\t\treturn math.Exp(((last-current)/10000)/t)\r\n\t}\r\n\r\n\tfor t := 1.0; t > 0.00001; t *= cooling {\r\n\t\tkeep := make(Points, len(pp))\r\n\t\tcopy(keep, pp)\r\n\r\n\t\t// Send all solutions for visualization\r\n\t\tsolution = append(solution, keep)\r\n\r\n\t\tfor i := 0; i < iterations; i += 1 {\r\n\t\t\tpp2 := pp.Neighbour()\r\n\t\t\tif ap(pp.Len(), pp2.Len(), t) > rand.Float64() {\r\n\t\t\t\tcopy(pp, pp2)\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn solution\r\n}", "func (_Contract *ContractCallerSession) CalculateVotingTally(proposalID *big.Int) (struct {\n\tProposalResolved bool\n\tWinnerID *big.Int\n\tVotes *big.Int\n}, error) {\n\treturn _Contract.Contract.CalculateVotingTally(&_Contract.CallOpts, proposalID)\n}", "func TestSelectVoterMaxVarious(t *testing.T) {\n\thash := 0\n\tfor minMaxRate := 1; minMaxRate <= 100000000; minMaxRate *= 10000 {\n\t\tt.Logf(\"<<< min: 100, max: %d >>>\", 100*minMaxRate)\n\t\tfor validators := 16; validators <= 256; validators *= 4 {\n\t\t\tfor voters := 1; voters <= validators; voters += 10 {\n\t\t\t\tvalSet, _ := randValidatorSetWithMinMax(PrivKeyEd25519, validators, 100, 100*int64(minMaxRate))\n\t\t\t\tvoterSet := SelectVoter(valSet, []byte{byte(hash)}, &VoterParams{int32(voters), 20})\n\t\t\t\tif voterSet.Size() < voters {\n\t\t\t\t\tt.Logf(\"Cannot elect voters up to MaxVoters: validators=%d, MaxVoters=%d, actual voters=%d\",\n\t\t\t\t\t\tvalidators, voters, voterSet.Size())\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\thash++\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *MovesSuite) TestPawnForwardTwiceBlocked() {\n\t// blocked by enemy queen\n\tmoves := s.validateMovesByFEN(\n\t\t\"8/8/8/8/4q3/8/4P3/8 w - - 0 1\",\n\t\tengine.TT(\"e2\"),\n\t\t[]engine.Tile{\n\t\t\tengine.TT(\"e3\"),\n\t\t},\n\t)\n\n\tassert.Equal(s.T(), 1, len(moves))\n\n\t// blocked by own knight\n\tmoves = s.validateMovesByFEN(\n\t\t\"8/8/8/8/4N3/8/4P3/8 w - - 0 1\",\n\t\tengine.TT(\"e2\"),\n\t\t[]engine.Tile{\n\t\t\tengine.TT(\"e3\"),\n\t\t},\n\t)\n\n\tassert.Equal(s.T(), 1, len(moves))\n}", "func (s *BaseSpeaker) CallJudgeElection(monitoring shared.MonitorResult, turnsInPower int, allIslands []shared.ClientID) shared.ElectionSettings {\n\t// example implementation calls an election if monitoring was performed and the result was negative\n\t// or if the number of turnsInPower exceeds 3\n\tvar electionsettings = shared.ElectionSettings{\n\t\tVotingMethod: shared.BordaCount,\n\t\tIslandsToVote: allIslands,\n\t\tHoldElection: false,\n\t}\n\tif monitoring.Performed && !monitoring.Result {\n\t\telectionsettings.HoldElection = true\n\t}\n\tif turnsInPower >= 2 {\n\t\telectionsettings.HoldElection = true\n\t}\n\treturn electionsettings\n}", "func (phi *Philosopher) GoToDinner(waitGrp *sync.WaitGroup, requestChannel, finishChannel chan string) {\n\tdefer waitGrp.Done()\n\n\tretryInterval := time.Duration(2000) * time.Millisecond\n\teatingDuration := time.Duration(5000) * time.Millisecond\n\n\tfor {\n\t\trequestChannel <- phi.name\n\t\tswitch <-phi.respChannel {\n\t\tcase \"OK\":\n\t\t\ttime.Sleep(eatingDuration)\n\t\t\tfinishChannel <- phi.name\n\t\tcase \"E:LIMIT\":\n\t\t\tfmt.Println(strings.ToUpper(\"----- \" + phi.name + \" LEFT THE TABLE. -----\"))\n\t\t\tfmt.Println()\n\t\t\treturn\n\t\tdefault:\n\t\t\ttime.Sleep(retryInterval)\n\t\t}\n\t}\n}", "func orchestrate(done chan<- bool) {\n\tvar wg sync.WaitGroup\n\tfor i := 1; i <= 25; i++ {\n\t\twg.Add(1)\n\t\tgo work(i, &wg)\n\t}\n\twg.Wait()\n\tdone <- true\n}", "func (s *speaker) CallJudgeElection(monitoring shared.MonitorResult, turnsInPower int, allIslands []shared.ClientID) shared.ElectionSettings {\n\t// example implementation calls an election if monitoring was performed and the result was negative\n\t// or if the number of turnsInPower exceeds 3\n\tvar electionsettings = shared.ElectionSettings{\n\t\tVotingMethod: shared.BordaCount,\n\t\tIslandsToVote: allIslands,\n\t\tHoldElection: false,\n\t}\n\t//there are more important things to do\n\tif s.getSpeakerBudget() < s.getHigherPriorityActionsCost(\"AppointNextJudge\") {\n\t\treturn electionsettings\n\t}\n\tif (monitoring.Performed && !monitoring.Result) || turnsInPower >= 2 {\n\t\telectionsettings.HoldElection = true\n\t}\n\treturn electionsettings\n}", "func (opts *HMACDeriveKeyOpts) Ephemeral() bool {\n\treturn opts.Temporary\n}", "func (opts *HMACDeriveKeyOpts) Ephemeral() bool {\n\treturn opts.Temporary\n}", "func BenchmarkPigeonHole(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\ttestFromFile(b, \"test_cnf_slow/hole8.cnf\", unsat())\n\t\ttestFromFile(b, \"test_cnf_slow/hole9.cnf\", unsat())\n\t}\n}", "func (al *AnomalyDetectionLimiter) Allow(event Event) bool {\n\treturn al.limiter.Allow(event.GetWorkloadID())\n}", "func (ferry *Ferry) CanAccept(car *Car) bool {\n\tfor _, accepted := range ferry.acceptedCars {\n\t\t// check if current type is accepted and has free space for this car.\n\t\tif car.Kind == accepted && len(ferry.loadedCars) < ferry.Capacity {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}" ]
[ "0.6404186", "0.62115526", "0.55111367", "0.5437489", "0.54326123", "0.5042886", "0.50084275", "0.49720517", "0.48578596", "0.45456734", "0.45001084", "0.4490827", "0.44305068", "0.4348827", "0.43133932", "0.42720458", "0.4265262", "0.42454138", "0.42271578", "0.4211225", "0.41849816", "0.414866", "0.4133971", "0.40811026", "0.40666452", "0.40580356", "0.405669", "0.40560362", "0.4048743", "0.40444842", "0.4033853", "0.40276834", "0.3991462", "0.3987721", "0.39850223", "0.3984918", "0.3984918", "0.39840156", "0.39822298", "0.39731315", "0.39731315", "0.3971857", "0.39710236", "0.39704677", "0.39683944", "0.39653105", "0.3959846", "0.3955726", "0.39529532", "0.39414385", "0.39406663", "0.39367694", "0.39279", "0.39258373", "0.3920685", "0.3915061", "0.38830003", "0.38810802", "0.38776854", "0.38752234", "0.38657218", "0.3845934", "0.38351977", "0.3835068", "0.3827794", "0.3823156", "0.38228825", "0.38099426", "0.38094163", "0.38093433", "0.38072547", "0.38069543", "0.38031277", "0.37994754", "0.37966993", "0.37954256", "0.3781459", "0.37780285", "0.37766778", "0.3775189", "0.37691242", "0.3763714", "0.37630263", "0.37583202", "0.3755745", "0.37508476", "0.37493798", "0.37487653", "0.37421727", "0.37413466", "0.37380928", "0.3735574", "0.37299243", "0.3728653", "0.37276337", "0.37247726", "0.37247726", "0.3723894", "0.37197137", "0.37166515" ]
0.72502726
0
SomeoneFinished takes the necessary actions when a philosopher finished eating.
func (host *DinnerHost) SomeoneFinished(name string) { if host.currentlyEating > 0 { host.currentlyEating-- } host.chopsticksFree[host.phiData[name].LeftChopstick()] = true host.chopsticksFree[host.phiData[name].RightChopstick()] = true host.phiData[name].FinishedEating() fmt.Println(name + " FINISHED EATING.") fmt.Println() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pd *philosopherData) FinishedEating() {\n\tpd.eating = false\n\tpd.leftChopstick = -1\n\tpd.rightChopstick = -1\n\tpd.finishedAt = time.Now()\n}", "func (p philosopher) eat() {\n\tfor j := 0; j < numberOfCourses; j++ {\n\t\t//Pick up sticks means lock both mutex\n\t\tp.leftChopstick.Lock()\n\t\tp.rightChopstick.Lock()\n\t\t// Acknowledge the start\n\t\t//starting to eat <number>\n\t\tfmt.Printf(\"Starting to eat %d(%s) [%s] \\n\", p.id+1, nameOfPhilosophers[p.id], courses[j])\n\t\ttime.Sleep(time.Second)\n\t\t//Release mutex\n\t\tp.rightChopstick.Unlock()\n\t\tp.leftChopstick.Unlock()\n\t\t// Acknowledge the finish\n\t\t//finishing eating <number>\n\t\tfmt.Printf(\"finishing eating %d(%s) [%s] \\n\", p.id+1, nameOfPhilosophers[p.id], courses[j])\n\t\ttime.Sleep(time.Second)\n\t}\n\teatWaitingGroup.Done()\n}", "func (philosopher *Philosopher) Eat(wg *sync.WaitGroup, host Host) {\n\tfor i := 0; i < 3; i++ {\n\t\thost.GiveMePermission()\n\t\tphilosopher.leftChopstick.Lock()\n\t\tphilosopher.rightChopstick.Lock()\n\t\tfmt.Printf(\"Starting to eat %d\\n\", philosopher.id)\n\t\ttime.Sleep(500 * time.Millisecond)\n\t\tfmt.Printf(\"Finishing eating %d. (time: %d)\\n\", philosopher.id, i+1)\n\t\tphilosopher.rightChopstick.Unlock()\n\t\tphilosopher.leftChopstick.Unlock()\n\t\thost.Done()\n\t}\n\twg.Done()\n}", "func philosopherPonderanceGoroutine(id int) {\n\tfor {\n\t\tif rand.Float64() < PHILSWITCHCHANCE {\n\t\t\tphilIn[id] <- 2\n\t\t\tisEating := <- philOut[id] == 1\n\t\t\t// Switch: Thinking <-> Eating.\n\t\t\tif isEating {\n\t\t\t\t// Drop forks and return to positing on the nature of the universe.\n\t\t\t\tphilIn[id] <- 1\n\t\t\t} else {\n\t\t\t\t// Attempt to begin eating. Return to postulating, if missing fork.\n\t\t\t\tphilIn[id] <- 0\n\t\t\t}\n\t\t\t<- philOut[id]\n\t\t}\n\t}\n}", "func (pd *philosopherData) StartedEating() {\n\tpd.eating = true\n\tpd.dinnersSpent++\n}", "func (ph *Handler) Done() {\n\tselect {\n\tcase info, ok := <-ph.panicChan: // Handles the case where we somehow do this exactly when a panic is sent\n\t\tif ok {\n\t\t\tclose(ph.quit)\n\t\t\tclose(ph.panicChan)\n\t\t\tph.mu.Lock()\n\t\t\tdefer ph.mu.Unlock()\n\t\t\tph.handleForwardedPanic(info)\n\t\t}\n\tdefault: // Only executes if no panics were sent AND panicChan has yet to be closed\n\t\tclose(ph.panicChan)\n\t}\n}", "func (g *game) dayDone() bool {\n\tplr, vts := g.countVotesFor(\"villager\")\n\tif vts <= g.alivePlayers()/2 && time.Since(g.StateTime) < StateTimeout {\n\t\treturn false\n\t}\n\n\tif vts == 0 {\n\t\tg.serverMessage(\"Villages didn't vote, nobody dies.\")\n\t\treturn true\n\t}\n\n\ttoBeKilled := plr[rand.Intn(len(plr))]\n\ttoBeKilled.Dead = true\n\tg.serverMessage(toBeKilled.Name + \" was lynched by an angry mob!\")\n\treturn true\n}", "func (p philosopher) eat() {\r\n\tdefer eatWgroup.Done()\r\n\tfor j := 0; j < 3; j++ {\r\n\t\tp.leftFork.Lock()\r\n\t\tp.rightFork.Lock()\r\n\r\n\t\tsay(\"eating\", p.id)\r\n\t\ttime.Sleep(time.Second)\r\n\r\n\t\tp.rightFork.Unlock()\r\n\t\tp.leftFork.Unlock()\r\n\r\n\t\tsay(\"finished eating\", p.id)\r\n\t\ttime.Sleep(time.Second)\r\n\t}\r\n\r\n}", "func (px *Paxos) Done(seq int) {\n\t// Your code here.\n\tpx.peerDone(seq, px.me)\n}", "func (eip *EventInProgress) Done() {\n\teip.doneFunc(eip.loggables) // create final event with extra data\n}", "func (philo philO) eat(maxeat chan string) {\n\tfor x := 0; x < 3; x++ {\n\t\tmaxeat <- philo.id\n\t\tphilo.meals++\n\t\tphilo.first.Lock()\n\t\tphilo.second.Lock()\n\t\tfmt.Printf(\"Philosopher #%s is eating a meal of rice\\n\", philo.id)\n\t\tphilo.first.Unlock()\n\t\tphilo.second.Unlock()\n\t\tfmt.Printf(\"Philosopher #%s is done eating a meal of rice\\n\", philo.id)\n\t\t<-maxeat\n\t\tif philo.meals == 3 {\n\t\t\tfmt.Printf(\"Philosopher #%s is finished eating!!!!!!\\n\", philo.id)\n\t\t}\n\t}\n}", "func (pe *PendingEvent) Done() {\n\tif pe == nil || pe.name == \"\" || trace.file == nil {\n\t\treturn\n\t}\n\twriteEvent(&traceinternal.ViewerEvent{\n\t\tName: pe.name,\n\t\tPhase: end,\n\t\tPid: trace.pid,\n\t\tTid: pe.tid,\n\t\tTime: float64(time.Since(trace.start).Microseconds()),\n\t})\n}", "func (pb *PhilosopherBase) Eat() {\n\n\tpb.State = philstate.Eating\n\tpb.StartEating()\n}", "func (v *ObservabilityVerifier) AfterCompleted(ctx context.Context) {}", "func (s *Server) Done() {\n\ts.doneCh <- true\n}", "func (f *fakeAnnouncer) Done() <-chan struct{} {\n\treturn f.ctx.Done()\n}", "func (c *Controller) onJourneyFinished(j domain.Journey) {\n\tc.queue.Push(j)\n\tc.metricsService.GaugeInc(metrics.JOURNEYS_FINISHED.String())\n\tc.checkAndStoreJourney(&j)\n}", "func (o Outcome) IsFinished() bool { return o.Reason != notCompleted }", "func (h *hombre) respirar() { h.respirando = true }", "func (c *Command) done() {\n\tc.push(c.Id, \"done\")\n}", "func done() {\n\tprintln(\"Done.\")\n\n\ttime.Sleep(1 * time.Hour)\n}", "func Finished() {\n\tnotify := notificator.New(notificator.Options{\n\t\tDefaultIcon: \"icon/default.png\",\n\t\tAppName: \"Organizer\",\n\t})\n\n\tnotify.Push(appName,\n\t\tfinishedMessage,\n\t\ticonPath,\n\t\tnotificator.UR_CRITICAL)\n}", "func (u *UserCalculator) Done() {}", "func (mts *metadataTestSender) ConsumerDone() {\n\tmts.input.ConsumerDone()\n}", "func (s *Server) Done() {\n\tif s.server == nil {\n\t\treturn\n\t}\n\t// Wait until killed.\n\t<-s.ctx.Done()\n}", "func waitForFinished() {\n\tch := make(chan struct{}) // blocking channel with no data\n\n\tgo func() {\n\t\ttime.Sleep(time.Duration(rand.Intn(500)) * time.Millisecond)\n\t\tclose(ch)\n\t\tfmt.Println(\"worker: send signal by closing channel\")\n\t}()\n\n\t_, wd := <-ch // want for slgnal\n\tfmt.Println(\"manager: signal received: WithDataFlag =\", wd)\n\n\ttime.Sleep(time.Second)\n\tfmt.Println(\"------------ done ---------\")\n}", "func (p *GenericPlugin) Done() <-chan struct{} {\n\treturn p.done\n}", "func (h *hombre) respirar() { h.respirando = true }", "func (mgr *manager) step_Terminated() mgr_step {\n\t// Let others see us as done. yayy!\n\tmgr.doneFuse.Fire()\n\t// We've finally stopped selecting. We're done. We're out.\n\t// No other goroutines alive should have reach to this channel, so we can close it.\n\tclose(mgr.ctrlChan_childDone)\n\t// It's over. No more step functions to call.\n\treturn nil\n}", "func (phi *Philosopher) GoToDinner(waitGrp *sync.WaitGroup, requestChannel, finishChannel chan string) {\n\tdefer waitGrp.Done()\n\n\tretryInterval := time.Duration(2000) * time.Millisecond\n\teatingDuration := time.Duration(5000) * time.Millisecond\n\n\tfor {\n\t\trequestChannel <- phi.name\n\t\tswitch <-phi.respChannel {\n\t\tcase \"OK\":\n\t\t\ttime.Sleep(eatingDuration)\n\t\t\tfinishChannel <- phi.name\n\t\tcase \"E:LIMIT\":\n\t\t\tfmt.Println(strings.ToUpper(\"----- \" + phi.name + \" LEFT THE TABLE. -----\"))\n\t\t\tfmt.Println()\n\t\t\treturn\n\t\tdefault:\n\t\t\ttime.Sleep(retryInterval)\n\t\t}\n\t}\n}", "func (g *queryGate) Done() {\n\tselect {\n\tcase <-g.ch:\n\tdefault:\n\t\tpanic(\"engine.queryGate.Done: more operations done than started\")\n\t}\n}", "func (c *context) Done() <-chan struct{} { return c.c.Done() }", "func whenDone() func() {\n\tstart := time.Now()\n\treturn func() {\n\t\tfmt.Printf(\"Total time: %v\\n\", time.Since(start))\n\t}\n}", "func (turingMachine *TuringMachine) HasFinished() bool {\n return turingMachine.hasFinished\n}", "func (px *Paxos) Done(seq int) {\n\t// Your code here.\n\tpx.peerDones[px.me] = seq\n}", "func (_m *MockWaiter) Done() {\n\t_m.Called()\n}", "func QuorumFinishedCaller(handler interface{}, params ...interface{}) {\n\thandler.(func(result *QuorumFinishedResult))(params[0].(*QuorumFinishedResult))\n}", "func (up *Uploader) UploadDone() {\n\tselect {\n\tcase <-up.uploader:\n\tdefault:\n\t\tpanic(\"No upload to wait for\")\n\t}\n}", "func Greeter(ctx context.Context, names <-chan []byte,\n\tgreetings chan<- []byte, errs <-chan error) {\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tlog.Println(\"finished\")\n\t\t\treturn\n\t\tcase err := <-errs:\n\t\t\tlog.Println(\"an error occurred:\", err)\n\t\tcase name := <-names:\n\t\t\tgreeting := \"Hello \" + string(name)\n\t\t\tgreetings <- []byte(greeting)\n\t\t}\n\t}\n}", "func (j *Job) done() { j.isDone <- true }", "func (gw *groupWaiter) Done() {\n\tgw.wg.Done()\n}", "func (mgr *manager) step_Quitting() mgr_step {\n\tif len(mgr.wards) == 0 {\n\t\treturn mgr.step_Terminated\n\t}\n\n\tselect {\n\tcase childDone := <-mgr.ctrlChan_childDone:\n\t\tmgr.reapChild(childDone)\n\t\treturn mgr.step_Quitting\n\t}\n}", "func (pb *PhilosopherBase) IsEating() bool {\n\treturn pb.State == philstate.Eating\n}", "func (s *SwiftServer) Finished() {\n\tif len(s.checks) > 0 {\n\t\ts.t.Error(\"Unused checks\", s.checks)\n\t}\n}", "func (px *Paxos) Done(seq int) {\n\targs := &DoneArgs{}\n\targs.Peer = px.peers[px.me]\n\targs.Seq = seq\n\tvar reply DoneResp\n\tfor _, peer := range px.peers {\n\t\tcall(peer, \"Paxos.DoneHandler\", args, &reply)\n\t}\n}", "func (t *Task) Done() {\n\tt.od.Do(func() {\n\t\tt.pwg.Done()\n\t})\n}", "func (t *Tournament) End() {\n\tif !t.hasEnded() {\n\t\tn := t.generateWinnerNum()\n\n\t\tt.Winner = Winner{\n\t\t\tPlayer: t.Participants[n],\n\t\t\tPrize: t.Deposit,\n\t\t}\n\n\t\tt.Participants[n].Fund(t.Deposit)\n\t\tt.Balance = 0\n\t}\n}", "func Done() <-chan struct{} {\n\treturn defaultManager.Done()\n}", "func (p *Plugin) After() <-chan struct{} {\n\treturn p.doneCh\n}", "func (c *Cooler) Done() {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tc.active = false\n}", "func (c *Client) Done() {\n\tc.doneCh <- true\n}", "func (client *Client) Done() {\n\tclient.done <- true\n}", "func (l localOptimizer) finishMethodDone(operation chan<- Task, result <-chan Task, task Task) {\n\ttask.Op = MethodDone\n\toperation <- task\n\ttask = <-result\n\tif task.Op != PostIteration {\n\t\tpanic(\"optimize: task should have returned post iteration\")\n\t}\n\tl.finish(operation, result)\n}", "func (f *Finisher) Finish(result interface{}) {\n\tif f.isFinished {\n\t\treturn\n\t}\n\tf.isFinished = true\n\tf.callback(result)\n}", "func (s *Server) Done() <-chan struct{} {\n\treturn s.shuttingDown\n}", "func (jpl *ChunkProgressLogger) chunkFinished(ctx context.Context) error {\n\tjpl.completedChunks++\n\treturn jpl.batcher.Add(ctx, jpl.perChunkContribution)\n}", "func (a *Aggregator) Done() {\n\tclose(a.done)\n\ta.w.Wait()\n}", "func (c *Client) Done() {\n\t<-c.done.Done()\n}", "func (r *Roller) DecidedDone(f ...Callable) {\n\tr.doners = append(r.doners, f...)\n}", "func (m *ClientMech) Completed() bool {\n\treturn true\n}", "func(this *GView) Done(youWin games.Outcome) {\n\tif youWin == games.Win {\n\t\tthis.inOut.Write(([]byte) (this.name + \" won.\\n\"))\n\t} else if youWin == games.Draw {\n\t\tthis.inOut.Write(([]byte) (\"There was a tie.\\n\"))\n\t} else {\n\t\tthis.inOut.Write(([]byte) (this.name + \" lost.\\n\"))\n\t}\n}", "func (o *observer) waitForEvent() error {\n\tleaderCh, errCh := o.follower.FollowElection()\n\tfor {\n\t\tselect {\n\t\tcase leader, ok := <-leaderCh:\n\t\t\tif !ok {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\to.Lock() // make sure we lock around modifying the current leader, and invoking callback\n\t\t\tlog.WithFields(log.Fields{\"role\": o.role, \"leader\": leader}).Info(\"New leader detected\")\n\t\t\to.metrics.LeaderChanged.Inc(1)\n\t\t\to.leader = leader\n\t\t\terr := o.callback(leader)\n\t\t\to.Unlock()\n\t\t\tif err != nil {\n\t\t\t\tlog.WithFields(log.Fields{\"role\": o.role, \"error\": err}).Error(\"NewLeaderCallback failed\")\n\t\t\t}\n\t\tcase err := <-errCh:\n\t\t\tif err != nil {\n\t\t\t\tlog.WithFields(log.Fields{\"role\": o.role, \"error\": err}).Error(\"Error following election\")\n\t\t\t\to.metrics.Error.Inc(1)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// just a shutdown signal from the docker/leadership lib,\n\t\t\t// we can propogate this and let the caller decide if we\n\t\t\t// should continue to run, or terminate\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func handleTestsFinishedEvent(event cloudevents.Event, shkeptncontext string, data *keptnevents.TestsFinishedEventData, logger *keptnutils.Logger) error {\n\tlogger.Info(fmt.Sprintf(\"Handling Tests Finished Event: %s\", event.Context.GetID()));\n\n\treturn nil\n}", "func (lc *Closer) Done() {\n\tlc.waiting.Done()\n}", "func (l *PoolListener) Done() {}", "func (inp ThingFrom) ThingDone(ops ...func(a Thing)) (done <-chan struct{}) {\n\tsig := make(chan struct{})\n\tgo inp.doneThing(sig, ops...)\n\treturn sig\n}", "func (it *messageIterator) done(ackID string, ack bool, r *AckResult, receiveTime time.Time) {\n\tit.addToDistribution(receiveTime)\n\tit.mu.Lock()\n\tdefer it.mu.Unlock()\n\tdelete(it.keepAliveDeadlines, ackID)\n\tif ack {\n\t\tit.pendingAcks[ackID] = r\n\t} else {\n\t\tit.pendingNacks[ackID] = r\n\t}\n\tit.checkDrained()\n}", "func (wg *WaitGroup) Done() {\n\twg.wg.Done()\n}", "func (t *Tortoise) OnHareOutput(lid types.LayerID, bid types.BlockID) {\n\tstart := time.Now()\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\twaitHareOutputDuration.Observe(float64(time.Since(start).Nanoseconds()))\n\tt.trtl.onHareOutput(lid, bid)\n\tif t.tracer != nil {\n\t\tt.tracer.On(&HareTrace{Layer: lid, Vote: bid})\n\t}\n}", "func (m *Manager) waitForFinish() {\n\tm.state.wg.Wait()\n}", "func (pb *PhilosopherBase) StartEating() {\n\tpb.WriteString(\"starts eating\")\n\tpb.DelaySend(pb.EatRange, NewState{NewState: philstate.Thinking})\n}", "func (g *Game) finished() bool {\r\n\t// check if there is a winner\r\n\tpl := g.hasWinner()\r\n\tif pl != nil {\r\n\t\tprintln(\"Player\", pl.name, \"wins!\")\r\n\t\treturn true\r\n\t}\r\n\r\n\tfor r := 0; r < 3; r++ {\r\n\t\tfor c := 0; c < 3; c++ {\r\n\t\t\tif g.panel.isCellFree(cell{r, c}) {\r\n\t\t\t\treturn false\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn true\r\n}", "func (s *Shim) Done() {\n\ts.add(-1)\n}", "func (st *LevelCompleteState) OnPause(world w.World) {}", "func (c *Controller) Finish() {}", "func handleFinished(a *Attempt) (abort, retry, fail, remuser, suc bool) {\n\t/* If we have a success */\n\tif a.Err == nil {\n\t\t/* Write it to a file */\n\t\tgo logSuccess(a)\n\t\tsuc = true\n\t\tif *gc.Onepw {\n\t\t\t/* If we only need one user, exit */\n\t\t\tabort = true\n\t\t\treturn\n\t\t} else {\n\t\t\t/* Otherwise, we're done with this user */\n\t\t\tfail = true\n\t\t\tremuser = true\n\t\t\treturn\n\t\t}\n\t}\n\t/* Print error debugging information */\n\tif *gc.Errdb {\n\t\tlog.Printf(\"[%v] %v@%v - %v ERROR (%T): %v\", a.Tasknum,\n\t\t\ta.Config.User, a.Host, a.Pass, a.Err, a.Err)\n\t}\n\t/* True if the error isn't handled */\n\tuh := false\n\t/* Switch on the type of error */\n\tswitch a.Err.(type) {\n\tcase *net.OpError:\n\t\tabort, retry, fail, remuser, uh = handleNetOpError(a)\n\tcase *TimeoutError:\n\t\tlog.Printf(\"[%v] No longer attacking %v: attack timed out\",\n\t\t\ta.Tasknum, a.Host)\n\t\tabort = true\n\tcase error: /* Should be last */\n\t\tabort, retry, fail, remuser, uh = handleGenericError(a)\n\tdefault:\n\t\tuh = true\n\t}\n\tif uh {\n\t\tlog.Printf(\"[%v] %v@%v - %v UNHANDLED ERROR (%T): %v\",\n\t\t\ta.Tasknum, a.Config.User, a.Host, a.Pass, a.Err, a.Err)\n\t\tfail = true\n\t\treturn\n\t}\n\treturn\n}", "func (p *Progress) Done() {\n\tp.MaybeReport(p.total)\n}", "func (px *Paxos) IfDone(args *IfDoneArgs, reply *IfDoneReply) error {\n\tpx.clog(DBG_DONE, \"IfDone\", \"check %d, local_done=%d\", args.Seq, px.local_done)\n\tif args.Seq <= px.local_done {\n\t\treply.Err = OK\n\t} else {\n\t\t// make other peers wait for me\n\t\treply.Err = Reject\n\t}\n\n\treturn nil\n}", "func (clientHandler) Done(ctx context.Context, err error) {}", "func (c *context) Done() <-chan struct{} {\n\treturn c.parent.Done()\n}", "func startAgentAndDone(agentName string, srvPs *pubsub.PubSub) {\n\tserviceEntrypoint, _ := entrypoints[agentName]\n\tretval := serviceEntrypoint.f(srvPs)\n\n\tret := strconv.Itoa(retval)\n\tif err := ioutil.WriteFile(fmt.Sprintf(\"/var/run/%s.done\", agentName),\n\t\t[]byte(ret), 0700); err != nil {\n\t\tlog.Fatalf(\"Error write done file: %v\", err)\n\t}\n}", "func (e *EventLog) Finish() {\n\te.el.Finish()\n}", "func (pm *persistManager) Done() error {\n\tpm.Lock()\n\tdefer pm.Unlock()\n\n\tif pm.status != persistManagerFlushing {\n\t\treturn errPersistManagerNotFlushing\n\t}\n\n\t// Emit timing metrics\n\tpm.metrics.writeDurationMs.Update(float64(pm.worked / time.Millisecond))\n\tpm.metrics.throttleDurationMs.Update(float64(pm.slept / time.Millisecond))\n\n\t// Reset state\n\tpm.reset()\n\n\treturn nil\n}", "func SendEventFinished(data EventFinishedData) {\n\tsendEvent(\"finished\", data)\n}", "func (p *DeploymentsClientWhatIfPoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (pl PromoteLearner) IsFinish(region *core.RegionInfo) bool {\n\tif p := region.GetStoreVoter(pl.ToStore); p != nil {\n\t\tif p.GetId() != pl.PeerID {\n\t\t\tlog.Warnf(\"expect %v, but obtain voter %v\", pl.String(), p.GetId())\n\t\t}\n\t\treturn p.GetId() == pl.PeerID\n\t}\n\treturn false\n}", "func exitAfter(d time.Duration) {\n\ttime.Sleep(d)\n\tlog.Fatalf(\"gosh: timed out after %v\", d)\n}", "func (m *OutboundMock) Finish() {\n\tm.MinimockFinish()\n}", "func (play *Play) Done() {\n\tcount := play.PhaseCount()\n\tplay.phases[count-1].active = false\n}", "func Finish() {\n\tsyscall.Syscall(gpFinish, 0, 0, 0, 0)\n}", "func (wm *WorkerManager) AnyJoined() bool {\n\treturn true\n}", "func (w *Worker) WaitForFinish() {\n\t<-w.done\n}", "func (s *Supermarket) finishedShoppingListener() {\n\tfor {\n\t\tif !s.openStatus && numberOfCurrentCustomersShopping == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\t// Check if customer is finished adding products to trolley using channel from the shop() method in Customer.go\n\t\tid := <-s.finishedShopping\n\n\t\t// Send customer to a checkout\n\t\ts.sendToCheckout(id)\n\t}\n}", "func (m *HostNetworkMock) Finish() {\n\tm.MinimockFinish()\n}", "func (game *T) Done() chan bool {\n\treturn game.close\n}", "func Done() {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tinternalPanicHandler.Done()\n}", "func (p *Pool) JobDone() {\n\tp.wg.Done()\n}", "func (p *Pool) JobDone() {\n\tp.wg.Done()\n}", "func (c *Command) Finish() {}", "func (a *Auther) AuthinfoDone(h *fastnntp.Handler) bool {\n\treturn false\n}" ]
[ "0.69764256", "0.58116984", "0.5761924", "0.55214846", "0.54901856", "0.54631877", "0.54514676", "0.52984303", "0.5249682", "0.5244871", "0.5196276", "0.51941454", "0.5174147", "0.5064095", "0.5041042", "0.50094306", "0.50072306", "0.49889994", "0.49314958", "0.49176306", "0.4909091", "0.48914897", "0.488368", "0.48796767", "0.48719692", "0.48667565", "0.48529467", "0.48521388", "0.48404852", "0.4827891", "0.48258263", "0.48166567", "0.48159817", "0.48156357", "0.4806341", "0.47924027", "0.47795677", "0.47779098", "0.47756732", "0.47688338", "0.47599453", "0.474061", "0.47380155", "0.47345832", "0.47234198", "0.4702602", "0.46872732", "0.4683107", "0.46816504", "0.46733403", "0.46727848", "0.46709335", "0.46662343", "0.46659678", "0.4664521", "0.4661288", "0.4657824", "0.46405193", "0.46346587", "0.4631123", "0.4628475", "0.46265355", "0.46238852", "0.46010628", "0.45986238", "0.45833683", "0.45806605", "0.4577699", "0.4576378", "0.45728984", "0.45728314", "0.45641208", "0.45595896", "0.4555834", "0.45495698", "0.45464733", "0.45327955", "0.45311606", "0.45248166", "0.45233837", "0.45227975", "0.45170018", "0.45168418", "0.45130336", "0.45038927", "0.44989762", "0.44928262", "0.44919026", "0.4491613", "0.4487696", "0.44835827", "0.44828078", "0.4480444", "0.44763824", "0.4474321", "0.44733366", "0.4468133", "0.4468133", "0.44584918", "0.44560024" ]
0.7649123
0
PrintReport shows the status of the philosophers in a verbose format.
func (host *DinnerHost) PrintReport(additionalInfo bool) { names := make([]string, 0, len(host.phiData)) maxNameLen := 0 for i := range host.phiData { names = append(names, i) if len(i) > maxNameLen { maxNameLen = len(i) } } sort.Strings(names) fmt.Printf("%*s | SEAT | LEFTCH. | RIGHTCH. | DINNERS | STATUS", maxNameLen, "NAME") fmt.Println() for _, name := range names { data := host.phiData[name] status := "waiting" if data.eating == true { status = "eating" } leftChopStr := strings.Replace(strconv.Itoa(data.LeftChopstick()), "-1", "X", 1) rightChopStr := strings.Replace(strconv.Itoa(data.RightChopstick()), "-1", "X", 1) repLine := fmt.Sprintf("%*s | %*d | %*s | %*s | %*d | %s", maxNameLen, name, 4, data.seat, 7, leftChopStr, 8, rightChopStr, 7, data.dinnersSpent, status) fmt.Println(repLine) } if additionalInfo { freeChops := fmt.Sprintf("CHOPSTICKS:") for chopInd, chopStat := range host.chopsticksFree { status := "FREE" if chopStat == false { status = "RESERVED" } freeChops += fmt.Sprintf(" %d[%s]", chopInd, status) } fmt.Println(freeChops) } fmt.Println() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Report) Print() {\n\tresTotal := 0\n\tfor i := range r.StatusCodes {\n\t\tresTotal += r.StatusCodes[i]\n\t}\n\n\terrTotal := 0\n\tfor i := range r.Errors {\n\t\terrTotal += r.Errors[i]\n\t}\n\n\tfmt.Printf(\" Duration: %0.3fs\\n\", r.Duration.Seconds())\n\tfmt.Printf(\" Requests: %d (%0.1f/s) (%0.5fs/r)\\n\",\n\t\tr.RequestCount,\n\t\tfloat64(r.RequestCount)/r.Duration.Seconds(),\n\t\tr.Duration.Seconds()/float64(r.RequestCount),\n\t)\n\n\tif errTotal > 0 {\n\t\tfmt.Printf(\" Errors: %d\\n\", errTotal)\n\t}\n\n\tfmt.Printf(\"Responses: %d (%0.1f/s) (%0.5fs/r)\\n\",\n\t\tresTotal,\n\t\tfloat64(resTotal)/r.Duration.Seconds(),\n\t\tr.Duration.Seconds()/float64(resTotal),\n\t)\n\tfor code, count := range r.StatusCodes {\n\t\tfmt.Printf(\" [%d]: %d\\n\", code, count)\n\t}\n\tfor err, count := range r.Errors {\n\t\tfmt.Printf(\"\\n%d times:\\n%s\\n\", count, err)\n\t}\n}", "func (results *Results) Print() {\n\tif verbose {\n\t\tfor _, result := range results.List {\n\t\t\tresult.Print()\n\t\t}\n\t}\n\n\tvar state string\n\tif results.Passed {\n\t\tstate = \"OK\"\n\t} else {\n\t\tstate = \"FAIL\"\n\t}\n\n\tif !verbose {\n\t\tfmt.Println(state)\n\t} else {\n\t\tfmt.Printf(\"--- %s %v\", state, results.Duration)\n\t}\n}", "func (app App) PrintReport() error {\n\tif app.session.APIToken != app.APIKey {\n\t\treturn errors.New(\"Session is not active\")\n\t}\n\n\tstart, end := getDates()\n\tworkspace, err := app.getWorkspace()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treport, err := app.session.GetDetailedReport(workspace.ID, start, end, 1)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdates, itemsByTime := getItemsByTime(report)\n\n\tfor _, date := range dates {\n\t\titems := itemsByTime[date]\n\n\t\tcolor.Green(date)\n\t\t// Holding a daily tally\n\t\tvar dayDuration int64\n\n\t\tfor _, item := range items {\n\t\t\tif err := printDetailedTimeEntry(item); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdayDuration += item.Duration\n\t\t}\n\n\t\tduration, err := getDuration(dayDuration)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcolor.Magenta(\"Total: %s\", duration)\n\t}\n\n\tduration, err := getDuration(int64(report.TotalGrand))\n\tif err != nil {\n\t\treturn err\n\t}\n\tcolor.Green(\"Grand Total: %s\", duration)\n\n\treturn nil\n}", "func (m *Main) PrintReport(format string) error {\n\tswitch format {\n\tcase \"json\":\n\t\tb, err := json.Marshal(m.Report)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Println(string(b))\n\tcase \"yaml\":\n\t\tb, err := yaml.Marshal(m.Report)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Println(string(b))\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown format %q, can be json|yaml\", format)\n\t}\n\treturn nil\n}", "func (s Status) Print() string {\n\tsflag := fmt.Sprintf(\"Status: 0x%x\\n\", s.Header)\n\tsflags := sarflags.Values(\"status\")\n\tfor f := range sflags {\n\t\tn := sarflags.GetStr(s.Header, sflags[f])\n\t\tsflag += fmt.Sprintf(\" %s:%s\\n\", sflags[f], n)\n\t}\n\tsflag += fmt.Sprintf(\" session:%d\\n\", s.Session)\n\tif sarflags.GetStr(s.Header, \"reqtstamp\") == \"yes\" {\n\t\tsflag += fmt.Sprintf(\" timestamp:%s\\n\", s.Tstamp.Print())\n\t}\n\tsflag += fmt.Sprintf(\" progress:%d\", s.Progress)\n\tsflag += fmt.Sprintf(\" inresponseto:%d\\n\", s.Inrespto)\n\tfor i := range s.Holes {\n\t\tsflag += fmt.Sprintf(\" Hole[%d]: Start:%d End:%d\\n\", i, s.Holes[i].Start, s.Holes[i].End)\n\t}\n\treturn sflag\n}", "func PrintStatus() {\n\threpo := sqlite.NewHeadsRepo()\n\ttrepo := sqlite.NewTaskRepo()\n\n\tvar pr *domain.Project\n\tvar t *domain.Task\n\tvar err error\n\n\tif t, pr, err = hrepo.GetCurrentTask(); err != nil {\n\t\tfmt.Printf(\"Error :%v\\n\", err)\n\t\treturn\n\t}\n\n\ttaskName := \"No definida\"\n\ttid := 0\n\n\tif t != nil {\n\t\ttaskName = t.Name\n\t\ttid = int(t.ID)\n\t}\n\n\tprojectName := \"No definido\"\n\tpid := 0\n\n\tif pr != nil {\n\t\tprojectName = pr.Name\n\t\tpid = int(pr.ID)\n\t}\n\n\ttoday, week, month, total, _ := trepo.GetAggregates(tid)\n\n\tst := status{\n\t\tCurrentProjectName: projectName,\n\t\tCurrentTaskName: taskName,\n\t\tPID: pid,\n\t\tTID: tid,\n\t\tTimeToday: minHours(today),\n\t\tTimeThisWeek: minHours(week),\n\t\tTimeThisMonth: minHours(month),\n\t\tTimeTotal: minHours(total),\n\t}\n\n\treport, err := template.New(\"report\").Parse(statusTemplate)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Error %v\", err)\n\t\treturn\n\t}\n\n\terr = report.Execute(os.Stdout, st)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Error %v\", err)\n\t}\n}", "func Print(v ...interface{}) {\n\tcheckInit()\n\ts := fmt.Sprint(v...)\n\tstd.Report(s)\n\tlog.Print(s)\n}", "func (of *Offspring) Report() string {\n\treturn fmt.Sprintf(\"%04d: %s --- score: %4.2f%% (%d/%d)\", of.Generation,\n\tstring(of.Phrase), of.RelativeFitness()*100, of.Fitness, of.MaxFitness() )\n}", "func printResults() {\n\tclearScreen()\n\n\tfmt.Println(\" Positions:\")\n\tfmt.Println(\"--------------------------\")\n\tfor _, exg := range exchanges {\n\t\tfmt.Printf(\"%-13s %10.2f\\n\", exg, exg.Position())\n\t}\n\tfmt.Println(\"--------------------------\")\n\tfmt.Printf(\"\\nRun P&L: $%.2f\\n\", pl)\n}", "func Print(s stat.Stat) {\n\tw := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', tabwriter.AlignRight|tabwriter.Debug)\n\tfmt.Fprintln(w, \"Total\\tTests\\tPass\\tFail\\tSkip\\t\")\n\tfmt.Fprintf(w, \"%v\\t%v\\t%v\\t%v\\t%v\\t\\n\", resultTotal(s), s.Tests, s.Pass, s.Fail, s.Skip)\n\tw.Flush()\n\n\tfmt.Printf(\"Elapsed: %v\\n\", s.Elapsed)\n\tfmt.Printf(\"Packages without Tests (%v/%v):\\n%v \\n\", s.Packages, len(s.EmptyPackages), s.EmptyPackages)\n}", "func printReport(changes []*route53.Change, zoneName string) {\n\tfmt.Println(\"*********************************************\")\n\tfmt.Printf(\"Proposed Changes for Zone %s:\\n\", zoneName)\n\tfmt.Println(\"*********************************************\")\n\tw := new(tabwriter.Writer)\n\tw.Init(os.Stdout, 0, 8, 2, '\\t', tabwriter.Debug|tabwriter.AlignRight)\n\tfmt.Fprintln(w, \"ACTION\\tNAME\\tTYPE\")\n\n\tfor _, change := range changes {\n\t\tfmt.Fprintln(w, fmt.Sprintf(\"%s\\t%s\\t%s\", aws.StringValue(change.Action),\n\t\t\taws.StringValue(change.ResourceRecordSet.Name),\n\t\t\taws.StringValue(change.ResourceRecordSet.Type)))\n\t}\n\tw.Flush()\n\tfmt.Printf(\"\\n\\n\")\n}", "func (l Langs) Print(all bool) {\n\n\ttable := tablewriter.NewWriter(os.Stdout)\n\n\tif all {\n\t\ttable.SetHeader([]string{\"Language\", \"Id(s)\", \"Available ?\"})\n\t} else {\n\t\ttable.SetHeader([]string{\"Language\", \"Available Id(s)\"})\n\t}\n\n\tlangs := Languages\n\tsort.Sort(ByName(langs))\n\n\tfor _, l := range langs {\n\t\t_, subOK := subdbLangs[l.ID]\n\t\t_, osOK := osLangs[l.ID]\n\t\tif all {\n\t\t\tavailable := \"No\"\n\t\t\tif subOK || osOK {\n\t\t\t\tavailable = \"Yes\"\n\t\t\t}\n\t\t\tvalues := []string{\n\t\t\t\tl.Description, // Language\n\t\t\t\tstrings.Join(append(l.Alias, l.ID), \", \"), // Id(s)\n\t\t\t\tavailable, // Available ?\n\t\t\t}\n\t\t\ttable.Append(values)\n\t\t} else if subOK || osOK {\n\t\t\tvalues := []string{\n\t\t\t\tl.Description, // Language\n\t\t\t\tstrings.Join(append(l.Alias, l.ID), \", \"), // Available Id(s)\n\t\t\t}\n\t\t\ttable.Append(values)\n\t\t}\n\t}\n\ttable.SetAutoWrapText(false)\n\ttable.SetColWidth(50)\n\ttable.Render() // Send output\n}", "func printReport(r reports.Report, w io.Writer, minPriority int8, pal *palette) {\n\n\tc.Fprint(w, \"\\n\")\n\tc.Fprint(w, c.FHeader(r.Title))\n\tc.Fprint(w, \"\\n\")\n\n\tfor _, ch := range r.Chunks {\n\t\tif ch.Priority >= minPriority {\n\t\t\tprintChunk(ch, w, minPriority, pal)\n\t\t}\n\t}\n\n\tc.Fprint(w, \"\\n\")\n}", "func (s *StressReport) Print(t *testing.T) {\n\tfmt.Printf(\"----- Stress Report for %s -----\\n\", t.Name())\n\tw := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\\t', tabwriter.AlignRight)\n\tfmt.Fprintf(w, \"%s\\t\\t%d iterations\\t%15.4f ns/iteration\", s.Duration, s.Iteration, float64(s.Duration.Nanoseconds())/float64(s.Iteration))\n\tif s.Extras != nil {\n\t\tfor _, metric := range s.Extras {\n\t\t\tfmt.Fprintf(w, \"\\t%15.4f %s\", metric.Value, metric.Unit)\n\t\t}\n\t}\n\n\tif delta := s.Delta(); delta != 0 {\n\t\tfmt.Fprintf(w, \"\\t%15.4f %%iterations\", delta)\n\t}\n\n\tfmt.Fprintln(w)\n\tw.Flush()\n\n\tfmt.Println()\n\tfmt.Printf(\"----- Profiling Report CPU for %s -----\\n\", t.Name())\n\tfmt.Println(string(s.TopCPU))\n\tfmt.Println()\n\n\tfmt.Println()\n\tfmt.Printf(\"----- Profiling Report Memory for %s -----\\n\", t.Name())\n\tfmt.Println(string(s.TopMem))\n\tfmt.Println()\n}", "func (pfs *Supervisor) PrintSummary() {\n\t//pfs.wg.Wait()\n\tpfs.mu.Lock()\n\tdefer pfs.mu.Unlock()\n\tvar total, passed, skipped, failed, missing []string\n\tfor _, pf := range pfs.fixtures {\n\t\tt, p, s, f, m := pf.printSummary()\n\t\ttotal = append(total, t...)\n\t\tpassed = append(passed, p...)\n\t\tskipped = append(skipped, s...)\n\t\tfailed = append(failed, f...)\n\t\tmissing = append(missing, m...)\n\t}\n\n\tif len(failed) != 0 {\n\t\tfmt.Printf(\"These tests failed:\\n\")\n\t\tfor _, n := range failed {\n\t\t\tfmt.Printf(\"FAILED> %s\\n\", n)\n\t\t}\n\t}\n\n\tif len(missing) != 0 {\n\t\tfmt.Printf(\"These tests did not report status:\\n\")\n\t\tfor _, n := range missing {\n\t\t\tfmt.Printf(\"MISSING> %s\\n\", n)\n\t\t}\n\t}\n\n\tsummary := fmt.Sprintf(\"Summary: %d failed; %d skipped; %d passed; %d missing (total %d)\",\n\t\tlen(failed), len(skipped), len(passed), len(missing), len(total))\n\tfmt.Fprintln(os.Stdout, summary)\n}", "func showGCPPrinterStatus(context *cli.Context) {\n\tconfig := getConfig(context)\n\tgcp := getGCP(config)\n\n\tprinter, _, err := gcp.Printer(context.String(\"printer-id\"))\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tfmt.Println(\"Name:\", printer.DefaultDisplayName)\n\tfmt.Println(\"State:\", printer.State.State)\n\n\tjobs, err := gcp.Jobs(context.String(\"printer-id\"))\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\t// Only init common states. Unusual states like DRAFT will only be shown\n\t// if there are jobs in that state.\n\tjobStateCounts := map[string]int{\n\t\t\"DONE\": 0,\n\t\t\"ABORTED\": 0,\n\t\t\"QUEUED\": 0,\n\t\t\"STOPPED\": 0,\n\t\t\"IN_PROGRESS\": 0,\n\t}\n\n\tfor _, job := range jobs {\n\t\tjobState := string(job.SemanticState.State.Type)\n\t\tjobStateCounts[jobState]++\n\t}\n\n\tfmt.Println(\"Printer jobs:\")\n\tfor state, count := range jobStateCounts {\n\t\tfmt.Println(\" \", state, \":\", count)\n\t}\n}", "func printSimpleReport(r *Report, to io.Writer) {\n\tvar summary = map[string]int{\n\t\t\"ADD\": 0,\n\t\t\"REMOVE\": 0,\n\t\t\"MODIFY\": 0,\n\t}\n\tfor _, entry := range r.entries {\n\t\tfmt.Fprintf(to, ansi.Color(\"%s %s\", r.format.changestyles[entry.changeType].color)+\"\\n\",\n\t\t\tentry.key,\n\t\t\tr.format.changestyles[entry.changeType].message,\n\t\t)\n\t\tsummary[entry.changeType]++\n\t}\n\tfmt.Fprintf(to, \"Plan: %d to add, %d to change, %d to destroy.\\n\", summary[\"ADD\"], summary[\"MODIFY\"], summary[\"REMOVE\"])\n}", "func VPrint(verbose bool, str string) {\n\tif verbose {\n\t\tfmt.Print(str)\n\t}\n}", "func (quiz *quiz) report() {\n\tfmt.Printf(\n\t\t\"You answered %v questions out of a total of %v and got %v correct\",\n\t\tquiz.answered,\n\t\tlen(quiz.questions),\n\t\tquiz.answeredCorrectly,\n\t)\n}", "func (r *DetectionResults) Report(promptContext prompt.PromptContext, mode string) string {\n\tvar result string\n\tvar filePathsForFailures []string\n\tvar data [][]string\n\n\ttable := tablewriter.NewWriter(os.Stdout)\n\ttable.SetHeader([]string{\"File\", \"Errors\", \"Severity\"})\n\ttable.SetRowLine(true)\n\n\tfor _, resultDetails := range r.Results {\n\t\tif len(resultDetails.FailureList) > 0 {\n\t\t\tfilePathsForFailures = append(filePathsForFailures, string(resultDetails.Filename))\n\t\t\tfailureData := r.ReportFileFailures(resultDetails.Filename)\n\t\t\tdata = append(data, failureData...)\n\t\t}\n\t}\n\n\tfilePathsForFailures = utility.UniqueItems(filePathsForFailures)\n\n\tif r.HasFailures() {\n\t\tfmt.Printf(\"\\n\\x1b[1m\\x1b[31mTalisman Report:\\x1b[0m\\x1b[0m\\n\")\n\t\ttable.AppendBulk(data)\n\t\ttable.Render()\n\t\tfmt.Println()\n\t\tr.suggestTalismanRC(filePathsForFailures, promptContext, mode)\n\t}\n\treturn result\n}", "func Report(list []dto.Project, out io.Writer, f OutputFlags) error {\n\tswitch {\n\tcase f.JSON:\n\t\treturn project.ProjectsJSONPrint(list, out)\n\tcase f.CSV:\n\t\treturn project.ProjectsCSVPrint(list, out)\n\tcase f.Quiet:\n\t\treturn project.ProjectPrintQuietly(list, out)\n\tcase f.Format != \"\":\n\t\treturn project.ProjectPrintWithTemplate(f.Format)(list, out)\n\tdefault:\n\t\treturn project.ProjectPrint(list, os.Stdout)\n\t}\n}", "func (mnrrp *MetricNumRRPairs) PrintStatistic(verbose bool) {\n\tfmt.Println(\"Metric Number of RR Pairs:\")\n\tfmt.Print(mnrrp.rrPairs.GetStatistics(verbose))\n}", "func (w *workTally) Print() {\n\ttable := tablewriter.NewWriter(os.Stdout)\n\ttable.SetHeader([]string{\"Issue ID\", \"Summary\", \"Time Spent\"})\n\ttable.SetFooter([]string{\"\", \"Total\", w.total.String()})\n\ttable.SetBorder(false)\n\tfor _, key := range w.sortedKeys() {\n\t\tentry := w.durationMap[key]\n\t\ttable.Append([]string{\n\t\t\tkey,\n\t\t\ttruncateString(entry.summary, 64),\n\t\t\tentry.duration.String(),\n\t\t})\n\t}\n\tfmt.Println(\"\")\n\ttable.Render()\n}", "func (twrkr *twerk) printStatus() {\n\tif !twrkr.config.Debug {\n\t\treturn\n\t}\n\tlive := twrkr.liveWorkersNum.Get()\n\tworking := twrkr.currentlyWorkingNum.Get()\n\tinQueue := len(twrkr.jobListener)\n\tidle := live - working\n\n\tlog.Printf(\"Live: %d; Working: %d; Idle: %d, Jobs in queue: %d; Max: %d\",\n\t\tlive, working, idle, inQueue, twrkr.config.Max)\n}", "func (l *LogStatus) Print() error {\n\tl.Type = \"status\"\n\tl.Time = time.Now()\n\tl.Duration = l.Time.Sub(l.ClientAt).Seconds()\n\treturn encoder.Encode(l)\n}", "func (conf *Config) Print() {\n\tlog.Info().Str(\"app\", version.AppVersion).Str(\"commit\", version.Commit).Msg(\"version\")\n\tlog.Info().Int(\"port\", conf.Port).Msg(\"gRPC port\")\n\tlog.Info().Str(\"URL\", conf.SystemModelAddress).Msg(\"systemModelAddress\")\n\tlog.Info().Str(\"URL\", conf.EdgeInventoryProxyAddress).Msg(\"edgeInventoryProxyAddress\")\n\tlog.Info().Str(\"prefix\", conf.AppClusterPrefix).Msg(\"appClusterPrefix\")\n\tlog.Info().Int(\"port\", conf.AppClusterPort).Msg(\"appClusterPort\")\n\tlog.Info().Bool(\"tls\", conf.UseTLS).Bool(\"skipServerCertValidation\", conf.SkipServerCertValidation).Str(\"cert\", conf.CACertPath).Str(\"cert\", conf.ClientCertPath).Msg(\"TLS parameters\")\n\tlog.Info().Dur(\"CacheTTL\", conf.CacheTTL).Msg(\"selected TTL for the stats cache in milliseconds\")\n}", "func PrintProgramStatus() {\r\n\tp := pprof.Lookup(\"goroutine\")\r\n\tif err := p.WriteTo(os.Stdout, 2); err != nil {\r\n\t\tfmt.Println(\"ERROR:\", err)\r\n\t\treturn\r\n\t}\r\n}", "func WriteReport(w io.Writer, suites []*TestSuite, ctxLen int, quiet bool) error {\n\ttests, failed, skipped := 0, 0, 0\n\n\tfor _, s := range suites {\n\t\tif s.Failed() {\n\t\t\tfailed++\n\t\t\tif !quiet {\n\t\t\t\tif err := s.WriteDiff(w, ctxLen); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"couldn't write %q: %s\", s.Name+\".err\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t} else if s.Skipped() {\n\t\t\tskipped++\n\t\t}\n\t\ttests++\n\t}\n\n\tplural := \"s\"\n\tif tests == 1 {\n\t\tplural = \"\"\n\t}\n\n\t_, err := fmt.Fprintf(w, \"# Ran %d test%s, %d skipped, %d failed.\\n\", tests, plural, skipped, failed)\n\treturn err\n}", "func ReportPrinter(w io.Writer, minPriority int8, colors bool) func(r reports.Report) error {\n\tvar pal *palette\n\tif colors {\n\t\tpal = &colored\n\t} else {\n\t\tpal = &notcolored\n\t}\n\n\tif w == nil {\n\t\tw = os.Stdout\n\t}\n\n\treturn func(r reports.Report) error {\n\t\tprintReport(r, w, minPriority, pal)\n\t\treturn nil\n\t}\n}", "func (p *Progress) Report() {\n\t// Find the longest project name\n\tlength := p.longestProjectNameLength()\n\n\t// Calculate the row format\n\trowElements := []string{\"| %-\", strconv.Itoa(length), \"s | %-9s | %10s |\\n\"}\n\trowFormat := strings.Join(rowElements, \"\")\n\n\t// Seperator format\n\tsepElements := []string{\"| %-\", strconv.Itoa(length), \"s | %-9s %10s |\\n\"}\n\tsepFormat := strings.Join(sepElements, \"\")\n\tsepString, capString := \"\", \"\"\n\tfor i := 0; i < length; i++ {\n\t\tsepString += \"-\"\n\t\tcapString += \"_\"\n\t}\n\tcap := fmt.Sprintf(\"__%s___________________________\\n\", capString)\n\n\treport := fmt.Sprintf(rowFormat, \"Projects\", \"Blocking\", \"Status\")\n\treport += fmt.Sprintf(sepFormat, sepString, \"---------\", \"----------\")\n\tp.mutex.Lock()\n\tsort.Sort(p.projectStatuses)\n\tfor _, status := range p.projectStatuses {\n\t\tblocking := \"No\"\n\n\t\tswitch {\n\t\tcase status.Project.Blocking && status.State == StateProcessing:\n\t\t\tblocking = \"BLOCKING\"\n\t\tcase status.Project.Blocking && status.State != StateProcessing:\n\t\t\tblocking = \"unblocked\"\n\t\t}\n\n\t\treport += fmt.Sprintf(rowFormat, status.Project.Name, blocking, status.State)\n\t}\n\tp.mutex.Unlock()\n\n\treport = fmt.Sprintf(\"%s%s%s\", cap, report, cap)\n\tp.C <- report\n}", "func Report(stat Textstat) error {\r\n stat.CharactersCount()\r\n stat.HistogramOfWords()\r\n stat.TheTopTen()\r\n \r\n \treturn print(report{\r\n\t\tTotalWords: stat.TotalWords(),\r\n\t\tUniqueWords: stat.UniqueWords(),\r\n\t\tAverageWordLength: stat.AverageWordLength(),\r\n ListOfWords: strings.Join(stat.ListOfWords(),\",\"),\r\n\t\t\r\n\t})\r\n}", "func (wa *WaitingArea) print() {\n\tvar sb strings.Builder\n\tfor _, row := range wa.seats {\n\t\tfor _, s := range row {\n\t\t\tsb.WriteString(string(s.status))\n\t\t}\n\t\tsb.WriteString(\"\\n\")\n\t}\n\tfmt.Println(sb.String())\n}", "func printResults() {\n\n\t// collect stats\n\ttotalLines := 0\n\ttotalCode := 0\n\ttotalComments := 0\n\tfor _, file := range filesStats {\n\t\ttotalLines = totalLines + file.TotalLines\n\t\ttotalCode = totalCode + file.CodeLines\n\t\ttotalComments = totalComments + file.CommentLines\n\t}\n\tfmt.Println(\"Overall stats:\")\n\tfmt.Printf(\" Number of files: %v\\n\", len(filesStats))\n\tfmt.Printf(\" Total lines: %v\\n\", totalLines)\n\tfmt.Printf(\" Code lines: %v\\n\", totalCode)\n\tfmt.Printf(\" Comment lines: %v\\n\", totalComments)\n\n\t// statistics for extensions\n\tif printExts == true {\n\t\t// NOTE: Sadly colprint accepts only slice, not map\n\t\t// thus conversion is needed.\n\t\ts := []*models.ExtensionStats{}\n\t\tfor _, e := range extensionStats {\n\t\t\ts = append(s, e)\n\t\t}\n\t\tfmt.Println(\"\\nStats by extensions\")\n\t\tcolprint.Print(s)\n\t\tfmt.Println()\n\t}\n\n\t// statistics for individual files\n\tif printFiles == true {\n\t\tfmt.Println(\"\\nStats by files:\")\n\t\tcolprint.Print(filesStats)\n\t}\n\tfmt.Println()\n}", "func (re *AllResults) PrintAllResults() {\n\t/*\tvop, _ := re.Validate()\n\t\tif vop != true {\n\t\t\tfunction, file, line, _ := runtime.Caller(1)\n\t\t\top := fmt.Sprintf(\"Validation failure at %s %s %d\", file, runtime.FuncForPC(function).Name(), line)\n\n\t\t\treturn errors.New(op)\n\t\t}*/\n\tfmt.Printf(\"Printing all of AllResults\\n\")\n\t/*\tfunction, file, line, _ := runtime.Caller(0)\n\t\top := fmt.Sprintf(\"Validation failure at %s %s %d\", file, runtime.FuncForPC(function).Name(), line)\n\t\tfmt.Printf(\"%s\\n\", op)*/\n\tfor k, v := range *re {\n\t\tfmt.Printf(\"%d\\t%s\\t%s\\t%s\\t%d\\n\", k, v.PluginName, v.OutputString, v.OutputDesc, v.OutputCode)\n\t}\n\n}", "func RPLSReport(ctx iris.Context) {\n\tvar req models.RPLSReportParams\n\tif err := decodeParams(&req, ctx); err != nil {\n\t\tctx.StatusCode(http.StatusBadRequest)\n\t\tctx.JSON(jsonError{\"Rapport RPLS, décodage \" + err.Error()})\n\t\treturn\n\t}\n\tvar resp models.RPLSReport\n\tdb := ctx.Values().Get(\"db\").(*sql.DB)\n\tif err := resp.GetAll(&req, db); err != nil {\n\t\tctx.StatusCode(http.StatusInternalServerError)\n\t\tctx.JSON(jsonError{\"Rapport RPLS, requête : \" + err.Error()})\n\t\treturn\n\t}\n\tctx.StatusCode(http.StatusOK)\n\tctx.JSON(resp)\n}", "func (s *Scout) Print(v ...interface{}) {\n\tstr := fmt.Sprint(v...)\n\ts.Report(str)\n\ts.Logger.Print(str)\n}", "func printVenues(venues []*untappd.Venue) {\n\ttw := tabWriter()\n\n\t// Print field header\n\tfmt.Fprintln(tw, \"ID\\tName\\tCategory\\tPublic\\tLocation\")\n\n\t// Print out each checkin\n\tfor _, v := range venues {\n\t\tfmt.Fprintf(tw, \"%d\\t%s\\t%s\\t%t\\t%s\\n\",\n\t\t\tv.ID,\n\t\t\tv.Name,\n\t\t\tv.Category,\n\t\t\tv.Public,\n\t\t\tfmt.Sprintf(\"%s, %s, %s\",\n\t\t\t\tv.Location.City,\n\t\t\t\tv.Location.State,\n\t\t\t\tv.Location.Country,\n\t\t\t),\n\t\t)\n\t}\n\n\t// Flush buffered output\n\tif err := tw.Flush(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (l thundraLogger) Print(v ...interface{}) {\n\tif logLevelId > infoLogLevelId {\n\t\treturn\n\t}\n\tlogManager.recentLogLevel = infoLogLevel\n\tlogManager.recentLogLevelId = infoLogLevelId\n\tadditionalCalldepth = 1\n\tl.Logger.Print(v)\n}", "func Print() {\n\tfmt.Println(\"Release Version:\", PDReleaseVersion)\n\tfmt.Println(\"Edition:\", PDEdition)\n\tfmt.Println(\"Git Commit Hash:\", PDGitHash)\n\tfmt.Println(\"Git Branch:\", PDGitBranch)\n\tfmt.Println(\"UTC Build Time: \", PDBuildTS)\n}", "func (s *Stats) PrintVerbose() {\n\tfmt.Println(\"Stats:\")\n\tfmt.Println(\"Time elapsed:\", s.Time)\n\tfmt.Println(\"Nodes coverage:\", s.NodeCoverage)\n\tfmt.Println(\"Links coverage:\", s.LinkCoverage)\n\tfmt.Println(\"Nodes histogram:\", s.NodeHistogram)\n\tfmt.Println(\"Links histogram:\", s.LinkHistogram)\n\tfmt.Println(\"TimeToNode histogram:\", s.TimeToNodeHistogram)\n}", "func Print() {\n\tfmt.Printf(\"Fabric peer server version %s\\n\", metadata.Version)\n}", "func Print(messages ...string) {\n\tif !verbose {\n\t\treturn\n\t}\n\n\tfor _, msg := range messages {\n\t\tfmt.Fprint(vDest, msg)\n\t}\n}", "func (s *ServerT) PrintInfo() {\n\tsupport.Logger.Infof(\"* Version %s (%s), build: %s\", support.VERSION, runtime.Version(), support.Build)\n\tsupport.Logger.Infof(\"* Environment: %s\", s.Config.AppyEnv)\n\tsupport.Logger.Infof(\"* Environment Config: %s\", support.DotenvPath)\n\n\thosts, _ := s.Hosts()\n\thost := fmt.Sprintf(\"http://%s:%s\", hosts[0], s.Config.HTTPPort)\n\n\tif s.Config.HTTPSSLEnabled == true {\n\t\thost = fmt.Sprintf(\"https://%s:%s\", hosts[0], s.Config.HTTPSSLPort)\n\t}\n\n\tsupport.Logger.Infof(\"* Listening on %s\", host)\n}", "func PrintStatus(resp gorequest.Response, body string, errs []error) {\n\tfmt.Println(\"<== \")\n\tfor _, e := range errs {\n\t\tif e != nil {\n\t\t\tfmt.Println(e)\n\t\t\treturn\n\t\t}\n\t}\n\n\tfmt.Println(\"<== Rsp Status:\", resp.Status)\n\tfmt.Printf(\"<== Rsp Body: %s\\n\", body)\n}", "func (s *counts) Report(title string, opts *options) {\n\tif opts.ShowLines {\n\t\tfmt.Printf(\"%8v\", s.lines)\n\t}\n\tif opts.ShowWords {\n\t\tfmt.Printf(\"%8v\", s.words)\n\t}\n\tif opts.ShowChars {\n\t\tfmt.Printf(\"%8v\", s.chars)\n\t}\n\tfmt.Printf(\" %8v\\n\", title)\n}", "func (m *Manager) statPrint() {\n\tfor {\n\t\tfmt.Printf(\"Customers Today: %03d, In Store: %03d, Shopping: %02d,\"+\n\t\t\t\" At Checkout: %02d, Checkouts Open: %d\\r\",\n\t\t\ttotalNumberOfCustomersToday, totalNumberOfCustomersInStore, numberOfCurrentCustomersShopping,\n\t\t\tnumberOfCurrentCustomersAtCheckout, numberOfCheckoutsOpen)\n\t\ttime.Sleep(time.Millisecond * 40)\n\n\t\tif !m.supermarket.openStatus && totalNumberOfCustomersInStore == 0 {\n\t\t\tfmt.Printf(\"\\n\")\n\t\t\tbreak\n\t\t}\n\t}\n\n\tm.wg.Done()\n}", "func (g *GlobalStats) PrintStatus() {\n\tg.nowScraping.RLock()\n\tdefer g.nowScraping.RUnlock()\n\n\tfmt.Println()\n\t// XXX: Optimize this if necessary.\n\tfor k, v := range g.nowScraping.Blog {\n\t\tif v {\n\t\t\tfmt.Println(k.GetStatus())\n\t\t}\n\t}\n\tfmt.Println()\n\n\tfmt.Println(g.filesDownloaded, \"/\", g.filesFound-g.alreadyExists, \"files downloaded.\")\n\tif g.alreadyExists != 0 {\n\t\tfmt.Println(g.alreadyExists, \"previously downloaded.\")\n\t}\n\tif g.hardlinked != 0 {\n\t\tfmt.Println(g.hardlinked, \"new hardlinks.\")\n\t}\n\tfmt.Println(byteSize(g.bytesDownloaded), \"of files downloaded during this session.\")\n\tfmt.Println(byteSize(g.bytesOverhead), \"of data downloaded as JSON overhead.\")\n\tfmt.Println(byteSize(g.bytesSaved), \"of bandwidth saved due to hardlinking.\")\n}", "func PrintPassengerDetails(passenger Passenger) {\n\tfmt.Println()\n\tfmt.Print(\"PASSENGER NAME - \")\n\tcolor.Set(color.FgMagenta)\n\tfmt.Printf(\"%s\\n\", strings.ToUpper(passenger.Name))\n\tcolor.Unset()\n\tfmt.Printf(\"ID : %d, AGE : %d, GENDER : %s, AADHAAR NO. : %s\\n\", passenger.Id, passenger.Age, passenger.Gender, passenger.AadhaarNo)\n\t//fmt.Println()\n\tPrintPassengerTravelHistory(passenger.TravelHistory)\n}", "func ExamplePrint() {\n\n\tprintTable(n, testAgainst[1:])\n\t//Output:\n\t//1 x 1 = 1\n\t//1 x 2 = 2\n\t//1 x 3 = 3\n}", "func (pg *ProblemGraph) NicePrint(bc *Blockchain) {\n\tfmt.Printf(\"\\n\")\n\tprintBlue(fmt.Sprintf(\"Hash: %x\\n\",pg.Hash))\n\t// for fr, to := range pg.Graph.AdjacencyList {\n // \tfmt.Println(fr, to)\n\t// }\n\tconnected := pg.Graph.IsConnected()\n\tprintGreen(fmt.Sprintf(\"Connected: %s\\n\", strconv.FormatBool(connected)))\n\t// for k := 3; k <= 8; k++ {\n\t// \tkcliques := pg.FindAllKCliques(k)\n\t// \tprintYellow(fmt.Sprintf(\"%d %d-cliques:\",len(kcliques), k))\n\t// \tfor _, c := range kcliques {\n\t// \t\tfmt.Print(c)\n\t// \t}\n\t// \tfmt.Print(\"\\n\")\n\t// }\n\tbsol := bc.GetBestSolution(pg, bc.GetBestHeight())\n\tprintYellow(fmt.Sprintf(\"Best solution: %d-clique:\",len(bsol)))\n\tfmt.Println(bsol)\n}", "func (p Plan) PrettyPrint() {\n\tfmt.Println(\"-> BEGIN AffectedServers\")\n\tfor _, server := range p.AffectedServers {\n\t\tfmt.Println(server.Name)\n\t}\n\tfmt.Println(\"=> END AffectedServers\")\n\tfmt.Println(\"-> BEGIN Commands\")\n\tfor k, commands := range p.Commands {\n\t\tround := k + 1\n\t\tfmt.Printf(\"--> BEGIN Round %d\\n\", round)\n\t\tfor _, command := range commands {\n\t\t\tif command.Sleep != 0 {\n\t\t\t\tfmt.Printf(\"---> Wait for %+v\\n\", command.Sleep)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfmt.Printf(\"---> BEGIN Server %s\\n\", command.Host.Name)\n\t\t\tfmt.Printf(\"----> RUN %s %s (Additional info: %+v; %+v)\\n\", command.Command, command.Args, command.Ports, command.Sleep)\n\t\t\tfor _, task := range command.SubTasks {\n\t\t\t\tfmt.Printf(\"-----> BEGIN Client %s\\n\", task.Host.Name)\n\t\t\t\tfmt.Printf(\"------> RUN %s %s (Additional info: %+v)\\n\", task.Command, task.Args, task.Ports)\n\t\t\t\tfmt.Printf(\"=====> END Client %s\\n\", task.Host.Name)\n\t\t\t}\n\t\t\tfmt.Printf(\"===> END Server %s\\n\", command.Host.Name)\n\t\t}\n\t\tfmt.Printf(\"==> END Round %d\\n\", round)\n\t}\n\tfmt.Println(\"=> END Commands\")\n}", "func (o *Options) Print(v interface{}) {\n\trows, err := getFormattedOutput(o.Log, v, *o.FO, getFormatter(o.Log, v))\n\tif err != nil {\n\t\to.out.Write([]byte(fmt.Sprintf(\"%v\\n\", err)))\n\t\treturn\n\t}\n\to.out.Write([]byte(fmt.Sprintf(\"%s\\n\", strings.Join(rows, \"\\n\"))))\n}", "func PrintEngine(engine *Engine) {\n\n\tprintln(\"---------------QLCPro Engine-----------------\")\n\n\tfor _, universe := range engine.InputOutputMap.Universes {\n\n\t\tfmt.Printf(\"Universe: Name=%v ID=%v\\n\", universe.Name, universe.ID)\n\t\tfmt.Printf(\" Output: Plugin=%v Line=%v\\n\", universe.Output.Plugin, universe.Output.Line)\n\t\tfmt.Printf(\" PluginParameters: outputIP=%v outputUni=%v transmitMode=%v\\n\",\n\t\t\tuniverse.Output.PluginParameter.OutputIP,\n\t\t\tuniverse.Output.PluginParameter.OutputUni,\n\t\t\tuniverse.Output.PluginParameter.TransmitMode,\n\t\t)\n\t}\n\n\tfmt.Printf(\"\\n\\nTotal Universes: %v\\n\\n\", len(engine.InputOutputMap.Universes))\n\tprintln(\"-----------------------------------------------\")\n\n\tfor _, fixture := range engine.Fixtures {\n\t\tfmt.Printf(\"Fixture\\n\")\n\t\tfmt.Printf(\" Manufacturer=%v\\n\", fixture.Manufacturer)\n\t\tfmt.Printf(\" Model=%v\\n\", fixture.Model)\n\t\tfmt.Printf(\" Mode=%v\\n\", fixture.Mode)\n\t\tfmt.Printf(\" ID=%v\\n\", fixture.ID)\n\t\tfmt.Printf(\" Name=%v\\n\", fixture.Name)\n\t\tfmt.Printf(\" Universe=%v\\n\", fixture.Universe)\n\t\tfmt.Printf(\" Address=%v\\n\", fixture.Address)\n\t\tfmt.Printf(\" Channels=%v\\n\", fixture.Channels)\n\t\tfmt.Printf(\" ExcludeFade=%v\\n\", fixture.ExcludeFade)\n\t}\n\n\tfmt.Printf(\"\\n\\nTotal Fixtures: %v\\n\\n\", len(engine.Fixtures))\n\tprintln(\"-----------------------------------------------\")\n\n\tfor _, fixtureGroup := range engine.FixtureGroups {\n\t\tfmt.Printf(\"FixtureGroup ID=%v Name=%v w=%v h=%v\\n\",\n\t\t\tfixtureGroup.ID,\n\t\t\tfixtureGroup.Name,\n\t\t\tfixtureGroup.Width,\n\t\t\tfixtureGroup.Height,\n\t\t)\n\t\tfor _, head := range fixtureGroup.Heads {\n\t\t\tfmt.Printf(\" Head X=%v Y=%v Fixture=%v Value=%v\\n\",\n\t\t\t\thead.X,\n\t\t\t\thead.Y,\n\t\t\t\thead.Fixture,\n\t\t\t\thead.Value,\n\t\t\t)\n\t\t}\n\t}\n\n\tfmt.Printf(\"\\n\\nTotal FixtureGroups: %v\\n\\n\", len(engine.FixtureGroups))\n\tprintln(\"-----------------------------------------------\")\n\n\tfor _, channelGroup := range engine.ChannelGroups {\n\t\tfmt.Printf(\"ChannelGroup ID=%v Name=%v Value=%v Channels=%v\\n\",\n\t\t\tchannelGroup.ID,\n\t\t\tchannelGroup.Name,\n\t\t\tchannelGroup.Value,\n\t\t\tchannelGroup.Channels,\n\t\t)\n\t}\n\n\tfmt.Printf(\"\\n\\nTotal ChannelGroups: %v\\n\\n\", len(engine.ChannelGroups))\n\tprintln(\"-----------------------------------------------\")\n\n}", "func (context *context) PrintTimings() {\n\tcontext.model.ctx.Whisper_print_timings()\n}", "func (self *TravellerBots) reportSummary(mp ModelParams) {\n\n\t// Compile results\n\tvar compiledBands []botStatsCompiled\n\tfor _,bot := range(self.bots) {\n\t\tcompiledBands = append(compiledBands, bot.stats.compile(bot.numInstances, mp.ReportDayDelta))\n\t}\n\t\n\t// Output CSV\n\tfn := filepath.Join(mp.WorkingFolder,\"bands.csv\")\n\tfh,_ := os.Create(fn)\n\tif fh == nil {\n\t\treturn\n\t}\n\tline:=\"Day\"\n\tfor i,_ := range(compiledBands) {\n\t\tline += fmt.Sprintf(\",refusedpercent_%d,cancelledpercent_%d,distance_%d\",i,i,i) \n\t}\n\tline +=\"\\n\"\n\tfh.WriteString(line)\n\tfor i:=0; i < len(compiledBands[0].lines); i++ {\n\t\tlineOut := fmt.Sprintf(\"%d,\",flap.Days(i+1) *mp.ReportDayDelta)\n\t\tfor _,compiled := range(compiledBands) {\n\t\t\tlineOut += compiled.lines[i]\n\t\t}\n\t\tlineOut=strings.TrimRight(lineOut,\",\")\n\t\tlineOut+=\"\\n\"\n\t\tfh.WriteString(lineOut)\n\t}\n\n\t// Output graphs\n\treportBandsDistance(compiledBands,mp)\n\treportBandsCancelled(compiledBands,mp)\n}", "func printDiffReport(r *Report, to io.Writer) {\n\tfor _, entry := range r.entries {\n\t\tfmt.Fprintf(to, ansi.Color(\"%s %s\", \"yellow\")+\"\\n\", entry.key, r.format.changestyles[entry.changeType].message)\n\t\tprintDiffRecords(entry.suppressedKinds, entry.kind, entry.context, entry.diffs, to)\n\t}\n}", "func (t *Track) Print() {\n\tfmt.Println(\"Track :\")\n\tfmt.Println(\"\\tindex : \", t.index)\n\tfmt.Println(\"\\tisAudio : \", t.isAudio)\n\tfmt.Println(\"\\tcreationTime : \", t.creationTime)\n\tfmt.Println(\"\\tmodificationTime : \", t.modificationTime)\n\tfmt.Println(\"\\tduration : \", t.duration)\n\tfmt.Println(\"\\ttimescale : \", t.timescale)\n\tfmt.Println(\"\\tgolbalTimescale : \", t.globalTimescale)\n\tfmt.Println(\"\\twidth : \", t.width)\n\tfmt.Println(\"\\theight : \", t.height)\n\tfmt.Println(\"\\tsampleRate : \", t.sampleRate)\n\tfmt.Println(\"\\tbitsPerSample : \", t.bitsPerSample)\n\tfmt.Println(\"\\tcolorTableId : \", t.colorTableId)\n\tfmt.Println(\"\\tbandwidth: \", t.bandwidth)\n\tfmt.Println(\"\\tcodec: \", t.codec)\n\tfmt.Println(\"\\tencrypted : \", (t.encryptInfos != nil))\n\tfmt.Println(\"\\tsamples count : \", len(t.samples))\n\tfmt.Println(\"\\tsegment type : \", t.segmentType)\n\tfmt.Println(\"\\tinit offset : \", t.initOffset)\n}", "func (r *ResultPrinter) PrintViolations(violations *domain.Violations) {\n\tif len(violations.Violations) > 0 {\n\t\tfmt.Fprint(r.buffer, r.formatter.FormatViolations(\"MUST\", violations.Must()))\n\t\tfmt.Fprint(r.buffer, r.formatter.FormatViolations(\"SHOULD\", violations.Should()))\n\t\tfmt.Fprint(r.buffer, r.formatter.FormatViolations(\"MAY\", violations.May()))\n\t\tfmt.Fprint(r.buffer, r.formatter.FormatViolations(\"HINT\", violations.Hint()))\n\n\t\tfmt.Fprint(r.buffer, r.formatter.FormatViolationsCount(&violations.ViolationsCount))\n\t}\n\tfmt.Fprint(r.buffer, r.formatter.FormatServerMessage(violations.Message))\n\n\tif violations.Message == \"\" && len(violations.Violations) == 0 {\n\t\tfmt.Fprint(r.buffer, r.formatter.FormatMessage(\"Congratulations! No violations found.\"))\n\t}\n}", "func (p Properties) Print() {\n\tfmt.Print(p)\n}", "func (r *Reporter) Report() {\n\t//---------------------------------------------------\n\t// Report to console\n\t//---------------------------------------------------\n\tsort.Ints(r.nOrderPerSec)\n\tsort.Ints(r.nRequestPerSec)\n\tnOrderPerSecMax := MeanOfMaxFive(r.nOrderPerSec)\n\tnOrderPerSecMin := MeanOfMinFive(r.nOrderPerSec)\n\tnOrderPerSecMean := Mean(r.nOrderPerSec)\n\tnRequestPerSecMax := MeanOfMaxFive(r.nRequestPerSec)\n\tnRequestPerSecMin := MeanOfMinFive(r.nRequestPerSec)\n\tnRequestPerSecMean := Mean(r.nRequestPerSec)\n\tsort.Ints(r.nRequestPerSec)\n\tpayCostNanoseconds := []float64{}\n\tfor i := 0; i < len(r.payCosts); i++ {\n\t\tpayCostNanoseconds = append(payCostNanoseconds, float64(r.payCosts[i].Nanoseconds()))\n\t}\n\tsort.Float64s(payCostNanoseconds)\n\tmsTakenTotal := int(r.elapsed.Nanoseconds() / 1000000.0)\n\tmsPerOrder := MeanFloat64(payCostNanoseconds) / 1000000.0\n\tmsPerRequest := SumFloat64(payCostNanoseconds) / 1000000.0 / float64(r.nRequestOk)\n\t//---------------------------------------------------\n\t// Report to console\n\t//---------------------------------------------------\n\tfmt.Print(\"\\nStats\\n\")\n\tfmt.Printf(\"Concurrency level: %d\\n\", r.cocurrency)\n\tfmt.Printf(\"Time taken for tests: %dms\\n\", msTakenTotal)\n\tfmt.Printf(\"Complete requests: %d\\n\", r.nRequestOk)\n\tfmt.Printf(\"Failed requests: %d\\n\", r.nRequestErr)\n\tfmt.Printf(\"Complete orders: %d\\n\", r.nOrderOk)\n\tfmt.Printf(\"Failed orders: %d\\n\", r.nOrderErr)\n\tfmt.Printf(\"Time per request: %.2fms\\n\", msPerRequest)\n\tfmt.Printf(\"Time per order: %.2fms\\n\", msPerOrder)\n\tfmt.Printf(\"Request per second: %d (max) %d (min) %d(mean)\\n\", nRequestPerSecMax, nRequestPerSecMin, nRequestPerSecMean)\n\tfmt.Printf(\"Order per second: %d (max) %d (min) %d (mean)\\n\\n\", nOrderPerSecMax, nOrderPerSecMin, nOrderPerSecMean)\n\tfmt.Printf(\"Percentage of orders made within a certain time (ms)\\n\")\n\tif len(payCostNanoseconds) == 0 {\n\t\treturn\n\t}\n\tpercentages := []float64{10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 95.5, 96, 96.5, 97, 97.5, 98, 98.5, 99, 99.9, 99.99, 100}\n\tfor _, percentage := range percentages {\n\t\tidx := int(percentage * float64(len(payCostNanoseconds)) / float64(100.0))\n\t\tif idx > 0 {\n\t\t\tidx = idx - 1\n\t\t} else {\n\t\t\tidx = 0\n\t\t}\n\t\tpayCostNanosecond := payCostNanoseconds[idx]\n\t\tfmt.Printf(\"%.2f%%\\t%d ms\\n\", percentage, int(payCostNanosecond/1000000.0))\n\t}\n}", "func (res BackTestResult) Show() TradestatPort {\n\t//\tp := NewPortfolio()\n\tmds := bean.NewRPCMDSConnC(\"tcp\", res.dbhost+\":\"+res.dbport)\n\tratesbook := make(ReferenceRateBook)\n\n\t// FIXME: think about how to show multi pair result\n\tvar stat TradestatPort\n\tif len(res.pairs) > 0 {\n\t\tp := res.pairs[0]\n\t\ttxn, _ := mds.GetTransactions(p, res.start, res.end)\n\t\tratesbook[p] = RefRatesFromTxn(txn)\n\t\t//\t\tsnapts.Print()\n\t\t//\t\tperfts.Print()\n\n\t\tstat = *Tradestat(p.Base, res.Txn, NewPortfolio(), ratesbook)\n\t\tstat.Print()\n\t}\n\treturn stat\n}", "func (s *severity) Print(details ...string) {\n\tj := &Jable{\n\t\tName: \"DTLS\",\n\t\tValue: fmt.Sprintf(\"%v\", details),\n\t}\n\t_, _ = log(s, j)\n}", "func PrintTable(outputs []core.Output, mirror io.Writer) {\n\tcolorReset := \"\\033[0m\"\n\tcolorRed := \"\\033[31m\"\n\tcolorGreen := \"\\033[32m\"\n\tcolorYellow := \"\\033[33m\"\n\tcolorCyan := \"\\033[36m\"\n\tt := table.NewWriter()\n\tt.SetOutputMirror(mirror)\n\tt.AppendHeader(table.Row{\"URL\", \"Endpoint\", \"Severity\", \"Plugin\", \"Remediation\"})\n\tfor _, output := range outputs {\n\t\tseverity := \"\"\n\t\tif output.Severity == \"High\" {\n\t\t\tseverity = fmt.Sprint(string(colorRed), \"High\", string(colorReset))\n\t\t} else if output.Severity == \"Medium\" {\n\t\t\tseverity = fmt.Sprint(string(colorYellow), \"Medium\", string(colorReset))\n\t\t} else if output.Severity == \"Low\" {\n\t\t\tseverity = fmt.Sprint(string(colorGreen), \"Low\", string(colorReset))\n\t\t} else {\n\t\t\tseverity = fmt.Sprint(string(colorCyan), \"Informational\", string(colorReset))\n\t\t}\n\t\tt.AppendRow([]interface{}{\n\t\t\toutput.URL,\n\t\t\toutput.Endpoint,\n\t\t\tseverity,\n\t\t\toutput.Name,\n\t\t\toutput.Remediation,\n\t\t})\n\t}\n\tt.SortBy([]table.SortBy{\n\t\t{Name: \"Severity\", Mode: table.Asc},\n\t})\n\tt.Render()\n}", "func PrintTracks(s statefulsort.StatefulSort) {\n\ttracks := GetTracks(s)\n\tconst format = \"%v\\t%v\\t%v\\t%v\\t%v\\t\\n\"\n\ttw := new(tabwriter.Writer).Init(os.Stdout, 0, 8, 2, ' ', 0)\n\tfmt.Fprintf(tw, format, \"Title\", \"Artist\", \"Album\", \"Year\", \"Length\")\n\tfmt.Fprintf(tw, format, \"-----\", \"------\", \"-----\", \"----\", \"------\")\n\tfor _, t := range tracks {\n\t\tfmt.Fprintf(tw, format, t.Title, t.Artist, t.Album, t.Year, t.Length)\n\t}\n\ttw.Flush() // calculate column widths and print table\n}", "func pverbose(format string, a ...interface{}) (n int, err error) {\n\tif *flVerbose {\n\t\treturn fmt.Printf(format+\"\\n\", a...)\n\t}\n\treturn 0, nil\n}", "func (trds TradeLogS) PrintStats(p Pair) {\n\tpv := make([]float64, 1)\n\tpl := make([]float64, 1)\n\tbaseAmt := 0.0\n\tassetAmt := 0.0\n\tfor _, v := range trds {\n\t\tif v.Pair == p {\n\t\t\tsign := 1.0\n\t\t\tif v.Side == \"SELL\" {\n\t\t\t\tsign = -1.0\n\t\t\t}\n\t\t\tbaseAmt = baseAmt - v.Price*v.Quantity*sign\n\t\t\tassetAmt = assetAmt + v.Quantity*sign\n\t\t\tif v.CommissionAsset == v.Pair.Base {\n\t\t\t\tbaseAmt = baseAmt - v.Commission\n\t\t\t} else {\n\t\t\t\tassetAmt = assetAmt - v.Commission\n\t\t\t}\n\t\t\tpl = append(pl, baseAmt+assetAmt*v.Price-pv[len(pv)-1])\n\t\t\tpv = append(pv, baseAmt+assetAmt*v.Price)\n\t\t}\n\t}\n\tmaxdd := MaxDD(pv)\n\tfmt.Println(\"MaxDD:\\t\", maxdd)\n\tfmt.Println(\"PL:\\t\", pv[len(pl)-1])\n}", "func (cp *CLIProvisioner) printTableResult(result entities.OperationResult) {\n\twriter := NewTabWriterHelper()\n\twriter.Println(\"Request:\\t\", result.RequestId)\n\twriter.Println(\"Type:\\t\", entities.ToOperationTypeString[result.Type])\n\twriter.Println(\"Progress:\\t\", entities.TaskProgressToString[result.Progress])\n\twriter.Println(\"Elapsed Time:\\t\", time.Duration(result.ElapsedTime).String())\n\tif result.Progress == entities.Error {\n\t\twriter.Println(\"Error:\\t\", result.ErrorMsg)\n\t} else {\n\t\tif result.ProvisionResult != nil {\n\t\t\twriter.Println(\"KubeConfig:\\t\", cp.writeKubeConfig(cp.request.ClusterName, result.ProvisionResult.RawKubeConfig))\n\t\t\twriter.Println(\"Ingress IP:\\t\", result.ProvisionResult.StaticIPAddresses.Ingress)\n\t\t\twriter.Println(\"DNS IP:\\t\", result.ProvisionResult.StaticIPAddresses.DNS)\n\t\t\twriter.Println(\"CoreDNS IP:\\t\", result.ProvisionResult.StaticIPAddresses.CoreDNSExt)\n\t\t\twriter.Println(\"VPN Server IP:\\t\", result.ProvisionResult.StaticIPAddresses.VPNServer)\n\t\t} else {\n\t\t\tlog.Warn().Msg(\"expecting provisioning result\")\n\t\t}\n\t}\n\terr := writer.Flush()\n\tif err != nil {\n\t\tlog.Fatal().Err(err).Msg(\"cannot write result to stdout\")\n\t}\n}", "func (r PrettyReporter) Report(ch chan *Result) error {\n\n\tdirty := false\n\tvar pass, fail, errs int\n\n\t// Report individual tests.\n\tfor tr := range ch {\n\t\tif tr.Pass() {\n\t\t\tpass++\n\t\t} else if tr.Error != nil {\n\t\t\terrs++\n\t\t} else if tr.Fail != nil {\n\t\t\tfail++\n\t\t}\n\t\tif !tr.Pass() || r.Verbose {\n\t\t\tfmt.Fprintln(r.Output, tr)\n\t\t\tdirty = true\n\t\t}\n\t\tif tr.Error != nil {\n\t\t\tfmt.Fprintf(r.Output, \" %v\\n\", tr.Error)\n\t\t}\n\t}\n\n\t// Report summary of test.\n\tif dirty {\n\t\tfmt.Fprintln(r.Output, strings.Repeat(\"-\", 80))\n\t}\n\n\ttotal := pass + fail + errs\n\n\tif pass != 0 {\n\t\tfmt.Fprintln(r.Output, \"PASS:\", fmt.Sprintf(\"%d/%d\", pass, total))\n\t}\n\n\tif fail != 0 {\n\t\tfmt.Fprintln(r.Output, \"FAIL:\", fmt.Sprintf(\"%d/%d\", fail, total))\n\t}\n\n\tif errs != 0 {\n\t\tfmt.Fprintln(r.Output, \"ERROR:\", fmt.Sprintf(\"%d/%d\", errs, total))\n\t}\n\n\treturn nil\n}", "func (r *Release) PrintStatus(out io.Writer) error {\n\tstatus, err := r.hapiClient.ReleaseStatus(r.name)\n\tif err != nil {\n\t\treturn errors.New(grpc.ErrorDesc(err))\n\t}\n\n\tif status.Info.LastDeployed != nil {\n\t\tfmt.Fprintf(out, \"LAST DEPLOYED: %s\\n\", timeconv.String(status.Info.LastDeployed))\n\t}\n\tfmt.Fprintf(out, \"NAMESPACE: %s\\n\", status.Namespace)\n\tfmt.Fprintf(out, \"STATUS: %s\\n\", status.Info.Status.Code)\n\tfmt.Fprintf(out, \"\\n\")\n\tif len(status.Info.Status.Resources) > 0 {\n\t\tre := regexp.MustCompile(\" +\")\n\n\t\tw := tabwriter.NewWriter(out, 0, 0, 2, ' ', tabwriter.TabIndent)\n\t\tfmt.Fprintf(w, \"RESOURCES:\\n%s\\n\", re.ReplaceAllString(status.Info.Status.Resources, \"\\t\"))\n\t\tw.Flush()\n\t}\n\tif status.Info.Status.LastTestSuiteRun != nil {\n\t\tlastRun := status.Info.Status.LastTestSuiteRun\n\t\tfmt.Fprintf(out, \"TEST SUITE:\\n%s\\n%s\\n\\n\",\n\t\t\tfmt.Sprintf(\"Last Started: %s\", timeconv.String(lastRun.StartedAt)),\n\t\t\tfmt.Sprintf(\"Last Completed: %s\", timeconv.String(lastRun.CompletedAt)),\n\t\t)\n\t}\n\n\tif len(status.Info.Status.Notes) > 0 {\n\t\tfmt.Fprintf(out, \"NOTES:\\n%s\\n\", status.Info.Status.Notes)\n\t}\n\treturn nil\n}", "func PrintResults(analysis types.Analysis) error {\n\n\tprepareAllSummary(analysis)\n\n\tif types.IsJSONoutput {\n\t\terr := printJSONOutput()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tprintSTDOUTOutput(analysis)\n\t}\n\n\treturn nil\n}", "func printChallenge(challenge AutomataChallenge) {\n\tfmt.Println()\n\tfmt.Println(\"Ruleset:\", challenge.Rules.Name)\n\tfmt.Println(\"Birth:\", challenge.Rules.Birth)\n\tfmt.Println(\"Survival:\", challenge.Rules.Survival)\n\tfmt.Println(\"Generations:\", challenge.Generations)\n}", "func GenerateTextReport(report analyzer.VulnerabilityReport, displayColumns int) {\n\tfmt.Printf(\"Summary Total:%d Open:%d High: %d Medium: %d Low: %d Unknown: %d Ignored: %d \\n\", report.CountTotal, report.CountOpen, report.CountHigh, report.CountMedium, report.CountLow, report.CountUnknown, report.CountIgnore)\n\tfor _, vul := range report.Vulnerabilities {\n\n\t\tmaxLen := len(vul.Description)\n\t\tif displayColumns < maxLen {\n\t\t\tmaxLen = displayColumns\n\t\t}\n\n\t\tfmt.Printf(\"%-12s %-6s %s: %s \\n\", vul.PackageName, vul.Severity, vul.CVE, vul.Description[:maxLen])\n\t}\n}", "func (vs *Vulnerabilities) Print() {\n\tfor _, v := range *vs {\n\t\tv.PrintPackageNameVersion()\n\t}\n}", "func (interpreter *StandardInterpreter) SummaryReport() []byte {\n\tbuf := bytes.NewBufferString(\"\")\n\tfmt.Fprintln(buf, \"<table><tr><th>Flower Summary</th></tr>\")\n\n\tfmt.Fprintln(buf, \"<tr><th>Rules</th></tr>\")\n\tfor element := interpreter.commands.Front(); element != nil; element = element.Next() {\n\t\tcmd, ok := element.Value.(*ServiceCommand)\n\t\tif ok {\n\t\t\tfmt.Fprintln(buf, \"<tr><td>\", cmd.String(), \"</tr></td>\")\n\t\t}\n\t}\n\tfmt.Fprintln(buf, \"</table>\")\n\treturn buf.Bytes()\n}", "func Print() {\n\tfmt.Printf(\"hierarchy, version %v (branch: %v, revision: %v), build date: %v, go version: %v\\n\", Version, Branch, GitSHA1, BuildDate, runtime.Version())\n}", "func Print(b *builder.FileBuilder) {\n\tp := &protoprint.Printer{}\n\tdesc, err := b.Build()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tstr, err := p.PrintProtoToString(desc)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Println(str)\n}", "func (l *Loader) printStatus() {\n\tfinishedSize := l.finishedDataSize.Load()\n\ttotalSize := l.totalDataSize.Load()\n\ttotalFileCount := l.totalFileCount.Load()\n\n\tinterval := time.Since(l.dbTableDataLastUpdatedTime)\n\tfor db, tables := range l.dbTableDataFinishedSize {\n\t\tfor table, size := range tables {\n\t\t\tcurFinished := size.Load()\n\t\t\tspeed := float64(curFinished-l.dbTableDataLastFinishedSize[db][table]) / interval.Seconds()\n\t\t\tl.dbTableDataLastFinishedSize[db][table] = curFinished\n\t\t\tif speed > 0 {\n\t\t\t\tremainingSeconds := float64(l.dbTableDataTotalSize[db][table].Load()-curFinished) / speed\n\t\t\t\tremainingTimeGauge.WithLabelValues(l.cfg.Name, l.cfg.WorkerName, l.cfg.SourceID, db, table).Set(remainingSeconds)\n\t\t\t}\n\t\t}\n\t}\n\tl.dbTableDataLastUpdatedTime = time.Now()\n\n\tl.logger.Info(\"progress status of load\",\n\t\tzap.Int64(\"finished_bytes\", finishedSize),\n\t\tzap.Int64(\"total_bytes\", totalSize),\n\t\tzap.Int64(\"total_file_count\", totalFileCount),\n\t\tzap.String(\"progress\", percent(finishedSize, totalSize, l.finish.Load())))\n\tprogressGauge.WithLabelValues(l.cfg.Name, l.cfg.SourceID).Set(progress(finishedSize, totalSize, l.finish.Load()))\n}", "func (a *Analyzer) Print(writer io.Writer, printAll bool) {\n\tparsedListeners := a.getParsedListeners()\n\t_, _ = fmt.Fprintf(writer, \"Checked %d/%d listeners with node IP %s.\\n\",\n\t\tlen(parsedListeners), len(a.listenerDump.DynamicListeners), a.nodeIP)\n\tPrintParsedListeners(writer, parsedListeners, printAll)\n}", "func (bpt *BplusTree) Print() {\n\tenabled, freq := TestPointIsEnabled(testPointFailDBFetch)\n\tif enabled {\n\t\tTestPointDisable(testPointFailDBFetch)\n\t}\n\tbpt.writeTree(true)\n\tif enabled {\n\t\tTestPointEnable(testPointFailDBFetch, freq)\n\t}\n}", "func Print(v ...interface{}) { std.lprint(INFO, v...) }", "func (v Vertex) Print() {\n fmt.Printf(\"Vertice: %d\\n Feromona Ini: %f\\n Feromona Act: %f\\n\", v.index, v.pheromone_init, v.pheromone)\n}", "func PrintInfo(descriptorDir string, status *tor.RouterStatus) {\n\n\tdesc, err := tor.LoadDescriptorFromDigest(descriptorDir, status.Digest, status.Publication)\n\tif err == nil {\n\t\tif !printedBanner {\n\t\t\tfmt.Println(\"fingerprint,nickname,ip_addr,or_port,dir_port,flags,published,version,platform,bandwidthavg,bandwidthburst,uptime,familysize\")\n\t\t\tprintedBanner = true\n\t\t}\n\t\tfmt.Printf(\"%s,%s,%d,%d,%d,%d\\n\", status, desc.OperatingSystem, desc.BandwidthAvg, desc.BandwidthBurst, desc.Uptime, len(desc.Family))\n\t} else {\n\t\tif !printedBanner {\n\t\t\tfmt.Println(\"fingerprint,nickname,ip_addr,or_port,dir_port,flags,published,version\")\n\t\t\tprintedBanner = true\n\t\t}\n\t\tfmt.Println(status)\n\t}\n}", "func (mgmt *MonitoringManager) PrintMonitoring() {\n\tif len(mgmt.MonitorList) <= 0 {\n\t\tfmt.Println(\"No IP monitoring facility\")\n\t\treturn\n\t}\n\tfmt.Println(\"==========================================\")\n\tfor _,v := range mgmt.MonitorList {\n\t\tfmt.Printf(\"%s - %s - %s to %s\\n\", v.Message.Addr.String(), v.Facility, v.Start.Format(\"02/01/2006 15:04:05\"), v.End.Format(\"02/01/2006 15:04:05\"))\n\t}\n\tfmt.Println(\"==========================================\")\n}", "func ShowInfo(agentID uuid.UUID) {\n\n\tif !isAgent(agentID) {\n\t\tmessage(\"warn\", fmt.Sprintf(\"%s is not a valid agent!\", agentID))\n\t\treturn\n\t}\n\n\ttable := tablewriter.NewWriter(os.Stdout)\n\ttable.SetAlignment(tablewriter.ALIGN_LEFT)\n\n\tdata := [][]string{\n\t\t{\"Status\", GetAgentStatus(agentID)},\n\t\t{\"ID\", Agents[agentID].ID.String()},\n\t\t{\"Platform\", Agents[agentID].Platform},\n\t\t{\"Architecture\", Agents[agentID].Architecture},\n\t\t{\"UserName\", Agents[agentID].UserName},\n\t\t{\"User GUID\", Agents[agentID].UserGUID},\n\t\t{\"Hostname\", Agents[agentID].HostName},\n\t\t{\"Process ID\", strconv.Itoa(Agents[agentID].Pid)},\n\t\t{\"IP\", fmt.Sprintf(\"%v\", Agents[agentID].Ips)},\n\t\t{\"Initial Check In\", Agents[agentID].InitialCheckIn.Format(time.RFC3339)},\n\t\t{\"Last Check In\", Agents[agentID].StatusCheckIn.Format(time.RFC3339)},\n\t\t{\"Agent Version\", Agents[agentID].Version},\n\t\t{\"Agent Build\", Agents[agentID].Build},\n\t\t{\"Agent Wait Time\", Agents[agentID].WaitTime},\n\t\t{\"Agent Wait Time Skew\", strconv.FormatInt(Agents[agentID].Skew, 10)},\n\t\t{\"Agent Message Padding Max\", strconv.Itoa(Agents[agentID].PaddingMax)},\n\t\t{\"Agent Max Retries\", strconv.Itoa(Agents[agentID].MaxRetry)},\n\t\t{\"Agent Failed Check In\", strconv.Itoa(Agents[agentID].FailedCheckin)},\n\t\t{\"Agent Kill Date\", time.Unix(Agents[agentID].KillDate, 0).UTC().Format(time.RFC3339)},\n\t\t{\"Agent Communication Protocol\", Agents[agentID].Proto},\n\t}\n\ttable.AppendBulk(data)\n\tfmt.Println()\n\ttable.Render()\n\tfmt.Println()\n}", "func (info *Info) PrintTo(p *Printer) {\n\tif len(info.Cnames) > 0 {\n\t\tp.Print(\"cnames {\")\n\t\tp.ShiftIn()\n\t\tfor _, r := range info.Cnames {\n\t\t\tp.Printf(\"%v -> %v\", r.Domain, RdToDomain(r.Rdata))\n\t\t}\n\t\tp.ShiftOut(\"}\")\n\t}\n\n\tif len(info.Results) == 0 {\n\t\tp.Print(\"(unresolvable)\")\n\t} else {\n\t\tp.Print(\"ips {\")\n\t\tp.ShiftIn()\n\n\t\tfor _, r := range info.Results {\n\t\t\td := r.Domain\n\t\t\tip := RdToIPv4(r.Rdata)\n\t\t\tif d.Equal(info.Domain) {\n\t\t\t\tp.Printf(\"%v\", ip)\n\t\t\t} else {\n\t\t\t\tp.Printf(\"%v(%v)\", ip, d)\n\t\t\t}\n\t\t}\n\n\t\tp.ShiftOut(\"}\")\n\t}\n\n\tif len(info.NameServers) > 0 {\n\t\tp.Print(\"servers {\")\n\t\tp.ShiftIn()\n\n\t\tfor _, ns := range info.NameServers {\n\t\t\tp.Printf(\"%v\", ns)\n\t\t}\n\n\t\tp.ShiftOut(\"}\")\n\t}\n\n\tif len(info.Records) > 0 {\n\t\tp.Print(\"records {\")\n\t\tp.ShiftIn()\n\n\t\tfor _, rr := range info.Records {\n\t\t\tp.Printf(\"%v\", rr.Digest())\n\t\t}\n\n\t\tp.ShiftOut(\"}\")\n\t}\n}", "func ShowPassengerTable() {\n\ttbl := table.New(\"ID\", \"Name\", \"Age\", \"Gender\", \"Aadhaar No.\", \"Number of Travels\")\n\ttbl.WithHeaderFormatter(func(format string, vals ...interface{}) string {\n\t\treturn strings.ToUpper(fmt.Sprintf(format, vals...))\n\t})\n\n\tpassengers := GetPassengerDetails()\n\n\tfor _, passenger := range passengers {\n\t\ttbl.AddRow(passenger.Id, passenger.Name, passenger.Age, passenger.Gender, passenger.AadhaarNo, len(passenger.TravelHistory))\n\t}\n\n\ttbl.Print()\n}", "func PrintVersionInfo(log logr.Logger) {\n\tlog.Info(\"Kyverno\", \"Version\", BuildVersion)\n\tlog.Info(\"Kyverno\", \"BuildHash\", BuildHash)\n\tlog.Info(\"Kyverno\", \"BuildTime\", BuildTime)\n}", "func printStatusWorkers(ps []pumaStatusWorker, currentPhase int) error {\n\tfor _, key := range ps {\n\t\tphase := Green(fmt.Sprintf(\"%d\", key.CurrentPhase))\n\t\tif key.CurrentPhase != currentPhase {\n\t\t\tphase = Red(fmt.Sprintf(\"%d\", key.CurrentPhase))\n\t\t}\n\n\t\tif !ExpandDetails {\n\t\t\tlcheckin := Green(timeElapsed(key.LastCheckin))\n\t\t\tif len(timeElapsed(key.LastCheckin)) >= 3 {\n\t\t\t\tlcheckin = Brown(timeElapsed(key.LastCheckin))\n\t\t\t}\n\n\t\t\tfmt.Printf(\"* %d [%d] CPU Av: %s%% CPU Times: %s Mem: %sMiB Phase: %s Uptime: %s Threads: %s (Last checkin: %s)\\n\", key.ID, key.Pid, colorCPU(key.CPUPercent), timeElapsedFromSeconds(key.CPUTimes), colorMemory(key.Memory), phase, timeElapsed(time.Unix(key.Uptime, 0).Format(time.RFC3339)), asciiThreadLoad(key.CurrentThreads, key.MaxThreads), lcheckin)\n\t\t\tcontinue\n\t\t}\n\n\t\tbootbtn := BgGreen(Bold(\"[UP]\"))\n\t\tif !key.IsBooted {\n\t\t\tbootbtn = BgRed(Bold(\"[DOWN]\"))\n\t\t\tfmt.Printf(\"* %s ~ PID %d\\tWorker ID %d\\tLast checkin: %s\\n\", bootbtn, key.Pid, key.ID, timeElapsed(key.LastCheckin))\n\t\t\tcontinue\n\t\t}\n\n\t\tfmt.Printf(\"* %s ~ PID %d\\tWorker ID %d\\tCPU Average: %s%%\\tMem: %sMiB\\tActive threads: %s\\n\", bootbtn, key.Pid, key.ID, colorCPU(key.CPUPercent), colorMemory(key.Memory), asciiThreadLoad(key.CurrentThreads, key.MaxThreads))\n\t\tfmt.Printf(\" Phase: %s\\tLast checkin: %s\\tTotal CPU times: %s\\tUptime: %s\\n\", phase, timeElapsed(key.LastCheckin), timeElapsedFromSeconds(key.CPUTimes), timeElapsed(time.Unix(key.Uptime, 0).Format(time.RFC3339)))\n\t}\n\treturn nil\n}", "func PrintPassengerTravelHistory(history []TravelHistory) {\n\tif len(history) < 1 {\n\t\tcolor.Set(color.FgCyan)\n\t\tfmt.Printf(\"NO TRAVEL RECORDS\\n\")\n\t\tcolor.Unset()\n\t\treturn\n\t}\n\tcolor.Set(color.FgCyan)\n\tfmt.Printf(\"TRAVEL RECORDS\\n\")\n\tcolor.Unset()\n\ttbl := table.New( \"Train name\", \"Train number\", \"Date\", \"Time\", \"From\", \"To\", \"Travel Class\").WithPadding(4)\n\tfor _, travel := range history {\n\t\ttbl.AddRow(travel.TrainName, travel.TrainNumber, travel.Date,travel.Time, travel.Location.From, travel.Location.To, travel.TravelClass)\n\t}\n\n\ttbl.Print()\n}", "func (self *StraightLineTrack) Print(prefix string) string {\n\tresult := fmt.Sprintf(\"%s/%s\\n\", prefix, self.Name)\n\tfor _, val := range self.Childs() {\n\t\tresult += val.Print(fmt.Sprintf(\"%s/%s\", prefix, self.Name))\n\t}\n\treturn result\n}", "func (obj *Facility) Report() {\n\tobj.BaseObj.Report()\n\tavr := obj.sumAdvance / obj.cntTransact\n\tfmt.Printf(\"Average advance %.2f \\tAverage utilization %.2f%%\\tNumber entries %.2f \\t\", avr,\n\t\t100*avr*obj.cntTransact/float64(obj.Pipe.SimTime), obj.cntTransact)\n\tif obj.HoldedTransactID > 0 {\n\t\tfmt.Print(\"Transact \", obj.HoldedTransactID, \" in facility\")\n\t\tpart, _, parentID := obj.tb.Item(obj.HoldedTransactID).transact.GetParts()\n\t\tif parentID > 0 {\n\t\t\tfmt.Print(\", parent transact \", parentID, \" part \", part)\n\t\t}\n\t} else {\n\t\tfmt.Print(\"Facility is empty\")\n\t}\n\tfmt.Printf(\"\\n\\n\")\n}", "func show_progress()bool{\nreturn flags['p']/* should progress reports be printed? */\n}", "func (l *LogConnect) Print(status string) error {\n\tl.Type = \"connect\"\n\tl.Status = status\n\tl.Time = time.Now()\n\treturn encoder.Encode(l)\n}", "func RRreportPets(ctx context.Context, ri *ReporterInfo) string {\n\tm, err := rlib.GetAllPets(ctx, ri.Raid)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\ts := fmt.Sprintf(\"%-11s %-10s %-25s %-15s %-15s %-15s %-9s %-10s %-10s\\n\", \"PETID\", \"RAID\", \"Name\", \"Type\", \"Breed\", \"Color\", \"Weight\", \"DtStart\", \"DtStop\")\n\tfor i := 0; i < len(m); i++ {\n\n\t\t// just before printing out, modify end date for this struct if applicable\n\t\trlib.HandleInterfaceEDI(&m[i], ri.Bid)\n\n\t\tswitch ri.OutputFormat {\n\t\tcase gotable.TABLEOUTTEXT:\n\t\t\ts += ReportPetToText(&m[i])\n\t\tcase gotable.TABLEOUTHTML:\n\t\t\tfmt.Printf(\"UNIMPLEMENTED\\n\")\n\t\tdefault:\n\t\t\tfmt.Printf(\"RRreportPets: unrecognized print format: %d\\n\", ri.OutputFormat)\n\t\t\treturn \"\"\n\t\t}\n\t}\n\treturn s\n}", "func (ir *InterpretResults) Print() {\n\tfor _, result := range ir.Results {\n\t\tfmt.Println(result)\n\t}\n\n\t// If there were results, skip a line at the end for readability\n\tif len(ir.Results) > 0 {\n\t\tfmt.Println(\"\")\n\t}\n}", "func (conf *Config) Print() {\n\tlog.Info().Str(\"app\", version.AppVersion).Str(\"commit\", version.Commit).Msg(\"version\")\n\tlog.Info().Int(\"port\", conf.Port).Msg(\"metrics endpoint port\")\n\tlog.Info().Str(\"namespace\", conf.Namespace).Str(\"subsystem\", conf.Subsystem).Str(\"name\", conf.Name).Msg(\"metric name\")\n\tlog.Info().Str(\"label\", conf.LabelName).Msg(\"label name\")\n\tlog.Info().Str(\"file\", conf.LabelFile).Msg(\"label values file\")\n}", "func (t Track) String() string {\n\tvar buf bytes.Buffer\n\tfmt.Fprintf(&buf, \"(%d) %s\\t\", t.ID, t.Name)\n\tfor i := 0; i < 16; i++ {\n\t\tif i%4 == 0 {\n\t\t\tfmt.Fprintf(&buf, \"|\")\n\t\t}\n\t\tif t.Steps[i] {\n\t\t\tfmt.Fprintf(&buf, \"x\")\n\t\t} else {\n\t\t\tfmt.Fprintf(&buf, \"-\")\n\t\t}\n\t}\n\tfmt.Fprintf(&buf, \"|\")\n\treturn buf.String()\n}", "func (s *StatLine) Print() string {\n\tvar res string\n\tif s.indexStat == \"R\" {\n\t\tres = fmt.Sprintf(\"%s was renamed to %s\\n\", s.oldPath, s.newPath)\n\t}\n\tres = res + fmt.Sprintf(\"%s is %s in the index and %s in the working tree.\",\n\t\ts.newPath,\n\t\tstatMap[s.indexStat],\n\t\tstatMap[s.workStat])\n\treturn res\n}", "func (p *Printer) Print(v ...interface{}) FullPrinter {\n state, fc := p.initState()\n defer p.reset(state)\n p.formatter.Print(fc, v...)\n p.fc.Writer.Write(state.Buffer)\n return p\n}", "func (s State) PPrint() {\n\tfmt.Print(s.String())\n}" ]
[ "0.56297374", "0.5454212", "0.54532796", "0.5422705", "0.5390026", "0.5388474", "0.5382206", "0.53081554", "0.5283081", "0.52563685", "0.5192705", "0.5180458", "0.51753974", "0.51391655", "0.5104317", "0.50879496", "0.5086181", "0.50839156", "0.5070934", "0.5053879", "0.5048816", "0.50394154", "0.5025253", "0.50198233", "0.50152975", "0.5007784", "0.49915963", "0.4975726", "0.4971894", "0.49715436", "0.4966398", "0.4948139", "0.4922718", "0.49084738", "0.4897359", "0.48919228", "0.48819053", "0.48814613", "0.48713577", "0.4871032", "0.48607233", "0.48531762", "0.48375115", "0.4835417", "0.48337576", "0.4819518", "0.4817682", "0.48131117", "0.480718", "0.48026624", "0.4796282", "0.47960132", "0.47902143", "0.47878692", "0.47830987", "0.476789", "0.4767039", "0.47606176", "0.47565702", "0.4737479", "0.4736497", "0.47272694", "0.47268635", "0.4725022", "0.47232726", "0.47225416", "0.47161207", "0.47078687", "0.47040758", "0.469906", "0.46974012", "0.46947616", "0.46910673", "0.46848407", "0.46837837", "0.46833038", "0.46735716", "0.46664983", "0.46656242", "0.46636075", "0.4662441", "0.4655576", "0.46480095", "0.4647745", "0.46426976", "0.4633924", "0.4632091", "0.4629", "0.46259806", "0.4625952", "0.46214798", "0.46169564", "0.4606444", "0.46053234", "0.46039593", "0.4598307", "0.45978612", "0.45958292", "0.45938343", "0.4584767" ]
0.702964
0
===== philosopherData methods CanEat checks if the philosopher specific criteria of eating is fulfilled.
func (pd *philosopherData) CanEat(maxDinner int) string { switch { case pd.eating: return "E:EATING" case pd.dinnersSpent >= maxDinner: return "E:LIMIT" case time.Now().Sub(pd.finishedAt) < (time.Duration(150) * time.Millisecond): return "E:JUSTFINISHED" } return "OK" }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pb *PhilosopherBase) IsEating() bool {\n\treturn pb.State == philstate.Eating\n}", "func (pb *PhilosopherBase) CheckEating() {\n\t// Check the primary invariant - neither neighbor should be eating, and I should hold\n\t// both forks\n\tAssert(\n\t\tfunc() bool {\n\t\t\treturn pb.LeftPhilosopher().GetState() != philstate.Eating &&\n\t\t\t\tpb.RightPhilosopher().GetState() != philstate.Eating\n\t\t},\n\t\t\"eat while a neighbor is eating\",\n\t)\n\n\tAssert(\n\t\tfunc() bool {\n\t\t\treturn pb.LeftFork().IsHeldBy(pb.ID) &&\n\t\t\t\tpb.RightFork().IsHeldBy(pb.ID)\n\t\t},\n\t\t\"eat without holding forks\",\n\t)\n}", "func (host *DinnerHost) AllowEating(name string) string {\n\tif host.currentlyEating >= host.maxParallel {\n\t\treturn \"E:FULL\"\n\t}\n\n\tdata := host.phiData[name]\n\n\tcanEat := data.CanEat(host.maxDinner)\n\tif canEat != \"OK\" {\n\t\treturn canEat\n\t}\n\n\tseatNumber := data.Seat()\n\tleftChop := seatNumber\n\trightChop := (seatNumber + 1) % host.tableCount\n\n\tif host.chopsticksFree[leftChop] {\n\t\thost.chopsticksFree[leftChop] = false\n\t\tdata.SetLeftChop(leftChop)\n\t}\n\tif host.chopsticksFree[rightChop] {\n\t\thost.chopsticksFree[rightChop] = false\n\t\tdata.SetRightChop(rightChop)\n\t}\n\n\tif !data.HasBothChopsticks() {\n\t\treturn \"E:CHOPSTICKS\"\n\t}\n\n\thost.currentlyEating++\n\tdata.StartedEating()\n\n\treturn \"OK\"\n}", "func (pb *PhilosopherBase) Eat() {\n\n\tpb.State = philstate.Eating\n\tpb.StartEating()\n}", "func (bo *hareOracle) Eligible(id uint32, committeeSize int, pubKey string, proof []byte) bool {\n\t//note: we don't use the proof in the oracle server. we keep it just for the future syntax\n\t//todo: maybe replace k to be uint32 like hare wants, and don't use -1 for blocks\n\treturn bo.oc.Eligible(id, committeeSize, pubKey)\n}", "func (philosopher *Philosopher) Eat(wg *sync.WaitGroup, host Host) {\n\tfor i := 0; i < 3; i++ {\n\t\thost.GiveMePermission()\n\t\tphilosopher.leftChopstick.Lock()\n\t\tphilosopher.rightChopstick.Lock()\n\t\tfmt.Printf(\"Starting to eat %d\\n\", philosopher.id)\n\t\ttime.Sleep(500 * time.Millisecond)\n\t\tfmt.Printf(\"Finishing eating %d. (time: %d)\\n\", philosopher.id, i+1)\n\t\tphilosopher.rightChopstick.Unlock()\n\t\tphilosopher.leftChopstick.Unlock()\n\t\thost.Done()\n\t}\n\twg.Done()\n}", "func philosopherPonderanceGoroutine(id int) {\n\tfor {\n\t\tif rand.Float64() < PHILSWITCHCHANCE {\n\t\t\tphilIn[id] <- 2\n\t\t\tisEating := <- philOut[id] == 1\n\t\t\t// Switch: Thinking <-> Eating.\n\t\t\tif isEating {\n\t\t\t\t// Drop forks and return to positing on the nature of the universe.\n\t\t\t\tphilIn[id] <- 1\n\t\t\t} else {\n\t\t\t\t// Attempt to begin eating. Return to postulating, if missing fork.\n\t\t\t\tphilIn[id] <- 0\n\t\t\t}\n\t\t\t<- philOut[id]\n\t\t}\n\t}\n}", "func (s Shark) Eat(a Animal) bool {\n\treturn s.Power() > a.Hp\n}", "func (b *OGame) IsPioneers() bool {\n\treturn b.lobby == LobbyPioneers\n}", "func (pd *philosopherData) FinishedEating() {\n\tpd.eating = false\n\tpd.leftChopstick = -1\n\tpd.rightChopstick = -1\n\tpd.finishedAt = time.Now()\n}", "func (pd *philosopherData) StartedEating() {\n\tpd.eating = true\n\tpd.dinnersSpent++\n}", "func CheckMapPointForFood(tile *GopherWorldTile) bool {\n\treturn tile.Food != nil && tile.Gopher == nil\n}", "func (pb *PhilosopherBase) IsHungry() bool {\n\treturn pb.State == philstate.Hungry\n}", "func (c CombatState) IsPartyDefeated() bool {\n\tfor _, actor := range c.Actors[party] {\n\t\tif !actor.IsKOed() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func canride(age, heightcm int) string {\n\tif (age >= 12) && (heightcm > 100){\n\t\treturn \"Can ride!\"\n\t} else {\n\t\treturn \"You cannot ride!\"\n\t}\n}", "func (p *Player) CanProceed(head, tail int) bool {\n\tfor _, domino := range p.GetDominos() {\n\t\tif domino.half[0] == head || domino.half[0] == tail ||\n\t\t\tdomino.half[1] == head || domino.half[1] == tail {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func planAppliedButProbesNeverHealthy(entry *planEntry) bool {\n\treturn entry.Plan.AppliedPlan != nil && reflect.DeepEqual(entry.Plan.Plan, *entry.Plan.AppliedPlan) && !entry.Plan.Healthy && !entry.Plan.ProbesUsable\n}", "func (p *OnuTcontProfile) CanSetAssured() bool {\r\n\treturn p.TcontType == 5 || p.TcontType == 3 || p.TcontType == 2\r\n}", "func (w *RandomWorld) IsHabitable(location GoWorld.Location) (bool, error) {\n\tif w.IsOutOfBounds(location) {\n\t\treturn false, fmt.Errorf(\n\t\t\t\"error checking inhabitable spot: the location (%d, %d) is out of bounds. WorldSize (%v, %v)\",\n\t\t\tlocation.X, location.Y, w.Width, w.Height)\n\t}\n\treturn w.TerrainSpots[location.X][location.Y].Surface.Habitable, nil\n}", "func doesHit(attacker *pet, defender pet) (bool){\n\tchanceToHit := float64(attacker.EffectiveACC) - defender.EffectiveEVA\n\t\n\tif float64(rand.Intn(100)) < chanceToHit {\n\t\treturn true\n\t}\n\t\n\t//fmt.Println(attacker.PetUser.Username, \" miss!\")\n\tattacker.MissCount++\n\treturn false\n}", "func (_Consents *consentsCaller) IsAllowedAt(ctx context.Context, userId [8]byte, appName string, action uint8, dataType string, blockNumber *big.Int) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\n\terr := _Consents.contract.Call(&bind.CallOpts{Context: ctx}, out, \"isAllowedAt\", userId, appName, action, dataType, blockNumber)\n\treturn *ret0, err\n}", "func (pb *PhilosopherBase) StartEating() {\n\tpb.WriteString(\"starts eating\")\n\tpb.DelaySend(pb.EatRange, NewState{NewState: philstate.Thinking})\n}", "func (y *YKVal) Phishing(ytoken *yubico.Token, ykey *yubico.Yubikey) bool {\n\t// this implementation raises more questions than answers...\n\t// https://github.com/Yubico/yubikey-val/blob/a850489d245c01c0f232db56af8ff0bfaa93fb21/ykval-verify.php#L431\n\t// however we need to only check if counter is the same otherwise we can't rely on yubikey clock\n\tif uint(ytoken.Counter()) != ykey.Counter {\n\t\treturn false\n\t}\n\n\ty.Debug().Object(\"yubikey\", util.YubikeyTSLog(*ykey)).\n\t\tObject(\"token\", util.TokenTSLog(*ytoken)).Msg(\"phishing test\")\n\tnow := time.Now().Unix()\n\tdelta := uint(ytoken.Tstph)<<16 + uint(ytoken.Tstpl) - ykey.High<<16 - ykey.Low\n\tdeviation := abs(now - ykey.Modified - int64(float64(delta)*KeyClockFreq))\n\tpercentage := float64(1)\n\tif now-ykey.Modified != 0 {\n\t\tpercentage = float64(deviation) / float64(now-ykey.Modified)\n\t}\n\ty.Debug().Uint(\"delta\", delta).Int64(\"deviation\", deviation).\n\t\tFloat64(\"percentage\", percentage).Msg(\"phishing test\")\n\treturn deviation > AbsTolerance && percentage > RelTolerance\n}", "func (c Certificate) Meets(lvl LevelOfTrust) bool {\n\treturn lvl.MetBy(c.Level)\n}", "func (gopher *Gopher) CheckMapPointForPartner(tile *GopherWorldTile) bool {\n\treturn tile.Gopher != nil && tile.Gopher.IsLookingForLove() && gopher.Gender.Opposite() == tile.Gopher.Gender\n}", "func (g *Game) CanPlaceSomewhere() bool {\n\tfor row := 0; row < BoardHeight; row++ {\n\t\tfor col := 0; col < BoardWidth; col++ {\n\t\t\tif g.IsValidPlacement(Piece{row, col}) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}", "func (_CommitteeManager *CommitteeManagerCaller) IsGovernor(opts *bind.CallOpts, account common.Address) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _CommitteeManager.contract.Call(opts, out, \"isGovernor\", account)\n\treturn *ret0, err\n}", "func (_CommitteeManager *CommitteeManagerCallerSession) IsGovernor(account common.Address) (bool, error) {\n\treturn _CommitteeManager.Contract.IsGovernor(&_CommitteeManager.CallOpts, account)\n}", "func (gt GtwyMgr) IsPermitted(ctx context.Context, appcontext, remoteAddress string) (bool, error) {\n\tif EnvDebugOn {\n\t\tlblog.LogEvent(\"GtwyMgr\", \"IsPermitted\", \"info\", \"start\")\n\t}\n\n\t//check the approval list\n\tq := datastore.NewQuery(gt.bc.GetConfigValue(ctx, \"EnvGtwayDsKind\")).\n\t\tNamespace(gt.bc.GetConfigValue(ctx, \"EnvGtwayDsNamespace\")).\n\t\tFilter(\"appcontext =\", appcontext).\n\t\tFilter(\"remoteaddress =\", remoteAddress).\n\t\tKeysOnly()\n\n\t//get the count\n\tn, err := gt.ds.Count(ctx, q)\n\t//if there was an error return it and false\n\tif err != nil {\n\t\tif err != datastore.ErrNoSuchEntity {\n\t\t\treturn false, err\n\t\t}\n\t\treturn false, nil\n\t}\n\n\t//return false if the count was zero\n\tif n == 0 {\n\t\treturn false, nil\n\t}\n\n\tif EnvDebugOn {\n\t\tlblog.LogEvent(\"GtwyMgr\", \"IsPermitted\", \"info\", strconv.Itoa(n))\n\t\tlblog.LogEvent(\"GtwyMgr\", \"IsPermitted\", \"info\", \"end\")\n\t}\n\n\t//otherwise the address is valid\n\treturn true, nil\n}", "func doesCrit(attacker *pet) (bool) {\n\tcritRand := float64(rand.Intn(100))\n\t\n\tif critRand < attacker.EffectiveCRI {\n\t\t//fmt.Println(attacker.PetUser.Username, \" rolled a\", critRand, \" crit!\")\n\t\tattacker.CritCount++\n\t\treturn true\n\t}\n\t\n\treturn false\n\t\n}", "func TestRecommendConfigEtcd_CheckProviderProbability_DataScienceOn(t *testing.T) {\n\tcfg := &recommendConfigEtcd{\n\t\trecommendEnabled: true,\n\t\trecommendMainPageEnabled: true,\n\t\trecommendDataScience: 100,\n\t\trecommendSponsoredProducts: 0,\n\t\trecommendTaobao: 0,\n\t\trandomizer: rand.New(rand.NewSource(time.Now().UnixNano())),\n\t}\n\n\tassert.Equal(t, false, cfg.CheckProviderProbability(ProviderTB))\n\tassert.Equal(t, false, cfg.CheckProviderProbability(ProviderTBPlacement))\n\tassert.Equal(t, false, cfg.CheckProviderProbability(ProviderTBWidget))\n\tassert.Equal(t, true, cfg.CheckProviderProbability(ProviderDS))\n\tassert.Equal(t, false, cfg.CheckProviderProbability(ProviderSP))\n}", "func (gs *GaleShapely) isBetterThanFiance(man, woman, fiance int) bool {\n\tfor _, choice := range gs.womenWishes[woman] {\n\t\tswitch choice {\n\t\tcase man:\n\t\t\treturn true\n\t\tcase fiance:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn false\n}", "func ExamHouse(h storage.House) bool {\n\treturn h.Age <= 5\n}", "func (r *Race) CanReach(atlas *Atlas, row, col int) bool {\n\tif r.OccupiedRegions(atlas) == 0 {\n\t\tif !atlas.IsAtBorder(row, col) {\n\t\t\treturn false\n\t\t}\n\t} else {\n\t\townRegionNearby := false\n\t\tf := func(region RegionI) {\n\t\t\tif troop := region.GetTroop(); troop != nil {\n\t\t\t\tif troop.Symbol == r.GetSymbol() {\n\t\t\t\t\townRegionNearby = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tatlas.ApplyToNeighbors(row, col, f)\n\t\tif ownRegionNearby == false {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func CheckMapPointForFemaleGopher(tile *GopherWorldTile) bool {\n\treturn tile.Gopher != nil && tile.Gopher.IsLookingForLove() && Female == tile.Gopher.Gender\n}", "func (_CommitteeManager *CommitteeManagerSession) IsGovernor(account common.Address) (bool, error) {\n\treturn _CommitteeManager.Contract.IsGovernor(&_CommitteeManager.CallOpts, account)\n}", "func (s *State) IsAbleToRecoverFromUnderstaffedState() bool {\n\ts.mtx.RLock()\n\tresult := len(s.ActivityProducers) >= s.chainParams.GeneralArbiters\n\ts.mtx.RUnlock()\n\treturn result\n}", "func (cm *CostModel) CanCompute(start, end time.Time) bool {\n\treturn start.Before(time.Now())\n}", "func (ferry *Ferry) CanAccept(car *Car) bool {\n\tfor _, accepted := range ferry.acceptedCars {\n\t\t// check if current type is accepted and has free space for this car.\n\t\tif car.Kind == accepted && len(ferry.loadedCars) < ferry.Capacity {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (o *NewLoyaltyProgram) HasTiers() bool {\n\tif o != nil && o.Tiers != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (_ERC20HecoManager *ERC20HecoManagerCallerSession) IsOwner() (bool, error) {\n\treturn _ERC20HecoManager.Contract.IsOwner(&_ERC20HecoManager.CallOpts)\n}", "func (fl *FaultLine) Possible() bool {\n\treturn !fl.disabled && fl.rand.Float64() <= fl.possibleProbability\n}", "func (ec *EthereumChain) IsEligibleForApplication(application common.Address) (bool, error) {\n\treturn ec.bondedECDSAKeepFactoryContract.IsOperatorEligible(\n\t\tec.Address(),\n\t\tapplication,\n\t)\n}", "func (p philosopher) eat() {\n\tfor j := 0; j < numberOfCourses; j++ {\n\t\t//Pick up sticks means lock both mutex\n\t\tp.leftChopstick.Lock()\n\t\tp.rightChopstick.Lock()\n\t\t// Acknowledge the start\n\t\t//starting to eat <number>\n\t\tfmt.Printf(\"Starting to eat %d(%s) [%s] \\n\", p.id+1, nameOfPhilosophers[p.id], courses[j])\n\t\ttime.Sleep(time.Second)\n\t\t//Release mutex\n\t\tp.rightChopstick.Unlock()\n\t\tp.leftChopstick.Unlock()\n\t\t// Acknowledge the finish\n\t\t//finishing eating <number>\n\t\tfmt.Printf(\"finishing eating %d(%s) [%s] \\n\", p.id+1, nameOfPhilosophers[p.id], courses[j])\n\t\ttime.Sleep(time.Second)\n\t}\n\teatWaitingGroup.Done()\n}", "func (p *Player) IsSpottedBy(other *Player) bool {\n\tif p.Entity == nil {\n\t\treturn false\n\t}\n\n\t// TODO extract ClientSlot() function\n\tclientSlot := other.EntityID - 1\n\tbit := uint(clientSlot)\n\tvar mask st.IProperty\n\tif bit < 32 {\n\t\tmask = p.Entity.FindPropertyI(\"m_bSpottedByMask.000\")\n\t} else {\n\t\tbit -= 32\n\t\tmask = p.Entity.FindPropertyI(\"m_bSpottedByMask.001\")\n\t}\n\treturn (mask.Value().IntVal & (1 << bit)) != 0\n}", "func (h HostHandler) IsEligible(host string) (string, bool) {\n\tif _, ok := h.eligibleHosts[host]; ok {\n\t\treturn host, true\n\t}\n\treturn host, false\n}", "func (b *picnicBasket) happy() bool {\n\treturn b.nServings > 1 && b.corkscrew\n}", "func (pre *preRoundTracker) CanProveSet(set *Set) bool {\n\t// a set is provable iff all its Values are provable\n\tfor bid := range set.values {\n\t\tif !pre.CanProveValue(bid) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (o *Organism) CheckChampionChildDamaged() bool {\n\tif o.isPopulationChampionChild && o.highestFitness > o.Fitness {\n\t\treturn true\n\t}\n\treturn false\n}", "func (*Checker) Do(ctx sayori.Context) error {\n\taperm, err := ctx.Session.State.UserChannelPermissions(\n\t\tctx.Message.Author.ID, ctx.Message.ChannelID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif aperm&discordgo.PermissionAdministrator != discordgo.PermissionAdministrator {\n\t\treturn errors.New(\"you don't have admin perms :(\")\n\t}\n\n\treturn nil\n}", "func (pre *preRoundTracker) CanProveValue(value types.BlockID) bool {\n\t// at least threshold occurrences of a given value\n\treturn pre.tracker.CountStatus(value) >= pre.threshold\n}", "func (p *Percolator) Percolates() bool {\n\treturn p.sites.Connected(p.topID, p.bottomID)\n}", "func (MemLimiter) IsHealthy() bool {\n\treturn true\n}", "func (me TAttlistMedlineCitationOwner) IsPip() bool { return me.String() == \"PIP\" }", "func (_ERC20HecoManager *ERC20HecoManagerSession) IsOwner() (bool, error) {\n\treturn _ERC20HecoManager.Contract.IsOwner(&_ERC20HecoManager.CallOpts)\n}", "func (r *Room) Participate(p Player, x, y int, color string) bool {\n\tif r.Status != Waiting {\n\t\treturn false\n\t}\n\treturn r.board.Add(p, x, y, color)\n}", "func IsAfternoon() bool {\n localTime := time.Now()\n return localTime.Hour() <= 18\n}", "func (s ClosedDoorState) Can(n DoorState) bool {\n\tswitch n.(type) {\n\tcase OpenDoorState:\n\t\treturn true\n\tcase LockedDoorState:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (d *Device) IsThermostat() bool {\n\treturn bitMasked{Functionbitmask: d.Functionbitmask}.hasMask(64)\n}", "func (w *RandomWorld) canPlaceBeing(spot GoWorld.Location, beingType string) bool {\n\t// Is there perhaps another being present?\n\tif w.TerrainSpots[spot.X][spot.Y].Being == uuid.Nil {\n\t\t// Can being move anywhere (Flying)\n\t\tif beingType == \"Flying\" {\n\t\t\treturn true\n\t\t} else if beingType == \"Water\" {\n\t\t\t// Water beings can move on water\n\t\t\tspotName, _ := w.GetSurfaceNameAt(spot)\n\t\t\tif spotName == \"Water\" || spotName == \"Grassland\" {\n\t\t\t\treturn true\n\t\t\t}\n\t\t} else {\n\t\t\tif w.TerrainSpots[spot.X][spot.Y].Surface.Habitable {\n\t\t\t\t// Spot can be moved on, {\n\t\t\t\t// No being present and habitable, we can safely move a being to this spot\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\t// Spot was not habitable or a being was present\n\treturn false\n}", "func (s OpenDoorState) Can(n DoorState) bool {\n\tswitch n.(type) {\n\tcase ClosedDoorState:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (t *Table) AllDoneTaking() bool {\n\tfor _, p := range t.players {\n\t\tif !p.GetDoneTaking() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func TestRecommendConfigEtcd_CheckProviderProbability_On(t *testing.T) {\n\tcfg := &recommendConfigEtcd{\n\t\trecommendEnabled: true,\n\t\trecommendMainPageEnabled: true,\n\t\trecommendDataScience: 100,\n\t\trecommendSponsoredProducts: 100,\n\t\trecommendTaobao: 100,\n\t\trandomizer: rand.New(rand.NewSource(time.Now().UnixNano())),\n\t}\n\n\tassert.Equal(t, true, cfg.CheckProviderProbability(ProviderTB))\n\tassert.Equal(t, true, cfg.CheckProviderProbability(ProviderTBPlacement))\n\tassert.Equal(t, true, cfg.CheckProviderProbability(ProviderTBWidget))\n\tassert.Equal(t, true, cfg.CheckProviderProbability(ProviderDS))\n\tassert.Equal(t, true, cfg.CheckProviderProbability(ProviderSP))\n}", "func (_Harberger *HarbergerCallerSession) IsPetrified() (bool, error) {\n\treturn _Harberger.Contract.IsPetrified(&_Harberger.CallOpts)\n}", "func (w *RandomWorld) QuenchHunger(b *GoWorld.Being, foodSpot GoWorld.Location) bool {\n\t// Adjacent fields and the center point (9 locations)\n\t// Usually the character moves on top of food when eating it so check 0,0 first\n\n\t// Has the Being eaten?\n\tate := false\n\t// Check the distance from food to being\n\tdistanceToFood := w.Distance(b.Position, foodSpot)\n\tif distanceToFood < 2 {\n\t\t// Food spot is an adjacent field, we can eat\n\t\t// Do we eat beings or plants?\n\t\tif beingID := w.TerrainSpots[foodSpot.X][foodSpot.Y].Being; beingID != uuid.Nil && (b.Type == \"Carnivore\" ||\n\t\t\tb.Type == \"Flying\") {\n\n\t\t\t// Being is present on the spot, EAT IT\n\t\t\tbeingToEat := w.BeingList[beingID.String()]\n\t\t\tb.Hunger -= beingToEat.Size * 4 // Nutritional value of being is 4x its size\n\t\t\tate = true\n\t\t\tdelete(w.BeingList, beingID.String())\n\t\t\tw.TerrainSpots[foodSpot.X][foodSpot.Y].Being = uuid.Nil\n\t\t\tif b.Hunger < 0 {\n\t\t\t\tb.Hunger = 0\n\t\t\t}\n\n\t\t} else {\n\t\t\t// Herbivore: eat plants\n\t\t\tfoodID := w.TerrainSpots[foodSpot.X][foodSpot.Y].Object\n\t\t\tif foodID == uuid.Nil {\n\t\t\t\tfmt.Println(\"The spot does not have an item for being to eat\")\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif w.FoodList[foodID.String()] == nil {\n\t\t\t\tfmt.Println(\"Hmm, terrain spot has food that is not in food list?? Being can not eat here\")\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tfood := w.FoodList[foodID.String()]\n\t\t\t// Eat the whole thing -> lowers hunger by nutritional value\n\t\t\tb.Hunger -= food.NutritionalValue\n\t\t\tate = true\n\t\t\tdelete(w.FoodList, food.ID.String())\n\t\t\tw.TerrainSpots[food.Position.X][food.Position.Y].Object = uuid.Nil\n\t\t\tw.updatePlantSpot(food.Position.X, food.Position.Y, food.Area, uuid.Nil)\n\n\t\t\t// Hunger should not be negative\n\t\t\tif b.Hunger < 0 {\n\t\t\t\t// The being can not eat more, so break out of the loop\n\t\t\t\tb.Hunger = 0\n\t\t\t}\n\t\t\t// Todo also lower thirst with a small chance\n\t\t}\n\t}\n\n\treturn ate\n}", "func (p *Player) IsAllIn() bool {\n\treturn !(p.Money > 0 || p.IsOutGame() || p.HasFolded())\n}", "func (a *_Atom) isElectronDonating() bool {\n\tif a.unsatEwNbrCount > 0 || a.satEwNbrCount > 0 ||\n\t\ta.unsaturation != cmn.UnsaturationNone {\n\t\treturn false\n\t}\n\n\tswitch a.atNum {\n\tcase 7, 15:\n\t\treturn a.bonds.Count() <= 3\n\tcase 8, 16:\n\t\treturn a.bonds.Count() <= 2\n\t}\n\n\treturn false\n}", "func checkObstruction(e *Elevator) {\n\tprobabilityNotBlocked := 70\n\tnumber := rand.Intn(100) //This random simulates the probability of an obstruction (I supposed 30% of chance something is blocking the door)\n\tfor number > probabilityNotBlocked {\n\t\te.obstructionSensorStatus = sensorOn\n\t\tfmt.Println(\" ! Elevator door is blocked by something, waiting until door is free before continue...\")\n\t\tnumber -= 30 //I'm supposing the random number is 100, I'll subtract 30 so it will be less than 70 (30% probability), so the second time it runs theres no one blocking the door\n\t}\n\te.obstructionSensorStatus = sensorOff\n\tfmt.Println(\" Elevator door is FREE\")\n}", "func Can(resource uuid.UUID, who uuid.UUID, scopes []string) bool {\n\tpexes, err := models.FindPermissions(resource, who, scopes)\n\tif err != nil {\n\t\tlog.Error().\n\t\t\tErr(err).\n\t\t\tStr(\"resource\", resource.String()).\n\t\t\tStr(\"who\", who.String()).\n\t\t\tStrs(\"scopes\", scopes).\n\t\t\tMsg(\"Could not fetch permissions to check for access\")\n\n\t\t// cannot be certain the user has permission. Say no in case of doubt\n\t\treturn false\n\t}\n\n\treturn len(pexes) == len(scopes)\n}", "func (p *Prober) isHealthy() bool {\n\thealthy := atomic.LoadUint32(&p.healthy)\n\treturn healthy > 0\n}", "func TestRecommendConfigEtcd_CheckProviderProbability_TaobaoOn(t *testing.T) {\n\tcfg := &recommendConfigEtcd{\n\t\trecommendEnabled: true,\n\t\trecommendMainPageEnabled: true,\n\t\trecommendDataScience: 0,\n\t\trecommendSponsoredProducts: 0,\n\t\trecommendTaobao: 100,\n\t\trandomizer: rand.New(rand.NewSource(time.Now().UnixNano())),\n\t}\n\n\tassert.Equal(t, true, cfg.CheckProviderProbability(ProviderTB))\n\tassert.Equal(t, true, cfg.CheckProviderProbability(ProviderTBPlacement))\n\tassert.Equal(t, true, cfg.CheckProviderProbability(ProviderTBWidget))\n\tassert.Equal(t, false, cfg.CheckProviderProbability(ProviderDS))\n\tassert.Equal(t, false, cfg.CheckProviderProbability(ProviderSP))\n}", "func (oc *oracleClient) Eligible(layer types.LayerID, round uint32, committeeSize int, id types.NodeID, sig []byte) (bool, error) {\n\tinstID := hashInstanceAndK(layer, round)\n\t// make special instance ID\n\toc.eMtx.Lock()\n\tif r, ok := oc.eligibilityMap[instID]; ok {\n\t\t_, valid := r[id.Key]\n\t\toc.eMtx.Unlock()\n\t\treturn valid, nil\n\t}\n\n\treq := validateQuery(oc.world, instID, committeeSize)\n\n\tresp := oc.client.Get(validate, req)\n\n\tres := &validList{}\n\terr := json.Unmarshal(resp, res)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\telgMap := make(map[string]struct{})\n\n\tfor _, v := range res.IDs {\n\t\telgMap[v] = struct{}{}\n\t}\n\n\t_, valid := elgMap[id.Key]\n\n\toc.eligibilityMap[instID] = elgMap\n\n\toc.eMtx.Unlock()\n\treturn valid, nil\n}", "func (s *State) IsAtWar(id pb.ProvinceId) bool {\n\tfor _, c := range s.Conflicts {\n\t\tfor _, a := range c.Attackers() {\n\t\t\tif a == id {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\tfor _, d := range c.Defenders() {\n\t\t\tif d == id {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func (_TreasureHunt *TreasureHuntSession) IsTreasureHere(latitude *big.Int, longitude *big.Int) (*types.Transaction, error) {\n\treturn _TreasureHunt.Contract.IsTreasureHere(&_TreasureHunt.TransactOpts, latitude, longitude)\n}", "func (p *particle) confirm() bool {\n\tif p.flags&flags_confirmed == 0 {\n\t\tp.flags |= flags_confirmed\n\t\tp.pool.disappear(p)\n\t}\n\treturn p.flags&flags_up == flags_up\n}", "func (s LockedDoorState) Can(n DoorState) bool {\n\tswitch n.(type) {\n\tcase ClosedDoorState:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func planAppliedButWaitingForProbes(entry *planEntry) bool {\n\treturn entry.Plan.AppliedPlan != nil && reflect.DeepEqual(entry.Plan.Plan, *entry.Plan.AppliedPlan) && !entry.Plan.Healthy\n}", "func (cp *ConstantPacer) Pace(elapsed time.Duration, hits uint64) (time.Duration, bool) {\n\n\tif cp.Max > 0 && hits >= cp.Max {\n\t\treturn 0, true\n\t}\n\n\tif cp.Freq == 0 {\n\t\treturn 0, false // Zero value = infinite rate\n\t}\n\n\texpectedHits := uint64(cp.Freq) * uint64(elapsed/nano)\n\tif hits < expectedHits {\n\t\t// Running behind, send next hit immediately.\n\t\treturn 0, false\n\t}\n\n\tinterval := uint64(nano / int64(cp.Freq))\n\tif math.MaxInt64/interval < hits {\n\t\t// We would overflow delta if we continued, so stop the attack.\n\t\treturn 0, true\n\t}\n\n\tdelta := time.Duration((hits + 1) * interval)\n\t// Zero or negative durations cause time.Sleep to return immediately.\n\treturn delta - elapsed, false\n}", "func veteran(games []game) bool {\n\tif len(games) >= 1000 {\n\t\treturn true\n\t}\n\treturn false\n}", "func (p *particle) isConfirmed() bool {\n\treturn p.flags&flags_confirmed != 0\n}", "func (cow Cow) Eat() {\n\tfmt.Println(cow.food)\n}", "func (b Bond) Interesting(f Filter) bool {\n\t// remove bonds with low coupon\n\tif b.Coupon < f.MinimumCoupon {\n\t\treturn false\n\t}\n\n\t// remove bonds with no date or more than 6 years of maturity\n\tmaximumMaturity := time.Now().Add(f.MaximumMaturity.Duration)\n\tif b.Maturity == nil || b.Maturity.After(maximumMaturity) {\n\t\treturn false\n\t}\n\n\t// remove bonds with low price or too expensive\n\tif b.LastPrice < f.MinimumPrice || b.LastPrice > f.MaximumPrice {\n\t\treturn false\n\t}\n\n\tif b.MinimumPiece < f.MinimumPiece || b.MinimumPiece > f.MaximumPiece {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (_Consents *consentsCaller) IsAllowed(ctx context.Context, userId [8]byte, appName string, action uint8, dataType string) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\n\terr := _Consents.contract.Call(&bind.CallOpts{Context: ctx}, out, \"isAllowed\", userId, appName, action, dataType)\n\treturn *ret0, err\n}", "func (_TreasureHunt *TreasureHuntTransactorSession) IsTreasureHere(latitude *big.Int, longitude *big.Int) (*types.Transaction, error) {\n\treturn _TreasureHunt.Contract.IsTreasureHere(&_TreasureHunt.TransactOpts, latitude, longitude)\n}", "func (a *Analysis) CanTheyConnect() bool {\n\treturn a.CanEnterDestination.IsPassing &&\n\t\ta.CanEscapeSource.IsPassing &&\n\t\ta.ConnectionBetweenVPCsIsActive.IsPassing &&\n\t\ta.ConnectionBetweenVPCsIsValid.IsPassing &&\n\t\ta.SourceSubnetHasRoute.IsPassing &&\n\t\ta.DestinationSubnetHasRoute.IsPassing\n}", "func (i Itinerary) IsExpected(event HandlingEvent) bool {\n\tif i.IsEmpty() {\n\t\treturn true\n\t}\n\n\tswitch event.Activity.Type {\n\tcase Receive:\n\t\treturn i.InitialDepartureLocation() == event.Activity.Location\n\tcase Load:\n\t\tfor _, l := range i.Legs {\n\t\t\tif l.LoadLocation == event.Activity.Location && l.VoyageNumber == event.Activity.VoyageNumber {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\tcase Unload:\n\t\tfor _, l := range i.Legs {\n\t\t\tif l.UnloadLocation == event.Activity.Location && l.VoyageNumber == event.Activity.VoyageNumber {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\tcase Claim:\n\t\treturn i.FinalArrivalLocation() == event.Activity.Location\n\t}\n\n\treturn true\n}", "func (w *RandomWorld) canPlaceWaterPlant(x, y int, plantArea float64, plantID uuid.UUID) bool {\n\tif w.TerrainSpots[x][y].Surface.CommonName != \"Water\" {\n\t\t// Non water surface provided\n\t\treturn false\n\t}\n\n\tif w.TerrainSpots[x][y].OccupyingPlant == uuid.Nil || w.TerrainSpots[x][y].OccupyingPlant == plantID {\n\t\t// Get a circular area around the spot (2D, depth not accounted for) and check if a plant is too close\n\t\tspots := w.MidpointCircleAt(GoWorld.Location{X: x, Y: y}, plantArea/2)\n\t\tfor _, spot := range spots {\n\t\t\t// Skip non water surfaces, as we only need points in water\n\t\t\tif w.TerrainSpots[spot.X][spot.Y].Surface.CommonName != \"Water\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif w.TerrainSpots[spot.X][spot.Y].OccupyingPlant != uuid.Nil &&\n\t\t\t\tw.TerrainSpots[x][y].OccupyingPlant != plantID {\n\t\t\t\t// Found a plant occupying a spot, not enough room for this plant\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\t// The necessary spots are not occupied, meaning a plant can live here\n\t\treturn true\n\t}\n\treturn false\n}", "func (g *Game) IsTie() bool {\n\treturn !g.GameBoard.IsWinner('X') && !g.GameBoard.IsWinner('O') && g.GameBoard.IsFull()\n}", "func (d *Dex) CanDestroy(sumCallback func() chainTypes.Coins) (ok bool) {\n\tsum := sumCallback()\n\treturn len(sum) == 0 || sum.IsZero()\n}", "func (context *context) IsEOT(t Token) bool {\n\treturn whisper.Token(t.Id) == context.model.ctx.Whisper_token_eot()\n}", "func (_Harberger *HarbergerCaller) IsPetrified(opts *bind.CallOpts) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _Harberger.contract.Call(opts, out, \"isPetrified\")\n\treturn *ret0, err\n}", "func (me TxsdAnimValueAttrsCalcMode) IsPaced() bool { return me.String() == \"paced\" }", "func (g *Game) HasTie() bool {\n\tif g.Board[A1] != empty &&\n\t\tg.Board[B1] != empty &&\n\t\tg.Board[C1] != empty &&\n\t\tg.Board[A2] != empty &&\n\t\tg.Board[B2] != empty &&\n\t\tg.Board[C2] != empty &&\n\t\tg.Board[A3] != empty &&\n\t\tg.Board[B3] != empty &&\n\t\tg.Board[C3] != empty {\n\t\treturn true\n\t}\n\treturn false\n}", "func checkWin() (bool, bool) {\n\tif len(Multiverse.Universes) == 0 {\n\t\treturn false, false\n\t}\n\n\tgoodPlayers := 0\n\tevilPlayers := 0\n\tgoodMustKillPlayers := 0\n\tevilMustKillPlayers := 0\n\n\tUpdateRoleTotals()\n\n\tfor _, p := range Players {\n\t\tif !playerIsDead(p) {\n\t\t\tamountEvil := 0\n\t\t\tamountGood := 0\n\t\t\tamountEvilMustKill := 0\n\t\t\tamountGoodMustKill := 0\n\t\t\tfor k, v := range p.Role.Totals {\n\t\t\t\tmustKill := roleTypes[k].EnemyMustKill\n\t\t\t\tif roleTypes[k].Evil {\n\t\t\t\t\tamountEvil += v\n\t\t\t\t\tif mustKill {\n\t\t\t\t\t\tamountGoodMustKill += v\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tamountGood += v\n\t\t\t\t\tif mustKill {\n\t\t\t\t\t\tamountEvilMustKill += v\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif amountEvil > 0 && amountGood > 0 {\n\t\t\t\treturn false, false\n\t\t\t}\n\n\t\t\tif amountGood > 0 {\n\t\t\t\tgoodPlayers++\n\t\t\t\tif amountEvilMustKill > 0 {\n\t\t\t\t\tevilMustKillPlayers++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif amountEvil > 0 {\n\t\t\t\tevilPlayers++\n\t\t\t\tif amountGoodMustKill > 0 {\n\t\t\t\t\tgoodMustKillPlayers++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif evilMustKillPlayers == 0 && goodPlayers <= evilPlayers {\n\t\treturn true, true\n\t}\n\tif goodMustKillPlayers == 0 && goodPlayers >= evilPlayers {\n\t\treturn true, false\n\t}\n\treturn false, false\n}", "func shouldIPing() bool {\n\treturn !initialElection &&\n\t\t!bullyImpl.EnCours() &&\n\t\t!bullyImpl.IsCoordinator()\n}", "func (_TreasureHunt *TreasureHuntTransactor) IsTreasureHere(opts *bind.TransactOpts, latitude *big.Int, longitude *big.Int) (*types.Transaction, error) {\n\treturn _TreasureHunt.contract.Transact(opts, \"IsTreasureHere\", latitude, longitude)\n}", "func (me *GJUser) AwardTrophy(id string) bool{\n\tr:=me.qreq(\"trophies/add-achieved\",\"trophy_id=\"+id)\n\treturn r[\"success\"]==\"true\" // temp line\n}", "func hasEscape(room *data.Room) bool {\n\t// If an adjacent room has a door which is not in any other adjacent room,\n\t// then that room has access to a hallway or outside.\n\tdoors, _ := getDoors(room, make(map[*data.Room]bool, 0))\n\tdoorCount := make(map[*data.Door]int, 0)\n\tfor _, door := range doors {\n\t\tdoorCount[door]++\n\t}\n\tfor _, v := range doorCount {\n\t\tif v == 1 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (p *Player) IsAlive() bool {\n\treturn p.Hp > 0\n}", "func (_Harberger *HarbergerSession) IsPetrified() (bool, error) {\n\treturn _Harberger.Contract.IsPetrified(&_Harberger.CallOpts)\n}" ]
[ "0.67761284", "0.62960804", "0.5892676", "0.5866577", "0.54240215", "0.5404304", "0.53131825", "0.529867", "0.5275247", "0.5270269", "0.5256047", "0.4995168", "0.4951213", "0.49461287", "0.4871539", "0.48602024", "0.4853061", "0.484365", "0.48434243", "0.48209658", "0.481871", "0.48014688", "0.47778612", "0.47348", "0.47244662", "0.47177947", "0.46882474", "0.46693084", "0.46620485", "0.4652239", "0.4649779", "0.46384838", "0.46381348", "0.4635689", "0.4628486", "0.4622532", "0.45957255", "0.4577238", "0.45567116", "0.45397264", "0.45381528", "0.45346108", "0.4524026", "0.45214644", "0.45213056", "0.44941258", "0.44883", "0.44819772", "0.44816422", "0.4476816", "0.44746086", "0.44650754", "0.44560215", "0.44435588", "0.44356444", "0.44313887", "0.44310945", "0.44308493", "0.44276607", "0.44257653", "0.44246098", "0.44198975", "0.4415844", "0.4413125", "0.44086468", "0.4404283", "0.44013074", "0.4397557", "0.4392939", "0.43891734", "0.43878734", "0.43831837", "0.43799448", "0.43790495", "0.43778357", "0.43754318", "0.43751886", "0.43719316", "0.4370803", "0.43702236", "0.43679038", "0.43650872", "0.43553826", "0.43534425", "0.43468896", "0.4345937", "0.43396735", "0.4335065", "0.43304467", "0.43183446", "0.4317904", "0.43145603", "0.43126962", "0.4303634", "0.42968848", "0.42931193", "0.42904273", "0.42892358", "0.42825574", "0.42698145" ]
0.74947786
0
StartedEating updates philosopher specific data when the philosopher starts eating.
func (pd *philosopherData) StartedEating() { pd.eating = true pd.dinnersSpent++ }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pb *PhilosopherBase) StartEating() {\n\tpb.WriteString(\"starts eating\")\n\tpb.DelaySend(pb.EatRange, NewState{NewState: philstate.Thinking})\n}", "func (pb *PhilosopherBase) Eat() {\n\n\tpb.State = philstate.Eating\n\tpb.StartEating()\n}", "func (pd *philosopherData) FinishedEating() {\n\tpd.eating = false\n\tpd.leftChopstick = -1\n\tpd.rightChopstick = -1\n\tpd.finishedAt = time.Now()\n}", "func (pb *PhilosopherBase) IsEating() bool {\n\treturn pb.State == philstate.Eating\n}", "func (philosopher *Philosopher) Eat(wg *sync.WaitGroup, host Host) {\n\tfor i := 0; i < 3; i++ {\n\t\thost.GiveMePermission()\n\t\tphilosopher.leftChopstick.Lock()\n\t\tphilosopher.rightChopstick.Lock()\n\t\tfmt.Printf(\"Starting to eat %d\\n\", philosopher.id)\n\t\ttime.Sleep(500 * time.Millisecond)\n\t\tfmt.Printf(\"Finishing eating %d. (time: %d)\\n\", philosopher.id, i+1)\n\t\tphilosopher.rightChopstick.Unlock()\n\t\tphilosopher.leftChopstick.Unlock()\n\t\thost.Done()\n\t}\n\twg.Done()\n}", "func (p philosopher) eat() {\n\tfor j := 0; j < numberOfCourses; j++ {\n\t\t//Pick up sticks means lock both mutex\n\t\tp.leftChopstick.Lock()\n\t\tp.rightChopstick.Lock()\n\t\t// Acknowledge the start\n\t\t//starting to eat <number>\n\t\tfmt.Printf(\"Starting to eat %d(%s) [%s] \\n\", p.id+1, nameOfPhilosophers[p.id], courses[j])\n\t\ttime.Sleep(time.Second)\n\t\t//Release mutex\n\t\tp.rightChopstick.Unlock()\n\t\tp.leftChopstick.Unlock()\n\t\t// Acknowledge the finish\n\t\t//finishing eating <number>\n\t\tfmt.Printf(\"finishing eating %d(%s) [%s] \\n\", p.id+1, nameOfPhilosophers[p.id], courses[j])\n\t\ttime.Sleep(time.Second)\n\t}\n\teatWaitingGroup.Done()\n}", "func philosopherPonderanceGoroutine(id int) {\n\tfor {\n\t\tif rand.Float64() < PHILSWITCHCHANCE {\n\t\t\tphilIn[id] <- 2\n\t\t\tisEating := <- philOut[id] == 1\n\t\t\t// Switch: Thinking <-> Eating.\n\t\t\tif isEating {\n\t\t\t\t// Drop forks and return to positing on the nature of the universe.\n\t\t\t\tphilIn[id] <- 1\n\t\t\t} else {\n\t\t\t\t// Attempt to begin eating. Return to postulating, if missing fork.\n\t\t\t\tphilIn[id] <- 0\n\t\t\t}\n\t\t\t<- philOut[id]\n\t\t}\n\t}\n}", "func (pb *PhilosopherBase) CheckEating() {\n\t// Check the primary invariant - neither neighbor should be eating, and I should hold\n\t// both forks\n\tAssert(\n\t\tfunc() bool {\n\t\t\treturn pb.LeftPhilosopher().GetState() != philstate.Eating &&\n\t\t\t\tpb.RightPhilosopher().GetState() != philstate.Eating\n\t\t},\n\t\t\"eat while a neighbor is eating\",\n\t)\n\n\tAssert(\n\t\tfunc() bool {\n\t\t\treturn pb.LeftFork().IsHeldBy(pb.ID) &&\n\t\t\t\tpb.RightFork().IsHeldBy(pb.ID)\n\t\t},\n\t\t\"eat without holding forks\",\n\t)\n}", "func (pb *PhilosopherBase) StartThinking() {\n\tpb.WriteString(\"starts thinking\")\n\tpb.DelaySend(pb.ThinkRange, NewState{NewState: philstate.Hungry})\n}", "func (h *CookiejarHandler) eat(ctx *processor.Context, amount int, fromKey string) error {\n\t// Get the composite address for the sender's public key\n\taddress := h.getAddress(fromKey)\n\tlogger.Debugf(\"Got the key %s and cookiejar address %s\", fromKey, address)\n\n\t// Get the current state\n\tstate, err := ctx.GetState([]string{address})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Get the current state for the address\n\tc, ok := state[address]\n\tif !ok {\n\t\t// The address doesn't exist, so we'll return with an error\n\t\tlogger.Errorf(\"No cookie jar with the key %s\", address)\n\t\treturn &processor.InternalError{Msg: \"Invalid cookie jar\"}\n\t}\n\n\tcookies, _ := strconv.Atoi(string(c)) // convert to int\n\tif cookies < amount {\n\t\t// Not enough of cookies, return an error\n\t\tlogger.Error(\"Not enough of cookies in the jar\")\n\t\treturn &processor.InvalidTransactionError{Msg: \"Not enough of cookies in the jar\"}\n\t}\n\n\t// Update the state to current amount of cookies - amount\n\tstate[address] = []byte(strconv.Itoa(cookies - amount))\n\n\t// Store the new state\n\taddresses, err := ctx.SetState(state)\n\tif err != nil {\n\t\treturn &processor.InternalError{Msg: fmt.Sprintf(\"Couldn't update state: %v\", err)}\n\t}\n\n\t// Check whether addresses is empty\n\tif len(addresses) == 0 {\n\t\treturn &processor.InternalError{Msg: \"No addresses in set response\"}\n\t}\n\n\t// Launch an event\n\tif err := ctx.AddEvent(\n\t\t\"cookiejar/eat\",\n\t\t[]processor.Attribute{processor.Attribute{\"cookies-ate\", strconv.Itoa(amount)}},\n\t\tnil,\n\t); err != nil {\n\t\treturn &processor.InternalError{Msg: fmt.Sprintf(\"Couldn't publish event: %v\", err)}\n\t}\n\n\treturn nil\n}", "func (p philosopher) eat() {\r\n\tdefer eatWgroup.Done()\r\n\tfor j := 0; j < 3; j++ {\r\n\t\tp.leftFork.Lock()\r\n\t\tp.rightFork.Lock()\r\n\r\n\t\tsay(\"eating\", p.id)\r\n\t\ttime.Sleep(time.Second)\r\n\r\n\t\tp.rightFork.Unlock()\r\n\t\tp.leftFork.Unlock()\r\n\r\n\t\tsay(\"finished eating\", p.id)\r\n\t\ttime.Sleep(time.Second)\r\n\t}\r\n\r\n}", "func (l *store) hakeeperTick() {\n\tisLeader, _, err := l.isLeaderHAKeeper()\n\tif err != nil {\n\t\tl.runtime.Logger().Error(\"failed to get HAKeeper Leader ID\", zap.Error(err))\n\t\treturn\n\t}\n\n\tif isLeader {\n\t\tcmd := hakeeper.GetTickCmd()\n\t\tctx, cancel := context.WithTimeout(context.Background(), hakeeperDefaultTimeout)\n\t\tdefer cancel()\n\t\tsession := l.nh.GetNoOPSession(hakeeper.DefaultHAKeeperShardID)\n\t\tif _, err := l.propose(ctx, session, cmd); err != nil {\n\t\t\tl.runtime.Logger().Error(\"propose tick failed\", zap.Error(err))\n\t\t\treturn\n\t\t}\n\t}\n}", "func (host *DinnerHost) Listen() {\n\tname := \"\"\n\tfor {\n\t\tselect {\n\t\tcase name = <-host.requestChannel:\n\t\t\tfmt.Println(name + \" WOULD LIKE TO EAT.\")\n\n\t\t\tresponse := host.AllowEating(name)\n\t\t\tkickOut := false\n\t\t\tswitch response {\n\t\t\tcase \"OK\":\n\t\t\t\tfmt.Println(name + \" STARTS EATING.\")\n\t\t\tcase \"E:CHOPSTICKS\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: REQUIRED CHOPSTICKS ARE NOT AVAILABLE.\")\n\t\t\tcase \"E:FULL\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: TWO OTHER PHILOSOPHERS ARE ALREADY EATING.\")\n\t\t\tcase \"E:JUSTFINISHED\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: JUST FINISHED THE PREVIOUS MEAL.\")\n\t\t\tcase \"E:EATING\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: ALREADY EATING.\")\n\t\t\tcase \"E:LIMIT\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: ALREADY HAD THREE DINNERS; MUST LEAVE.\")\n\t\t\t\thost.freeSeats = append(host.freeSeats, host.phiData[name].Seat())\n\t\t\t\tkickOut = true\n\t\t\t}\n\t\t\tfmt.Println()\n\n\t\t\thost.phiData[name].RespChannel() <- response\n\n\t\t\tif kickOut {\n\t\t\t\tdelete(host.phiData, name)\n\t\t\t}\n\t\tcase name = <-host.finishChannel:\n\t\t\thost.SomeoneFinished(name)\n\t\t}\n\t\thost.PrintReport(false)\n\t}\n}", "func (pd *philosopherData) Init(respChannel chan string) {\n\tpd.respChannel = respChannel\n\tpd.eating = false\n\tpd.dinnersSpent = 0\n\tpd.seat = -1\n\tpd.leftChopstick = -1\n\tpd.rightChopstick = -1\n}", "func (s *BaseConcertoListener) EnterEos(ctx *EosContext) {}", "func (pb *PhilosopherBase) Start() {\n\tpb.State = philstate.Thinking\n\tpb.StartThinking()\n}", "func (host *DinnerHost) AllowEating(name string) string {\n\tif host.currentlyEating >= host.maxParallel {\n\t\treturn \"E:FULL\"\n\t}\n\n\tdata := host.phiData[name]\n\n\tcanEat := data.CanEat(host.maxDinner)\n\tif canEat != \"OK\" {\n\t\treturn canEat\n\t}\n\n\tseatNumber := data.Seat()\n\tleftChop := seatNumber\n\trightChop := (seatNumber + 1) % host.tableCount\n\n\tif host.chopsticksFree[leftChop] {\n\t\thost.chopsticksFree[leftChop] = false\n\t\tdata.SetLeftChop(leftChop)\n\t}\n\tif host.chopsticksFree[rightChop] {\n\t\thost.chopsticksFree[rightChop] = false\n\t\tdata.SetRightChop(rightChop)\n\t}\n\n\tif !data.HasBothChopsticks() {\n\t\treturn \"E:CHOPSTICKS\"\n\t}\n\n\thost.currentlyEating++\n\tdata.StartedEating()\n\n\treturn \"OK\"\n}", "func (s *BaseCobol85PreprocessorListener) EnterFamilyPhrase(ctx *FamilyPhraseContext) {}", "func (p Philosopher) dine(wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\tp.leftFork.Lock()\n\tp.rightFork.Lock()\n\n\tfmt.Println(p.id, \" is eating\")\n\t//used pause values to minimise.\n\ttime.Sleep(2 * time.Second)\n\tp.rightFork.Unlock()\n\tp.leftFork.Unlock()\n\n}", "func SetHeartbeating(flag bool) {\n\tif ticker == nil {\n\t\tsetTicker()\n\t}\n\n\tif isGossip == flag {\n\t\tif isGossip {\n\t\t\tWarn.Println(\"You are already running Gossip\")\n\t\t} else {\n\t\t\tWarn.Println(\"You are already running All to All\")\n\t\t}\n\t\treturn\n\t}\n\n\tisGossip = flag\n\tinterval := time.Millisecond\n\tif isGossip {\n\t\tInfo.Println(\"Running Gossip at T =\", Configuration.Settings.gossipInterval)\n\t\tinterval = time.Duration(Configuration.Settings.gossipInterval) * 1000 * interval\n\t} else {\n\t\tInfo.Println(\"Running All-to-All at T =\", Configuration.Settings.allInterval)\n\t\tinterval = time.Duration(Configuration.Settings.allInterval) * 1000 * interval\n\t}\n\n\tticker.Reset(interval)\n}", "func (s *BaseLittleDuckListener) EnterEstatuto(ctx *EstatutoContext) {}", "func (s *BaseAspidaListener) EnterTPoints(ctx *TPointsContext) {}", "func (host *DinnerHost) Init(tableCount, maxParallel, maxDinner int) {\n\thost.phiData = make(map[string]*philosopherData)\n\thost.requestChannel = make(chan string)\n\thost.finishChannel = make(chan string)\n\thost.maxParallel = maxParallel\n\tif host.maxParallel > tableCount {\n\t\thost.maxParallel = tableCount\n\t}\n\thost.maxDinner = maxDinner\n\thost.currentlyEating = 0\n\thost.tableCount = tableCount\n\thost.chopsticksFree = make([]bool, 5)\n\tfor i := range host.chopsticksFree {\n\t\thost.chopsticksFree[i] = true\n\t}\n\trand.Seed(time.Now().Unix())\n\thost.freeSeats = rand.Perm(tableCount)\n}", "func (philo philO) eat(maxeat chan string) {\n\tfor x := 0; x < 3; x++ {\n\t\tmaxeat <- philo.id\n\t\tphilo.meals++\n\t\tphilo.first.Lock()\n\t\tphilo.second.Lock()\n\t\tfmt.Printf(\"Philosopher #%s is eating a meal of rice\\n\", philo.id)\n\t\tphilo.first.Unlock()\n\t\tphilo.second.Unlock()\n\t\tfmt.Printf(\"Philosopher #%s is done eating a meal of rice\\n\", philo.id)\n\t\t<-maxeat\n\t\tif philo.meals == 3 {\n\t\t\tfmt.Printf(\"Philosopher #%s is finished eating!!!!!!\\n\", philo.id)\n\t\t}\n\t}\n}", "func (s *Basememcached_protocolListener) EnterTime(ctx *TimeContext) {}", "func (s *BasecluListener) EnterEquate(ctx *EquateContext) {}", "func (self *Event) updateEventParticipantFromAmiandoParticipant(logger *log.Logger, person *Person, eventParticipant *EventParticipant, amiandoParticipant *amiando.Participant) error {\n\teventParticipant.Event.Set(self)\n\teventParticipant.Person.Set(person)\n\n\tdate, err := amiandoToModelDateTime(amiandoParticipant.CreatedDate)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = eventParticipant.AppliedDate.Set(date)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Background\n\taBackgroundData := amiandoData[\"Background\"]\n\tfor i := 0; i < len(aBackgroundData); i++ {\n\t\tif background, ok := amiandoParticipant.FindUserData(aBackgroundData[i]); ok {\n\t\t\teventParticipant.Background.Set(background.String())\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Other Background\n\taOtherData := amiandoData[\"Other\"]\n\tfor i := 0; i < len(aOtherData); i++ {\n\t\tif bgother, ok := amiandoParticipant.FindUserData(aOtherData[i]); ok {\n\t\t\teventParticipant.Background2.Set(bgother.String())\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Pitching?\n\taIsPichtingData := amiandoData[\"IsPitching\"]\n\tfor i := 0; i < len(aIsPichtingData); i++ {\n\t\tif isPitching, ok := amiandoParticipant.FindUserData(aIsPichtingData[i]); ok {\n\t\t\tif isPitching.String() == \"yes\" || isPitching.String() == \"Yes\" {\n\t\t\t\teventParticipant.PresentsIdea = true\n\t\t\t\tlogger.Printf(\"Presents an idea\")\n\n\t\t\t\t// aTeamNameData := amiandoData[\"TeamName\"]\n\t\t\t\t// for j:=0; j < len(aTeamNameData); j++ {\n\t\t\t\t// \tif teamname, ok := amiandoParticipant.FindUserData(aTeamNameData[j]); ok {\n\t\t\t\t// \t\tteam, created := createTeamFromAmiando(amiandoParticipant)\n\n\t\t\t\t// \t\tif created {\n\t\t\t\t// \t\t\tperson.Team = team.Ref()\n\t\t\t\t// \t\t}\n\n\t\t\t\t// \t}\n\t\t\t\t// }\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Startup Name\n\taStartupNameData := amiandoData[\"StartupName\"]\n\tfor i := 0; i < len(aStartupNameData); i++ {\n\t\tif startupname, ok := amiandoParticipant.FindUserData(aStartupNameData[i]); ok {\n\t\t\teventParticipant.Startup.Name.Set(startupname.String())\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Startup Website\n\taStartupWebsiteData := amiandoData[\"StartupWebsite\"]\n\tfor i := 0; i < len(aStartupWebsiteData); i++ {\n\t\tif startupWebsite, ok := amiandoParticipant.FindUserData(aStartupWebsiteData[i]); ok {\n\t\t\teventParticipant.Startup.Website.Set(startupWebsite.String())\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Startup #Employee\n\taStartupEmployeeData := amiandoData[\"StartupNrEmployee\"]\n\tfor i := 0; i < len(aStartupEmployeeData); i++ {\n\t\tif startupNrEmployees, ok := amiandoParticipant.FindUserData(aStartupEmployeeData[i]); ok {\n\t\t\teventParticipant.Startup.NrEmployees.Set(startupNrEmployees.String())\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Startup Years active\n\taStartupYearsData := amiandoData[\"StartupYears\"]\n\tfor i := 0; i < len(aStartupYearsData); i++ {\n\t\tif startupYearsActive, ok := amiandoParticipant.FindUserData(aStartupYearsData[i]); ok {\n\t\t\teventParticipant.Startup.YearsActive.Set(startupYearsActive.String())\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Accommodation\n\taAccomodationData := amiandoData[\"Accommodation\"]\n\tfor i := 0; i < len(aAccomodationData); i++ {\n\t\taccommodation, ok := amiandoParticipant.FindUserData(aAccomodationData[i])\n\t\tif ok {\n\n\t\t\teventParticipant.Accommodation.Set(accommodation.String())\n\n\t\t\tbreak\n\t\t}\n\n\t}\n\n\t// Ticket Data\n\teventParticipant.Ticket.AmiandoTicketID.Set(amiandoParticipant.TicketID.String())\n\teventParticipant.Ticket.Type.Set(string(amiandoParticipant.TicketType))\n\teventParticipant.Ticket.InvoiceNumber.Set(amiandoParticipant.InvoiceNumber)\n\teventParticipant.Ticket.RegistrationNumber.Set(amiandoParticipant.RegistrationNumber)\n\tif amiandoParticipant.CheckedDate != \"\" {\n\t\tdate, err := amiandoToModelDateTime(amiandoParticipant.CheckedDate)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = eventParticipant.Ticket.CheckedDate.Set(date)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif amiandoParticipant.CancelledDate != \"\" {\n\t\tdate, err := amiandoToModelDateTime(amiandoParticipant.CancelledDate)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = eventParticipant.Ticket.CancelledDate.Set(date)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn eventParticipant.Save()\n}", "func (p *Participant) newSignedUpdate() {\n\t// Check that this function was not called by error.\n\tif p.engine.SiblingIndex() > state.QuorumSize {\n\t\tp.log.Error(\"error call on newSignedUpdate\")\n\t\treturn\n\t}\n\n\t// Generate the entropy for this round of random numbers.\n\tvar entropy state.Entropy\n\tcopy(entropy[:], siacrypto.RandomByteSlice(state.EntropyVolume))\n\n\tsp, err := p.engine.BuildStorageProof()\n\tif err == state.ErrEmptyQuorum {\n\t\tp.log.Debug(\"could not build storage proof:\", err)\n\t} else if err != nil {\n\t\tp.log.Error(sialog.AddCtx(err, \"failed to construct storage proof\"))\n\t\treturn\n\t}\n\thb := delta.Heartbeat{\n\t\tParentBlock: p.engine.Metadata().ParentBlock,\n\t\tEntropy: entropy,\n\t\tStorageProof: sp,\n\t}\n\n\tsignature, err := p.secretKey.SignObject(hb)\n\tif err != nil {\n\t\tp.log.Error(\"failed to sign heartbeat:\", err)\n\t\treturn\n\t}\n\n\t// Create the update with the heartbeat and heartbeat signature.\n\tp.engineLock.RLock()\n\tupdate := Update{\n\t\tHeight: p.engine.Metadata().Height,\n\t\tHeartbeat: hb,\n\t\tHeartbeatSignature: signature,\n\t}\n\tp.engineLock.RUnlock()\n\n\t// Attach all of the script inputs to the update, clearing the list of\n\t// script inputs in the process.\n\tp.updatesLock.Lock()\n\tupdate.ScriptInputs = p.scriptInputs\n\tp.scriptInputs = nil\n\tp.updatesLock.Unlock()\n\n\t// Attach all of the update advancements to the signed heartbeat and sign\n\t// them.\n\tp.updatesLock.Lock()\n\tupdate.UpdateAdvancements = p.updateAdvancements\n\tp.updateAdvancements = nil\n\tfor _, ua := range update.UpdateAdvancements {\n\t\tuas, err := p.secretKey.SignObject(ua)\n\t\tif err != nil {\n\t\t\t// log an error\n\t\t\tcontinue\n\t\t}\n\t\tupdate.AdvancementSignatures = append(update.AdvancementSignatures, uas)\n\t}\n\tp.updatesLock.Unlock()\n\n\t// Sign the update and create a SignedUpdate object with ourselves as the\n\t// first signatory.\n\tupdateSignature, err := p.secretKey.SignObject(update)\n\tsu := SignedUpdate{\n\t\tUpdate: update,\n\t\tSignatories: make([]byte, 1),\n\t\tSignatures: make([]siacrypto.Signature, 1),\n\t}\n\tsu.Signatories[0] = p.engine.SiblingIndex()\n\tsu.Signatures[0] = updateSignature\n\n\t// Add the heartbeat to our own heartbeat map.\n\tupdateHash, err := siacrypto.HashObject(update)\n\tif err != nil {\n\t\tp.log.Error(\"failed to hash update:\", err)\n\t\treturn\n\t}\n\tp.updatesLock.Lock()\n\tp.updates[p.engine.SiblingIndex()][updateHash] = update\n\tp.updatesLock.Unlock()\n\n\t// Broadcast the SignedUpdate to the network.\n\tp.broadcast(network.Message{\n\t\tProc: \"Participant.HandleSignedUpdate\",\n\t\tArgs: su,\n\t})\n}", "func (s *BaseAspidaListener) EnterPoints(ctx *PointsContext) {}", "func startMutator(b *esbridge.Bridge) {\n\tif *role == \"2\" {\n\t\tgo func() {\n\t\t\tkey := shared.EntityKey{\n\t\t\t\tID: entityID,\n\t\t\t\tEntity: entityType,\n\t\t\t}\n\t\t\tfor {\n\t\t\t\texampleMutex.Lock()\n\t\t\t\texampleItem.ClosedDate = time.Now()\n\t\t\t\texampleMutex.Unlock()\n\t\t\t\tlogrus.Println(\"Mutated\", key.ID)\n\t\t\t\tlogrus.Println(\"NotifyAllOfChange(\", key.Hash(), \")\")\n\t\t\t\tb.NotifyAllOfChange(key)\n\t\t\t\ttime.Sleep(1000 * time.Millisecond)\n\t\t\t}\n\t\t}()\n\t}\n\n}", "func (_m *KenContext) SetEphemeral(v bool) {\n\t_m.Called(v)\n}", "func (es *EtcdService) startHeartBeating() {\n\tsafego.RunWithRestart(func() {\n\t\tfor {\n\t\t\tif es.closed {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif err := es.heartBeat(); err != nil {\n\t\t\t\tlogging.Errorf(\"Error heart beat to etcd: %v\", err)\n\t\t\t\t//delay after error\n\t\t\t\ttime.Sleep(10 * time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttime.Sleep(90 * time.Second)\n\t\t}\n\t})\n}", "func (s *BaseDiceListener) EnterStart(ctx *StartContext) {}", "func ProviderHeartbeat(ctx context.Context,\n\tprovider ServerProvider, opt *ProvideOptions,\n) {\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tif isDebug {\n\t\t\t\tfmt.Println(\"context done\")\n\t\t\t}\n\t\t\treturn\n\t\tdefault:\n\t\t\tif err := provider.Provide(opt); err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t}\n\t\tif isDebug {\n\t\t\tfmt.Println(\"provider heartbeat doing\")\n\t\t}\n\t\ttime.Sleep(opt.HeartbeatDuration)\n\t}\n}", "func (c *RaftCtx) runTickerEvents() {\n\ttickerElectionTimeout := time.NewTicker(electionTimeoutDuration())\n\ttickerHeartbeat := time.NewTicker(heartbeatInterval)\n\n\tfor {\n\t\tselect {\n\t\tcase <-tickerElectionTimeout.C:\n\t\t\t//TODO: Do something better here\n\t\t\t// Skip if not follower\n\t\t\tif c.state != StateFollower {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\theartbeatCount := atomic.LoadUint64(&c.heartbeat)\n\t\t\tif heartbeatCount == 0 {\n\t\t\t\tc.attemptLeadership()\n\t\t\t}\n\n\t\t\t// Reset to 0\n\t\t\tatomic.StoreUint64(&c.heartbeat, 0)\n\n\t\tcase <-tickerHeartbeat.C:\n\t\t\t// TODO: Avoid this somehow\n\t\t\tif c.state != StateLeader {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\trequest := AppendEntriesRequest{\n\t\t\t\tLeaderName: c.name,\n\t\t\t\tTerm: c.currentTerm,\n\t\t\t\tEntries: []Log{},\n\t\t\t}\n\n\t\t\tlog.Printf(\"Sending heartbeats\")\n\t\t\tfor name, node := range c.config.Nodes {\n\t\t\t\tif name != c.name {\n\t\t\t\t\t_, err := node.sendAppendEntries(request)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Printf(\"Error while sending append-entries to %v: %v\\n\", node, err)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n}", "func (phStats *passwordHasherStats) startAccumulating() {\n\tgo phStats.accumulateStats()\n}", "func (s *BasemumpsListener) EnterEof(ctx *EofContext) {}", "func (s *BaseRFC5424Listener) EnterTime(ctx *TimeContext) {}", "func (host *DinnerHost) SomeoneFinished(name string) {\n\tif host.currentlyEating > 0 {\n\t\thost.currentlyEating--\n\t}\n\thost.chopsticksFree[host.phiData[name].LeftChopstick()] = true\n\thost.chopsticksFree[host.phiData[name].RightChopstick()] = true\n\thost.phiData[name].FinishedEating()\n\tfmt.Println(name + \" FINISHED EATING.\")\n\tfmt.Println()\n}", "func (k *ListenerImpl) EnterStart(ctx *generated.StartContext) {\n\tk.Things = make(map[string]*model.Thing)\n\tfor _, defCtx := range ctx.GetThings() {\n\t\tname := defCtx.GetName().GetText()\n\t\tif _, hasItem := k.Things[name]; hasItem {\n\t\t\tlog.Fatalf(\"The thing name \\\"%s\\\" is already used\", name)\n\t\t}\n\n\t\tnewThing := model.Thing{Name: name}\n\t\tnewThing.Items = make(map[string]*model.DataItem)\n\t\tfor i, thingContentCtx := range defCtx.GetSensors() {\n\t\t\tnewDataItem := createNewDataItem(uint(i), thingContentCtx)\n\t\t\tif _, hasItem := newThing.Items[newDataItem.Name]; hasItem {\n\t\t\t\tlog.Fatalf(\"The item name \\\"%s\\\" is already used\", newDataItem.Name)\n\t\t\t}\n\n\t\t\tnewThing.Items[newDataItem.Name] = &newDataItem\n\t\t}\n\n\t\tk.Things[name] = &newThing\n\t}\n}", "func (le *LeaderElector) Alive(_ *interface{}, stillLeader *bool) error {\n\tif le.LeaderSID == le.ThisServer.SID {\n\t\t*stillLeader = true\n\t\treturn nil\n\t}\n\t*stillLeader = false\n\treturn nil\n}", "func (pace *pacemakerState) eventProgress() {\n\tpace.tProgress = time.After(pace.config.DeltaProgress)\n}", "func (r *Raft) leader() int {\n\t//fmt.Println(\"In leader(), I am: \", r.Myconfig.Id)\n\n\tr.sendAppendEntriesRPC() //send Heartbeats\n\t//waitTime := 4 //duration between two heartbeats\n\twaitTime := 1\n\twaitTime_secs := secs * time.Duration(waitTime)\n\t//fmt.Println(\"Heartbeat time out is\", waitTime)\n\n\twaitTimeAE := 5 //max time to wait for AE_Response\n\tHeartbeatTimer := r.StartTimer(HeartbeatTimeout, waitTime) //starts the timer and places timeout object on the channel\n\t//var AppendEntriesTimer *time.Timer\n\twaitStepDown := 7\n\tRetryTimer := r.StartTimer(RetryTimeOut, waitStepDown)\n\t//fmt.Println(\"I am\", r.Myconfig.Id, \"timer created\", AppendEntriesTimer)\n\tresponseCount := 0\n\tfor {\n\n\t\treq := r.receive() //wait for client append req,extract the msg received on self eventCh\n\t\tswitch req.(type) {\n\t\tcase ClientAppendReq:\n\t\t\t//reset the heartbeat timer, now this sendRPC will maintain the authority of the leader\n\t\t\tHeartbeatTimer.Reset(waitTime_secs)\n\t\t\trequest := req.(ClientAppendReq)\n\t\t\tdata := request.data\n\t\t\t//fmt.Println(\"Received CA request,cmd is: \", string(data))\n\t\t\t//No check for semantics of cmd before appending to log?\n\t\t\tr.AppendToLog_Leader(data) //append to self log as byte array\n\t\t\tr.sendAppendEntriesRPC()\n\t\t\tresponseCount = 0 //for RetryTimer\n\t\t\t//AppendEntriesTimer = r.StartTimer(AppendEntriesTimeOut, waitTimeAE) //Can be written in HeartBeatTimer too\n\t\t\t//fmt.Println(\"I am\", r.Myconfig.Id, \"Timer assigned a value\", AppendEntriesTimer)\n\t\tcase AppendEntriesResponse:\n\t\t\tresponse := req.(AppendEntriesResponse)\n\t\t\t//fmt.Println(\"got AE_Response! from : \", response.followerId, response)\n\t\t\tresponseCount += 1\n\t\t\tif responseCount >= majority {\n\t\t\t\twaitTime_retry := secs * time.Duration(waitStepDown)\n\t\t\t\tRetryTimer.Reset(waitTime_retry)\n\t\t\t}\n\t\t\t//when isHeartBeat is true then success is also true according to the code in serviceAEReq so case wont be there when isHB is true and success is false\n\t\t\t// isHB true means it is a succeeded heartbeat hence no work to do if it is AE req then only proceed else do nothing and continue\n\t\t\t//So when follower's log is stale or he is more latest, it would set isHB false\n\t\t\tif !response.isHeartBeat {\n\t\t\t\tretVal := r.serviceAppendEntriesResp(response, HeartbeatTimer, waitTimeAE, waitTime)\n\t\t\t\tif retVal == follower {\n\t\t\t\t\treturn follower\n\t\t\t\t}\n\n\t\t\t}\n\n\t\tcase AppendEntriesReq: // in case some other leader is also in function, it must fall back or remain leader\n\t\t\trequest := req.(AppendEntriesReq)\n\t\t\tif request.term > r.currentTerm {\n\t\t\t\t//fmt.Println(\"In leader,AE_Req case, I am \", r.Myconfig.Id, \"becoming follower now, because request.term, r.currentTerm\", request.term, r.currentTerm)\n\t\t\t\tr.currentTerm = request.term //update self term and step down\n\t\t\t\tr.votedFor = -1 //since term has increased so votedFor must be reset to reflect for this term\n\t\t\t\tr.WriteCVToDisk()\n\t\t\t\treturn follower //sender server is the latest leader, become follower\n\t\t\t} else {\n\t\t\t\t//reject the request sending false\n\t\t\t\treply := AppendEntriesResponse{r.currentTerm, false, r.Myconfig.Id, false, r.myMetaData.lastLogIndex}\n\t\t\t\tsend(request.leaderId, reply)\n\t\t\t}\n\n\t\tcase int: //Time out-time to send Heartbeats!\n\t\t\ttimeout := req.(int)\n\t\t\tif timeout == RetryTimeOut {\n\t\t\t\tRetryTimer.Stop()\n\t\t\t\treturn follower\n\t\t\t}\n\t\t\t//fmt.Println(\"Timeout of\", r.Myconfig.Id, \"is of type:\", timeout)\n\n\t\t\t//waitTime_secs := secs * time.Duration(waitTime)\n\t\t\tif timeout == HeartbeatTimeout {\n\t\t\t\t//fmt.Println(\"Leader:Reseting HB timer\")\n\t\t\t\tHeartbeatTimer.Reset(waitTime_secs)\n\t\t\t\tresponseCount = 0 //since new heartbeat is now being sent\n\t\t\t\t//it depends on nextIndex which is correctly read in prepAE_Req method,\n\t\t\t\t//since it was AE other than HB(last entry), it would have already modified the nextIndex map\n\t\t\t\tr.sendAppendEntriesRPC() //This either sends Heartbeats or retries the failed AE due to which the timeout happened,\n\t\t\t\t//HeartbeatTimer.Reset(secs * time.Duration(8)) //for checking leader change, setting timer of f4 to 8s--DOESN'T work..-_CHECK\n\t\t\t}\n\n\t\t}\n\t}\n}", "func (s *ExternalAgentRunningState) Exited() error {\n\ts.agent.setStateUnsafe(s.agent.ExitedState)\n\treturn nil\n}", "func (s *Basememcached_protocolListener) EnterExptime(ctx *ExptimeContext) {}", "func (e *Engine) setHAState(state spb.HaState) error {\n\tselect {\n\tcase e.haManager.stateChan <- state:\n\tdefault:\n\t\treturn fmt.Errorf(\"state channel if full\")\n\t}\n\treturn nil\n}", "func (e *ElkTimeseriesForwarder) start() {\n\n\tlog.L.Infof(\"Starting event forwarder for %v\", e.index())\n\tticker := time.NewTicker(e.interval)\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\t//send it off\n\t\t\tlog.L.Debugf(\"Sending bulk ELK update for %v\", e.index())\n\n\t\t\tgo forward(e.index(), e.url, e.buffer)\n\t\t\te.buffer = []ElkBulkUpdateItem{}\n\n\t\tcase event := <-e.incomingChannel:\n\t\t\te.bufferevent(event)\n\t\t}\n\t}\n}", "func (s *BasetelephoneListener) EnterVariation(ctx *VariationContext) {}", "func (s *BasesiciListener) EnterLocation(ctx *LocationContext) {}", "func (s *BaseAspidaListener) EnterElifStat(ctx *ElifStatContext) {}", "func (s *BasejossListener) EnterFactor(ctx *FactorContext) {}", "func (s *BasecluListener) EnterWhere_(ctx *Where_Context) {}", "func (e *EngineClient) HAState(state spb.HaState) error {\n\tengineConn, err := net.DialTimeout(\"unix\", e.Socket, engineTimeout)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"HAState: Dial failed: %v\", err)\n\t}\n\tengineConn.SetDeadline(time.Now().Add(engineTimeout))\n\tengine := rpc.NewClient(engineConn)\n\tdefer engine.Close()\n\n\tvar reply int\n\tctx := ipc.NewTrustedContext(seesaw.SCHA)\n\tif err := engine.Call(\"SeesawEngine.HAState\", &ipc.HAState{ctx, state}, &reply); err != nil {\n\t\treturn fmt.Errorf(\"HAState: SeesawEngine.HAState failed: %v\", err)\n\t}\n\treturn nil\n}", "func (mem *Member) Tick() {\n\tif ticker == nil {\n\t\tsetTicker()\n\t}\n\n\tif enabledHeart {\n\t\tWarn.Println(\"Heartbeating has already started.\")\n\t\treturn\n\t}\n\n\tmemMetrics.StartMonitor()\n\tenabledHeart = true\n\tfor {\n\t\t// Listen channel to disable heartbeating\n\t\tselect {\n\t\tcase <-disableHeart:\n\t\t\tenabledHeart = false\n\t\t\tWarn.Println(\"Stopped heartbeating.\")\n\t\t\treturn\n\t\tcase _ = <-ticker.C:\n\t\t\t// Increment heartbeat counter of self\n\t\t\tentry := mem.membershipList[mem.memberID]\n\t\t\tentry.HeartbeatCount += 1\n\t\t\tentry.Timestamp = time.Now()\n\t\t\tmem.membershipList[mem.memberID] = entry\n\t\t\t// Gossip or AllToAll\n\t\t\tif isGossip {\n\t\t\t\tfor i := 0.0; i < Configuration.Settings.numProcessesToGossip; i++ {\n\t\t\t\t\tmem.Gossip()\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tmem.AllToAll()\n\t\t\t}\n\t\t}\n\t}\n}", "func Eat(a Apple) {\n\tif a.Eaten != true {\n\t\ta.Eaten = true\n\t}\n\tfmt.Println(\"Already eaten\")\n}", "func (e *Engine) manager() {\n\tfor {\n\t\t// process ha state updates first before processing others\n\t\tselect {\n\t\tcase state := <-e.haManager.stateChan:\n\t\t\tlog.Infof(\"Received HA state notification %v\", state)\n\t\t\te.haManager.setState(state)\n\t\t\tcontinue\n\t\tcase status := <-e.haManager.statusChan:\n\t\t\tlog.V(1).Infof(\"Received HA status notification (%v)\", status.State)\n\t\t\te.haManager.setStatus(status)\n\t\t\tcontinue\n\t\tdefault:\n\t\t}\n\t\tselect {\n\t\tcase state := <-e.haManager.stateChan:\n\t\t\tlog.Infof(\"Received HA state notification %v\", state)\n\t\t\te.haManager.setState(state)\n\n\t\tcase status := <-e.haManager.statusChan:\n\t\t\tlog.V(1).Infof(\"Received HA status notification (%v)\", status.State)\n\t\t\te.haManager.setStatus(status)\n\n\t\tcase n := <-e.notifier.C:\n\t\t\tlog.Infof(\"Received cluster config notification; %v\", &n)\n\t\t\te.syncServer.notify(&SyncNote{Type: SNTConfigUpdate, Time: time.Now()})\n\n\t\t\tvua, err := newVserverUserAccess(n.Cluster)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Ignoring notification due to invalid vserver access configuration: %v\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\te.clusterLock.Lock()\n\t\t\te.cluster = n.Cluster\n\t\t\te.clusterLock.Unlock()\n\n\t\t\te.vserverAccess.update(vua)\n\n\t\t\tif n.MetadataOnly {\n\t\t\t\tlog.Infof(\"Only metadata changes found, processing complete.\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif ha, err := e.haConfig(); err != nil {\n\t\t\t\tlog.Errorf(\"Manager failed to determine haConfig: %v\", err)\n\t\t\t} else if ha.Enabled {\n\t\t\t\te.haManager.enable()\n\t\t\t} else {\n\t\t\t\te.haManager.disable()\n\t\t\t}\n\n\t\t\tnode, err := e.thisNode()\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Manager failed to identify local node: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !node.VserversEnabled {\n\t\t\t\te.shutdownVservers()\n\t\t\t\te.deleteVLANs()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Process new cluster configuration.\n\t\t\te.updateVLANs()\n\n\t\t\t// TODO(jsing): Ensure this does not block.\n\t\t\te.updateVservers()\n\n\t\t\te.updateARPMap()\n\n\t\tcase <-e.haManager.timer():\n\t\t\tlog.Infof(\"Timed out waiting for HAState\")\n\t\t\te.haManager.setState(spb.HaState_UNKNOWN)\n\n\t\tcase svs := <-e.vserverChan:\n\t\t\tif _, ok := e.vservers[svs.Name]; !ok {\n\t\t\t\tlog.Infof(\"Received vserver snapshot for unconfigured vserver %s, ignoring\", svs.Name)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlog.V(1).Infof(\"Updating vserver snapshot for %s\", svs.Name)\n\t\t\te.vserverLock.Lock()\n\t\t\te.vserverSnapshots[svs.Name] = svs\n\t\t\te.vserverLock.Unlock()\n\n\t\tcase override := <-e.overrideChan:\n\t\t\tsn := &SyncNote{Type: SNTOverride, Time: time.Now()}\n\t\t\tswitch o := override.(type) {\n\t\t\tcase *seesaw.BackendOverride:\n\t\t\t\tsn.BackendOverride = o\n\t\t\tcase *seesaw.DestinationOverride:\n\t\t\t\tsn.DestinationOverride = o\n\t\t\tcase *seesaw.VserverOverride:\n\t\t\t\tsn.VserverOverride = o\n\t\t\t}\n\t\t\te.syncServer.notify(sn)\n\t\t\te.handleOverride(override)\n\n\t\tcase <-e.shutdown:\n\t\t\tlog.Info(\"Shutting down engine...\")\n\n\t\t\t// Tell other components to shutdown and then wait for\n\t\t\t// them to do so.\n\t\t\te.shutdownIPC <- true\n\t\t\te.shutdownRPC <- true\n\t\t\t<-e.shutdownIPC\n\t\t\t<-e.shutdownRPC\n\n\t\t\te.syncClient.disable()\n\t\t\te.shutdownVservers()\n\t\t\te.hcManager.shutdown()\n\t\t\te.deleteVLANs()\n\t\t\te.ncc.Close()\n\n\t\t\tlog.Info(\"Shutdown complete\")\n\t\t\treturn\n\t\t}\n\t}\n}", "func (s *BaseCGListener) EnterHtab(ctx *HtabContext) {}", "func (r *Handler) Started(id uint64) {\n\tr.id = id\n\tlog.V(1).Info(\n\t\t\"event: started.\",\n\t\t\"id\",\n\t\tr.id)\n}", "func (g *GateKeeper) announce() error {\n\tm, err := json.Marshal(g.Meta)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Debug().Msg(\"Starting to announce API to etcd\")\n\t_, err = (*g.etcd).Set(context.Background(), \"/meta/gatekeeper\", string(m), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Info().Msg(\"Gatekeeper registered in etcd.\")\n\treturn nil\n}", "func (hs *HealthStatusInfo) NodeStarted() {\n\ths.lock()\n\tdefer hs.unLock()\n\ths.startTime = time.Now()\n\ths.NodeType = Configuration.NodeType\n}", "func (tt *TtTable) AgeEntries() {\n\tstartTime := time.Now()\n\tif tt.numberOfEntries > 0 {\n\t\tnumberOfGoroutines := uint64(32) // arbitrary - uses up to 32 threads\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(int(numberOfGoroutines))\n\t\tslice := tt.maxNumberOfEntries / numberOfGoroutines\n\t\tfor i := uint64(0); i < numberOfGoroutines; i++ {\n\t\t\tgo func(i uint64) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tstart := i * slice\n\t\t\t\tend := start + slice\n\t\t\t\tif i == numberOfGoroutines-1 {\n\t\t\t\t\tend = tt.maxNumberOfEntries\n\t\t\t\t}\n\t\t\t\tfor n := start; n < end; n++ {\n\t\t\t\t\tif tt.data[n].Key != 0 {\n\t\t\t\t\t\ttt.data[n].Age++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}(i)\n\t\t}\n\t\twg.Wait()\n\t}\n\telapsed := time.Since(startTime)\n\ttt.log.Debug(out.Sprintf(\"Aged %d entries of %d in %d ms\\n\", tt.numberOfEntries, len(tt.data), elapsed.Milliseconds()))\n}", "func (e *etcdCacheEntry) startWatching(c *EtcdConfig) {\n // no locking; this must only be called by another method that handles synchronization\n if !e.watching {\n if e.finalize == nil {\n e.finalize = make(chan struct{})\n }\n e.watching = true\n go e.watch(c)\n }\n}", "func (p *Init) ExitedAt() time.Time {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\treturn p.exited\n}", "func (h *Healthz) Alive() {\n\th.Lock()\n\th.alive = healthy\n\th.Unlock()\n\treturn\n}", "func (hb *heartbeat) Beat() error {\n\tctx, err := func() (ctx context.Context, err error) {\n\t\thb.lock.Lock()\n\t\tdefer hb.lock.Unlock()\n\t\tif hb.cancel != nil {\n\t\t\terr = ErrRunning\n\t\t} else {\n\t\t\tctx, hb.cancel = context.WithCancel(context.Background())\n\t\t}\n\t\treturn\n\t}()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\thb.lock.Lock()\n\t\tdefer hb.lock.Unlock()\n\t\thb.cancel()\n\t\thb.cancel = nil\n\t}()\n\n\t// get the value if we don't have it\n\tdeadline, _ := context.WithTimeout(ctx, hb.frequency)\n\thb.value, err = hb.get(deadline)\n\tif isEtcdErrorCode(err, etcd.ErrorCodeKeyNotFound) {\n\t\treturn ErrNotFound\n\t} else if err != nil {\n\t\treturn err\n\t}\n\n\t// set the ttl since the first tick is not immediate\n\terr = hb.set(deadline)\n\tif isEtcdErrorCode(err, etcd.ErrorCodeKeyNotFound) {\n\t\treturn ErrDeleted\n\t} else if err != nil {\n\t\treturn err\n\t}\n\n\t// set ttl on every timer tick\n\tticker := time.NewTicker(hb.frequency)\n\tfor {\n\t\tselect {\n\t\tcase tick := <-ticker.C:\n\t\t\tdeadline, _ := context.WithDeadline(ctx, tick.Add(hb.frequency))\n\t\t\terr := hb.set(deadline)\n\t\t\tif inClusterError(err, context.Canceled) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (s *Server) startEnterpriseLeader() {}", "func (tr *trooper) updateEnergy() {\n\tchange := false\n\n\t// teleport energy increases to max.\n\tif tr.teleportEnergy < tr.temax {\n\t\ttr.teleportEnergy++\n\t\tchange = true\n\t}\n\n\t// cloak energy is used until gone.\n\tif tr.cloaked {\n\t\tchange = true\n\t\ttr.cloakEnergy -= 4\n\t\tif tr.cloakEnergy <= 0 {\n\t\t\ttr.cloakEnergy = 0\n\t\t\ttr.cloak(false)\n\t\t}\n\t}\n\tif change {\n\t\ttr.energyChanged()\n\t}\n}", "func (p *Provider) Serve() {\n\tdefer close(p.stopDone)\n\tp.logger.Info(\"Running\")\n\tfor {\n\t\tselect {\n\t\tcase u := <-p.updatesChan:\n\t\t\tp.handleUpdate(u)\n\t\tcase r := <-p.internalRequestChan:\n\t\t\tswitch v := r.(type) {\n\t\t\tcase streamsRequest:\n\t\t\t\tp.handleStreamsRequest(v)\n\t\t\tcase streamRequest:\n\t\t\t\tp.handleStreamRequest(v)\n\t\t\tcase entityRequest:\n\t\t\t\tp.handleEntityRequest(v)\n\t\t\t}\n\t\tcase <-p.stop:\n\t\t\tp.logger.Info(\"Stopping...\")\n\t\t\treturn\n\t\t}\n\t}\n}", "func (s *session) addParty(p *party) error {\n\tif s.login != p.login {\n\t\treturn trace.AccessDenied(\n\t\t\t\"can't switch users from %v to %v for session %v\",\n\t\t\ts.login, p.login, s.id)\n\t}\n\n\ts.parties[p.id] = p\n\t// write last chunk (so the newly joined parties won't stare\n\t// at a blank screen)\n\tgetRecentWrite := func() []byte {\n\t\ts.writer.Lock()\n\t\tdefer s.writer.Unlock()\n\t\tdata := make([]byte, 0, 1024)\n\t\tfor i := range s.writer.recentWrites {\n\t\t\tdata = append(data, s.writer.recentWrites[i]...)\n\t\t}\n\t\treturn data\n\t}\n\tp.Write(getRecentWrite())\n\n\t// register this party as one of the session writers\n\t// (output will go to it)\n\ts.writer.addWriter(string(p.id), p, true)\n\tp.ctx.AddCloser(p)\n\ts.term.AddParty(1)\n\n\t// update session on the session server\n\tstorageUpdate := func(db rsession.Service) {\n\t\tdbSession, err := db.GetSession(s.getNamespace(), s.id)\n\t\tif err != nil {\n\t\t\ts.log.Errorf(\"Unable to get session %v: %v\", s.id, err)\n\t\t\treturn\n\t\t}\n\t\tdbSession.Parties = append(dbSession.Parties, rsession.Party{\n\t\t\tID: p.id,\n\t\t\tUser: p.user,\n\t\t\tServerID: p.serverID,\n\t\t\tRemoteAddr: p.site,\n\t\t\tLastActive: p.getLastActive(),\n\t\t})\n\t\tdb.UpdateSession(rsession.UpdateRequest{\n\t\t\tID: dbSession.ID,\n\t\t\tParties: &dbSession.Parties,\n\t\t\tNamespace: s.getNamespace(),\n\t\t})\n\t}\n\tif s.registry.srv.GetSessionServer() != nil {\n\t\tgo storageUpdate(s.registry.srv.GetSessionServer())\n\t}\n\n\ts.log.Infof(\"New party %v joined session: %v\", p.String(), s.id)\n\n\t// this goroutine keeps pumping party's input into the session\n\tgo func() {\n\t\tdefer s.term.AddParty(-1)\n\t\t_, err := io.Copy(s.term.PTY(), p)\n\t\tif err != nil {\n\t\t\ts.log.Errorf(\"Party member %v left session %v due an error: %v\", p.id, s.id, err)\n\t\t}\n\t\ts.log.Infof(\"Party member %v left session %v.\", p.id, s.id)\n\t}()\n\treturn nil\n}", "func (a HTTPAPI) EPTHealth(c *gin.Context) {\n\tc.JSON(http.StatusOK, EPTHealthResp{\n\t\tOk: true,\n\t})\n}", "func (s *BasevhdlListener) EnterEntity_declarative_part(ctx *Entity_declarative_partContext) {}", "func (s *Shard) startHeartbeater(interval time.Duration, stop <-chan struct{}) (err error) {\n\tt := time.NewTicker(interval)\n\n\tfor {\n\t\tselect {\n\t\tcase <-t.C:\n\t\t\tif err = s.sendHeartbeat(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\tcase <-stop:\n\t\t\tt.Stop()\n\t\t\treturn\n\t\t}\n\t}\n}", "func (room *RoomRecorder) peoplePlayerEnter(msg synced.Msg) {\n\tif conn, recover, ok := room.peoplCheck(msg); ok {\n\t\troom.AddConnection(conn, true, recover)\n\t}\n}", "func (m *Atkinson) Update(p, ep float64) (float64, float64, float64) {\n\tvar a, q, g float64\n\tph, eph := p/24., ep/24.\n\tfor i := 0; i < 24; i++ {\n\t\ta1, q1, g1 := m.UpdateHourly(ph, eph)\n\t\ta += a1\n\t\tq += q1\n\t\tg += g1\n\t}\n\treturn a, q, g\n\t// return m.UpdateHourly(p, ep)\n}", "func (s *BasedifListener) EnterPair(ctx *PairContext) {}", "func (snake Snake) Eat() {\n\tfmt.Println(snake.food)\n}", "func (s *BaseLittleDuckListener) EnterAsignacion(ctx *AsignacionContext) {}", "func (s *BasePlSqlParserListener) EnterFor_update_of_part(ctx *For_update_of_partContext) {}", "func (s *BaseLittleDuckListener) EnterFactor(ctx *FactorContext) {}", "func (s *BasecookieListener) EnterAv_pairs(ctx *Av_pairsContext) {}", "func (s *BasedifListener) EnterData(ctx *DataContext) {}", "func (t *tracer) Entering() Tracer {\n\tif !t.IsNull() && !t.inDone {\n\t\tif t.sw != nil {\n\t\t\tt.sw.Start()\n\t\t}\n\t\tif t.enabled {\n\t\t\tt.inDone = true\n\t\t\tmsg := goingInPrefix + t.buildMessage()\n\t\t\tif msg != \"\" {\n\t\t\t\tlogrus.Tracef(msg)\n\t\t\t}\n\t\t}\n\t}\n\treturn t\n}", "func (_XStaking *XStakingCallerSession) Earned(account common.Address) (*big.Int, error) {\n\treturn _XStaking.Contract.Earned(&_XStaking.CallOpts, account)\n}", "func (l *Level) Evolve() {\n\t// Advance schedule until we find the player.\n\tfor {\n\t\tactor := l.scheduler.Next()\n\t\tactor.Ticker.Tick(l.scheduler.delay)\n\n\t\tif ai := actor.AI; ai != nil && actor.Sheet.CanAct() {\n\t\t\tai.Act()\n\t\t}\n\t\tif actor.IsPlayer() {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (_XStaking *XStakingSession) Earned(account common.Address) (*big.Int, error) {\n\treturn _XStaking.Contract.Earned(&_XStaking.CallOpts, account)\n}", "func (bird Bird) Eat() {\n\tfmt.Println(bird.food)\n}", "func (session *Session) Start(mesure *Mesure) {\n\tlog.Printf(\"start: session: %+v\\n\", session)\n\tfor {\n\t\tselect {\n\t\tcase msg := <-session.client.income:\n\t\t\tsession.server.outcome <- msg\n\t\t\tmesure.Process(msg)\n\t\tcase msg := <-session.server.income:\n\t\t\tsession.client.outcome <- msg\n\t\t\tmesure.Process(msg)\n\t\tcase <-session.done:\n\t\t\tsession.Close()\n\t\t\treturn\n\t\t}\n\t}\n}", "func (l *SpotListener) Start(ctx context.Context, notices chan<- TerminationNotice, log *logrus.Entry) error {\n\tif !l.metadata.Available() {\n\t\treturn errors.New(\"ec2 metadata is not available\")\n\t}\n\n\tticker := time.NewTicker(l.interval)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tcase <-ticker.C:\n\t\t\tlog.Debug(\"Polling ec2 metadata for spot termination notices\")\n\n\t\t\tout, err := l.metadata.GetMetadata(\"spot/termination-time\")\n\t\t\tif err != nil {\n\t\t\t\tif e, ok := err.(awserr.Error); ok && strings.Contains(e.OrigErr().Error(), \"404\") {\n\t\t\t\t\t// Metadata returns 404 when there is no termination notice available\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tlog.WithError(err).Warn(\"Failed to get spot termination\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif out == \"\" {\n\t\t\t\tlog.Error(\"Empty response from metadata\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tt, err := time.Parse(time.RFC3339, out)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithError(err).Error(\"Failed to parse termination time\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnotices <- &spotTerminationNotice{\n\t\t\t\tnoticeType: l.Type(),\n\t\t\t\tinstanceID: l.instanceID,\n\t\t\t\ttransition: \"ec2:SPOT_INSTANCE_TERMINATION\",\n\t\t\t\tterminationTime: t,\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (c *TimeAvgAggregator) Enter(e Event, w Window) {\n\tval := c.getValue(e.Value)\n\tif !c.initialized {\n\t\tc.startTime = e.Timestamp\n\t\tc.startValue = val\n\t\tc.initialized = true\n\t}\n\tc.endTime = e.Timestamp\n\tc.endValue = val\n}", "func (s *BaseAspidaListener) EnterHosts(ctx *HostsContext) {}", "func (e *Employee) SayHi() {\n\tfmt.Printf(\"Hi, I am %s, I work in %s. Call me on %s\\n\", e.name,\n\t\te.company, e.phone)\n}", "func (s *BaseGShellListener) EnterStart(ctx *StartContext) {}", "func (g *providerDaemon) Start(ctx context.Context) <-chan []error {\n\tech := make(chan []error)\n\tpch := g.athenz.Start(ctx)\n\tsch := g.server.ListenAndServe(ctx)\n\tgo func() {\n\t\temap := make(map[error]uint64, 1)\n\t\tdefer close(ech)\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\terrs := make([]error, 0, len(emap)+1)\n\t\t\t\tfor err, count := range emap {\n\t\t\t\t\terrs = append(errs, errors.WithMessagef(err, \"%d times appeared\", count))\n\t\t\t\t}\n\t\t\t\terrs = append(errs, ctx.Err())\n\t\t\t\tech <- errs\n\t\t\t\treturn\n\t\t\tcase e := <-pch:\n\t\t\t\tglg.Errorf(\"pch %v\", e)\n\t\t\t\tglg.Error(e)\n\t\t\t\tcause := errors.Cause(e)\n\t\t\t\t_, ok := emap[cause]\n\t\t\t\tif !ok {\n\t\t\t\t\temap[cause] = 0\n\t\t\t\t}\n\t\t\t\temap[cause]++\n\t\t\tcase errs := <-sch:\n\t\t\t\tglg.Errorf(\"sch %v\", errs)\n\t\t\t\tech <- errs\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn ech\n}", "func (rf *Raft) heartbeatAppendEntries() {\n\t// make server -> reply map\n\treplies := make([]*AppendEntriesReply, len(rf.peers))\n\tfor servIdx := range rf.peers {\n\t\treplies[servIdx] = &AppendEntriesReply{}\n\t}\n\n\tfor !rf.killed() {\n\t\trf.mu.Lock()\n\n\t\t// if we are no longer the leader\n\t\tif rf.state != Leader {\n\t\t\trf.Log(LogDebug, \"Discovered no longer the leader, stopping heartbeat\")\n\t\t\trf.mu.Unlock()\n\t\t\treturn\n\t\t}\n\t\t// send out heartbeats concurrently if leader\n\t\tfor servIdx := range rf.peers {\n\t\t\tif servIdx != rf.me {\n\n\t\t\t\t// successful request - update matchindex and nextindex accordingly\n\t\t\t\tif replies[servIdx].Success {\n\t\t\t\t\tif replies[servIdx].HighestLogIndexAdded > 0 {\n\t\t\t\t\t\trf.matchIndex[servIdx] = replies[servIdx].HighestLogIndexAdded\n\t\t\t\t\t}\n\t\t\t\t\trf.nextIndex[servIdx] = rf.matchIndex[servIdx] + 1\n\n\t\t\t\t\t// failed request - check for better term or decrease nextIndex\n\t\t\t\t} else if !replies[servIdx].Success && replies[servIdx].Returned {\n\n\t\t\t\t\t// we might have found out we shouldn't be the leader!\n\t\t\t\t\tif replies[servIdx].CurrentTerm > rf.currentTerm {\n\t\t\t\t\t\trf.Log(LogDebug, \"Detected server with higher term, stopping heartbeat and changing to follower.\")\n\t\t\t\t\t\trf.state = Follower\n\t\t\t\t\t\trf.currentTerm = replies[servIdx].CurrentTerm\n\n\t\t\t\t\t\t// persist - updated current term\n\t\t\t\t\t\tdata := rf.GetStateBytes(false)\n\t\t\t\t\t\trf.persister.SaveRaftState(data)\n\n\t\t\t\t\t\tgo rf.heartbeatTimeoutCheck()\n\t\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\t// failure - we need to decrease next index\n\t\t\t\t\t// 1. case where follower has no entry at the place we thought\n\t\t\t\t\t// => want to back up to start of follower log\n\t\t\t\t\t// 2. case where server has entry with different term NOT seen by leader\n\t\t\t\t\t// => want to back up nextIndex to the start of the 'run' of entries with that term (i.e. IndexFirstConflictingTerm)\n\t\t\t\t\t// 3. case where server has entry with different term that HAS been seen by leader\n\t\t\t\t\t// => want to back up to last entry leader has with that term\n\t\t\t\t\t//\n\t\t\t\t\t// Note for 2 and 3 ... if leader does not have the relevant log\n\t\t\t\t\t// entries, we need to call InstallSnapshot!\n\t\t\t\t\t//\n\t\t\t\t\trf.Log(LogInfo, \"Failed to AppendEntries to server\", servIdx, \"\\n - IndexFirstConflictingTerm\", replies[servIdx].IndexFirstConflictingTerm, \"\\n - ConflictingEntryTerm\", replies[servIdx].ConflictingEntryTerm, \"\\n - LastLogIndex\", replies[servIdx].LastLogIndex)\n\t\t\t\t\tif replies[servIdx].ConflictingEntryTerm == -1 {\n\t\t\t\t\t\t// case 1 - follower has no entry at the given location\n\t\t\t\t\t\trf.nextIndex[servIdx] = replies[servIdx].LastLogIndex + 1\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// if not case 1, need to check we have the logs at and beyond\n\t\t\t\t\t\t// IndexFirstConflictingTerm\n\t\t\t\t\t\traftLogIdx := rf.getTrimmedLogIndex(replies[servIdx].IndexFirstConflictingTerm)\n\t\t\t\t\t\tif raftLogIdx == -1 {\n\t\t\t\t\t\t\t// don't have the logs we need - will need to snapshot\n\t\t\t\t\t\t\t// set nextIndex to the lastIncludedIndex to force this\n\t\t\t\t\t\t\trf.nextIndex[servIdx] = rf.lastIncludedIndex\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif rf.log[raftLogIdx].Term != replies[servIdx].ConflictingEntryTerm {\n\t\t\t\t\t\t\t\t// case 2 - follower has a term not seen by leader\n\t\t\t\t\t\t\t\trf.Log(LogDebug, \"Case 2: follower has a term not seen by leader\")\n\t\t\t\t\t\t\t\trf.nextIndex[servIdx] = replies[servIdx].IndexFirstConflictingTerm\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// case 3 - follower has a term seen by leader\n\t\t\t\t\t\t\t\t// need to go to latest entry that leader has with this term\n\t\t\t\t\t\t\t\trf.Log(LogDebug, \"Case 3: follower has a term seen by leader, finding leader's latest entry with this term \\n - rf.log[\", rf.log)\n\t\t\t\t\t\t\t\trf.nextIndex[servIdx] = replies[servIdx].IndexFirstConflictingTerm\n\t\t\t\t\t\t\t\tfor rf.log[rf.getTrimmedLogIndex(rf.nextIndex[servIdx])].Term == replies[servIdx].ConflictingEntryTerm {\n\t\t\t\t\t\t\t\t\trf.nextIndex[servIdx]++\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// if we need to install a snapshot, then\n\t\t\t\t// nextIndex becomes the next index after the snapshot we will install\n\t\t\t\t// notice that we will then immediately send an AppendEntries request to the server,\n\t\t\t\t// and it will fail until the snapshot is installed, and we will just keep\n\t\t\t\t// resetting nextIndex\n\t\t\t\tif rf.nextIndex[servIdx] <= rf.lastIncludedIndex {\n\t\t\t\t\trf.Log(LogInfo, \"Failed to AppendEntries to server\", servIdx, \"- need to send InstallSnapshot!\")\n\t\t\t\t\trf.nextIndex[servIdx] = rf.lastIncludedIndex + 1\n\n\t\t\t\t\t// actually call the RPC\n\t\t\t\t\targs := &InstallSnapshotArgs{\n\t\t\t\t\t\tLeaderTerm: rf.currentTerm,\n\t\t\t\t\t\tSnapshot: rf.persister.ReadSnapshot(),\n\t\t\t\t\t}\n\t\t\t\t\treply := &InstallSnapshotReply{}\n\t\t\t\t\tgo rf.sendInstallSnapshot(servIdx, args, reply)\n\t\t\t\t}\n\n\t\t\t\t// send a new append entries request to the server if the last one has finished\n\t\t\t\trf.Log(LogDebug, \"rf.nextIndex for server\", servIdx, \"set to idx\", rf.nextIndex[servIdx], \"\\n - rf.log\", rf.log, \"\\n - rf.lastIncludedIndex\", rf.lastIncludedIndex, \"\\n - rf.lastIncludedTerm\", rf.lastIncludedTerm)\n\t\t\t\tentries := []LogEntry{}\n\t\t\t\tif len(rf.log) > 0 {\n\t\t\t\t\tentries = rf.log[rf.getTrimmedLogIndex(rf.nextIndex[servIdx]):]\n\t\t\t\t}\n\t\t\t\targs := &AppendEntriesArgs{\n\t\t\t\t\tLeaderTerm: rf.currentTerm,\n\t\t\t\t\tLeaderCommitIndex: rf.commitIndex,\n\t\t\t\t\tLogEntries: entries,\n\t\t\t\t}\n\n\t\t\t\t// only place the reply into replies, when the RPC completes,\n\t\t\t\t// to prevent partial data (unsure if this can happen but seems like a good idea)\n\t\t\t\tgo func(servIdx int) {\n\t\t\t\t\trf.Log(LogDebug, \"sendAppendEntries to servIdx\", servIdx)\n\t\t\t\t\treply := &AppendEntriesReply{}\n\t\t\t\t\tok := rf.sendAppendEntries(servIdx, args, reply)\n\t\t\t\t\tif ok {\n\t\t\t\t\t\trf.Log(LogDebug, \"Received AppendEntries reply from server\", servIdx, \"\\n - reply\", reply)\n\t\t\t\t\t\treplies[servIdx] = reply\n\t\t\t\t\t}\n\t\t\t\t}(servIdx)\n\t\t\t}\n\t\t}\n\n\t\t// walk up through possible new commit indices\n\t\t// update commit index\n\t\torigIndex := rf.commitIndex\n\t\tnewIdx := rf.commitIndex + 1\n\t\tfor len(rf.log) > 0 && newIdx <= rf.log[len(rf.log)-1].Index {\n\t\t\treplicas := 1 // already replicated in our log\n\t\t\tfor servIdx := range rf.peers {\n\t\t\t\tif servIdx != rf.me && rf.matchIndex[servIdx] >= newIdx {\n\t\t\t\t\treplicas++\n\t\t\t\t}\n\t\t\t}\n\t\t\tif replicas >= int(math.Ceil(float64(len(rf.peers))/2.0)) &&\n\t\t\t\tnewIdx > rf.lastIncludedIndex &&\n\t\t\t\trf.getTrimmedLogIndex(newIdx) >= 0 &&\n\t\t\t\trf.log[rf.getTrimmedLogIndex(newIdx)].Term == rf.currentTerm {\n\t\t\t\trf.commitIndex = newIdx\n\t\t\t\trf.Log(LogInfo, \"Entry \", rf.log[rf.getTrimmedLogIndex(rf.commitIndex)], \"replicated on a majority of servers. Commited to index\", rf.commitIndex)\n\t\t\t}\n\t\t\tnewIdx++\n\t\t}\n\n\t\t// send messages to applyCh for every message that was committed\n\t\tfor origIndex < rf.commitIndex {\n\t\t\torigIndex++\n\t\t\tif rf.getTrimmedLogIndex(origIndex) >= 0 {\n\t\t\t\trf.Log(LogInfo, \"Sending applyCh confirmation for commit of \", rf.log[rf.getTrimmedLogIndex(origIndex)], \"at index\", origIndex)\n\t\t\t\t{\n\t\t\t\t\trf.applyCh <- ApplyMsg{\n\t\t\t\t\t\tCommandValid: true,\n\t\t\t\t\t\tCommandIndex: origIndex,\n\t\t\t\t\t\tCommandTerm: rf.currentTerm,\n\t\t\t\t\t\tCommand: rf.log[rf.getTrimmedLogIndex(origIndex)].Command,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\trf.mu.Unlock()\n\t\ttime.Sleep(heartbeatSendInterval)\n\t}\n}", "func (s *BasePlSqlParserListener) EnterStart_standby_clause(ctx *Start_standby_clauseContext) {}", "func (h *Handler) OnSessionStarted(ctx context.Context, request *alexa.Request, session *alexa.Session, ctxPtr *alexa.Context, response *alexa.Response) error {\n\tlog.Printf(\"OnSessionStarted requestId=%s, sessionId=%s\", request.RequestID, session.SessionID)\n\treturn nil\n}", "func (t *Tortoise) OnHareOutput(lid types.LayerID, bid types.BlockID) {\n\tstart := time.Now()\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\twaitHareOutputDuration.Observe(float64(time.Since(start).Nanoseconds()))\n\tt.trtl.onHareOutput(lid, bid)\n\tif t.tracer != nil {\n\t\tt.tracer.On(&HareTrace{Layer: lid, Vote: bid})\n\t}\n}", "func (s *BaseConcertoListener) EnterStar(ctx *StarContext) {}", "func (c *EntityStats) OnAwake() {\n\t// Create new delegate \"entity-stats\"\n\tengosdl.Logger.Trace().Str(\"component\", \"entity-stats\").Str(\"entity-stats\", c.GetName()).Msg(\"OnAwake\")\n\tc.SetDelegate(engosdl.GetDelegateManager().CreateDelegate(c, \"on-entity-stats\"))\n\tc.Component.OnAwake()\n\n}", "func StartedAt(v time.Time) predicate.Session {\n\treturn predicate.Session(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldStartedAt), v))\n\t})\n}" ]
[ "0.6710584", "0.6607078", "0.60708874", "0.568095", "0.54228866", "0.5064942", "0.47981277", "0.4762116", "0.47001022", "0.46074983", "0.4593535", "0.45334417", "0.44835374", "0.44762683", "0.44677076", "0.44670615", "0.44586268", "0.43989903", "0.43988955", "0.43647748", "0.43629447", "0.4356445", "0.43345085", "0.43191946", "0.4313082", "0.4307137", "0.4306122", "0.42785025", "0.42349482", "0.42092818", "0.4206912", "0.42057413", "0.41890037", "0.418099", "0.41635126", "0.4149471", "0.41307828", "0.41301212", "0.41232288", "0.41191193", "0.41062984", "0.4090807", "0.4088873", "0.40856674", "0.40841576", "0.40338925", "0.403183", "0.40170544", "0.4013365", "0.40020138", "0.39832294", "0.39818174", "0.39807597", "0.39795288", "0.39746043", "0.39692017", "0.39684793", "0.3960996", "0.39293158", "0.39274815", "0.39266118", "0.3916009", "0.39151695", "0.39134914", "0.39129734", "0.39121056", "0.39045882", "0.39024842", "0.3895712", "0.38869056", "0.3885329", "0.3876082", "0.38737795", "0.38732743", "0.38720983", "0.386927", "0.3865706", "0.3863668", "0.38624123", "0.38597983", "0.38589168", "0.38553166", "0.3851821", "0.38497567", "0.38496318", "0.38481575", "0.38345703", "0.3831908", "0.38295233", "0.3828137", "0.3826269", "0.38210294", "0.38156003", "0.38136435", "0.3807285", "0.38069814", "0.3804341", "0.38035697", "0.3799032", "0.37975043" ]
0.77862406
0
FinishedEating updates philosopher specific data when the philosopher finished eating.
func (pd *philosopherData) FinishedEating() { pd.eating = false pd.leftChopstick = -1 pd.rightChopstick = -1 pd.finishedAt = time.Now() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (host *DinnerHost) SomeoneFinished(name string) {\n\tif host.currentlyEating > 0 {\n\t\thost.currentlyEating--\n\t}\n\thost.chopsticksFree[host.phiData[name].LeftChopstick()] = true\n\thost.chopsticksFree[host.phiData[name].RightChopstick()] = true\n\thost.phiData[name].FinishedEating()\n\tfmt.Println(name + \" FINISHED EATING.\")\n\tfmt.Println()\n}", "func (pd *philosopherData) StartedEating() {\n\tpd.eating = true\n\tpd.dinnersSpent++\n}", "func (pb *PhilosopherBase) Eat() {\n\n\tpb.State = philstate.Eating\n\tpb.StartEating()\n}", "func (pb *PhilosopherBase) IsEating() bool {\n\treturn pb.State == philstate.Eating\n}", "func (philosopher *Philosopher) Eat(wg *sync.WaitGroup, host Host) {\n\tfor i := 0; i < 3; i++ {\n\t\thost.GiveMePermission()\n\t\tphilosopher.leftChopstick.Lock()\n\t\tphilosopher.rightChopstick.Lock()\n\t\tfmt.Printf(\"Starting to eat %d\\n\", philosopher.id)\n\t\ttime.Sleep(500 * time.Millisecond)\n\t\tfmt.Printf(\"Finishing eating %d. (time: %d)\\n\", philosopher.id, i+1)\n\t\tphilosopher.rightChopstick.Unlock()\n\t\tphilosopher.leftChopstick.Unlock()\n\t\thost.Done()\n\t}\n\twg.Done()\n}", "func (p philosopher) eat() {\n\tfor j := 0; j < numberOfCourses; j++ {\n\t\t//Pick up sticks means lock both mutex\n\t\tp.leftChopstick.Lock()\n\t\tp.rightChopstick.Lock()\n\t\t// Acknowledge the start\n\t\t//starting to eat <number>\n\t\tfmt.Printf(\"Starting to eat %d(%s) [%s] \\n\", p.id+1, nameOfPhilosophers[p.id], courses[j])\n\t\ttime.Sleep(time.Second)\n\t\t//Release mutex\n\t\tp.rightChopstick.Unlock()\n\t\tp.leftChopstick.Unlock()\n\t\t// Acknowledge the finish\n\t\t//finishing eating <number>\n\t\tfmt.Printf(\"finishing eating %d(%s) [%s] \\n\", p.id+1, nameOfPhilosophers[p.id], courses[j])\n\t\ttime.Sleep(time.Second)\n\t}\n\teatWaitingGroup.Done()\n}", "func (g *game) dayDone() bool {\n\tplr, vts := g.countVotesFor(\"villager\")\n\tif vts <= g.alivePlayers()/2 && time.Since(g.StateTime) < StateTimeout {\n\t\treturn false\n\t}\n\n\tif vts == 0 {\n\t\tg.serverMessage(\"Villages didn't vote, nobody dies.\")\n\t\treturn true\n\t}\n\n\ttoBeKilled := plr[rand.Intn(len(plr))]\n\ttoBeKilled.Dead = true\n\tg.serverMessage(toBeKilled.Name + \" was lynched by an angry mob!\")\n\treturn true\n}", "func (eip *EventInProgress) Done() {\n\teip.doneFunc(eip.loggables) // create final event with extra data\n}", "func (philo philO) eat(maxeat chan string) {\n\tfor x := 0; x < 3; x++ {\n\t\tmaxeat <- philo.id\n\t\tphilo.meals++\n\t\tphilo.first.Lock()\n\t\tphilo.second.Lock()\n\t\tfmt.Printf(\"Philosopher #%s is eating a meal of rice\\n\", philo.id)\n\t\tphilo.first.Unlock()\n\t\tphilo.second.Unlock()\n\t\tfmt.Printf(\"Philosopher #%s is done eating a meal of rice\\n\", philo.id)\n\t\t<-maxeat\n\t\tif philo.meals == 3 {\n\t\t\tfmt.Printf(\"Philosopher #%s is finished eating!!!!!!\\n\", philo.id)\n\t\t}\n\t}\n}", "func philosopherPonderanceGoroutine(id int) {\n\tfor {\n\t\tif rand.Float64() < PHILSWITCHCHANCE {\n\t\t\tphilIn[id] <- 2\n\t\t\tisEating := <- philOut[id] == 1\n\t\t\t// Switch: Thinking <-> Eating.\n\t\t\tif isEating {\n\t\t\t\t// Drop forks and return to positing on the nature of the universe.\n\t\t\t\tphilIn[id] <- 1\n\t\t\t} else {\n\t\t\t\t// Attempt to begin eating. Return to postulating, if missing fork.\n\t\t\t\tphilIn[id] <- 0\n\t\t\t}\n\t\t\t<- philOut[id]\n\t\t}\n\t}\n}", "func (ph *Handler) Done() {\n\tselect {\n\tcase info, ok := <-ph.panicChan: // Handles the case where we somehow do this exactly when a panic is sent\n\t\tif ok {\n\t\t\tclose(ph.quit)\n\t\t\tclose(ph.panicChan)\n\t\t\tph.mu.Lock()\n\t\t\tdefer ph.mu.Unlock()\n\t\t\tph.handleForwardedPanic(info)\n\t\t}\n\tdefault: // Only executes if no panics were sent AND panicChan has yet to be closed\n\t\tclose(ph.panicChan)\n\t}\n}", "func (t *Tournament) End() {\n\tif !t.hasEnded() {\n\t\tn := t.generateWinnerNum()\n\n\t\tt.Winner = Winner{\n\t\t\tPlayer: t.Participants[n],\n\t\t\tPrize: t.Deposit,\n\t\t}\n\n\t\tt.Participants[n].Fund(t.Deposit)\n\t\tt.Balance = 0\n\t}\n}", "func (eb *ElectrumBackend) Finish() {\n\tclose(eb.doneCh)\n\teb.removeAllNodes()\n\t// TODO: we could gracefully disconnect from all the nodes. We currently don't, because the\n\t// program is going to terminate soon anyways.\n}", "func (host *DinnerHost) Listen() {\n\tname := \"\"\n\tfor {\n\t\tselect {\n\t\tcase name = <-host.requestChannel:\n\t\t\tfmt.Println(name + \" WOULD LIKE TO EAT.\")\n\n\t\t\tresponse := host.AllowEating(name)\n\t\t\tkickOut := false\n\t\t\tswitch response {\n\t\t\tcase \"OK\":\n\t\t\t\tfmt.Println(name + \" STARTS EATING.\")\n\t\t\tcase \"E:CHOPSTICKS\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: REQUIRED CHOPSTICKS ARE NOT AVAILABLE.\")\n\t\t\tcase \"E:FULL\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: TWO OTHER PHILOSOPHERS ARE ALREADY EATING.\")\n\t\t\tcase \"E:JUSTFINISHED\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: JUST FINISHED THE PREVIOUS MEAL.\")\n\t\t\tcase \"E:EATING\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: ALREADY EATING.\")\n\t\t\tcase \"E:LIMIT\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: ALREADY HAD THREE DINNERS; MUST LEAVE.\")\n\t\t\t\thost.freeSeats = append(host.freeSeats, host.phiData[name].Seat())\n\t\t\t\tkickOut = true\n\t\t\t}\n\t\t\tfmt.Println()\n\n\t\t\thost.phiData[name].RespChannel() <- response\n\n\t\t\tif kickOut {\n\t\t\t\tdelete(host.phiData, name)\n\t\t\t}\n\t\tcase name = <-host.finishChannel:\n\t\t\thost.SomeoneFinished(name)\n\t\t}\n\t\thost.PrintReport(false)\n\t}\n}", "func (pb *PhilosopherBase) CheckEating() {\n\t// Check the primary invariant - neither neighbor should be eating, and I should hold\n\t// both forks\n\tAssert(\n\t\tfunc() bool {\n\t\t\treturn pb.LeftPhilosopher().GetState() != philstate.Eating &&\n\t\t\t\tpb.RightPhilosopher().GetState() != philstate.Eating\n\t\t},\n\t\t\"eat while a neighbor is eating\",\n\t)\n\n\tAssert(\n\t\tfunc() bool {\n\t\t\treturn pb.LeftFork().IsHeldBy(pb.ID) &&\n\t\t\t\tpb.RightFork().IsHeldBy(pb.ID)\n\t\t},\n\t\t\"eat without holding forks\",\n\t)\n}", "func (p *CassandraDataCentersUpdatePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (g *queryGate) Done() {\n\tselect {\n\tcase <-g.ch:\n\tdefault:\n\t\tpanic(\"engine.queryGate.Done: more operations done than started\")\n\t}\n}", "func (e *EventLog) Finish() {\n\te.el.Finish()\n}", "func (pm *persistManager) Done() error {\n\tpm.Lock()\n\tdefer pm.Unlock()\n\n\tif pm.status != persistManagerFlushing {\n\t\treturn errPersistManagerNotFlushing\n\t}\n\n\t// Emit timing metrics\n\tpm.metrics.writeDurationMs.Update(float64(pm.worked / time.Millisecond))\n\tpm.metrics.throttleDurationMs.Update(float64(pm.slept / time.Millisecond))\n\n\t// Reset state\n\tpm.reset()\n\n\treturn nil\n}", "func (s *Session) End() {\n\ts.Stats.FinishedAt = time.Now()\n\ts.Stats.Status = StatusFinished\n\ts.StateStore.Close()\n}", "func (jpl *ChunkProgressLogger) chunkFinished(ctx context.Context) error {\n\tjpl.completedChunks++\n\treturn jpl.batcher.Add(ctx, jpl.perChunkContribution)\n}", "func (f *Finisher) Finish(result interface{}) {\n\tif f.isFinished {\n\t\treturn\n\t}\n\tf.isFinished = true\n\tf.callback(result)\n}", "func (r *Round) Finished() bool {\n\tfinished := true\n\tfor _, seating := range r.Seatings {\n\t\tfinished = finished && seating.Finished\n\t}\n\treturn finished\n}", "func (process *Process) Finish() {\n\tprocess.Action.Finish()\n\tprocess.updateInDatabase()\n}", "func (p *DatabaseAccountsOfflineRegionPoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (sh *StepSessionHandler) End() {\n\tfmt.Println(\"End session\")\n}", "func (dbea *DiskBackedEditAcc) FinishedEditing(ctx context.Context) (types.EditProvider, error) {\n\t// If we never flushed to disk then there is no need. Just return the data from the backing edit accumulator\n\tif dbea.flushCount == 0 {\n\t\treturn dbea.backing.FinishedEditing(ctx)\n\t}\n\n\t// flush any data we haven't flushed yet before processing\n\tsinceLastFlush := dbea.accumulated % dbea.flushInterval\n\tif sinceLastFlush > 0 {\n\t\tdbea.flusher.Flush(dbea.backing, (uint64(dbea.flushCount)))\n\t\tdbea.flushCount++\n\t\tdbea.backing = nil\n\t}\n\n\tresults, err := dbea.flusher.Wait(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\teps := make([]types.EditProvider, len(results))\n\tfor i := 0; i < len(results); i++ {\n\t\teps[i] = results[i].Edits\n\t}\n\n\treturn NewEPMerger(ctx, dbea.vrw, eps)\n}", "func (p *CassandraClustersUpdatePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (p *CassandraDataCentersDeletePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (pe *PendingEvent) Done() {\n\tif pe == nil || pe.name == \"\" || trace.file == nil {\n\t\treturn\n\t}\n\twriteEvent(&traceinternal.ViewerEvent{\n\t\tName: pe.name,\n\t\tPhase: end,\n\t\tPid: trace.pid,\n\t\tTid: pe.tid,\n\t\tTime: float64(time.Since(trace.start).Microseconds()),\n\t})\n}", "func (cfg *config) end() {\n\tcfg.checkTimeout()\n\tif cfg.t.Failed() == false {\n\t\tcfg.mu.Lock()\n\t\tt := time.Since(cfg.t0).Seconds() // real time\n\t\tnpeers := cfg.n // number of Raft peers\n\t\tnrpc := cfg.rpcTotal() - cfg.rpcs0 // number of RPC sends\n\t\tnbytes := cfg.bytesTotal() - cfg.bytes0 // number of bytes\n\t\tncmds := cfg.maxIndex - cfg.maxIndex0 // number of Raft agreements reported\n\t\tcfg.mu.Unlock()\n\n\t\tfmt.Printf(\" ... Passed --\")\n\t\tfmt.Printf(\" %4.1f %d %4d %7d %4d\\n\", t, npeers, nrpc, nbytes, ncmds)\n\t}\n}", "func (turingMachine *TuringMachine) HasFinished() bool {\n return turingMachine.hasFinished\n}", "func (s *Supermarket) finishedShoppingListener() {\n\tfor {\n\t\tif !s.openStatus && numberOfCurrentCustomersShopping == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\t// Check if customer is finished adding products to trolley using channel from the shop() method in Customer.go\n\t\tid := <-s.finishedShopping\n\n\t\t// Send customer to a checkout\n\t\ts.sendToCheckout(id)\n\t}\n}", "func (operation *Operation) Finish() {\n\toperation.Action.Finish()\n\toperation.updateInDatabase()\n}", "func (it *messageIterator) done(ackID string, ack bool, r *AckResult, receiveTime time.Time) {\n\tit.addToDistribution(receiveTime)\n\tit.mu.Lock()\n\tdefer it.mu.Unlock()\n\tdelete(it.keepAliveDeadlines, ackID)\n\tif ack {\n\t\tit.pendingAcks[ackID] = r\n\t} else {\n\t\tit.pendingNacks[ackID] = r\n\t}\n\tit.checkDrained()\n}", "func (mts *metadataTestSender) ConsumerDone() {\n\tmts.input.ConsumerDone()\n}", "func (pd *philosopherData) CanEat(maxDinner int) string {\n\tswitch {\n\tcase pd.eating:\n\t\treturn \"E:EATING\"\n\tcase pd.dinnersSpent >= maxDinner:\n\t\treturn \"E:LIMIT\"\n\tcase time.Now().Sub(pd.finishedAt) < (time.Duration(150) * time.Millisecond):\n\t\treturn \"E:JUSTFINISHED\"\n\t}\n\treturn \"OK\"\n}", "func (s *SleepService) End(ctx context.Context, family *goparent.Family, child *goparent.Child) error {\r\n\tsleep, _, err := s.Status(ctx, family, child)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\tif sleep == nil {\r\n\t\treturn goparent.ErrNoExistingSession\r\n\t}\r\n\r\n\tsleep.End = time.Now()\r\n\terr = s.Save(ctx, sleep)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\treturn nil\r\n}", "func (p *CassandraDataCentersClientUpdatePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (h *hombre) respirar() { h.respirando = true }", "func (game Game) Finished() bool {\n\treturn game.finished\n}", "func (pb *PhilosopherBase) StartEating() {\n\tpb.WriteString(\"starts eating\")\n\tpb.DelaySend(pb.EatRange, NewState{NewState: philstate.Thinking})\n}", "func (p philosopher) eat() {\r\n\tdefer eatWgroup.Done()\r\n\tfor j := 0; j < 3; j++ {\r\n\t\tp.leftFork.Lock()\r\n\t\tp.rightFork.Lock()\r\n\r\n\t\tsay(\"eating\", p.id)\r\n\t\ttime.Sleep(time.Second)\r\n\r\n\t\tp.rightFork.Unlock()\r\n\t\tp.leftFork.Unlock()\r\n\r\n\t\tsay(\"finished eating\", p.id)\r\n\t\ttime.Sleep(time.Second)\r\n\t}\r\n\r\n}", "func (p *DatabaseAccountsClientOfflineRegionPoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (s *BasecluListener) ExitEquate(ctx *EquateContext) {}", "func (data KeepAliveData) Complete() {\n}", "func (l *Listener) ExitAtEnd(ctx *parser.AtEndContext) {}", "func (s *fseEncoder) HistogramFinished(maxSymbol uint8, maxCount int) {\n\ts.maxCount = maxCount\n\ts.symbolLen = uint16(maxSymbol) + 1\n\ts.clearCount = maxCount != 0\n}", "func (p *CassandraDataCentersCreateUpdatePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (p *ManagedClustersUpdateTagsPoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (px *Paxos) Done(seq int) {\n\t// Your code here.\n\tpx.peerDone(seq, px.me)\n}", "func (l localOptimizer) finishMethodDone(operation chan<- Task, result <-chan Task, task Task) {\n\ttask.Op = MethodDone\n\toperation <- task\n\ttask = <-result\n\tif task.Op != PostIteration {\n\t\tpanic(\"optimize: task should have returned post iteration\")\n\t}\n\tl.finish(operation, result)\n}", "func (pl PromoteLearner) IsFinish(region *core.RegionInfo) bool {\n\tif p := region.GetStoreVoter(pl.ToStore); p != nil {\n\t\tif p.GetId() != pl.PeerID {\n\t\t\tlog.Warnf(\"expect %v, but obtain voter %v\", pl.String(), p.GetId())\n\t\t}\n\t\treturn p.GetId() == pl.PeerID\n\t}\n\treturn false\n}", "func (h *HashGenerator) CloseProvider() {\n\th.Done <- struct{}{}\n}", "func (m *Metric) Done() {\n\t// End open spans.\n\tm.mu.Lock() // Lock protects the slice of spans changing size.\n\tvar zeroTime time.Time\n\tfor _, s := range m.spans {\n\t\tif s.EndTime == zeroTime {\n\t\t\ts.End()\n\t\t}\n\t}\n\tm.mu.Unlock()\n\n\tif atomic.LoadInt32(&registered) == 0 {\n\t\t// No saver registered,\n\t\t// don't send any metrics.\n\t\treturn\n\t}\n\n\tselect {\n\tcase saveQueue <- m:\n\t\t// Sent\n\tdefault:\n\t\t// Warn if channel is full.\n\t\tlog.Error.Printf(\"metric: channel is full. Dropping metric %q.\", m.Name)\n\t}\n}", "func (b *Block) Finalize(endorsements []*endorsement.Endorsement, ts time.Time) error {\n\tif len(b.endorsements) != 0 {\n\t\treturn errors.New(\"the block has been finalized\")\n\t}\n\tb.endorsements = endorsements\n\tb.commitTime = ts\n\n\treturn nil\n}", "func (c *Controller) onJourneyFinished(j domain.Journey) {\n\tc.queue.Push(j)\n\tc.metricsService.GaugeInc(metrics.JOURNEYS_FINISHED.String())\n\tc.checkAndStoreJourney(&j)\n}", "func (c *ComponentChest) Finish() {\n\n\t//Check if Finish() has already been called\n\tif c.initialized {\n\t\treturn\n\t}\n\n\tc.initialized = true\n\n\t//Now that no more decks are coming, we can create deckNames once and be\n\t//done with it.\n\tc.deckNames = make([]string, len(c.decks))\n\n\ti := 0\n\n\tfor name := range c.decks {\n\t\tc.deckNames[i] = name\n\t\ti++\n\t}\n}", "func (dt *DirTracker) Finished() bool {\n\treturn dt.finished.Get()\n}", "func (g *Game) finished() bool {\r\n\t// check if there is a winner\r\n\tpl := g.hasWinner()\r\n\tif pl != nil {\r\n\t\tprintln(\"Player\", pl.name, \"wins!\")\r\n\t\treturn true\r\n\t}\r\n\r\n\tfor r := 0; r < 3; r++ {\r\n\t\tfor c := 0; c < 3; c++ {\r\n\t\t\tif g.panel.isCellFree(cell{r, c}) {\r\n\t\t\t\treturn false\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn true\r\n}", "func (c *Coordinator) Done() bool {\n\treturn c.isDone.Load().(bool)\n}", "func (ts *TeeSpan) Finish() {\n\tfor _, sp := range ts.spans {\n\t\tsp.Finish()\n\t}\n}", "func EndBlocker(ctx sdk.Context, keeper *keeper.Keeper) error {\n\tdefer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyEndBlocker)\n\n\tlogger := ctx.Logger().With(\"module\", \"x/\"+types.ModuleName)\n\t// delete dead proposals from store and returns theirs deposits.\n\t// A proposal is dead when it's inactive and didn't get enough deposit on time to get into voting phase.\n\trng := collections.NewPrefixUntilPairRange[time.Time, uint64](ctx.BlockTime())\n\terr := keeper.InactiveProposalsQueue.Walk(ctx, rng, func(key collections.Pair[time.Time, uint64], _ uint64) (bool, error) {\n\t\tproposal, err := keeper.Proposals.Get(ctx, key.K2())\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\terr = keeper.DeleteProposal(ctx, proposal.Id)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tparams, err := keeper.Params.Get(ctx)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif !params.BurnProposalDepositPrevote {\n\t\t\terr = keeper.RefundAndDeleteDeposits(ctx, proposal.Id) // refund deposit if proposal got removed without getting 100% of the proposal\n\t\t} else {\n\t\t\terr = keeper.DeleteAndBurnDeposits(ctx, proposal.Id) // burn the deposit if proposal got removed without getting 100% of the proposal\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\t// called when proposal become inactive\n\t\tkeeper.Hooks().AfterProposalFailedMinDeposit(ctx, proposal.Id)\n\n\t\tctx.EventManager().EmitEvent(\n\t\t\tsdk.NewEvent(\n\t\t\t\ttypes.EventTypeInactiveProposal,\n\t\t\t\tsdk.NewAttribute(types.AttributeKeyProposalID, fmt.Sprintf(\"%d\", proposal.Id)),\n\t\t\t\tsdk.NewAttribute(types.AttributeKeyProposalResult, types.AttributeValueProposalDropped),\n\t\t\t),\n\t\t)\n\n\t\tlogger.Info(\n\t\t\t\"proposal did not meet minimum deposit; deleted\",\n\t\t\t\"proposal\", proposal.Id,\n\t\t\t\"expedited\", proposal.Expedited,\n\t\t\t\"title\", proposal.Title,\n\t\t\t\"min_deposit\", sdk.NewCoins(proposal.GetMinDepositFromParams(params)...).String(),\n\t\t\t\"total_deposit\", sdk.NewCoins(proposal.TotalDeposit...).String(),\n\t\t)\n\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// fetch active proposals whose voting periods have ended (are passed the block time)\n\trng = collections.NewPrefixUntilPairRange[time.Time, uint64](ctx.BlockTime())\n\terr = keeper.ActiveProposalsQueue.Walk(ctx, rng, func(key collections.Pair[time.Time, uint64], _ uint64) (bool, error) {\n\t\tproposal, err := keeper.Proposals.Get(ctx, key.K2())\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar tagValue, logMsg string\n\n\t\tpasses, burnDeposits, tallyResults, err := keeper.Tally(ctx, proposal)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\t// If an expedited proposal fails, we do not want to update\n\t\t// the deposit at this point since the proposal is converted to regular.\n\t\t// As a result, the deposits are either deleted or refunded in all cases\n\t\t// EXCEPT when an expedited proposal fails.\n\t\tif passes || !proposal.Expedited {\n\t\t\tif burnDeposits {\n\t\t\t\terr = keeper.DeleteAndBurnDeposits(ctx, proposal.Id)\n\t\t\t} else {\n\t\t\t\terr = keeper.RefundAndDeleteDeposits(ctx, proposal.Id)\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\n\t\terr = keeper.ActiveProposalsQueue.Remove(ctx, collections.Join(*proposal.VotingEndTime, proposal.Id))\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tswitch {\n\t\tcase passes:\n\t\t\tvar (\n\t\t\t\tidx int\n\t\t\t\tevents sdk.Events\n\t\t\t\tmsg sdk.Msg\n\t\t\t)\n\n\t\t\t// attempt to execute all messages within the passed proposal\n\t\t\t// Messages may mutate state thus we use a cached context. If one of\n\t\t\t// the handlers fails, no state mutation is written and the error\n\t\t\t// message is logged.\n\t\t\tcacheCtx, writeCache := ctx.CacheContext()\n\t\t\tmessages, err := proposal.GetMsgs()\n\t\t\tif err != nil {\n\t\t\t\tproposal.Status = v1.StatusFailed\n\t\t\t\tproposal.FailedReason = err.Error()\n\t\t\t\ttagValue = types.AttributeValueProposalFailed\n\t\t\t\tlogMsg = fmt.Sprintf(\"passed proposal (%v) failed to execute; msgs: %s\", proposal, err)\n\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// execute all messages\n\t\t\tfor idx, msg = range messages {\n\t\t\t\thandler := keeper.Router().Handler(msg)\n\n\t\t\t\tvar res *sdk.Result\n\t\t\t\tres, err = handler(cacheCtx, msg)\n\t\t\t\tif err != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tevents = append(events, res.GetEvents()...)\n\t\t\t}\n\n\t\t\t// `err == nil` when all handlers passed.\n\t\t\t// Or else, `idx` and `err` are populated with the msg index and error.\n\t\t\tif err == nil {\n\t\t\t\tproposal.Status = v1.StatusPassed\n\t\t\t\ttagValue = types.AttributeValueProposalPassed\n\t\t\t\tlogMsg = \"passed\"\n\n\t\t\t\t// write state to the underlying multi-store\n\t\t\t\twriteCache()\n\n\t\t\t\t// propagate the msg events to the current context\n\t\t\t\tctx.EventManager().EmitEvents(events)\n\t\t\t} else {\n\t\t\t\tproposal.Status = v1.StatusFailed\n\t\t\t\tproposal.FailedReason = err.Error()\n\t\t\t\ttagValue = types.AttributeValueProposalFailed\n\t\t\t\tlogMsg = fmt.Sprintf(\"passed, but msg %d (%s) failed on execution: %s\", idx, sdk.MsgTypeURL(msg), err)\n\t\t\t}\n\t\tcase proposal.Expedited:\n\t\t\t// When expedited proposal fails, it is converted\n\t\t\t// to a regular proposal. As a result, the voting period is extended, and,\n\t\t\t// once the regular voting period expires again, the tally is repeated\n\t\t\t// according to the regular proposal rules.\n\t\t\tproposal.Expedited = false\n\t\t\tparams, err := keeper.Params.Get(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tendTime := proposal.VotingStartTime.Add(*params.VotingPeriod)\n\t\t\tproposal.VotingEndTime = &endTime\n\n\t\t\terr = keeper.ActiveProposalsQueue.Set(ctx, collections.Join(*proposal.VotingEndTime, proposal.Id), proposal.Id)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\ttagValue = types.AttributeValueExpeditedProposalRejected\n\t\t\tlogMsg = \"expedited proposal converted to regular\"\n\t\tdefault:\n\t\t\tproposal.Status = v1.StatusRejected\n\t\t\tproposal.FailedReason = \"proposal did not get enough votes to pass\"\n\t\t\ttagValue = types.AttributeValueProposalRejected\n\t\t\tlogMsg = \"rejected\"\n\t\t}\n\n\t\tproposal.FinalTallyResult = &tallyResults\n\n\t\terr = keeper.SetProposal(ctx, proposal)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\t// when proposal become active\n\t\tkeeper.Hooks().AfterProposalVotingPeriodEnded(ctx, proposal.Id)\n\n\t\tlogger.Info(\n\t\t\t\"proposal tallied\",\n\t\t\t\"proposal\", proposal.Id,\n\t\t\t\"status\", proposal.Status.String(),\n\t\t\t\"expedited\", proposal.Expedited,\n\t\t\t\"title\", proposal.Title,\n\t\t\t\"results\", logMsg,\n\t\t)\n\n\t\tctx.EventManager().EmitEvent(\n\t\t\tsdk.NewEvent(\n\t\t\t\ttypes.EventTypeActiveProposal,\n\t\t\t\tsdk.NewAttribute(types.AttributeKeyProposalID, fmt.Sprintf(\"%d\", proposal.Id)),\n\t\t\t\tsdk.NewAttribute(types.AttributeKeyProposalResult, tagValue),\n\t\t\t\tsdk.NewAttribute(types.AttributeKeyProposalLog, logMsg),\n\t\t\t),\n\t\t)\n\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (h *hombre) respirar() { h.respirando = true }", "func (l *Logger) Finished(url string, code int, latency time.Duration, urls, errors int) {\n\tl.m.Lock()\n\tdefer l.m.Unlock()\n\tl.Log = append(l.Log, fmt.Sprintf(\"finish %s: %d, %d, %d\", url, code, urls, errors))\n}", "func (p *CassandraClustersCreateUpdatePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (session *session) pairingCompleted() error {\n\tif session.Status == irma.ServerStatusPairing {\n\t\tsession.setStatus(irma.ServerStatusConnected)\n\t\treturn nil\n\t}\n\treturn errors.New(\"Pairing was not enabled\")\n}", "func (o Outcome) IsFinished() bool { return o.Reason != notCompleted }", "func (s *Basegff3Listener) ExitEnd(ctx *EndContext) {}", "func (s *Server) Done() {\n\ts.doneCh <- true\n}", "func (p *AgentPoolsDeletePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (p *CustomDomainsUpdatePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func end(state GameState) {\n\tlog.Printf(\"%s END\\n\\n\", state.Game.ID)\n}", "func end(state GameState) {\n\tlog.Printf(\"%s END\\n\\n\", state.Game.ID)\n}", "func (_GameJam *GameJamSession) Finish() (*types.Transaction, error) {\n\treturn _GameJam.Contract.Finish(&_GameJam.TransactOpts)\n}", "func (buf *RespBuffer) Finished() {\n\tbuf.finLock <- struct{}{}\n\tbuf.finished <- struct{}{}\n\t<-buf.finLock\n}", "func (p *DatabaseAccountsUpdatePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (p *CassandraClustersClientUpdatePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func Finished() {\n\tnotify := notificator.New(notificator.Options{\n\t\tDefaultIcon: \"icon/default.png\",\n\t\tAppName: \"Organizer\",\n\t})\n\n\tnotify.Push(appName,\n\t\tfinishedMessage,\n\t\ticonPath,\n\t\tnotificator.UR_CRITICAL)\n}", "func (s *BasePlSqlParserListener) ExitFor_update_of_part(ctx *For_update_of_partContext) {}", "func (p *ProgressMeter) Finish() {\n\tclose(p.finished)\n\tp.update()\n\tp.logger.Close()\n\tif !p.dryRun && p.estimatedBytes > 0 {\n\t\tfmt.Fprintf(os.Stdout, \"\\n\")\n\t}\n}", "func (p *ProgressMeter) Finish() {\n\tclose(p.finished)\n\tp.update()\n\tp.logger.Close()\n\tif !p.dryRun && p.estimatedBytes > 0 {\n\t\tfmt.Fprintf(os.Stdout, \"\\n\")\n\t}\n}", "func (p *AgentPoolsUpgradeNodeImageVersionPoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (c *context) Done() <-chan struct{} { return c.c.Done() }", "func (p *DomainsUpdatePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (h *CookiejarHandler) eat(ctx *processor.Context, amount int, fromKey string) error {\n\t// Get the composite address for the sender's public key\n\taddress := h.getAddress(fromKey)\n\tlogger.Debugf(\"Got the key %s and cookiejar address %s\", fromKey, address)\n\n\t// Get the current state\n\tstate, err := ctx.GetState([]string{address})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Get the current state for the address\n\tc, ok := state[address]\n\tif !ok {\n\t\t// The address doesn't exist, so we'll return with an error\n\t\tlogger.Errorf(\"No cookie jar with the key %s\", address)\n\t\treturn &processor.InternalError{Msg: \"Invalid cookie jar\"}\n\t}\n\n\tcookies, _ := strconv.Atoi(string(c)) // convert to int\n\tif cookies < amount {\n\t\t// Not enough of cookies, return an error\n\t\tlogger.Error(\"Not enough of cookies in the jar\")\n\t\treturn &processor.InvalidTransactionError{Msg: \"Not enough of cookies in the jar\"}\n\t}\n\n\t// Update the state to current amount of cookies - amount\n\tstate[address] = []byte(strconv.Itoa(cookies - amount))\n\n\t// Store the new state\n\taddresses, err := ctx.SetState(state)\n\tif err != nil {\n\t\treturn &processor.InternalError{Msg: fmt.Sprintf(\"Couldn't update state: %v\", err)}\n\t}\n\n\t// Check whether addresses is empty\n\tif len(addresses) == 0 {\n\t\treturn &processor.InternalError{Msg: \"No addresses in set response\"}\n\t}\n\n\t// Launch an event\n\tif err := ctx.AddEvent(\n\t\t\"cookiejar/eat\",\n\t\t[]processor.Attribute{processor.Attribute{\"cookies-ate\", strconv.Itoa(amount)}},\n\t\tnil,\n\t); err != nil {\n\t\treturn &processor.InternalError{Msg: fmt.Sprintf(\"Couldn't publish event: %v\", err)}\n\t}\n\n\treturn nil\n}", "func (pp *PermuteProtocol) Finalize(ciphertext *bfv.Ciphertext, permutation []uint64, crs *ring.Poly, share RefreshShare, ciphertextOut *bfv.Ciphertext) {\n\tpp.Decrypt(ciphertext, share.RefreshShareDecrypt, pp.tmp1)\n\tpp.Permute(pp.tmp1, permutation, pp.tmp1)\n\tpp.Recrypt(pp.tmp1, crs, share.RefreshShareRecrypt, ciphertextOut)\n}", "func (c *Cooler) Done() {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tc.active = false\n}", "func (game *T) Done() chan bool {\n\treturn game.close\n}", "func (p *VaultsUpdatePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (up *updateProgressConfiguration) FinishTime() *time.Time {\n\treturn up.finishTime\n}", "func EndGame(s *discordgo.Session) {\n\t// Loop through all players\n\tfor _, player := range Players {\n\t\t// if a player's score is higher than the current one, then\n\t\t// update the high score with the player's score.\n\t\tif player.Score > HighScore {\n\t\t\tHighScore = player.Score\n\t\t\tHighScoreID = player.PlayerID\n\t\t}\n\t}\n\t// Error catching here, if HighScoreID is blank, then no winners.\n\tif HighScoreID == \"\" {\n\t\ts.ChannelMessageSend(utils.Config.CAHChannelID, \"The game has ended with no winners. Better luck next time!\")\n\t\treturn\n\t}\n\n\ts.ChannelMessageSend(utils.Config.CAHChannelID, fmt.Sprintf(\"Congratulations %s You won the game with %d points!\", Players[HighScoreID].PlayerName, HighScore))\n\t// At this point, I would reset all the variables and stuff, but the\n\t// InitializeData function that runs when a new game is started\n\t// does it for me.\n}", "func (j *Job) done() { j.isDone <- true }", "func (p *LiveEventsUpdatePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (p *CassandraClustersDeletePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (c *Coordinator) Done() bool {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\treturn c.done\n}", "func (px *Paxos) Done(seq int) {\n\t// Your code here.\n\tpx.peerDones[px.me] = seq\n}", "func (p *StreamingEndpointsUpdatePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (p *LiveOutputsDeletePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func EndBlocker(ctx sdk.Context, keeper Keeper) sdk.Tags {\n\tlogger := keeper.Logger(ctx)\n\tresTags := sdk.NewTags()\n\n\tinactiveIterator := keeper.InactiveProposalQueueIterator(ctx, ctx.BlockHeader().Time)\n\tdefer inactiveIterator.Close()\n\tfor ; inactiveIterator.Valid(); inactiveIterator.Next() {\n\t\tvar proposalID uint64\n\n\t\tkeeper.cdc.MustUnmarshalBinaryLengthPrefixed(inactiveIterator.Value(), &proposalID)\n\t\tinactiveProposal, ok := keeper.GetProposal(ctx, proposalID)\n\t\tif !ok {\n\t\t\tpanic(fmt.Sprintf(\"proposal %d does not exist\", proposalID))\n\t\t}\n\n\t\tkeeper.DeleteProposal(ctx, proposalID)\n\t\tkeeper.DeleteDeposits(ctx, proposalID) // delete any associated deposits (burned)\n\n\t\tresTags = resTags.AppendTag(tags.ProposalID, fmt.Sprintf(\"%d\", proposalID))\n\t\tresTags = resTags.AppendTag(tags.ProposalResult, tags.ActionProposalDropped)\n\n\t\tlogger.Info(\n\t\t\tfmt.Sprintf(\"proposal %d (%s) didn't meet minimum deposit of %s (had only %s); deleted\",\n\t\t\t\tinactiveProposal.ProposalID,\n\t\t\t\tinactiveProposal.GetTitle(),\n\t\t\t\tkeeper.GetDepositParams(ctx).MinDeposit,\n\t\t\t\tinactiveProposal.TotalDeposit,\n\t\t\t),\n\t\t)\n\t}\n\n\t// fetch active proposals whose voting periods have ended (are passed the block time)\n\tactiveIterator := keeper.ActiveProposalQueueIterator(ctx, ctx.BlockHeader().Time)\n\tdefer activeIterator.Close()\n\tfor ; activeIterator.Valid(); activeIterator.Next() {\n\t\tvar proposalID uint64\n\n\t\tkeeper.cdc.MustUnmarshalBinaryLengthPrefixed(activeIterator.Value(), &proposalID)\n\t\tactiveProposal, ok := keeper.GetProposal(ctx, proposalID)\n\t\tif !ok {\n\t\t\tpanic(fmt.Sprintf(\"proposal %d does not exist\", proposalID))\n\t\t}\n\t\tpasses, burnDeposits, tallyResults := tally(ctx, keeper, activeProposal)\n\n\t\tvar tagValue, logMsg string\n\n\t\tif burnDeposits {\n\t\t\tkeeper.DeleteDeposits(ctx, activeProposal.ProposalID)\n\t\t} else {\n\t\t\tkeeper.RefundDeposits(ctx, activeProposal.ProposalID)\n\t\t}\n\n\t\tif passes {\n\t\t\thandler := keeper.router.GetRoute(activeProposal.ProposalRoute())\n\t\t\tcacheCtx, writeCache := ctx.CacheContext()\n\n\t\t\t// The proposal handler may execute state mutating logic depending\n\t\t\t// on the proposal content. If the handler fails, no state mutation\n\t\t\t// is written and the error message is logged.\n\t\t\terr := handler(cacheCtx, activeProposal.Content)\n\t\t\tif err == nil {\n\t\t\t\tactiveProposal.Status = StatusPassed\n\t\t\t\ttagValue = tags.ActionProposalPassed\n\t\t\t\tlogMsg = \"passed\"\n\n\t\t\t\t// write state to the underlying multi-store\n\t\t\t\twriteCache()\n\t\t\t} else {\n\t\t\t\tactiveProposal.Status = StatusFailed\n\t\t\t\ttagValue = tags.ActionProposalFailed\n\t\t\t\tlogMsg = fmt.Sprintf(\"passed, but failed on execution: %s\", err.ABCILog())\n\t\t\t}\n\t\t} else {\n\t\t\tactiveProposal.Status = StatusRejected\n\t\t\ttagValue = tags.ActionProposalRejected\n\t\t\tlogMsg = \"rejected\"\n\t\t}\n\n\t\tactiveProposal.FinalTallyResult = tallyResults\n\n\t\tkeeper.SetProposal(ctx, activeProposal)\n\t\tkeeper.RemoveFromActiveProposalQueue(ctx, activeProposal.VotingEndTime, activeProposal.ProposalID)\n\n\t\tlogger.Info(\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"proposal %d (%s) tallied; result: %s\",\n\t\t\t\tactiveProposal.ProposalID, activeProposal.GetTitle(), logMsg,\n\t\t\t),\n\t\t)\n\n\t\tresTags = resTags.AppendTag(tags.ProposalID, fmt.Sprintf(\"%d\", proposalID))\n\t\tresTags = resTags.AppendTag(tags.ProposalResult, tagValue)\n\t}\n\n\treturn resTags\n}" ]
[ "0.63093334", "0.58876115", "0.58766305", "0.5421732", "0.5419533", "0.51385415", "0.49990445", "0.49211752", "0.48569322", "0.48507303", "0.48308152", "0.48283854", "0.4770093", "0.47173318", "0.47077057", "0.47041526", "0.46748292", "0.46745336", "0.46711296", "0.46498522", "0.46367687", "0.45826963", "0.45662838", "0.4564823", "0.45637777", "0.4557312", "0.45298013", "0.45246765", "0.45151058", "0.45112127", "0.45104572", "0.45063338", "0.4498664", "0.44849902", "0.447394", "0.44712818", "0.4460766", "0.44558996", "0.44534174", "0.44512838", "0.44375148", "0.44269836", "0.44191277", "0.4417544", "0.44110993", "0.44075733", "0.44008094", "0.43893343", "0.43889323", "0.43877476", "0.4386563", "0.43807068", "0.43741214", "0.43650177", "0.43543527", "0.43517387", "0.43494013", "0.43468812", "0.43463418", "0.43414384", "0.4328676", "0.43217364", "0.43162242", "0.43144542", "0.43138343", "0.43136188", "0.43081346", "0.4305095", "0.4303062", "0.42977569", "0.42968962", "0.42959642", "0.42850205", "0.42850205", "0.427868", "0.42768738", "0.42645538", "0.4260539", "0.42565414", "0.425047", "0.42467666", "0.42467666", "0.42465705", "0.42456952", "0.4245465", "0.42435858", "0.4242834", "0.42425624", "0.42380977", "0.42348588", "0.4233801", "0.42296985", "0.42278045", "0.42274225", "0.42269048", "0.42244038", "0.42243186", "0.4224085", "0.42204523", "0.42124593" ]
0.8208014
0
RespChannel returns the philosopher's response channel.
func (pd *philosopherData) RespChannel() chan string { return pd.respChannel }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (phi *Philosopher) RespChannel() chan string {\n\treturn phi.respChannel\n}", "func (c *WSClient) GetResponseChannel() chan *model.WebSocketResponse {\n\treturn c.ResponseChannel\n}", "func (pp *PushPromise) Response() *ClientResponse {\n\treturn <-pp.responseChannel\n}", "func (m *mockedChannel) GetReplyChannel() <-chan *govppapi.VppReply {\n\treturn m.channel.GetReplyChannel()\n}", "func (k *Kafka) ResponseChan() <-chan types.Response {\n\treturn k.responseChan\n}", "func (z *ZMQ4) ResponseChan() <-chan types.Response {\n\treturn z.responseChan\n}", "func (p *Player) Channel() *api.Channel {\n\tretCh := make(chan *api.Channel)\n\tp.chGetChannel <- retCh\n\tc := <-retCh\n\treturn c\n}", "func (cmd *Command) Response() chan *Response {\n\treturn cmd.response\n}", "func decodeGRPCEchoResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.EchoReply)\n\treturn endpoints.EchoResponse{Rs: reply.Rs}, nil\n}", "func (p *HostedProgramInfo) Channel() io.ReadWriteCloser {\n\treturn p.TaoChannel\n}", "func (m *MetricsExtracor) Channel() chan<- interface{} {\n\treturn m.channel\n}", "func (closer *Closer) CloseChannel() chan struct{} {\n\treturn closer.channel\n}", "func (bft *ProtocolBFTCoSi) readResponseChan(c chan responseChan, t RoundType) error {\n\ttimeout := time.After(bft.Timeout)\n\tfor {\n\t\tif bft.isClosing() {\n\t\t\treturn errors.New(\"Closing\")\n\t\t}\n\n\t\tselect {\n\t\tcase msg, ok := <-c:\n\t\t\tif !ok {\n\t\t\t\tlog.Lvl3(\"Channel closed\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tfrom := msg.ServerIdentity.Public\n\t\t\tr := msg.Response\n\n\t\t\tswitch msg.Response.TYPE {\n\t\t\tcase RoundPrepare:\n\t\t\t\tbft.tempPrepareResponse = append(bft.tempPrepareResponse, r.Response)\n\t\t\t\tbft.tempExceptions = append(bft.tempExceptions, r.Exceptions...)\n\t\t\t\tbft.tempPrepareResponsePublics = append(bft.tempPrepareResponsePublics, from)\n\t\t\t\t// There is no need to have more responses than we have\n\t\t\t\t// commits. We _should_ check here if we get the same\n\t\t\t\t// responses from the same nodes. But as this is deprecated\n\t\t\t\t// and replaced by ByzCoinX, we'll leave it like that.\n\t\t\t\tif t == RoundPrepare && len(bft.tempPrepareResponse) == len(bft.tempPrepareCommit) {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase RoundCommit:\n\t\t\t\tbft.tempCommitResponse = append(bft.tempCommitResponse, r.Response)\n\t\t\t\t// Same reasoning as in RoundPrepare.\n\t\t\t\tif t == RoundCommit && len(bft.tempCommitResponse) == len(bft.tempCommitCommit) {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-timeout:\n\t\t\tlog.Lvl1(\"timeout while trying to read response messages\")\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func newPhilosopherDataPtr(respChannel chan string) *philosopherData {\n\tpd := new(philosopherData)\n\tpd.Init(respChannel)\n\treturn pd\n}", "func (e *EventNotif) Channel() (res <-chan Event) {\n\treturn e.eventsCh\n}", "func (c *WSClient) SetResponseChannel(rc chan *model.WebSocketResponse) {\n\tc.ResponseChannel = rc\n}", "func NewCloseSecureChannelResponse(resHeader *ResponseHeader) *CloseSecureChannelResponse {\n\treturn &CloseSecureChannelResponse{\n\t\tResponseHeader: resHeader,\n\t}\n}", "func (ch *clientSecureChannel) responseWorker() {\n\tfor {\n\t\tres, err := ch.readResponse()\n\t\tif err != nil {\n\t\t\tif ch.reconnecting {\n\t\t\t\ttime.Sleep(1000 * time.Millisecond)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif ch.errCode == ua.Good {\n\t\t\t\tif ec, ok := err.(ua.StatusCode); ok {\n\t\t\t\t\tch.errCode = ec\n\t\t\t\t}\n\t\t\t}\n\t\t\tclose(ch.cancellation)\n\t\t\treturn\n\t\t}\n\t\tch.handleResponse(res)\n\t}\n}", "func (res channelBase) Channel() *types.Channel {\n\treturn res.channel\n}", "func encodeGRPCEchoResponse(_ context.Context, grpcReply interface{}) (res interface{}, err error) {\n\n\treply := grpcReply.(endpoints.EchoResponse)\n\treturn &pb.EchoReply{Rs: reply.Rs}, def.GrpcEncodeError(reply.Err)\n}", "func (o *DeleteChannelHandlerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 204:\n\t\tresult := NewDeleteChannelHandlerNoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewDeleteChannelHandlerUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 403:\n\t\tresult := NewDeleteChannelHandlerForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 500:\n\t\tresult := NewDeleteChannelHandlerInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\tdata, err := ioutil.ReadAll(response.Body())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"Requested DELETE /matchmaking/namespaces/{namespace}/channels/{channel} returns an error %d: %s\", response.Code(), string(data))\n\t}\n}", "func (p *pipeline) Channel() Channel {\n\treturn p.channel\n}", "func (m *MockCallResult) Channel() <-chan *Result {\n\targs := m.MethodCalled(\"Channel\")\n\n\tif resultChan := args.Get(0); resultChan != nil {\n\t\treturn resultChan.(<-chan *Result)\n\t}\n\n\treturn nil\n}", "func (c *Client) Channel(ctx context.Context, r ChannelRequest) (*ChannelReply, error) {\r\n\treq, err := http.NewRequestWithContext(\r\n\t\tctx,\r\n\t\thttp.MethodGet,\r\n\t\tfmt.Sprintf(\"%s/%s/channel/%s\", c.getChanelBaseEndpoint(), r.AccountID, r.ChannelID),\r\n\t\tnil,\r\n\t)\r\n\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\tres := ChannelReply{}\r\n\tif err := c.sendRequest(req, &res); err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\treturn &res, nil\r\n}", "func (r *role) ProposeChannel(req client.ChannelProposal) (*paymentChannel, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), r.timeout)\n\tdefer cancel()\n\t_ch, err := r.Client.ProposeChannel(ctx, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Client.OnNewChannel callback adds paymentChannel wrapper to the chans map\n\tch, ok := r.chans.channel(_ch.ID())\n\tif !ok {\n\t\treturn ch, errors.New(\"channel not found\")\n\t}\n\treturn ch, nil\n}", "func (k *ChannelKeeper) Channel() *amqp.Channel {\n\treturn k.msgCh\n}", "func (f future) Response() <-chan network.Response {\n\tin := transport.Future(f).Result()\n\tout := make(chan network.Response, cap(in))\n\tgo func(in <-chan *packet.Packet, out chan<- network.Response) {\n\t\tfor packet := range in {\n\t\t\tout <- (*packetWrapper)(packet)\n\t\t}\n\t\tclose(out)\n\t}(in, out)\n\treturn out\n}", "func (ticker *PausableTicker) GetChannel() <-chan time.Time {\n\treturn ticker.channel\n}", "func mainChannel() {\n\n\tretCanal := make(chan string)\n\n\tgo say(\"world\", retCanal) // retorna uma mensagem no channel retChannel\n\n\tfmt.Println(<-retCanal) // \taqui, a go routine principal esta esperando receber a mensagem do channel retornado pela go routine acima\n}", "func (remote *SerialRemote) Channel() chan []byte {\n\treturn remote.channel\n}", "func (rc *responseController) CalculateChannelResponse(ill models.IlluminationCode, startWave, stopWave, step int, normPatchNumber int) (bool, []models.ChannelResponse) {\n\tstatus := false\n\tresponses := make([]models.ChannelResponse, 0)\n\n\tvar illSpectrum map[int]float64\n\tswitch ill {\n\tcase models.D65:\n\t\tillSpectrum = rc.d65Map\n\tcase models.IllA:\n\t\tillSpectrum = rc.illAMap\n\tdefault:\n\t\tbreak\n\t}\n\n\t// calculate each color chart response\n\tfor i := 0; i < 24; i++ {\n\t\t// device channel response stocker\n\t\tgrCh := 0.0\n\t\tgbCh := 0.0\n\t\trCh := 0.0\n\t\tbCh := 0.0\n\n\t\t// scan wave length\n\t\tfor wavelength := startWave; wavelength <= stopWave; wavelength += step {\n\t\t\tgr, gb, r, b := rc.calculateEachChannelResponse(\n\t\t\t\tillSpectrum,\n\t\t\t\trc.deviceQEGrMap,\n\t\t\t\trc.deviceQEGbMap,\n\t\t\t\trc.deviceQERedMap,\n\t\t\t\trc.deviceQEBlueMap,\n\t\t\t\trc.colorCheckerMap[i],\n\t\t\t\twavelength,\n\t\t\t)\n\n\t\t\t// accumulate response\n\t\t\tgrCh += gr\n\t\t\tgbCh += gb\n\t\t\trCh += r\n\t\t\tbCh += b\n\t\t}\n\n\t\t// make channel response object\n\t\tres := &models.ChannelResponse{\n\t\t\tCheckerNumber: i + 1,\n\t\t\tGr: grCh,\n\t\t\tGb: gbCh,\n\t\t\tR: rCh,\n\t\t\tB: bCh,\n\t\t}\n\n\t\t// stock the chennel response data to stocker\n\t\trc.responses = append(rc.responses, *res)\n\n\t\t// update status\n\t\tstatus = true\n\t}\n\n\t// normarize channel response by ref patch signal\n\tif status {\n\t\trefPatch := rc.responses[normPatchNumber-1]\n\t\trefPatchGrGb := (refPatch.Gr + refPatch.Gb) / 2.0\n\n\t\tfor _, data := range rc.responses {\n\t\t\tresponse := &models.ChannelResponse{\n\t\t\t\tCheckerNumber: data.CheckerNumber,\n\t\t\t\tGr: data.Gr / refPatchGrGb,\n\t\t\t\tGb: data.Gb / refPatchGrGb,\n\t\t\t\tR: data.R / refPatchGrGb,\n\t\t\t\tB: data.B / refPatchGrGb,\n\t\t\t}\n\t\t\t// stacking\n\t\t\tresponses = append(responses, *response)\n\t\t}\n\t}\n\n\treturn status, responses\n}", "func (c *connection) Channel() (amqpChannel, error) {\n\tch, err := c.conn.Channel()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := ch.Confirm(wait); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &channel{ch}, nil\n}", "func (*ListGuildChannelsResponse) Descriptor() ([]byte, []int) {\n\treturn file_discord_v1_cache_proto_rawDescGZIP(), []int{3}\n}", "func (ch *clientSecureChannel) handleResponse(res ua.ServiceResponse) error {\n\tch.mapPendingResponses()\n\thnd := res.Header().RequestHandle\n\tif op, ok := ch.pendingResponses[hnd]; ok {\n\t\tdelete(ch.pendingResponses, hnd)\n\t\tselect {\n\t\tcase op.ResponseCh() <- res:\n\t\tdefault:\n\t\t\tfmt.Println(\"In handleResponse, responseCh was blocked.\")\n\t\t}\n\t\treturn nil\n\t}\n\treturn ua.BadUnknownResponse\n}", "func PollResponse(w http.ResponseWriter, r *http.Request) {\n\ttimeout := make(chan bool)\n\tgo func() {\n\t\ttime.Sleep(30e9)\n\t\ttimeout <- true\n\t}()\n\n\tid := hub.newClient()\n\tdefer func() {\n\t\tclose(timeout)\n\t\thub.endSession(id)\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase msg := <-hub.client[id]:\n\t\t\tio.WriteString(w, msg)\n\t\t\treturn\n\t\tcase <-timeout:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (*Session) HandleResponse(msg proto.Message, err error) error {\n\tif err != nil {\n\t\t// check, if it is a gRPC error\n\t\ts, ok := status.FromError(err)\n\n\t\t// otherwise, forward the error message\n\t\tif !ok {\n\t\t\treturn err\n\t\t}\n\n\t\t// create a new error with just the message\n\t\treturn errors.New(s.Message())\n\t}\n\n\topt := protojson.MarshalOptions{\n\t\tMultiline: true,\n\t\tIndent: \" \",\n\t\tEmitUnpopulated: true,\n\t}\n\n\tb, _ := opt.Marshal(msg)\n\n\t_, err = fmt.Fprintf(Output, \"%s\\n\", string(b))\n\n\treturn err\n}", "func (tv *TV) teardownResponseChannel(id string) {\n\ttv.resMutex.Lock()\n\tdefer tv.resMutex.Unlock()\n\n\tif ch, ok := tv.res[id]; ok {\n\t\tclose(ch)\n\t\tdelete(tv.res, id)\n\t}\n}", "func (p *PeerSubscription) CloseChan() <-chan struct{} {\n\treturn p.closeChan\n}", "func (wire *Wire) Response() <-chan Response {\n\treturn wire.responses\n}", "func (ch *Channel) Close() {}", "func waitForResponse(originalResp *Response, channel chan *rpc.Call) {\n\tresp := <-channel\n\tvar test *Response\n\ttest = resp.Reply.(*Response)\n\ttest.client.Close()\n\toriginalResp.Reply = test.Reply\n\treturn\n}", "func (t *channelTransport) recv() <-chan pb.Message {\n\treturn t.recvChan\n}", "func (tr *Peer) ReceiverChannel() <-chan *RPC {\n\ttr.mtx.Lock()\n\tdefer tr.mtx.Unlock()\n\n\treturn tr.server.ReceiverChannel()\n}", "func (tv *TV) setupResponseChannel(id string) chan Message {\n\ttv.resMutex.Lock()\n\tdefer tv.resMutex.Unlock()\n\n\tif tv.res == nil {\n\t\ttv.res = make(map[string]chan<- Message)\n\t}\n\n\tch := make(chan Message, 1)\n\ttv.res[id] = ch\n\treturn ch\n}", "func (o *Output) getResponse() {\r\n\tfor response := range o.receiveChannel {\r\n\t\tlog.Println(\"Producer: got a response to write\")\r\n\t\tif err := o.writeResponse(response); err != nil {\r\n\t\t\tcontinue\r\n\t\t}\r\n\t}\r\n}", "func (*GetGuildChannelResponse) Descriptor() ([]byte, []int) {\n\treturn file_discord_v1_cache_proto_rawDescGZIP(), []int{5}\n}", "func (k *ChannelKeeper) Return() <-chan amqp.Return {\n\treturn k.returnCh\n}", "func (s *Service) RPCHandler(w http.ResponseWriter, r *http.Request) {\n\n\t// get response struct\n\trespObj := s.Do(r)\n\n\t// set custom response headers\n\tfor header, value := range s.Headers {\n\t\tw.Header().Set(header, value)\n\t}\n\n\t// set response headers\n\tfor header, value := range respObj.Headers {\n\t\tw.Header().Set(header, value)\n\t}\n\n\t// notification does not send responses to client\n\tif respObj.IsNotification {\n\t\t// set response header to 204, (no content)\n\t\tw.WriteHeader(http.StatusNoContent)\n\t\treturn\n\t}\n\n\t// write response code to HTTP writer interface\n\tw.WriteHeader(respObj.HTTPResponseStatusCode)\n\n\t// write data to HTTP writer interface\n\t_, err := w.Write(respObj.ResponseMarshal())\n\tif err != nil { // this should never happen\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n}", "func decodeGRPCSayHelloResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.SayHelloReply)\n\treturn endpoints.SayHelloResponse{Rs: reply.Rs}, nil\n}", "func (m *Manager) TerminationChannel(name string) chan struct{} {\n\tif c := m.lookup(name); c != nil {\n\t\treturn c.terminated\n\t}\n\n\tc := make(chan struct{})\n\tclose(c)\n\treturn c\n}", "func (conn *Connection) Channel() chan []byte {\n\treturn conn.channel\n}", "func (h *Helm) UpdateChannel() <-chan struct{} {\n\treturn h.trigger\n}", "func (p *LightningPool) Channel(ctx context.Context) (*amqp.Channel, error) {\n\tvar (\n\t\tk *amqp.Channel\n\t\terr error\n\t)\n\n\tp.mx.Lock()\n\tlast := len(p.set) - 1\n\tif last >= 0 {\n\t\tk = p.set[last]\n\t\tp.set = p.set[:last]\n\t}\n\tp.mx.Unlock()\n\n\t// If pool is empty create new channel\n\tif last < 0 {\n\t\tk, err = p.new(ctx)\n\t\tif err != nil {\n\t\t\treturn k, errors.Wrap(err, \"failed to create new\")\n\t\t}\n\t}\n\n\treturn k, nil\n}", "func (s *secretRenewer) RenewChannel() chan secrets {\n\treturn s.renewCh\n}", "func (*CMsgGCRerollPlayerChallengeResponse) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_common_proto_rawDescGZIP(), []int{25}\n}", "func (m *MetricsHolder) Channel() chan<- interface{} {\n\treturn m.channel\n}", "func (gp *GetProjects) GetResponse() ActionResponseInterface {\n\treturn <-gp.responseCh\n}", "func (c *Connection) Channel() (*Channel, error) {\n\tch, err := c.Connection.Channel()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tchannel := &Channel{\n\t\tChannel: ch,\n\t\tdelayer: &delayer{delaySeconds: c.delaySeconds},\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\treason, ok := <-channel.Channel.NotifyClose(make(chan *amqp.Error))\n\t\t\t// exit this goroutine if channel is closed by developer\n\t\t\tif !ok || channel.IsClosed() {\n\t\t\t\tdebug(\"channel closed\")\n\t\t\t\tchannel.Close() // ensure closed flag is set when channel is closed\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tdebugf(\"channel closed, reason: %v\", reason)\n\n\t\t\t// recreate if channel is not closed by developer\n\t\t\tfor {\n\t\t\t\t// wait for channel recreate\n\t\t\t\twait(channel.delaySeconds)\n\n\t\t\t\tch, err := c.Connection.Channel()\n\t\t\t\tif err == nil {\n\t\t\t\t\tdebug(\"channel recreate success\")\n\t\t\t\t\tchannel.methodMap.Range(func(k, v interface{}) bool {\n\t\t\t\t\t\tmethodName, _ := k.(string)\n\t\t\t\t\t\tchannel.DoMethod(ch, methodName)\n\t\t\t\t\t\tdebugf(\"channel do method %v success\", methodName)\n\t\t\t\t\t\treturn true\n\t\t\t\t\t})\n\t\t\t\t\tchannel.Channel = ch\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tdebugf(\"channel recreate failed, err: %v\", err)\n\t\t\t}\n\t\t}\n\n\t}()\n\n\treturn channel, nil\n}", "func (*CMsgClientToGCHasPlayerVotedForMVPResponse) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{180}\n}", "func (r *Readiness) GetChannel() chan ReadinessMessage {\n\treturn r.channel\n}", "func (meta *MetaAI) GetChannel(c chan string) {\n\tmeta.l.Lock()\n\tdefer meta.l.Unlock()\n\n\tmeta.i = c\n}", "func (o *PutChannelsChannelIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 204:\n\t\tresult := NewPutChannelsChannelIDNoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewPutChannelsChannelIDDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func GetResponseCh(userId int64, urlType string) (*result.Result, *apierrors.ApiError){\n\n\tch := make(chan *result.Result)\n\tdefer close(ch)\n\n\tvar wg sync.WaitGroup\n\tvar result result.Result\n\n\n\tuser := user.User{\n\t\tID: userId,\n\t}\n\tuser.Get(urlType)\n\tresult.User = &user\n\n\tgo func() {\n\n\t\tfor i := 0; i < 2; i++ {\n\n\t\t\titem := <-ch\n\t\t\twg.Done()\n\t\t\tif item.Site != nil {\n\t\t\t\tresult.Site = item.Site\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif item.Country != nil {\n\t\t\t\tresult.Country = item.Country\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}()\n\n\twg.Add(2)\n\tgo getCountry(user.CountryID, urlType, ch, &wg)\n\tgo getSite(user.SiteID, urlType, ch, &wg)\n\twg.Wait()\n\n\treturn &result, nil\n\n}", "func (r Rabbit) GetCh() *amqp.Channel {\n\treturn r.ch\n}", "func (t *TCPTransport) Responses() <-chan []byte {\n\treturn t.responses\n}", "func (clientHandler) Response(ctx context.Context, conn *jsonrpc2.Conn, direction jsonrpc2.Direction, r *jsonrpc2.WireResponse) context.Context {\n\treturn ctx\n}", "func (*CBroadcast_EndBroadcastSession_Response) Descriptor() ([]byte, []int) {\n\treturn file_steammessages_broadcast_steamclient_proto_rawDescGZIP(), []int{3}\n}", "func (ch *ServerChannel) Disconnect(c *Client) {}", "func (c channelConveyor) Close() {\n\tclose(c.outputCh)\n}", "func (o *GetAllSessionsInChannelReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetAllSessionsInChannelOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewGetAllSessionsInChannelBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewGetAllSessionsInChannelUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 403:\n\t\tresult := NewGetAllSessionsInChannelForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewGetAllSessionsInChannelNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 500:\n\t\tresult := NewGetAllSessionsInChannelInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\tdata, err := ioutil.ReadAll(response.Body())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"Requested GET /matchmaking/v1/admin/namespaces/{namespace}/channels/{channelName}/sessions returns an error %d: %s\", response.Code(), string(data))\n\t}\n}", "func (o *CreateChannelReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 201:\n\t\tresult := NewCreateChannelCreated()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewCreateChannelBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 401:\n\t\tresult := NewCreateChannelUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 422:\n\t\tresult := NewCreateChannelUnprocessableEntity()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewCreateChannelInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (ch *InternalChannel) Disconnect(c *Client) {}", "func decodeGRPCTicResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\t_ = grpcReply.(*pb.TicResponse)\n\treturn endpoints.TicResponse{}, nil\n}", "func (*CBroadcast_WebRTCLookupTURNServer_Response) Descriptor() ([]byte, []int) {\n\treturn file_steammessages_broadcast_steamclient_proto_rawDescGZIP(), []int{52}\n}", "func Response(conn net.Conn, provider net.Conn) {\n\tch := make(chan bool)\n\tgo transfer(conn, provider, ch)\n\tgo transfer(provider, conn, ch)\n\t<-ch\n\tconn.Close()\n\tprovider.Close()\n\t<-ch\n\tclose(ch)\n}", "func (c Client) GetChannels(lineupURI string) (*ChannelResponse, error) {\n\turl := fmt.Sprint(DefaultBaseURL, lineupURI)\n\tfmt.Println(\"URL:>\", url)\n\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\treq.Header.Set(\"token\", c.Token)\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\tlog.Fatal(resp.Status)\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close() //resp.Body.Close() will run when we're finished.\n\n\t// make the map\n\th := new(ChannelResponse)\n\n // debug code\t\n //body, _ := ioutil.ReadAll(resp.Body)\n\t//fmt.Println(string(body))\n\n\t// decode the body into the map\n\terr = json.NewDecoder(resp.Body).Decode(&h)\n\tif err != nil {\n\t\tfmt.Println(\"Error parsing channel response line\")\n\t\tlog.Fatal(err)\n\t\treturn nil, err\n\t}\n\n\treturn h, nil\n}", "func (*WebhookResponse) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_dialogflow_v2beta1_webhook_proto_rawDescGZIP(), []int{1}\n}", "func (mf *MethodFrame) Channel() uint16 { return mf.ChannelID }", "func (a *Agent) ShutdownCh() <-chan struct{} {\n\treturn a.shutdownCh\n}", "func (c *webSocketHandshakeResponseReceivedClient) GetStream() rpcc.Stream { return c.Stream }", "func (s *Subscription) C() <-chan interface{} {\n\treturn s.channel\n}", "func PlayResp(client *http.Client) gin.HandlerFunc {\n\n\t//Define a handler function that uses the provided http client from main\n\tfn := func(c *gin.Context) {\n\n\t\t// Create a PlayerChoice variable to bind POST body JSON to, then do just that\n\t\tpc := PlayerChoice{}\n\t\tif err := c.ShouldBindWith(&pc, binding.JSON); err != nil {\n\t\t\tlog.Errorln(err)\n\t\t\tc.AbortWithStatusJSON(422, map[string]string{\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\t// Check for an empty or invalid player choice\n\t\tif pc.Player == 0 || pc.Player > 5 {\n\t\t\tlog.Errorln(\"Empty or invalid player choice.\")\n\t\t\tc.AbortWithStatusJSON(422, map[string]string{\n\t\t\t\t\"error\": \"Empty or invalid player choice\",\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\t// Grab all choices and use them to get full context for players choice\n\t\tchoices := Choices()\n\t\tchoice := choices[pc.Player-1]\n\n\t\t// Play rpsls and return the result\n\t\tresult, err := PlayGame(client, choice)\n\t\tif result == nil {\n\t\t\tc.AbortWithStatusJSON(500, map[string]string{\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\t// Call the JSON method of the Context to render the given interface into JSON\n\t\tc.JSON(\n\t\t\t// Set the HTTP status to 200 (OK)\n\t\t\thttp.StatusOK,\n\t\t\t// Pass the data that the response uses\n\t\t\tresult,\n\t\t)\n\t}\n\n\treturn gin.HandlerFunc(fn)\n\n}", "func ChannelHandler(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase http.MethodGet:\n\t\terr := fmt.Errorf(\"Unsupported method %s\", r.Method)\n\t\terrorHandler(w, r, http.StatusInternalServerError, err)\n\t\treturn\n\tcase http.MethodPost:\n\t\t// Create a new channel.\n\t\tc := &channel.Channel{}\n\t\tdecoder := json.NewDecoder(r.Body)\n\t\tvar payload *channel.CreatePayload\n\t\terr := decoder.Decode(&payload)\n\t\tif err != nil {\n\t\t\terrorHandler(w, r, http.StatusInternalServerError, err)\n\t\t\treturn\n\t\t}\n\n\t\treq := &channel.CreateRequest{Payload: payload}\n\t\tres, err := c.Create(req)\n\t\tif err != nil {\n\t\t\terrorHandler(w, r, http.StatusInternalServerError, err)\n\t\t\treturn\n\t\t}\n\t\tb, err := json.Marshal(res)\n\t\tif err != nil {\n\t\t\terrorHandler(w, r, http.StatusInternalServerError, err)\n\t\t\treturn\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write(b)\n\t\treturn\n\tcase http.MethodPut:\n\t\terr := fmt.Errorf(\"Unsupported method %s\", r.Method)\n\t\terrorHandler(w, r, http.StatusInternalServerError, err)\n\t\treturn\n\tcase http.MethodDelete:\n\t\terr := fmt.Errorf(\"Unsupported method %s\", r.Method)\n\t\terrorHandler(w, r, http.StatusInternalServerError, err)\n\t\treturn\n\tdefault:\n\t\terr := fmt.Errorf(\"Unsupported method %s\", r.Method)\n\t\terrorHandler(w, r, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n}", "func (c *Provider) ChannelProvider() fab.ChannelProvider {\n\treturn c.channelProvider\n}", "func (a *AbstractSessionChannelHandler) OnClose() {}", "func (cs *ChannelService) Channel() (apifabclient.Channel, error) {\n\treturn cs.fabricProvider.CreateChannelClient(cs.identityContext, cs.cfg)\n}", "func DecodeGrpcRespRoute(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func (this *service) CommandChannel() chan<- Command {\n\treturn this._commandChannel\n}", "func ChoicesResp(c *gin.Context) {\n\n\t// Variable that holds all possible choices in the rpsls game\n\tchoices := Choices()\n\n\t// Call the JSON method of the Context to render the given interface into JSON\n\tc.JSON(\n\t\t// Set the HTTP status to 200 (OK)\n\t\thttp.StatusOK,\n\t\t// Pass the data that the response uses\n\t\tchoices,\n\t)\n\n}", "func (o WorkerPoolOutput) Channel() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *WorkerPool) pulumi.StringOutput { return v.Channel }).(pulumi.StringOutput)\n}", "func (t *gRPCTransport) recv() <-chan pb.Message {\n\treturn t.recvChan\n}", "func (c *Client) Channel() string {\n\treturn c.channel\n}", "func (r *Resolver) Channel(args struct{ ID string }) (*channels.ChannelResolver, error) {\n\treturn channels.GetChannel(args)\n}", "func DecodeGrpcRespRouteDistinguisher(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func (c *Client) Channel(channelID discord.ChannelID) (*discord.Channel, error) {\n\tvar channel *discord.Channel\n\treturn channel, c.RequestJSON(&channel, \"GET\", EndpointChannels+channelID.String())\n}", "func (o *GetChannelsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetChannelsOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewGetChannelsUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewGetChannelsNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 500:\n\t\tresult := NewGetChannelsInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\tdata, err := ioutil.ReadAll(response.Body())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"Requested GET /ugc/v1/public/namespaces/{namespace}/users/{userId}/channels returns an error %d: %s\", response.Code(), string(data))\n\t}\n}", "func encodeGRPCSayHelloResponse(_ context.Context, grpcReply interface{}) (res interface{}, err error) {\n\treply := grpcReply.(endpoints.SayHelloResponse)\n\treturn &pb.SayHelloReply{Rs: reply.Rs}, def.GrpcEncodeError(reply.Err)\n}", "func (resp *response) CloseNotify() <-chan bool {\n\treturn resp.ResponseWriter.(http.CloseNotifier).CloseNotify()\n}", "func (ch *clientSecureChannel) readResponse() (ua.ServiceResponse, error) {\n\tch.receivingSemaphore.Lock()\n\tdefer ch.receivingSemaphore.Unlock()\n\tvar res ua.ServiceResponse\n\tvar paddingHeaderSize int\n\tvar plainHeaderSize int\n\tvar bodySize int\n\tvar paddingSize int\n\tsignatureSize := ch.securityPolicy.SymSignatureSize()\n\n\tvar bodyStream = buffer.NewPartitionAt(bufferPool)\n\tdefer bodyStream.Reset()\n\n\tvar receiveBuffer = *(bytesPool.Get().(*[]byte))\n\tdefer bytesPool.Put(&receiveBuffer)\n\n\tvar bodyDecoder = ua.NewBinaryDecoder(bodyStream, ch)\n\n\t// read chunks\n\tvar chunkCount int32\n\tvar isFinal bool\n\n\tfor !isFinal {\n\t\tchunkCount++\n\t\tif i := int32(ch.maxChunkCount); i > 0 && chunkCount > i {\n\t\t\treturn nil, ua.BadEncodingLimitsExceeded\n\t\t}\n\n\t\tcount, err := ch.Read(receiveBuffer)\n\t\tif err != nil || count == 0 {\n\t\t\treturn nil, ua.BadSecureChannelClosed\n\t\t}\n\n\t\tvar stream = bytes.NewReader(receiveBuffer[0:count])\n\t\tvar decoder = ua.NewBinaryDecoder(stream, ch)\n\n\t\tvar messageType uint32\n\t\tif err := decoder.ReadUInt32(&messageType); err != nil {\n\t\t\treturn nil, ua.BadDecodingError\n\t\t}\n\t\tvar messageLength uint32\n\t\tif err := decoder.ReadUInt32(&messageLength); err != nil {\n\t\t\treturn nil, ua.BadDecodingError\n\t\t}\n\n\t\tif count != int(messageLength) {\n\t\t\treturn nil, ua.BadDecodingError\n\t\t}\n\n\t\tswitch messageType {\n\t\tcase ua.MessageTypeChunk, ua.MessageTypeFinal:\n\t\t\t// header\n\t\t\tvar channelID uint32\n\t\t\tif err := decoder.ReadUInt32(&channelID); err != nil {\n\t\t\t\treturn nil, ua.BadDecodingError\n\t\t\t}\n\t\t\tif channelID != ch.channelID {\n\t\t\t\treturn nil, ua.BadTCPSecureChannelUnknown\n\t\t\t}\n\n\t\t\t// symmetric security header\n\t\t\tvar tokenID uint32\n\t\t\tif err := decoder.ReadUInt32(&tokenID); err != nil {\n\t\t\t\treturn nil, ua.BadDecodingError\n\t\t\t}\n\n\t\t\t// detect new token\n\t\t\tch.tokenLock.RLock()\n\t\t\tif tokenID != ch.receivingTokenID {\n\t\t\t\tch.receivingTokenID = tokenID\n\n\t\t\t\tswitch ch.securityMode {\n\t\t\t\tcase ua.MessageSecurityModeSignAndEncrypt, ua.MessageSecurityModeSign:\n\t\t\t\t\t// (re)create remote security keys for verifying, decrypting\n\t\t\t\t\tremoteSecurityKey := calculatePSHA(ch.localNonce, ch.remoteNonce, len(ch.remoteSigningKey)+len(ch.remoteEncryptingKey)+len(ch.remoteInitializationVector), ch.securityPolicyURI)\n\t\t\t\t\tjj := copy(ch.remoteSigningKey, remoteSecurityKey)\n\t\t\t\t\tjj += copy(ch.remoteEncryptingKey, remoteSecurityKey[jj:])\n\t\t\t\t\tcopy(ch.remoteInitializationVector, remoteSecurityKey[jj:])\n\n\t\t\t\t\t// update verifier and decrypter with new symmetric keys\n\t\t\t\t\tch.symVerifyHMAC = ch.securityPolicy.SymHMACFactory(ch.remoteSigningKey)\n\t\t\t\t\tif ch.securityMode == ua.MessageSecurityModeSignAndEncrypt {\n\t\t\t\t\t\tch.symDecryptingBlockCipher, _ = aes.NewCipher(ch.remoteEncryptingKey)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tch.tokenLock.RUnlock()\n\n\t\t\tplainHeaderSize = 16\n\t\t\t// decrypt\n\t\t\tif ch.securityMode == ua.MessageSecurityModeSignAndEncrypt {\n\t\t\t\tspan := receiveBuffer[plainHeaderSize:count]\n\t\t\t\tif len(span)%ch.symDecryptingBlockCipher.BlockSize() != 0 {\n\t\t\t\t\treturn nil, ua.BadDecodingError\n\t\t\t\t}\n\t\t\t\tcipher.NewCBCDecrypter(ch.symDecryptingBlockCipher, ch.remoteInitializationVector).CryptBlocks(span, span)\n\t\t\t}\n\n\t\t\t// verify\n\t\t\tswitch ch.securityMode {\n\t\t\tcase ua.MessageSecurityModeSignAndEncrypt, ua.MessageSecurityModeSign:\n\t\t\t\tsigStart := count - signatureSize\n\t\t\t\tch.symVerifyHMAC.Reset()\n\t\t\t\tch.symVerifyHMAC.Write(receiveBuffer[:sigStart])\n\t\t\t\tsig := ch.symVerifyHMAC.Sum(nil)\n\t\t\t\tif !hmac.Equal(sig, receiveBuffer[sigStart:count]) {\n\t\t\t\t\treturn nil, ua.BadSecurityChecksFailed\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// read sequence header\n\t\t\tvar unused uint32\n\t\t\tif err = decoder.ReadUInt32(&unused); err != nil {\n\t\t\t\treturn nil, ua.BadDecodingError\n\t\t\t}\n\n\t\t\tif err = decoder.ReadUInt32(&unused); err != nil {\n\t\t\t\treturn nil, ua.BadDecodingError\n\t\t\t}\n\n\t\t\t// body\n\t\t\tswitch ch.securityMode {\n\t\t\tcase ua.MessageSecurityModeSignAndEncrypt:\n\t\t\t\tif ch.securityPolicy.SymEncryptionBlockSize() > 256 {\n\t\t\t\t\tpaddingHeaderSize = 2\n\t\t\t\t\tstart := int(messageLength) - signatureSize - paddingHeaderSize\n\t\t\t\t\tpaddingSize = int(binary.LittleEndian.Uint16(receiveBuffer[start : start+2]))\n\t\t\t\t} else {\n\t\t\t\t\tpaddingHeaderSize = 1\n\t\t\t\t\tstart := int(messageLength) - signatureSize - paddingHeaderSize\n\t\t\t\t\tpaddingSize = int(receiveBuffer[start])\n\t\t\t\t}\n\t\t\t\tbodySize = int(messageLength) - plainHeaderSize - sequenceHeaderSize - paddingSize - paddingHeaderSize - signatureSize\n\n\t\t\tdefault:\n\t\t\t\tbodySize = int(messageLength) - plainHeaderSize - sequenceHeaderSize - signatureSize\n\t\t\t}\n\n\t\t\tm := plainHeaderSize + sequenceHeaderSize\n\t\t\tn := m + bodySize\n\t\t\t_, err = bodyStream.Write(receiveBuffer[m:n])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tisFinal = messageType == ua.MessageTypeFinal\n\n\t\tcase ua.MessageTypeOpenFinal:\n\t\t\t// header\n\t\t\tvar unused1 uint32\n\t\t\tif err = decoder.ReadUInt32(&unused1); err != nil {\n\t\t\t\treturn nil, ua.BadDecodingError\n\t\t\t}\n\t\t\t// asymmetric header\n\t\t\tvar unused2 string\n\t\t\tif err = decoder.ReadString(&unused2); err != nil {\n\t\t\t\treturn nil, ua.BadDecodingError\n\t\t\t}\n\t\t\tvar unused3 ua.ByteString\n\t\t\tif err := decoder.ReadByteString(&unused3); err != nil {\n\t\t\t\treturn nil, ua.BadDecodingError\n\t\t\t}\n\t\t\tif err := decoder.ReadByteString(&unused3); err != nil {\n\t\t\t\treturn nil, ua.BadDecodingError\n\t\t\t}\n\t\t\tplainHeaderSize = count - stream.Len()\n\n\t\t\t// decrypt\n\t\t\tswitch ch.securityMode {\n\t\t\tcase ua.MessageSecurityModeSignAndEncrypt, ua.MessageSecurityModeSign:\n\t\t\t\tcipherTextBlockSize := ch.localPrivateKeySize\n\t\t\t\tcipherText := make([]byte, cipherTextBlockSize)\n\t\t\t\tjj := plainHeaderSize\n\t\t\t\tfor ii := plainHeaderSize; ii < int(messageLength); ii += cipherTextBlockSize {\n\t\t\t\t\tcopy(cipherText, receiveBuffer[ii:])\n\t\t\t\t\t// decrypt with local private key.\n\t\t\t\t\tplainText, err := ch.securityPolicy.RSADecrypt(ch.localPrivateKey, cipherText)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tjj += copy(receiveBuffer[jj:], plainText)\n\t\t\t\t}\n\t\t\t\t// msg is shorter after decryption\n\t\t\t\tmessageLength = uint32(jj)\n\t\t\t}\n\n\t\t\t// verify\n\t\t\tswitch ch.securityMode {\n\t\t\tcase ua.MessageSecurityModeSignAndEncrypt, ua.MessageSecurityModeSign:\n\t\t\t\t// verify with remote public key.\n\t\t\t\tsigEnd := int(messageLength)\n\t\t\t\tsigStart := sigEnd - ch.remotePublicKeySize\n\t\t\t\terr := ch.securityPolicy.RSAVerify(ch.remotePublicKey, receiveBuffer[:sigStart], receiveBuffer[sigStart:sigEnd])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, ua.BadDecodingError\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// sequence header\n\t\t\tvar unused uint32\n\t\t\tif err = decoder.ReadUInt32(&unused); err != nil {\n\t\t\t\treturn nil, ua.BadDecodingError\n\t\t\t}\n\t\t\tif err = decoder.ReadUInt32(&unused); err != nil {\n\t\t\t\treturn nil, ua.BadDecodingError\n\t\t\t}\n\n\t\t\t// body\n\t\t\tswitch ch.securityMode {\n\t\t\tcase ua.MessageSecurityModeSignAndEncrypt, ua.MessageSecurityModeSign:\n\t\t\t\tcipherTextBlockSize := ch.localPrivateKeySize\n\t\t\t\tsignatureSize := ch.remotePublicKeySize\n\t\t\t\tif cipherTextBlockSize > 256 {\n\t\t\t\t\tpaddingHeaderSize = 2\n\t\t\t\t\tstart := int(messageLength) - signatureSize - paddingHeaderSize\n\t\t\t\t\tpaddingSize = int(binary.LittleEndian.Uint16(receiveBuffer[start : start+2]))\n\t\t\t\t} else {\n\t\t\t\t\tpaddingHeaderSize = 1\n\t\t\t\t\tstart := int(messageLength) - signatureSize - paddingHeaderSize\n\t\t\t\t\tpaddingSize = int(receiveBuffer[start])\n\t\t\t\t}\n\t\t\t\tbodySize = int(messageLength) - plainHeaderSize - sequenceHeaderSize - paddingSize - paddingHeaderSize - signatureSize\n\n\t\t\tdefault:\n\t\t\t\tbodySize = int(messageLength) - plainHeaderSize - sequenceHeaderSize // - ch.asymRemoteSignatureSize\n\t\t\t}\n\n\t\t\tm := plainHeaderSize + sequenceHeaderSize\n\t\t\tn := m + bodySize\n\t\t\tif _, err := bodyStream.Write(receiveBuffer[m:n]); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tisFinal = messageType == ua.MessageTypeOpenFinal\n\n\t\tcase ua.MessageTypeError, ua.MessageTypeAbort:\n\t\t\tvar statusCode uint32\n\t\t\tif err := decoder.ReadUInt32(&statusCode); err != nil {\n\t\t\t\treturn nil, ua.BadDecodingError\n\t\t\t}\n\t\t\tvar unused string\n\t\t\tif err = decoder.ReadString(&unused); err != nil {\n\t\t\t\treturn nil, ua.BadDecodingError\n\t\t\t}\n\t\t\tch.errCode = ua.StatusCode(statusCode)\n\t\t\treturn nil, ua.StatusCode(statusCode)\n\n\t\tdefault:\n\t\t\treturn nil, ua.BadUnknownResponse\n\t\t}\n\n\t\tif i := int64(ch.maxMessageSize); i > 0 && bodyStream.Len() > i {\n\t\t\treturn nil, ua.BadEncodingLimitsExceeded\n\t\t}\n\t}\n\n\tvar nodeID ua.NodeID\n\tif err := bodyDecoder.ReadNodeID(&nodeID); err != nil {\n\t\treturn nil, ua.BadDecodingError\n\t}\n\tvar temp interface{}\n\tswitch nodeID {\n\n\t// frequent\n\tcase ua.ObjectIDPublishResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.PublishResponse)\n\tcase ua.ObjectIDReadResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.ReadResponse)\n\tcase ua.ObjectIDBrowseResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.BrowseResponse)\n\tcase ua.ObjectIDBrowseNextResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.BrowseNextResponse)\n\tcase ua.ObjectIDTranslateBrowsePathsToNodeIDsResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.TranslateBrowsePathsToNodeIDsResponse)\n\tcase ua.ObjectIDWriteResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.WriteResponse)\n\tcase ua.ObjectIDCallResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.CallResponse)\n\tcase ua.ObjectIDHistoryReadResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.HistoryReadResponse)\n\n\t// moderate\n\tcase ua.ObjectIDGetEndpointsResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.GetEndpointsResponse)\n\tcase ua.ObjectIDOpenSecureChannelResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.OpenSecureChannelResponse)\n\tcase ua.ObjectIDCloseSecureChannelResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.CloseSecureChannelResponse)\n\tcase ua.ObjectIDCreateSessionResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.CreateSessionResponse)\n\tcase ua.ObjectIDActivateSessionResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.ActivateSessionResponse)\n\tcase ua.ObjectIDCloseSessionResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.CloseSessionResponse)\n\tcase ua.ObjectIDCreateMonitoredItemsResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.CreateMonitoredItemsResponse)\n\tcase ua.ObjectIDDeleteMonitoredItemsResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.DeleteMonitoredItemsResponse)\n\tcase ua.ObjectIDCreateSubscriptionResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.CreateSubscriptionResponse)\n\tcase ua.ObjectIDDeleteSubscriptionsResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.DeleteSubscriptionsResponse)\n\tcase ua.ObjectIDSetPublishingModeResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.SetPublishingModeResponse)\n\tcase ua.ObjectIDServiceFaultEncodingDefaultBinary:\n\t\ttemp = new(ua.ServiceFault)\n\n\t\t// rare\n\tcase ua.ObjectIDModifyMonitoredItemsResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.ModifyMonitoredItemsResponse)\n\tcase ua.ObjectIDSetMonitoringModeResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.SetMonitoringModeResponse)\n\tcase ua.ObjectIDSetTriggeringResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.SetTriggeringResponse)\n\tcase ua.ObjectIDModifySubscriptionResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.ModifySubscriptionResponse)\n\tcase ua.ObjectIDRepublishResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.RepublishResponse)\n\tcase ua.ObjectIDTransferSubscriptionsResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.TransferSubscriptionsResponse)\n\tcase ua.ObjectIDFindServersResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.FindServersResponse)\n\tcase ua.ObjectIDFindServersOnNetworkResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.FindServersOnNetworkResponse)\n\tcase ua.ObjectIDRegisterServerResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.RegisterServerResponse)\n\tcase ua.ObjectIDRegisterServer2ResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.RegisterServer2Response)\n\tcase ua.ObjectIDCancelResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.CancelResponse)\n\tcase ua.ObjectIDAddNodesResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.AddNodesResponse)\n\tcase ua.ObjectIDAddReferencesResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.AddReferencesResponse)\n\tcase ua.ObjectIDDeleteNodesResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.DeleteNodesResponse)\n\tcase ua.ObjectIDDeleteReferencesResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.DeleteReferencesResponse)\n\tcase ua.ObjectIDRegisterNodesResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.RegisterNodesResponse)\n\tcase ua.ObjectIDUnregisterNodesResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.UnregisterNodesResponse)\n\tcase ua.ObjectIDQueryFirstResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.QueryFirstResponse)\n\tcase ua.ObjectIDQueryNextResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.QueryNextResponse)\n\tcase ua.ObjectIDHistoryUpdateResponseEncodingDefaultBinary:\n\t\ttemp = new(ua.HistoryUpdateResponse)\n\tdefault:\n\t\treturn nil, ua.BadDecodingError\n\t}\n\n\t// decode fields from message stream\n\tif err := bodyDecoder.Decode(temp); err != nil {\n\t\treturn nil, ua.BadDecodingError\n\t}\n\tres = temp.(ua.ServiceResponse)\n\n\tif ch.trace {\n\t\tb, _ := json.MarshalIndent(res, \"\", \" \")\n\t\tlog.Printf(\"%s%s\", reflect.TypeOf(res).Elem().Name(), b)\n\t}\n\n\treturn res, nil\n}", "func (req *ClientRequest) Response() *ClientResponse {\n\treturn <-req.response\n}" ]
[ "0.74732906", "0.63205546", "0.6136704", "0.59820163", "0.5934196", "0.56702816", "0.5615735", "0.5534477", "0.55267626", "0.54537576", "0.545056", "0.5432424", "0.5431622", "0.53828216", "0.5352966", "0.53456414", "0.5324112", "0.5295222", "0.5273228", "0.5262387", "0.52615595", "0.5206778", "0.5195412", "0.5193813", "0.51776236", "0.51767164", "0.51647484", "0.515097", "0.5141753", "0.5114414", "0.51121515", "0.5111364", "0.51048857", "0.51002747", "0.5099279", "0.50937545", "0.50934", "0.5085173", "0.5072483", "0.5069322", "0.5066282", "0.50634867", "0.50611573", "0.50483495", "0.50472736", "0.5043678", "0.50344354", "0.5015961", "0.5010735", "0.49889264", "0.4988277", "0.49751464", "0.49681386", "0.49679345", "0.4963639", "0.49556822", "0.4945191", "0.49239436", "0.49025917", "0.48987523", "0.48951173", "0.4878258", "0.48635283", "0.48526004", "0.48439023", "0.482902", "0.4823266", "0.4808298", "0.47962257", "0.4795456", "0.4781594", "0.47814518", "0.47797838", "0.4779471", "0.4777777", "0.47768956", "0.47757176", "0.47725648", "0.47550207", "0.4751073", "0.4749285", "0.4748528", "0.4738392", "0.47350425", "0.47341892", "0.4731087", "0.47235644", "0.47218412", "0.47209004", "0.47195607", "0.4718661", "0.4718084", "0.47160497", "0.4714501", "0.47006273", "0.46998817", "0.4696869", "0.46932188", "0.4687726", "0.46827462" ]
0.739178
1
LeftChopstick returns the ID of the philosopher's currently reserved left chopstick. If no left chopstick is reserved, then 1 is returned.
func (pd *philosopherData) LeftChopstick() int { return pd.leftChopstick }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pd *philosopherData) SetLeftChop(leftChop int) {\n\tpd.leftChopstick = leftChop\n}", "func (pb *PhilosopherBase) LeftPhilosopher() Philosopher {\n\t// Add NPhils to avoid a negative index\n\tindex := (pb.ID + NPhils - 1) % NPhils\n\treturn Philosophers[index]\n}", "func (pb *PhilosopherBase) leftForkID() int {\n\treturn pb.ID\n}", "func (o *TileBounds) GetLeft() int32 {\n\tif o == nil || o.Left == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Left\n}", "func GetLeftIndex(n int) int {\n\treturn 2*n + 1\n}", "func (me *BitStream) Left() int {\n\treturn me.Bits - me.Index\n}", "func (unpacker *BitUnpacker) Left() uint32 {\n\treturn unpacker.size - (unpacker.pbyte*8 + unpacker.pbit)\n}", "func (pd *philosopherData) RightChopstick() int {\n\treturn pd.rightChopstick\n}", "func left(i int) int {\n\treturn i*2 + 1\n}", "func (o *WorkbookChart) GetLeft() AnyOfnumberstringstring {\n\tif o == nil || o.Left == nil {\n\t\tvar ret AnyOfnumberstringstring\n\t\treturn ret\n\t}\n\treturn *o.Left\n}", "func (pb *PhilosopherBase) LeftFork() Fork {\n\treturn Forks[pb.leftForkID()]\n}", "func left(index int) int {\n\treturn 2*index + 1\n}", "func left(i int) int {\r\n\treturn (i * 2) + 1\r\n}", "func left(x uint) uint {\n\tif level(x) == 0 {\n\t\treturn x\n\t}\n\n\treturn x ^ (0x01 << (level(x) - 1))\n}", "func (o *WorkbookChart) HasLeft() bool {\n\tif o != nil && o.Left != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func Left(i int) int {\n\treturn 2 * i\n}", "func (p Permutator) left() int {\n\treturn (p.amount - p.index) + 1\n}", "func (o *TileBounds) GetLeftOk() (*int32, bool) {\n\tif o == nil || o.Left == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Left, true\n}", "func (p Permutator) Left() int {\n\t<- p.idle\n\tremaining := p.left()\n\tp.idle <- true\n\treturn remaining\n}", "func (g Game) Left() []Player {\n\tvar players []Player\n\tif isEmptyPlayer(g.LeftPlayerTwo) {\n\t\tplayers = make([]Player, 1)\n\t\tplayers[0] = g.LeftPlayerOne.Player\n\t} else {\n\t\tplayers = make([]Player, 2)\n\t\tplayers[0] = g.LeftPlayerOne.Player\n\t\tplayers[1] = g.LeftPlayerTwo.Player\n\t}\n\treturn players\n}", "func (o *WorkbookChart) GetLeftOk() (AnyOfnumberstringstring, bool) {\n\tif o == nil || o.Left == nil {\n\t\tvar ret AnyOfnumberstringstring\n\t\treturn ret, false\n\t}\n\treturn *o.Left, true\n}", "func isLeftHand(k int) bool { return k < 21 }", "func (b *Board) checkLeft(row int, column int) {\n\tif b.connected < 3 && column > 0 {\n\t\tif b.positions[row][column] == b.positions[row][column-1] {\n\t\t\tb.connected++\n\t\t\tb.checkLeft(row, column-1)\n\t\t}\n\t}\n}", "func (self SimpleInterval) Left() float64 {\n\treturn self.LR[0]\n}", "func (board *Board) Left() *Board {\n\tblankPosition := board.PositionOfBlank()\n\tif blankPosition%board.Dimension == 0 {\n\t\treturn nil\n\t}\n\n\tclone := board.Clone()\n\tclone.move = LEFT\n\ttile := clone.GetTileAt(blankPosition - 1)\n\tclone.SetTileAt(blankPosition-1, BLANK)\n\tclone.SetTileAt(blankPosition, tile)\n\tclone.cost = clone.g + clone.Cost()\n\treturn clone\n}", "func (b *Bound) Left() float64 {\n\treturn b.sw[0]\n}", "func (b *BHeap) left(i int) int {\n\treturn i<<1 + 1\n}", "func (g *Game) GetOrCalculateLeftScore() int {\n\tif g.LeftScore == 0 {\n\t\t_, left := g.GameScore()\n\t\treturn int(left)\n\t}\n\treturn g.LeftScore\n}", "func (o *WorkbookChart) SetLeft(v AnyOfnumberstringstring) {\n\to.Left = &v\n}", "func (this *GpioReader) LeftButton() bool {\n\tcount, err := this.leftButtonFile.Read(this.data)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif count != 2 {\n\t\tlog.Fatal(\"Expected 2 bytes for left button read and got\", count)\n\t}\n\n\t// seek back to beginning of file\n\t_, err = this.leftButtonFile.Seek(0, 0)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tbuttonDown := this.data[0] == 48 // ascii '0'\n\n\treturn buttonDown\n\n\t// if buttonDown != this.leftPrevious {\n\t// \tthis.leftPrevious = buttonDown\n\n\t// \tif buttonDown {\t\t\t\n\t// \t\treturn ButtonPush\n\t// \t} else {\n\t// \t\treturn ButtonRelease\n\t// \t}\n\t// }\n}", "func (d Data) FaceLeft() bool {\n\treturn d.faceLeft\n}", "func leftChild(i int) int {\n\treturn (i * 2) + 1\n}", "func (tm *Term) FixLeft() error {\n\ttm.FixCols = ints.MaxInt(tm.FixCols-1, 0)\n\treturn tm.Draw()\n}", "func (m *IntervalMutation) OldStockID(ctx context.Context) (v int, err error) {\n\tif !m.op.Is(OpUpdateOne) {\n\t\treturn v, errors.New(\"OldStockID is only allowed on UpdateOne operations\")\n\t}\n\tif m.id == nil || m.oldValue == nil {\n\t\treturn v, errors.New(\"OldStockID requires an ID field in the mutation\")\n\t}\n\toldValue, err := m.oldValue(ctx)\n\tif err != nil {\n\t\treturn v, fmt.Errorf(\"querying old value for OldStockID: %w\", err)\n\t}\n\treturn oldValue.StockID, nil\n}", "func (m *SplitRegionResponse) GetLeft() *metapb.Region {\n\tif m != nil {\n\t\treturn m.Left\n\t}\n\treturn nil\n}", "func (o *os) GetPowerPercentLeft() gdnative.Int {\n\to.ensureSingleton()\n\t//log.Println(\"Calling _OS.GetPowerPercentLeft()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"_OS\", \"get_power_percent_left\")\n\n\t// Call the parent method.\n\t// int\n\tretPtr := gdnative.NewEmptyInt()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := gdnative.NewIntFromPointer(retPtr)\n\treturn ret\n}", "func GetSmsLeft(lastname, login, pass string) (SmsLeft, error) {\n\tclient, err := newHTTPClient()\n\tif err != nil {\n\t\treturn NoSmsLeft, errors.Wrap(err, \"unable to create httpClient\")\n\t}\n\n\tloginner := httpLoginner{client}\n\tif err = loginner.Login(lastname, login, pass); err != nil {\n\t\treturn NoSmsLeft, errors.Wrap(err, \"unable to login\")\n\t}\n\n\tsmsLeftGetter := &httpSmsLeftGetter{client}\n\treturn smsLeftGetter.Get()\n}", "func (*ChannelsGetLeftChannelsRequest) TypeID() uint32 {\n\treturn ChannelsGetLeftChannelsRequestTypeID\n}", "func (ll *LinkedList) PopLeft() (int, bool) {\n\tif ll.IsEmpty() {\n\t\treturn -1, false\n\t}\n\n\telement := ll.start.value\n\n\t// single element\n\tif ll.start == ll.end {\n\t\tll.Clear()\n\t} else {\n\t\tll.start = ll.start.next\n\t\tll.start.previous = nil\n\t\tll.length--\n\t}\n\n\treturn element, true\n}", "func LeftChild(index, depth uint) (uint, error) {\n\tif index&1 == 0 {\n\t\treturn 0, errors.New(\"No left child\")\n\t}\n\tif depth == 0 {\n\t\tdepth = Depth(index)\n\t}\n\n\treturn Index(depth-1, Offset(index, depth)*2), nil\n}", "func (s SGTree) leftChild(treeIndex int) int {\n\treturn 2*treeIndex + 1\n}", "func (c *Client) LeftTeamName() string {\n\treturn c.lTeamName\n}", "func IsLowerLeft(key uint32) bool {\n\treturn ((key & 0x30) == 0x20)\n}", "func (p *CockroachDriver) LeftQuote() byte {\n\treturn '\"'\n}", "func (o *TileBounds) HasLeft() bool {\n\tif o != nil && o.Left != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func getCharsLeftCount(limit int, position Point, dir Point) int {\n\tleft := 0\n\t// increase counter while position is not out of boundaries of grid\n\tfor !outOfBound(position, limit) {\n\t\tposition.x += dir.x\n\t\tposition.y += dir.y\n\t\tleft++\n\t}\n\n\treturn left\n}", "func (mg *MoveGen) generatePawnLeftAttack(pawns uint64) uint64 {\n\tarea := uint64(0x7f7f7f7f7f7f7f7f)\n\tvar attacks uint64\n\tvar attackDirection int\n\tif mg.isWhite() {\n\t\tattackDirection = 9 // promotions\n\t\tattacks = (pawns & area) << 9\n\t\tattacks &= mg.state.colours[0] // TODO: en passant\n\t} else {\n\t\tattackDirection = -7 // promotions\n\t\tattacks = (pawns & area) >> 7\n\t\tattacks &= mg.state.colours[1] // TODO: en passant\n\t}\n\n\tcache := attacks\n\n\t// promotions\n\tattacks ^= mg.generatePromotions(attackDirection, attacks)\n\n\tmg.mover.SetFlags(4) // 0b0100, capture\n\tfor i := LSB(attacks); i != 64; i = NLSB(&attacks, i) {\n\t\tmg.mover.SetFrom(uint16(i + attackDirection))\n\t\tmg.mover.SetTo(uint16(i))\n\t\tmg.moves[mg.index] = mg.mover.GetMove()\n\t\tmg.index++\n\t}\n\n\treturn cache\n}", "func ShiftLeft(input []byte, shiftNum int) (result []byte, leftMostCarryFlag bool) {\n\tif shiftNum >= 1 {\n\t\tresult = make([]byte, len(input))\n\t\tcopy(result, input)\n\n\t\tfor i := 0; i < len(result); i++ {\n\t\t\tcarryFlag := ((result[i] & 0x80) == 0x80)\n\n\t\t\tif i > 0 && carryFlag {\n\t\t\t\tresult[i-1] |= 0x01\n\t\t\t} else if i == 0 {\n\t\t\t\tleftMostCarryFlag = carryFlag\n\t\t\t}\n\n\t\t\tresult[i] <<= 1\n\t\t}\n\n\t\tif shiftNum == 1 {\n\t\t\treturn result, leftMostCarryFlag\n\t\t}\n\t\treturn ShiftLeft(result, shiftNum-1)\n\t}\n\n\treturn input, false\n}", "func (l *Label) left(g *Graph) (*Label, *DataError) {\n Assert(nilLabel, l != nil)\n Assert(nilGraph, g != nil)\n Assert(nilLabelStore, g.labelStore != nil)\n \n return g.labelStore.findAllowZero(l.l)\n}", "func (m *Machine) Left() {\n\tfmt.Printf(\">> LEFT\\n\")\n\t// If we're at the 0th position, then we need to expand our tape array:\n\tif m.position == 0 {\n\t\tsize := len(m.Tape)\n\t\tm.Tape = append(make([]Cell, size), m.Tape...)\n\t\tm.position += size\n\t}\n\n\tm.position -= 1\n}", "func (v *TypePair) GetLeft() (o *Type) {\n\tif v != nil {\n\t\to = v.Left\n\t}\n\treturn\n}", "func (o *os) GetPowerSecondsLeft() gdnative.Int {\n\to.ensureSingleton()\n\t//log.Println(\"Calling _OS.GetPowerSecondsLeft()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"_OS\", \"get_power_seconds_left\")\n\n\t// Call the parent method.\n\t// int\n\tretPtr := gdnative.NewEmptyInt()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := gdnative.NewIntFromPointer(retPtr)\n\treturn ret\n}", "func LeftSpan(index, depth uint) uint {\n\tif index&1 == 0 {\n\t\treturn index\n\t}\n\tif depth == 0 {\n\t\tdepth = Depth(index)\n\t}\n\n\treturn Offset(index, depth) * twoPow(depth+1)\n}", "func (e Equation) Left() Type {\n\treturn e.left\n}", "func (h *heap) leftChildIndex(i int64) int64 {\n\treturn i*2 + 1\n}", "func (this *BigInteger) ShiftLeft(n int64) *BigInteger {\n\tvar r *BigInteger = NewBigInteger()\n\tif n < 0 {\n\t\tthis.RShiftTo(-n, r)\n\t} else {\n\t\tthis.LShiftTo(n, r)\n\t}\n\treturn r\n}", "func (c *Console) Left(n Int) *Console {\n\tPrint(_CSI + n.ToString() + \"D\")\n\treturn c\n}", "func (o *TileBounds) SetLeft(v int32) {\n\to.Left = &v\n}", "func LeftShift(scope *Scope, x tf.Output, y tf.Output) (z tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"LeftShift\",\n\t\tInput: []tf.Input{\n\t\t\tx, y,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func NewLeftDrone(ctx *middleware.Context, handler LeftDroneHandler) *LeftDrone {\n\treturn &LeftDrone{Context: ctx, Handler: handler}\n}", "func (o DashboardSpacingPtrOutput) Left() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DashboardSpacing) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Left\n\t}).(pulumi.StringPtrOutput)\n}", "func (d *Deque) Left() interface{} {\n\treturn d.left[d.leftOff]\n}", "func (v Vect) TurnLeft() Vect {\n\tif v.X == 0 {\n\t\tif v.Y == 1 {\n\t\t\treturn Vect{-1, 0}\n\t\t}\n\t\tif v.Y == -1 {\n\t\t\treturn Vect{1, 0}\n\t\t}\n\t}\n\tif v.X == -1 {\n\t\treturn Vect{0, -1}\n\t}\n\treturn Vect{0, 1}\n}", "func (d *Deque) PopLeft() (res interface{}) {\n\tres, d.left[d.leftOff] = d.left[d.leftOff], nil\n\td.leftOff++\n\tif d.leftOff == blockSize {\n\t\td.leftOff = 0\n\t\td.leftIdx = (d.leftIdx + 1) % len(d.blocks)\n\t\td.left = d.blocks[d.leftIdx]\n\t}\n\treturn\n}", "func shift_left_once(key_chunk string) string {\n\tshifted := \"\"\n\tfor i := 1; i < 28; i++ {\n\t\tshifted += string(key_chunk[i])\n\t}\n\tshifted += string(key_chunk[0])\n\treturn shifted\n}", "func (d *Display) CursorLeft() error {\n\t_, err := d.port.Write([]byte(CursorLeft))\n\treturn err\n}", "func (tree *DNFTree) CreateLeftChild(nodeID int, phi br.ClauseSet, isFinal bool) int {\n\tif debug {\n\t\tif nodeID < 0 {\n\t\t\tpanic(\"Expected nodeID >= 0 in CreateLeftChild\")\n\t\t}\n\t\tif nodeID >= len(tree.Content) {\n\t\t\tpanic(\"Expected nodeID < len(content) in CreateLeftChild\")\n\t\t}\n\t}\n\tn := tree.Content[nodeID]\n\tid := tree.CreateNodeEntry(phi, n.depth+1, isFinal)\n\tn.leftChild = id\n\treturn id\n}", "func ShiftLeft0(t TermT, n uint32) TermT {\n\treturn TermT(C.yices_shift_left0(C.term_t(t), C.uint32_t(n)))\n}", "func (r *Reactions) GetLaugh() int {\n\tif r == nil || r.Laugh == nil {\n\t\treturn 0\n\t}\n\treturn *r.Laugh\n}", "func (tree *Tree) Left() *Node {\n\tvar parent *Node\n\tcurrent := tree.Root\n\tfor current != nil {\n\t\tparent = current\n\t\tcurrent = current.Left\n\t}\n\treturn parent\n}", "func (e *LineEditor) CursorLeft() {\n\n\tif e.Cx > 0 {\n\t\te.Cx--\n\t}\n}", "func RotateLeft(x uint, k int) uint {\n\tif UintSize == 32 {\n\t\treturn uint(RotateLeft32(uint32(x), k))\n\t}\n\treturn uint(RotateLeft64(uint64(x), k))\n}", "func (c *Controller) Left() {\n\tc.Target.Translate(-10, 0)\n\tif c.Target.Collider.col.left == true {\n\t\tc.Target.Translate(11, 0)\n\t}\n}", "func (gc *LinearConverter) CropLeft() int {\n\treturn 0\n}", "func MoveLeftRename(cf CornerFace) CornerFace {\n\tswitch cf {\n\tcase FACE_FRONT:\n\t\treturn FACE_RIGHT\n\tcase FACE_LEFT:\n\t\treturn FACE_FRONT\n\tcase FACE_BACK:\n\t\treturn FACE_LEFT\n\tcase FACE_RIGHT:\n\t\treturn FACE_BACK\n\t}\n\treturn cf // no translation for top needed\n}", "func (g *G) ShipsLeft() []ShipType {\n\t/* Fill in this Function */\n\treturn []ShipType{}\n}", "func (mmEphemeralMode *GatewayMock) EphemeralModeBeforeCounter() uint64 {\n\treturn mm_atomic.LoadUint64(&mmEphemeralMode.beforeEphemeralModeCounter)\n}", "func (g Game) LeftPlayerNames() []string {\n\tresult := make([]string, 0, 2)\n\tfor _, n := range g.Left() {\n\t\tresult = append(result, n.Nickname)\n\t}\n\treturn result\n}", "func (b *TestDriver) Left(val int) error {\n\tlog.Printf(\"Left: %d\", val)\n\treturn nil\n}", "func (mt MerkleTree) LeftTree() *MerkleTree {\n\treturn mt.leftTree\n}", "func (m *HostNetworkMock) GetNodeIDMinimockPreCounter() uint64 {\n\treturn atomic.LoadUint64(&m.GetNodeIDPreCounter)\n}", "func NewShiftLeft(left, right sql.Expression) *BitOp {\n\treturn NewBitOp(left, right, sqlparser.ShiftLeftStr)\n}", "func (eln *EmptyLeafNode) GetLeftChild() Node {\n\treturn nil\n}", "func RotateLeft32(x uint32, k int) uint32 {\n\tconst n = 32\n\ts := uint(k) & (n - 1)\n\treturn x<<s | x>>(n-s)\n}", "func ShiftLeft1(t TermT, n uint32) TermT {\n\treturn TermT(C.yices_shift_left1(C.term_t(t), C.uint32_t(n)))\n}", "func (b *TestDriver) LeftFlip() (err error) {\n\tb.Publish(Rolling, true)\n\treturn nil\n}", "func (g *GroupCallParticipant) SetLeft(value bool) {\n\tif value {\n\t\tg.Flags.Set(1)\n\t\tg.Left = true\n\t} else {\n\t\tg.Flags.Unset(1)\n\t\tg.Left = false\n\t}\n}", "func (n *Node) LeftRed() bool {\n\treturn n.Left != nil && n.Left.Color == Red\n}", "func (o DashboardSpacingOutput) Left() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DashboardSpacing) *string { return v.Left }).(pulumi.StringPtrOutput)\n}", "func (m *IntervalMutation) StockID() (r int, exists bool) {\n\tv := m.stock\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func MaskLeft(s string) string {\n\trs := []rune(s)\n\tfor i := 0; i < len(rs)-4; i++ {\n\t\trs[i] = 'X'\n\t}\n\treturn string(rs)\n}", "func (_Flopper *FlopperSession) Kicks() (*big.Int, error) {\n\treturn _Flopper.Contract.Kicks(&_Flopper.CallOpts)\n}", "func leftAngleCode(data []byte) int {\n\ti := 1\n\tfor i < len(data) {\n\t\tif data[i] == '>' {\n\t\t\tbreak\n\t\t}\n\t\tif !isnum(data[i]) {\n\t\t\treturn 0\n\t\t}\n\t\ti++\n\t}\n\treturn i\n}", "func Left(s string, n int) string {\n\tif n < 1 {\n\t\treturn \"\"\n\t}\n\trunes := []rune(s)\n\tif n >= len(runes) {\n\t\treturn s\n\t}\n\n\treturn string(runes[:n])\n\n}", "func lexLeftDelim(l *lexer) stateFn {\n\tl.pos += Pos(len(l.leftDelim))\n\tif strings.HasPrefix(l.input[l.pos:], leftComment) {\n\t\treturn lexComment\n\t}\n\tl.emit(itemLeftDelim)\n\tl.parenDepth = 0\n\treturn lexInsideAction\n}", "func RotateLeft(t TermT, n uint32) TermT {\n\treturn TermT(C.yices_rotate_left(C.term_t(t), C.uint32_t(n)))\n}", "func ProcessLeftMove(mySnake *snake.Snake, myBoard *board.GameBoard) (bool, bool) {\n\tif mySnake.Head.Y-1 < 0 {\n\t\terrorcatch.ReportError(errors.New(\"wall collision\"))\n\t\treturn false, true\n\t}\n\ttargetLocation := myBoard.Data[mySnake.Head.X][mySnake.Head.Y-1]\n\tif targetLocation.Status > 0 {\n\t\tif targetLocation.Status == 2 {\n\t\t\terrorcatch.ReportError(errors.New(\"backward move\"))\n\t\t\treturn false, true\n\t\t} else {\n\t\t\terrorcatch.ReportError(errors.New(\"self collision\"))\n\t\t\treturn false, true\n\t\t}\n\t}\n\tif targetLocation.Status == -1 {\n\t\tmySnake.UpdateSnake(targetLocation, true)\n\t} else {\n\t\tmySnake.UpdateSnake(targetLocation, false)\n\t}\n\tmyBoard.UpdateSnakeOnBoard(*mySnake)\n\tif mySnake.Tail.Status == (myBoard.Breadth * myBoard.Length) {\n\t\treturn true, false\n\t}\n\tif targetLocation.Status == -1 {\n\t\tfood := food.CreateFood(myBoard.Data)\n\t\tmyBoard.UpdateFoodOnBoard(food)\n\t}\n\treturn false, false\n}", "func (pb *PhilosopherBase) rightForkID() int {\n\treturn (pb.ID + 1) % NPhils\n}", "func (m *ConsensusNetworkMock) GetNodeIDMinimockPreCounter() uint64 {\n\treturn atomic.LoadUint64(&m.GetNodeIDPreCounter)\n}", "func (s *MovesSuite) TestPawnTakesLeft() {\n\tmoves := s.validateMovesByFEN(\n\t\t\"8/8/8/3n4/4P3/8/8/8 w - - 0 1\",\n\t\tengine.TT(\"e4\"),\n\t\t[]engine.Tile{\n\t\t\tengine.TT(\"e5\"),\n\t\t\tengine.TT(\"d5\"),\n\t\t},\n\t)\n\n\t// can move 2 pieces forward\n\tassert.Equal(s.T(), len(moves), 2)\n\n\tmoves = s.validateMovesByFEN(\n\t\t\"8/8/8/3nQ3/4P3/8/8/8 w - - 0 1\",\n\t\tengine.TT(\"e4\"),\n\t\t[]engine.Tile{\n\t\t\tengine.TT(\"d5\"),\n\t\t},\n\t)\n\n\t// can move 2 pieces forward\n\tassert.Equal(s.T(), 1, len(moves))\n}" ]
[ "0.65881366", "0.6262872", "0.6020674", "0.599668", "0.5949332", "0.5799947", "0.57248265", "0.5690946", "0.5689781", "0.56741303", "0.5670073", "0.5580993", "0.5556395", "0.5534706", "0.5498963", "0.540528", "0.5384801", "0.53816605", "0.537523", "0.53650707", "0.5326458", "0.52840954", "0.52839136", "0.52747315", "0.52714056", "0.52552617", "0.5246294", "0.52420247", "0.5158021", "0.51548994", "0.51385003", "0.5119793", "0.5116621", "0.5097901", "0.50951505", "0.5037096", "0.5037002", "0.5021442", "0.50024515", "0.49906757", "0.49720442", "0.49573407", "0.4932662", "0.49190146", "0.4901754", "0.4900757", "0.48929584", "0.4886118", "0.4884018", "0.488162", "0.48813096", "0.48723307", "0.4871867", "0.48686686", "0.48657638", "0.48594022", "0.48438004", "0.48142", "0.4795871", "0.47857532", "0.47773904", "0.47734636", "0.4771342", "0.47703686", "0.47695145", "0.47604766", "0.47599697", "0.4747766", "0.4741318", "0.4738072", "0.47316682", "0.47234637", "0.47169635", "0.4716194", "0.47089937", "0.4695814", "0.4691717", "0.46851432", "0.4682827", "0.46823606", "0.46757674", "0.46754104", "0.4656764", "0.46565688", "0.46563485", "0.46466374", "0.46357864", "0.46346736", "0.46253487", "0.46189383", "0.46164578", "0.46093056", "0.46040112", "0.45942378", "0.45929343", "0.45853618", "0.45828912", "0.45758542", "0.4575426", "0.4555334" ]
0.7724993
0
RightChopstick returns the ID of the philosopher's currently reserved right chopstick. If no right chopstick is reserved, then 1 is returned.
func (pd *philosopherData) RightChopstick() int { return pd.rightChopstick }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pd *philosopherData) LeftChopstick() int {\n\treturn pd.leftChopstick\n}", "func (pb *PhilosopherBase) rightForkID() int {\n\treturn (pb.ID + 1) % NPhils\n}", "func (pd *philosopherData) SetRightChop(rightChop int) {\n\tpd.rightChopstick = rightChop\n}", "func (pb *PhilosopherBase) RightPhilosopher() Philosopher {\n\tindex := (pb.ID + 1) % NPhils\n\treturn Philosophers[index]\n}", "func right(i int) int {\n\treturn i*2 + 2\n}", "func GetRightIndex(n int) int {\n\treturn 2*n + 2\n}", "func right(index int) int {\n\treturn 2*index + 2\n}", "func right(i int) int {\r\n\treturn (i * 2 ) + 2\r\n}", "func (s Square) Right() int {\n\treturn s.left + s.width\n}", "func (pb *PhilosopherBase) RightFork() Fork {\n\treturn Forks[pb.rightForkID()]\n}", "func SocketRight(idx int) string {\n\tswitch idx {\n\tcase 1, 2, 5:\n\t\treturn \"socketRight\"\n\t}\n\treturn \"\"\n}", "func (b *BHeap) right(i int) int {\n\treturn i<<1 + 2\n}", "func rightChild(i int) int {\n\treturn (i * 2) + 2\n}", "func Right(i int) int {\n\treturn 2*i + 1\n}", "func right(x uint, n uint) uint {\n\tif level(x) == 0 {\n\t\treturn x\n\t}\n\n\tr := x ^ (0x03 << (level(x) - 1))\n\tfor r > 2*(n-1) {\n\t\tr = left(r)\n\t}\n\treturn r\n}", "func (m *CUserMsg_ParticleManager_UpdateParticleOrient) GetRight() *CMsgVector {\n\tif m != nil {\n\t\treturn m.Right\n\t}\n\treturn nil\n}", "func (m *PatientrightsMutation) PatientrightsPatientrightstypeID() (id int, exists bool) {\n\tif m._PatientrightsPatientrightstype != nil {\n\t\treturn *m._PatientrightsPatientrightstype, true\n\t}\n\treturn\n}", "func (m *RoomdetailMutation) Roomprice() (r int, exists bool) {\n\tv := m.roomprice\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (m *PatientrightstypeMutation) PatientrightstypeAbilitypatientrightsID() (id int, exists bool) {\n\tif m._PatientrightstypeAbilitypatientrights != nil {\n\t\treturn *m._PatientrightstypeAbilitypatientrights, true\n\t}\n\treturn\n}", "func rightShift(s *keyboard.State) (*Violation, error) {\n if len(s.LastCharacters) < 1 {\n return nil, status.Error(\n codes.FailedPrecondition,\n \"rightshift vimprovement check ran before character input was received.\",\n )\n }\n if s.RightShiftDown && rightShiftViolatingKeys[s.LastCharacters[0]] {\n return &rsViolation, nil\n }\n return nil, nil\n}", "func (h *heap) rightChildIndex(i int64) int64 {\n\treturn i*2 + 2\n}", "func (s SGTree) rightChild(treeIndex int) int {\n\treturn 2*treeIndex + 2\n}", "func (self *TileSprite) Right() int{\n return self.Object.Get(\"right\").Int()\n}", "func botRoyalty(hr ofc.Handrank) int {\n\treturn botRoyaltyTable[hr[0]]\n}", "func (this *GpioReader) RightButton() bool {\n\tcount, err := this.rightButtonFile.Read(this.data)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif count != 2 {\n\t\tlog.Fatal(\"Expected 2 bytes for right button read and got\", count)\n\t}\n\n\t// seek back to beginning of file\n\t_, err = this.rightButtonFile.Seek(0, 0)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tbuttonDown := this.data[0] == 48 // ascii '0'\n\n\treturn buttonDown\n\n\t// if buttonDown != this.rightPrevious {\n\t// \tthis.rightPrevious = buttonDown\n\n\t// \tif buttonDown {\n\t// \t\treturn ButtonPush\n\t// \t} else {\n\t// \t\treturn ButtonRelease\n\t// \t}\n\t// }\n}", "func (m *SplitRegionResponse) GetRight() *metapb.Region {\n\tif m != nil {\n\t\treturn m.Right\n\t}\n\treturn nil\n}", "func (g *Game) GetOrCalculateRightScore() int {\n\tif g.RightScore == 0 {\n\t\tright, _ := g.GameScore()\n\t\treturn int(right)\n\t}\n\treturn g.RightScore\n}", "func (m NoSides) GetSideComplianceID() (v string, err quickfix.MessageRejectError) {\n\tvar f field.SideComplianceIDField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func (s *Scope) GetRight() raytracing.Vector {\n\treturn *s.Right\n}", "func (self SimpleInterval) Right() float64 {\n\treturn self.LR[1]\n}", "func (m NoSides) GetSecondaryClOrdID() (v string, err quickfix.MessageRejectError) {\n\tvar f field.SecondaryClOrdIDField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func (b *Bound) Right() float64 {\n\treturn b.ne[0]\n}", "func (m *IntervalMutation) StockID() (r int, exists bool) {\n\tv := m.stock\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (pd *philosopherData) HasBothChopsticks() bool {\n\treturn (pd.leftChopstick >= 0) && (pd.rightChopstick >= 0)\n}", "func RightChild(index, depth uint) (uint, error) {\n\tif index&1 == 0 {\n\t\treturn 0, errors.New(\"No right child\")\n\t}\n\tif depth == 0 {\n\t\tdepth = Depth(index)\n\t}\n\n\treturn Index(depth-1, 1+(Offset(index, depth)*2)), nil\n}", "func (c *Client) RightTeamName() string {\n\treturn c.rTeamName\n}", "func (p *CockroachDriver) RightQuote() byte {\n\treturn '\"'\n}", "func (r *Reactions) GetHooray() int {\n\tif r == nil || r.Hooray == nil {\n\t\treturn 0\n\t}\n\treturn *r.Hooray\n}", "func (db *DB) readReplicaRR() (uint32, *sql.DB) {\n\tif db.readReplicasCount == 1 {\n\t\tdb.RLock()\n\t\tdefer db.RUnlock()\n\t\treturn 0, db.readReplicas[0]\n\t}\n\n\t// db.count may overflow and start from 0\n\tidx := atomic.AddUint32(&db.count, 1) % db.readReplicasCount\n\tdb.RLock()\n\treadReplica := db.readReplicas[idx]\n\tdb.RUnlock()\n\n\t// if the readReplica is not sick, return it\n\tdb.sickMu.RLock()\n\t_, sick := db.sick[idx]\n\tdb.sickMu.RUnlock()\n\tif !sick {\n\t\treturn idx, readReplica\n\t}\n\n\t// return the next readReplica\n\tidx = atomic.AddUint32(&db.count, 1) % db.readReplicasCount\n\tdb.RLock()\n\tdefer db.RUnlock()\n\treturn idx, db.readReplicas[idx]\n}", "func (g Game) Right() []Player {\n\tvar players []Player\n\tif isEmptyPlayer(g.RightPlayerTwo) {\n\t\tplayers = make([]Player, 1)\n\t\tplayers[0] = g.RightPlayerOne.Player\n\t} else {\n\t\tplayers = make([]Player, 2)\n\t\tplayers[0] = g.RightPlayerOne.Player\n\t\tplayers[1] = g.RightPlayerTwo.Player\n\t}\n\treturn players\n}", "func (c *Console) Right(n Int) *Console {\n\tPrint(_CSI + n.ToString() + \"C\")\n\treturn c\n}", "func (h *heap) rightSiblingIndex(i int64) int64 {\n\treturn i + 1\n}", "func midRoyalty(hr ofc.Handrank) int {\n\treturn midRoyaltyTable[hr[0]]\n}", "func (tm *Term) FixRight() error {\n\ttm.FixCols++ // no obvious max\n\treturn tm.Draw()\n}", "func (c Chessboard) rookCastleKingsidePosition(color int) int {\n if color == 0 {\n return 63\n }\n\n return 7\n}", "func (d *Deque) Right() interface{} {\n\tif d.rightOff > 0 {\n\t\treturn d.right[d.rightOff-1]\n\t} else {\n\t\treturn d.blocks[(d.rightIdx-1+len(d.blocks))%len(d.blocks)][blockSize-1]\n\t}\n}", "func indexOfFirstRightBracket(key string) int {\n\treturn (rightBracketRegExp.FindStringIndex(key)[1] - 1)\n}", "func isLeftHand(k int) bool { return k < 21 }", "func (b *ballotMaster) GetWinner() (string, bool) {\n\tb.mutex.Lock()\n\tdefer b.mutex.Unlock()\n\n\tif b.winner != nil {\n\t\treturn b.winner.proposed.GetCndId(), true\n\t}\n\n\treturn \"\", false\n}", "func (o DashboardSpacingPtrOutput) Right() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DashboardSpacing) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Right\n\t}).(pulumi.StringPtrOutput)\n}", "func (pd *philosopherData) SetLeftChop(leftChop int) {\n\tpd.leftChopstick = leftChop\n}", "func (m *RoomdetailMutation) PledgeID() (id int, exists bool) {\n\tif m.pledge != nil {\n\t\treturn *m.pledge, true\n\t}\n\treturn\n}", "func GetGoID() int64", "func (pb *PhilosopherBase) LeftPhilosopher() Philosopher {\n\t// Add NPhils to avoid a negative index\n\tindex := (pb.ID + NPhils - 1) % NPhils\n\treturn Philosophers[index]\n}", "func (v *TypePair) GetRight() (o *Type) {\n\tif v != nil {\n\t\to = v.Right\n\t}\n\treturn\n}", "func getAvailableRoomId() int {\n\tfor i, used := range roomIdsFlag {\n\t\tif !used {\n\t\t\troomIdsFlag[i] = true\n\t\t\treturn i + 1\n\t\t}\n\t}\n\treturn 0\n}", "func (leftDiner *Diner) HookupRightChannel(rightDiner *Diner) {\n\tif leftDiner.rightChannel != nil {\n\t\tlog.Panic(\"Left diner: %v right channel has already been set\", leftDiner)\n\t}\n\tlog.Debug(\"%v hooking to %v\", leftDiner, rightDiner)\n\tleftDiner.rightChannel = rightDiner.leftChannel\n}", "func (c Chessboard) rookCastleQueensidePosition(color int) int {\n if color == 0 {\n return 56\n }\n\n return 0\n}", "func (g *Game) getSpareBonus(rollIndex int) int {\n\treturn g.rolls[rollIndex+2]\n}", "func getGssWrapTokenID() [2]byte {\n\treturn [2]byte{0x05, 0x04}\n}", "func SPI_IOC_WR_LSB_FIRST() uintptr {\n\treturn ioctl.IOW(SPI_IOC_MAGIC, 2, 1)\n}", "func (p Problem) ROperand() int {\n\treturn p.right\n}", "func (m *UserMutation) SpouseID() (id int, exists bool) {\n\tif m.spouse != nil {\n\t\treturn *m.spouse, true\n\t}\n\treturn\n}", "func RightSpan(index, depth uint) uint {\n\tif index&1 == 0 {\n\t\treturn index\n\t}\n\tif depth == 0 {\n\t\tdepth = Depth(index)\n\t}\n\n\treturn (Offset(index, depth)+1)*twoPow(depth+1) - 2\n}", "func (self *Graphics) Right() int{\n return self.Object.Get(\"right\").Int()\n}", "func SPI_IOC_WR_BITS_PER_WORD() uintptr {\n\treturn ioctl.IOW(SPI_IOC_MAGIC, 3, 1)\n}", "func (b *Board) checkRight(row int, column int) {\n\tif b.connected < 3 && column < 6 {\n\t\tif b.positions[row][column] == b.positions[row][column+1] {\n\t\t\tb.connected++\n\t\t\tb.checkRight(row, column+1)\n\t\t}\n\t}\n}", "func (gt *myGoTickle) Remainder() uint32 {\n\treturn gt.total - uint32(len(gt.ticketCh))\n}", "func bisectRight(list []RingKey, x RingKey, lo, hi int) int {\n\tfor {\n\t\tif !(lo < hi) {\n\t\t\tbreak\n\t\t}\n\t\tmid := (lo + hi) / 2\n\t\tif x < list[mid] {\n\t\t\thi = mid\n\t\t} else {\n\t\t\tlo = mid + 1\n\t\t}\n\t}\n\treturn lo\n}", "func (l *Label) right(g *Graph) (*Label, *DataError) {\n Assert (nilLabel, l != nil)\n Assert(nilGraph, g != nil)\n Assert(nilLabelStore, g.labelStore != nil)\n \n return g.labelStore.findAllowZero(l.r)\n}", "func (board *Board) Right() *Board {\n\tblankPosition := board.PositionOfBlank()\n\tif (blankPosition+1)%board.Dimension == 0 {\n\t\treturn nil\n\t}\n\n\tclone := board.Clone()\n\tclone.move = RIGHT\n\ttile := clone.GetTileAt(blankPosition + 1)\n\tclone.SetTileAt(blankPosition+1, BLANK)\n\tclone.SetTileAt(blankPosition, tile)\n\tclone.cost = clone.g + clone.Cost()\n\treturn clone\n}", "func (r *Reactions) GetLaugh() int {\n\tif r == nil || r.Laugh == nil {\n\t\treturn 0\n\t}\n\treturn *r.Laugh\n}", "func (c *Client) GetRPS() int32 {\n\treturn atomic.LoadInt32(&c.rps)\n}", "func (r *MessageBookmarkRemove) RawChannelID() string {\n\treturn r.rawChannelID\n}", "func (g *gridCombined) getNonOverlapedID() int {\n\n\tfor _, c := range g.claims {\n\t\toverlap := false\n\t\tstartX := c.leftEdge\n\t\tstartY := c.topEdge\n\t\t// Y axis\n\t\tfor y := startY; y <= c.height+c.topEdge-1; y++ {\n\t\t\t// X axis\n\t\t\tfor x := startX; x <= c.width+c.leftEdge-1; x++ {\n\t\t\t\tif len(g.grid[y][x]) > 1 || len(g.grid[y][x]) == 0 {\n\t\t\t\t\toverlap = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif !overlap {\n\t\t\treturn c.id\n\t\t}\n\t}\n\n\t//No claim found\n\treturn -1\n}", "func chanByPosNum(channs []*discordgo.Channel, posNum int) (string, error) {\n\tfor _, chann := range channs {\n\t\tif chann.Type == 2 {\n\t\t\tif chann.Position == posNum {\n\t\t\t\treturn chann.ID, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", errors.New(\"not nound\")\n}", "func (r *MessageReactionRemove) RawChannelID() string {\n\treturn r.rawChannelID\n}", "func (m Message) GetSecondaryClOrdID(f *field.SecondaryClOrdIDField) quickfix.MessageRejectError {\n\treturn m.Body.Get(f)\n}", "func (m *DropMutation) SeriesID() (r uint32, exists bool) {\n\tv := m.series\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func SPI_IOC_RD_BITS_PER_WORD() uintptr {\n\treturn ioctl.IOR(SPI_IOC_MAGIC, 3, 1)\n}", "func lastId() uint64 {\n\treturn _getCounter()\n}", "func (b *BaseElement) GetMarginRight() int32 {\n\treturn b.mr\n}", "func (pb *PhilosopherBase) leftForkID() int {\n\treturn pb.ID\n}", "func ShiftRight(input []byte, shiftNum int) (result []byte, rightMostCarryFlag bool) {\n\tif shiftNum >= 1 {\n\t\tresult = make([]byte, len(input))\n\t\tcopy(result, input)\n\t\tfor i := len(result) - 1; i >= 0; i-- {\n\t\t\tcarryFlag := ((result[i] & 0x01) == 0x01)\n\n\t\t\tif i < len(result)-1 && carryFlag {\n\t\t\t\tresult[i+1] |= 0x80\n\t\t\t} else if i == len(result)-1 {\n\t\t\t\trightMostCarryFlag = carryFlag\n\t\t\t}\n\n\t\t\tresult[i] >>= 1\n\t\t}\n\n\t\tif shiftNum == 1 {\n\t\t\treturn result, rightMostCarryFlag\n\t\t}\n\t\treturn ShiftRight(result, shiftNum-1)\n\t}\n\n\treturn input, false\n}", "func getNewID() int{\n for k,_ := range BaseInfo.mCanUseID{\n delete(BaseInfo.mCanUseID,k)\n return k\n }\n if BaseInfo.iNowMaxID < BaseInfo.iInitID + BaseInfo.iMaxConnectNumber{\n BaseInfo.iNowMaxID++\n return BaseInfo.iNowMaxID\n }\n L.W(\"socket max ID used!!!\",L.Level_Error)\n return -1\n}", "func ShiftRight0(t TermT, n uint32) TermT {\n\treturn TermT(C.yices_shift_right0(C.term_t(t), C.uint32_t(n)))\n}", "func (action *Action) findLuckyNum(isSolo bool, lott *LotteryDB) int64 {\n\tvar num int64 = 0\n\tif isSolo {\n\t\t//used for internal verfication\n\t\tnum = 12345\n\t} else {\n\t\trandMolNum := (lott.TotalPurchasedTxNum+action.height-lott.LastTransToPurState)%3 + 2 //3~5\n\n\t\tmodify, err := action.GetModify(lott.LastTransToPurState, action.height-1, randMolNum)\n\t\tllog.Error(\"findLuckyNum\", \"begin\", lott.LastTransToPurState, \"end\", action.height-1, \"randMolNum\", randMolNum)\n\n\t\tif err != nil {\n\t\t\tllog.Error(\"findLuckyNum\", \"err\", err)\n\t\t\treturn -1\n\t\t}\n\n\t\tbaseNum, err := strconv.ParseUint(common.ToHex(modify[0:4]), 0, 64)\n\t\tif err != nil {\n\t\t\tllog.Error(\"findLuckyNum\", \"err\", err)\n\t\t\treturn -1\n\t\t}\n\n\t\tnum = int64(baseNum) % luckyNumMol\n\t}\n\treturn num\n}", "func (c *Controller) Right() {\n\tc.Target.Translate(10, 0)\n\tif c.Target.Collider.col.right == true {\n\t\tc.Target.Translate(-11, 0)\n\t}\n}", "func (m *EntityMutation) Ticker() (r string, exists bool) {\n\tv := m.ticker\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func chopRight(expr string) (left string, tok rune, right string) {\n\t// XXX implementation redacted for CHALLENGE1.\n\t// TODO restore implementation and replace '~'\n\tparts := strings.Split(expr, \"~\")\n\tif len(parts) != 4 {\n\t\treturn\n\t}\n\tleft = parts[0]\n\ttok = rune(parts[1][0])\n\tright = parts[2]\n\t// close = parts[3]\n\treturn\n}", "func (d *Deque) PopRight() (res interface{}) {\n\td.rightOff--\n\tif d.rightOff < 0 {\n\t\td.rightOff = blockSize - 1\n\t\td.rightIdx = (d.rightIdx - 1 + len(d.blocks)) % len(d.blocks)\n\t\td.right = d.blocks[d.rightIdx]\n\t}\n\tres, d.right[d.rightOff] = d.right[d.rightOff], nil\n\treturn\n}", "func (rPersister *RamPersister) GetRightMarketData() map[string]*tomochain.RightMarketInfo {\n\trPersister.mu.Lock()\n\tdefer rPersister.mu.Unlock()\n\treturn rPersister.rightMarketInfo\n}", "func (self *Rectangle) Right() int{\n return self.Object.Get(\"right\").Int()\n}", "func (r *RedirectNode) RightFD() int { return r.rmap.rfd }", "func (u *UserStories) GetMaxReadID() (value int, ok bool) {\n\tif u == nil {\n\t\treturn\n\t}\n\tif !u.Flags.Has(0) {\n\t\treturn value, false\n\t}\n\treturn u.MaxReadID, true\n}", "func (t *Table) GetTrickRecipient() int {\n\tif t.firstPlayer < 0 || t.firstPlayer >= len(t.players) || t.trick[t.firstPlayer] == nil {\n\t\treturn -1\n\t}\n\ttrickSuit := t.trick[t.firstPlayer].GetSuit()\n\thighestCardFace := card.Two\n\thighestIndex := -1\n\tfor i := 0; i < len(t.trick); i++ {\n\t\tcurCard := t.trick[i]\n\t\tif curCard == nil {\n\t\t\treturn -1\n\t\t}\n\t\tif curCard.GetSuit() == trickSuit && curCard.GetFace() >= highestCardFace {\n\t\t\thighestCardFace = curCard.GetFace()\n\t\t\thighestIndex = i\n\t\t}\n\t}\n\treturn highestIndex\n}", "func (m *StockMutation) IDstock() (r string, exists bool) {\n\tv := m._IDstock\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (s *swimmer) orientedRight() bool {\n\treturn s.direction() == 1\n}", "func (d *Display) CursorRight() error {\n\t_, err := d.port.Write([]byte(CursorRight))\n\treturn err\n}", "func (o DashboardSpacingOutput) Right() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DashboardSpacing) *string { return v.Right }).(pulumi.StringPtrOutput)\n}" ]
[ "0.6000476", "0.5958347", "0.5808549", "0.5757586", "0.52596444", "0.5213842", "0.51808405", "0.5127504", "0.511142", "0.5061769", "0.5043667", "0.5025362", "0.50220555", "0.49533984", "0.49085295", "0.4904905", "0.49002224", "0.48957118", "0.48860118", "0.48467997", "0.48426872", "0.48028633", "0.47972965", "0.47968528", "0.47525802", "0.4729046", "0.46977335", "0.46786487", "0.46503443", "0.46461746", "0.46207613", "0.4609654", "0.45882952", "0.45660657", "0.4535986", "0.4532442", "0.4523821", "0.4517386", "0.4483867", "0.4483324", "0.4466703", "0.444699", "0.4415623", "0.44149458", "0.44119728", "0.44076627", "0.44034952", "0.44032866", "0.4399894", "0.4399647", "0.43926144", "0.4385373", "0.4380125", "0.4376111", "0.43626", "0.43593386", "0.43459946", "0.43326274", "0.43197554", "0.43193728", "0.43099266", "0.4305243", "0.42929745", "0.42893398", "0.42889863", "0.42804646", "0.4274881", "0.42715487", "0.42688787", "0.42679513", "0.42562765", "0.42464465", "0.4237817", "0.4237634", "0.4235453", "0.42312655", "0.42306876", "0.4222784", "0.42223486", "0.42219302", "0.42085472", "0.42080924", "0.4207696", "0.42000884", "0.4186004", "0.41847834", "0.41833463", "0.41819337", "0.41750988", "0.4173777", "0.4164777", "0.41623485", "0.41567808", "0.41545948", "0.41474456", "0.41444823", "0.41414532", "0.41391638", "0.4135818", "0.41345194" ]
0.75467765
0
HasBothChopsticks returns true if both of the chopstics are reserved for the philosopher.
func (pd *philosopherData) HasBothChopsticks() bool { return (pd.leftChopstick >= 0) && (pd.rightChopstick >= 0) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m NoSides) HasSecondaryClOrdID() bool {\n\treturn m.Has(tag.SecondaryClOrdID)\n}", "func (a *_Atom) isCH2() bool {\n\treturn a.atNum == 6 && a.hCount == 2\n}", "func (o *W2) HasWagesTipsOtherComp() bool {\n\tif o != nil && o.WagesTipsOtherComp.IsSet() {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (a *_Atom) isSaturatedCH2() bool {\n\treturn a.isSaturatedC() && a.hCount == 2\n}", "func (pb *PhilosopherBase) IsHungry() bool {\n\treturn pb.State == philstate.Hungry\n}", "func (y *YKVal) Phishing(ytoken *yubico.Token, ykey *yubico.Yubikey) bool {\n\t// this implementation raises more questions than answers...\n\t// https://github.com/Yubico/yubikey-val/blob/a850489d245c01c0f232db56af8ff0bfaa93fb21/ykval-verify.php#L431\n\t// however we need to only check if counter is the same otherwise we can't rely on yubikey clock\n\tif uint(ytoken.Counter()) != ykey.Counter {\n\t\treturn false\n\t}\n\n\ty.Debug().Object(\"yubikey\", util.YubikeyTSLog(*ykey)).\n\t\tObject(\"token\", util.TokenTSLog(*ytoken)).Msg(\"phishing test\")\n\tnow := time.Now().Unix()\n\tdelta := uint(ytoken.Tstph)<<16 + uint(ytoken.Tstpl) - ykey.High<<16 - ykey.Low\n\tdeviation := abs(now - ykey.Modified - int64(float64(delta)*KeyClockFreq))\n\tpercentage := float64(1)\n\tif now-ykey.Modified != 0 {\n\t\tpercentage = float64(deviation) / float64(now-ykey.Modified)\n\t}\n\ty.Debug().Uint(\"delta\", delta).Int64(\"deviation\", deviation).\n\t\tFloat64(\"percentage\", percentage).Msg(\"phishing test\")\n\treturn deviation > AbsTolerance && percentage > RelTolerance\n}", "func passwordHasTwoPairs(ibytes *[]byte) bool {\n\tvar hasFirst bool\n\tvar firstPairChar byte\n\tvar last byte\n\tfor i := 0; i < len(*ibytes); i++ {\n\t\tc := (*ibytes)[i]\n\t\tif c == last {\n\t\t\tif !hasFirst {\n\t\t\t\thasFirst = true\n\t\t\t\tfirstPairChar = c\n\t\t\t} else {\n\t\t\t\tif c != firstPairChar {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t\t//Otherwise another set of first\n\t\t\t}\n\t\t}\n\t\tlast = c\n\t}\n\treturn false\n}", "func (me TAttlistOtherIDSource) IsCpfh() bool { return me.String() == \"CPFH\" }", "func (a *_Atom) isNH2orOHorSH() bool {\n\tif a.hCount == 0 || a.unsaturation != cmn.UnsaturationNone {\n\t\treturn false\n\t}\n\n\tswitch a.atNum {\n\tcase 7:\n\t\treturn a.hCount == 2\n\tcase 8, 16:\n\t\treturn a.hCount == 1\n\t}\n\n\treturn false\n}", "func IsTwoPair(cs [5]Card) *Hand {\n\trankCount := make(map[CardRank]int)\n\tfor _, c := range cs {\n\t\trankCount[c.Rank]++\n\t}\n\n\tpairs := 0\n\ttieBreakers := make([]CardRank, 0)\n\tfor rank, count := range rankCount {\n\t\tif count == 2 {\n\t\t\tpairs++\n\t\t\ttieBreakers = append(tieBreakers, rank)\n\t\t}\n\t}\n\n\tif pairs != 2 {\n\t\treturn nil\n\t}\n\n\t// Swap pairs so that the highest pair comes first\n\tif tieBreakers[0] < tieBreakers[1] {\n\t\ttempCard := tieBreakers[0]\n\t\ttieBreakers[0] = tieBreakers[1]\n\t\ttieBreakers[1] = tempCard\n\t}\n\n\t// Add kicker\n\tfor _, c := range cs {\n\t\tif rankCount[c.Rank] != 2 {\n\t\t\ttieBreakers = append(tieBreakers, c.Rank)\n\t\t}\n\t}\n\n\treturn &Hand{\n\t\tRank: TwoPair,\n\t\tTieBreakers: tieBreakers,\n\t}\n}", "func SameSSHPubkeys(a, b ssh.PublicKey) bool {\n\treturn bytes.Compare(a.Marshal(), b.Marshal()) == 0\n}", "func (o *W2) HasThirdPartySickPay() bool {\n\tif o != nil && o.ThirdPartySickPay.IsSet() {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *W2) HasOther() bool {\n\tif o != nil && o.Other.IsSet() {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (pd *philosopherData) RightChopstick() int {\n\treturn pd.rightChopstick\n}", "func (match *Match) DecideTrickWinner() error {\n\n\tdefer match.setNextTrickLeader()\n\n\tif CompareCards(DummyCard, match.mostRecentlyPlayed[0]) {\n\t\treturn errors.New(\"playerOne's card not properly stored\")\n\t}\n\n\tif CompareCards(DummyCard, match.mostRecentlyPlayed[1]) {\n\t\treturn errors.New(\"playerTwo's card not properly stored\")\n\t}\n\n\tpOneCard := match.mostRecentlyPlayed[0]\n\tpTwoCard := match.mostRecentlyPlayed[1]\n\ttrump, err := match.deck.getTrump()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif pOneCard.suit == trump.suit && pTwoCard.suit != trump.suit {\n\t\tmatch.playerOneWonTrick = true\n\t\treturn nil\n\t} else if pOneCard.suit != trump.suit && pTwoCard.suit == trump.suit {\n\t\tmatch.playerOneWonTrick = false\n\t\treturn nil\n\t} else {\n\t\tif match.playerOneLed {\n\t\t\tif pTwoCard.suit != pOneCard.suit {\n\t\t\t\tmatch.playerOneWonTrick = true\n\t\t\t\treturn nil\n\t\t\t} else if faceValueRanks[pOneCard.faceValue] >= faceValueRanks[pTwoCard.faceValue] {\n\t\t\t\tmatch.playerOneWonTrick = true\n\t\t\t\treturn nil\n\t\t\t} else {\n\t\t\t\tmatch.playerOneWonTrick = false\n\t\t\t\treturn nil\n\t\t\t}\n\t\t} else {\n\t\t\tif pOneCard.suit != pTwoCard.suit {\n\t\t\t\tmatch.playerOneWonTrick = false\n\t\t\t\treturn nil\n\t\t\t} else if faceValueRanks[pTwoCard.faceValue] >= faceValueRanks[pOneCard.faceValue] {\n\t\t\t\tmatch.playerOneWonTrick = false\n\t\t\t\treturn nil\n\t\t\t} else {\n\t\t\t\tmatch.playerOneWonTrick = true\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n}", "func (o *W2) HasSocialSecurityTips() bool {\n\tif o != nil && o.SocialSecurityTips.IsSet() {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (me TAttlistKeywordListOwner) IsHhs() bool { return me.String() == \"HHS\" }", "func (o *Ga4ghChemotherapy) HasDose() bool {\n\tif o != nil && o.Dose != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (m NoSides) HasCoveredOrUncovered() bool {\n\treturn m.Has(tag.CoveredOrUncovered)\n}", "func (pd *philosopherData) SetRightChop(rightChop int) {\n\tpd.rightChopstick = rightChop\n}", "func IsChopGeneratedObject(objectMeta *meta.ObjectMeta) bool {\n\n\t// ObjectMeta must have some labels\n\tif len(objectMeta.Labels) == 0 {\n\t\treturn false\n\t}\n\n\t// ObjectMeta must have LabelChop\n\t_, ok := objectMeta.Labels[LabelChop]\n\n\treturn ok\n}", "func (a *_Atom) isSaturatedCHavingH() bool {\n\treturn a.isSaturatedC() && a.hCount > 0\n}", "func TwoSat(clauses []Clause) bool {\n\tedges := make([]scc.Edge, 0, len(clauses)*2)\n\tfor _, cl := range clauses {\n\t\tedges = append(edges, scc.Edge{-cl.A, cl.B})\n\t\tedges = append(edges, scc.Edge{-cl.B, cl.A})\n\t}\n\n\tleaderMap := scc.SCC2(edges)\n\n\tfor node, leader := range leaderMap {\n\t\tleader1, ok := leaderMap[-node]\n\t\tif ok && (leader1 == leader) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func contain(k1, k2 Kline) bool {\n\tif k1.isYang() && k2.isYang() {\n\t\tif k1.Open < k2.Open && k1.Close > k2.Close {\n\t\t\treturn true\n\t\t}\n\t}\n\tif k1.isYin() && k2.isYin() {\n\t\tif k1.Open > k2.Open && k1.Close < k2.Close {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (g *Blockchain) IsOkhotsk(height uint64) bool {\n\treturn g.isPost(g.OkhotskBlockHeight, height)\n}", "func Equal(PBKDF2_x, PBKDF2_y []byte) bool {\n\treturn len(PBKDF2_x) == len(PBKDF2_y) &&\n\t\tsubtle.ConstantTimeCompare(PBKDF2_x, PBKDF2_y) == 1\n}", "func (me TartIdTypeInt) IsPmcbook() bool { return me.String() == \"pmcbook\" }", "func (o *Ga4ghTumourboard) HasCnvsDiscussed() bool {\n\tif o != nil && o.CnvsDiscussed != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (p *PluginCapabilitySet) HasToplogies() bool {\n\treturn p.hasTopologies\n}", "func (o *Channel) HasChannelProtocols() bool {\n\tif o != nil && o.ChannelProtocols != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (pc *PitchClass) HasSamePitchAs(other *PitchClass) bool {\n\tif pc == nil || other == nil {\n\t\treturn false\n\t}\n\treturn (pc.value % OctaveValue) == (other.value % OctaveValue)\n}", "func (o *W2) HasMedicareWagesAndTips() bool {\n\tif o != nil && o.MedicareWagesAndTips.IsSet() {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (me TxsdPresentationAttributesGraphicsShapeRendering) IsCrispEdges() bool {\n\treturn me.String() == \"crispEdges\"\n}", "func overlap(c1, c2 claim) bool {\n\tleft := &c1\n\tright := &c2\n\ttop := &c1\n\tbottom := &c2\n\n\tif c1.origin[0] > c2.origin[0] {\n\t\tleft = &c2\n\t\tright = &c1\n\t}\n\tif c1.origin[1] > c2.origin[1] {\n\t\ttop = &c2\n\t\tbottom = &c1\n\t}\n\n\treturn (left.origin[0]+left.size[0] > right.origin[0]) && (top.origin[1]+top.size[1] > bottom.origin[1])\n}", "func (me TxsdPaymentMechanism) IsCh() bool { return me.String() == \"CH\" }", "func (pb *PhilosopherBase) IsRightFork(f Fork) bool {\n\treturn f == pb.RightFork()\n}", "func (o *Ga4ghTumourboard) HasGermlineSnvDiscussed() bool {\n\tif o != nil && o.GermlineSnvDiscussed != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (d *deviceCommon) CanHotPlug() (bool, []string) {\n\treturn true, []string{}\n}", "func (m NoSides) HasClOrdID() bool {\n\treturn m.Has(tag.ClOrdID)\n}", "func AreFamily(a *Person, b *Person) bool {\n\tif a == b {\n\t\treturn false\n\t}\n\t// are parents or siblings x removed\n\tif recursiveAreParentsOrSiblings(a, b) {\n\t\treturn true\n\t}\n\n\t// are spouses\n\tfor _, spouse := range a.spouses {\n\t\tif spouse == b {\n\t\t\treturn true\n\t\t}\n\t\tif recursiveAreParentsOrSiblings(spouse, b) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor _, spouse := range b.spouses {\n\t\tif spouse == a {\n\t\t\treturn true\n\t\t}\n\t\tif recursiveAreParentsOrSiblings(spouse, a) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\t// are cousins\n\tfor _, parentA := range []*Person{a.mother, a.father} {\n\t\tif parentA == nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, parentB := range []*Person{b.mother, b.father} {\n\t\t\tif parentB == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif areSiblingsOrParents(parentA, parentB) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}", "func (o *MicrosoftGraphTeamFunSettings) HasAllowStickersAndMemes() bool {\n\tif o != nil && o.AllowStickersAndMemes != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func CheckPbkdf2(password, encoded string, keyLen int, h func() hash.Hash) (bool, error) {\n\tparts := strings.SplitN(encoded, \"$\", 4)\n\tif len(parts) != 4 {\n\t\treturn false, errors.New(\"Hash must consist of 4 segments\")\n\t}\n\titer, err := strconv.Atoi(parts[1])\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"Wrong number of iterations: %v\", err)\n\t}\n\tsalt := []byte(parts[2])\n\tk, err := base64.StdEncoding.DecodeString(parts[3])\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"Wrong hash encoding: %v\", err)\n\t}\n\tdk := pbkdf2.Key([]byte(password), salt, iter, keyLen, h)\n\treturn bytes.Equal(k, dk), nil\n}", "func (me TxsdSelectionAnswerTypeSequenceStyleSuggestion) IsMultichooser() bool {\n\treturn me.String() == \"multichooser\"\n}", "func check_two_pairs(hand []Card)bool{\r\n\tif hand[1].Rank == hand[2].Rank && hand[3].Rank == hand[4].Rank{\r\n\t\treturn true\r\n\t}\r\n\tif hand[0].Rank == hand[1].Rank && hand[3].Rank == hand[4].Rank{\r\n\t\treturn true\r\n\t}\r\n\tif hand[0].Rank == hand[1].Rank && hand[2].Rank == hand[3].Rank{\r\n\t\treturn true\r\n\t}\r\n\treturn false\r\n}", "func (me TxsdNodeRoleSimpleContentExtensionCategory) IsP2P() bool { return me.String() == \"p2p\" }", "func Same(t1, t2 *tree.Tree) bool {\n\n\treturnVal := true\n\ttree1 := make(chan int)\n\ttree2 := make(chan int)\n\n\tgo Closer(t1, tree1)\n\tgo Closer(t2, tree2)\n\n\ttree1Val := <-tree1\n\ttree2Val := <-tree2\n\n\tif tree1Val != tree2Val {\n\t\treturnVal = false\n\t}\n\n\treturn returnVal\n}", "func (o *StorageRemoteKeySetting) HasSecondaryServer() bool {\n\tif o != nil && o.SecondaryServer != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *TppCredentialsParams) HasTppClientSecret() bool {\n\tif o != nil && o.TppClientSecret != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (_BREMICO *BREMICOCallerSession) HasClosed() (bool, error) {\n\treturn _BREMICO.Contract.HasClosed(&_BREMICO.CallOpts)\n}", "func (o *PairAnyValueAnyValue) HasSecond() bool {\n\tif o != nil && o.Second != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (_BREMICO *BREMICOCaller) HasClosed(opts *bind.CallOpts) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _BREMICO.contract.Call(opts, out, \"hasClosed\")\n\treturn *ret0, err\n}", "func (f *FSEIDFields) HasCh() bool {\n\treturn has3rdBit(f.Flags)\n}", "func isSecretEqual(x, y *PGPSigningSecret) bool {\n\tif x == nil || y == nil {\n\t\treturn x == y\n\t} else {\n\t\tpx := x.PgpKey.privateKey\n\t\tpy := y.PgpKey.privateKey\n\t\treturn reflect.DeepEqual(x.PgpKey.publicKey, y.PgpKey.publicKey) &&\n\t\t\treflect.DeepEqual(px.PrivateKey, py.PrivateKey) &&\n\t\t\treflect.DeepEqual(px.Encrypted, py.Encrypted) &&\n\t\t\treflect.DeepEqual(px.PublicKey, py.PublicKey)\n\t}\n}", "func HitOtherSnake(board structs.Board, head structs.Coordinate) bool {\n\tcount := 0\n\tfor _, snake := range board.Snakes {\n\t\tfor _, coord := range snake.Body {\n\t\t\tif coord.X == head.X && coord.Y == head.Y {\n\t\t\t\tcount += 1\n\t\t\t}\n\t\t}\n\t}\n\treturn count > 1\n}", "func (b Board) isKingInCheck(color Color) bool {\n\t// Opposing pawn is descending our y axis.\n\toppoPawnDirection := -1\n\tif color == Black {\n\t\toppoPawnDirection = 1\n\t}\n\n\tmyKing := b.getKing(color)\n\n\t// From the king's position, generate diagonal moves. Do we\n\t// see an opposing bishop, pawn, or queen?\n\tdiagMoves := myKing.generateDiagonalMoves(*myKing.getSquare())\n\tfor _, m := range diagMoves {\n\t\tp := b.getPieceBySquare(*m)\n\t\tif p == nil || p.color == color {\n\t\t\tcontinue\n\t\t}\n\t\tif p.pieceType == BishopType || p.pieceType == QueenType {\n\t\t\treturn true\n\t\t}\n\t\tif p.pieceType == PawnType {\n\t\t\t// Opposing pawns can only go in 1 direction.\n\t\t\tif (myKing.getSquare().y - m.y) == oppoPawnDirection {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\t// From the king's position, generate straight moves. Do we\n\t// see an opposing rook or queen?\n\tstraightMoves := myKing.generateStraightMoves(*myKing.getSquare())\n\tfor _, m := range straightMoves {\n\t\tp := b.getPieceBySquare(*m)\n\t\tif p == nil || p.color == color {\n\t\t\tcontinue\n\t\t}\n\t\tif p.pieceType == RookType || p.pieceType == QueenType {\n\t\t\treturn true\n\t\t}\n\t}\n\n\t// From the king's position, generate knight moves. Do we see\n\t// an opposing knight?\n\tknightMoves := myKing.generateKnightMoves(*myKing.getSquare())\n\tfor _, m := range knightMoves {\n\t\tp := b.getPieceBySquare(*m)\n\t\tif p == nil || p.color == color {\n\t\t\tcontinue\n\t\t}\n\t\tif p.pieceType == KnightType {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (gs *GaleShapely) isBetterThanFiance(man, woman, fiance int) bool {\n\tfor _, choice := range gs.womenWishes[woman] {\n\t\tswitch choice {\n\t\tcase man:\n\t\t\treturn true\n\t\tcase fiance:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn false\n}", "func (s *Stack) IsHappy() bool {\n\tfor _, v := range s.cakes {\n\t\tif !v {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (b *picnicBasket) happy() bool {\n\treturn b.nServings > 1 && b.corkscrew\n}", "func (recv *ParamSpecUnichar) Equals(other *ParamSpecUnichar) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func (p *Player) HasFolded() bool {\n\treturn helpers.ContainsString(p.Game.CurrentQuestionRound().FoldedPlayerIds, p.ID)\n}", "func (k KernSubtable) IsCrossStream() bool {\n\treturn k.coverage&kerxCrossStream != 0\n}", "func (o *Ga4ghChemotherapy) HasDoseFrequency() bool {\n\tif o != nil && o.DoseFrequency != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func isPytha(a,b,c int ) bool{\n\tif a*a+b*b ==c*c {\n\t\treturn true\n\t}\n\treturn false\n}", "func (g *Blockchain) IsCook(height uint64) bool {\n\treturn g.isPost(g.CookBlockHeight, height)\n}", "func (o *VersionedConnection) HasBends() bool {\n\tif o != nil && o.Bends != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *W2) HasSocialSecurityWages() bool {\n\tif o != nil && o.SocialSecurityWages.IsSet() {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (c Chessboard) validPieceBishop(square int) bool {\n return int(c.boardSquares[square] % 10) == 3\n}", "func (h *Hand) CanSplit() bool {\n\tif len(h.Cards) != 2 {\n\t\treturn false\n\t}\n\tfor _, first := range h.Cards[0].Values() {\n\t\tif !util.IntsContain(first, h.Cards[1].Values()) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func twoStrings(s1 string, s2 string) string {\n\talpha := \"abcdefghijklmnopqrstuvwxyz\"\n\tfor _, b := range alpha {\n\t\tsub := string(b)\n\t\tif strings.Contains(s1, sub) && strings.Contains(s2, sub) {\n\t\t\treturn \"YES\"\n\t\t}\n\t}\n\treturn \"NO\"\n}", "func (me TAttlistMedlineCitationOwner) IsHsr() bool { return me.String() == \"HSR\" }", "func (tk Kinds) IsSub2Cat() bool {\n\treturn tk.Sub2Cat() == tk\n}", "func (proxy *LinkedProxyConfig) IsCertSecretRelated(secretName string) bool {\n\tif proxy.Primary.CertSecret == secretName {\n\t\treturn true\n\t}\n\tif proxy.Backup != nil && proxy.Backup.CertSecret == secretName {\n\t\treturn true\n\t}\n\treturn false\n}", "func (o *W2) HasDependentCareBenefits() bool {\n\tif o != nil && o.DependentCareBenefits.IsSet() {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (me TClipFillRuleType) IsEvenodd() bool { return me.String() == \"evenodd\" }", "func (o *Ga4ghChemotherapy) HasDoseUnit() bool {\n\tif o != nil && o.DoseUnit != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *Capitalization) HasSCAETHFlowPoints() bool {\n\tif o != nil && o.SCAETHFlowPoints != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func canMakeTwoRightOneTop(p int) bool {\n\tif p >= 49 {\n\t\treturn false\n\t}\n\n\tswitch p {\n\tcase 8, 16, 24, 32, 40, 48, 56, 64:\n\t\treturn false\n\t}\n\treturn true\n}", "func (hm *HareMetadata) Equivocation(other *HareMetadata) bool {\n\treturn hm.Layer == other.Layer && hm.Round == other.Round && hm.MsgHash != other.MsgHash\n}", "func HasOverlap(x, y []byte) bool {\n\treturn len(x) > 0 && len(y) > 0 &&\n\t\tuintptr(unsafe.Pointer(&x[0])) <= uintptr(unsafe.Pointer(&y[len(y)-1])) &&\n\t\tuintptr(unsafe.Pointer(&y[0])) <= uintptr(unsafe.Pointer(&x[len(x)-1]))\n}", "func Same(t1, t2 *Tree) bool {\n\tch1 := make(chan int)\n\tch2 := make(chan int)\n\tgo Walk(t1, ch1)\n\tgo Walk(t2, ch2)\n\tfor k := range ch1 {\n\t\tselect {\n\t\tcase g := <-ch2:\n\t\t\tif k != g {\n\t\t\t\treturn false\n\t\t\t}\n\t\tdefault:\n\t\t\tbreak\n\t\t}\n\t}\n\treturn true\n}", "func (b Block) HasTicks() bool {\n\treturn len(b.ticks) > 0\n}", "func (k Keeper) HasCohort(ctx sdk.Context, id uint64) bool {\n\tstore := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.CohortKey))\n\treturn store.Has(GetCohortIDBytes(id))\n}", "func (h *Hand) HasBlackJack() bool {\n\t// Blackjack is achieved with 2 cards only, otherwise it's just 21.\n\tif len(h.Cards) != 2 {\n\t\treturn false\n\t}\n\tfor _, score := range h.Scores() {\n\t\tif score == 21 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (suite *KeeperTestSuite) TestChanCloseConfirm() {\n\tvar (\n\t\tpath *ibctesting.Path\n\t\tchannelCap *capabilitytypes.Capability\n\t\theightDiff uint64\n\t)\n\n\ttestCases := []testCase{\n\t\t{\"success\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\terr := path.EndpointA.SetChannelClosed()\n\t\t\tsuite.Require().NoError(err)\n\t\t}, true},\n\t\t{\"channel doesn't exist\", func() {\n\t\t\t// any non-nil values work for connections\n\t\t\tpath.EndpointA.ChannelID = ibctesting.FirstChannelID\n\t\t\tpath.EndpointB.ChannelID = ibctesting.FirstChannelID\n\n\t\t\t// ensure channel capability check passes\n\t\t\tsuite.chainB.CreateChannelCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\t\t}, false},\n\t\t{\"channel state is CLOSED\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\terr := path.EndpointB.SetChannelClosed()\n\t\t\tsuite.Require().NoError(err)\n\t\t}, false},\n\t\t{\"connection not found\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\t// set the channel's connection hops to wrong connection ID\n\t\t\tchannel := path.EndpointB.GetChannel()\n\t\t\tchannel.ConnectionHops[0] = \"doesnotexist\"\n\t\t\tsuite.chainB.App.GetIBCKeeper().ChannelKeeper.SetChannel(suite.chainB.GetContext(), path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, channel)\n\t\t}, false},\n\t\t{\"connection is not OPEN\", func() {\n\t\t\tsuite.coordinator.SetupClients(path)\n\n\t\t\terr := path.EndpointB.ConnOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\t// create channel in init\n\t\t\tpath.SetChannelOrdered()\n\t\t\terr = path.EndpointB.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\t// ensure channel capability check passes\n\t\t\tsuite.chainB.CreateChannelCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\t\t}, false},\n\t\t{\"consensus state not found\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\terr := path.EndpointA.SetChannelClosed()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\theightDiff = 3\n\t\t}, false},\n\t\t{\"channel verification failed\", func() {\n\t\t\t// channel not closed\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\t\t}, false},\n\t\t{\"channel capability not found\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\terr := path.EndpointA.SetChannelClosed()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = capabilitytypes.NewCapability(3)\n\t\t}, false},\n\t}\n\n\tfor _, tc := range testCases {\n\t\ttc := tc\n\t\tsuite.Run(fmt.Sprintf(\"Case %s\", tc.msg), func() {\n\t\t\tsuite.SetupTest() // reset\n\t\t\theightDiff = 0 // must explicitly be changed\n\t\t\tpath = ibctesting.NewPath(suite.chainA, suite.chainB)\n\n\t\t\ttc.malleate()\n\n\t\t\tchannelKey := host.ChannelKey(path.EndpointA.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\t\t\tproof, proofHeight := suite.chainA.QueryProof(channelKey)\n\n\t\t\terr := suite.chainB.App.GetIBCKeeper().ChannelKeeper.ChanCloseConfirm(\n\t\t\t\tsuite.chainB.GetContext(), path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID, channelCap,\n\t\t\t\tproof, malleateHeight(proofHeight, heightDiff),\n\t\t\t)\n\n\t\t\tif tc.expPass {\n\t\t\t\tsuite.Require().NoError(err)\n\t\t\t} else {\n\t\t\t\tsuite.Require().Error(err)\n\t\t\t}\n\t\t})\n\t}\n}", "func (s *Segment) IsCrackBooster() bool {\n\treturn s.SegmentType == CrackBooster\n}", "func (o *EquipmentFanControl) HasEquipmentChassis() bool {\n\tif o != nil && o.EquipmentChassis != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func matchesLigature(l tables.Ligature, glyphsFromSecond []GID) bool {\n\tif len(glyphsFromSecond) != len(l.ComponentGlyphIDs) {\n\t\treturn false\n\t}\n\tfor i, g := range glyphsFromSecond {\n\t\tif g != GID(l.ComponentGlyphIDs[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (s1 Byte) IsSuperset(s2 Byte) bool {\n\tfor item := range s2 {\n\t\tif !s1.Has(item) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (r *ReactionHub) HasReactions(T int) bool {\n\tswitch T {\n\tcase ReactionOnCollision:\n\t\treturn len(r.OnCollision) != 0\n\tcase ReactionOnInteraction:\n\t\treturn len(r.OnInteraction) != 0\n\t}\n\treturn false\n}", "func (m NoSides) HasCashMargin() bool {\n\treturn m.Has(tag.CashMargin)\n}", "func (o *W2) HasSocialSecurityTaxWithheld() bool {\n\tif o != nil && o.SocialSecurityTaxWithheld.IsSet() {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func Same(t1, t2 *tree.Tree) bool {\n\tch1 := make(chan int)\n\tch2 := make(chan int)\n\n\tgo Walk(t1, ch1)\n\tgo Walk(t2, ch2)\n\n\tfor i := range ch1 {\n\t\tif (i != <-ch2) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (o *Permissao) HasChave() bool {\n\tif o != nil && o.Chave.IsSet() {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (s Ship) newBowIntersect(other Ship) bool {\n\treturn s.newBowCoordinate == other.newBowCoordinate ||\n\t\ts.newBowCoordinate == other.newPosition ||\n\t\ts.newBowCoordinate == other.newSternCoordinate\n}", "func (r *Reconciler) shouldGC(ctx context.Context, bc *intv1alpha1.BrokerCell) bool {\n\t// TODO use the constants in #1132 once it's merged\n\t// We only garbage collect brokercells that were automatically created by the GCP broker controller.\n\tif bc.GetAnnotations()[\"internal.events.cloud.google.com/creator\"] != \"googlecloud\" {\n\t\treturn false\n\t}\n\n\t// TODO(#866) Only select brokers that point to this brokercell by label selector once the\n\t// webhook assigns the brokercell label, i.e.,\n\t// r.brokerLister.List(labels.SelectorFromSet(map[string]string{\"brokercell\":bc.Name, \"brokercellns\":bc.Namespace}))\n\tbrokers, err := r.brokerLister.List(labels.Everything())\n\tif err != nil {\n\t\tlogging.FromContext(ctx).Error(\"Failed to list brokers, skipping garbage collection logic\", zap.String(\"brokercell\", bc.Name), zap.String(\"Namespace\", bc.Namespace))\n\t\treturn false\n\t}\n\n\tif len(brokers) > 0 {\n\t\t// There are still Brokers using this BrokerCell, do not garbage collect it.\n\t\treturn false\n\t}\n\n\t// TODO(#866) Only select Channels that point to this brokercell by label selector once the\n\t// webhook assigns the brokercell label, i.e.,\n\t// r.brokerLister.List(labels.SelectorFromSet(map[string]string{\"brokercell\":bc.Name, \"brokercellns\":bc.Namespace}))\n\tchannels, err := r.channelLister.List(labels.Everything())\n\tif err != nil {\n\t\tlogging.FromContext(ctx).Error(\"Failed to list Channels, skipping garbage collection logic\", zap.String(\"brokercell\", bc.Name), zap.String(\"Namespace\", bc.Namespace))\n\t\treturn false\n\t}\n\tif len(channels) > 0 {\n\t\t// There are still Channels using this BrokerCell, do not garbage collect it.\n\t\treturn false\n\t}\n\n\treturn true\n}", "func EqualG2(p1, p2 *bn256.G2) bool {\n\tp1Bytes := new(bn256.G2).Set(p1).Marshal()\n\tp2Bytes := new(bn256.G2).Set(p2).Marshal()\n\treturn bytes.Equal(p1Bytes, p2Bytes)\n}", "func Same(t1, t2 *tree.Tree) bool {\n\tvar br bool\n\tch1, ch2 := make(chan int), make(chan int)\n\n\tgo Walk(t1, ch1)\n\tgo Walk(t2, ch2)\n\n\tfor i := range ch1 {\n\t\tif i == <-ch2 {\n\t\t\tbr = true\n\t\t} else {\n\t\t\tbr = false\n\t\t\tbreak\n\t\t}\n\t}\n\treturn br\n}", "func (sh *SecretHashes) Equal(other *SecretHashes) bool {\n\tif sh == nil || other == nil {\n\t\treturn false\n\t} else if sh == other {\n\t\treturn true\n\t}\n\n\treturn sh.AuthJWT == other.AuthJWT &&\n\t\tsh.RocksDBEncryptionKey == other.RocksDBEncryptionKey &&\n\t\tsh.TLSCA == other.TLSCA &&\n\t\tsh.SyncTLSCA == other.SyncTLSCA\n}", "func Same(t1, t2 *tree.Tree) bool {\n\tch1 := make(chan int)\n\tch2 := make(chan int)\n\tgo WalkAndClose(t1, ch1)\n\tgo WalkAndClose(t2, ch2)\n\n\treturn <-ch1 == <-ch2\n}", "func (b *OGame) IsPioneers() bool {\n\treturn b.lobby == LobbyPioneers\n}" ]
[ "0.5317944", "0.5296062", "0.5277232", "0.5124482", "0.5096115", "0.48617804", "0.48070192", "0.48061496", "0.47766778", "0.46941173", "0.46610683", "0.4627525", "0.4598935", "0.45885637", "0.4588383", "0.4579903", "0.45707598", "0.4565912", "0.45405233", "0.45387453", "0.4515168", "0.44989312", "0.44768375", "0.44661257", "0.44651887", "0.44474143", "0.44420806", "0.44350654", "0.44172928", "0.44140843", "0.4413087", "0.440636", "0.4396713", "0.43866864", "0.4378059", "0.43481088", "0.43410376", "0.43365246", "0.43315172", "0.4331323", "0.43264344", "0.43250248", "0.43206152", "0.4319097", "0.43127206", "0.4312686", "0.43028888", "0.42926818", "0.42912313", "0.42660278", "0.42492667", "0.4240916", "0.42376614", "0.423227", "0.42289042", "0.4222038", "0.4218238", "0.42173237", "0.4214086", "0.42114496", "0.42032576", "0.42031607", "0.4199451", "0.4198843", "0.4196245", "0.4190898", "0.4187964", "0.41878137", "0.41772902", "0.4175719", "0.41739517", "0.4169826", "0.41517976", "0.4149093", "0.41490918", "0.41440195", "0.41420203", "0.4131716", "0.41294974", "0.412803", "0.412696", "0.4123774", "0.41133654", "0.4112336", "0.4110167", "0.41074577", "0.41057858", "0.41040134", "0.41029388", "0.41016224", "0.41011953", "0.40980697", "0.40920696", "0.40891668", "0.40879935", "0.40868676", "0.40846902", "0.40821418", "0.40795398", "0.40786391" ]
0.8689262
0
SetLeftChop can be used to set the left chopstick ID for the philosopher.
func (pd *philosopherData) SetLeftChop(leftChop int) { pd.leftChopstick = leftChop }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pd *philosopherData) LeftChopstick() int {\n\treturn pd.leftChopstick\n}", "func (pb *PhilosopherBase) LeftPhilosopher() Philosopher {\n\t// Add NPhils to avoid a negative index\n\tindex := (pb.ID + NPhils - 1) % NPhils\n\treturn Philosophers[index]\n}", "func (o *TileBounds) SetLeft(v int32) {\n\to.Left = &v\n}", "func (o *WorkbookChart) SetLeft(v AnyOfnumberstringstring) {\n\to.Left = &v\n}", "func (pb *PhilosopherBase) LeftFork() Fork {\n\treturn Forks[pb.leftForkID()]\n}", "func (pb *PhilosopherBase) leftForkID() int {\n\treturn pb.ID\n}", "func (tm *Term) FixLeft() error {\n\ttm.FixCols = ints.MaxInt(tm.FixCols-1, 0)\n\treturn tm.Draw()\n}", "func (tree *BinaryTree) SetLeft(value int) *BinaryTree {\n\ttree.left = &BinaryTree{value: value, left: nil, right: nil}\n\treturn tree\n}", "func (n *Node) MoveLeft(p []int, i int) {\n\tif i%NumberColumns > 0 {\n\t\tc := n.ClonePuzzle()\n\t\ttemp := c[i-1]\n\t\tc[i-1] = c[i]\n\t\tc[i] = temp\n\n\t\tchild := NewPuzzle(c)\n\t\tchild.Move = boardPositions[i-1]\n\t\tchild.Parent = n\n\t\tchild.G = n.G + 1\n\t\tn.Children = append(n.Children, child)\n\t}\n}", "func (pd *philosopherData) SetRightChop(rightChop int) {\n\tpd.rightChopstick = rightChop\n}", "func (m *Machine) Left() {\n\tfmt.Printf(\">> LEFT\\n\")\n\t// If we're at the 0th position, then we need to expand our tape array:\n\tif m.position == 0 {\n\t\tsize := len(m.Tape)\n\t\tm.Tape = append(make([]Cell, size), m.Tape...)\n\t\tm.position += size\n\t}\n\n\tm.position -= 1\n}", "func (g *GroupCallParticipant) SetLeft(value bool) {\n\tif value {\n\t\tg.Flags.Set(1)\n\t\tg.Left = true\n\t} else {\n\t\tg.Flags.Unset(1)\n\t\tg.Left = false\n\t}\n}", "func (e *Tree) SetLeft(replacement *Tree) { e.left = replacement }", "func SetKeyboardColourLeft(red, green, blue uint8) error {\n\thex := fmt.Sprintf(\"0x%02x%02x%02x\", red, green, blue)\n\treturn writeSysfsValue(\"color_left\", hex)\n}", "func MoveLeftRename(cf CornerFace) CornerFace {\n\tswitch cf {\n\tcase FACE_FRONT:\n\t\treturn FACE_RIGHT\n\tcase FACE_LEFT:\n\t\treturn FACE_FRONT\n\tcase FACE_BACK:\n\t\treturn FACE_LEFT\n\tcase FACE_RIGHT:\n\t\treturn FACE_BACK\n\t}\n\treturn cf // no translation for top needed\n}", "func (c *Controller) Left() {\n\tc.Target.Translate(-10, 0)\n\tif c.Target.Collider.col.left == true {\n\t\tc.Target.Translate(11, 0)\n\t}\n}", "func (o *WorkbookChart) GetLeft() AnyOfnumberstringstring {\n\tif o == nil || o.Left == nil {\n\t\tvar ret AnyOfnumberstringstring\n\t\treturn ret\n\t}\n\treturn *o.Left\n}", "func (xs *Sheet) SetMarginLeft(margin float64) {\n\txs.xb.lib.NewProc(\"xlSheetSetMarginLeftW\").\n\t\tCall(xs.self, F(margin))\n}", "func (tm *Term) ScrollLeft() error {\n\ttm.ColSt = ints.MaxInt(tm.ColSt-1, 0)\n\treturn tm.Draw()\n}", "func (p *player) moveLeft() {\n\tp.setX(game.MaxInt(0, p.x()-1))\n\tp.setDirection(false)\n}", "func Left(i int) int {\n\treturn 2 * i\n}", "func (c *Console) Left(n Int) *Console {\n\tPrint(_CSI + n.ToString() + \"D\")\n\treturn c\n}", "func (p Prefix) LeftShift(word string) string {\r\n\telem := p[len(p)-1]\r\n\tcopy(p[1:], p[:len(p)-1])\r\n\tp[0] = word\r\n\treturn elem\r\n}", "func (tree *DNFTree) CreateLeftChild(nodeID int, phi br.ClauseSet, isFinal bool) int {\n\tif debug {\n\t\tif nodeID < 0 {\n\t\t\tpanic(\"Expected nodeID >= 0 in CreateLeftChild\")\n\t\t}\n\t\tif nodeID >= len(tree.Content) {\n\t\t\tpanic(\"Expected nodeID < len(content) in CreateLeftChild\")\n\t\t}\n\t}\n\tn := tree.Content[nodeID]\n\tid := tree.CreateNodeEntry(phi, n.depth+1, isFinal)\n\tn.leftChild = id\n\treturn id\n}", "func (b *TestDriver) LeftFlip() (err error) {\n\tb.Publish(Rolling, true)\n\treturn nil\n}", "func (c *Camera) MoveLeft() {\n\tc.x -= c.worldWidth / 10\n\tc.Update()\n}", "func (eln *EmptyLeafNode) SetLeftChild(child Node) {\n\tpanic(\"Cannot set children of an empty leaf node\")\n}", "func (unpacker *BitUnpacker) Left() uint32 {\n\treturn unpacker.size - (unpacker.pbyte*8 + unpacker.pbit)\n}", "func (this *BigInteger) ShiftLeft(n int64) *BigInteger {\n\tvar r *BigInteger = NewBigInteger()\n\tif n < 0 {\n\t\tthis.RShiftTo(-n, r)\n\t} else {\n\t\tthis.LShiftTo(n, r)\n\t}\n\treturn r\n}", "func RotateLeft(t TermT, n uint32) TermT {\n\treturn TermT(C.yices_rotate_left(C.term_t(t), C.uint32_t(n)))\n}", "func left(i int) int {\n\treturn i*2 + 1\n}", "func (me *BitStream) Left() int {\n\treturn me.Bits - me.Index\n}", "func (board *Board) Left() *Board {\n\tblankPosition := board.PositionOfBlank()\n\tif blankPosition%board.Dimension == 0 {\n\t\treturn nil\n\t}\n\n\tclone := board.Clone()\n\tclone.move = LEFT\n\ttile := clone.GetTileAt(blankPosition - 1)\n\tclone.SetTileAt(blankPosition-1, BLANK)\n\tclone.SetTileAt(blankPosition, tile)\n\tclone.cost = clone.g + clone.Cost()\n\treturn clone\n}", "func (gc *LinearConverter) CropLeft() int {\n\treturn 0\n}", "func (r *RoverDriver) Left() {\n r.commands <- left\n}", "func LeftShift(scope *Scope, x tf.Output, y tf.Output) (z tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"LeftShift\",\n\t\tInput: []tf.Input{\n\t\t\tx, y,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func (o *TileBounds) GetLeft() int32 {\n\tif o == nil || o.Left == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Left\n}", "func Left(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tconfig, err := ReadConfig(\"config.json\")\n\tif err != nil {\n\t\tfmt.Println(\"error: open config.json\")\n\t}\n\n\tangle := config.WebapiRotationAngle + config.WebapiRightAngle\n\tExecCommand(w, \"set_servo \"+strconv.Itoa(angle))\n}", "func (fn *formulaFuncs) LEFT(argsList *list.List) formulaArg {\n\treturn fn.leftRight(\"LEFT\", argsList)\n}", "func (e *LineEditor) CursorLeft() {\n\n\tif e.Cx > 0 {\n\t\te.Cx--\n\t}\n}", "func ShiftLeft1(t TermT, n uint32) TermT {\n\treturn TermT(C.yices_shift_left1(C.term_t(t), C.uint32_t(n)))\n}", "func left(index int) int {\n\treturn 2*index + 1\n}", "func (mt MerkleTree) LeftTree() *MerkleTree {\n\treturn mt.leftTree\n}", "func (p *CockroachDriver) LeftQuote() byte {\n\treturn '\"'\n}", "func (g *Game) moveLeft() {\n\tif g.state != gameStarted {\n\t\treturn\n\t}\n\n\tg.direction = 2\n\tg.play()\n}", "func Left(opts ...Option) LeftOption {\n\treturn leftOption(func() []Option {\n\t\treturn opts\n\t})\n}", "func GetLeftIndex(n int) int {\n\treturn 2*n + 1\n}", "func (e *Tree) PushLeft(value interface{}) *Tree {\n\treturn e.pushTree(\"left\", value)\n}", "func (d *Display) CursorLeft() error {\n\t_, err := d.port.Write([]byte(CursorLeft))\n\treturn err\n}", "func (n *Node) MoveDownLeft(p []int, i int) {\n\tif i%NumberColumns > 0 && i < 8 {\n\t\tc := n.ClonePuzzle()\n\t\ttemp := c[i+3]\n\t\tc[i+3] = c[i]\n\t\tc[i] = temp\n\n\t\tchild := NewPuzzle(c)\n\t\tchild.Move = boardPositions[i+3]\n\t\tchild.Parent = n\n\t\tchild.G = n.G + 1\n\t\tn.Children = append(n.Children, child)\n\t}\n}", "func (v Vect) TurnLeft() Vect {\n\tif v.X == 0 {\n\t\tif v.Y == 1 {\n\t\t\treturn Vect{-1, 0}\n\t\t}\n\t\tif v.Y == -1 {\n\t\t\treturn Vect{1, 0}\n\t\t}\n\t}\n\tif v.X == -1 {\n\t\treturn Vect{0, -1}\n\t}\n\treturn Vect{0, 1}\n}", "func left(x uint) uint {\n\tif level(x) == 0 {\n\t\treturn x\n\t}\n\n\treturn x ^ (0x01 << (level(x) - 1))\n}", "func PadLeft(str string, padStr string, padLen int) string {\n\treturn buildPadStr(str, padStr, padLen, true, false)\n}", "func (p Permutator) Left() int {\n\t<- p.idle\n\tremaining := p.left()\n\tp.idle <- true\n\treturn remaining\n}", "func NewShiftLeft(left, right sql.Expression) *BitOp {\n\treturn NewBitOp(left, right, sqlparser.ShiftLeftStr)\n}", "func (g Game) Left() []Player {\n\tvar players []Player\n\tif isEmptyPlayer(g.LeftPlayerTwo) {\n\t\tplayers = make([]Player, 1)\n\t\tplayers[0] = g.LeftPlayerOne.Player\n\t} else {\n\t\tplayers = make([]Player, 2)\n\t\tplayers[0] = g.LeftPlayerOne.Player\n\t\tplayers[1] = g.LeftPlayerTwo.Player\n\t}\n\treturn players\n}", "func (pd *philosopherData) RightChopstick() int {\n\treturn pd.rightChopstick\n}", "func left(i int) int {\r\n\treturn (i * 2) + 1\r\n}", "func MaskLeft(s string) string {\n\trs := []rune(s)\n\tfor i := 0; i < len(rs)-4; i++ {\n\t\trs[i] = 'X'\n\t}\n\treturn string(rs)\n}", "func (ls *linestate) editMoveLeft() {\n\tif ls.pos > 0 {\n\t\tls.pos--\n\t\tls.refreshLine()\n\t}\n}", "func NewLeft(str, len sql.Expression) sql.Expression {\n\treturn Left{str, len}\n}", "func (v *TextView) SetLeftMargin(margin int) {\n\tC.gtk_text_view_set_left_margin(v.native(), C.gint(margin))\n}", "func ShiftLeft0(t TermT, n uint32) TermT {\n\treturn TermT(C.yices_shift_left0(C.term_t(t), C.uint32_t(n)))\n}", "func (s *State) RotateLeft() {\n\tif s.robotLost {\n\t\treturn\n\t}\n\tswitch s.direction {\n\tcase North:\n\t\ts.direction = West\n\t\tbreak\n\tcase South:\n\t\ts.direction = East\n\t\tbreak\n\tcase West:\n\t\ts.direction = South\n\t\tbreak\n\tcase East:\n\t\ts.direction = North\n\t\tbreak\n\t}\n}", "func (b *TestDriver) Left(val int) error {\n\tlog.Printf(\"Left: %d\", val)\n\treturn nil\n}", "func (o *WorkbookChart) HasLeft() bool {\n\tif o != nil && o.Left != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func lexLeftDelim(l *lexer) stateFn {\n\tl.pos += Pos(len(l.leftDelim))\n\tif strings.HasPrefix(l.input[l.pos:], leftComment) {\n\t\treturn lexComment\n\t}\n\tl.emit(itemLeftDelim)\n\tl.parenDepth = 0\n\treturn lexInsideAction\n}", "func RotateLeft64(x uint64, k int) uint64 {\n\tconst n = 64\n\ts := uint(k) & (n - 1)\n\treturn x<<s | x>>(n-s)\n}", "func LeftChild(index, depth uint) (uint, error) {\n\tif index&1 == 0 {\n\t\treturn 0, errors.New(\"No left child\")\n\t}\n\tif depth == 0 {\n\t\tdepth = Depth(index)\n\t}\n\n\treturn Index(depth-1, Offset(index, depth)*2), nil\n}", "func shift_left_once(key_chunk string) string {\n\tshifted := \"\"\n\tfor i := 1; i < 28; i++ {\n\t\tshifted += string(key_chunk[i])\n\t}\n\tshifted += string(key_chunk[0])\n\treturn shifted\n}", "func (self *TileSprite) SetLeftA(member int) {\n self.Object.Set(\"left\", member)\n}", "func (builder *Builder) Left(n uint) *Builder {\n\treturn builder.With(Left(n))\n}", "func (b *Bot) SetLeftChatMemberHandler(fn leftChatMembersHandlerFunc) {\n\tb.handlers.leftChatMembersHandler = fn\n}", "func Left(s string, n int) string {\n\tif n < 1 {\n\t\treturn \"\"\n\t}\n\trunes := []rune(s)\n\tif n >= len(runes) {\n\t\treturn s\n\t}\n\n\treturn string(runes[:n])\n\n}", "func (self *Graphics) SetLeftA(member int) {\n self.Object.Set(\"left\", member)\n}", "func (self SimpleInterval) Left() float64 {\n\treturn self.LR[0]\n}", "func (o DashboardSpacingOutput) Left() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DashboardSpacing) *string { return v.Left }).(pulumi.StringPtrOutput)\n}", "func (d *Deque) PushLeft(data interface{}) {\n\td.leftOff--\n\tif d.leftOff < 0 {\n\t\td.leftOff = blockSize - 1\n\t\td.leftIdx = (d.leftIdx - 1 + len(d.blocks)) % len(d.blocks)\n\n\t\t// If we wrapped over to the right, insert a new block and update indices\n\t\tif d.leftIdx == d.rightIdx {\n\t\t\td.leftIdx++\n\t\t\tbuffer := make([][]interface{}, len(d.blocks)+1)\n\t\t\tcopy(buffer[:d.leftIdx], d.blocks[:d.leftIdx])\n\t\t\tbuffer[d.leftIdx] = make([]interface{}, blockSize)\n\t\t\tcopy(buffer[d.leftIdx+1:], d.blocks[d.leftIdx:])\n\t\t\td.blocks = buffer\n\t\t}\n\t\td.left = d.blocks[d.leftIdx]\n\t}\n\td.left[d.leftOff] = data\n}", "func (p Permutator) left() int {\n\treturn (p.amount - p.index) + 1\n}", "func LeftPad(s string, padStr string, pLen int) string {\n\treturn strings.Repeat(padStr, pLen) + s\n}", "func RotateLeft(x uint, k int) uint {\n\tif UintSize == 32 {\n\t\treturn uint(RotateLeft32(uint32(x), k))\n\t}\n\treturn uint(RotateLeft64(uint64(x), k))\n}", "func (o DashboardSpacingPtrOutput) Left() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DashboardSpacing) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Left\n\t}).(pulumi.StringPtrOutput)\n}", "func (_obj *Apichannels) Channels_getLeftChannelsOneWayWithContext(tarsCtx context.Context, params *TLchannels_getLeftChannels, _opt ...map[string]string) (ret Messages_Chats, err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = params.WriteBlock(_os, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tvar _status map[string]string\n\tvar _context map[string]string\n\tif len(_opt) == 1 {\n\t\t_context = _opt[0]\n\t} else if len(_opt) == 2 {\n\t\t_context = _opt[0]\n\t\t_status = _opt[1]\n\t}\n\t_resp := new(requestf.ResponsePacket)\n\n\terr = _obj.s.Tars_invoke(tarsCtx, 1, \"channels_getLeftChannels\", _os.ToBytes(), _status, _context, _resp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tif len(_opt) == 1 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t} else if len(_opt) == 2 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t\tfor k := range _status {\n\t\t\tdelete(_status, k)\n\t\t}\n\t\tfor k, v := range _resp.Status {\n\t\t\t_status[k] = v\n\t\t}\n\n\t}\n\t_ = length\n\t_ = have\n\t_ = ty\n\treturn ret, nil\n}", "func (v *TypePair) IsSetLeft() bool {\n\treturn v != nil && v.Left != nil\n}", "func (l *Label) rotateLeft(g *Graph) uint16 {\n Assert(nilLabel, l != nil)\n Assert(nilGraph, g != nil)\n Assert(nilLabelStore, g.labelStore != nil)\n Assert(nilLabelWriteMap, g.labelStore.writes != nil)\n \n // perform the rotation\n right, _ := l.right(g) // TODO do not ignore error\n l.r = right.l\n right.l = l.Id\n \n l.setHeight(g)\n right.setHeight(g)\n \n // make sure the changes are written\n g.labelStore.writes[l.Id] = l\n g.labelStore.writes[right.Id] = right\n \n return right.Id\n}", "func PanLeft(image *dali.Canvas, iterations, focalPointReal *dali.InputElement, vp *ViewPort,\n\tcontrol *sync.Mutex, progress *dali.ProgressElement) {\n\tcontrol.Lock()\n\tdefer control.Unlock()\n\tlength := 4 * vp.ZoomLevel\n\tvp.ImaginaryPlaneFocalPoint -= complex(0.1*length, 0)\n\n\tiv := iterations.Value()\n\ti, _ := strconv.Atoi((iv))\n\tDrawMandelbrot(\n\t\tvp,\n\t\ti,\n\t\timage,\n\t\tprogress)\n\n\tfocalPointReal.Set(fmt.Sprintf(\"%.14f\", real(vp.ImaginaryPlaneFocalPoint)))\n}", "func (tree *Tree) Left() *Node {\n\tvar parent *Node\n\tcurrent := tree.Root\n\tfor current != nil {\n\t\tparent = current\n\t\tcurrent = current.Left\n\t}\n\treturn parent\n}", "func (d *Deque) PopLeft() (res interface{}) {\n\tres, d.left[d.leftOff] = d.left[d.leftOff], nil\n\td.leftOff++\n\tif d.leftOff == blockSize {\n\t\td.leftOff = 0\n\t\td.leftIdx = (d.leftIdx + 1) % len(d.blocks)\n\t\td.left = d.blocks[d.leftIdx]\n\t}\n\treturn\n}", "func (m *MockDriver) LeftQuote() byte {\n\treturn '\"'\n}", "func (n nexter) FoldLeft(id string, x Fold, options ...*Option) Builder {\n\topt := &Option{\n\t\tBufferSize: intP(0),\n\t}\n\n\tif len(options) > 0 {\n\t\topt = opt.merge(options...)\n\t}\n\n\tnext := &node{}\n\tedge := newEdge(opt.BufferSize)\n\n\tfr := func(payload ...*Packet) *Packet {\n\t\tif len(payload) == 1 {\n\t\t\treturn payload[0]\n\t\t}\n\n\t\td := payload[0]\n\n\t\tfor i := 1; i < len(payload); i++ {\n\t\t\td.Data = x(d.Data, payload[i].Data)\n\t\t}\n\n\t\treturn d\n\t}\n\n\tnext.vertex = vertex{\n\t\tid: id,\n\t\tvertexType: \"fold\",\n\t\tmetrics: createMetrics(id, \"fold\"),\n\t\toption: opt,\n\t\thandler: func(payload []*Packet) {\n\t\t\tedge.channel <- []*Packet{fr(payload...)}\n\t\t},\n\t\tconnector: func(ctx context.Context, b *builder) error {\n\t\t\tif next.next == nil {\n\t\t\t\treturn fmt.Errorf(\"non-terminated fold\")\n\t\t\t}\n\t\t\treturn next.next.cascade(ctx, b, edge)\n\t\t},\n\t}\n\tnext = n(next)\n\n\treturn nexter(func(n *node) *node {\n\t\tnext.next = n\n\t\treturn n\n\t})\n}", "func (i *Interface) ClickLeft(double bool) *astibob.Cmd {\n\treturn &astibob.Cmd{\n\t\tAbilityName: name,\n\t\tEventName: websocketEventNameAction,\n\t\tPayload: PayloadAction{\n\t\t\tAction: actionClickLeft,\n\t\t\tDouble: double,\n\t\t},\n\t}\n}", "func (rbst *RBSTAbelGroup) RotateLeft(root *Node, start, stop, k int) *Node {\r\n\tstart++\r\n\tk %= (stop - start + 1)\r\n\r\n\tx, y := rbst.SplitByRank(root, start-1)\r\n\ty, z := rbst.SplitByRank(y, k)\r\n\tz, p := rbst.SplitByRank(z, stop-start+1-k)\r\n\treturn rbst.Merge(rbst.Merge(rbst.Merge(x, z), y), p)\r\n}", "func (p *Player) LeftAccelerate(dist float32) {\n\tp.Speed = limitHSpeed(p.Speed.Add(p.SideFacingDir(dist)))\n}", "func (t *Text) IdentLeft(n int) *Text {\n\tif n < 0 {\n\t\treturn t\n\t}\n\tt.addMethod(func() {\n\t\tt.buffer.WriteString(strings.Repeat(\" \", n))\n\t})\n\treturn t\n}", "func (s *System) Left() (err error) {\n\ts.mux.Lock()\n\tdefer s.mux.Unlock()\n\n\t// If we are currently displaying text and their is an image, then we should\n\t// no longer display the text, navigating the slide in two steps.\n\tif s.displayBoth && s.affirmations[s.activeAffirmationIndex].displayImage != nil {\n\t\ts.displayBoth = false // We've navigated to the beginning of a slide, show the image alone.\n\t\treturn\n\t}\n\n\tif s.activeAffirmationIndex == 0 {\n\t\ts.activeAffirmationIndex = s.maxAffirmationIndex()\n\t} else {\n\t\ts.activeAffirmationIndex--\n\t}\n\ts.displayBoth = true // We just navigated backwards to a slide, show the text.\n\treturn nil\n}", "func (b *Board) checkLeft(row int, column int) {\n\tif b.connected < 3 && column > 0 {\n\t\tif b.positions[row][column] == b.positions[row][column-1] {\n\t\t\tb.connected++\n\t\t\tb.checkLeft(row, column-1)\n\t\t}\n\t}\n}", "func (e Equation) Left() Type {\n\treturn e.left\n}", "func (d *ContextMenuHandler) OnBeforeContextMenu(browser *Browser, frame *Frame, params *ContextMenuParams, model *MenuModel) {\n\tlookupContextMenuHandlerProxy(d.Base()).OnBeforeContextMenu(d, browser, frame, params, model)\n}", "func ColumnLeft(name string) {\n\tidx := colIndex(name)\n\tif idx > 0 {\n\t\tswapCols(idx, idx-1)\n\t}\n}", "func LeftOf(x ...interface{}) Either {\n\treturn newEither(false, x...)\n}" ]
[ "0.73707217", "0.6286688", "0.59980017", "0.5986728", "0.57390344", "0.56987184", "0.56917906", "0.55924845", "0.5445735", "0.5435871", "0.54053646", "0.5357424", "0.5353087", "0.53485155", "0.5300217", "0.52607894", "0.5196165", "0.519229", "0.51670706", "0.51670057", "0.515564", "0.51367074", "0.50885916", "0.50858015", "0.5080702", "0.50618523", "0.5051104", "0.50478745", "0.50215596", "0.5020752", "0.4995758", "0.49850732", "0.4975182", "0.49505365", "0.49487212", "0.49457315", "0.4942132", "0.493848", "0.4932738", "0.49204412", "0.49151972", "0.49137798", "0.49077857", "0.4906306", "0.49054143", "0.48975912", "0.48890483", "0.48825496", "0.4877684", "0.48740542", "0.48700517", "0.48599106", "0.48571217", "0.48425266", "0.4837795", "0.4834439", "0.48285255", "0.48262128", "0.48208454", "0.48034173", "0.47953773", "0.4786231", "0.4777882", "0.4768427", "0.47638085", "0.47532544", "0.47303456", "0.47283944", "0.4726776", "0.47261837", "0.4719144", "0.4702945", "0.46930438", "0.4692252", "0.46909016", "0.46837306", "0.46828058", "0.46681148", "0.46608874", "0.4649756", "0.4636969", "0.46283084", "0.4622545", "0.4608349", "0.46076828", "0.46058637", "0.4605315", "0.4588502", "0.4584822", "0.4584484", "0.45834595", "0.45760152", "0.45726573", "0.4569995", "0.45633835", "0.45620236", "0.45555726", "0.45452544", "0.4543299", "0.45408252" ]
0.8535612
0
SetRightChop can be used to set the right chopstick ID for the philosopher.
func (pd *philosopherData) SetRightChop(rightChop int) { pd.rightChopstick = rightChop }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pd *philosopherData) RightChopstick() int {\n\treturn pd.rightChopstick\n}", "func (pd *philosopherData) SetLeftChop(leftChop int) {\n\tpd.leftChopstick = leftChop\n}", "func (mu *ModelUpdate) SetRight(b bool) *ModelUpdate {\n\tmu.mutation.SetRight(b)\n\treturn mu\n}", "func (muo *ModelUpdateOne) SetRight(b bool) *ModelUpdateOne {\n\tmuo.mutation.SetRight(b)\n\treturn muo\n}", "func (leftDiner *Diner) HookupRightChannel(rightDiner *Diner) {\n\tif leftDiner.rightChannel != nil {\n\t\tlog.Panic(\"Left diner: %v right channel has already been set\", leftDiner)\n\t}\n\tlog.Debug(\"%v hooking to %v\", leftDiner, rightDiner)\n\tleftDiner.rightChannel = rightDiner.leftChannel\n}", "func (pb *PhilosopherBase) RightPhilosopher() Philosopher {\n\tindex := (pb.ID + 1) % NPhils\n\treturn Philosophers[index]\n}", "func (pb *PhilosopherBase) rightForkID() int {\n\treturn (pb.ID + 1) % NPhils\n}", "func (pb *PhilosopherBase) RightFork() Fork {\n\treturn Forks[pb.rightForkID()]\n}", "func (pd *philosopherData) LeftChopstick() int {\n\treturn pd.leftChopstick\n}", "func (e *Tree) SetRight(replacement *Tree) { e.right = replacement }", "func (tm *Term) FixRight() error {\n\ttm.FixCols++ // no obvious max\n\treturn tm.Draw()\n}", "func (xs *Sheet) SetMarginRight(margin float64) {\n\txs.xb.lib.NewProc(\"xlSheetSetMarginRightW\").\n\t\tCall(xs.self, F(margin))\n}", "func (xs *Sheet) SetRightToLeft(rightToLeft int) {\n\txs.xb.lib.NewProc(\"xlSheetSetRightToLeftW\").\n\t\tCall(xs.self, I(rightToLeft))\n}", "func SetKeyboardColourRight(red, green, blue uint8) error {\n\thex := fmt.Sprintf(\"0x%02x%02x%02x\", red, green, blue)\n\treturn writeSysfsValue(\"color_right\", hex)\n}", "func (o *StockCvterm) SetStockCvtermprop(exec boil.Executor, insert bool, related *StockCvtermprop) error {\n\tvar err error\n\n\tif insert {\n\t\trelated.StockCvtermID = o.StockCvtermID\n\n\t\tif err = related.Insert(exec); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to insert into foreign table\")\n\t\t}\n\t} else {\n\t\tupdateQuery := fmt.Sprintf(\n\t\t\t\"UPDATE \\\"stock_cvtermprop\\\" SET %s WHERE %s\",\n\t\t\tstrmangle.SetParamNames(\"\\\"\", \"\\\"\", 1, []string{\"stock_cvterm_id\"}),\n\t\t\tstrmangle.WhereClause(\"\\\"\", \"\\\"\", 2, stockCvtermpropPrimaryKeyColumns),\n\t\t)\n\t\tvalues := []interface{}{o.StockCvtermID, related.StockCvtermpropID}\n\n\t\tif boil.DebugMode {\n\t\t\tfmt.Fprintln(boil.DebugWriter, updateQuery)\n\t\t\tfmt.Fprintln(boil.DebugWriter, values)\n\t\t}\n\n\t\tif _, err = exec.Exec(updateQuery, values...); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to update foreign table\")\n\t\t}\n\n\t\trelated.StockCvtermID = o.StockCvtermID\n\n\t}\n\n\tif o.R == nil {\n\t\to.R = &stockCvtermR{\n\t\t\tStockCvtermprop: related,\n\t\t}\n\t} else {\n\t\to.R.StockCvtermprop = related\n\t}\n\n\tif related.R == nil {\n\t\trelated.R = &stockCvtermpropR{\n\t\t\tStockCvterm: o,\n\t\t}\n\t} else {\n\t\trelated.R.StockCvterm = o\n\t}\n\treturn nil\n}", "func (eln *EmptyLeafNode) SetRightChild(child Node) {\n\tpanic(\"Cannot set children of an empty leaf node\")\n}", "func (r *RoverDriver) Right() {\n r.commands <- right\n}", "func chopRight(expr string) (left string, tok rune, right string) {\n\t// XXX implementation redacted for CHALLENGE1.\n\t// TODO restore implementation and replace '~'\n\tparts := strings.Split(expr, \"~\")\n\tif len(parts) != 4 {\n\t\treturn\n\t}\n\tleft = parts[0]\n\ttok = rune(parts[1][0])\n\tright = parts[2]\n\t// close = parts[3]\n\treturn\n}", "func (m *PatientrightsMutation) SetPatientrightsPatientrightstypeID(id int) {\n\tm._PatientrightsPatientrightstype = &id\n}", "func (self *TileSprite) SetRightA(member int) {\n self.Object.Set(\"right\", member)\n}", "func (c *Controller) Right() {\n\tc.Target.Translate(10, 0)\n\tif c.Target.Collider.col.right == true {\n\t\tc.Target.Translate(-11, 0)\n\t}\n}", "func (self *Graphics) SetRightA(member int) {\n self.Object.Set(\"right\", member)\n}", "func (pd *philosopherData) HasBothChopsticks() bool {\n\treturn (pd.leftChopstick >= 0) && (pd.rightChopstick >= 0)\n}", "func (m *CUserMsg_ParticleManager_UpdateParticleOrient) GetRight() *CMsgVector {\n\tif m != nil {\n\t\treturn m.Right\n\t}\n\treturn nil\n}", "func (p *player) moveRight() {\n\tp.setX(game.MinInt(cols-1, p.x()+1))\n\tp.setDirection(true)\n}", "func (r *HashJsonCodecRedisController) SetSomeInt64(key string, someInt64 int64) (err error) {\n\t// redis conn\n\tconn := r.pool.Get()\n\tdefer conn.Close()\n\n\t// set SomeInt64 field\n\tr.m.SomeInt64 = someInt64\n\t_, err = conn.Do(\"HSET\", key, \"SomeInt64\", someInt64)\n\n\treturn\n}", "func (ch *Channel) settleSecondary(pctx context.Context) error {\n\t// TODO (mano): Document what happens when a Settle fails, should channel close be called again ?\n\tctx, cancel := context.WithTimeout(pctx, ch.timeoutCfg.settleChSecondary(ch.challengeDurSecs))\n\tdefer cancel()\n\terr := ch.pch.SettleSecondary(ctx)\n\tif err != nil {\n\t\tch.Error(\"Settling channel\", err)\n\t\treturn perun.GetAPIError(err)\n\t}\n\tch.close()\n\treturn nil\n}", "func (self *Rectangle) SetRightA(member int) {\n self.Object.Set(\"right\", member)\n}", "func right(i int) int {\n\treturn i*2 + 2\n}", "func (c *Console) Right(n Int) *Console {\n\tPrint(_CSI + n.ToString() + \"C\")\n\treturn c\n}", "func (o *RentalRower) SetRower(exec boil.Executor, insert bool, related *Rower) error {\n\tvar err error\n\tif insert {\n\t\tif err = related.Insert(exec, boil.Infer()); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to insert into foreign table\")\n\t\t}\n\t}\n\n\tupdateQuery := fmt.Sprintf(\n\t\t\"UPDATE \\\"rental_rowers\\\" SET %s WHERE %s\",\n\t\tstrmangle.SetParamNames(\"\\\"\", \"\\\"\", 1, []string{\"rower_id\"}),\n\t\tstrmangle.WhereClause(\"\\\"\", \"\\\"\", 2, rentalRowerPrimaryKeyColumns),\n\t)\n\tvalues := []interface{}{related.ID, o.ID}\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, updateQuery)\n\t\tfmt.Fprintln(boil.DebugWriter, values)\n\t}\n\n\tif _, err = exec.Exec(updateQuery, values...); err != nil {\n\t\treturn errors.Wrap(err, \"failed to update local table\")\n\t}\n\n\tqueries.Assign(&o.RowerID, related.ID)\n\tif o.R == nil {\n\t\to.R = &rentalRowerR{\n\t\t\tRower: related,\n\t\t}\n\t} else {\n\t\to.R.Rower = related\n\t}\n\n\tif related.R == nil {\n\t\trelated.R = &rowerR{\n\t\t\tRentalRowers: RentalRowerSlice{o},\n\t\t}\n\t} else {\n\t\trelated.R.RentalRowers = append(related.R.RentalRowers, o)\n\t}\n\n\treturn nil\n}", "func (p *CockroachDriver) RightQuote() byte {\n\treturn '\"'\n}", "func (c *expression) extendRight(n *expression) *expression {\n\n\tc.right = n\n\tn.parent = c\n\n\tfmt.Printf(\"++++++++++++++++++++++++++ extendRight FROM %s -> [%s] \\n\", c.opr, n.opr)\n\treturn n\n}", "func (pc *PatientrightsCreate) SetPatientrightsPatientrightstypeID(id int) *PatientrightsCreate {\n\tpc.mutation.SetPatientrightsPatientrightstypeID(id)\n\treturn pc\n}", "func (m *Machine) Right() {\n\tfmt.Printf(\">> RIGHT\\n\")\n\t// If we're at the last position, then we need to expand our tape array:\n\tif m.position == (len(m.Tape) - 1) {\n\t\tsize := len(m.Tape)\n\t\tm.Tape = append(m.Tape, make([]Cell, size)...)\n\t}\n\n\tm.position += 1\n}", "func (n *Node) MoveRight(p []int, i int) {\n\tif i%NumberColumns != 3 {\n\t\tc := n.ClonePuzzle()\n\t\ttemp := c[i+1]\n\t\tc[i+1] = c[i]\n\t\tc[i] = temp\n\n\t\tchild := NewPuzzle(c)\n\t\tchild.Move = boardPositions[i+1]\n\t\tchild.Parent = n\n\t\tchild.G = n.G + 1\n\t\tn.Children = append(n.Children, child)\n\t}\n}", "func (d *Display) CursorRight() error {\n\t_, err := d.port.Write([]byte(CursorRight))\n\treturn err\n}", "func (image *Image2D) SetR(x, y int, r uint8) {\n\tidx := image.getIdx(x, y)\n\timage.data[idx] = r\n}", "func (m *PatientrightstypeMutation) SetPatientrightstypeAbilitypatientrightsID(id int) {\n\tm._PatientrightstypeAbilitypatientrights = &id\n}", "func (mySelf SQLJoin) Right() SQLJoin {\n\tmySelf.right = true\n\treturn mySelf\n}", "func (tm *Term) ScrollRight() error {\n\ttm.ColSt++ // no obvious max\n\treturn tm.Draw()\n}", "func (y *YeeLight) SetBright(bright int, effect Effect, duration int) (*Answer, error) {\n\tif bright < 1 || bright > 100 {\n\t\treturn nil, errors.Wrapf(ErrInvalidRange, \"invalid bright value: %d\", bright)\n\t}\n\tif !isValidDuration(duration) {\n\t\treturn nil, errors.Wrapf(ErrInvalidType, \"invalid duration value: %d\", duration)\n\t}\n\tcmd, err := y.newCommand(\"set_bright\", []interface{}{bright, effect, duration})\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\treturn y.sendCommand(cmd)\n}", "func Right(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tconfig, err := ReadConfig(\"config.json\")\n\tif err != nil {\n\t\tfmt.Println(\"error: open config.json\")\n\t}\n\n\tangle := config.WebapiRotationAngle + config.WebapiLeftAngle\n\tExecCommand(w, \"set_servo \"+strconv.Itoa(angle))\n}", "func (m *RoomdetailMutation) SetRoomprice(i int) {\n\tm.roomprice = &i\n\tm.addroomprice = nil\n}", "func SocketRight(idx int) string {\n\tswitch idx {\n\tcase 1, 2, 5:\n\t\treturn \"socketRight\"\n\t}\n\treturn \"\"\n}", "func (m *PatientrightsMutation) SetPatientrightsPatientrecordID(id int) {\n\tm._PatientrightsPatientrecord = &id\n}", "func (r *HashJsonCodecRedisController) SetSomeUint64(key string, someUint64 uint64) (err error) {\n\t// redis conn\n\tconn := r.pool.Get()\n\tdefer conn.Close()\n\n\t// set SomeUint64 field\n\tr.m.SomeUint64 = someUint64\n\t_, err = conn.Do(\"HSET\", key, \"SomeUint64\", someUint64)\n\n\treturn\n}", "func right(i int) int {\r\n\treturn (i * 2 ) + 2\r\n}", "func (c Client) SetSecondaryID(ctx context.Context, primary, secondary it.IssueID) error {\n\treturn it.ErrNotImplemented\n}", "func (i *Interface) ClickRight(double bool) *astibob.Cmd {\n\treturn &astibob.Cmd{\n\t\tAbilityName: name,\n\t\tEventName: websocketEventNameAction,\n\t\tPayload: PayloadAction{\n\t\t\tAction: actionClickRight,\n\t\t\tDouble: double,\n\t\t},\n\t}\n}", "func (s *swimmer) setDirection(right bool) {\n\tif right {\n\t\ts.moveDirection = 1\n\t} else {\n\t\ts.moveDirection = -1\n\t}\n}", "func (c hashChainer) chainBorderRight(seed []byte, proof [][]byte) []byte {\n\tfor _, h := range proof {\n\t\tseed = c.hasher.HashChildren(h, seed)\n\t}\n\treturn seed\n}", "func (w *ServerInterfaceWrapper) RenewSecretChannel(ctx echo.Context) error {\n\tvar err error\n\t// ------------- Path parameter \"id\" -------------\n\tvar id int\n\n\terr = runtime.BindStyledParameter(\"simple\", false, \"id\", ctx.Param(\"id\"), &id)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter id: %s\", err))\n\t}\n\n\tctx.Set(\"OAuth.Scopes\", []string{\"\"})\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.RenewSecretChannel(ctx, id)\n\treturn err\n}", "func (m NoSides) SetSecondaryClOrdID(v string) {\n\tm.Set(field.NewSecondaryClOrdID(v))\n}", "func (v *TextView) SetRightMargin(margin int) {\n\tC.gtk_text_view_set_right_margin(v.native(), C.gint(margin))\n}", "func Right(i int) int {\n\treturn 2*i + 1\n}", "func MoveRightRename(cf CornerFace) CornerFace {\n\tswitch cf {\n\tcase FACE_FRONT:\n\t\treturn FACE_LEFT\n\tcase FACE_LEFT:\n\t\treturn FACE_BACK\n\tcase FACE_BACK:\n\t\treturn FACE_RIGHT\n\tcase FACE_RIGHT:\n\t\treturn FACE_FRONT\n\t}\n\treturn cf // no translation for top needed\n}", "func (m *MockDriver) RightQuote() byte {\n\treturn '\"'\n}", "func (b *TestDriver) Right(val int) error {\n\tlog.Printf(\"Right: %d\", val)\n\n\treturn nil\n}", "func SETOC(mr operand.Op) { ctx.SETOC(mr) }", "func right(index int) int {\n\treturn 2*index + 2\n}", "func (c *Camera) MoveRight() {\n\tc.x += c.worldWidth / 10\n\tc.Update()\n}", "func (c *Context) SetFreqCorrection(ppm int) (err int) {\n\treturn int(C.rtlsdr_set_freq_correction((*C.rtlsdr_dev_t)(c.dev),\n\t\tC.int(ppm)))\n}", "func RightShift(scope *Scope, x tf.Output, y tf.Output) (z tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"RightShift\",\n\t\tInput: []tf.Input{\n\t\t\tx, y,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func rightShift(s *keyboard.State) (*Violation, error) {\n if len(s.LastCharacters) < 1 {\n return nil, status.Error(\n codes.FailedPrecondition,\n \"rightshift vimprovement check ran before character input was received.\",\n )\n }\n if s.RightShiftDown && rightShiftViolatingKeys[s.LastCharacters[0]] {\n return &rsViolation, nil\n }\n return nil, nil\n}", "func (m *SplitRegionResponse) GetRight() *metapb.Region {\n\tif m != nil {\n\t\treturn m.Right\n\t}\n\treturn nil\n}", "func (v *TypePair) IsSetRight() bool {\n\treturn v != nil && v.Right != nil\n}", "func (g *Game) moveRight() {\n\tif g.state != gameStarted {\n\t\treturn\n\t}\n\n\tg.direction = 1\n\tg.play()\n}", "func (tree *DNFTree) CreateRightChild(nodeID int, phi br.ClauseSet, isFinal bool) int {\n\tif debug {\n\t\tif nodeID < 0 {\n\t\t\tpanic(\"Expected nodeID >= 0 in CreateRightChild\")\n\t\t}\n\t\tif nodeID >= len(tree.Content) {\n\t\t\tpanic(\"Expected nodeID < len(content) in CreateRightChild\")\n\t\t}\n\t}\n\tn := tree.Content[nodeID]\n\tid := tree.CreateNodeEntry(phi, n.depth+1, isFinal)\n\tn.rightChild = id\n\treturn id\n}", "func (c hashChainer) chainInnerRight(seed []byte, proof [][]byte, index int64) []byte {\n\tfor i, h := range proof {\n\t\tif (index>>uint(i))&1 == 1 {\n\t\t\tseed = c.hasher.HashChildren(h, seed)\n\t\t}\n\t}\n\treturn seed\n}", "func (_BaseContent *BaseContentTransactor) SetRights(opts *bind.TransactOpts, stakeholder common.Address, access_type uint8, access uint8) (*types.Transaction, error) {\n\treturn _BaseContent.contract.Transact(opts, \"setRights\", stakeholder, access_type, access)\n}", "func (y *Yeelight) SetBright(brightness, effect, duration string) string {\n\tcmd := `{\"id\":5,\"method\":\"set_bright\",\"params\":[` + brightness + `,\"` + effect + `\",` + duration + `]}`\n\treturn y.request(cmd)\n}", "func (_BaseContentType *BaseContentTypeTransactor) SetRights(opts *bind.TransactOpts, stakeholder common.Address, access_type uint8, access uint8) (*types.Transaction, error) {\n\treturn _BaseContentType.contract.Transact(opts, \"setRights\", stakeholder, access_type, access)\n}", "func ShiftRight0(t TermT, n uint32) TermT {\n\treturn TermT(C.yices_shift_right0(C.term_t(t), C.uint32_t(n)))\n}", "func (m *Metadata) SetRights(rights string) {\n\tm.Rights = []ElementLang{{Value: rights}}\n}", "func (m *PatientrightsMutation) SetPatientrightsMedicalrecordstaffID(id int) {\n\tm._PatientrightsMedicalrecordstaff = &id\n}", "func (r *Rights) setClientRights(cliUID string, rights *ttnpb.Rights) {\n\tif r.ClientRights == nil {\n\t\tr.ClientRights = make(map[string]*ttnpb.Rights)\n\t}\n\tr.ClientRights[cliUID] = rights\n}", "func (m *PatientrightstypeMutation) AddPatientrightstypePatientrightIDs(ids ...int) {\n\tif m._PatientrightstypePatientrights == nil {\n\t\tm._PatientrightstypePatientrights = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm._PatientrightstypePatientrights[ids[i]] = struct{}{}\n\t}\n}", "func (d *Deque) PopRight() (res interface{}) {\n\td.rightOff--\n\tif d.rightOff < 0 {\n\t\td.rightOff = blockSize - 1\n\t\td.rightIdx = (d.rightIdx - 1 + len(d.blocks)) % len(d.blocks)\n\t\td.right = d.blocks[d.rightIdx]\n\t}\n\tres, d.right[d.rightOff] = d.right[d.rightOff], nil\n\treturn\n}", "func (n *Node) MoveDownRight(p []int, i int) {\n\tif i%NumberColumns != 3 && i < 8 {\n\t\tc := n.ClonePuzzle()\n\t\ttemp := c[i+5]\n\t\tc[i+5] = c[i]\n\t\tc[i] = temp\n\n\t\tchild := NewPuzzle(c)\n\t\tchild.Move = boardPositions[i+5]\n\t\tchild.Parent = n\n\t\tchild.G = n.G + 1\n\t\tn.Children = append(n.Children, child)\n\t}\n}", "func (f *FilterExpression) WithRight(right string) *FilterExpression {\n\tf.Right = right\n\treturn f\n}", "func (m *PatientrightsMutation) ResetPatientrightsPatientrightstype() {\n\tm._PatientrightsPatientrightstype = nil\n\tm.cleared_PatientrightsPatientrightstype = false\n}", "func (s Square) Right() int {\n\treturn s.left + s.width\n}", "func (m *PatientrightstypeMutation) RemovePatientrightstypePatientrightIDs(ids ...int) {\n\tif m.removed_PatientrightstypePatientrights == nil {\n\t\tm.removed_PatientrightstypePatientrights = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.removed_PatientrightstypePatientrights[ids[i]] = struct{}{}\n\t}\n}", "func (b *TestDriver) RightFlip() (err error) {\n\tb.Publish(Rolling, true)\n\treturn nil\n}", "func (m *UserMutation) SetSpouseID(id int) {\n\tm.spouse = &id\n}", "func (db *DB) SetDrop(ctx context.Context, drop *jetdrop.JetDrop) error {\n\tk := prefixkey(scopeIDJetDrop, drop.Pulse.Bytes())\n\t_, err := db.get(ctx, k)\n\tif err == nil {\n\t\treturn ErrOverride\n\t}\n\n\tencoded, err := jetdrop.Encode(drop)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn db.set(ctx, k, encoded)\n}", "func (f *FSEIDFields) SetChIDFlag() {\n\tf.Flags |= 0x08\n}", "func (o *RowerGroup) SetRower(exec boil.Executor, insert bool, related *Rower) error {\n\tvar err error\n\tif insert {\n\t\tif err = related.Insert(exec, boil.Infer()); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to insert into foreign table\")\n\t\t}\n\t}\n\n\tupdateQuery := fmt.Sprintf(\n\t\t\"UPDATE \\\"rower_group\\\" SET %s WHERE %s\",\n\t\tstrmangle.SetParamNames(\"\\\"\", \"\\\"\", 1, []string{\"rower_id\"}),\n\t\tstrmangle.WhereClause(\"\\\"\", \"\\\"\", 2, rowerGroupPrimaryKeyColumns),\n\t)\n\tvalues := []interface{}{related.ID, o.ID}\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, updateQuery)\n\t\tfmt.Fprintln(boil.DebugWriter, values)\n\t}\n\n\tif _, err = exec.Exec(updateQuery, values...); err != nil {\n\t\treturn errors.Wrap(err, \"failed to update local table\")\n\t}\n\n\tqueries.Assign(&o.RowerID, related.ID)\n\tif o.R == nil {\n\t\to.R = &rowerGroupR{\n\t\t\tRower: related,\n\t\t}\n\t} else {\n\t\to.R.Rower = related\n\t}\n\n\tif related.R == nil {\n\t\trelated.R = &rowerR{\n\t\t\tRowerGroups: RowerGroupSlice{o},\n\t\t}\n\t} else {\n\t\trelated.R.RowerGroups = append(related.R.RowerGroups, o)\n\t}\n\n\treturn nil\n}", "func (s Server) SetRadioPower(ctx context.Context, req *nb.RadioPowerRequest) (*nb.RadioPowerResponse, error) {\n\tif req != nil {\n\t\toffset := req.GetOffset()\n\t\tvar pa []sb.XICICPA\n\t\tswitch offset {\n\t\tcase nb.StationPowerOffset_PA_DB_0:\n\t\t\tpa = append(pa, sb.XICICPA_XICIC_PA_DB_0)\n\t\tcase nb.StationPowerOffset_PA_DB_1:\n\t\t\tpa = append(pa, sb.XICICPA_XICIC_PA_DB_1)\n\t\tcase nb.StationPowerOffset_PA_DB_2:\n\t\t\tpa = append(pa, sb.XICICPA_XICIC_PA_DB_2)\n\t\tcase nb.StationPowerOffset_PA_DB_3:\n\t\t\tpa = append(pa, sb.XICICPA_XICIC_PA_DB_3)\n\t\tcase nb.StationPowerOffset_PA_DB_MINUS3:\n\t\t\tpa = append(pa, sb.XICICPA_XICIC_PA_DB_MINUS3)\n\t\tcase nb.StationPowerOffset_PA_DB_MINUS6:\n\t\t\tpa = append(pa, sb.XICICPA_XICIC_PA_DB_MINUS6)\n\t\tcase nb.StationPowerOffset_PA_DB_MINUS1DOT77:\n\t\t\tpa = append(pa, sb.XICICPA_XICIC_PA_DB_MINUS1DOT77)\n\t\tcase nb.StationPowerOffset_PA_DB_MINUX4DOT77:\n\t\t\tpa = append(pa, sb.XICICPA_XICIC_PA_DB_MINUX4DOT77)\n\n\t\t}\n\n\t\tecgi := sb.ECGI{\n\t\t\tEcid: req.GetEcgi().GetEcid(),\n\t\t\tPlmnId: req.GetEcgi().GetPlmnid(),\n\t\t}\n\n\t\tctrlResponse := sb.ControlResponse{\n\t\t\tMessageType: sb.MessageType_RRM_CONFIG,\n\t\t\tS: &sb.ControlResponse_RRMConfig{\n\t\t\t\tRRMConfig: &sb.RRMConfig{\n\t\t\t\t\tEcgi: &ecgi,\n\t\t\t\t\tPA: pa,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\terr := manager.GetManager().SB.SendResponse(ctrlResponse)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\treturn nil, fmt.Errorf(\"SetRadioPower request cannot be nil\")\n\t}\n\treturn &nb.RadioPowerResponse{Success: true}, nil\n}", "func (piuo *ProviderIDUpdateOne) SetMturkWorkerID(s string) *ProviderIDUpdateOne {\n\tpiuo.mutation.SetMturkWorkerID(s)\n\treturn piuo\n}", "func (xs *Sheet) SetGroupSummaryRight(right int) {\n\txs.xb.lib.NewProc(\"xlSheetSetGroupSummaryRightW\").\n\t\tCall(xs.self, I(right))\n}", "func (ctx *RequestContext) RemoveRight(right string) {\n\tif !ctx.IsAuthenticated() {\n\t\treturn\n\t}\n\n\trights := ctx.principal.Rights\n\n\ti := sort.Search(len(rights), func(i int) bool {\n\t\treturn rights[i] == right\n\t})\n\n\tif i >= len(rights) {\n\t\treturn\n\t}\n\n\tctx.principal.Rights = append(rights[:i], rights[i+1:]...)\n}", "func RSet(data, setData []byte) []byte {\n\tdataLength := len(data)\n\tsetDataLength := len(setData)\n\n\toperationLength := dataLength\n\tif setDataLength > dataLength {\n\t\toperationLength = setDataLength\n\t}\n\n\tresult, _ := Set(LPad(data, operationLength, 0x00), LPad(setData, operationLength, 0x00))\n\treturn result\n}", "func (_BaseLibrary *BaseLibraryTransactor) SetRights(opts *bind.TransactOpts, stakeholder common.Address, access_type uint8, access uint8) (*types.Transaction, error) {\n\treturn _BaseLibrary.contract.Transact(opts, \"setRights\", stakeholder, access_type, access)\n}", "func right(x uint, n uint) uint {\n\tif level(x) == 0 {\n\t\treturn x\n\t}\n\n\tr := x ^ (0x03 << (level(x) - 1))\n\tfor r > 2*(n-1) {\n\t\tr = left(r)\n\t}\n\treturn r\n}", "func withPatientrightstypeID(id int) patientrightstypeOption {\n\treturn func(m *PatientrightstypeMutation) {\n\t\tvar (\n\t\t\terr error\n\t\t\tonce sync.Once\n\t\t\tvalue *Patientrightstype\n\t\t)\n\t\tm.oldValue = func(ctx context.Context) (*Patientrightstype, error) {\n\t\t\tonce.Do(func() {\n\t\t\t\tif m.done {\n\t\t\t\t\terr = fmt.Errorf(\"querying old values post mutation is not allowed\")\n\t\t\t\t} else {\n\t\t\t\t\tvalue, err = m.Client().Patientrightstype.Get(ctx, id)\n\t\t\t\t}\n\t\t\t})\n\t\t\treturn value, err\n\t\t}\n\t\tm.id = &id\n\t}\n}", "func (m *HexMutation) SetRobberID(id int) {\n\tm.robber = &id\n}", "func (m *PatientrightstypeMutation) PatientrightstypeAbilitypatientrightsID() (id int, exists bool) {\n\tif m._PatientrightstypeAbilitypatientrights != nil {\n\t\treturn *m._PatientrightstypeAbilitypatientrights, true\n\t}\n\treturn\n}", "func (v Vect) TurnRight() Vect {\n\tif v.X == 0 {\n\t\tif v.Y == 1 {\n\t\t\treturn Vect{1, 0}\n\t\t}\n\t\tif v.Y == -1 {\n\t\t\treturn Vect{-1, 0}\n\t\t}\n\t}\n\tif v.X == -1 {\n\t\treturn Vect{0, 1}\n\t}\n\treturn Vect{0, -1}\n}" ]
[ "0.69573504", "0.59875613", "0.5662351", "0.56364334", "0.548881", "0.5417917", "0.523246", "0.52043736", "0.5199709", "0.5080951", "0.49201763", "0.49007967", "0.48246032", "0.4820003", "0.48147878", "0.48145658", "0.47534108", "0.47301134", "0.4703716", "0.4702519", "0.4677242", "0.46316954", "0.45923066", "0.45628864", "0.4554426", "0.45290717", "0.448803", "0.44536132", "0.4432926", "0.442871", "0.44276986", "0.44222197", "0.44137174", "0.439812", "0.43866554", "0.43849498", "0.43539312", "0.43507558", "0.4350622", "0.4350487", "0.4334026", "0.43269095", "0.43229887", "0.43067384", "0.42990217", "0.42953527", "0.42910275", "0.42877096", "0.4279938", "0.42775458", "0.42773992", "0.42612842", "0.42498067", "0.42429796", "0.42313668", "0.4222659", "0.42193103", "0.41973707", "0.419737", "0.41859823", "0.41827014", "0.41689125", "0.41614002", "0.41540313", "0.4152069", "0.41515395", "0.41462195", "0.4134804", "0.41309103", "0.41297337", "0.41270864", "0.41251895", "0.4122556", "0.4119962", "0.41156468", "0.41016012", "0.40952483", "0.40935826", "0.4088272", "0.40766665", "0.4073782", "0.40714705", "0.40713423", "0.40675265", "0.40596926", "0.40561056", "0.40531978", "0.40512997", "0.40472564", "0.40469402", "0.40451765", "0.4041639", "0.40163246", "0.4015327", "0.40105307", "0.40082115", "0.40008748", "0.39976987", "0.3995907", "0.39862475" ]
0.8305589
0
TakeSeat can be used to set the seat number for the philosopher.
func (pd *philosopherData) TakeSeat(seatNumber int) { pd.seat = seatNumber }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pd *philosopherData) Seat() int {\n\treturn pd.seat\n}", "func (_XStaking *XStakingTransactorSession) Stake(amount *big.Int) (*types.Transaction, error) {\n\treturn _XStaking.Contract.Stake(&_XStaking.TransactOpts, amount)\n}", "func (_XStaking *XStakingSession) Stake(amount *big.Int) (*types.Transaction, error) {\n\treturn _XStaking.Contract.Stake(&_XStaking.TransactOpts, amount)\n}", "func (_IStakingRewards *IStakingRewardsSession) Stake(amount *big.Int) (*types.Transaction, error) {\n\treturn _IStakingRewards.Contract.Stake(&_IStakingRewards.TransactOpts, amount)\n}", "func (_IStakingRewards *IStakingRewardsTransactorSession) Stake(amount *big.Int) (*types.Transaction, error) {\n\treturn _IStakingRewards.Contract.Stake(&_IStakingRewards.TransactOpts, amount)\n}", "func (g General) ReserveSeat(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tid := ps.ByName(\"id\")\n\tdata, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\t// Should log error here\n\t\tw.WriteHeader(500)\n\t\treturn\n\t}\n\tflight := g.Schedule.FindFlight(id)\n\tif flight == nil {\n\t\t// Should log error here\n\t\tw.WriteHeader(404)\n\t\treturn\n\t}\n\n\tvar reservation map[string][]string\n\tif err = json.Unmarshal(data, &reservation); err != nil {\n\t\t// Should log error here\n\t\tw.WriteHeader(500)\n\t\treturn\n\t}\n\treserves, ok := reservation[\"reserves\"]\n\tif !ok {\n\t\t// Should log error here\n\t\tw.WriteHeader(400)\n\t\treturn\n\t}\n\tvar wg sync.WaitGroup\n\tvar errors []error\n\tfor _, shortcut := range reserves {\n\t\twg.Add(1)\n\t\tgo func(shortcut string) {\n\t\t\terr := flight.Plane.ReserveSeat(shortcut)\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t\twg.Done()\n\t\t}(shortcut)\n\t}\n\twg.Wait()\n\tif len(errors) == 0 {\n\t\tw.WriteHeader(200)\n\t\treturn\n\t}\n\n\terrorsDto := map[string][]error{\n\t\t\"errors\": errors,\n\t}\n\tw.WriteHeader(500)\n\tg.sendJSON(w, errorsDto)\n}", "func (_IStakingRewards *IStakingRewardsTransactor) Stake(opts *bind.TransactOpts, amount *big.Int) (*types.Transaction, error) {\n\treturn _IStakingRewards.contract.Transact(opts, \"stake\", amount)\n}", "func (_XStaking *XStakingTransactor) Stake(opts *bind.TransactOpts, amount *big.Int) (*types.Transaction, error) {\n\treturn _XStaking.contract.Transact(opts, \"stake\", amount)\n}", "func (s *Sportbike) GetSeats() int {\n\treturn 1\n}", "func (_Lmc *LmcTransactor) Stake(opts *bind.TransactOpts, _tokenAmount *big.Int) (*types.Transaction, error) {\n\treturn _Lmc.contract.Transact(opts, \"stake\", _tokenAmount)\n}", "func (_Lmc *LmcTransactorSession) Stake(_tokenAmount *big.Int) (*types.Transaction, error) {\n\treturn _Lmc.Contract.Stake(&_Lmc.TransactOpts, _tokenAmount)\n}", "func (s *SportMotor) NumSeats() int {\n\treturn 1\n}", "func (b *BikeBuilder) SetSeats() BuildProcess {\n\tb.v.Seats = 2\n\treturn b\n}", "func (c *CarBuilder) SetSeats() BuildProcess {\n\tc.v.Seats = 5\n\treturn c\n}", "func (_Lmc *LmcSession) Stake(_tokenAmount *big.Int) (*types.Transaction, error) {\n\treturn _Lmc.Contract.Stake(&_Lmc.TransactOpts, _tokenAmount)\n}", "func (p *Poset) StakeOf(addr hash.Peer) uint64 {\n\tf := p.frame(p.state.LastFinishedFrameN+stateGap, true)\n\tdb := p.store.StateDB(f.Balances)\n\treturn db.VoteBalance(addr)\n}", "func (o *Drive) GetSeat(ctx context.Context) (seat string, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Seat\").Store(&seat)\n\treturn\n}", "func (_ChpRegistry *ChpRegistryTransactorSession) Stake(_nodeIp uint32, _rewardsAddr common.Address) (*types.Transaction, error) {\n\treturn _ChpRegistry.Contract.Stake(&_ChpRegistry.TransactOpts, _nodeIp, _rewardsAddr)\n}", "func (_ChpRegistry *ChpRegistryTransactor) Stake(opts *bind.TransactOpts, _nodeIp uint32, _rewardsAddr common.Address) (*types.Transaction, error) {\n\treturn _ChpRegistry.contract.Transact(opts, \"stake\", _nodeIp, _rewardsAddr)\n}", "func (_ChpRegistry *ChpRegistrySession) Stake(_nodeIp uint32, _rewardsAddr common.Address) (*types.Transaction, error) {\n\treturn _ChpRegistry.Contract.Stake(&_ChpRegistry.TransactOpts, _nodeIp, _rewardsAddr)\n}", "func (broadcast *Broadcast) StakeIn(ctx context.Context, username, deposit,\n\tprivKeyHex string, seq int64) (*model.BroadcastResponse, error) {\n\tmsg := model.StakeInMsg{\n\t\tUsername: username,\n\t\tDeposit: deposit,\n\t}\n\treturn broadcast.broadcastTransaction(ctx, msg, privKeyHex, seq, \"\", false)\n}", "func (h *Hub) FindSeat(d string) (*Room, Game) {\n\n\t/* \tHandle resurrecting a game. A when a websocket connection disconnects, which is common,\n\t \trely on an incomplete in play game, and return that old seat to the user without making\n\t\ta new room from scratch.\n\t */\n\n\tgame, err := GameDaoInstance().FindIncompleteGameForDevice(d)\n\n\tif err == nil && game.ID != \"\" {\n\t\troom, err := RoomDaoInstance().FindRoom(game.Room)\n\n\t\tif err == nil && room != nil {\n\t\t\tif h.hub[room.Name] != nil {\n\t\t\t\treturn h.hub[room.Name], game\n\t\t\t} else {\n\t\t\t\th.hub[room.Name] = room\n\t\t\t\t// Because this room is no longer in memory, clear out the clients.\n\t\t\t\troom.Clients = make(map[string]*Client)\n\t\t\t\treturn room, game\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Println(\"Finding a seat.\")\n\n\tfor _, room := range h.hub {\n\t\t/* Iterate through to check if the room has a seat available, that the game is not currently in play, and the\n\t\t * existing deviceId is not already in.\n\t\t */\n\t\tif len(room.PlayerId) < 2 && room.InPlay == false && !containsPlayerId(d, room) && !isBlackListed(d, room) {\n\n\t\t\treturn room, game\n\t\t}\n\t}\n\n\t// If we make it here, create the room anew.\n\tlog.Println(\"No seats found; creating a room anew.\")\n\treturn h.CreateRoom(time.Now().String()), game\n}", "func (_RandomBeacon *RandomBeaconCallerSession) Staking() (common.Address, error) {\n\treturn _RandomBeacon.Contract.Staking(&_RandomBeacon.CallOpts)\n}", "func getSeatCount() (seatCount int) {\n\tvar err error\n\tif len(os.Args) > 1 {\n\t\tseatCount, err = strconv.Atoi(os.Args[1])\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"\\nFATAL: seatCount parameter could not be converted to int: %v\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t} else {\n\t\tseatCount = 1\n\t}\n\treturn\n}", "func (_RandomBeacon *RandomBeaconSession) Staking() (common.Address, error) {\n\treturn _RandomBeacon.Contract.Staking(&_RandomBeacon.CallOpts)\n}", "func (f Fortune) Stake() decimal.Decimal { return f.stake }", "func (broadcast *Broadcast) StakeOut(ctx context.Context, username, amount,\n\tprivKeyHex string, seq int64) (*model.BroadcastResponse, error) {\n\tmsg := model.StakeOutMsg{\n\t\tUsername: username,\n\t\tAmount: amount,\n\t}\n\treturn broadcast.broadcastTransaction(ctx, msg, privKeyHex, seq, \"\", false)\n}", "func (s *Seat) SetSeatClosed() {\n\ts.SeatClosed = true\n}", "func (rig *testRig) auditSwap_taker() error {\n\tmatchInfo := rig.matchInfo\n\tif rig.auth.newReq != nil {\n\t\tselect {\n\t\tcase <-rig.auth.newReq:\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"no taker audit request\")\n\t\t}\n\t}\n\treq := rig.auth.getReq(matchInfo.taker.acct)\n\tmatchInfo.db.takerAudit = req\n\tif req == nil {\n\t\treturn fmt.Errorf(\"failed to find audit request for taker after maker's init\")\n\t}\n\treturn rig.auditSwap(req.req, matchInfo.takerOID, matchInfo.db.makerSwap.contract, \"taker\", matchInfo.taker)\n}", "func (k Keeper) SetStake(ctx sdk.Context, delAddr sdk.AccAddress, s types.Stake) {\n\tstore := ctx.KVStore(k.storeKey)\n\tkey := types.StakeKey(s.VendorID, s.PostID, delAddr)\n\tvalue := k.MustMarshalStake(s)\n\tstore.Set(key, value)\n}", "func (_Casper *CasperTransactor) SetPrice(opts *bind.TransactOpts, newPrice *big.Int) (*types.Transaction, error) {\n\treturn _Casper.contract.Transact(opts, \"setPrice\", newPrice)\n}", "func (f *Fortune) Skim(amount decimal.Decimal) {\n\tf.active.Sub(amount)\n\tf.saving.Add(amount)\n}", "func (snake *Snake) Eat(eatme Edible) {\n\n\toldLength := snake.length\n\n\tif snake.advanced && snake.size < maxSize {\n\n\t\tsnake.size += sizeIncrease\n\t\tsnake.avatar = snake.GetImageForSize(int(snake.size))\n\n\t}\n\n\tsnake.length += eatme.amount()\n\n\tif snake.length > maxLength {\n\t\tsnake.length = maxLength\n\t}\n\n\tif snake.length != oldLength {\n\n\t\t//tail will now be longer, which we can\n\t\t//now go through, and \"skip\" our old length #-1\n\t\t//of segments, and set them all to the old length-1'th\n\t\t//position\n\n\t\tmyTail := snake.GetMyTail().Skip(oldLength - 1)\n\t\tlastSegment := <-myTail\n\n\t\tfor segment := range myTail {\n\t\t\tsegment.x = lastSegment.x\n\t\t\tsegment.y = lastSegment.y\n\t\t}\n\n\t}\n\n}", "func (snake Snake) Eat() {\n\tfmt.Println(snake.food)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepCallerSession) MemberStake() (*big.Int, error) {\n\treturn _BondedECDSAKeep.Contract.MemberStake(&_BondedECDSAKeep.CallOpts)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) MemberStake() (*big.Int, error) {\n\treturn _BondedECDSAKeep.Contract.MemberStake(&_BondedECDSAKeep.CallOpts)\n}", "func (clt *SMServiceClient) ProposeSupply(spo *SupplyOpts) uint64 {\n\tpid := GenerateIntID()\n\tts := ptypes.TimestampNow()\n\tsp := &Supply{\n\t\tId: pid,\n\t\tSenderId: uint64(clt.ClientID),\n\t\tTargetId: spo.Target,\n\t\tType: clt.MType,\n\t\tTs: ts,\n\t\tSupplyName: spo.Name,\n\t\tArgJson: spo.JSON,\n\t}\n\n\tif spo.SimSupply != nil {\n\t\tsp.WithSimSupply(spo.SimSupply)\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\t_, err := clt.Client.ProposeSupply(ctx, sp)\n\t//log.Printf(\"%v.Test err %v, [%v]\", clt, err, sp)\n\tif err != nil {\n\t\tlog.Printf(\"%v.ProposeSupply err %v, [%v]\", clt, err, sp)\n\t\treturn 0 // should check...\n\t}\n\treturn pid\n}", "func (p *Bare) sprintTrice() (n int, err error) {\n\tswitch p.trice.Type {\n\tcase \"TRICE0\":\n\t\treturn p.trice0()\n\tcase \"TRICE8_1\":\n\t\treturn p.trice81()\n\tcase \"TRICE8_2\":\n\t\treturn p.trice82()\n\tcase \"TRICE8_3\":\n\t\treturn p.trice83()\n\tcase \"TRICE8_4\":\n\t\treturn p.trice84()\n\tcase \"TRICE8_5\":\n\t\treturn p.trice85()\n\tcase \"TRICE8_6\":\n\t\treturn p.trice86()\n\tcase \"TRICE8_7\":\n\t\treturn p.trice87()\n\tcase \"TRICE8_8\":\n\t\treturn p.trice88()\n\tcase \"TRICE16_1\":\n\t\treturn p.trice161()\n\tcase \"TRICE16_2\":\n\t\treturn p.trice162()\n\tcase \"TRICE16_3\":\n\t\treturn p.trice163()\n\tcase \"TRICE16_4\":\n\t\treturn p.trice164()\n\tcase \"TRICE32_1\":\n\t\treturn p.trice321()\n\tcase \"TRICE32_2\":\n\t\treturn p.trice322()\n\tcase \"TRICE32_3\":\n\t\treturn p.trice323()\n\tcase \"TRICE32_4\":\n\t\treturn p.trice324()\n\tcase \"TRICE64_1\":\n\t\treturn p.trice641()\n\tcase \"TRICE64_2\":\n\t\treturn p.trice642()\n\t}\n\treturn p.outOfSync(fmt.Sprintf(\"Unexpected trice.Type %s\", p.trice.Type))\n}", "func (_Casper *CasperTransactorSession) SetPrice(newPrice *big.Int) (*types.Transaction, error) {\n\treturn _Casper.Contract.SetPrice(&_Casper.TransactOpts, newPrice)\n}", "func NewSeats(size int) []*Seat {\n\tseats := make([]*Seat, size)\n\tfor i := 0; i < size; i++ {\n\t\tseats[i] = NewSeat()\n\t}\n\n\treturn seats\n}", "func (w *rpcWallet) StakeInfo(ctx context.Context) (*wallet.StakeInfoData, error) {\n\tres, err := w.rpcClient.GetStakeInfo(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsdiff, err := dcrutil.NewAmount(res.Difficulty)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttotalSubsidy, err := dcrutil.NewAmount(res.TotalSubsidy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &wallet.StakeInfoData{\n\t\tBlockHeight: res.BlockHeight,\n\t\tTotalSubsidy: totalSubsidy,\n\t\tSdiff: sdiff,\n\t\tOwnMempoolTix: res.OwnMempoolTix,\n\t\tUnspent: res.Unspent,\n\t\tVoted: res.Voted,\n\t\tRevoked: res.Revoked,\n\t\tUnspentExpired: res.UnspentExpired,\n\t\tPoolSize: res.PoolSize,\n\t\tAllMempoolTix: res.AllMempoolTix,\n\t\tImmature: res.Immature,\n\t\tLive: res.Live,\n\t\tMissed: res.Missed,\n\t\tExpired: res.Expired,\n\t}, nil\n}", "func (g *Game) Shot(shot int) {\n\n\tif g.isOver() {\n\t\tfmt.Println(\"Illegal extra shot\")\n\t\treturn\n\t}\n\tfmt.Printf(\"Shot: %d, Pinup: %d. Game frames: %v \\n\", shot, g.numPinUp, g.frames)\n\tg.accountBonus(shot)\n\tg.recordShot(shot)\n\tg.prepareNextShot()\n}", "func (_Lmc *LmcCallerSession) StakeLimit() (*big.Int, error) {\n\treturn _Lmc.Contract.StakeLimit(&_Lmc.CallOpts)\n}", "func (stg *SimpleStrategy) SetTakeProfit(openPosition kate.Position) *kate.TakeProfitEvt {\n\tif openPosition.Direction == kate.LONG && openPosition.TakeProfit <= 0 {\n\t\treturn &kate.TakeProfitEvt{Price: openPosition.EntryPrice * 1.005}\n\t}\n\treturn nil\n}", "func (s *state4) SettlingAt() (abi.ChainEpoch, error) {/* 0E6 counters maximum */\n\treturn s.State.SettlingAt, nil\n}", "func (_Lmc *LmcSession) StakeLimit() (*big.Int, error) {\n\treturn _Lmc.Contract.StakeLimit(&_Lmc.CallOpts)\n}", "func (_Bindings *BindingsTransactor) Seize(opts *bind.TransactOpts, liquidator common.Address, borrower common.Address, seizeTokens *big.Int) (*types.Transaction, error) {\n\treturn _Bindings.contract.Transact(opts, \"seize\", liquidator, borrower, seizeTokens)\n}", "func (_EtherDelta *EtherDeltaSession) ChangeFeeTake(feeTake_ *big.Int) (*types.Transaction, error) {\n\treturn _EtherDelta.Contract.ChangeFeeTake(&_EtherDelta.TransactOpts, feeTake_)\n}", "func (m *SecureScoreControlProfile) SetTier(value *string)() {\n err := m.GetBackingStore().Set(\"tier\", value)\n if err != nil {\n panic(err)\n }\n}", "func (_Harberger *HarbergerTransactor) SetPrice(opts *bind.TransactOpts, _tokenId *big.Int, _price *big.Int) (*types.Transaction, error) {\n\treturn _Harberger.contract.Transact(opts, \"setPrice\", _tokenId, _price)\n}", "func SawTooth(x, period float64) float64 {\n\tx += period / 2\n\tt := x / period\n\treturn period*(t-math.Floor(t)) - period/2\n}", "func (t *SimpleChaincode) transferCert(APIstub shim.ChaincodeStubInterface, args []string) pb.Response {\n\t// 0 1\n\t// \"Seatno\", \"SName\"\n\tif len(args) < 2 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 2\")\n\t}\n\tSeatno := args[0]\n\tSName := args[1]\n\n\tcertAsBytes, err := APIstub.GetState(Seatno)\n\tif certAsBytes == nil {\n\t\treturn shim.Error(\"Could not locate Cert\")\n\t}\n\tcertToTransfer := cert{}\n\tjson.Unmarshal(certAsBytes, &certToTransfer) //unmarshal it aka JSON.parse()\n\n\tcertToTransfer.Student_Name = SName //change the owner\n\n\tcertJSONasBytes, _ := json.Marshal(certToTransfer)\n\terr = APIstub.PutState(Seatno, certJSONasBytes) //rewrite the certificate\n\tif err != nil {\n\t\treturn shim.Error(fmt.Sprintf(\"Failed to change Cert holder: %s\", Seatno))\n\t}\n\n\treturn shim.Success(nil)\n}", "func (*SeatDataAccessObject) DeleteBySeatID(seatID int) {\n\tvar seat Seat\n\t_, err := orm.Table(seat).ID(seatID).Delete(&seat)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (_EtherDelta *EtherDeltaTransactorSession) ChangeFeeTake(feeTake_ *big.Int) (*types.Transaction, error) {\n\treturn _EtherDelta.Contract.ChangeFeeTake(&_EtherDelta.TransactOpts, feeTake_)\n}", "func (_RandomBeacon *RandomBeaconCaller) EligibleStake(opts *bind.CallOpts, stakingProvider common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _RandomBeacon.contract.Call(opts, &out, \"eligibleStake\", stakingProvider)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (v *victorianChair) SitDown() string {\n\treturn \"Sitting on the victorian chair\"\n}", "func (peer *Peer) Seen() {\n\tpeer.LastSeen = utc.UnixNow()\n}", "func (_CrToken *CrTokenTransactor) Seize(opts *bind.TransactOpts, liquidator common.Address, borrower common.Address, seizeTokens *big.Int) (*types.Transaction, error) {\n\treturn _CrToken.contract.Transact(opts, \"seize\", liquidator, borrower, seizeTokens)\n}", "func (_Casper *CasperSession) SetPrice(newPrice *big.Int) (*types.Transaction, error) {\n\treturn _Casper.Contract.SetPrice(&_Casper.TransactOpts, newPrice)\n}", "func (_RandomBeacon *RandomBeaconSession) EligibleStake(stakingProvider common.Address) (*big.Int, error) {\n\treturn _RandomBeacon.Contract.EligibleStake(&_RandomBeacon.CallOpts, stakingProvider)\n}", "func (a Snake) Eat() {\n\tfmt.Printf(\"%s \\n\", a.food)\n}", "func NewSeatAssignment(code string) SeatAssignment {\n\t// Cheating.\n\trowCode := code[:7]\n\trowCode = strings.ReplaceAll(rowCode, \"B\", \"1\")\n\trowCode = strings.ReplaceAll(rowCode, \"F\", \"0\")\n\trow, err := strconv.ParseInt(rowCode, 2, 64)\n\tif err != nil {\n\t\t//fmt.Printf(\"Failed parsing row from %s\", code)\n\t}\n\tcolCode := code[7:]\n\tcolCode = strings.ReplaceAll(colCode, \"R\", \"1\")\n\tcolCode = strings.ReplaceAll(colCode, \"L\", \"0\")\n\tcol, err := strconv.ParseInt(colCode, 2, 64)\n\tif err != nil {\n\t\t//fmt.Printf(\"Failed parsing column from %s\", code)\n\t}\n\n\tseatID := row*8 + col\n\n\treturn SeatAssignment{\n\t\tcode: code,\n\t\trowCode: rowCode,\n\t\tcolCode: rowCode,\n\t\trow: row,\n\t\tcolumn: col,\n\t\tSeatID: seatID,\n\t}\n}", "func SecondHand(t time.Time) Point {\n\treturn Point{150, 60}\n}", "func (_Bindings *BindingsTransactorSession) Seize(liquidator common.Address, borrower common.Address, seizeTokens *big.Int) (*types.Transaction, error) {\n\treturn _Bindings.Contract.Seize(&_Bindings.TransactOpts, liquidator, borrower, seizeTokens)\n}", "func (gt *myGoTickle) Take() {\n\t<-gt.ticketCh\n}", "func (_RandomBeacon *RandomBeaconCaller) Staking(opts *bind.CallOpts) (common.Address, error) {\n\tvar out []interface{}\n\terr := _RandomBeacon.contract.Call(opts, &out, \"staking\")\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (_RandomBeacon *RandomBeaconCallerSession) EligibleStake(stakingProvider common.Address) (*big.Int, error) {\n\treturn _RandomBeacon.Contract.EligibleStake(&_RandomBeacon.CallOpts, stakingProvider)\n}", "func (m *SecureScoreControlProfile) SetThreats(value []string)() {\n m.threats = value\n}", "func (*SeatDataAccessObject) FindByID(seatID int) *Seat {\n\tvar seat Seat\n\thas, err := orm.Table(seat).ID(seatID).Get(&seat)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif !has {\n\t\treturn nil\n\t}\n\treturn &seat\n}", "func (_BondedECDSAKeep *BondedECDSAKeepCaller) MemberStake(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BondedECDSAKeep.contract.Call(opts, out, \"memberStake\")\n\treturn *ret0, err\n}", "func (r *SubscriptionsService) ChangeSeats(customerId string, subscriptionId string, seats *Seats) *SubscriptionsChangeSeatsCall {\n\treturn &SubscriptionsChangeSeatsCall{\n\t\ts: r.s,\n\t\tcustomerId: customerId,\n\t\tsubscriptionId: subscriptionId,\n\t\tseats: seats,\n\t\tcaller_: googleapi.JSONCall{},\n\t\tparams_: make(map[string][]string),\n\t\tpathTemplate_: \"customers/{customerId}/subscriptions/{subscriptionId}/changeSeats\",\n\t\tcontext_: googleapi.NoContext,\n\t}\n}", "func (*SeatDataAccessObject) FindByMerchantIDAndNumber(merchantID int,\n\tnumber string) *Seat {\n\n\tvar seat Seat\n\thas, err := orm.Table(seat).Where(\"MerchantID = ? AND Number = ?\",\n\t\tmerchantID, number).Get(&seat)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif !has {\n\t\treturn nil\n\t}\n\treturn &seat\n\n}", "func (m *SecureScoreControlProfile) SetThreats(value []string)() {\n err := m.GetBackingStore().Set(\"threats\", value)\n if err != nil {\n panic(err)\n }\n}", "func (_EtherDelta *EtherDeltaCallerSession) FeeTake() (*big.Int, error) {\n\treturn _EtherDelta.Contract.FeeTake(&_EtherDelta.CallOpts)\n}", "func (*SeatDataAccessObject) FindByMerchantID(merchantID int) []Seat {\n\tseatList := make([]Seat, 0)\n\terr := orm.Table(\"Seat\").Where(\"MerchantID=?\", merchantID).Find(&seatList)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn seatList\n}", "func SetAt(t int64) {\n\tinternal.Syscall1i64(SETAT, t)\n}", "func (o *GetLogsParams) SetTake(take *int64) {\n\to.Take = take\n}", "func (s *Spanet) SetHour(hour int) (int, error) {\n\treturn s.commandInt(\"S04\", hour, 0, 23, \"hour\", \"%02d\")\n}", "func (m *SecureScoreControlProfile) SetTier(value *string)() {\n m.tier = value\n}", "func (app *application) recordStrike(w http.ResponseWriter, r *http.Request) {\n\ttype PlayerTurn struct {\n\t\tValid \t\t\tbool\t\t\t`json:\"valid\"`\n\t\tPinColor\t\tstring\t\t\t`json:\"pin_color\"`\n\t\tShipType\t\tstring\t\t\t`json:\"sunken_ship\"`\n\t\tWinner\t\t\tbool\t\t\t`json:\"winner\"`\n\t}\n\n\terr := r.ParseForm()\n\tform := forms.New(r.PostForm)\n\tbattleID, _ := strconv.Atoi(form.Get(\"battleID\"))\n\tboardID, _ := strconv.Atoi(form.Get(\"boardID\"))\n\tcoordX, _ := strconv.Atoi(form.Get(\"coordX\"))\n\tcoordY := form.Get(\"coordY\")\n\t//fmt.Println(\"coordX:\", coordX, \"|coordY:\", coordY)\n\t//fmt.Println(\"battleID:\", battleID)\n\t//fmt.Println(\"boardID:\", boardID)\n\tplayerID := app.session.GetInt(r, \"authenticatedPlayerID\")\n\tsecretTurn := form.Get(\"secretTurn\")\n\tvar out []byte;\n\tvar PT PlayerTurn\n\n\tplayerTakingTheirTurn, validTurn := app.checkTurn(playerID, battleID, secretTurn)\n\tif validTurn {\n\t\t// Make sure this player belongs to this battle\n\t\t//checkBattle(playerID, battleID)\n\t\t// Update the database with the new strike, update Turn to be the other player\n\t\tnewSecret, err := app.GenerateRandomString(32)\n\t\tif err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t}\n\t\tpinColor, shipType, winner, err := app.positions.Update(playerID, playerTakingTheirTurn, battleID, boardID, coordX, coordY, newSecret)\n\t\tif err != nil {\n\t\t\tapp.infoLog.Println(\"Update failed for \", playerID, battleID, boardID, coordX, coordY)\n\t\t\tapp.errorLog.Println(\"Error\", err.Error())\n\t\t}\n\t\t//fmt.Println(\"pinColor is\", pinColor)\n\t\tPT.Valid = true\n\t\tPT.PinColor = pinColor\n\t\tPT.ShipType = shipType\n\t\tPT.Winner = winner\n\t\tout, err = json.Marshal(PT)\n\t\tif err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t}\n\t} else {\n\t\tapp.errorLog.Println(\"Looks like somebody is attempting to hack or the person submitting the strike is not in sync with the database...\")\n\t\tPT.Valid = false\n\t\tPT.PinColor = \"\"\n\t\tPT.ShipType = \"charlie\"\n\t\tPT.Winner = false\n\t\tout, err = json.Marshal(PT)\n\t\tif err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t}\n\t}\n\tapp.renderJson(w, r, out)\n}", "func (thisInv *inventory)StockShelf() { // Decrement inventory where getting it from it \n\tfor (thisInv.inventoryCokeCount >= 0 || thisInv.inventoryPepsiCount >= 0) {\n\t\ttime.Sleep(10 * time.Millisecond)\n\t\trand.Seed(time.Now().UnixNano())\n\t\tvar brandSelector int = (rand.Intn(2)) + 1\n\t\tif (brandSelector == 1) {\n\t\t\tthisInv.shelfCokeCount += 1\n\t\t\tfmt.Println(\"1 Coke Can Placed on Shelf\")\n\t\t} else if (brandSelector == 2) {\n\t\t\tthisInv.shelfPepsiCount += 1\n\t\t\tfmt.Println(\"1 Pepsi Can Placed on Shelf\")\n\t\t}\n\t}\n}", "func (k Keeper) SetStakeStruct(ctx sdk.Context, stakeID string, stakestruct StakeStruct) {\n\tstore := ctx.KVStore(k.storeKey)\n\tstore.Set([]byte(stakeID), k.cdc.MustMarshalBinaryBare(stakestruct))\n}", "func dealerselect(indcard int) int {\n\tvar newdcard int // Number of cards in the hand.\n\n\tswitch {\n\tcase DealerTotal < 17:\n\t\t// Less than 17? Hit. Unless tied or winning.\n\t\tnewdcard = indcard + 1\n\t\tfmt.Println(\"Dealer takes a card.\")\n\t\tkutil.Pause(2)\n\tcase DealerTotal >= 17:\n\t\t// If dealer total greater or equal to 17, stay.\n\t\tnewdcard = indcard\n\t\tfmt.Println(\"Dealer stays.\")\n\t\tkutil.Pause(2)\n\t}\n\n\treturn newdcard\n}", "func (rig *testRig) sendSwap_taker(checkStatus bool) (err error) {\n\tmatchInfo := rig.matchInfo\n\ttaker := matchInfo.taker\n\tswap, err := rig.sendSwap(taker, matchInfo.takerOID, matchInfo.maker.addr)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error sending taker swap transaction: %w\", err)\n\t}\n\tmatchInfo.db.takerSwap = swap\n\tif err != nil {\n\t\treturn err\n\t}\n\ttracker := rig.getTracker()\n\t// Check the match status.\n\tif checkStatus {\n\t\tif tracker.Status != order.TakerSwapCast {\n\t\t\treturn fmt.Errorf(\"unexpected swap status %d after taker swap notification\", tracker.Status)\n\t\t}\n\t\terr := rig.checkResponse(matchInfo.taker, \"init\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (_Bindings *BindingsSession) Seize(liquidator common.Address, borrower common.Address, seizeTokens *big.Int) (*types.Transaction, error) {\n\treturn _Bindings.Contract.Seize(&_Bindings.TransactOpts, liquidator, borrower, seizeTokens)\n}", "func (o *AlertGetMonitorGroupAlertsParams) SetTake(take *int32) {\n\to.Take = take\n}", "func performSeatChange(seatRows [][]byte) (bool, [][]byte) {\n\tvar seatRowsCopy [][]byte\n\tseatChange := false\n\tfor rowIndex := 0; rowIndex < numRows; rowIndex++ {\n\t\trowCopy := make([]byte, numSeats)\n\t\tfor seatIndex := 0; seatIndex < numSeats; seatIndex++ {\n\t\t\tseatStatus := seatRows[rowIndex][seatIndex]\n\t\t\tif seatStatus == '.' {\n\t\t\t\trowCopy[seatIndex] = seatStatus\n\t\t\t\tcontinue // Floor\n\t\t\t}\n\n\t\t\toccupiedAjacentSeats := countOccupiedAjacentSeats(rowIndex, seatIndex, seatRows)\n\t\t\tif occupiedAjacentSeats == 0 {\n\t\t\t\trowCopy[seatIndex] = '#' // occupied\n\t\t\t\tif rowCopy[seatIndex] != seatStatus {\n\t\t\t\t\tseatChange = true\n\t\t\t\t}\n\t\t\t} else if occupiedAjacentSeats >= 5 {\n\t\t\t\trowCopy[seatIndex] = 'L' // free\n\t\t\t\tif rowCopy[seatIndex] != seatStatus {\n\t\t\t\t\tseatChange = true\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trowCopy[seatIndex] = seatStatus\n\t\t\t}\n\t\t}\n\t\tseatRowsCopy = append(seatRowsCopy, rowCopy)\n\t}\n\n\treturn seatChange, seatRowsCopy\n}", "func (b *Board) setSpot(x int, y int, s *Spot) {\n\tb.grid[x][y] = s\n}", "func (_EtherDelta *EtherDeltaTransactor) ChangeFeeTake(opts *bind.TransactOpts, feeTake_ *big.Int) (*types.Transaction, error) {\n\treturn _EtherDelta.contract.Transact(opts, \"changeFeeTake\", feeTake_)\n}", "func (_CrToken *CrTokenTransactorSession) Seize(liquidator common.Address, borrower common.Address, seizeTokens *big.Int) (*types.Transaction, error) {\n\treturn _CrToken.Contract.Seize(&_CrToken.TransactOpts, liquidator, borrower, seizeTokens)\n}", "func (_EtherDelta *EtherDeltaSession) FeeTake() (*big.Int, error) {\n\treturn _EtherDelta.Contract.FeeTake(&_EtherDelta.CallOpts)\n}", "func (thisShelf *inventory)MakeCustomers() {\n\tfor (thisShelf.shelfCokeCount >= 0 || thisShelf.shelfPepsiCount >= 0) {\n\t\ttime.Sleep(75 * time.Millisecond)\n\t\trand.Seed(time.Now().UnixNano())\n\t\tvar brandSelector int = (rand.Intn(2)) + 1\n\t\tif (brandSelector == 1) {\n\t\t\ttime.Sleep(75 * time.Millisecond)\n\t\t\trand.Seed(time.Now().UnixNano())\n\t\t\tvar canNumSelector int = (rand.Intn(4)) + 1\n\t\t\tvar actualNumCoke int\n\t\t\tif (canNumSelector == 1) {\n\t\t\t\tactualNumCoke = 6\n\t\t\t} else if (canNumSelector == 2) {\n\t\t\t\tactualNumCoke = 12\n\t\t\t} else if (canNumSelector == 3) {\n\t\t\t\tactualNumCoke = 18\n\t\t\t} else {\n\t\t\t\tactualNumCoke = 24\n\t\t\t}\n\t\t\tvar numRemovedCoke int = 0\n\t\t\tfor (numRemovedCoke == 0) {\n\t\t\t\tif (thisShelf.shelfCokeCount > actualNumCoke) {\n\t\t\t\t\tthisShelf.shelfCokeCount = thisShelf.shelfCokeCount - actualNumCoke\n\t\t\t\t\tnumRemovedCoke = actualNumCoke\n\t\t\t\t}\n\t\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t\t}\n\t\t\tthisShelf.checkoutCokeCount = thisShelf.checkoutCokeCount + numRemovedCoke\n\t\t\tfmt.Println(numRemovedCoke, \" Cans of Coke Removed from Shelf by Customer\")\n\t\t} else if (brandSelector == 2) {\n\t\t\ttime.Sleep(75 * time.Millisecond)\n\t\t\trand.Seed(time.Now().UnixNano())\n\t\t\tvar canNumSelector2 int = (rand.Intn(4)) + 1\n\t\t\tvar actualNumPepsi int\n\t\t\tif (canNumSelector2 == 1) {\n\t\t\t\tactualNumPepsi = 6\n\t\t\t} else if (canNumSelector2 == 2) {\n\t\t\t\tactualNumPepsi = 12\n\t\t\t} else if (canNumSelector2 == 3) {\n\t\t\t\tactualNumPepsi = 18\n\t\t\t} else {\n\t\t\t\tactualNumPepsi = 24\n\t\t\t}\n\t\t\tvar numRemovedPepsi int = 0\n\t\t\tfor (numRemovedPepsi == 0) {\n\t\t\t\tif (thisShelf.shelfPepsiCount > actualNumPepsi) {\n\t\t\t\t\tthisShelf.shelfPepsiCount = thisShelf.shelfPepsiCount - actualNumPepsi\n\t\t\t\t\tnumRemovedPepsi = actualNumPepsi\n\t\t\t\t}\n\t\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t\t}\n\t\t\tthisShelf.checkoutPepsiCount = thisShelf.checkoutPepsiCount + numRemovedPepsi\n\t\t\tfmt.Println(numRemovedPepsi, \" Cans of Pepsi Removed from Shelf by Customer\")\n\t\t}\n\t}\n}", "func (_Harberger *HarbergerTransactorSession) SetPrice(_tokenId *big.Int, _price *big.Int) (*types.Transaction, error) {\n\treturn _Harberger.Contract.SetPrice(&_Harberger.TransactOpts, _tokenId, _price)\n}", "func (k Keeper) SetStakeData(ctx sdk.Context, stakeID string, name, atom, token string) {\n\tparts := strings.Split(stakeID, \"-\")\n\tstakestruct := k.GetStakeStruct(ctx, stakeID)\n\tstakestruct.Ticker = parts[1]\n\tfound := false\n\tfor i, record := range stakestruct.Stakes {\n\t\tif record.Name == name {\n\t\t\tstakestruct.Stakes[i].Atom = atom\n\t\t\tstakestruct.Stakes[i].Token = token\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\trecord := AccStake{\n\t\t\tName: name,\n\t\t\tAtom: atom,\n\t\t\tToken: token,\n\t\t}\n\t\tstakestruct.Stakes = append(stakestruct.Stakes, record)\n\t}\n\tk.SetStakeStruct(ctx, stakeID, stakestruct)\n}", "func (a *AdditionalGUTI) SetSpare(spare uint8) {}", "func (o *Poke) SetIdentifier(id string) {\n\n}", "func (s *Starbase) TakeDamage(damage int) {\n\ts.Shields -= damage\n}", "func (_ChpRegistry *ChpRegistryTransactorSession) StakeCore(_coreIp uint32, _coreId []byte) (*types.Transaction, error) {\n\treturn _ChpRegistry.Contract.StakeCore(&_ChpRegistry.TransactOpts, _coreIp, _coreId)\n}", "func SsS(playerName string, difficulty int) {\r\n\tpChoice = 0\r\n\twins, loss, tie := 0, 0, 0\r\n\tPrettyPrints(8)\r\n\r\n\tfmt.Printf(\"BEHOLD! YOU HAVE ENTERED THE FIGHT PIT OF TRIPLE S!\\n CHOOSE YOUR WEAPON MORTAL OR DIE A DOG'S DEATH AT THE HANDS OF MOGTAR THE OGRE!\\n\")\r\n\tSssWeapon(wins, loss, tie)\r\n\r\n}", "func (_IUniswapV2Pair *IUniswapV2PairTransactor) Skim(opts *bind.TransactOpts, to common.Address) (*types.Transaction, error) {\r\n\treturn _IUniswapV2Pair.contract.Transact(opts, \"skim\", to)\r\n}" ]
[ "0.6817128", "0.5949888", "0.5916402", "0.59100485", "0.5907139", "0.5810014", "0.571648", "0.5691221", "0.555828", "0.5531796", "0.549875", "0.5491495", "0.5442286", "0.543301", "0.5426342", "0.53746474", "0.5314343", "0.5172025", "0.5138974", "0.50715095", "0.5044223", "0.5019989", "0.501844", "0.49459457", "0.4917476", "0.4903403", "0.48012188", "0.4790299", "0.4770413", "0.47371435", "0.4717259", "0.47005242", "0.46717185", "0.46640733", "0.46402797", "0.4626867", "0.46185544", "0.46109623", "0.45591828", "0.45549187", "0.45214012", "0.4517166", "0.44947344", "0.44808584", "0.447055", "0.44450426", "0.44334304", "0.4430234", "0.442963", "0.44082662", "0.44064757", "0.43871373", "0.438556", "0.4381065", "0.43751422", "0.4371012", "0.43643853", "0.43637782", "0.4357961", "0.43348733", "0.4327676", "0.43251112", "0.4319444", "0.43176427", "0.431429", "0.4305861", "0.42913836", "0.42884743", "0.42857322", "0.4285279", "0.42800045", "0.4276646", "0.42751914", "0.42712134", "0.42678598", "0.42662", "0.42647496", "0.42635292", "0.4260078", "0.42528543", "0.42469478", "0.42291492", "0.42252707", "0.42237633", "0.4223564", "0.42146978", "0.42093337", "0.42070338", "0.42034772", "0.42000902", "0.4199612", "0.4199591", "0.41938755", "0.41901094", "0.41878474", "0.41826463", "0.4178092", "0.4175023", "0.41709137", "0.41699955" ]
0.84893584
0
Seat returns the seat number of the philosopher.
func (pd *philosopherData) Seat() int { return pd.seat }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *Sportbike) GetSeats() int {\n\treturn 1\n}", "func (pd *philosopherData) TakeSeat(seatNumber int) {\n\tpd.seat = seatNumber\n}", "func (s *SportMotor) NumSeats() int {\n\treturn 1\n}", "func getSeatCount() (seatCount int) {\n\tvar err error\n\tif len(os.Args) > 1 {\n\t\tseatCount, err = strconv.Atoi(os.Args[1])\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"\\nFATAL: seatCount parameter could not be converted to int: %v\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t} else {\n\t\tseatCount = 1\n\t}\n\treturn\n}", "func getNumberofSeats(c models.Unit) int {\n\ttemp := 0\n\turl := \"https://courses.students.ubc.ca/cs/courseschedule?pname=subjarea&tname=subj-section&\" +\n\t\t\"dept=\" + c.Dept + \"&course=\" + c.Number + \"&section=\" + c.Section\n\tfmt.Println(\"the url requested is: \" + url)\n\tres, err := http.Get(url)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer res.Body.Close()\n\tif res.StatusCode != 200 {\n\t\tlog.Fatal(\"status code error: %s %d\\n\", res.Status, res.StatusCode)\n\t}\n\tdoc, err := goquery.NewDocumentFromReader(res.Body)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdoc.Find(\"table.\\\\'table\").Each(func(index int, item *goquery.Selection) {\n\t\tinfo := item.Text()\n\t\tseats := strings.Split(info, \"\\n\")\n\t\ttemp, _ = strconv.Atoi(strings.SplitAfter(seats[4], \"General Seats Remaining:\")[1])\n\t})\n\treturn temp\n}", "func (o *Drive) GetSeat(ctx context.Context) (seat string, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Seat\").Store(&seat)\n\treturn\n}", "func (h *Hub) FindSeat(d string) (*Room, Game) {\n\n\t/* \tHandle resurrecting a game. A when a websocket connection disconnects, which is common,\n\t \trely on an incomplete in play game, and return that old seat to the user without making\n\t\ta new room from scratch.\n\t */\n\n\tgame, err := GameDaoInstance().FindIncompleteGameForDevice(d)\n\n\tif err == nil && game.ID != \"\" {\n\t\troom, err := RoomDaoInstance().FindRoom(game.Room)\n\n\t\tif err == nil && room != nil {\n\t\t\tif h.hub[room.Name] != nil {\n\t\t\t\treturn h.hub[room.Name], game\n\t\t\t} else {\n\t\t\t\th.hub[room.Name] = room\n\t\t\t\t// Because this room is no longer in memory, clear out the clients.\n\t\t\t\troom.Clients = make(map[string]*Client)\n\t\t\t\treturn room, game\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Println(\"Finding a seat.\")\n\n\tfor _, room := range h.hub {\n\t\t/* Iterate through to check if the room has a seat available, that the game is not currently in play, and the\n\t\t * existing deviceId is not already in.\n\t\t */\n\t\tif len(room.PlayerId) < 2 && room.InPlay == false && !containsPlayerId(d, room) && !isBlackListed(d, room) {\n\n\t\t\treturn room, game\n\t\t}\n\t}\n\n\t// If we make it here, create the room anew.\n\tlog.Println(\"No seats found; creating a room anew.\")\n\treturn h.CreateRoom(time.Now().String()), game\n}", "func (snake Snake) Eat() {\n\tfmt.Println(snake.food)\n}", "func (s *section) Ident() int {\n\treturn s.sec\n}", "func SearchSeat(n int, f func(int) int) (int, bool) {\n\tidx, low, high := 0, 0, n\n\tfor low < high {\n\t\tmid := int(uint(low+high) >> 1)\n\t\td := f(mid)\n\t\tif d == 0 {\n\t\t\treturn mid, true\n\t\t} else if d < 0 {\n\t\t\tlow = mid + 1\n\t\t\tidx = low\n\t\t} else {\n\t\t\thigh = mid\n\t\t\tidx = mid\n\t\t}\n\t}\n\treturn idx, false\n}", "func NewSeats(size int) []*Seat {\n\tseats := make([]*Seat, size)\n\tfor i := 0; i < size; i++ {\n\t\tseats[i] = NewSeat()\n\t}\n\n\treturn seats\n}", "func STONE() int { return game.Stone }", "func (g General) ReserveSeat(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tid := ps.ByName(\"id\")\n\tdata, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\t// Should log error here\n\t\tw.WriteHeader(500)\n\t\treturn\n\t}\n\tflight := g.Schedule.FindFlight(id)\n\tif flight == nil {\n\t\t// Should log error here\n\t\tw.WriteHeader(404)\n\t\treturn\n\t}\n\n\tvar reservation map[string][]string\n\tif err = json.Unmarshal(data, &reservation); err != nil {\n\t\t// Should log error here\n\t\tw.WriteHeader(500)\n\t\treturn\n\t}\n\treserves, ok := reservation[\"reserves\"]\n\tif !ok {\n\t\t// Should log error here\n\t\tw.WriteHeader(400)\n\t\treturn\n\t}\n\tvar wg sync.WaitGroup\n\tvar errors []error\n\tfor _, shortcut := range reserves {\n\t\twg.Add(1)\n\t\tgo func(shortcut string) {\n\t\t\terr := flight.Plane.ReserveSeat(shortcut)\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t\twg.Done()\n\t\t}(shortcut)\n\t}\n\twg.Wait()\n\tif len(errors) == 0 {\n\t\tw.WriteHeader(200)\n\t\treturn\n\t}\n\n\terrorsDto := map[string][]error{\n\t\t\"errors\": errors,\n\t}\n\tw.WriteHeader(500)\n\tg.sendJSON(w, errorsDto)\n}", "func (c *CarBuilder) SetSeats() BuildProcess {\n\tc.v.Seats = 5\n\treturn c\n}", "func (f Fortune) Stake() decimal.Decimal { return f.stake }", "func (tod *ValidatedTimeOfDay) Sec() int {\n\treturn tod.sec\n}", "func (b *BikeBuilder) SetSeats() BuildProcess {\n\tb.v.Seats = 2\n\treturn b\n}", "func (p *Poset) StakeOf(addr hash.Peer) uint64 {\n\tf := p.frame(p.state.LastFinishedFrameN+stateGap, true)\n\tdb := p.store.StateDB(f.Balances)\n\treturn db.VoteBalance(addr)\n}", "func (t *Toy) Sold() int {\n\treturn t.sold\n}", "func (p Player)CountPoint(boardCows []int)int{\n\t// Point if 100 for each color staying on board\n\ttotal := 0\n\tfor i,nb := range p.Cows {\n\t\ttotal+=boardCows[i]*100 * int(nb)\n\t}\n\tfor _,money := range p.Moneys {\n\t\ttotal+=money\n\t}\n\treturn total\n}", "func checkIfSeatIsOccupied(rowIndexDelta int, seatIndexDelta int, rowIndex int, seatIndex int, seatRows [][]byte) int {\n\n\tfor {\n\t\trowIndex += rowIndexDelta\n\t\tseatIndex += seatIndexDelta\n\t\tif rowIndex < 0 || rowIndex >= numRows {\n\t\t\treturn 0\n\t\t}\n\t\tif seatIndex < 0 || seatIndex >= numSeats {\n\t\t\treturn 0\n\t\t}\n\t\tswitch seatRows[rowIndex][seatIndex] {\n\t\tcase '#':\n\t\t\treturn 1\n\t\tcase '.':\n\t\t\tcontinue\n\t\tcase 'L':\n\t\t\treturn 0\n\t\t}\n\t}\n}", "func (cpu *Mos6502) sei() uint8 {\n\tcpu.setStatusFlag(I, true)\n\treturn 0\n}", "func (s semi) sharp() semi {\n\treturn s + 1\n}", "func (_BondedECDSAKeep *BondedECDSAKeepCallerSession) MemberStake() (*big.Int, error) {\n\treturn _BondedECDSAKeep.Contract.MemberStake(&_BondedECDSAKeep.CallOpts)\n}", "func (s *Seat) SeatIsClosed() bool {\n\treturn s.SeatClosed\n}", "func (cow Cow) Eat() {\n\tfmt.Println(cow.food)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) MemberStake() (*big.Int, error) {\n\treturn _BondedECDSAKeep.Contract.MemberStake(&_BondedECDSAKeep.CallOpts)\n}", "func GetOccupiedSeatsCountByGrid(grid SeatGrid) int {\n\toccupiedSeatsCount := 0\n\n\tfor y := range grid {\n\t\tfor x := range grid[y] {\n\t\t\tif grid[y][x] == OccupiedSeat {\n\t\t\t\toccupiedSeatsCount++\n\t\t\t}\n\t\t}\n\t}\n\n\treturn occupiedSeatsCount\n}", "func (p *Bare) sprintTrice() (n int, err error) {\n\tswitch p.trice.Type {\n\tcase \"TRICE0\":\n\t\treturn p.trice0()\n\tcase \"TRICE8_1\":\n\t\treturn p.trice81()\n\tcase \"TRICE8_2\":\n\t\treturn p.trice82()\n\tcase \"TRICE8_3\":\n\t\treturn p.trice83()\n\tcase \"TRICE8_4\":\n\t\treturn p.trice84()\n\tcase \"TRICE8_5\":\n\t\treturn p.trice85()\n\tcase \"TRICE8_6\":\n\t\treturn p.trice86()\n\tcase \"TRICE8_7\":\n\t\treturn p.trice87()\n\tcase \"TRICE8_8\":\n\t\treturn p.trice88()\n\tcase \"TRICE16_1\":\n\t\treturn p.trice161()\n\tcase \"TRICE16_2\":\n\t\treturn p.trice162()\n\tcase \"TRICE16_3\":\n\t\treturn p.trice163()\n\tcase \"TRICE16_4\":\n\t\treturn p.trice164()\n\tcase \"TRICE32_1\":\n\t\treturn p.trice321()\n\tcase \"TRICE32_2\":\n\t\treturn p.trice322()\n\tcase \"TRICE32_3\":\n\t\treturn p.trice323()\n\tcase \"TRICE32_4\":\n\t\treturn p.trice324()\n\tcase \"TRICE64_1\":\n\t\treturn p.trice641()\n\tcase \"TRICE64_2\":\n\t\treturn p.trice642()\n\t}\n\treturn p.outOfSync(fmt.Sprintf(\"Unexpected trice.Type %s\", p.trice.Type))\n}", "func (s *Seat) SetSeatClosed() {\n\ts.SeatClosed = true\n}", "func (c *connectionService) SessionID() SID {\n\ts := SID(atomic.AddUint32(&c.sid, 1))\n\tg := SID(env.GateID) << gateIDShift\n\treturn g | s\n}", "func (c *Creature) DetermineSizStrikeRank() *Attribute {\n\n\tsizSR := &Attribute{\n\t\tName: \"SIZ Strike Rank\",\n\t\tMax: 5,\n\t}\n\n\tsiz := c.Statistics[\"SIZ\"]\n\n\tsiz.UpdateStatistic()\n\n\tswitch {\n\tcase siz.Total < 7:\n\t\tsizSR.Base = 3\n\tcase siz.Total < 15:\n\t\tsizSR.Base = 2\n\tcase siz.Total < 22:\n\t\tsizSR.Base = 1\n\tcase siz.Total > 21:\n\t\tsizSR.Base = 0\n\t}\n\treturn sizSR\n}", "func (_Crowdsale *CrowdsaleSession) PctSold() (*big.Int, error) {\n\treturn _Crowdsale.Contract.PctSold(&_Crowdsale.CallOpts)\n}", "func (s *Seriet) At(i int) Point {\n\treturn s.serie[i]\n}", "func (t *Table) WhoseTurn() int {\n\tallNil := true\n\tfor i, c := range t.trick {\n\t\tnextPlayerIndex := (i + 1) % len(t.players)\n\t\tif c != nil {\n\t\t\tallNil = false\n\t\t\tif t.trick[nextPlayerIndex] == nil {\n\t\t\t\treturn nextPlayerIndex\n\t\t\t}\n\t\t}\n\t}\n\tif allNil {\n\t\treturn t.firstPlayer\n\t}\n\treturn -1\n}", "func (_Constants *ConstantsSession) MinStake() (*big.Int, error) {\n\treturn _Constants.Contract.MinStake(&_Constants.CallOpts)\n}", "func (t *Triangle) At(i int) int {\n\treturn t.verteces[i]\n}", "func NewSeatAssignment(code string) SeatAssignment {\n\t// Cheating.\n\trowCode := code[:7]\n\trowCode = strings.ReplaceAll(rowCode, \"B\", \"1\")\n\trowCode = strings.ReplaceAll(rowCode, \"F\", \"0\")\n\trow, err := strconv.ParseInt(rowCode, 2, 64)\n\tif err != nil {\n\t\t//fmt.Printf(\"Failed parsing row from %s\", code)\n\t}\n\tcolCode := code[7:]\n\tcolCode = strings.ReplaceAll(colCode, \"R\", \"1\")\n\tcolCode = strings.ReplaceAll(colCode, \"L\", \"0\")\n\tcol, err := strconv.ParseInt(colCode, 2, 64)\n\tif err != nil {\n\t\t//fmt.Printf(\"Failed parsing column from %s\", code)\n\t}\n\n\tseatID := row*8 + col\n\n\treturn SeatAssignment{\n\t\tcode: code,\n\t\trowCode: rowCode,\n\t\tcolCode: rowCode,\n\t\trow: row,\n\t\tcolumn: col,\n\t\tSeatID: seatID,\n\t}\n}", "func (_Crowdsale *CrowdsaleCallerSession) PctSold() (*big.Int, error) {\n\treturn _Crowdsale.Contract.PctSold(&_Crowdsale.CallOpts)\n}", "func Interest(num int) int {\n\treturn 6000\n}", "func nextSeatOccupied(seatMap *SeatMap, x, y, stepX, stepY int) bool {\n\ti := x + stepX\n\tj := y + stepY\n\n\tfor i >= 0 && i < len(seatMap.seats) && j >= 0 && j < len(seatMap.seats[i]) {\n\t\tif seatMap.seats[i][j] == 'L' {\n\t\t\treturn false\n\t\t} else if seatMap.seats[i][j] == '#' {\n\t\t\treturn true\n\t\t}\n\t\ti += stepX\n\t\tj += stepY\n\t}\n\treturn false\n}", "func NewSector(rows, cols int, excludeTags []string, fullTags bool, poiChance, otherWorldChance int, density Density) *Stars {\n\ts := &Stars{\n\t\tRows: rows,\n\t\tCols: cols,\n\t}\n\n\tdVal := 0\n\tswitch density {\n\tcase SPARSE:\n\t\tdVal = 8\n\tcase AVERAGE:\n\t\tdVal = 4\n\tcase DENSE:\n\t\tdVal = 2\n\t}\n\n\tcells := s.Rows * s.Cols\n\tstars := (rand.Intn(cells/4) / 2) + (cells / dVal)\n\n\tfor row, col := rand.Intn(s.Rows), rand.Intn(s.Cols); len(s.Systems) <= stars; row, col = rand.Intn(s.Rows), rand.Intn(s.Cols) {\n\t\tif !s.active(row, col) {\n\t\t\ts.Systems = append(s.Systems, NewStar(row, col, s.systemName(), excludeTags, fullTags, poiChance, otherWorldChance))\n\t\t}\n\t}\n\n\treturn s\n}", "func (dt DateTime) Second() int {\n\treturn dt.Time().Second()\n}", "func (a Snake) Eat() {\n\tfmt.Printf(\"%s \\n\", a.food)\n}", "func (_MonsterOwnership *MonsterOwnershipSession) SecondsPerBlock() (*big.Int, error) {\n\treturn _MonsterOwnership.Contract.SecondsPerBlock(&_MonsterOwnership.CallOpts)\n}", "func (r *Reservation) nights() int {\n\t// filter out hours, minutes and seconds\n\tarrival := time.Date(r.Arrival.Year(), r.Arrival.Month(), r.Arrival.Day(), 0, 0, 0, 0, time.UTC)\n\tdeparture := time.Date(r.Departure.Year(), r.Departure.Month(), r.Departure.Day(), 0, 0, 0, 0, time.UTC)\n\n\treturn int(departure.Sub(arrival).Hours() / 24)\n}", "func (_Constants *ConstantsCallerSession) MinStake() (*big.Int, error) {\n\treturn _Constants.Contract.MinStake(&_Constants.CallOpts)\n}", "func Sachsen(y int, inklSonntage ...bool) Region {\n\tffun := []func(int) Feiertag{Reformationstag, BußUndBettag}\n\treturn Region{\"Sachsen\", \"SN\", createFeiertagsList(y, \"DE\", ffun)}\n}", "func (et ExfatTimestamp) Second() int {\n\treturn int(et & 31)\n}", "func (c Clock) Hour() int {\n\treturn int(time.Duration(c) / time.Hour)\n}", "func (f Person) CurrSpouse() (spouse *Person, err error) {\n\tif !f.married {\n\t\treturn nil, fmt.Errorf(\"person is not married:\\n%v\", f)\n\t}\n\treturn f.spouses[len(f.spouses)-1], nil\n}", "func (_MonsterOwnership *MonsterOwnershipCallerSession) SecondsPerBlock() (*big.Int, error) {\n\treturn _MonsterOwnership.Contract.SecondsPerBlock(&_MonsterOwnership.CallOpts)\n}", "func SecondHand(t time.Time) Point {\n\treturn Point{150, 60}\n}", "func topRoyalty(hr ofc.Handrank) int {\n\tif hr[0] == ofc.TRIPS {\n\t\treturn 10 + hr[1]\n\t} else if hr[0] == ofc.PAIR && hr[1] >= 6 {\n\t\treturn hr[1] - 3\n\t} else {\n\t\treturn 0\n\t}\n}", "func (game *T) JSON(seat *Seat) cast.JSON {\n\tif game == nil {\n\t\treturn nil\n\t}\n\tseats := cast.JSON{}\n\tfor _, s := range game.Seats {\n\t\tseats[s.Username] = s.JSON()\n\t}\n\treturn cast.JSON{\n\t\t\"id\": game.ID(),\n\t\t// \"life\": seat.Life,\n\t\t\"hand\": seat.Hand.JSON(),\n\t\t\"state\": game.State.JSON(),\n\t\t// \"elements\": seat.Elements.JSON(),\n\t\t\"username\": seat.Username,\n\t\t// \"opponent\": game.GetOpponentSeat(seat.Username).Username,\n\t\t\"seats\": seats,\n\t}\n}", "func countStairs(n int) int {\n\tmatrix := make([]int, n + 1) // create memo table\n\tmatrix[0], matrix[1], matrix[2] = 0, 1, 2 // seed the table with initial conditions\n\tfor i := 3; i < len(matrix); i++ {\n\t\tmatrix[i] = matrix[i-1] + matrix[i-2] // build up results\n\t}\n\treturn matrix[len(matrix)-1] // return final result\n}", "func (_RandomBeacon *RandomBeaconSession) EligibleStake(stakingProvider common.Address) (*big.Int, error) {\n\treturn _RandomBeacon.Contract.EligibleStake(&_RandomBeacon.CallOpts, stakingProvider)\n}", "func (*SeatDataAccessObject) FindByID(seatID int) *Seat {\n\tvar seat Seat\n\thas, err := orm.Table(seat).ID(seatID).Get(&seat)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif !has {\n\t\treturn nil\n\t}\n\treturn &seat\n}", "func (_XStaking *XStakingTransactorSession) Stake(amount *big.Int) (*types.Transaction, error) {\n\treturn _XStaking.Contract.Stake(&_XStaking.TransactOpts, amount)\n}", "func (r *Lanczos) GetS() float64 {\n\treturn 3.0\n}", "func (_XStaking *XStakingSession) Stake(amount *big.Int) (*types.Transaction, error) {\n\treturn _XStaking.Contract.Stake(&_XStaking.TransactOpts, amount)\n}", "func GetTeachingCourseNum(teacher string) int {\n\tvar count int\n\n\tdb.Table(\"course\").Where(\"teacher = ?\", teacher).Count(&count)\n\treturn count\n}", "func (ses *Ses) NumStmt() int {\n\tses.RLock()\n\topenStmts := ses.openStmts\n\tses.RUnlock()\n\treturn openStmts.len()\n}", "func (cat *Category) GetTally() int {\n\treturn cat.Tally\n}", "func (*SeatDataAccessObject) DeleteBySeatID(seatID int) {\n\tvar seat Seat\n\t_, err := orm.Table(seat).ID(seatID).Delete(&seat)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func OccupiedNeighbours(seatMap *SeatMap, x, y int) int {\n\toccupied := 0\n\n\tfor i := x - 1; i <= x+1; i++ {\n\t\tif i < 0 || i >= len(seatMap.seats) {\n\t\t\tcontinue\n\t\t}\n\t\tfor j := y - 1; j <= y+1; j++ {\n\t\t\tif j < 0 || j >= len(seatMap.seats[i]) || (i == x && j == y) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif seatMap.seats[i][j] == '#' {\n\t\t\t\toccupied++\n\t\t\t}\n\t\t}\n\t}\n\n\treturn occupied\n}", "func (s *statement) prevTurn() int {\n\treturn (s.Step+2)%4 + 1\n}", "func (cpu *Mos6502) sec() uint8 {\n\tcpu.setStatusFlag(C, true)\n\treturn 0\n}", "func midRoyalty(hr ofc.Handrank) int {\n\treturn midRoyaltyTable[hr[0]]\n}", "func (w *rpcWallet) StakeInfo(ctx context.Context) (*wallet.StakeInfoData, error) {\n\tres, err := w.rpcClient.GetStakeInfo(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsdiff, err := dcrutil.NewAmount(res.Difficulty)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttotalSubsidy, err := dcrutil.NewAmount(res.TotalSubsidy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &wallet.StakeInfoData{\n\t\tBlockHeight: res.BlockHeight,\n\t\tTotalSubsidy: totalSubsidy,\n\t\tSdiff: sdiff,\n\t\tOwnMempoolTix: res.OwnMempoolTix,\n\t\tUnspent: res.Unspent,\n\t\tVoted: res.Voted,\n\t\tRevoked: res.Revoked,\n\t\tUnspentExpired: res.UnspentExpired,\n\t\tPoolSize: res.PoolSize,\n\t\tAllMempoolTix: res.AllMempoolTix,\n\t\tImmature: res.Immature,\n\t\tLive: res.Live,\n\t\tMissed: res.Missed,\n\t\tExpired: res.Expired,\n\t}, nil\n}", "func (a Cow) Eat() {\n\tfmt.Printf(\"%s \\n\", a.food)\n}", "func line() int {\n\t_, _, line, _ := runtime.Caller(1)\n\treturn line\n\n}", "func Run(lines []string) {\n\tids := []int{}\n\tfor _, s := range lines {\n\t\trow, col := findSeat(s)\n\t\tids = append(ids, seatID(row, col))\n\t}\n\tmax := maxInSlice(ids)\n\tfmt.Printf(\"max: %v\\n\", max)\n\tmySeat := findMySeat(ids)\n\tfmt.Printf(\"my seat is %v\\n\", mySeat)\n}", "func setMontyHallGame() (int, int) {\n\tvar (\n\t\tmontysChoice int\n\t\tprizeDoor int\n\t\tgoat1Door int\n\t\tgoat2Door int\n\t\tnewDoor int\n\t)\n\n\tguestDoor := rand.Intn(3)\n\n\tareDoorsSelected := false\n\tfor !areDoorsSelected {\n\t\tprizeDoor = rand.Intn(3)\n\t\tgoat1Door = rand.Intn(3)\n\t\tgoat2Door = rand.Intn(3)\n\t\tif prizeDoor != goat1Door && prizeDoor != goat2Door && goat1Door != goat2Door {\n\t\t\tareDoorsSelected = true\n\t\t}\n\t}\n\n\tshowGoat := false\n\tfor !showGoat {\n\t\tmontysChoice = rand.Intn(3)\n\t\tif montysChoice != prizeDoor && montysChoice != guestDoor {\n\t\t\tshowGoat = true\n\t\t}\n\t}\n\n\tmadeSwitch := false\n\tfor !madeSwitch {\n\t\tnewDoor = rand.Intn(3)\n\t\tif newDoor != guestDoor && newDoor != montysChoice {\n\t\t\tmadeSwitch = true\n\t\t}\n\t}\n\treturn newDoor, prizeDoor\n}", "func Age(secs float64, planet Planet) float64 {\n\tvar age = 0.0\n\tswitch planet {\n\tcase \"Earth\":\n\t\tage = getAge(secs, 1)\n\tcase \"Mercury\":\n\t\tage = getAge(secs, 0.2408467)\n\tcase \"Venus\":\n\t\tage = getAge(secs, 0.61519726)\n\tcase \"Mars\":\n\t\tage = getAge(secs, 1.8808158)\n\tcase \"Jupiter\":\n\t\tage = getAge(secs, 11.862615)\n\tcase \"Saturn\":\n\t\tage = getAge(secs, 29.447498)\n\tcase \"Uranus\":\n\t\tage = getAge(secs, 84.016846)\n\tcase \"Neptune\":\n\t\tage = getAge(secs, 164.79132)\n\t}\n\treturn age\n}", "func (v *victorianChair) SitDown() string {\n\treturn \"Sitting on the victorian chair\"\n}", "func NewSeata(cfg Cfg) (*Seata, error) {\n\tf := &Seata{\n\t\tcfg: cfg,\n\t\tsvr: goetty.NewServer(cfg.Addr,\n\t\t\tgoetty.WithServerDecoder(meta.ProxyDecoder),\n\t\t\tgoetty.WithServerEncoder(meta.ProxyEncoder),\n\t\t\tgoetty.WithServerIDGenerator(goetty.NewUUIDV4IdGenerator())),\n\t\tproxies: make(map[string]*session),\n\t}\n\n\tf.cfg.TransSendCB = f.doNotify\n\tf.store = NewStore(f.cfg)\n\treturn f, nil\n}", "func main() {\n\tn := 5\n\tseatManager := Constructor(n); // 初始化 SeatManager ,有 5 个座位。\n\tfmt.Println(seatManager.Reserve()) // 所有座位都可以预约,所以返回最小编号的座位,也就是 1 。\n\tfmt.Println(seatManager.Reserve()) // 可以预约的座位为 [2,3,4,5] ,返回最小编号的座位,也就是 2 。\n\tseatManager.Unreserve(2); // 将座位 2 变为可以预约,现在可预约的座位为 [2,3,4,5] 。\n\tfmt.Println(seatManager.Reserve()) // 可以预约的座位为 [2,3,4,5] ,返回最小编号的座位,也就是 2 。\n\tfmt.Println(seatManager.Reserve()) // 可以预约的座位为 [3,4,5] ,返回最小编号的座位,也就是 3 。\n\tfmt.Println(seatManager.Reserve()) // 可以预约的座位为 [4,5] ,返回最小编号的座位,也就是 4 。\n\tfmt.Println(seatManager.Reserve()) // 唯一可以预约的是座位 5 ,所以返回 5 。\n\tseatManager.Unreserve(5); // 将座位 5 变为可以预约,现在可预约的座位为 [5] 。\n}", "func (_RandomBeacon *RandomBeaconCallerSession) EligibleStake(stakingProvider common.Address) (*big.Int, error) {\n\treturn _RandomBeacon.Contract.EligibleStake(&_RandomBeacon.CallOpts, stakingProvider)\n}", "func (rt *recvTxOut) SpentBy() (txSha *btcwire.ShaHash, height int32) {\n\tif rt.spentBy == nil {\n\t\treturn nil, 0\n\t}\n\treturn &rt.spentBy.txSha, rt.spentBy.height\n}", "func Twin(n int) (int, bool) {\n\tif OptimizedTrialDivision(int64(n)) && OptimizedTrialDivision(int64(n+2)) {\n\t\treturn n + 2, true\n\t}\n\treturn -1, false\n}", "func (o *Tier) GetPrice() int32 {\n\tif o == nil || o.Price == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Price\n}", "func (m *UserMutation) SpouseID() (id int, exists bool) {\n\tif m.spouse != nil {\n\t\treturn *m.spouse, true\n\t}\n\treturn\n}", "func occupiedAround(x int, y int, seats [][]rune) int {\n\tocc := 0\n\n\t// all seats around\n\tchngs := [8][2]int{{-1, -1}, {0, -1}, {1, -1}, {-1, 0}, {1, 0}, {-1, 1}, {0, 1}, {1, 1}}\n\n\t// calculate the number of occupied seats around\n\tfor _, mv := range chngs {\n\t\tnx := x\n\t\tny := y\n\t\tfor {\n\t\t\tnx += mv[0]\n\t\t\tny += mv[1]\n\t\t\tif nx >= 0 && ny >= 0 && nx < len(seats[0]) && ny < len(seats) {\n\t\t\t\tif seats[ny][nx] == '.' {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif seats[ny][nx] == '#' {\n\t\t\t\t\tocc++\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn occ\n}", "func (d Dice) Min() int {\n\treturn d.min\n}", "func (g *Game) getSpareBonus(rollIndex int) int {\n\treturn g.rolls[rollIndex+2]\n}", "func (e *Square10) DetermineWinner() int {\n\tscore := []int{0, 0}\n\tfor _, owner := range e.ownership {\n\t\tif owner == contested {\n\t\t\tcontinue\n\t\t}\n\t\tscore[owner]++\n\t}\n\tfor player, points := range score {\n\t\tif points+player > 50 {\n\t\t\treturn player\n\t\t}\n\t}\n\treturn -1\n}", "func (dt DateTime) Second() int {\n\treturn dt.src.Second()\n}", "func (_IStakingRewards *IStakingRewardsTransactorSession) Stake(amount *big.Int) (*types.Transaction, error) {\n\treturn _IStakingRewards.Contract.Stake(&_IStakingRewards.TransactOpts, amount)\n}", "func (*SeatDataAccessObject) FindByMerchantID(merchantID int) []Seat {\n\tseatList := make([]Seat, 0)\n\terr := orm.Table(\"Seat\").Where(\"MerchantID=?\", merchantID).Find(&seatList)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn seatList\n}", "func Cat(num int) int {\n\tif num < 15 {\n\t\tprecalc := map[int]int{\n\t\t\t0: 1,\n\t\t\t1: 1,\n\t\t\t2: 2,\n\t\t\t3: 5,\n\t\t\t4: 14,\n\t\t\t5: 42,\n\t\t\t6: 132,\n\t\t\t7: 429,\n\t\t\t8: 1430,\n\t\t\t9: 4862,\n\t\t\t10: 16796,\n\t\t\t11: 58786,\n\t\t\t12: 208012,\n\t\t\t13: 742900,\n\t\t\t14: 2674440,\n\t\t}\n\t\treturn precalc[num]\n\t}\n\n\t// return catNoPreCalc(num)\n\n\tvar b, c big.Int\n\n\tn := int64(num)\n\ts := fmt.Sprint(c.Div(b.Binomial(n*2, n), c.SetInt64(n+1)))\n\tj, _ := strconv.Atoi(s)\n\treturn j\n\n}", "func number() int {\n\treturn 75\n}", "func (_Crowdsale *CrowdsaleSession) FramesSold() (*big.Int, error) {\n\treturn _Crowdsale.Contract.FramesSold(&_Crowdsale.CallOpts)\n}", "func Simon() {\n\tfmt.Printf(\"Enter how many strikes you have: \")\n\tstrikes = inputInteger()\n\trecieveSerial()\n\tif serialVowel {\n\t\tsimonBody(vowelPresent)\n\t} else {\n\t\tsimonBody(noVowelPresent)\n\t}\n}", "func (p *PunchCard) GetHour() int {\n\tif p == nil || p.Hour == nil {\n\t\treturn 0\n\t}\n\treturn *p.Hour\n}", "func (s *svcPaths) NumSvc() int {\n\ts.mux.RLock()\n\tdefer s.mux.RUnlock()\n\treturn len(s.StoPs)\n}", "func (s *section) Size() (i int) {\n\tfor k := range s.tm.container {\n\t\tif k.sec == s.sec {\n\t\t\ti++\n\t\t}\n\t}\n\treturn\n}", "func SawTooth(x, period float64) float64 {\n\tx += period / 2\n\tt := x / period\n\treturn period*(t-math.Floor(t)) - period/2\n}", "func (_IStakingRewards *IStakingRewardsSession) Stake(amount *big.Int) (*types.Transaction, error) {\n\treturn _IStakingRewards.Contract.Stake(&_IStakingRewards.TransactOpts, amount)\n}", "func CountPageClothes(c * gin.Context){\n\tdb := database.DBConn()\n\trows, err := db.Query(\"Select count(*) FROM clothes\")\n\tif err != nil{\n\t\tc.JSON(500, gin.H{\n\t\t\t\"messages\" : \"Story not found\",\n\t\t});\n\t\tpanic(err)\n\t}\n\tvar rs int\n\tfor rows.Next() {\n\t\terr = rows.Scan(&rs)\n\t}\n\tif rs%12==0 {\n\t\trs = rs/12\n\t} else{\n\t\trs = rs/12 +1\n\t}\n\tc.JSON(200, rs)\n\tdefer db.Close() // Hoãn lại việc close database connect cho đến khi hàm Read() thực hiệc xong*/\n}" ]
[ "0.6878676", "0.6828725", "0.6795338", "0.63282037", "0.55180174", "0.5344577", "0.52272886", "0.4829826", "0.47706714", "0.4760905", "0.47434962", "0.46960112", "0.46913013", "0.46708304", "0.4629666", "0.4629208", "0.45705917", "0.45350242", "0.45322928", "0.44546917", "0.44489458", "0.442365", "0.4398543", "0.43899542", "0.43839467", "0.43715927", "0.43706647", "0.4368532", "0.43666306", "0.434377", "0.43221554", "0.43210414", "0.43140623", "0.43100068", "0.4308249", "0.43049663", "0.42943603", "0.42847633", "0.42805046", "0.42740262", "0.4268545", "0.4265999", "0.42530495", "0.4234512", "0.42266643", "0.42161763", "0.42159232", "0.42130333", "0.42117727", "0.42076746", "0.42067683", "0.42024106", "0.41811764", "0.41703576", "0.41667178", "0.4162581", "0.4158452", "0.41522822", "0.4144787", "0.41337892", "0.4121492", "0.41159388", "0.41098642", "0.4102667", "0.4098212", "0.4094778", "0.40931106", "0.40912506", "0.40901417", "0.40851432", "0.40787417", "0.40736344", "0.4068568", "0.40646073", "0.40641356", "0.40616515", "0.40594468", "0.40578395", "0.40556434", "0.40530115", "0.40406722", "0.4040366", "0.40294278", "0.4025885", "0.4023281", "0.40206832", "0.4014979", "0.40110928", "0.40066844", "0.40058854", "0.40030208", "0.40003827", "0.40002012", "0.3998134", "0.3993921", "0.39927593", "0.3991802", "0.39803296", "0.3977453", "0.39747596" ]
0.8243649
0
NewPhilosopherPtr creates and initializes a Philosopher object and returns a pointer to it.
func NewPhilosopherPtr(name string) *Philosopher { phi := new(Philosopher) phi.Init(name) return phi }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newPhilosopherDataPtr(respChannel chan string) *philosopherData {\n\tpd := new(philosopherData)\n\tpd.Init(respChannel)\n\treturn pd\n}", "func (pb *PhilosopherBase) LeftPhilosopher() Philosopher {\n\t// Add NPhils to avoid a negative index\n\tindex := (pb.ID + NPhils - 1) % NPhils\n\treturn Philosophers[index]\n}", "func (pb *PhilosopherBase) RightPhilosopher() Philosopher {\n\tindex := (pb.ID + 1) % NPhils\n\treturn Philosophers[index]\n}", "func NewPlugin(proto, path string, params ...string) *Plugin {\n\tif proto != \"unix\" && proto != \"tcp\" {\n\t\tpanic(\"Invalid protocol. Specify 'unix' or 'tcp'.\")\n\t}\n\tp := &Plugin{\n\t\texe: path,\n\t\tproto: proto,\n\t\tparams: params,\n\t\tinitTimeout: 2 * time.Second,\n\t\texitTimeout: 2 * time.Second,\n\t\thandler: NewDefaultErrorHandler(),\n\t\tmeta: meta(\"pingo\" + randstr(5)),\n\t\tobjsCh: make(chan *objects),\n\t\tconnCh: make(chan *conn),\n\t\tkillCh: make(chan *waiter),\n\t\texitCh: make(chan struct{}),\n\t}\n\treturn p\n}", "func NewPGConnector() *PGConnector { return &PGConnector{} }", "func NewPGConnector() *PGConnector { return &PGConnector{} }", "func NewHOTP() *HOTP { return &HOTP{} }", "func NewProver(n int) *Prover {\n\tmaxGenerators := 256\n\tgenerators := GeneratorsCreate(maxGenerators)\n\tG := generators[0 : maxGenerators/2]\n\tH := generators[maxGenerators/2:]\n\n\tgx, _ := new(big.Int).SetString(\"50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0\", 16)\n\tgy, _ := new(big.Int).SetString(\"31d3c6863973926e049e637cb1b5f40a36dac28af1766968c30c2313f3a38904\", 16)\n\tg := Point{X: gx, Y: gy}\n\n\th := Point{X: curve.Gx, Y: curve.Gy}\n\n\tpowersOfTwo := powers(big.NewInt(2), n)\n\n\treturn &Prover{\n\t\tn: n,\n\t\tG: G,\n\t\tH: H,\n\t\tValueGenerator: &g,\n\t\tBlindingGenerator: &h,\n\t\tpowersOfTwo: powersOfTwo,\n\t}\n}", "func (phi *Philosopher) Init(name string) {\n\tphi.name = name\n\tphi.respChannel = make(chan string)\n}", "func newPiholeClient(cfg PiholeConfig) (piholeAPI, error) {\n\tif cfg.Server == \"\" {\n\t\treturn nil, ErrNoPiholeServer\n\t}\n\n\t// Setup a persistent cookiejar for storing PHP session information\n\tjar, err := cookiejar.New(&cookiejar.Options{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Setup an HTTP client using the cookiejar\n\thttpClient := &http.Client{\n\t\tJar: jar,\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tInsecureSkipVerify: cfg.TLSInsecureSkipVerify,\n\t\t\t},\n\t\t},\n\t}\n\tcl := instrumented_http.NewClient(httpClient, &instrumented_http.Callbacks{})\n\n\tp := &piholeClient{\n\t\tcfg: cfg,\n\t\thttpClient: cl,\n\t}\n\n\tif cfg.Password != \"\" {\n\t\tif err := p.retrieveNewToken(context.Background()); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn p, nil\n}", "func NewPiPanelGTK() *pipanel.Frontend {\n\treturn &pipanel.Frontend{\n\t\tAlerter: gtkttsalerter.New(),\n\t\tAudioPlayer: beeper.New(),\n\t\tDisplayManager: pitouch.New(),\n\t\tPowerManager: systemdpwr.New(),\n\t}\n}", "func NewDinnerHostPtr(tableCount, maxParallel, maxDinner int) *DinnerHost {\n\thost := new(DinnerHost)\n\thost.Init(tableCount, maxParallel, maxDinner)\n\treturn host\n}", "func NewPTracer(store Store) PTracer {\n\tt := PTracer{\n\t\tops: make(chan func()),\n\t\tstopped: make(chan stopped),\n\t\tquit: make(chan struct{}),\n\t\tchildAttached: make(chan struct{}),\n\n\t\tthreads: make(map[int]*thread),\n\t\tprocesses: make(map[int]*process),\n\t\tstore: store,\n\t}\n\tgo t.waitLoop()\n\tgo t.loop()\n\treturn t\n}", "func New(size int) Perceptron {\n\tsize++\n\tp := make(Perceptron, size)\n\tp.init()\n\treturn p\n}", "func NewPhysicsP2(game *Game) *PhysicsP2 {\n return &PhysicsP2{js.Global.Get(\"Phaser\").Get(\"Physics\").Get(\"P2\").New(game)}\n}", "func NewPengo(x, y int, game *tl.Game) *Pengo {\n\treturn &Pengo{\n\t\tr: tl.NewRectangle(x, y, 1, 1, tl.ColorRed),\n\t\tx: x,\n\t\ty: y,\n\t\tg: game,\n\t\td: NONE,\n\t}\n}", "func NewPi(label string, t Term, body Term) Pi {\n\treturn Pi{\n\t\tLabel: label,\n\t\tType: t,\n\t\tBody: body,\n\t}\n}", "func newProxy(pType ProxyType) (proxy, error) {\n\tswitch pType {\n\tcase NoopProxyType:\n\t\treturn &noopProxy{}, nil\n\tcase CCProxyType:\n\t\treturn &ccProxy{}, nil\n\tdefault:\n\t\treturn &noopProxy{}, nil\n\t}\n}", "func NewPorthole(\n\tscanner shared.Scanning,\n\tpersister shared.Persistence,\n\tticker shared.Clock,\n\tconfig *Config,\n) *Porthole {\n\talbumAdditions := foldermusic.NewAdditions(\n\t\tscanner,\n\t\tpersister,\n\t\tconfig.LatestAdditionsLimit)\n\tstatusCoordinator := status.NewCoordinator(\n\t\tconfig.GitCommit,\n\t\t&status.MusicStatusWorker{albumAdditions},\n\t\tticker.NewClock(),\n\t\ttime.Duration(config.SleepAfter)*time.Millisecond)\n\treturn &Porthole{\n\t\tticker,\n\t\tconfig,\n\t\tstatusCoordinator,\n\t}\n}", "func New() *Gopher {\n\tg := &Gopher{\n\t\tdelay: 1000 * time.Millisecond,\n\t\tactivity: Waiting,\n\t\tcolor: White,\n\t\tw: colorable.NewColorableStdout(),\n\t\tdone: make(chan struct{}, 1),\n\t}\n\treturn g\n}", "func NewHypotheses(config GeneratorConfig) *Hypotheses {\n\treturn &Hypotheses{\n\t\tconfig: config,\n\t\tbeams: make([]Hypothesis, 0),\n\t\tworstScore: 1e9,\n\t}\n}", "func NewHeap() *Heap {\n return &Heap{}\n}", "func NewPhysicsP2I(args ...interface{}) *PhysicsP2 {\n return &PhysicsP2{js.Global.Get(\"Phaser\").Get(\"Physics\").Get(\"P2\").New(args)}\n}", "func NewProposer(c *Configuration, port int) *Proposer {\n\tvar myNode *Node\n\tfor _, node := range c.Nodes() {\n\t\tif node.Port() == strconv.Itoa(port) {\n\t\t\tmyNode = node\n\t\t\tbreak\n\t\t}\n\t}\n\tif myNode == nil {\n\t\tpanic(\"my node not found in configuration\")\n\t}\n\n\t// initialize leader detector with a time delay for failure detector.\n\tld := NewLeaderDetector(*c, myNode, 10*time.Second)\n\n\treturn &Proposer{\n\t\tnode: myNode,\n\t\tconfig: c,\n\t\tcrnd: uint32(port - c.Size()), // initialize round number\n\t\ttrustMsgs: ld.Subscribe(),\n\t\tcvalIn: make(chan bool, 1),\n\t\tstop: make(chan struct{}),\n\t}\n}", "func NewHelloWorld(pid uint8) *HelloWorld {\n\tp := &HelloWorld{\n\t\tpid: pid,\n\t}\n\treturn p\n}", "func NewPG() (*PGCtrl, error) {\n\treturn &PGCtrl{}, nil\n}", "func NewSchedProbPlugin(name,queueName string,threshold float64) *SchedProbPlugin{\r\n return &SchedProbPlugin{\r\n Name: name,\r\n QueueName: queueName,\r\n threshold: threshold,\r\n }\r\n}", "func NewDeleter(config *common.RuntimeConfig, procTable ProcTable) *Deleter {\n\treturn &Deleter{\n\t\tRuntimeConfig: config,\n\t\tProcTable: procTable,\n\t}\n}", "func NewPit(id string, x, y, width, height int32, depth int8, w *world.World) *Pit {\n\treturn &Pit{\n\t\tID: id,\n\t\tX: x,\n\t\tY: y,\n\t\tW: width,\n\t\tH: height,\n\t\tdepth: depth,\n\t\tworld: w,\n\t}\n}", "func NewProof(b *Block) *PoW {\n\t//Initialize target as bigInt\n\ttarget := big.NewInt(1)\n\t//Leftshit bit operation\n\ttarget.Lsh(target, uint(256-b.Difficulty))\n\t//return the pointer\n\tpow := &PoW{b, target}\n\treturn pow\n}", "func NewP2P() *P2P {\n\t// Setup a background context\n\tctx := context.Background()\n\n\t// Setup a P2P Host Node\n\tnodehost, kaddht := setupHost(ctx)\n\t// Debug log\n\tlogrus.Debugln(\"Created the P2P Host and the Kademlia DHT.\")\n\n\t// Bootstrap the Kad DHT\n\tbootstrapDHT(ctx, nodehost, kaddht)\n\t// Debug log\n\tlogrus.Debugln(\"Bootstrapped the Kademlia DHT and Connected to Bootstrap Peers\")\n\n\t// Create a peer discovery service using the Kad DHT\n\troutingdiscovery := discovery.NewRoutingDiscovery(kaddht)\n\t// Debug log\n\tlogrus.Debugln(\"Created the Peer Discovery Service.\")\n\n\t// Create a PubSub handler with the routing discovery\n\tpubsubhandler := setupPubSub(ctx, nodehost, routingdiscovery)\n\t// Debug log\n\tlogrus.Debugln(\"Created the PubSub Handler.\")\n\n\t// Return the P2P object\n\treturn &P2P{\n\t\tCtx: ctx,\n\t\tHost: nodehost,\n\t\tKadDHT: kaddht,\n\t\tDiscovery: routingdiscovery,\n\t\tPubSub: pubsubhandler,\n\t}\n}", "func NewPointer(elem Type) *Pointer { return &Pointer{base: elem} }", "func NewPhysicsP21O(game *Game, config interface{}) *PhysicsP2 {\n return &PhysicsP2{js.Global.Get(\"Phaser\").Get(\"Physics\").Get(\"P2\").New(game, config)}\n}", "func NewPar(P, Q Process) *Par { return &Par{Procs: []Process{P, Q}} }", "func NewHg(dir string) *Hg {\n\treturn &Hg{\n\t\tDir: dir,\n\t}\n}", "func New() *Prober {\n\treturn newForTest(time.Now, newRealTicker)\n}", "func (pb *PhilosopherBase) GetID() int {\n\treturn pb.ID\n}", "func NewPointer(conn *websocket.Conn, pointingSession *PointingSession, name string) *Pointer {\n\treturn &Pointer{\n\t\tconn: conn,\n\t\tsend: make(chan []byte),\n\t\t// the pointer has knows about the pointing session this is to BroadCast to everyone in that session\n\t\tpointingSession: pointingSession,\n\t\tName: name,\n\t}\n}", "func NewProtocol(idx *indexservice.Indexer, cfg indexprotocol.HermesConfig) *Protocol {\n\treturn &Protocol{\n\t\tindexer: idx,\n\t\thermesConfig: cfg,\n\t}\n}", "func PtrNewSaiyan(name string, power int) *Saiyan {\n\treturn &Saiyan{\n\t\tName: name,\n\t\tPower: power,\n\t}\n}", "func New(T, C, K int) (*ph, error) {\n\tvar errList []string\n\tif !powerOf2(T) {\n\t\terrList = append(errList, fmt.Sprintf(\"T must be a power of 2, got: %d\", T))\n\t}\n\tif K >= T {\n\t\terrList = append(errList, \"K must be less than T\")\n\t}\n\tif !powerOf2(C) || C >= T {\n\t\terrList = append(errList, \"C must be a power of 2 and less than T\")\n\t}\n\tif len(errList) > 0 {\n\t\treturn nil, errors.New(strings.Join(errList, \"\\n\"))\n\t}\n\tlog2C := int(math.Log2(float64(C)))\n\tlog2T := int(math.Log2(float64(T)))\n\tpublicKeyLen := N * C\n\n\tp := &ph{\n\t\tt: T,\n\t\tc: C,\n\t\tk: K,\n\n\t\tlog2T: log2T,\n\t\tlog2C: log2C,\n\n\t\t_SKLEN: 2 * N,\n\t\tstreamLen: 8 * K,\n\t\tpublicKeyLen: publicKeyLen,\n\n\t\tekLen: N * T,\n\n\t\tsigLen: (K * N) + (K * (log2T - log2C) * N) + N,\n\t}\n\n\treturn p, nil\n}", "func NewProcedureMock(t minimock.Tester) *ProcedureMock {\n\tm := &ProcedureMock{t: t}\n\tif controller, ok := t.(minimock.MockController); ok {\n\t\tcontroller.RegisterMocker(m)\n\t}\n\n\tm.ProceedMock = mProcedureMockProceed{mock: m}\n\tm.ProceedMock.callArgs = []*ProcedureMockProceedParams{}\n\n\treturn m\n}", "func Init(config Config) pdfium.Pool {\n\t// Create an hclog.Logger\n\tlogger := hclog.New(&hclog.LoggerOptions{\n\t\tName: \"plugin\",\n\t\tOutput: os.Stdout,\n\t\tLevel: hclog.Debug,\n\t})\n\n\tvar handshakeConfig = plugin.HandshakeConfig{\n\t\tProtocolVersion: 1,\n\t\tMagicCookieKey: \"BASIC_PLUGIN\",\n\t\tMagicCookieValue: \"hello\",\n\t}\n\n\t// pluginMap is the map of plugins we can dispense.\n\tvar pluginMap = map[string]plugin.Plugin{\n\t\t\"pdfium\": &commons.PdfiumPlugin{},\n\t}\n\n\t// If we don't have a log callback, make the callback no-op.\n\tif config.LogCallback == nil {\n\t\tconfig.LogCallback = func(s string) {}\n\t}\n\n\tfactory := pool.NewPooledObjectFactory(\n\t\tfunc(goctx.Context) (interface{}, error) {\n\t\t\tnewWorker := &worker{}\n\n\t\t\tclient := plugin.NewClient(&plugin.ClientConfig{\n\t\t\t\tHandshakeConfig: handshakeConfig,\n\t\t\t\tPlugins: pluginMap,\n\t\t\t\tCmd: exec.Command(config.Command.BinPath, config.Command.Args...),\n\t\t\t\tLogger: logger,\n\t\t\t\tStartTimeout: config.Command.StartTimeout,\n\t\t\t})\n\n\t\t\trpcClient, err := client.Client()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\traw, err := rpcClient.Dispense(\"pdfium\")\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tpdfium := raw.(commons.Pdfium)\n\n\t\t\tpong, err := pdfium.Ping()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif pong != \"Pong\" {\n\t\t\t\treturn nil, errors.New(\"Wrong ping/pong result\")\n\t\t\t}\n\n\t\t\tnewWorker.pluginClient = client\n\t\t\tnewWorker.rpcClient = rpcClient\n\t\t\tnewWorker.plugin = pdfium\n\n\t\t\treturn newWorker, nil\n\t\t}, nil, func(ctx goctx.Context, object *pool.PooledObject) bool {\n\t\t\tworker := object.Object.(*worker)\n\t\t\tif worker.pluginClient.Exited() {\n\t\t\t\tconfig.LogCallback(\"Worker exited\")\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\terr := worker.rpcClient.Ping()\n\t\t\tif err != nil {\n\t\t\t\tconfig.LogCallback(fmt.Sprintf(\"Error on RPC ping: %s\", err.Error()))\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tpong, err := worker.plugin.Ping()\n\t\t\tif err != nil {\n\t\t\t\tconfig.LogCallback(fmt.Sprintf(\"Error on plugin ping:: %s\", err.Error()))\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tif pong != \"Pong\" {\n\t\t\t\terr = errors.New(\"Wrong ping/pong result\")\n\t\t\t\tconfig.LogCallback(fmt.Sprintf(\"Error on plugin ping:: %s\", err.Error()))\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\treturn true\n\t\t}, nil, nil)\n\tp := pool.NewObjectPoolWithDefaultConfig(goctx.Background(), factory)\n\tp.Config = &pool.ObjectPoolConfig{\n\t\tBlockWhenExhausted: true,\n\t\tMinIdle: config.MinIdle,\n\t\tMaxIdle: config.MaxIdle,\n\t\tMaxTotal: config.MaxTotal,\n\t\tTestOnBorrow: true,\n\t\tTestOnReturn: true,\n\t\tTestOnCreate: true,\n\t}\n\n\tp.PreparePool(goctx.Background())\n\n\tmultiThreadedMutex.Lock()\n\tdefer multiThreadedMutex.Unlock()\n\n\tpoolRef := uuid.New()\n\n\t// Create a new PDFium pool.\n\tnewPool := &pdfiumPool{\n\t\tpoolRef: poolRef.String(),\n\t\tinstanceRefs: map[string]*pdfiumInstance{},\n\t\tlock: &sync.Mutex{},\n\t\tworkerPool: p,\n\t}\n\n\tpoolRefs[newPool.poolRef] = newPool\n\n\treturn newPool\n}", "func (s *ParticlePhysicsSystem) New(world *ecs.World) {\n\ts.simulationAcc = 0\n\ts.simulationStep = 1.0 / float32(s.SimulationRate)\n}", "func (pd *philosopherData) Init(respChannel chan string) {\n\tpd.respChannel = respChannel\n\tpd.eating = false\n\tpd.dinnersSpent = 0\n\tpd.seat = -1\n\tpd.leftChopstick = -1\n\tpd.rightChopstick = -1\n}", "func NewPuppy(color string, height int, name string) Puppy {\n\treturn Puppy{\n\t\tparent: Dog{color: color, height: height, name: name},\n\t\tname: name,\n\t}\n}", "func New(pid, ppid uint32, name, cmndline, exe string, sid *windows.SID, sessionID uint32) *PS {\n\tps := &PS{\n\t\tPID: pid,\n\t\tPpid: ppid,\n\t\tName: name,\n\t\tCmdline: cmndline,\n\t\tExe: exe,\n\t\tArgs: cmdline.Split(cmndline),\n\t\tSID: sid.String(),\n\t\tSessionID: sessionID,\n\t\tThreads: make(map[uint32]Thread),\n\t\tModules: make([]Module, 0),\n\t\tHandles: make([]htypes.Handle, 0),\n\t}\n\tps.Username, ps.Domain, _, _ = sid.LookupAccount(\"\")\n\treturn ps\n}", "func NewGoodbye(l *log.Logger) *Goodbye {\n\treturn &Goodbye{l}\n}", "func NewPPO(short, long, signal uint, priceType string) *ppo {\r\n\treturn &ppo{\r\n\t\tperiod: long,\r\n\t\tprev: math.NaN(),\r\n\t\tpriceType: priceType,\r\n\t\tshort: NewEMA(short, priceType),\r\n\t\tlong: NewEMA(long, priceType),\r\n\t\tsignal: NewEMA(signal, priceType),\r\n\t}\r\n}", "func NewPharse(pharse string) (*Pharse, error) {\n\tvar p Pharse\n\tp.Pharse = pharse\n\tp.Translations = make(map[string]Translate, 0)\n\n\tsum, err := sha1sum(pharse)\n\tp.Sum = sum\n\n\treturn &p, err\n}", "func NewPlanner()(*Planner) {\n m := &Planner{\n Entity: *NewEntity(),\n }\n return m\n}", "func newProtonInstance(proton core.Protoner) reflect.Value {\n\tbaseValue := reflect.ValueOf(proton)\n\n\t// try to create new value of proton\n\tmethod := baseValue.MethodByName(\"New\")\n\tif method.IsValid() {\n\t\treturns := method.Call(emptyParameters)\n\t\tif len(returns) <= 0 {\n\t\t\tpanic(fmt.Sprintf(\"Method New must has at least 1 returns. now %d\", len(returns)))\n\t\t}\n\t\treturn returns[0]\n\t} else {\n\t\t// return reflect.New(reflect.TypeOf(proton).Elem())\n\t\treturn newInstance(reflect.TypeOf(proton))\n\t}\n}", "func New(p string, t time.Time) *PT {\n\treturn &PT{p, t}\n}", "func NewPlugin() (shared.Plugin, error) {\n\treturn instance, nil\n}", "func NewPlugin(next http.HandlerFunc) http.HandlerFunc {\n\tp, err := plugin.Open(\"plugin.so\")\n\tif err != nil {\n\t\tif strings.HasPrefix(err.Error(), \"plugin.Open\") {\n\t\t\tfmt.Printf(\"error: could not open plugin file 'plugin.so': %v\\n\", err)\n\t\t}\n\t\treturn next\n\t}\n\tf, err := p.Lookup(\"Handler\")\n\tif err != nil {\n\t\tfmt.Printf(\"error: could not find plugin Handler function %v\\n\", err)\n\t\treturn next\n\t}\n\tpluginFn, ok := f.(func(http.HandlerFunc) http.HandlerFunc)\n\tif !ok {\n\t\tfmt.Println(\"error: plugin Handler function should be 'func(http.HandlerFunc) http.HandlerFunc'\")\n\t\treturn next\n\t}\n\treturn pluginFn(next)\n}", "func NewProof(hash *hash.Hash, public Public, private Private) *Proof {\n\tn := public.Pedersen.N\n\tphi := private.Phi\n\n\ta := make([]*big.Int, params.StatParam)\n\tA := make([]*big.Int, params.StatParam)\n\n\tfor i := 0; i < params.StatParam; i++ {\n\t\t// aᵢ ∈ mod ϕ(N)\n\t\ta[i] = sample.IntervalLN(rand.Reader)\n\t\ta[i].Mod(a[i], phi)\n\n\t\t// Aᵢ = tᵃ mod N\n\t\tA[i] = new(big.Int).Exp(public.Pedersen.T, a[i], n)\n\t}\n\n\tes := challenge(hash, public, A)\n\n\tZ := make([]*big.Int, params.StatParam)\n\tfor i := 0; i < params.StatParam; i++ {\n\t\tz := a[i]\n\t\tif es[i] {\n\t\t\tz.Add(z, private.Lambda)\n\t\t\tz.Mod(z, phi)\n\t\t}\n\t\tZ[i] = z\n\t}\n\n\treturn &Proof{\n\t\tA: &A,\n\t\tZ: &Z,\n\t}\n}", "func NewGopper(cachelocation, cachelocationsysljson, fsType, accept string) (*gop.GopperService, error) {\n\tr := gop.GopperService{}\n\tswitch fsType {\n\tcase \"os\":\n\t\tr.Gopper = gop_filesystem.New(afero.NewOsFs(), MemoryLoc(accept))\n\tcase \"mem\", \"memory\", \"\":\n\t\tr.Gopper = gop_filesystem.New(MemoryFs(accept), \"/\")\n\tcase \"gcs\":\n\t\tif accept == pbjsonaccept {\n\t\t\tcachelocation = cachelocationsysljson\n\t\t}\n\t\tgcs := gop_gcs.New(cachelocation)\n\t\tr.Gopper = &gcs\n\t}\n\tgh := retriever_github.New(\n\t\tcli.TokensFromString(\n\t\t\t\"github.com:\"+Secret(\"GH_TOKEN\")))\n\tproxyURL, err := url.Parse(Secret(\"HTTP_PROXY\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgh.Client = &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)}}\n\tswitch accept {\n\tcase pbjsonaccept:\n\t\tr.Retriever =\n\t\t\tretriever_wrapper.New(\n\t\t\t\tNewProcessor(\n\t\t\t\t\tmodules.New(\n\t\t\t\t\t\tgh,\n\t\t\t\t\t\t\"sysl_modules/sysl_modules.yaml\")))\n\tdefault:\n\t\tr.Retriever =\n\t\t\tretriever_wrapper.New(\n\t\t\t\tmodules.New(\n\t\t\t\t\tgh,\n\t\t\t\t\t\"sysl_modules/sysl_modules.yaml\"))\n\n\t}\n\treturn &r, nil\n}", "func newPlayer(s sender, tape tape, pm core.PulseManager, scheme core.PlatformCryptographyScheme) *player {\n\treturn &player{sender: s, tape: tape, pm: pm, scheme: scheme}\n}", "func NewSibling(t interface {\n\tmock.TestingT\n\tCleanup(func())\n}) *Sibling {\n\tmock := &Sibling{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func newPeer(server *server, name string, connectionString string, heartbeatInterval time.Duration) *Peer {\n\treturn &Peer{\n\t\tserver: server,\n\t\tName: name,\n\t\tConnectionString: connectionString,\n\t\theartbeatInterval: heartbeatInterval,\n\t}\n}", "func New() *Greeter {\n\treturn &Greeter{}\n}", "func New() *Greeter {\n\treturn &Greeter{}\n}", "func New() *Greeter {\n\treturn &Greeter{}\n}", "func New(next goproxy.Plugin, cache FileCache) goproxy.Plugin {\n\treturn &plugin{next: next, cache: cache}\n}", "func NewFHIPE(l int, boundX, boundY *big.Int) (*FHIPE, error) {\n\tboundXY := new(big.Int).Mul(boundX, boundY)\n\tprod := new(big.Int).Mul(big.NewInt(int64(2*l)), boundXY)\n\tif prod.Cmp(bn256.Order) > 0 {\n\t\treturn nil, fmt.Errorf(\"2 * l * boundX * boundY should be smaller than group order\")\n\t}\n\n\treturn &FHIPE{\n\t\tParams: &FHIPEParams{\n\t\t\tL: l,\n\t\t\tBoundX: boundX,\n\t\t\tBoundY: boundY}}, nil\n}", "func NewPair(p *big.Int, g int64) (private, public *big.Int) {\n\tprivate = PrivateKey(p)\n\tpublic = PublicKey(private, p, g)\n\treturn\n}", "func NewPHash() PHash {\n\treturn PHash{\n\t\twidth: 32,\n\t\theight: 32,\n\t\tinterp: imgproc.BilinearExact,\n\t}\n}", "func New(qChan qtypes_qchannel.QChan, cfg *config.Config, name string) (Plugin, error) {\n\tp := Plugin{\n\t\tPlugin: qtypes_plugin.NewNamedPlugin(qChan, cfg, pluginTyp, pluginPkg, name, version),\n\t}\n\tp.Version = version\n\tp.Name = name\n\treturn p, nil\n}", "func New(disco *xep0030.DiscoInfo, presenceHub *xep0115.EntityCaps, router router.Router, rosterRep repository.Roster, pubSubRep repository.PubSub) *Pep {\n\tp := &Pep{\n\t\trunQueue: runqueue.New(\"xep0163\"),\n\t\trosterRep: rosterRep,\n\t\tpubSubRep: pubSubRep,\n\t\trouter: router,\n\t\tdisco: disco,\n\t\tentityCaps: presenceHub,\n\t}\n\t// register account identity and features\n\tif disco != nil {\n\t\tfor _, feature := range pepFeatures {\n\t\t\tdisco.RegisterAccountFeature(feature)\n\t\t}\n\t}\n\t// register disco items\n\tp.registerDiscoItems(context.Background())\n\treturn p\n}", "func philosopherPonderanceGoroutine(id int) {\n\tfor {\n\t\tif rand.Float64() < PHILSWITCHCHANCE {\n\t\t\tphilIn[id] <- 2\n\t\t\tisEating := <- philOut[id] == 1\n\t\t\t// Switch: Thinking <-> Eating.\n\t\t\tif isEating {\n\t\t\t\t// Drop forks and return to positing on the nature of the universe.\n\t\t\t\tphilIn[id] <- 1\n\t\t\t} else {\n\t\t\t\t// Attempt to begin eating. Return to postulating, if missing fork.\n\t\t\t\tphilIn[id] <- 0\n\t\t\t}\n\t\t\t<- philOut[id]\n\t\t}\n\t}\n}", "func NewIChanOf(pq *PQueue) *IChan {\n\tpoke := make(chan struct{})\n\tdata := make(chan []byte)\n\n\tichan := &IChan{pqueue: pq, poke: poke, output: data}\n\n\tpuller := &puller{\n\t\tpqueue: ichan.pqueue,\n\t\tpoke: ichan.poke,\n\t\tqueueSize: ichan.pqueue.size,\n\t}\n\tichan.puller = puller\n\n\tgo puller.recv(data)\n\n\tichan.poke <- struct{}{}\n\treturn ichan\n}", "func NewProcTable() *ProcTableImpl {\n\treturn &ProcTableImpl{procTable: make(map[string]ProcEntry)}\n}", "func NewPomeloPacketDecoder() *PomeloPacketDecoder {\n\treturn &PomeloPacketDecoder{}\n}", "func New(\n\tctx context.Context,\n\tdsn string,\n\twaitFor time.Duration,\n\ttracer opentracing.Tracer,\n) (PgxWrapper, error) {\n\tcfg, err := pgxpool.ParseConfig(dsn)\n\tif err != nil {\n\t\treturn PgxWrapper{}, fmt.Errorf(\"could not create new connection configuration: %w\", err)\n\t}\n\n\tpool, err := newPgxPool(ctx, cfg, waitFor)\n\tif err != nil {\n\t\treturn PgxWrapper{}, fmt.Errorf(\"could not create new connection pool: %w\", err)\n\t}\n\n\treturn PgxWrapper{\n\t\tpool: pool,\n\t\ttracer: tracer,\n\t}, nil\n}", "func NewPopTable(h SQLHandle) *PopTable {\n\treturn &PopTable{h}\n}", "func NewPointer() *link {\n\treturn new(link)\n}", "func NewPinger(underlyingConn ircparse.Conn, cfg PingConfig) (ircparse.Conn, error) {\n\tif cfg.Interval == 0 {\n\t\tcfg.Interval = 1 * time.Minute\n\t}\n\tif cfg.Timeout == 0 {\n\t\tcfg.Timeout = 2 * cfg.Interval\n\t}\n\tp := &pinger{\n\t\tcfg: cfg,\n\t\tunderlyingConn: underlyingConn,\n\t\texpecting: map[string]struct{}{},\n\t\tpongChan: make(chan *ircparse.Message, 8),\n\t\tclosedChan: make(chan struct{}),\n\t}\n\n\tgo p.loop()\n\treturn p, nil\n}", "func NewProxy(addr string, prophetAddrs ...string) *Proxy {\n\tp := &Proxy{\n\t\tAddr: addr,\n\t\tsvr: goetty.NewServer(addr,\n\t\t\tgoetty.WithServerDecoder(meta.SeataDecoder),\n\t\t\tgoetty.WithServerEncoder(meta.SeataEncoder),\n\t\t\tgoetty.WithServerIDGenerator(goetty.NewUUIDV4IdGenerator())),\n\t\tsessions: make(map[string]*session),\n\t}\n\n\tp.router = newRouter(p.handleRsp, prophetAddrs...)\n\treturn p\n}", "func New(inputRadius int) *Haversine {\n\th := Haversine{radius: float64(inputRadius)}\n\tif h.radius == 0 {\n\t\th.radius = radius\n\t}\n\treturn &h\n}", "func New() *Kolonish {\n\treturn &Kolonish{}\n}", "func (pb *PhilosopherBase) IsHungry() bool {\n\treturn pb.State == philstate.Hungry\n}", "func New() *Plugin {\n\treturn &Plugin{}\n}", "func New(hh hHandler, kh kHandler) Interactor {\n\treturn Interactor{hh: hh, kh: kh}\n}", "func New(_ runtime.Object, h framework.Handle) (framework.Plugin, error) {\n\treturn &PodState{handle: h}, nil\n}", "func NewParticle(id int, config Config) *Particle {\n\treturn &Particle{\n\t\tID: id,\n\t\tConfig: config,\n\t\tDirection: Vector{\n\t\t\trandf(-100, 100) / 100.0,\n\t\t\trandf(-100, 100) / 100.0,\n\t\t},\n\t}\n}", "func New(tb testing.TB, settings hostdb.HostSettings, wm host.Wallet, tpool host.TransactionPool) *Host {\n\ttb.Helper()\n\tl, err := net.Listen(\"tcp\", \":0\")\n\tif err != nil {\n\t\ttb.Fatal(err)\n\t}\n\ttb.Cleanup(func() { l.Close() })\n\tsettings.NetAddress = modules.NetAddress(l.Addr().String())\n\tsettings.UnlockHash, err = wm.Address()\n\tif err != nil {\n\t\ttb.Fatal(err)\n\t}\n\tkey := ed25519.NewKeyFromSeed(frand.Bytes(ed25519.SeedSize))\n\th := &Host{\n\t\tPublicKey: hostdb.HostKeyFromPublicKey(ed25519hash.ExtractPublicKey(key)),\n\t\tSettings: settings,\n\t\tl: l,\n\t}\n\tcs := newEphemeralContractStore(key)\n\tss := newEphemeralSectorStore()\n\tsh := host.NewSessionHandler(key, (*constantHostSettings)(&h.Settings), cs, ss, wm, tpool, nopMetricsRecorder{})\n\tgo listen(sh, l)\n\th.cw = host.NewChainWatcher(tpool, wm, cs, ss)\n\treturn h\n}", "func NewPlayer(conn *dbus.Conn, name string, interpolate bool, poll int) (p *Player) {\n\tplayerName := strings.ReplaceAll(name, INTERFACE+\".\", \"\")\n\tvar pid uint32\n\tconn.BusObject().Call(\"org.freedesktop.DBus.GetConnectionUnixProcessID\", 0, name).Store(&pid)\n\tfor key, val := range knownPlayers {\n\t\tif strings.Contains(name, key) {\n\t\t\tplayerName = val\n\t\t\tbreak\n\t\t}\n\t}\n\tif playerName == \"Browser\" {\n\t\tfile, err := ioutil.ReadFile(fmt.Sprintf(\"/proc/%d/cmdline\", pid))\n\t\tif err == nil {\n\t\t\tcmd := string(file)\n\t\t\tfor key, val := range knownBrowsers {\n\t\t\t\tif strings.Contains(cmd, key) {\n\t\t\t\t\tplayerName = val\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tp = &Player{\n\t\tPlayer: conn.Object(name, PATH),\n\t\tconn: conn,\n\t\tName: playerName,\n\t\tFullName: name,\n\t\tpid: pid,\n\t\tinterpolate: interpolate,\n\t\tpoll: poll,\n\t}\n\tp.Refresh()\n\treturn\n}", "func newPprofHandler(svr *server.Server, rd *render.Render) *pprofHandler {\n\treturn &pprofHandler{\n\t\tsvr: svr,\n\t\trd: rd,\n\t}\n}", "func NewPerm(input interface{}, less Less) (*Permutator, error) {\n\tvalue := reflect.ValueOf(input)\n \n\t//check to see if i is a slice\n\tif value.Kind() != reflect.Slice {\n\t\treturn nil, errors.New(\"argument must be a slice\")\n\t}\n \n\tif value.IsValid() != true {\n\t\treturn nil, errors.New(\"argument must not be nil\")\n\t}\n \n\tif value.Len() == 0 {\n\t\treturn nil, errors.New(\"argument must not be empty\")\n\t}\n\n\tl := reflect.MakeSlice(value.Type(), value.Len(), value.Len())\n\t\n reflect.Copy(l, value)\n \n\tvalue = l\n \n\tlength := value.Len()\n \n\tif less == nil {\n lessType, err := getLessFunctionByValueType(value)\n if err != nil {\n return nil, err\n }\n less = lessType\n\t}\n \n sortValues(value, less)\n\n\ts := &Permutator { value: value, less: less, length: length, index: 1, amount: factorial(length) }\n\ts.idle = make(chan bool, 1)\n\ts.idle <- true\n \n\treturn s, nil\n}", "func NewPlugin(opts ...Option) *Plugin {\n\tp := &Plugin{}\n\n\tp.SetName(\"generator\")\n\tp.KVStore = &etcd.DefaultPlugin\n\tp.KVScheduler = &kvscheduler.DefaultPlugin\n\n\tfor _, o := range opts {\n\t\to(p)\n\t}\n\n\tp.Setup()\n\n\treturn p\n}", "func New(chainID, remote string) (provider.Provider, error) {\n\thttpClient, err := rpcclient.NewHTTP(remote, \"/websocket\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewWithClient(chainID, httpClient), nil\n}", "func NewFakeProcTable() *FakeProcTableImpl {\n\treturn &FakeProcTableImpl{realTable: NewProcTable()}\n}", "func NewPlugin(name, version, endpointType string) (*Plugin, error) {\n\t// Setup base plugin.\n\tplugin, err := common.NewPlugin(name, version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Plugin{\n\t\tPlugin: plugin,\n\t\tEndpointType: endpointType,\n\t}, nil\n}", "func newPingChannelServer(s *StorjTelehash) func() ChannelHandler {\n\treturn func() ChannelHandler {\n\t\tlogging.Println(\"factory\")\n\t\tlogging.Println(s)\n\t\treturn &pingChannelServer{st: s}\n\t}\n}", "func NewLinkedList() LinkedList {\n\treturn LinkedList{}\n}", "func NewProxy(\n\tlightClient *light.Client,\n\tlistenAddr, providerAddr string,\n\tconfig *rpcserver.Config,\n\tlogger log.Logger,\n\topts ...lrpc.Option,\n) (*Proxy, error) {\n\trpcClient, err := rpchttp.NewWithTimeout(providerAddr, \"/websocket\", uint(config.WriteTimeout.Seconds()))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create http client for %s: %w\", providerAddr, err)\n\t}\n\n\treturn &Proxy{\n\t\tAddr: listenAddr,\n\t\tConfig: config,\n\t\tClient: lrpc.NewClient(rpcClient, lightClient, opts...),\n\t\tLogger: logger,\n\t}, nil\n}", "func (phi *Philosopher) Name() string {\n\treturn phi.name\n}", "func newPlayer(x, y int, right bool, moveTimer, shotTimer,\n\toxygen int) *player {\n\tsub := newSubmarine(x, y, right, moveTimer, shotTimer)\n\n\treturn &player{\n\t\tsubmarine: sub,\n\t\tremainingOxygen: oxygen,\n\t\tdiverCount: 0,\n\t}\n}", "func NewPier(repoRoot string, config *repo.Config) (*Pier, error) {\n\tstore, err := leveldb.New(filepath.Join(config.RepoRoot, \"store\"))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"read from datastaore %w\", err)\n\t}\n\n\tlogger := loggers.Logger(loggers.App)\n\tprivateKey, err := repo.LoadPrivateKey(repoRoot)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"repo load key: %w\", err)\n\t}\n\n\taddr, err := privateKey.PublicKey().Address()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"get address from private key %w\", err)\n\t}\n\n\tnodePrivKey, err := repo.LoadNodePrivateKey(repoRoot)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"repo load node key: %w\", err)\n\t}\n\n\tvar (\n\t\tck checker.Checker\n\t\tcryptor txcrypto.Cryptor\n\t\tex exchanger.IExchanger\n\t\tlite lite.Lite\n\t\tpierHA agency.PierHA\n\t\tsync syncer.Syncer\n\t\tapiServer *api.Server\n\t\tmeta *pb.Interchain\n\t\t//chain *appchainmgr.Appchain\n\t\tpeerManager peermgr.PeerManager\n\t)\n\n\tswitch config.Mode.Type {\n\tcase repo.DirectMode: //直链模式\n\t\tpeerManager, err = peermgr.New(config, nodePrivKey, privateKey, 1, loggers.Logger(loggers.PeerMgr))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"peerMgr create: %w\", err)\n\t\t}\n\n\t\truleMgr, err := rulemgr.New(store, peerManager, loggers.Logger(loggers.RuleMgr))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"ruleMgr create: %w\", err)\n\t\t}\n\n\t\tappchainMgr, err := appchain.NewManager(config.Appchain.DID, store, peerManager, loggers.Logger(loggers.AppchainMgr))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"ruleMgr create: %w\", err)\n\t\t}\n\n\t\tapiServer, err = api.NewServer(appchainMgr, peerManager, config, loggers.Logger(loggers.ApiServer))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"gin service create: %w\", err)\n\t\t}\n\n\t\tck = checker.NewDirectChecker(ruleMgr, appchainMgr)\n\n\t\tcryptor, err = txcrypto.NewDirectCryptor(appchainMgr, privateKey)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cryptor create: %w\", err)\n\t\t}\n\n\t\tmeta = &pb.Interchain{}\n\t\tlite = &direct_lite.MockLite{}\n\tcase repo.RelayMode: //中继链架构模式。\n\t\tck = &checker.MockChecker{}\n\n\t\t// pier register to bitxhub and got meta infos about its related\n\t\t// appchain from bitxhub\n\t\topts := []rpcx.Option{\n\t\t\trpcx.WithLogger(logger),\n\t\t\trpcx.WithPrivateKey(privateKey),\n\t\t}\n\t\tnodesInfo := make([]*rpcx.NodeInfo, 0, len(config.Mode.Relay.Addrs))\n\t\tfor _, addr := range config.Mode.Relay.Addrs {\n\t\t\tnodeInfo := &rpcx.NodeInfo{Addr: addr}\n\t\t\tif config.Security.EnableTLS {\n\t\t\t\tnodeInfo.CertPath = filepath.Join(config.RepoRoot, config.Security.Tlsca)\n\t\t\t\tnodeInfo.EnableTLS = config.Security.EnableTLS\n\t\t\t\tnodeInfo.CommonName = config.Security.CommonName\n\t\t\t}\n\t\t\tnodesInfo = append(nodesInfo, nodeInfo)\n\t\t}\n\t\topts = append(opts, rpcx.WithNodesInfo(nodesInfo...), rpcx.WithTimeoutLimit(config.Mode.Relay.TimeoutLimit))\n\t\tclient, err := rpcx.New(opts...)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"create bitxhub client: %w\", err)\n\t\t}\n\n\t\t// agent queries appchain info from bitxhub\n\t\tmeta, err = getInterchainMeta(client, config.Appchain.DID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t//chain, err = getAppchainInfo(client)\n\t\t//if err != nil {\n\t\t//\treturn nil, err\n\t\t//}\n\n\t\tcryptor, err = txcrypto.NewRelayCryptor(client, privateKey)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cryptor create: %w\", err)\n\t\t}\n\n\t\tlite, err = bxh_lite.New(client, store, loggers.Logger(loggers.BxhLite))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"lite create: %w\", err)\n\t\t}\n\n\t\tsync, err = syncer.New(addr.String(), config.Appchain.DID, repo.RelayMode,\n\t\t\tsyncer.WithClient(client), syncer.WithLite(lite),\n\t\t\tsyncer.WithStorage(store), syncer.WithLogger(loggers.Logger(loggers.Syncer)),\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"syncer create: %w\", err)\n\t\t}\n\t\tpierHAConstructor, err := agency.GetPierHAConstructor(config.HA.Mode)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"pier ha constructor not found\")\n\t\t}\n\t\tpierHA = pierHAConstructor(client, config.Appchain.DID)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported mode\")\n\t}\n\n\t//use meta info to instantiate monitor and executor module\n\textra, err := json.Marshal(meta.InterchainCounter)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"marshal interchain meta: %w\", err)\n\t}\n\n\tvar cli plugins.Client\n\tvar grpcPlugin *plugin.Client\n\terr = retry.Retry(func(attempt uint) error {\n\t\tcli, grpcPlugin, err = plugins.CreateClient(config.Appchain.DID, config.Appchain, extra)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(\"client plugin create:%s\", err)\n\t\t}\n\t\treturn err\n\t}, strategy.Wait(3*time.Second))\n\tif err != nil {\n\t\tlogger.Panic(err)\n\t}\n\n\tmnt, err := monitor.New(cli, cryptor, loggers.Logger(loggers.Monitor))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"monitor create: %w\", err)\n\t}\n\n\texec, err := executor.New(cli, config.Appchain.DID, store, cryptor, loggers.Logger(loggers.Executor))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"executor create: %w\", err)\n\t}\n\n\tex, err = exchanger.New(config.Mode.Type, config.Appchain.DID, meta,\n\t\texchanger.WithChecker(ck),\n\t\texchanger.WithExecutor(exec),\n\t\texchanger.WithMonitor(mnt),\n\t\texchanger.WithPeerMgr(peerManager),\n\t\texchanger.WithSyncer(sync),\n\t\texchanger.WithAPIServer(apiServer),\n\t\texchanger.WithStorage(store),\n\t\texchanger.WithLogger(loggers.Logger(loggers.Exchanger)),\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"exchanger create: %w\", err)\n\t}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\n\treturn &Pier{\n\t\tprivateKey: privateKey,\n\t\tplugin: cli,\n\t\tgrpcPlugin: grpcPlugin,\n\t\t// appchain: chain,\n\t\tmeta: meta,\n\t\tmonitor: mnt,\n\t\texchanger: ex,\n\t\texec: exec,\n\t\tlite: lite,\n\t\tpierHA: pierHA,\n\t\tlogger: logger,\n\t\tstorage: store,\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\tconfig: config,\n\t}, nil\n}", "func NewHandle(ctx *cuda.Context) (*Handle, error) {\n\tres := &Handle{ctx: ctx, ptrMode: Host}\n\terr := newError(\"cublasCreate\", C.cublasCreate(&res.handle))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\truntime.SetFinalizer(res, func(obj *Handle) {\n\t\tgo obj.ctx.Run(func() error {\n\t\t\tC.cublasDestroy(obj.handle)\n\t\t\treturn nil\n\t\t})\n\t})\n\treturn res, nil\n}" ]
[ "0.7390079", "0.5313849", "0.51934826", "0.50953144", "0.4946036", "0.4946036", "0.49414137", "0.48797095", "0.48634556", "0.48188093", "0.47800687", "0.47365052", "0.47281492", "0.47103977", "0.47000962", "0.46877432", "0.46819764", "0.46738124", "0.45898148", "0.45856252", "0.45829633", "0.45710436", "0.4569065", "0.45608258", "0.455563", "0.45545182", "0.45444554", "0.45130223", "0.45035356", "0.44914788", "0.4488164", "0.44682634", "0.44612372", "0.44443497", "0.4441644", "0.44372743", "0.44277772", "0.44190168", "0.44177952", "0.44080094", "0.4402781", "0.43945417", "0.43779606", "0.43667862", "0.43623573", "0.4357163", "0.435234", "0.4352273", "0.4339863", "0.43396032", "0.43321747", "0.43189365", "0.43165588", "0.43140924", "0.43135434", "0.4287563", "0.42648938", "0.42574516", "0.42573366", "0.42552897", "0.42535067", "0.42535067", "0.42535067", "0.4241093", "0.42308822", "0.42290536", "0.42285287", "0.42271873", "0.42248812", "0.4222228", "0.422138", "0.4217294", "0.42156795", "0.41960526", "0.4186719", "0.41816154", "0.41759473", "0.41722196", "0.41679794", "0.41679594", "0.41650617", "0.4157748", "0.41541708", "0.41532642", "0.41532192", "0.41491205", "0.41483843", "0.4144627", "0.4139095", "0.41384655", "0.4138245", "0.4138143", "0.41353902", "0.41246957", "0.41202447", "0.41192847", "0.41131577", "0.41111386", "0.410984", "0.41059285" ]
0.8623369
0
Init can be used to initialize a Philosopher.
func (phi *Philosopher) Init(name string) { phi.name = name phi.respChannel = make(chan string) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pd *philosopherData) Init(respChannel chan string) {\n\tpd.respChannel = respChannel\n\tpd.eating = false\n\tpd.dinnersSpent = 0\n\tpd.seat = -1\n\tpd.leftChopstick = -1\n\tpd.rightChopstick = -1\n}", "func (host *DinnerHost) Init(tableCount, maxParallel, maxDinner int) {\n\thost.phiData = make(map[string]*philosopherData)\n\thost.requestChannel = make(chan string)\n\thost.finishChannel = make(chan string)\n\thost.maxParallel = maxParallel\n\tif host.maxParallel > tableCount {\n\t\thost.maxParallel = tableCount\n\t}\n\thost.maxDinner = maxDinner\n\thost.currentlyEating = 0\n\thost.tableCount = tableCount\n\thost.chopsticksFree = make([]bool, 5)\n\tfor i := range host.chopsticksFree {\n\t\thost.chopsticksFree[i] = true\n\t}\n\trand.Seed(time.Now().Unix())\n\thost.freeSeats = rand.Perm(tableCount)\n}", "func (s *Solo) Init(state *state.State, service *service.Service) error {\n\n\ts.logger.Debug(\"INIT\")\n\n\ts.state = state\n\ts.service = service\n\n\treturn nil\n}", "func (g *Glutton) Init() (err error) {\n\n\tctx := context.Background()\n\tg.ctx, g.cancel = context.WithCancel(ctx)\n\n\tgluttonServerPort := uint(g.conf.GetInt(\"glutton_server\"))\n\n\t// Initiate the freki processor\n\tg.processor, err = freki.New(viper.GetString(\"interface\"), g.rules, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Initiating glutton server\n\tg.processor.AddServer(freki.NewUserConnServer(gluttonServerPort))\n\t// Initiating log producer\n\tif g.conf.GetBool(\"enableGollum\") {\n\t\tg.producer = producer.Init(g.id.String(), g.conf.GetString(\"gollumAddress\"))\n\t}\n\t// Initiating protocol handlers\n\tg.mapProtocolHandlers()\n\tg.registerHandlers()\n\n\terr = g.processor.Init()\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn nil\n}", "func (pb *PhilosopherBase) Start() {\n\tpb.State = philstate.Thinking\n\tpb.StartThinking()\n}", "func (p Polynomial) Init(s []ed25519.Scalar) {\n\tcopy(p.coeffs, s)\n}", "func (s *Sim) Init() {\n\ts.System = make([]*poly.Chain,0)\n\ts.solver = new(solver.RK4)\n\ts.solver.Mods = make([]solver.Modifier,0)\n\ts.solverInit = false\n}", "func (o *ParamsReg) Init(nFeatures int) {\n\to.theta = la.NewVector(nFeatures)\n\to.bkpTheta = la.NewVector(nFeatures)\n}", "func (g *grpc) Init(gen *generator.Generator) {\n\tg.gen = gen\n}", "func newPhilosopherDataPtr(respChannel chan string) *philosopherData {\n\tpd := new(philosopherData)\n\tpd.Init(respChannel)\n\treturn pd\n}", "func (s *Speaker) Init() error { return nil }", "func (p *Noise) Init() error {\n\tfieldFilter, err := filter.NewIncludeExcludeFilter(p.IncludeFields, p.ExcludeFields)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating fieldFilter failed: %w\", err)\n\t}\n\tp.fieldFilter = fieldFilter\n\n\tswitch p.NoiseType {\n\tcase \"\", \"laplacian\":\n\t\tp.generator = &distuv.Laplace{Mu: p.Mu, Scale: p.Scale}\n\tcase \"uniform\":\n\t\tp.generator = &distuv.Uniform{Min: p.Min, Max: p.Max}\n\tcase \"gaussian\":\n\t\tp.generator = &distuv.Normal{Mu: p.Mu, Sigma: p.Scale}\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown distribution type %q\", p.NoiseType)\n\t}\n\treturn nil\n}", "func (Operator *Operators) Init(stub shim.ChaincodeStubInterface) peer.Response {\n\t// Simply print a message\n\tfmt.Println(\"Initialize voting contract\")\n\n\t// Init lists\n\tvoter_list, _ := json.Marshal([]Operators{})\n\tvotes, _ := json.Marshal([]Votes{})\n\tclosedVotes, _ := json.Marshal([]Votes{})\n\n\t// Put states to level DB\n\tstub.PutState(\"Operators\", voter_list)\n\tstub.PutState(\"Votes\", votes)\n\tstub.PutState(\"closedVotes\", closedVotes)\n\n\t// Return success\n\treturn shim.Success([]byte(\"true\"))\n}", "func (p Perceptron) init() {\n\trand.Seed(time.Now().UnixNano())\n\tfor k := range p {\n\t\tp[k] = rand.Float64() - float64(rand.Intn(1))\n\t}\n}", "func (m *PooledWrapper) Init(context.Context, ...wrapping.Option) error {\n\treturn nil\n}", "func Init(r *Rope) {\n\tr.Head = knot{\n\t\theight: 1,\n\t\tnexts: make([]skipknot, MaxHeight),\n\t}\n}", "func (p *HelloWorld) Init(reg *types.Register, pm types.ProcessManager, cn types.Provider) error {\n\tp.pm = pm\n\tp.cn = cn\n\tif vp, err := pm.ProcessByName(\"fleta.vault\"); err != nil {\n\t\treturn err\n\t} else if v, is := vp.(*vault.Vault); !is {\n\t\treturn types.ErrInvalidProcess\n\t} else {\n\t\tp.vault = v\n\t}\n\n\treg.RegisterTransaction(1, &Hello{})\n\n\treturn nil\n}", "func (plugin *Plugin) Init() error {\n\tplugin.Log.Debug(\"Initializing interface plugin\")\n\n\tplugin.fixNilPointers()\n\n\tplugin.ifStateNotifications = plugin.Deps.IfStatePub\n\tconfig, err := plugin.retrieveDPConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif config != nil {\n\t\tplugin.ifMtu = config.Mtu\n\t\tplugin.Log.Infof(\"Mtu read from config us set to %v\", plugin.ifMtu)\n\t\tplugin.enableStopwatch = config.Stopwatch\n\t\tif plugin.enableStopwatch {\n\t\t\tplugin.Log.Infof(\"stopwatch enabled for %v\", plugin.PluginName)\n\t\t} else {\n\t\t\tplugin.Log.Infof(\"stopwatch disabled for %v\", plugin.PluginName)\n\t\t}\n\t} else {\n\t\tplugin.ifMtu = defaultMtu\n\t\tplugin.Log.Infof(\"MTU set to default value %v\", plugin.ifMtu)\n\t\tplugin.Log.Infof(\"stopwatch disabled for %v\", plugin.PluginName)\n\t}\n\n\t// all channels that are used inside of publishIfStateEvents or watchEvents must be created in advance!\n\tplugin.ifStateChan = make(chan *intf.InterfaceStateNotification, 100)\n\tplugin.bdStateChan = make(chan *l2plugin.BridgeDomainStateNotification, 100)\n\tplugin.resyncConfigChan = make(chan datasync.ResyncEvent)\n\tplugin.resyncStatusChan = make(chan datasync.ResyncEvent)\n\tplugin.changeChan = make(chan datasync.ChangeEvent)\n\tplugin.ifIdxWatchCh = make(chan ifaceidx.SwIfIdxDto, 100)\n\tplugin.bdIdxWatchCh = make(chan bdidx.ChangeDto, 100)\n\tplugin.linuxIfIdxWatchCh = make(chan ifaceidx2.LinuxIfIndexDto, 100)\n\tplugin.errorChannel = make(chan ErrCtx, 100)\n\n\t// create plugin context, save cancel function into the plugin handle\n\tvar ctx context.Context\n\tctx, plugin.cancel = context.WithCancel(context.Background())\n\n\t//FIXME run following go routines later than following init*() calls - just before Watch()\n\n\t// run event handler go routines\n\tgo plugin.publishIfStateEvents(ctx)\n\tgo plugin.publishBdStateEvents(ctx)\n\tgo plugin.watchEvents(ctx)\n\n\t// run error handler\n\tgo plugin.changePropagateError()\n\n\terr = plugin.initIF(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = plugin.initACL(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = plugin.initL2(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = plugin.initL3(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = plugin.initErrorHandler()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = plugin.subscribeWatcher()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgPlugin = plugin\n\n\treturn nil\n}", "func (p *AbstractProvider) Init() error {\n\treturn nil\n}", "func (impl *Impl) Init(conf core.ImplConf, space core.Space) (core.Clust, error) {\n\tvar mcmcConf = conf.(Conf)\n\t_ = impl.buffer.Apply()\n\timpl.iter = 0\n\treturn impl.initializer(mcmcConf.InitK, impl.buffer.Data(), space, mcmcConf.RGen)\n}", "func (p *servicePlugin) Init(g *generator.Generator) {\n\tp.Generator = g\n}", "func (s *SCEP) Init(config Config) (err error) {\n\tswitch {\n\tcase s.Type == \"\":\n\t\treturn errors.New(\"provisioner type cannot be empty\")\n\tcase s.Name == \"\":\n\t\treturn errors.New(\"provisioner name cannot be empty\")\n\t}\n\n\t// Default to 2048 bits minimum public key length (for CSRs) if not set\n\tif s.MinimumPublicKeyLength == 0 {\n\t\ts.MinimumPublicKeyLength = 2048\n\t}\n\n\tif s.MinimumPublicKeyLength%8 != 0 {\n\t\treturn errors.Errorf(\"%d bits is not exactly divisible by 8\", s.MinimumPublicKeyLength)\n\t}\n\n\ts.encryptionAlgorithm = s.EncryptionAlgorithmIdentifier // TODO(hs): we might want to upgrade the default security to AES-CBC?\n\tif s.encryptionAlgorithm < 0 || s.encryptionAlgorithm > 4 {\n\t\treturn errors.New(\"only encryption algorithm identifiers from 0 to 4 are valid\")\n\t}\n\n\ts.challengeValidationController = newChallengeValidationController(\n\t\tconfig.WebhookClient,\n\t\ts.GetOptions().GetWebhooks(),\n\t)\n\n\t// TODO: add other, SCEP specific, options?\n\n\ts.ctl, err = NewController(s, s.Claims, config, s.Options)\n\treturn\n}", "func (p *ExamplePlugin) Init() error {\n\treturn nil\n}", "func (p *ExamplePlugin) Init() error {\n\treturn nil\n}", "func (h *facts) Init(output chan<- *plugin.SlackResponse, bot *plugin.Bot) {\n\th.sink = output\n\th.bot = bot\n\th.configuration = viper.New()\n\th.configuration.AddConfigPath(\"/etc/slackhal/\")\n\th.configuration.AddConfigPath(\"$HOME/.slackhal\")\n\th.configuration.AddConfigPath(\".\")\n\th.configuration.SetConfigName(\"plugin-facts\")\n\th.configuration.SetConfigType(\"yaml\")\n\terr := h.configuration.ReadInConfig()\n\tif err != nil {\n\t\tzap.L().Error(\"Not able to read configuration for facts plugin.\", zap.Error(err))\n\t\th.Disabled = true\n\t\treturn\n\t}\n\tdbPath := h.configuration.GetString(\"database.path\")\n\th.factDB = new(stormDB)\n\terr = h.factDB.Connect(dbPath)\n\tif err != nil {\n\t\tzap.L().Error(\"Error while opening the facts database!\", zap.Error(err))\n\t\th.Disabled = true\n\t\treturn\n\t}\n}", "func (p *PRPlugin) init() {\n\tp.Logger = log.NewFor(p.Name)\n\tp.Debug(\"plugin initialized\")\n}", "func init() {\n\tifStarted = false\n\t/* Public and Private Key need to be created upon Node initialization */\n\t/* Need to generate a Curve first with the elliptic library, then generate key based on that curve */\n\tsignature_p.GeneratePublicAndPrivateKey()\n}", "func (p *PipelineProvisioner) Init(opts ...grpc.DialOption) error {\n\treturn nil\n}", "func Init(c *conf.Config, s *service.Service) {\n\trelationSvc = s\n\tverify = v.New(c.Verify)\n\tanti = antispam.New(c.Antispam)\n\taddFollowingRate = rate.New(c.AddFollowingRate)\n\t// init inner router\n\tengine := bm.DefaultServer(c.BM)\n\tsetupInnerEngine(engine)\n\tif err := engine.Start(); err != nil {\n\t\tlog.Error(\"engine.Start() error(%v)\", err)\n\t\tpanic(err)\n\t}\n}", "func (egs *ExampleGenServer) Init(p *ergo.Process, args ...interface{}) (state interface{}) {\n\tfmt.Printf(\"Init: args %v \\n\", args)\n\tegs.process = p\n\tInitialState := &State{\n\t\tvalue: args[0].(int), // 100\n\t}\n\treturn InitialState\n}", "func (o *DynCoefs) Init(dat *inp.SolverData) {\n\n\t// hmin\n\to.hmin = dat.DtMin\n\n\t// HHT\n\to.HHT = dat.HHT\n\n\t// θ-method\n\to.θ = dat.Theta\n\tif o.θ < 1e-5 || o.θ > 1.0 {\n\t\tchk.Panic(\"θ-method requires 1e-5 <= θ <= 1.0 (θ = %v is incorrect)\", o.θ)\n\t}\n\n\t// HHT method\n\tif dat.HHT {\n\t\to.α = dat.HHTalp\n\t\tif o.α < -1.0/3.0 || o.α > 0.0 {\n\t\t\tchk.Panic(\"HHT method requires: -1/3 <= α <= 0 (α = %v is incorrect)\", o.α)\n\t\t}\n\t\to.θ1 = (1.0 - 2.0*o.α) / 2.0\n\t\to.θ2 = (1.0 - o.α) * (1.0 - o.α) / 2.0\n\n\t\t// Newmark's method\n\t} else {\n\t\to.θ1, o.θ2 = dat.Theta1, dat.Theta2\n\t\tif o.θ1 < 0.0001 || o.θ1 > 1.0 {\n\t\t\tchk.Panic(\"θ1 must be between 0.0001 and 1.0 (θ1 = %v is incorrect)\", o.θ1)\n\t\t}\n\t\tif o.θ2 < 0.0001 || o.θ2 > 1.0 {\n\t\t\tchk.Panic(\"θ2 must be between 0.0001 and 1.0 (θ2 = %v is incorrect)\", o.θ2)\n\t\t}\n\t}\n}", "func Init() {\n\t// default :\n\t// micro health go.micro.api.gin call this function.\n\tModules.Router.POST(\"/\", NoModules)\n\tModules.Router.GET(\"/\", NoModules)\n\n\t// Examples Begin:micro api --handler=http as proxy, default is rpc .\n\t// Base module router for rest full, Preferences is name of table or tables while Module equals database.\n\t// Call url:curl \"http://localhost:8004/Preferences/GetPreference?user=1\"\n\te := new( examples )\n\tclient.DefaultClient = client.NewClient( client.Registry(etcdv3.DefaultEtcdRegistry) )\n\te.cl = example.NewPreferencesService(conf.ApiConf.SrvName, client.DefaultClient)\n\tModules.Router.GET(\"/Preferences/*action\", e.Preferences)\n\t// Examples End\n\n\t// register other handlers here, each request run in goroutine.\n\t// To register others...\n\n\tlog.Info(\"Modules init finished.\")\n}", "func (c *HelloWorld) Init(ctx contract.Context, req *types.HelloRequest) error {\n\treturn nil\n}", "func Init(c *conf.Config) {\n\t// service\n\tinitService(c)\n\t// init grpc\n\tgrpcSvr = grpc.New(nil, arcSvc, newcomerSvc)\n\tengineOuter := bm.DefaultServer(c.BM.Outer)\n\t// init outer router\n\touterRouter(engineOuter)\n\tif err := engineOuter.Start(); err != nil {\n\t\tlog.Error(\"engineOuter.Start() error(%v) | config(%v)\", err, c)\n\t\tpanic(err)\n\t}\n}", "func (s *RPC) Init(c context.Context, id string, state rpc.State) error {\n\tstepID, err := strconv.ParseInt(id, 10, 64)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tworkflow, err := s.store.WorkflowLoad(stepID)\n\tif err != nil {\n\t\tlog.Error().Msgf(\"error: cannot find step with id %d: %s\", stepID, err)\n\t\treturn err\n\t}\n\n\tagent, err := s.getAgentFromContext(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\tworkflow.AgentID = agent.ID\n\n\tcurrentPipeline, err := s.store.GetPipeline(workflow.PipelineID)\n\tif err != nil {\n\t\tlog.Error().Msgf(\"error: cannot find pipeline with id %d: %s\", workflow.PipelineID, err)\n\t\treturn err\n\t}\n\n\trepo, err := s.store.GetRepo(currentPipeline.RepoID)\n\tif err != nil {\n\t\tlog.Error().Msgf(\"error: cannot find repo with id %d: %s\", currentPipeline.RepoID, err)\n\t\treturn err\n\t}\n\n\tif currentPipeline.Status == model.StatusPending {\n\t\tif currentPipeline, err = pipeline.UpdateToStatusRunning(s.store, *currentPipeline, state.Started); err != nil {\n\t\t\tlog.Error().Msgf(\"error: init: cannot update build_id %d state: %s\", currentPipeline.ID, err)\n\t\t}\n\t}\n\n\ts.updateForgeStatus(c, repo, currentPipeline, workflow)\n\n\tdefer func() {\n\t\tcurrentPipeline.Workflows, _ = s.store.WorkflowGetTree(currentPipeline)\n\t\tmessage := pubsub.Message{\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"repo\": repo.FullName,\n\t\t\t\t\"private\": strconv.FormatBool(repo.IsSCMPrivate),\n\t\t\t},\n\t\t}\n\t\tmessage.Data, _ = json.Marshal(model.Event{\n\t\t\tRepo: *repo,\n\t\t\tPipeline: *currentPipeline,\n\t\t})\n\t\tif err := s.pubsub.Publish(c, \"topic/events\", message); err != nil {\n\t\t\tlog.Error().Err(err).Msg(\"can not publish step list to\")\n\t\t}\n\t}()\n\n\tworkflow, err = pipeline.UpdateWorkflowToStatusStarted(s.store, *workflow, state)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.updateForgeStatus(c, repo, currentPipeline, workflow)\n\treturn nil\n}", "func (h *Handler) Init(c *config.Config) {\n\th.gatewayAddr = c.GatewaySvc\n\th.allowedLanguages = c.AllowedLanguages\n\tif len(h.allowedLanguages) == 0 {\n\t\th.allowedLanguages = []string{\"cs\", \"de\", \"en\", \"es\", \"fr\", \"it\", \"gl\"}\n\t}\n}", "func (sys *BucketMetadataSys) Init(ctx context.Context, buckets []BucketInfo, objAPI ObjectLayer) error {\n\tif objAPI == nil {\n\t\treturn errServerNotInitialized\n\t}\n\n\t// In gateway mode, we don't need to load the policies\n\t// from the backend.\n\tif globalIsGateway {\n\t\treturn nil\n\t}\n\n\t// Load PolicySys once during boot.\n\treturn sys.load(ctx, buckets, objAPI)\n}", "func (pr *PolicyReflector) Init(stopCh2 <-chan struct{}, wg *sync.WaitGroup) error {\n\tpr.stopCh = stopCh2\n\tpr.wg = wg\n\n\trestClient := pr.K8sClientset.ExtensionsV1beta1().RESTClient()\n\tlistWatch := pr.K8sListWatch.NewListWatchFromClient(restClient, \"networkpolicies\", \"\", fields.Everything())\n\tpr.k8sPolicyStore, pr.k8sPolicyController = pr.K8sListWatch.NewInformer(\n\t\tlistWatch,\n\t\t&core_v1beta1.NetworkPolicy{},\n\t\t0,\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: func(obj interface{}) {\n\t\t\t\tpolicy, ok := obj.(*core_v1beta1.NetworkPolicy)\n\t\t\t\tif !ok {\n\t\t\t\t\tpr.Log.Warn(\"Failed to cast newly created policy object\")\n\t\t\t\t} else {\n\t\t\t\t\tpr.addPolicy(policy)\n\t\t\t\t}\n\t\t\t},\n\t\t\tDeleteFunc: func(obj interface{}) {\n\t\t\t\tpolicy, ok := obj.(*core_v1beta1.NetworkPolicy)\n\t\t\t\tif !ok {\n\t\t\t\t\tpr.Log.Warn(\"Failed to cast removed policy object\")\n\t\t\t\t} else {\n\t\t\t\t\tpr.deletePolicy(policy)\n\t\t\t\t}\n\t\t\t},\n\t\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\t\tpolicyOld, ok1 := oldObj.(*core_v1beta1.NetworkPolicy)\n\t\t\t\tpolicyNew, ok2 := newObj.(*core_v1beta1.NetworkPolicy)\n\t\t\t\tif !ok1 || !ok2 {\n\t\t\t\t\tpr.Log.Warn(\"Failed to cast changed policy object\")\n\t\t\t\t} else {\n\t\t\t\t\tpr.updatePolicy(policyNew, policyOld)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t)\n\treturn nil\n}", "func Init(repo *config.RepoConfig, opr *operator.Operator) Cherry {\n\tc := cherry{\n\t\towner: repo.Owner,\n\t\trepo: repo.Repo,\n\t\tready: false,\n\t\trule: repo.Rule,\n\t\trelease: repo.Release,\n\t\ttypeLabel: repo.TypeLabel,\n\t\tignoreLabel: repo.IgnoreLabel,\n\t\tdryrun: repo.Dryrun,\n\t\tforkedRepoCollaborators: make(map[string]struct{}),\n\t\tcollaboratorInvitation: make(map[string]time.Time),\n\t\topr: opr,\n\t\tcfg: repo,\n\t}\n\tgo c.runLoadCollaborators()\n\treturn &c\n}", "func (hem *GW) Init(rootURL string, username string, password string) {\n\them.rootURL = rootURL\n\them.username = username\n\them.password = password\n\them.loadSmartMeterAttribute()\n}", "func (i *I2PGatePlugin) Init() error {\n /*i := Setup()\n if err != nil {\n\t\treturn nil, err\n\t}*/\n\treturn nil\n}", "func (mod *EthModule) Init() error {\n\tm := mod.eth\n\t// if didn't call NewEth\n\tif m.config == nil {\n\t\tm.config = DefaultConfig\n\t}\n\n\t//ethdoug.Adversary = mod.Config.Adversary\n\n\t// if no ethereum instance\n\tif m.ethereum == nil {\n\t\tm.ethConfig()\n\t\tm.newEthereum()\n\t}\n\n\t// public interface\n\tpipe := xeth.New(m.ethereum)\n\t// load keys from file. genesis block keys. convenient for testing\n\n\tm.pipe = pipe\n\tm.keyManager = m.ethereum.KeyManager()\n\t//m.reactor = m.ethereum.Reactor()\n\n\t// subscribe to the new block\n\tm.chans = make(map[string]chan types.Event)\n\t//m.reactchans = make(map[string]chan ethreact.Event)\n\tm.Subscribe(\"newBlock\", \"newBlock\", \"\")\n\n\tlog.Println(m.ethereum.Port)\n\n\treturn nil\n}", "func init() {\n\tingestion.Register(config.CONSTRUCTOR_NANO, newPerfProcessor)\n}", "func (s *SCEP) Init(config Config) (err error) {\n\tswitch {\n\tcase s.Type == \"\":\n\t\treturn errors.New(\"provisioner type cannot be empty\")\n\tcase s.Name == \"\":\n\t\treturn errors.New(\"provisioner name cannot be empty\")\n\t}\n\n\t// Mask the actual challenge value, so it won't be marshaled\n\ts.secretChallengePassword = s.ChallengePassword\n\ts.ChallengePassword = \"*** redacted ***\"\n\n\t// Default to 2048 bits minimum public key length (for CSRs) if not set\n\tif s.MinimumPublicKeyLength == 0 {\n\t\ts.MinimumPublicKeyLength = 2048\n\t}\n\n\tif s.MinimumPublicKeyLength%8 != 0 {\n\t\treturn errors.Errorf(\"%d bits is not exactly divisible by 8\", s.MinimumPublicKeyLength)\n\t}\n\n\ts.encryptionAlgorithm = s.EncryptionAlgorithmIdentifier // TODO(hs): we might want to upgrade the default security to AES-CBC?\n\tif s.encryptionAlgorithm < 0 || s.encryptionAlgorithm > 4 {\n\t\treturn errors.New(\"only encryption algorithm identifiers from 0 to 4 are valid\")\n\t}\n\n\t// TODO: add other, SCEP specific, options?\n\n\ts.ctl, err = NewController(s, s.Claims, config, s.Options)\n\treturn\n}", "func (a *amqpPubSub) Init(ctx context.Context, metadata pubsub.Metadata) error {\n\tamqpMeta, err := parseAMQPMetaData(metadata, a.logger)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ta.metadata = amqpMeta\n\n\ts, err := a.connect(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ta.session = s\n\n\treturn err\n}", "func (o *Cos) Init(prms Prms) (err error) {\n\tfor _, p := range prms {\n\t\tswitch p.N {\n\t\tcase \"a\":\n\t\t\to.a = p.V\n\t\tcase \"b\":\n\t\t\to.b = p.V\n\t\tcase \"c\":\n\t\t\to.c = p.V\n\t\tcase \"b/pi\": // b/π => b = b/pi * π\n\t\t\to.b = p.V * math.Pi\n\t\tdefault:\n\t\t\treturn chk.Err(\"cos: parameter named %q is invalid\", p.N)\n\t\t}\n\t}\n\treturn\n}", "func Init() {\n\t// default ..\n\t// micro health go.micro.api.gin call this function..\n\tModules.Router.POST(\"/\", NoModules)\n\tModules.Router.GET(\"/gin\", NoModules)\n\t// Modules.Router.GET(\"/gin\", NoModules)\n\t// Modules.Router.GET(\"/dbservice\", NoModules)\n\n\t// Examples Begin:micro api --handler=http as proxy, default is rpc .\n\t// Base module router for rest full, Preferences is name of table or tables while Module equals database.\n\t// Call url:curl \"http://localhost:8004/Preferences/GetPreference?user=1\"\n\te := new(examples)\n\t// Init Preferences Server Client\n\te.cl = go_micro_srv_dbservice.NewPreferencesService(conf2.AppConf.SrvName, client.DefaultClient)\n\tModules.Router.GET(\"/Preferences/*action\", e.Preferences)\n\t// Examples End\n\n\t// register other handlers here, each request run in goroutine.\n\n\t// To register others...\n\n\tfmt.Println(\"Modules init finished.\")\n}", "func (eng *Engine) Init(cfg string) error {\n\treturn nil\n}", "func (r *Ricochet) Init() {\n\tr.newconns = make(chan *OpenConnection)\n\tr.networkResolver = utils.NetworkResolver{}\n\tr.rni = new(utils.RicochetNetwork)\n}", "func (P *Parser) Init(g Grammar) {\n\tP.p = g.compile()\n}", "func (o *CallbackOperator) Init() {}", "func (m *Main) Init() error {\n\n\tlog.Printf(\"Loading GeoCode data ...\")\n\t//u.LoadGeoCodes()\n\n\tvar err error\n\tm.indexer, err = pdk.SetupPilosa(m.Hosts, m.IndexName, u.Frames, m.BufferSize)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error setting up Pilosa '%v'\", err)\n\t}\n\t//m.client = m.indexer.Client()\n\n\t// Initialize S3 client\n\tsess, err2 := session.NewSession(&aws.Config{\n\t\tRegion: aws.String(m.AWSRegion)},\n\t)\n\n\tif err2 != nil {\n\t\treturn fmt.Errorf(\"Creating S3 session: %v\", err2)\n\t}\n\n\t// Create S3 service client\n\tm.S3svc = s3.New(sess)\n\n\treturn nil\n}", "func (sp *ServiceProcessor) Init() error {\n\tsp.reset()\n\treturn nil\n}", "func Init() error {\n\tif config.GetGov() == nil {\n\t\treturn ErrNoConfig\n\t}\n\n\tfor name, opts := range config.GetGov().DistMap {\n\t\topts.Name = name\n\t\tf, ok := distributorPlugins[name]\n\t\tif !ok {\n\t\t\tlog.Warn(\"unsupported plugin \" + opts.Type)\n\t\t\tcontinue\n\t\t}\n\t\tcd, err := f(opts)\n\t\tif err != nil {\n\t\t\tlog.Error(\"can not init config distributor\", err)\n\t\t\treturn err\n\t\t}\n\t\tdistributors[name+\"::\"+opts.Type] = cd\n\t}\n\n\tif config.GetGov().MatchGroup != nil {\n\t\tRegisterPolicySchema(KindMatchGroup, config.GetGov().MatchGroup.ValidationSpec)\n\t}\n\n\tif config.GetGov().Policies != nil {\n\t\tvar names []string\n\t\tfor kind, policy := range config.GetGov().Policies {\n\t\t\tRegisterPolicySchema(kind, policy.ValidationSpec)\n\t\t\tnames = append(names, util.ToSnake(kind))\n\t\t}\n\t\tPolicyNames = names\n\t}\n\treturn nil\n}", "func (rc *Container) Init(p *Policy, logger klog.FormatLogger) error {\n\trc.Lock()\n\tdefer rc.Unlock()\n\trc.logger = logger\n\tif p == nil {\n\t\treturn nil\n\t}\n\tvar err error\n\trc.cliRetryer, err = NewRetryer(*p, rc.cbContainer, logger)\n\tif err != nil {\n\t\trc.msg = err.Error()\n\t\treturn fmt.Errorf(\"NewRetryer in Init failed, err=%w\", err)\n\t}\n\treturn nil\n}", "func (t *Procure2Pay) Init(stub shim.ChaincodeStubInterface) pb.Response {\n\t\n\t\tfmt.Println(\"Initiate the chaincde\")\n\t\treturn shim.Success(nil)\n\t\t\n}", "func (ps *PrjnStru) Init(prjn emer.Prjn) {\n\tps.LeabraPrj = prjn.(LeabraPrjn)\n}", "func Init() {\n\tEngine = gin.Default()\n}", "func (h *MessageHandler) Init(ctx context.Context) error {\n\tm := newMiddleware(h)\n\th.middleware = m\n\n\th.jetTreeUpdater = jet.NewFetcher(h.Nodes, h.JetStorage, h.Bus, h.JetCoordinator)\n\n\th.setHandlersForLight(m)\n\n\treturn nil\n}", "func (mp *Provider) Init(expiration time.Duration, cfg session.ProviderConfig) error {\n\tif cfg.Name() != ProviderName {\n\t\treturn errInvalidProviderConfig\n\t}\n\n\tmp.config = cfg.(*Config)\n\tmp.expiration = expiration\n\n\treturn nil\n}", "func (c *ClusterManager) Init(zl instances.ZoneLister, pp backends.ProbeProvider) {\n\tc.instancePool.Init(zl)\n\tc.backendPool.Init(pp)\n\t// TODO: Initialize other members as needed.\n}", "func (pp *PolicyProcessor) Init() error {\n\tpp.podIPAddressMap = make(map[podmodel.ID]net.IP)\n\tpp.Cache.Watch(pp)\n\treturn nil\n}", "func (p *Plugin) Init() error {\n\treturn p.IdempotentInit(plugintools.LoggingInitFunc(p.Log, p, p.init))\n}", "func Init() *node.Plugin {\n\tconfigure := func(*node.Plugin) {\n\t\tlog := logger.NewLogger(PluginName)\n\t\tdownloader.Init(log, parameters.GetString(parameters.IpfsGatewayAddress))\n\t}\n\trun := func(*node.Plugin) {\n\t\t// Nothing to run here\n\t}\n\n\tPlugin := node.NewPlugin(PluginName, node.Enabled, configure, run)\n\treturn Plugin\n}", "func (p *LinearPacer) initialize() {\n\tif p.Start.Freq == 0 {\n\t\tpanic(\"LinearPacer.Start cannot be 0\")\n\t}\n\n\tif p.Slope == 0 {\n\t\tpanic(\"LinearPacer.Slope cannot be 0\")\n\t}\n\n\tp.once.Do(func() {\n\t\tp.sp = StepPacer{\n\t\t\tStart: p.Start,\n\t\t\tStep: p.Slope,\n\t\t\tStepDuration: time.Second,\n\t\t\tStop: p.Stop,\n\t\t\tLoadDuration: p.LoadDuration,\n\t\t}\n\n\t\tp.sp.initialize()\n\t})\n}", "func (s *Hipchat) Init(c *config.Config) error {\n\turl := c.Handler.Hipchat.Url\n\troom := c.Handler.Hipchat.Room\n\ttoken := c.Handler.Hipchat.Token\n\n\tif token == \"\" {\n\t\ttoken = os.Getenv(\"KW_HIPCHAT_TOKEN\")\n\t}\n\n\tif room == \"\" {\n\t\troom = os.Getenv(\"KW_HIPCHAT_ROOM\")\n\t}\n\n\tif url == \"\" {\n\t\turl = os.Getenv(\"KW_HIPCHAT_URL\")\n\t}\n\n\ts.Token = token\n\ts.Room = room\n\ts.Url = url\n\n\treturn checkMissingHipchatVars(s)\n}", "func Init() {\n\tonce.Do(initialize)\n}", "func (p *provider) Init(ctx servicehub.Context) error {\n\tp.cache = make(map[uint64]aggregate)\n\tp.rulers = make([]*ruler, len(p.Cfg.Rules))\n\tfor idx, r := range p.Cfg.Rules {\n\t\trr, err := newRuler(r)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"newRuler err: %w\", err)\n\t\t}\n\t\tp.rulers[idx] = rr\n\t}\n\treturn nil\n}", "func (*plugin) Init(params plugins.InitParams) error {\n\treturn nil\n}", "func (chaincode *Chaincode) Init(stub shim.ChaincodeStubInterface) peer.Response {\n\tchaincode.BPI = NewBPI(\"https://api.coindesk.com/v1/bpi/currentprice.json\", 10*time.Second)\n\n\t// Get the args from the transaction proposal\n\targs := stub.GetStringArgs()\n\tif len(args) != 2 {\n\t\treturn shim.Error(\"Incorrect arguments. Expecting a key and a value\")\n\t}\n\n\tgo func() {\n\t\tvar server = http.NewServeMux()\n\t\tserver.HandleFunc(\"/bpi\", func(writer http.ResponseWriter, request *http.Request) {\n\t\t\tvar price, err = chaincode.GetPrice()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprint(writer, err.Error())\n\t\t\t\twriter.WriteHeader(http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfmt.Fprintf(writer, \"%v\", price.Bpi)\n\t\t})\n\t\thttp.ListenAndServe(\":8090\", server)\n\t}()\n\n\t// Set up any variables or assets here by calling stub.PutState()\n\n\t// We store the key and the value on the ledger\n\terr := stub.PutState(args[0], []byte(args[1]))\n\tif err != nil {\n\t\treturn shim.Error(fmt.Sprintf(\"Failed to create asset: %s\", args[0]))\n\t}\n\treturn shim.Success(nil)\n}", "func (c *Context) Init() {\n\tc.Logger = zerolog.New(zerolog.ConsoleWriter{Out: os.Stdout}).With().Timestamp().Logger()\n\tc.Logger = c.Logger.Hook(zerolog.HookFunc(c.getMemoryUsage))\n\n\tc.inShutdownMutex.Lock()\n\tc.inShutdown = false\n\tc.inShutdownMutex.Unlock()\n\n\tc.RandomSource = rand.New(rand.NewSource(time.Now().Unix()))\n\n\tc.Logger.Info().Msgf(\"LBTDS v. %s is starting...\", VERSION)\n}", "func (sys *BucketMetadataSys) Init(ctx context.Context, buckets []BucketInfo, objAPI ObjectLayer) error {\n\tif objAPI == nil {\n\t\treturn errServerNotInitialized\n\t}\n\n\t// In gateway mode, we don't need to load the policies\n\t// from the backend.\n\tif globalIsGateway {\n\t\treturn nil\n\t}\n\n\t// Load bucket metadata sys in background\n\tgo sys.load(ctx, buckets, objAPI)\n\treturn nil\n}", "func init() {\n\tp, err := New()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tproviders.Register(p)\n}", "func (s *GCPCKMSSeal) Init(_ context.Context) error {\n\treturn nil\n}", "func Init() {}", "func Init() {}", "func (br *BGPReflector) Init() (err error) {\n\treturn nil\n}", "func (s *ParticlePhysicsSystem) New(world *ecs.World) {\n\ts.simulationAcc = 0\n\ts.simulationStep = 1.0 / float32(s.SimulationRate)\n}", "func (s *Session) Init() {\n\ts.setEthereumRPCPath()\n\ts.setPayloadRPCPath()\n}", "func (t *Ticker) Init() {\n\tt.ticker = time.NewTicker(t.UpdateInterval)\n}", "func Init() {\n\tC.yices_init()\n}", "func (s *ISideChain) Init(size int) {\n\n\tsidechain := IblockChain{}\n\tReadIot()\n\tsidechain.Init()\n\tsidechain.GenerateBlocks(size - 1)\n\ts.Chain = sidechain\n\t//s.chain.PrintBlockChain()\n}", "func (h *Handler) Init(dbManager database.Manager, cacheManager cache.Manager, mqManager messagingqueue.Manager) {\n\th.dbManager = dbManager\n\th.cacheManager = cacheManager\n\th.mqManager = mqManager\n}", "func (plugin *RouteConfigurator) Init() (err error) {\n\n\tlog.Debug(\"Initializing L3 plugin\")\n\n\t// Init VPP API channel\n\tplugin.vppChan, err = plugin.GoVppmux.NewAPIChannel()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = plugin.checkMsgCompatibility()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (r *Egress) Init(op egress.Options) error {\n\t// the manager use dests to init, so must init after dests\n\tif err := initEgressManager(); err != nil {\n\t\treturn err\n\t}\n\treturn refresh()\n}", "func (d *SQLike) Init(tk *destination.Toolkit) error {\n\twh, err := d.AsWarehouse()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.wh = wh\n\treturn nil\n}", "func (p *provider) Init(ctx servicehub.Context) error {\n\tp.Router.POST(p.Cfg.RemoteWriteUrl, p.prwHandler)\n\treturn nil\n}", "func Init() error {\n\n}", "func Init(config Config) pdfium.Pool {\n\t// Create an hclog.Logger\n\tlogger := hclog.New(&hclog.LoggerOptions{\n\t\tName: \"plugin\",\n\t\tOutput: os.Stdout,\n\t\tLevel: hclog.Debug,\n\t})\n\n\tvar handshakeConfig = plugin.HandshakeConfig{\n\t\tProtocolVersion: 1,\n\t\tMagicCookieKey: \"BASIC_PLUGIN\",\n\t\tMagicCookieValue: \"hello\",\n\t}\n\n\t// pluginMap is the map of plugins we can dispense.\n\tvar pluginMap = map[string]plugin.Plugin{\n\t\t\"pdfium\": &commons.PdfiumPlugin{},\n\t}\n\n\t// If we don't have a log callback, make the callback no-op.\n\tif config.LogCallback == nil {\n\t\tconfig.LogCallback = func(s string) {}\n\t}\n\n\tfactory := pool.NewPooledObjectFactory(\n\t\tfunc(goctx.Context) (interface{}, error) {\n\t\t\tnewWorker := &worker{}\n\n\t\t\tclient := plugin.NewClient(&plugin.ClientConfig{\n\t\t\t\tHandshakeConfig: handshakeConfig,\n\t\t\t\tPlugins: pluginMap,\n\t\t\t\tCmd: exec.Command(config.Command.BinPath, config.Command.Args...),\n\t\t\t\tLogger: logger,\n\t\t\t\tStartTimeout: config.Command.StartTimeout,\n\t\t\t})\n\n\t\t\trpcClient, err := client.Client()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\traw, err := rpcClient.Dispense(\"pdfium\")\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tpdfium := raw.(commons.Pdfium)\n\n\t\t\tpong, err := pdfium.Ping()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif pong != \"Pong\" {\n\t\t\t\treturn nil, errors.New(\"Wrong ping/pong result\")\n\t\t\t}\n\n\t\t\tnewWorker.pluginClient = client\n\t\t\tnewWorker.rpcClient = rpcClient\n\t\t\tnewWorker.plugin = pdfium\n\n\t\t\treturn newWorker, nil\n\t\t}, nil, func(ctx goctx.Context, object *pool.PooledObject) bool {\n\t\t\tworker := object.Object.(*worker)\n\t\t\tif worker.pluginClient.Exited() {\n\t\t\t\tconfig.LogCallback(\"Worker exited\")\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\terr := worker.rpcClient.Ping()\n\t\t\tif err != nil {\n\t\t\t\tconfig.LogCallback(fmt.Sprintf(\"Error on RPC ping: %s\", err.Error()))\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tpong, err := worker.plugin.Ping()\n\t\t\tif err != nil {\n\t\t\t\tconfig.LogCallback(fmt.Sprintf(\"Error on plugin ping:: %s\", err.Error()))\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tif pong != \"Pong\" {\n\t\t\t\terr = errors.New(\"Wrong ping/pong result\")\n\t\t\t\tconfig.LogCallback(fmt.Sprintf(\"Error on plugin ping:: %s\", err.Error()))\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\treturn true\n\t\t}, nil, nil)\n\tp := pool.NewObjectPoolWithDefaultConfig(goctx.Background(), factory)\n\tp.Config = &pool.ObjectPoolConfig{\n\t\tBlockWhenExhausted: true,\n\t\tMinIdle: config.MinIdle,\n\t\tMaxIdle: config.MaxIdle,\n\t\tMaxTotal: config.MaxTotal,\n\t\tTestOnBorrow: true,\n\t\tTestOnReturn: true,\n\t\tTestOnCreate: true,\n\t}\n\n\tp.PreparePool(goctx.Background())\n\n\tmultiThreadedMutex.Lock()\n\tdefer multiThreadedMutex.Unlock()\n\n\tpoolRef := uuid.New()\n\n\t// Create a new PDFium pool.\n\tnewPool := &pdfiumPool{\n\t\tpoolRef: poolRef.String(),\n\t\tinstanceRefs: map[string]*pdfiumInstance{},\n\t\tlock: &sync.Mutex{},\n\t\tworkerPool: p,\n\t}\n\n\tpoolRefs[newPool.poolRef] = newPool\n\n\treturn newPool\n}", "func (c *GrpcClient) Init() error {\n\tconn, err := grpc.Dial(c.serverURL, grpc.WithInsecure(), grpc.WithBlock())\n\tif err != nil {\n\t\tlog.Fatalf(\"did not connect %v\", err)\n\t\treturn err\n\t} else {\n\t\tlog.Printf(\"connnect to grpc server at %s\", c.serverURL)\n\t}\n\tc.client = protos.NewClaculatorClient(conn)\n\treturn nil\n}", "func (s *Flattener) Init(conf map[string]string) error {\n\treturn nil\n}", "func (g *Gorc) Init() {\n\tg.Lock()\n\tg.count = 0\n\tg.waitMillis = 100 * time.Millisecond\n\tg.Unlock()\n}", "func (e *Engine) init() {\n\n\te.mutex.Lock()\n\tdefer e.mutex.Unlock()\n\n\tif e.ctx == nil || e.cancel == nil {\n\t\te.ctx, e.cancel = context.WithCancel(e.parent)\n\t}\n\n\tif e.timeout == 0 {\n\t\te.timeout = DefaultTimeout\n\t}\n\n\tif len(e.signals) == 0 && !e.noSignal {\n\t\te.signals = Signals\n\t}\n\n\tif e.interrupt == nil {\n\t\te.interrupt = make(chan os.Signal, 1)\n\t}\n\n}", "func (plugin *Plugin) Init() error {\n\tplugin.Log.Debug(\"Initializing Linux plugin\")\n\n\tconfig, err := plugin.retrieveLinuxConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif config != nil {\n\t\tif config.Disabled {\n\t\t\tplugin.disabled = true\n\t\t\tplugin.Log.Infof(\"Disabling Linux plugin\")\n\t\t\treturn nil\n\t\t}\n\t} else {\n\t\tplugin.Log.Infof(\"stopwatch disabled for %v\", plugin.PluginName)\n\t}\n\n\tplugin.resyncChan = make(chan datasync.ResyncEvent)\n\tplugin.changeChan = make(chan datasync.ChangeEvent)\n\tplugin.msChan = make(chan *nsplugin.MicroserviceCtx)\n\tplugin.ifMicroserviceNotif = make(chan *nsplugin.MicroserviceEvent, 100)\n\tplugin.ifIndexesWatchChan = make(chan ifaceidx.LinuxIfIndexDto, 100)\n\tplugin.vppIfIndexesWatchChan = make(chan ifaceVPP.SwIfIdxDto, 100)\n\n\t// Create plugin context and save cancel function into the plugin handle.\n\tvar ctx context.Context\n\tctx, plugin.cancel = context.WithCancel(context.Background())\n\n\t// Run event handler go routines\n\tgo plugin.watchEvents(ctx)\n\n\terr = plugin.initNs()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = plugin.initIF(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = plugin.initL3()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn plugin.subscribeWatcher()\n}", "func (g *gcp) Init() error {\n\treturn nil\n}", "func init() {\n\t// Initialization goes here\n}", "func Init(c *conf.Config, s *service.Service) {\n\tpushSrv = s\n\tauthSrv = permit.New(c.Auth)\n\tengine := bm.DefaultServer(c.HTTPServer)\n\troute(engine)\n\tif err := engine.Start(); err != nil {\n\t\tlog.Error(\"engine.Start error(%v)\", err)\n\t\tpanic(err)\n\t}\n}", "func Init(\n\tctx context.Context,\n\tobservationCtx *observation.Context,\n\tdb database.DB,\n\t_ codeintel.Services,\n\t_ conftypes.UnifiedWatchable,\n\tenterpriseServices *enterprise.Services,\n) error {\n\tenterpriseServices.OwnResolver = resolvers.New()\n\n\treturn nil\n}", "func init() {\n\t// init func\n}", "func (plugin *Skeleton) Init() (err error) {\n\treturn nil\n}" ]
[ "0.7276373", "0.6355817", "0.5999975", "0.5858239", "0.583943", "0.57498544", "0.57212317", "0.57122844", "0.56993496", "0.5698908", "0.5674601", "0.56481105", "0.5638302", "0.5636005", "0.5599019", "0.5598491", "0.5584853", "0.5519274", "0.55019903", "0.54974216", "0.54847467", "0.5484442", "0.548238", "0.548238", "0.5451518", "0.54474026", "0.54464614", "0.544631", "0.54456574", "0.54369783", "0.5410176", "0.5402824", "0.5389987", "0.5369428", "0.53654253", "0.536097", "0.53561836", "0.5347438", "0.53473663", "0.53368515", "0.53192866", "0.53169656", "0.53046536", "0.5301924", "0.5297874", "0.52899766", "0.52895975", "0.52888054", "0.5286442", "0.5283553", "0.52792144", "0.5278375", "0.5276127", "0.52708966", "0.52679837", "0.52648425", "0.5243127", "0.5241235", "0.523427", "0.52324265", "0.5228326", "0.52279603", "0.5227754", "0.5216069", "0.5212691", "0.5209483", "0.5205995", "0.52049327", "0.52048737", "0.519927", "0.519687", "0.51904494", "0.5184795", "0.5174661", "0.51740307", "0.51740307", "0.5156978", "0.5146259", "0.5145458", "0.51414716", "0.51397836", "0.513945", "0.51388544", "0.51386976", "0.5137541", "0.51360005", "0.5135782", "0.5133846", "0.5126131", "0.5124879", "0.5119476", "0.5117507", "0.5116377", "0.5113653", "0.5104129", "0.51031387", "0.5099817", "0.5096854", "0.5089811", "0.50776714" ]
0.7609891
0
Name returns the name of the philosopher.
func (phi *Philosopher) Name() string { return phi.name }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (h *Salute) Name() string {\n\treturn \"Salute\"\n}", "func (Phosphorus) GetName() string {\n\treturn \"Phosphorus\"\n}", "func (c Chaos) Name() string { return \"chaos\" }", "func (o *OVH) GetName() string {\n\treturn \"OVH\"\n}", "func (g *Guessit) Name() string {\n\treturn moduleName\n}", "func (p ByName) Name() string { return p.name }", "func (n *piName) Name() string {\n\treturn n.name\n}", "func (server *Server) Name() string {\n\treturn \"Gophermine\"\n}", "func (h *CookiejarHandler) FamilyName() string {\n\treturn familyName\n}", "func (o *Ga4ghChemotherapy) GetName() string {\n\tif o == nil || o.Name == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Name\n}", "func (h *TokenizerPathHierarchy) Name() string {\n\treturn h.name\n}", "func (p *Peer) Name() string {\n\treturn p.name\n}", "func (p *Peer) Name() string {\n\treturn p.name\n}", "func (p *Peer) Name() string {\n\treturn p.name\n}", "func (Krypton) GetName() string {\n\treturn \"Krypton\"\n}", "func (p *Plugin) Name() string {\n\treturn \"golang\"\n}", "func (ipecho) Name() string { return \"IPEcho\" }", "func (s Mocha) Name() string {\n\treturn mochaName\n}", "func (b *Bot) Name() string {\n\treturn b.name\n}", "func (Lawrencium) GetName() string {\n\treturn \"Lawrencium\"\n}", "func (d *HetznerCloudProvider) Name() string {\n\treturn cloudprovider.HetznerProviderName\n}", "func (_Weth *WethSession) Name() (string, error) {\n\treturn _Weth.Contract.Name(&_Weth.CallOpts)\n}", "func (p *Protocol) Name() string {\n\treturn protocolID\n}", "func (p *Protocol) Name() string {\n\treturn protocolID\n}", "func (p *Protocol) Name() string {\n\treturn protocolID\n}", "func (p *HelloWorld) Name() string {\n\treturn \"demo.HelloWorld\"\n}", "func (pn *PitchNamer) Name(pitch PitchClass) string {\n\treturn pn.lookup[pitch.value]\n}", "func (_Weth *WethCallerSession) Name() (string, error) {\n\treturn _Weth.Contract.Name(&_Weth.CallOpts)\n}", "func (g Gossiper) Name() string {\n\treturn g.name\n}", "func (h *HTTP) Name() string {\n\treturn ModuleName()\n}", "func (t *LogProviderHandler) Name() string {\n\treturn LogProvider\n}", "func (g GitHub) Name() string {\n\tif g.local != \"\" {\n\t\treturn g.local\n\t}\n\treturn g.binary\n}", "func (p *GogoPlugin) Name() string {\n\treturn \"gogo:protobuf:protoc-gen-\" + p.variant\n}", "func (p *ProtocGenGoPlugin) Name() string {\n\treturn ProtocGenGoPluginName\n}", "func (p *Player) Name() string {\n\treturn p.name\n}", "func (p *Player) Name() string {\n\treturn p.name\n}", "func (p *Player) Name() string {\n\treturn p.name\n}", "func (p *Player) Name() string {\n\treturn p.name\n}", "func (p *Player) Name() (s string) {\n\tif p != nil && p.User() != nil {\n\t\ts = p.User().Name\n\t}\n\treturn\n}", "func (p *servicePlugin) Name() string { return \"protorpc\" }", "func (s *SimilarityLMJelinekMercer) Name() string {\n\treturn s.name\n}", "func (p *procBase) Name() string {\n\treturn p.name\n}", "func (p *HostClonePhase) Name() string {\n\treturn HostClonePhaseName\n}", "func (c Provider) Name() string {\n\treturn \"GitHub\"\n}", "func (ps *GetProcedureState) Name() string {\n\treturn \"getProcedureResult\"\n}", "func (p *GenericPlugin) Name() string {\n\n\tswitch p.state {\n\tcase stateNotLoaded:\n\t\treturn path.Base(p.filename)\n\tdefault:\n\t}\n\n\treturn p.name()\n}", "func (p *Provider) Name() string {\n\treturn p.name\n}", "func (cmd *CLI) Name() string {\n\tvar name string\n\tif cmd.parent != nil {\n\t\tname = strings.Join([]string{cmd.parent.Name(), cmd.name}, \" \")\n\t} else {\n\t\tname = cmd.name\n\t}\n\treturn name\n}", "func (snowflake) GetName() string {\n\treturn \"snowflake\"\n}", "func (e *Huobi) GetName() string {\n\treturn e.option.Name\n}", "func (eng *Engine) Name() string {\n\treturn \"JS-Plugin-Engine\"\n}", "func (r *Roster) Name() string { return ModuleName }", "func (g *Gear) Name() string {\n\treturn g.name\n}", "func (n *Node) Name() string {\n\treturn \"committee node\"\n}", "func (n *Node) Name() string {\n\treturn \"committee node\"\n}", "func (o LienOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Lien) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (e *Domain) Name() string {\n\treturn e.name\n}", "func GetName() string {\n\treturn \"etcd\"\n}", "func (p *Plugin) Name() string {\n\treturn p.PluginObj.Name\n}", "func (b Branch) Name() string {\n\treturn polName\n}", "func (p *processor) Name() string {\n\treturn p.name\n}", "func (p *pathInfo) Name() string {\n\treturn p.path\n}", "func (b *Being) GetName() string {\n\treturn b.Name.Display\n}", "func (g *TokenFilterSynonymGraph) Name() string {\n\treturn g.name\n}", "func (d Distribution) Name() string {\n\treturn strings.Replace(d.ID, \"-\", \"::\", -1)\n}", "func (p *Wheel) Name() string {\n\treturn p.name\n}", "func (m *Meow) Name() string { return \"cow\" }", "func (o Outside) Name() string {\n\treturn polName\n}", "func (p *Platform) Name() string {\n\treturn p.name\n}", "func (k *Kind) Name() string {\n\treturn \"team\"\n}", "func (factory *SevenBeeFactory) Name() string {\n\treturn \"seven\"\n}", "func (fs *githubFs) Name() string {\n\treturn \"github\"\n}", "func (p *Peer) Name() string {\n\treturn p.m.LocalNode().Name\n}", "func (h Dnstap) Name() string { return \"dnstap\" }", "func (ilp *IlpFormatter) Name() string {\n\treturn ilp.name\n}", "func (o WebhookOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Webhook) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (s *Plugin) Name() string {\n\treturn PluginName\n}", "func (Sodium) GetName() string {\n\treturn \"Sodium\"\n}", "func (o LoggerEventhubOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LoggerEventhub) string { return v.Name }).(pulumi.StringOutput)\n}", "func (j *DSGitHub) Name() string {\n\treturn j.DS\n}", "func (c *Ping) Name() string {\n\treturn \"PING\"\n}", "func (r *Portfolio) Name() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"name\"])\n}", "func (e ENS) Name() string { return \"ens\" }", "func (sh SubdirectoryHeader) Name() string {\n\treturn string(sh.SubdirectoryName[0 : sh.TypeAndNameLength&0xf])\n}", "func (p Plugin) GetName() string {\n\treturn Name\n}", "func (s *session) Name() string {\n\treturn s.name\n}", "func (t *tectonic) Name() string {\n\treturn \"Tectonic Manifests\"\n}", "func (Plugin) Name() string { return pluginName }", "func (p *Provider) GetName() string {\n\treturn p.Name\n}", "func (w *SpamModule) Name() string {\n\treturn \"Spam\"\n}", "func (r *RandBorn) Name() string {\n\treturn \"RandBorn\"\n}", "func (p *Plugin) GetName() string {\n\treturn p.Name\n}", "func (s *Speacies) GetName() string {\n\treturn s.Name\n}", "func (g *Gpg) Name() string {\n\treturn gpgLabel\n}", "func (module *Crawler) Name() string {\n\treturn Name\n}", "func (m *Monster) Name() string { return NameFromID(m.id) }", "func (*gaeModule) Name() module.Name {\n\treturn ModuleName\n}", "func (z *Zombie) GetName() string {\n\treturn z.name\n}", "func GetName() string {\n\treturn newX2ethereum().GetName()\n}", "func (p Prometheus) Name() string {\n\treturn \"Prometheus probe for \" + p.URL + \" [\" + p.Key + \"]\"\n}" ]
[ "0.64045525", "0.6307802", "0.5870844", "0.581691", "0.5806899", "0.57955635", "0.57790506", "0.57770675", "0.5758934", "0.5722854", "0.5718736", "0.57177335", "0.57177335", "0.57177335", "0.5709185", "0.5692677", "0.5664142", "0.5660303", "0.5648683", "0.5646586", "0.5639321", "0.5634269", "0.5607001", "0.5607001", "0.5607001", "0.5599219", "0.55982804", "0.558955", "0.5559862", "0.5552062", "0.55161846", "0.5496706", "0.5490035", "0.5483652", "0.5476596", "0.5476596", "0.5476596", "0.5476596", "0.5475721", "0.546773", "0.54667246", "0.54551977", "0.5454737", "0.54489774", "0.5445777", "0.5443619", "0.54414725", "0.54401314", "0.54391825", "0.5433571", "0.5431421", "0.5428936", "0.54239047", "0.5409634", "0.5409634", "0.54069746", "0.5402735", "0.5402048", "0.5401315", "0.54008245", "0.5399043", "0.5393904", "0.5390634", "0.538828", "0.5387469", "0.5384638", "0.53724086", "0.5371577", "0.5371422", "0.53711224", "0.5361188", "0.5360395", "0.5359409", "0.53528243", "0.53515893", "0.5351138", "0.53505796", "0.5345314", "0.53429794", "0.5341323", "0.5340096", "0.53393066", "0.53358245", "0.5335523", "0.53342897", "0.53341615", "0.53323805", "0.5332256", "0.53310835", "0.533074", "0.53213376", "0.5317448", "0.5314699", "0.53124785", "0.5310217", "0.53086966", "0.53045547", "0.53006333", "0.5298513", "0.52953196" ]
0.8613802
0
RespChannel returns the philosopher's dedicated response channel.
func (phi *Philosopher) RespChannel() chan string { return phi.respChannel }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pd *philosopherData) RespChannel() chan string {\n\treturn pd.respChannel\n}", "func (c *WSClient) GetResponseChannel() chan *model.WebSocketResponse {\n\treturn c.ResponseChannel\n}", "func (pp *PushPromise) Response() *ClientResponse {\n\treturn <-pp.responseChannel\n}", "func (m *mockedChannel) GetReplyChannel() <-chan *govppapi.VppReply {\n\treturn m.channel.GetReplyChannel()\n}", "func (k *Kafka) ResponseChan() <-chan types.Response {\n\treturn k.responseChan\n}", "func (p *Player) Channel() *api.Channel {\n\tretCh := make(chan *api.Channel)\n\tp.chGetChannel <- retCh\n\tc := <-retCh\n\treturn c\n}", "func (z *ZMQ4) ResponseChan() <-chan types.Response {\n\treturn z.responseChan\n}", "func (cmd *Command) Response() chan *Response {\n\treturn cmd.response\n}", "func decodeGRPCEchoResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.EchoReply)\n\treturn endpoints.EchoResponse{Rs: reply.Rs}, nil\n}", "func (p *HostedProgramInfo) Channel() io.ReadWriteCloser {\n\treturn p.TaoChannel\n}", "func (m *MetricsExtracor) Channel() chan<- interface{} {\n\treturn m.channel\n}", "func (res channelBase) Channel() *types.Channel {\n\treturn res.channel\n}", "func (bft *ProtocolBFTCoSi) readResponseChan(c chan responseChan, t RoundType) error {\n\ttimeout := time.After(bft.Timeout)\n\tfor {\n\t\tif bft.isClosing() {\n\t\t\treturn errors.New(\"Closing\")\n\t\t}\n\n\t\tselect {\n\t\tcase msg, ok := <-c:\n\t\t\tif !ok {\n\t\t\t\tlog.Lvl3(\"Channel closed\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tfrom := msg.ServerIdentity.Public\n\t\t\tr := msg.Response\n\n\t\t\tswitch msg.Response.TYPE {\n\t\t\tcase RoundPrepare:\n\t\t\t\tbft.tempPrepareResponse = append(bft.tempPrepareResponse, r.Response)\n\t\t\t\tbft.tempExceptions = append(bft.tempExceptions, r.Exceptions...)\n\t\t\t\tbft.tempPrepareResponsePublics = append(bft.tempPrepareResponsePublics, from)\n\t\t\t\t// There is no need to have more responses than we have\n\t\t\t\t// commits. We _should_ check here if we get the same\n\t\t\t\t// responses from the same nodes. But as this is deprecated\n\t\t\t\t// and replaced by ByzCoinX, we'll leave it like that.\n\t\t\t\tif t == RoundPrepare && len(bft.tempPrepareResponse) == len(bft.tempPrepareCommit) {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase RoundCommit:\n\t\t\t\tbft.tempCommitResponse = append(bft.tempCommitResponse, r.Response)\n\t\t\t\t// Same reasoning as in RoundPrepare.\n\t\t\t\tif t == RoundCommit && len(bft.tempCommitResponse) == len(bft.tempCommitCommit) {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-timeout:\n\t\t\tlog.Lvl1(\"timeout while trying to read response messages\")\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (c *WSClient) SetResponseChannel(rc chan *model.WebSocketResponse) {\n\tc.ResponseChannel = rc\n}", "func (closer *Closer) CloseChannel() chan struct{} {\n\treturn closer.channel\n}", "func (c *Client) Channel(ctx context.Context, r ChannelRequest) (*ChannelReply, error) {\r\n\treq, err := http.NewRequestWithContext(\r\n\t\tctx,\r\n\t\thttp.MethodGet,\r\n\t\tfmt.Sprintf(\"%s/%s/channel/%s\", c.getChanelBaseEndpoint(), r.AccountID, r.ChannelID),\r\n\t\tnil,\r\n\t)\r\n\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\tres := ChannelReply{}\r\n\tif err := c.sendRequest(req, &res); err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\treturn &res, nil\r\n}", "func (ch *clientSecureChannel) responseWorker() {\n\tfor {\n\t\tres, err := ch.readResponse()\n\t\tif err != nil {\n\t\t\tif ch.reconnecting {\n\t\t\t\ttime.Sleep(1000 * time.Millisecond)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif ch.errCode == ua.Good {\n\t\t\t\tif ec, ok := err.(ua.StatusCode); ok {\n\t\t\t\t\tch.errCode = ec\n\t\t\t\t}\n\t\t\t}\n\t\t\tclose(ch.cancellation)\n\t\t\treturn\n\t\t}\n\t\tch.handleResponse(res)\n\t}\n}", "func (e *EventNotif) Channel() (res <-chan Event) {\n\treturn e.eventsCh\n}", "func NewCloseSecureChannelResponse(resHeader *ResponseHeader) *CloseSecureChannelResponse {\n\treturn &CloseSecureChannelResponse{\n\t\tResponseHeader: resHeader,\n\t}\n}", "func (tv *TV) setupResponseChannel(id string) chan Message {\n\ttv.resMutex.Lock()\n\tdefer tv.resMutex.Unlock()\n\n\tif tv.res == nil {\n\t\ttv.res = make(map[string]chan<- Message)\n\t}\n\n\tch := make(chan Message, 1)\n\ttv.res[id] = ch\n\treturn ch\n}", "func encodeGRPCEchoResponse(_ context.Context, grpcReply interface{}) (res interface{}, err error) {\n\n\treply := grpcReply.(endpoints.EchoResponse)\n\treturn &pb.EchoReply{Rs: reply.Rs}, def.GrpcEncodeError(reply.Err)\n}", "func newPhilosopherDataPtr(respChannel chan string) *philosopherData {\n\tpd := new(philosopherData)\n\tpd.Init(respChannel)\n\treturn pd\n}", "func (p *pipeline) Channel() Channel {\n\treturn p.channel\n}", "func (f future) Response() <-chan network.Response {\n\tin := transport.Future(f).Result()\n\tout := make(chan network.Response, cap(in))\n\tgo func(in <-chan *packet.Packet, out chan<- network.Response) {\n\t\tfor packet := range in {\n\t\t\tout <- (*packetWrapper)(packet)\n\t\t}\n\t\tclose(out)\n\t}(in, out)\n\treturn out\n}", "func (*ListGuildChannelsResponse) Descriptor() ([]byte, []int) {\n\treturn file_discord_v1_cache_proto_rawDescGZIP(), []int{3}\n}", "func (rc *responseController) CalculateChannelResponse(ill models.IlluminationCode, startWave, stopWave, step int, normPatchNumber int) (bool, []models.ChannelResponse) {\n\tstatus := false\n\tresponses := make([]models.ChannelResponse, 0)\n\n\tvar illSpectrum map[int]float64\n\tswitch ill {\n\tcase models.D65:\n\t\tillSpectrum = rc.d65Map\n\tcase models.IllA:\n\t\tillSpectrum = rc.illAMap\n\tdefault:\n\t\tbreak\n\t}\n\n\t// calculate each color chart response\n\tfor i := 0; i < 24; i++ {\n\t\t// device channel response stocker\n\t\tgrCh := 0.0\n\t\tgbCh := 0.0\n\t\trCh := 0.0\n\t\tbCh := 0.0\n\n\t\t// scan wave length\n\t\tfor wavelength := startWave; wavelength <= stopWave; wavelength += step {\n\t\t\tgr, gb, r, b := rc.calculateEachChannelResponse(\n\t\t\t\tillSpectrum,\n\t\t\t\trc.deviceQEGrMap,\n\t\t\t\trc.deviceQEGbMap,\n\t\t\t\trc.deviceQERedMap,\n\t\t\t\trc.deviceQEBlueMap,\n\t\t\t\trc.colorCheckerMap[i],\n\t\t\t\twavelength,\n\t\t\t)\n\n\t\t\t// accumulate response\n\t\t\tgrCh += gr\n\t\t\tgbCh += gb\n\t\t\trCh += r\n\t\t\tbCh += b\n\t\t}\n\n\t\t// make channel response object\n\t\tres := &models.ChannelResponse{\n\t\t\tCheckerNumber: i + 1,\n\t\t\tGr: grCh,\n\t\t\tGb: gbCh,\n\t\t\tR: rCh,\n\t\t\tB: bCh,\n\t\t}\n\n\t\t// stock the chennel response data to stocker\n\t\trc.responses = append(rc.responses, *res)\n\n\t\t// update status\n\t\tstatus = true\n\t}\n\n\t// normarize channel response by ref patch signal\n\tif status {\n\t\trefPatch := rc.responses[normPatchNumber-1]\n\t\trefPatchGrGb := (refPatch.Gr + refPatch.Gb) / 2.0\n\n\t\tfor _, data := range rc.responses {\n\t\t\tresponse := &models.ChannelResponse{\n\t\t\t\tCheckerNumber: data.CheckerNumber,\n\t\t\t\tGr: data.Gr / refPatchGrGb,\n\t\t\t\tGb: data.Gb / refPatchGrGb,\n\t\t\t\tR: data.R / refPatchGrGb,\n\t\t\t\tB: data.B / refPatchGrGb,\n\t\t\t}\n\t\t\t// stacking\n\t\t\tresponses = append(responses, *response)\n\t\t}\n\t}\n\n\treturn status, responses\n}", "func (m *MockCallResult) Channel() <-chan *Result {\n\targs := m.MethodCalled(\"Channel\")\n\n\tif resultChan := args.Get(0); resultChan != nil {\n\t\treturn resultChan.(<-chan *Result)\n\t}\n\n\treturn nil\n}", "func (k *ChannelKeeper) Channel() *amqp.Channel {\n\treturn k.msgCh\n}", "func (wire *Wire) Response() <-chan Response {\n\treturn wire.responses\n}", "func (o *DeleteChannelHandlerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 204:\n\t\tresult := NewDeleteChannelHandlerNoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewDeleteChannelHandlerUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 403:\n\t\tresult := NewDeleteChannelHandlerForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 500:\n\t\tresult := NewDeleteChannelHandlerInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\tdata, err := ioutil.ReadAll(response.Body())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"Requested DELETE /matchmaking/namespaces/{namespace}/channels/{channel} returns an error %d: %s\", response.Code(), string(data))\n\t}\n}", "func (ticker *PausableTicker) GetChannel() <-chan time.Time {\n\treturn ticker.channel\n}", "func (p *LightningPool) Channel(ctx context.Context) (*amqp.Channel, error) {\n\tvar (\n\t\tk *amqp.Channel\n\t\terr error\n\t)\n\n\tp.mx.Lock()\n\tlast := len(p.set) - 1\n\tif last >= 0 {\n\t\tk = p.set[last]\n\t\tp.set = p.set[:last]\n\t}\n\tp.mx.Unlock()\n\n\t// If pool is empty create new channel\n\tif last < 0 {\n\t\tk, err = p.new(ctx)\n\t\tif err != nil {\n\t\t\treturn k, errors.Wrap(err, \"failed to create new\")\n\t\t}\n\t}\n\n\treturn k, nil\n}", "func (ch *clientSecureChannel) handleResponse(res ua.ServiceResponse) error {\n\tch.mapPendingResponses()\n\thnd := res.Header().RequestHandle\n\tif op, ok := ch.pendingResponses[hnd]; ok {\n\t\tdelete(ch.pendingResponses, hnd)\n\t\tselect {\n\t\tcase op.ResponseCh() <- res:\n\t\tdefault:\n\t\t\tfmt.Println(\"In handleResponse, responseCh was blocked.\")\n\t\t}\n\t\treturn nil\n\t}\n\treturn ua.BadUnknownResponse\n}", "func (tv *TV) teardownResponseChannel(id string) {\n\ttv.resMutex.Lock()\n\tdefer tv.resMutex.Unlock()\n\n\tif ch, ok := tv.res[id]; ok {\n\t\tclose(ch)\n\t\tdelete(tv.res, id)\n\t}\n}", "func (*GetGuildChannelResponse) Descriptor() ([]byte, []int) {\n\treturn file_discord_v1_cache_proto_rawDescGZIP(), []int{5}\n}", "func (r *role) ProposeChannel(req client.ChannelProposal) (*paymentChannel, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), r.timeout)\n\tdefer cancel()\n\t_ch, err := r.Client.ProposeChannel(ctx, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Client.OnNewChannel callback adds paymentChannel wrapper to the chans map\n\tch, ok := r.chans.channel(_ch.ID())\n\tif !ok {\n\t\treturn ch, errors.New(\"channel not found\")\n\t}\n\treturn ch, nil\n}", "func (remote *SerialRemote) Channel() chan []byte {\n\treturn remote.channel\n}", "func (c *connection) Channel() (amqpChannel, error) {\n\tch, err := c.conn.Channel()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := ch.Confirm(wait); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &channel{ch}, nil\n}", "func PollResponse(w http.ResponseWriter, r *http.Request) {\n\ttimeout := make(chan bool)\n\tgo func() {\n\t\ttime.Sleep(30e9)\n\t\ttimeout <- true\n\t}()\n\n\tid := hub.newClient()\n\tdefer func() {\n\t\tclose(timeout)\n\t\thub.endSession(id)\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase msg := <-hub.client[id]:\n\t\t\tio.WriteString(w, msg)\n\t\t\treturn\n\t\tcase <-timeout:\n\t\t\treturn\n\t\t}\n\t}\n}", "func mainChannel() {\n\n\tretCanal := make(chan string)\n\n\tgo say(\"world\", retCanal) // retorna uma mensagem no channel retChannel\n\n\tfmt.Println(<-retCanal) // \taqui, a go routine principal esta esperando receber a mensagem do channel retornado pela go routine acima\n}", "func (conn *Connection) Channel() chan []byte {\n\treturn conn.channel\n}", "func (c *Connection) Channel() (*Channel, error) {\n\tch, err := c.Connection.Channel()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tchannel := &Channel{\n\t\tChannel: ch,\n\t\tdelayer: &delayer{delaySeconds: c.delaySeconds},\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\treason, ok := <-channel.Channel.NotifyClose(make(chan *amqp.Error))\n\t\t\t// exit this goroutine if channel is closed by developer\n\t\t\tif !ok || channel.IsClosed() {\n\t\t\t\tdebug(\"channel closed\")\n\t\t\t\tchannel.Close() // ensure closed flag is set when channel is closed\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tdebugf(\"channel closed, reason: %v\", reason)\n\n\t\t\t// recreate if channel is not closed by developer\n\t\t\tfor {\n\t\t\t\t// wait for channel recreate\n\t\t\t\twait(channel.delaySeconds)\n\n\t\t\t\tch, err := c.Connection.Channel()\n\t\t\t\tif err == nil {\n\t\t\t\t\tdebug(\"channel recreate success\")\n\t\t\t\t\tchannel.methodMap.Range(func(k, v interface{}) bool {\n\t\t\t\t\t\tmethodName, _ := k.(string)\n\t\t\t\t\t\tchannel.DoMethod(ch, methodName)\n\t\t\t\t\t\tdebugf(\"channel do method %v success\", methodName)\n\t\t\t\t\t\treturn true\n\t\t\t\t\t})\n\t\t\t\t\tchannel.Channel = ch\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tdebugf(\"channel recreate failed, err: %v\", err)\n\t\t\t}\n\t\t}\n\n\t}()\n\n\treturn channel, nil\n}", "func (m *MetricsHolder) Channel() chan<- interface{} {\n\treturn m.channel\n}", "func (tr *Peer) ReceiverChannel() <-chan *RPC {\n\ttr.mtx.Lock()\n\tdefer tr.mtx.Unlock()\n\n\treturn tr.server.ReceiverChannel()\n}", "func waitForResponse(originalResp *Response, channel chan *rpc.Call) {\n\tresp := <-channel\n\tvar test *Response\n\ttest = resp.Reply.(*Response)\n\ttest.client.Close()\n\toriginalResp.Reply = test.Reply\n\treturn\n}", "func (m *Manager) TerminationChannel(name string) chan struct{} {\n\tif c := m.lookup(name); c != nil {\n\t\treturn c.terminated\n\t}\n\n\tc := make(chan struct{})\n\tclose(c)\n\treturn c\n}", "func (o *Output) getResponse() {\r\n\tfor response := range o.receiveChannel {\r\n\t\tlog.Println(\"Producer: got a response to write\")\r\n\t\tif err := o.writeResponse(response); err != nil {\r\n\t\t\tcontinue\r\n\t\t}\r\n\t}\r\n}", "func (*CMsgGCRerollPlayerChallengeResponse) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_common_proto_rawDescGZIP(), []int{25}\n}", "func decodeGRPCSayHelloResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.SayHelloReply)\n\treturn endpoints.SayHelloResponse{Rs: reply.Rs}, nil\n}", "func (s *Service) RPCHandler(w http.ResponseWriter, r *http.Request) {\n\n\t// get response struct\n\trespObj := s.Do(r)\n\n\t// set custom response headers\n\tfor header, value := range s.Headers {\n\t\tw.Header().Set(header, value)\n\t}\n\n\t// set response headers\n\tfor header, value := range respObj.Headers {\n\t\tw.Header().Set(header, value)\n\t}\n\n\t// notification does not send responses to client\n\tif respObj.IsNotification {\n\t\t// set response header to 204, (no content)\n\t\tw.WriteHeader(http.StatusNoContent)\n\t\treturn\n\t}\n\n\t// write response code to HTTP writer interface\n\tw.WriteHeader(respObj.HTTPResponseStatusCode)\n\n\t// write data to HTTP writer interface\n\t_, err := w.Write(respObj.ResponseMarshal())\n\tif err != nil { // this should never happen\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n}", "func (p *PeerSubscription) CloseChan() <-chan struct{} {\n\treturn p.closeChan\n}", "func (meta *MetaAI) GetChannel(c chan string) {\n\tmeta.l.Lock()\n\tdefer meta.l.Unlock()\n\n\tmeta.i = c\n}", "func GetResponseCh(userId int64, urlType string) (*result.Result, *apierrors.ApiError){\n\n\tch := make(chan *result.Result)\n\tdefer close(ch)\n\n\tvar wg sync.WaitGroup\n\tvar result result.Result\n\n\n\tuser := user.User{\n\t\tID: userId,\n\t}\n\tuser.Get(urlType)\n\tresult.User = &user\n\n\tgo func() {\n\n\t\tfor i := 0; i < 2; i++ {\n\n\t\t\titem := <-ch\n\t\t\twg.Done()\n\t\t\tif item.Site != nil {\n\t\t\t\tresult.Site = item.Site\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif item.Country != nil {\n\t\t\t\tresult.Country = item.Country\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}()\n\n\twg.Add(2)\n\tgo getCountry(user.CountryID, urlType, ch, &wg)\n\tgo getSite(user.SiteID, urlType, ch, &wg)\n\twg.Wait()\n\n\treturn &result, nil\n\n}", "func (t *channelTransport) recv() <-chan pb.Message {\n\treturn t.recvChan\n}", "func (*Session) HandleResponse(msg proto.Message, err error) error {\n\tif err != nil {\n\t\t// check, if it is a gRPC error\n\t\ts, ok := status.FromError(err)\n\n\t\t// otherwise, forward the error message\n\t\tif !ok {\n\t\t\treturn err\n\t\t}\n\n\t\t// create a new error with just the message\n\t\treturn errors.New(s.Message())\n\t}\n\n\topt := protojson.MarshalOptions{\n\t\tMultiline: true,\n\t\tIndent: \" \",\n\t\tEmitUnpopulated: true,\n\t}\n\n\tb, _ := opt.Marshal(msg)\n\n\t_, err = fmt.Fprintf(Output, \"%s\\n\", string(b))\n\n\treturn err\n}", "func (o WorkerPoolOutput) Channel() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *WorkerPool) pulumi.StringOutput { return v.Channel }).(pulumi.StringOutput)\n}", "func (*CMsgClientToGCHasPlayerVotedForMVPResponse) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{180}\n}", "func (ctx *Context) SpecificChannelHandler(w http.ResponseWriter, r *http.Request) {\n\t//Get the channelID from the request's URL path\n\t_, id := path.Split(r.URL.String())\n\n\t//Get current state\n\tss := &SessionState{}\n\t_, err := sessions.GetState(r, ctx.SessionKey, ctx.SessionStore, ss)\n\tif err != nil {\n\t\thttp.Error(w, \"error getting current session : \"+err.Error(), http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t//Get channel from store\n\tc, err := ctx.MessageStore.GetChannelByID(messages.ChannelID(id))\n\tif err != nil {\n\t\thttp.Error(w, \"error getting channel: \"+err.Error(), http.StatusNotFound)\n\t\treturn\n\t}\n\n\tswitch r.Method {\n\t//gets the most recent 500 messages form the specified channel if user is allowed.\n\tcase \"GET\":\n\t\tif c.Private && !c.IsMember(ss.User.ID) {\n\t\t\thttp.Error(w, \"error getting channel : you are either not a member or the channel is private\", http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\n\t\tms, err := ctx.MessageStore.GetChannelMessages(messages.ChannelID(id), 500)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"error getting channel messages: \"+err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Add(headerContentType, contentTypeJSONUTF8)\n\t\tencoder := json.NewEncoder(w)\n\t\tencoder.Encode(ms)\n\t//updates the channel's name/description if the current user is creator\n\tcase \"PATCH\":\n\t\tif ss.User.ID != c.CreatorID {\n\t\t\thttp.Error(w, \"error updating channel: you aren't the owner\", http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\n\t\td := json.NewDecoder(r.Body)\n\t\tcu := &messages.ChannelUpdates{}\n\t\tif err := d.Decode(cu); err != nil {\n\t\t\thttp.Error(w, \"error decoding JSON\"+err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif err := cu.Validate(); err != nil {\n\t\t\thttp.Error(w, \"invalid channel: \"+err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tuc, err := ctx.MessageStore.UpdateChannel(cu, c)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"error updating channel: \"+err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\t//Notify client of updated channel through websocket\n\t\tn, err := uc.ToUpdatedChannelEvent()\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"error creating channel event: \"+err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tctx.Notifier.Notify(n)\n\n\t\tw.Header().Add(headerContentType, contentTypeJSONUTF8)\n\t\tencoder := json.NewEncoder(w)\n\t\tencoder.Encode(uc)\n\n\t//deletes the specified channel if current user is creator\n\tcase \"DELETE\":\n\t\tif ss.User.ID != c.CreatorID {\n\t\t\thttp.Error(w, \"error updating channel: you aren't the owner\", http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\n\t\tif err := ctx.MessageStore.DeleteChannel(messages.ChannelID(id)); err != nil {\n\t\t\thttp.Error(w, \"error deleting channel: \"+err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\t//Notify client of deleted channel through websocket\n\t\tn, err := c.ToDeletedChannelEvent()\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"error creating channel event: \"+err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tctx.Notifier.Notify(n)\n\n\t\tw.Header().Add(headerContentType, contentTypeText)\n\t\tw.Write([]byte(\"channel succesfully deleted\"))\n\n\t//adds the current user to the members list of the specified channel if\n\t//it's public. Uses the 'Link' header to get the userID to allow channel creators to add\n\t//users to private channels.\n\tcase \"LINK\":\n\t\tw.Header().Add(headerContentType, contentTypeText)\n\t\tif c.Private {\n\t\t\tif ss.User.ID != c.CreatorID {\n\t\t\t\thttp.Error(w, \"error updating channel: you aren't the owner\", http.StatusUnauthorized)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t//grab id from Link header\n\t\t\tid := users.UserID(r.Header.Get(headerLink))\n\t\t\t//if it's zero length, return StatusbadRequest\n\t\t\tif len(id) == 0 {\n\t\t\t\thttp.Error(w, \"invalid id used in Link header\", http.StatusBadRequest)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif err := ctx.MessageStore.AddChannelMember(id, c); err != nil {\n\t\t\t\thttp.Error(w, \"error adding member to channel: \"+err.Error(), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write([]byte(\"succesfully added member to channel\"))\n\t\t} else {\n\t\t\tif err := ctx.MessageStore.AddChannelMember(ss.User.ID, c); err != nil {\n\t\t\t\thttp.Error(w, \"error adding current user to channel: \"+err.Error(), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t//Notify client of new user joined channel through websocket\n\t\t\tn, err := ss.User.ToUserJoinedChannelEvent()\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(w, \"error creating user event: \"+err.Error(), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx.Notifier.Notify(n)\n\n\t\t\tw.Write([]byte(\"succesfully added member to channel\"))\n\t\t}\n\t//removes the current user to the members list. Uses 'Link' header to\n\t//get the userID to allow channel creators to remove users from private channel.\n\tcase \"UNLINK\":\n\t\tw.Header().Add(headerContentType, contentTypeText)\n\t\tif c.Private {\n\t\t\tif ss.User.ID != c.CreatorID {\n\t\t\t\thttp.Error(w, \"error updating channel: you aren't the owner\", http.StatusUnauthorized)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t//grab id from Link header\n\t\t\tid := users.UserID(r.Header.Get(headerLink))\n\t\t\t//if it's zero length, return StatusbadRequest\n\t\t\tif len(id) == 0 {\n\t\t\t\thttp.Error(w, \"invalid id used in Link header\", http.StatusBadRequest)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif err := ctx.MessageStore.RemoveChannelmember(id, c); err != nil {\n\t\t\t\thttp.Error(w, \"error removing member from channel: \"+err.Error(), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write([]byte(\"succesfully removed member from channel\"))\n\t\t} else {\n\t\t\tif err := ctx.MessageStore.RemoveChannelmember(ss.User.ID, c); err != nil {\n\t\t\t\thttp.Error(w, \"error removing member from channel: \"+err.Error(), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t//Notify client of user left channel through websocket\n\t\t\tn, err := ss.User.ToUserLeftChannelEvent()\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(w, \"error creating user event: \"+err.Error(), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx.Notifier.Notify(n)\n\n\t\t\tw.Write([]byte(\"succesfully removed member from channel\"))\n\t\t}\n\t}\n}", "func (ch *Channel) Close() {}", "func (o *PutChannelsChannelIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 204:\n\t\tresult := NewPutChannelsChannelIDNoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewPutChannelsChannelIDDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (s *secretRenewer) RenewChannel() chan secrets {\n\treturn s.renewCh\n}", "func (c *Client) Channel(channelID discord.ChannelID) (*discord.Channel, error) {\n\tvar channel *discord.Channel\n\treturn channel, c.RequestJSON(&channel, \"GET\", EndpointChannels+channelID.String())\n}", "func (r *Readiness) GetChannel() chan ReadinessMessage {\n\treturn r.channel\n}", "func (mf *MethodFrame) Channel() uint16 { return mf.ChannelID }", "func (t *TCPTransport) Responses() <-chan []byte {\n\treturn t.responses\n}", "func (clientHandler) Response(ctx context.Context, conn *jsonrpc2.Conn, direction jsonrpc2.Direction, r *jsonrpc2.WireResponse) context.Context {\n\treturn ctx\n}", "func (h *Helm) UpdateChannel() <-chan struct{} {\n\treturn h.trigger\n}", "func decodeGRPCTicResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\t_ = grpcReply.(*pb.TicResponse)\n\treturn endpoints.TicResponse{}, nil\n}", "func (cs *ChannelService) Channel() (apifabclient.Channel, error) {\n\treturn cs.fabricProvider.CreateChannelClient(cs.identityContext, cs.cfg)\n}", "func (r Rabbit) GetCh() *amqp.Channel {\n\treturn r.ch\n}", "func (gp *GetProjects) GetResponse() ActionResponseInterface {\n\treturn <-gp.responseCh\n}", "func (*CBroadcast_WebRTCLookupTURNServer_Response) Descriptor() ([]byte, []int) {\n\treturn file_steammessages_broadcast_steamclient_proto_rawDescGZIP(), []int{52}\n}", "func (k *ChannelKeeper) Return() <-chan amqp.Return {\n\treturn k.returnCh\n}", "func (r *Resolver) Channel(args struct{ ID string }) (*channels.ChannelResolver, error) {\n\treturn channels.GetChannel(args)\n}", "func (c Client) GetChannels(lineupURI string) (*ChannelResponse, error) {\n\turl := fmt.Sprint(DefaultBaseURL, lineupURI)\n\tfmt.Println(\"URL:>\", url)\n\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\treq.Header.Set(\"token\", c.Token)\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\tlog.Fatal(resp.Status)\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close() //resp.Body.Close() will run when we're finished.\n\n\t// make the map\n\th := new(ChannelResponse)\n\n // debug code\t\n //body, _ := ioutil.ReadAll(resp.Body)\n\t//fmt.Println(string(body))\n\n\t// decode the body into the map\n\terr = json.NewDecoder(resp.Body).Decode(&h)\n\tif err != nil {\n\t\tfmt.Println(\"Error parsing channel response line\")\n\t\tlog.Fatal(err)\n\t\treturn nil, err\n\t}\n\n\treturn h, nil\n}", "func (rc *Ctx) Response() ResponseWriter {\n\treturn rc.response\n}", "func Response(conn net.Conn, provider net.Conn) {\n\tch := make(chan bool)\n\tgo transfer(conn, provider, ch)\n\tgo transfer(provider, conn, ch)\n\t<-ch\n\tconn.Close()\n\tprovider.Close()\n\t<-ch\n\tclose(ch)\n}", "func (c *Provider) ChannelProvider() fab.ChannelProvider {\n\treturn c.channelProvider\n}", "func (o *CreateChannelReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 201:\n\t\tresult := NewCreateChannelCreated()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewCreateChannelBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 401:\n\t\tresult := NewCreateChannelUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 422:\n\t\tresult := NewCreateChannelUnprocessableEntity()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewCreateChannelInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (r *postBoostResolver) Channel(ctx context.Context, post *posts.Boost) (*channels.Channel, error) {\n\treturn r.getChannel(ctx, post)\n}", "func (c *webCtx) Response() http.ResponseWriter {\n\treturn c.resp\n}", "func ChannelHandler(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase http.MethodGet:\n\t\terr := fmt.Errorf(\"Unsupported method %s\", r.Method)\n\t\terrorHandler(w, r, http.StatusInternalServerError, err)\n\t\treturn\n\tcase http.MethodPost:\n\t\t// Create a new channel.\n\t\tc := &channel.Channel{}\n\t\tdecoder := json.NewDecoder(r.Body)\n\t\tvar payload *channel.CreatePayload\n\t\terr := decoder.Decode(&payload)\n\t\tif err != nil {\n\t\t\terrorHandler(w, r, http.StatusInternalServerError, err)\n\t\t\treturn\n\t\t}\n\n\t\treq := &channel.CreateRequest{Payload: payload}\n\t\tres, err := c.Create(req)\n\t\tif err != nil {\n\t\t\terrorHandler(w, r, http.StatusInternalServerError, err)\n\t\t\treturn\n\t\t}\n\t\tb, err := json.Marshal(res)\n\t\tif err != nil {\n\t\t\terrorHandler(w, r, http.StatusInternalServerError, err)\n\t\t\treturn\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write(b)\n\t\treturn\n\tcase http.MethodPut:\n\t\terr := fmt.Errorf(\"Unsupported method %s\", r.Method)\n\t\terrorHandler(w, r, http.StatusInternalServerError, err)\n\t\treturn\n\tcase http.MethodDelete:\n\t\terr := fmt.Errorf(\"Unsupported method %s\", r.Method)\n\t\terrorHandler(w, r, http.StatusInternalServerError, err)\n\t\treturn\n\tdefault:\n\t\terr := fmt.Errorf(\"Unsupported method %s\", r.Method)\n\t\terrorHandler(w, r, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n}", "func (*CBroadcast_EndBroadcastSession_Response) Descriptor() ([]byte, []int) {\n\treturn file_steammessages_broadcast_steamclient_proto_rawDescGZIP(), []int{3}\n}", "func (ch *InternalChannel) Disconnect(c *Client) {}", "func (ctx *serverRequestContextImpl) GetResp() http.ResponseWriter {\n\treturn ctx.resp\n}", "func (o *GetAllSessionsInChannelReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetAllSessionsInChannelOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewGetAllSessionsInChannelBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewGetAllSessionsInChannelUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 403:\n\t\tresult := NewGetAllSessionsInChannelForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewGetAllSessionsInChannelNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 500:\n\t\tresult := NewGetAllSessionsInChannelInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\tdata, err := ioutil.ReadAll(response.Body())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"Requested GET /matchmaking/v1/admin/namespaces/{namespace}/channels/{channelName}/sessions returns an error %d: %s\", response.Code(), string(data))\n\t}\n}", "func (c *Client) Channel() string {\n\treturn c.channel\n}", "func (this *service) CommandChannel() chan<- Command {\n\treturn this._commandChannel\n}", "func (f *feedback) Channel() (<-chan *FeedbackMessage, error) {\n\tif f.conn != nil {\n\t\treturn f.chanel, nil\n\t}\n\n\tif err := f.createConnection(); err != nil {\n\t\tlogerr(\"Unable to start feedback connection: %s\", err)\n\t\treturn nil, err\n\t}\n\n\tf.stopWait.Add(1)\n\tgo f.monitorService()\n\n\treturn f.chanel, nil\n}", "func (_obj *Apichannels) Channels_getParticipants(params *TLchannels_getParticipants, _opt ...map[string]string) (ret Channels_ChannelParticipants, err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = params.WriteBlock(_os, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tvar _status map[string]string\n\tvar _context map[string]string\n\tif len(_opt) == 1 {\n\t\t_context = _opt[0]\n\t} else if len(_opt) == 2 {\n\t\t_context = _opt[0]\n\t\t_status = _opt[1]\n\t}\n\t_resp := new(requestf.ResponsePacket)\n\ttarsCtx := context.Background()\n\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"channels_getParticipants\", _os.ToBytes(), _status, _context, _resp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\t_is := codec.NewReader(tools.Int8ToByte(_resp.SBuffer))\n\terr = ret.ReadBlock(_is, 0, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tif len(_opt) == 1 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t} else if len(_opt) == 2 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t\tfor k := range _status {\n\t\t\tdelete(_status, k)\n\t\t}\n\t\tfor k, v := range _resp.Status {\n\t\t\t_status[k] = v\n\t\t}\n\n\t}\n\t_ = length\n\t_ = have\n\t_ = ty\n\treturn ret, nil\n}", "func (ch *ServerChannel) Disconnect(c *Client) {}", "func (p *Publisher) GetChannel() *amqp.Channel {\n\tp.publicMethodsLock.Lock()\n\tdefer p.publicMethodsLock.Unlock()\n\treturn p.getChannelWithoutLock()\n}", "func GetChannel(protocol, host string, port int, secureConfig *tls.Config) (ReaderWriterCloser, error) {\n\tvar conn net.Conn\n\tvar err error\n\tconn, err = net.Dial(protocol, host+\":\"+strconv.Itoa(port))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif protocol == \"tcp\" {\n\t\tconn.(*net.TCPConn).SetKeepAlive(true)\n\t\tconn.(*net.TCPConn).SetKeepAlivePeriod(30 * time.Second)\n\t}\n\tif secureConfig != nil {\n\t\tconn = tls.Client(conn, secureConfig)\n\t}\n\tvar readerWriter ReaderWriterCloser = &Channel{\n\t\tprotocol: protocol,\n\t\thost: host,\n\t\tport: port,\n\t\tconn: conn,\n\t\tmaxRead: 8 * 1024,\n\t\treadBuffer: make([]byte, 0),\n\t\twriteBuffer: make([]byte, 0),\n\t\twriteChannel: make(chan writeComplete, 100),\n\t\treadTimeout: 60 * time.Second,\n\t\twriteTimeout: 60 * time.Second,\n\t}\n\tgo readerWriter.(*Channel).writeRoutine()\n\treturn readerWriter, nil\n}", "func Channel(m *operatorsv1.MultiClusterHub) *unstructured.Unstructured {\n\tch := &unstructured.Unstructured{\n\t\tObject: map[string]interface{}{\n\t\t\t\"apiVersion\": \"apps.open-cluster-management.io/v1\",\n\t\t\t\"kind\": \"Channel\",\n\t\t\t\"metadata\": map[string]interface{}{\n\t\t\t\t\"name\": ChannelName,\n\t\t\t\t\"namespace\": m.Namespace,\n\t\t\t},\n\t\t\t\"spec\": map[string]interface{}{\n\t\t\t\t\"type\": \"HelmRepo\",\n\t\t\t\t\"pathname\": channelURL(m),\n\t\t\t},\n\t\t},\n\t}\n\tif m.Status.CurrentVersion != version.Version {\n\t\tch.SetAnnotations(AnnotationRateHigh)\n\t} else {\n\t\tch.SetAnnotations(AnnotationRateLow)\n\t}\n\n\tch.SetOwnerReferences([]metav1.OwnerReference{\n\t\t*metav1.NewControllerRef(m, m.GetObjectKind().GroupVersionKind()),\n\t})\n\treturn ch\n}", "func (hf *HeaderFrame) Channel() uint16 { return hf.ChannelID }", "func (*CMsgClientToGCRequestPlusWeeklyChallengeResultResponse) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{274}\n}", "func (*WebhookResponse) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_dialogflow_v2beta1_webhook_proto_rawDescGZIP(), []int{1}\n}", "func ChoicesResp(c *gin.Context) {\n\n\t// Variable that holds all possible choices in the rpsls game\n\tchoices := Choices()\n\n\t// Call the JSON method of the Context to render the given interface into JSON\n\tc.JSON(\n\t\t// Set the HTTP status to 200 (OK)\n\t\thttp.StatusOK,\n\t\t// Pass the data that the response uses\n\t\tchoices,\n\t)\n\n}", "func (*GetGuildRoleResponse) Descriptor() ([]byte, []int) {\n\treturn file_discord_v1_cache_proto_rawDescGZIP(), []int{13}\n}", "func GetChannel(service *service.Service, name string) (*Channel, error) {\n\t// Call get channel by name endpoint\n\tres, err := service.SimpleCall(\"private.channel.get\", nil, wamp.Dict{\"name\": name})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Check and return response\n\tif len(res.Arguments) > 0 && res.Arguments[0] != nil {\n\t\tchannel, err := conv.ToStringMap(res.Arguments[0])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn &Channel{\n\t\t\tName: conv.ToString(channel[\"name\"]),\n\t\t\tBotName: conv.ToString(channel[\"bot_name\"]),\n\t\t}, nil\n\t}\n\treturn nil, nil\n}" ]
[ "0.7525077", "0.64802736", "0.6193416", "0.61042297", "0.5942383", "0.5751946", "0.5705949", "0.56923497", "0.5657395", "0.5650136", "0.5641518", "0.5622532", "0.55227107", "0.54787594", "0.5476853", "0.5465402", "0.54651755", "0.5463305", "0.54460514", "0.54182273", "0.5416078", "0.53984076", "0.538422", "0.5347148", "0.53442734", "0.53409797", "0.53246164", "0.53156114", "0.53060675", "0.5296988", "0.52943397", "0.52915764", "0.5291485", "0.52907366", "0.5288502", "0.5272821", "0.5269091", "0.52340394", "0.5212104", "0.5163296", "0.5159889", "0.5156449", "0.5149921", "0.5147451", "0.5144623", "0.5122571", "0.51060534", "0.5097211", "0.50821996", "0.50674254", "0.50598574", "0.50591475", "0.50574064", "0.5051089", "0.50509906", "0.50420713", "0.50306207", "0.50216633", "0.5020054", "0.49990302", "0.4993714", "0.49929962", "0.49882072", "0.49839386", "0.49825191", "0.49812353", "0.49807823", "0.49788207", "0.4972915", "0.4970658", "0.49690154", "0.49428603", "0.4942707", "0.49380064", "0.49350664", "0.49267295", "0.4919725", "0.49177206", "0.4914646", "0.4913604", "0.4913359", "0.49105006", "0.49097347", "0.4908018", "0.49077186", "0.49004734", "0.48984274", "0.4897914", "0.4881967", "0.48812187", "0.48800835", "0.4877432", "0.48543182", "0.48510468", "0.48457998", "0.48452953", "0.4844547", "0.4833281", "0.48167175", "0.48152098" ]
0.75294656
0
GoToDinner is the philosopher's main task. They periodically issue eat requests to the host, unless not already eating. When asked so by the host, the philosopher leaves.
func (phi *Philosopher) GoToDinner(waitGrp *sync.WaitGroup, requestChannel, finishChannel chan string) { defer waitGrp.Done() retryInterval := time.Duration(2000) * time.Millisecond eatingDuration := time.Duration(5000) * time.Millisecond for { requestChannel <- phi.name switch <-phi.respChannel { case "OK": time.Sleep(eatingDuration) finishChannel <- phi.name case "E:LIMIT": fmt.Println(strings.ToUpper("----- " + phi.name + " LEFT THE TABLE. -----")) fmt.Println() return default: time.Sleep(retryInterval) } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func philosopherPonderanceGoroutine(id int) {\n\tfor {\n\t\tif rand.Float64() < PHILSWITCHCHANCE {\n\t\t\tphilIn[id] <- 2\n\t\t\tisEating := <- philOut[id] == 1\n\t\t\t// Switch: Thinking <-> Eating.\n\t\t\tif isEating {\n\t\t\t\t// Drop forks and return to positing on the nature of the universe.\n\t\t\t\tphilIn[id] <- 1\n\t\t\t} else {\n\t\t\t\t// Attempt to begin eating. Return to postulating, if missing fork.\n\t\t\t\tphilIn[id] <- 0\n\t\t\t}\n\t\t\t<- philOut[id]\n\t\t}\n\t}\n}", "func (p Philosopher) dine(wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\tp.leftFork.Lock()\n\tp.rightFork.Lock()\n\n\tfmt.Println(p.id, \" is eating\")\n\t//used pause values to minimise.\n\ttime.Sleep(2 * time.Second)\n\tp.rightFork.Unlock()\n\tp.leftFork.Unlock()\n\n}", "func (host *DinnerHost) Listen() {\n\tname := \"\"\n\tfor {\n\t\tselect {\n\t\tcase name = <-host.requestChannel:\n\t\t\tfmt.Println(name + \" WOULD LIKE TO EAT.\")\n\n\t\t\tresponse := host.AllowEating(name)\n\t\t\tkickOut := false\n\t\t\tswitch response {\n\t\t\tcase \"OK\":\n\t\t\t\tfmt.Println(name + \" STARTS EATING.\")\n\t\t\tcase \"E:CHOPSTICKS\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: REQUIRED CHOPSTICKS ARE NOT AVAILABLE.\")\n\t\t\tcase \"E:FULL\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: TWO OTHER PHILOSOPHERS ARE ALREADY EATING.\")\n\t\t\tcase \"E:JUSTFINISHED\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: JUST FINISHED THE PREVIOUS MEAL.\")\n\t\t\tcase \"E:EATING\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: ALREADY EATING.\")\n\t\t\tcase \"E:LIMIT\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: ALREADY HAD THREE DINNERS; MUST LEAVE.\")\n\t\t\t\thost.freeSeats = append(host.freeSeats, host.phiData[name].Seat())\n\t\t\t\tkickOut = true\n\t\t\t}\n\t\t\tfmt.Println()\n\n\t\t\thost.phiData[name].RespChannel() <- response\n\n\t\t\tif kickOut {\n\t\t\t\tdelete(host.phiData, name)\n\t\t\t}\n\t\tcase name = <-host.finishChannel:\n\t\t\thost.SomeoneFinished(name)\n\t\t}\n\t\thost.PrintReport(false)\n\t}\n}", "func TurnEver(d *turn.Dancing, l *tees.Tees) {\n\n//\tif d.OnLeaf(l){\t\t\t\treturn\t}\t// YES We have to abort\n//\tif d.OnGoal(l){\t\t\t\treturn\t}\t// YES We have a solution\n\tif l.IsEmpty(){\t\t\t\treturn\t}\t// YES We have a solution - but we don't tell anyone\n\tnext, ok := d.OnFail(l); if !ok {\treturn\t}\t// YES We have a failure\n\n//\td.Level++\n\td.Dance(next)\n//\td.Level--\n}", "func (g *game) dayDone() bool {\n\tplr, vts := g.countVotesFor(\"villager\")\n\tif vts <= g.alivePlayers()/2 && time.Since(g.StateTime) < StateTimeout {\n\t\treturn false\n\t}\n\n\tif vts == 0 {\n\t\tg.serverMessage(\"Villages didn't vote, nobody dies.\")\n\t\treturn true\n\t}\n\n\ttoBeKilled := plr[rand.Intn(len(plr))]\n\ttoBeKilled.Dead = true\n\tg.serverMessage(toBeKilled.Name + \" was lynched by an angry mob!\")\n\treturn true\n}", "func (host *DinnerHost) SomeoneFinished(name string) {\n\tif host.currentlyEating > 0 {\n\t\thost.currentlyEating--\n\t}\n\thost.chopsticksFree[host.phiData[name].LeftChopstick()] = true\n\thost.chopsticksFree[host.phiData[name].RightChopstick()] = true\n\thost.phiData[name].FinishedEating()\n\tfmt.Println(name + \" FINISHED EATING.\")\n\tfmt.Println()\n}", "func (m *Module) DoTheDew() error {\n\tlog.Printf(\"[%s][%s] Doing the dew!\", m.Config.Server.Name, m.Version)\n\tstats, err := m.fetch()\n\tif err != nil {\n\t\treturn wrap(\"failed to fetch\", err)\n\t}\n\n\tif m.Version == \"decompose\" {\n\t\tstats.AdsBlockedToday = 0\n\t}\n\n\ttopStats, err := m.fetchTopStats()\n\tif err != nil {\n\t\t// ignore top Stats\n\t\tlog.Printf(\"no top stats, skipped: %s\", err)\n\t\ttopStats = TopStats{}\n\t}\n\n\tmsg := m.compose(stats, topStats)\n\tif msg == \"\" {\n\t\treturn wrap(\"failed to compose\", errors.New(\"empty message\"))\n\t}\n\n\tif !m.Config.Twitter.Enabled {\n\t\tlog.Printf(\"[%s][%s][dry] %s\", m.Config.Server.Name, m.Version, msg)\n\t\treturn nil\n\t}\n\n\ttweet, err := m.twitter.PostTweet(msg, nil)\n\tif err != nil {\n\t\treturn wrap(\"failed to tweet\", err)\n\t}\n\n\tlog.Printf(\"[%s][%s][%s] %s\", m.Config.Server.Name, m.Version, tweet.CreatedAt, tweet.Text)\n\treturn nil\n}", "func (philosopher *Philosopher) Eat(wg *sync.WaitGroup, host Host) {\n\tfor i := 0; i < 3; i++ {\n\t\thost.GiveMePermission()\n\t\tphilosopher.leftChopstick.Lock()\n\t\tphilosopher.rightChopstick.Lock()\n\t\tfmt.Printf(\"Starting to eat %d\\n\", philosopher.id)\n\t\ttime.Sleep(500 * time.Millisecond)\n\t\tfmt.Printf(\"Finishing eating %d. (time: %d)\\n\", philosopher.id, i+1)\n\t\tphilosopher.rightChopstick.Unlock()\n\t\tphilosopher.leftChopstick.Unlock()\n\t\thost.Done()\n\t}\n\twg.Done()\n}", "func verTwo() {\n\tsleepyGopher := func(id int, c chan int) {\n\t\ttime.Sleep(3 * time.Second)\n\t\tfmt.Printf(\"...%v snore...\\n\", id)\n\t\tc <- id\n\t}\n\n\tc := make(chan int)\n\n\tfmt.Println(\"Running code from listing 30.4\")\n\n\t// This loop spins up the goroutines.\n\tfor i := 0; i < 5; i++ {\n\t\tgo sleepyGopher(i, c)\n\t}\n\t// This loop waits for the channel to send an integer from each goroutine call\n\tfor i := 0; i < 5; i++ {\n\t\t// When \"sleepyGopher()\" hits \n\t\tgopherId := <-c\n\t\tfmt.Printf(\"gopher %v has finished sleeping\\n\", gopherId)\n\t}\n}", "func (p philosopher) eat() {\r\n\tdefer eatWgroup.Done()\r\n\tfor j := 0; j < 3; j++ {\r\n\t\tp.leftFork.Lock()\r\n\t\tp.rightFork.Lock()\r\n\r\n\t\tsay(\"eating\", p.id)\r\n\t\ttime.Sleep(time.Second)\r\n\r\n\t\tp.rightFork.Unlock()\r\n\t\tp.leftFork.Unlock()\r\n\r\n\t\tsay(\"finished eating\", p.id)\r\n\t\ttime.Sleep(time.Second)\r\n\t}\r\n\r\n}", "func (s *BaseDiceListener) EnterDic(ctx *DicContext) {}", "func pingTimeoutHandler(_ *PingMessageTask, env *Env) {\n log.Debugf(\"Ping Timeout #%+v\", env.session.GetCurrentMissingHb())\n\n\tif !env.IsHeartbeatAllowed() {\n\t\tlog.Debug(\"Exceeded missing_hb_allowed. Stop ping task...\")\n \n // Get dot peer common name from current session\n cn, err := env.session.DtlsGetPeerCommonName()\n if err != nil {\n log.WithError(err).Error(\"DtlsGetPeercCommonName() failed\")\n return\n }\n\n // Get customer from common name\n customer, err := models.GetCustomerByCommonName(cn)\n if err != nil || customer.Id == 0 {\n log.WithError(err).Error(\"Customer not found.\")\n return\n }\n\n // Trigger mitigation mechanism is active\n log.Debug(\"Start Trigger Mitigation mechanism.\")\n err = controllers.TriggerMitigation(customer)\n if err != nil {\n log.WithError(err).Error(\"TriggerMitigation() failed\")\n return\n }\n env.session.SetIsPingTask(false)\n\n log.Debugf(\"DTLS session: %+v has already disconnected. Terminate session...\", env.session.String())\n env.session.TerminateConnectingSession(env.context)\n return\n }\n log.Debugf(\"[Session Mngt Thread]: Re-send ping message (id = %+v) to check client connection\", env.pingMessageTask.message.MessageID)\n env.Run(env.pingMessageTask)\n}", "func (p philosopher) eat() {\n\tfor j := 0; j < numberOfCourses; j++ {\n\t\t//Pick up sticks means lock both mutex\n\t\tp.leftChopstick.Lock()\n\t\tp.rightChopstick.Lock()\n\t\t// Acknowledge the start\n\t\t//starting to eat <number>\n\t\tfmt.Printf(\"Starting to eat %d(%s) [%s] \\n\", p.id+1, nameOfPhilosophers[p.id], courses[j])\n\t\ttime.Sleep(time.Second)\n\t\t//Release mutex\n\t\tp.rightChopstick.Unlock()\n\t\tp.leftChopstick.Unlock()\n\t\t// Acknowledge the finish\n\t\t//finishing eating <number>\n\t\tfmt.Printf(\"finishing eating %d(%s) [%s] \\n\", p.id+1, nameOfPhilosophers[p.id], courses[j])\n\t\ttime.Sleep(time.Second)\n\t}\n\teatWaitingGroup.Done()\n}", "func PlayGoTacToe() {\n\tgo Hub.run()\n\tgo Mh.handle()\n\tvotes := make(map[Coord]int)\n\tdecisionTimer := time.After(decisionInterval)\n\tfor {\n\t\tselect {\n\t\tcase input := <-VoteInput:\n\t\t\tvar vote voteMsg\n\t\t\terr := json.Unmarshal(input, &vote)\n\t\t\tif err != nil {\n\t\t\t\t// Invalid vote data, who cares\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlog.Printf(\"Received vote %d,%d from %s\", vote.X, vote.Y, vote.Player)\n\t\t\tif vote.Player == fmt.Sprint(board.Turn) {\n\t\t\t\tcoord := Coord{vote.X, vote.Y}\n\t\t\t\t// Only process votes for empty fields\n\t\t\t\tif board.Fields[coord] == EMPTY {\n\t\t\t\t\tvotes[coord] += 1\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Println(\"Ignoring vote, not your turn!\")\n\t\t\t}\n\t\tcase <-decisionTimer:\n\t\t\tdecide(votes)\n\t\t\t// New channel to remove votes placed deciding\n\t\t\tVoteInput = make(chan []byte)\n\t\t\tvotes = make(map[Coord]int)\n\t\t\tdecisionTimer = time.After(decisionInterval)\n\t\t}\n\t}\n}", "func doBye(w http.ResponseWriter, r *http.Request) {\n\ts, err := newServerCGI(w, r)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\thost, path, port := s.extractHost(\"bye\")\n\thost = s.checkRemote(host)\n\tif host == \"\" {\n\t\treturn\n\t}\n\tn, err := node.MakeNode(host, path, port)\n\tif err == nil {\n\t\ts.NodeManager.RemoveFromList(n)\n\t}\n\tfmt.Fprintln(s.wr, \"BYEBYE\")\n}", "func SpawnDolevNode(id int, sn *SimulatedNetwork, numTotalNodes int, ps *PublicSwarmUpdateServer, pinkslip chan struct{}) {\n\n\tstate_crashed := false\n\n\t// we run a centisecond (cs) granular clock. (we can't exactly visualize ms granularity...)\n\t// clockSkew := int((rand.Float64()*1.0 - 1.0) * float64(sn.roundTimeSkew) / float64(sn.configDayMS) / 10.0) // configDayMS is actually in cs, and there are 10 ms in 1 cs\n\tclockSkew := 1000000 * float64(sn.roundTimeSkew) * 10.0 / float64(sn.configDayMS) / 10.0 * float64(id) * 10.0 // id is temp\n\tcachedSkewConfig := sn.roundTimeSkew\n\tcachedDay := sn.configDayMS\n\n\tclockDur := time.Duration(10000000+clockSkew) * time.Nanosecond\n\tclockTicker := time.NewTicker(clockDur)\n\tclockVal := 0\n\troundNum := 0\n\tlastAdjustedClockVal := 0\n\n\t// skewedRoundLength := sn.roundTime + int((rand.Float64()*2.0-1.0)*float64(sn.roundTimeSkew))\n\t// skewedDayLength := sn.configDayMS + int((rand.Float64()*2.0-1.0)*float64(sn.configDaySkewStdDev))\n\n\t// cachedDTS := sn.configDaySkewStdDev\n\n\t// proposedDay := 0\n\t// correctedDay := 0\n\t// currentRound := 0\n\tmyMailbox := sn.MailboxFor(id)\n\t// dur := int(math.Exp(math.Log(float64(sn.configDayMS)) + rand.NormFloat64()*float64(sn.configDaySkewStdDev)))\n\t// if dur < 1 {\n\t// \tdur = 1\n\t// }\n\t// D := time.Duration(dur) * time.Millisecond\n\t// ticker := time.NewTicker(D)\n\n\t// roundDur := sn.roundTime + int((rand.Float64()*2.0-1.0)*float64(sn.roundTimeSkew)) // in ms\n\t// roundDMS := time.Duration(roundDur) * time.Millisecond\n\t// roundTicker := time.NewTicker(roundDMS)\n\n\t// knownProposals := make([]int, numTotalNodes)\n\t// var crashRecovery <-chan time.Time\n\n\t// prevDur := dur\n\tfor {\n\t\tselect {\n\t\t// case <-crashRecovery:\n\t\t// \t// if nil, this case never triggers\n\t\t// \tstate_crashed = false\n\t\t// \t// fire our timer\n\t\t// \tD = time.Duration(prevDur) * time.Millisecond\n\t\t// \tticker = time.NewTicker(D)\n\t\tcase <-clockTicker.C:\n\t\t\t// fmt.Printf(\"TICK%d;%d\\n\", clockVal, id)\n\t\t\t// advance our clock\n\t\t\tclockVal += 1\n\t\t\tnewDay := false\n\n\t\t\tif clockVal%sn.configDayMS == 0 {\n\t\t\t\t// new day!\n\t\t\t\t// send a sync/new-day message with the current clock time\n\t\t\t\t// fmt.Println(\"Node reached new day: \", id)\n\t\t\t\tlastAdjustedClockVal = clockVal\n\t\t\t\tm := Message{}\n\t\t\t\tm.from = id\n\t\t\t\tm.name = \"new-day\"\n\t\t\t\tm.contents = clockVal\n\t\t\t\tsn.Broadcast(m)\n\t\t\t\tnewDay = true\n\t\t\t}\n\t\t\tif clockVal%sn.roundTime == 0 {\n\t\t\t\t// new round!\n\t\t\t\troundNum = clockVal / sn.roundTime\n\n\t\t\t\t// send a message to test msg-delivery-guarantee\n\t\t\t\tm := Message{}\n\t\t\t\tm.from = id\n\t\t\t\tm.name = \"checkround\"\n\t\t\t\tm.contents = roundNum\n\t\t\t\tsn.Broadcast(m)\n\n\t\t\t\tif newDay {\n\t\t\t\t\tps.BroadcastSwarmUpdate(SwarmUpdate{id, roundNum, 1})\n\t\t\t\t} else {\n\t\t\t\t\tps.BroadcastSwarmUpdate(SwarmUpdate{id, roundNum, 0})\n\t\t\t\t}\n\n\t\t\t\tif sn.roundTimeSkew != cachedSkewConfig || sn.configDayMS != cachedDay {\n\t\t\t\t\tcachedSkewConfig = sn.roundTimeSkew\n\t\t\t\t\tcachedDay = sn.configDayMS\n\t\t\t\t\t// clockSkew = int((rand.Float64()*1.0 - 1.0) * float64(sn.roundTimeSkew) / float64(sn.configDayMS) / 10.0)\n\t\t\t\t\tclockSkew = 1000000 * float64(sn.roundTimeSkew) * 10.0 / float64(sn.configDayMS) / 10.0 * float64(id) * 10.0 // id is temp\n\t\t\t\t\t// if id == 1 {\n\t\t\t\t\t// \tfmt.Println(\"hello\")\n\t\t\t\t\t// \tfmt.Println(clockSkew)\n\t\t\t\t\t// }\n\t\t\t\t\tclockTicker.Stop()\n\t\t\t\t\tclockDur = time.Duration(10000000+clockSkew) * time.Nanosecond\n\t\t\t\t\tclockTicker = time.NewTicker(clockDur)\n\t\t\t\t}\n\n\t\t\t\t// // check if our clocks changed at all (ok this is actually dynamic...)\n\t\t\t\t// // actually... let's skew the actual clocks.\n\t\t\t\t// if sn.roundTimeSkew != cachedRTS {\n\t\t\t\t// \tskewedRoundLength = sn.roundTime + int((rand.Float64()*2.0-1.0)*float64(sn.roundTimeSkew))\n\t\t\t\t// \tcachedRTS = sn.roundTimeSkew\n\n\t\t\t\t// \tclockTicker.Stop()\n\t\t\t\t// \tclockDur = time.Duration(10) * time.Millisecond\n\t\t\t\t// \tclockTicker := time.NewTicker(clockDur)\n\t\t\t\t// }\n\t\t\t\t// if sn.configDaySkewStdDev != cachedDTS {\n\t\t\t\t// \t// ignore the day skew for now\n\t\t\t\t// \tskewedDayLength = sn.configDayMS + int((rand.Float64()*2.0-1.0)*float64(sn.configDaySkewStdDev))\n\t\t\t\t// \tcachedDTS = sn.configDaySkewStdDev\n\t\t\t\t// }\n\n\t\t\t\t// if skewedRoundLength < 1 {\n\t\t\t\t// \tskewedRoundLength = 1\n\t\t\t\t// }\n\t\t\t\t// if skewedDayLength < 1 {\n\t\t\t\t// \tskewedDayLength = 1\n\t\t\t\t// }\n\t\t\t}\n\n\t\t// case <-ticker.C:\n\t\t// \tif state_crashed {\n\t\t// \t\tbreak\n\t\t// \t}\n\t\t// \tproposedDay += 1\n\t\t// \t// send a sync message\n\t\t// \tm := Message{}\n\t\t// \tm.from = id\n\t\t// \tm.name = \"proposed-day\"\n\t\t// \tm.contents = proposedDay\n\t\t// \t// fmt.Println(m)\n\t\t// \tsn.Broadcast(m)\n\t\t// \tps.BroadcastSwarmUpdate(SwarmUpdate{id, proposedDay, 0})\n\n\t\t// \t// check if new D or dynamic skew\n\t\t// \tdur := sn.configDayMS + int(rand.NormFloat64()*float64(sn.configDaySkewStdDev))\n\t\t// \tdur = dur + int(rand.NormFloat64()*float64(sn.configEveryDaySkewStdDev))\n\t\t// \tif dur < 1 {\n\t\t// \t\tdur = 1\n\t\t// \t}\n\t\t// \tif dur != prevDur {\n\t\t// \t\tticker.Stop()\n\t\t// \t\tD = time.Duration(dur) * time.Millisecond\n\t\t// \t\tticker = time.NewTicker(D)\n\t\t// \t\tprevDur = dur\n\t\t// \t}\n\t\tcase m := <-myMailbox:\n\t\t\t// nodes are alive are always processing new day messages\n\t\t\tif state_crashed {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// we have a message!\n\t\t\tswitch m.name {\n\t\t\tcase \"checkround\":\n\t\t\t\tif m.contents < roundNum {\n\t\t\t\t\t// we didn't wait long enough. For some reason, new-day messages trigger this prematurely.\n\t\t\t\t\t// fmt.Printf(\"Delta: \\t%d\\n\", roundNum-m.contents)\n\t\t\t\t\tps.NoteMessageDelivery(false, roundNum-m.contents)\n\t\t\t\t} else if m.contents > roundNum {\n\t\t\t\t\t// this is fine, our clock is slower than the sender\n\t\t\t\t\tps.NoteMessageDelivery(true, roundNum-m.contents)\n\t\t\t\t} else {\n\t\t\t\t\tps.NoteMessageDelivery(true, roundNum-m.contents)\n\t\t\t\t}\n\t\t\tcase \"proposed-day\":\n\t\t\t\t// HONEST DOLEV's - every sync message is basically a new-day message\n\t\t\t\t// if m.contents <= knownProposals[m.from] {\n\t\t\t\t// \tbreak\n\t\t\t\t// }\n\t\t\t\t// knownProposals[m.from] = m.contents\n\t\t\t\t// // check if a majority of known proposals have advanced past some time\n\t\t\t\t// majorityCheck := make([]int, len(knownProposals))\n\t\t\t\t// copy(majorityCheck, knownProposals)\n\t\t\t\t// sort.Sort(sort.Reverse(sort.IntSlice(majorityCheck)))\n\t\t\t\t// majorityDay := majorityCheck[len(majorityCheck)/2]\n\n\t\t\t\t// if majorityDay <= correctedDay {\n\t\t\t\t// \tbreak\n\t\t\t\t// }\n\t\t\t\t// m.contents = majorityDay\n\t\t\t\tfallthrough\n\t\t\tcase \"new-day\":\n\t\t\t\tif m.contents <= lastAdjustedClockVal {\n\t\t\t\t\t// this is unrelated, but we don't verify any proofs yet\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tclockVal = m.contents\n\t\t\t\tlastAdjustedClockVal = clockVal\n\t\t\t\troundNum = clockVal / sn.roundTime\n\t\t\t\tps.BroadcastSwarmUpdate(SwarmUpdate{id, roundNum, 1})\n\t\t\t\t// gossip new day\n\t\t\t\tm := Message{}\n\t\t\t\tm.from = id\n\t\t\t\tm.name = \"new-day\"\n\t\t\t\tm.contents = clockVal\n\t\t\t\tsn.Broadcast(m)\n\t\t\t\t// correctedDay = m.contents\n\t\t\t\t// proposedDay = correctedDay\n\t\t\t\t// ticker.Stop()\n\t\t\t\t// roundTicker.Stop()\n\n\t\t\t\t// ps.BroadcastSwarmUpdate(SwarmUpdate{id, proposedDay, 1})\n\t\t\t\t// // gossip new-day\n\t\t\t\t// m := Message{}\n\t\t\t\t// m.from = id\n\t\t\t\t// m.name = \"new-day\"\n\t\t\t\t// m.contents = correctedDay\n\t\t\t\t// sn.Broadcast(m)\n\n\t\t\t\t// // check if we crashed...\n\t\t\t\t// if rand.Float64() < sn.crashProbability {\n\t\t\t\t// \t// edge failure\n\t\t\t\t// \tstate_crashed = true\n\t\t\t\t// \t// recover after 1 second for now\n\t\t\t\t// \tG := time.Duration(1000) * time.Millisecond\n\t\t\t\t// \tcrashRecoveryT := time.NewTimer(G)\n\t\t\t\t// \tcrashRecovery = crashRecoveryT.C\n\t\t\t\t// \tbreak\n\t\t\t\t// }\n\n\t\t\t\t// // check if new D or dynamic skew\n\t\t\t\t// dur := sn.configDayMS + int(rand.NormFloat64()*float64(sn.configDaySkewStdDev))\n\t\t\t\t// dur = dur + int(rand.NormFloat64()*float64(sn.configEveryDaySkewStdDev))\n\t\t\t\t// if dur < 1 {\n\t\t\t\t// \tdur = 1\n\t\t\t\t// }\n\t\t\t\t// D = time.Duration(dur) * time.Millisecond\n\t\t\t\t// ticker = time.NewTicker(D)\n\t\t\t\t// roundTicker = time.NewTicker(roundDMS)\n\t\t\t\t// prevDur = dur\n\t\t\t}\n\t\tcase <-pinkslip:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (b *OGame) BuyOfferOfTheDay() error {\n\treturn b.WithPriority(taskRunner.Normal).BuyOfferOfTheDay()\n}", "func (s *Runservice) etcdPingerLoop(ctx context.Context) {\n\tfor {\n\t\tif err := s.etcdPinger(ctx); err != nil {\n\t\t\tlog.Errorf(\"err: %+v\", err)\n\t\t}\n\n\t\tsleepCh := time.NewTimer(1 * time.Second).C\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-sleepCh:\n\t\t}\n\t}\n}", "func (b *TestDriver) Halt() (err error) {\n\tlog.Println(\"Halt Drone\")\n\tb.Land()\n\n\ttime.Sleep(500 * time.Millisecond)\n\treturn\n}", "func main() {\n\trand.Seed(time.Now().UnixNano())\n\n\tnumTourists := 25\n\tmaxOnline := 8\n\n\tvar wg sync.WaitGroup\n\twg.Add(numTourists)\n\n\tdone := make(chan interface{}, maxOnline)\n\tdefer close(done)\n\n\tonline := func(done chan interface{}, wg *sync.WaitGroup, i int) {\n\t\tkv := make(map[int]int, 1)\n\tloop:\n\t\tselect {\n\t\tcase done <- i:\n\t\t\tlog.Printf(\"Tourist %d is online.\\n\", i)\n\t\t\tduration := 5 + rand.Intn(10)\n\t\t\ttime.Sleep(time.Duration(duration) * time.Second)\n\t\t\tlog.Printf(\"Tourist %d is done, having spent %d seconds online.\\n\", i, duration)\n\t\t\t<-done\n\t\t\twg.Done()\n\t\tdefault:\n\t\t\t_, ok := kv[i]\n\t\t\tif !ok {\n\t\t\t\tkv[i] = i\n\t\t\t\tlog.Printf(\"Tourist %d waiting for turn.\\n\", i)\n\t\t\t}\n\t\t\tgoto loop\n\t\t}\n\n\t}\n\n\tfor i := 0; i < numTourists; i++ {\n\t\tgo online(done, &wg, i+1)\n\t}\n\n\twg.Wait()\n\n\tlog.Println(\"The place is empty, let's close up and go to the beach!\")\n}", "func (r *RaftNode) doFollower() stateFunction {\n\n\tr.initFollowerState()\n\n\t// election timer for handling going into candidate state\n\telectionTimer := r.randomTimeout(r.config.ElectionTimeout)\n\n\tfor {\n\t\tselect {\n\t\tcase shutdown := <-r.gracefulExit:\n\t\t\tif shutdown {\n\t\t\t\tr.Out(\"Shutting down\")\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\tcase <-electionTimer:\n\t\t\t// if we timeout with no appendEntries heartbeats,\n\t\t\t// start election with this node\n\t\t\tr.Out(\"Election timeout\")\n\n\t\t\t// for debugging purposes:\n\t\t\tif r.debugCond != nil {\n\t\t\t\tr.debugCond.L.Lock()\n\t\t\t\tr.Out(\"Waiting for broadcast...\")\n\t\t\t\tr.debugCond.Wait()\n\t\t\t\tr.debugCond.L.Unlock()\n\t\t\t}\n\n\t\t\treturn r.doCandidate\n\n\t\tcase msg := <-r.requestVote:\n\t\t\tif votedFor, _ := r.handleRequestVote(msg); votedFor {\n\t\t\t\t// reset timeout if voted so not all (non-candidate-worthy) nodes become candidates at once\n\t\t\t\tr.Debug(\"Election timeout reset\")\n\t\t\t\telectionTimer = r.randomTimeout(r.config.ElectionTimeout)\n\t\t\t}\n\t\tcase msg := <-r.appendEntries:\n\t\t\tif resetTimeout, _ := r.handleAppendEntries(msg); resetTimeout {\n\t\t\t\telectionTimer = r.randomTimeout(r.config.ElectionTimeout)\n\t\t\t}\n\t\tcase msg := <-r.registerClient:\n\t\t\tr.Out(\"RegisterClient received\")\n\t\t\tr.handleRegisterClientAsNonLeader(msg)\n\n\t\tcase msg := <-r.clientRequest:\n\t\t\tr.handleClientRequestAsNonLeader(msg)\n\t\t}\n\t}\n}", "func (s *BaseDiceListener) ExitDic(ctx *DicContext) {}", "func (diner *Diner) Dine(round uint) {\n\t// simple function to decide if we are lying this round\n\tisLiar := diner.isLiar(round)\n\n\t// our \"coin flip\"\n\tmyCoin := utils.NextBool()\n\tlog.Debug(\"Round: %v, Diner: %v, Coin: %v\", round, diner.id, myCoin)\n\n\tlog.Debug(\"%v Sending to right: %v\", diner, myCoin)\n\n\t// send the value to our right channel\n\tdiner.rightChannel <- myCoin\n\n\tlog.Debug(\"%v Receiving from left\", diner)\n\n\t// and wait for our left channel to tell us their value\n\tleftCoin := <-diner.leftChannel\n\n\tlog.Debug(\"%v Received: %v\", diner, leftCoin)\n\tlog.Debug(\"%v Comparing mine %v to left's %v\", diner, myCoin, leftCoin)\n\n\t// do we have the same values?\n\tisDifferent := utils.XOR(leftCoin, myCoin)\n\n\t// let's assume we aren't lying\n\tvalueToSend := isDifferent\n\n\t// however if we are, let's flip our valueToSend\n\tif isLiar {\n\t\tvalueToSend = !valueToSend\n\t}\n\n\tlog.Debug(\"%v, isLiar: %v, isDifferent: %v, valueToSend: %v\", diner, isLiar, isDifferent, valueToSend)\n\n\t// let our observer know what our value is\n\tdiner.observerChannel <- common.ObserverMessage{valueToSend, diner.id}\n\tdiner.resultChannel <- common.RoundResult{\n\t\tIsDifferent: valueToSend,\n\t\tDinerId: diner.id,\n\t\tCoinValue: myCoin}\n\t// and let the logs know we finished this course\n\tlog.Debug(\"Diner %v finished round: %v\", diner.id, round)\n}", "func timeOutHandler() {\n\n\tticket := time.NewTicker(time.Millisecond * 50)\n\tfor {\n\t\tselect {\n\t\tcase <-ticket.C:\n\t\t\tif time.Now().UnixNano()-aliveTimer.UnixNano() > 1e6*320 {\n\t\t\t\tlginfo.Flag = 0\n\t\t\t\tlginfo.Ibreak = 153\n\t\t\t\tfmt.Println(\"Connect to server side timeout\")\n\t\t\t\t// 300ms no reply then shutdown\n\t\t\t} else {\n\t\t\t\t//fmt.Println(\"i am alive\")\n\t\t\t}\n\t\t}\n\t}\n}", "func (e *Engine) GoPonder() {\n\tif atomic.CompareAndSwapInt32(&e.running, 0, 1) {\n\t\te.startNow(true)\n\t}\n}", "func Bye(from string) (string, error) {\n\treturn makeRequest(\"bye\", from)\n}", "func CreateDinner(date string, venue string, hostName string, attendeeNames []string) (model.Dinner, error) {\n\tdateTime, err := time.Parse(model.DateFormat, date)\n\tif err != nil {\n\t\treturn model.Dinner{}, err\n\t}\n\n\trow, err := database.InsertDinner(dateTime, venue, hostName)\n\tif err != nil {\n\t\treturn model.Dinner{}, err\n\t}\n\n\tdinner, err := model.NewDinnerFromMap(row)\n\tif err != nil {\n\t\treturn dinner, err\n\t}\n\n\tdinner.Attended, err = database.InsertGuests(dinner.ID, attendeeNames)\n\treturn dinner, err\n}", "func (n *Node) bye() bool {\n\tres, err := n.Talk(\"/bye/\"+n.Myself.toxstring(), true, nil)\n\tif err != nil {\n\t\tlog.Println(\"/bye\", n.Nodestr, \"error\")\n\t\treturn false\n\t}\n\treturn len(res) > 0 && (res[0] == \"BYEBYE\")\n}", "func (peer *Peer) heartbeat() {\n\tpeer.HeartbeatTicker = time.NewTicker(time.Second)\n\n\tfor {\n\t\t<-peer.HeartbeatTicker.C\n\n\t\t// Check For Defib\n\t\tif time.Now().After(peer.LastHeartbeat.Add(5 * time.Second)) {\n\t\t\tpeer.Logger.Warn(\"Peer\", \"%02X: Peer Defib (no response for >5 seconds)\", peer.ServerNetworkNode.ID)\n\t\t\tpeer.State = PeerStateDefib\n\t\t}\n\n\t\tswitch peer.State {\n\t\tcase PeerStateConnected:\n\t\t\terr := peer.SendPacket(packets.NewPacket(packets.CMD_HEARTBEAT, nil))\n\t\t\tif err != nil {\n\t\t\t\tpeer.Logger.Error(\"Peer\", \"%02X: Error Sending Heartbeat, disconnecting\", peer.ServerNetworkNode.ID)\n\t\t\t\tpeer.Disconnect()\n\t\t\t\treturn\n\t\t\t}\n\t\tcase PeerStateDefib:\n\t\t\tif time.Now().After(peer.LastHeartbeat.Add(10 * time.Second)) {\n\t\t\t\tpeer.Logger.Warn(\"Peer\", \"%02X: Peer DOA (Defib for 5 seconds), disconnecting\", peer.ServerNetworkNode.ID)\n\t\t\t\tpeer.Disconnect()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (pb *PhilosopherBase) Eat() {\n\n\tpb.State = philstate.Eating\n\tpb.StartEating()\n}", "func (rf *Raft) doLeader() {\n\tglog.Infof(\"%s Become leader\", rf)\n\n\trf.state.becomeLeader()\n\tpeerChs := make([]chan struct{}, len(rf.peers))\n\tdefer func() {\n\t\tglog.Infof(\"%s Before leader quit, notify all peers to quit\", rf)\n\t\tfor _, peerCh := range peerChs {\n\t\t\tclose(peerCh)\n\t\t}\n\t\tglog.Infof(\"%s Leader quit.\", rf)\n\t}()\n\n\tfor peer := range peerChs {\n\t\tpeerChs[peer] = make(chan struct{})\n\t\tgo rf.replicator(peer, peerChs[peer])\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-rf.termChangedCh:\n\t\t\treturn\n\t\tcase <-rf.shutdownCh:\n\t\t\treturn\n\t\tcase s := <-rf.appendEntriesCh:\n\t\t\trf.processAppendEntries(s)\n\t\tcase s := <-rf.requestVoteChan:\n\t\t\trf.processRequestVote(s)\n\t\tcase <-rf.submitedCh:\n\t\t\tdrainOut(rf.submitedCh)\n\t\t\t// fan-out to each peer\n\t\t\tfor _, peerCh := range peerChs {\n\t\t\t\tpeerCh <- struct{}{}\n\t\t\t}\n\t\t}\n\t}\n}", "func main() {\n\trand.Seed(time.Now().UnixNano())\n\tgconfig := Kiai.Connect(\"localhost:4000\", \"Easyfucka\", 1, 0) //Creates a variable with a GameConfig type. The output unit of connect function is Gameconfig which consists of multiple int data. Width,Height,MaxMoves,MaxFires,MaxHealth,PlayerCount,Timeout\n\tdefer Kiai.Disconnect() //Makes sure that at the end of the main function bot disconnects from server.\n\t\n\t\n\tfor {\n\t\tturn = Kiai.WaitForTurn() //Assigns the starting values of the wait for turn to turn variable.\n\t\t\n\t\tif start == false {\n\t\t\tfirstdecision(gconfig)\n\t\t}\n\t\t\n\t\tif iterate == maxiteration {\n\t\t\titerate = 0\n\t\t\tif path < 4 {\n\t\t\t\tpath += 1 \n\t\t\t} else {\n\t\t\t\tpath = 1\t\n\t\t\t}\t\t\n\t\t}\n\t\t\n\t\tif path == 1 { //This part is one of the four movement tactics that belong to a path. For all the moves left it directs the bot towards the corner and if corner is reached, it starts main offense.\n\t\t\t\n\t\t\tfor i := 0; i < turn.MovesLeft; i++ {\n\t\t\t\tfiring()\n\t\t\t\t\n\t\t\t\tif turn.X == 0 && turn.Y == 0 {\n\t\t\t\t\tmaintactic()\n\t\t\t\t\tbreak\n\t\t\t\t} else if turn.X != 0 && turn.Y != 0 {\n\t\t\t\t\tturn.Move(Kiai.NorthWest)\n\t\t\t\t} else if turn.X == 0 && turn.Y != 0 {\n\t\t\t\t\tturn.Move(Kiai.North)\n\t\t\t\t} else if turn.X != 0 && turn.Y == 0 {\n\t\t\t\t\tturn.Move(Kiai.West)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif path == 2 {\n\t\t\t\n\t\t\tfor i := 0; i < turn.MovesLeft; i++ {\n\t\t\t\tfiring()\n\t\t\t\t\n\t\t\t\tif turn.X == gconfig.Width-1 && turn.Y == 0 {\n\t\t\t\t\tmaintactic()\n\t\t\t\t\tbreak\n\t\t\t\t} else if turn.X != gconfig.Width-1 && turn.Y != 0 {\n\t\t\t\t\tturn.Move(Kiai.NorthEast)\n\t\t\t\t} else if turn.X == gconfig.Width-1 && turn.Y != 0 {\n\t\t\t\t\tturn.Move(Kiai.North)\n\t\t\t\t} else if turn.X != gconfig.Width-1 && turn.Y == 0 {\n\t\t\t\t\tturn.Move(Kiai.East)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif path == 3 {\n\t\t\t\n\t\t\tfor i := 0; i < turn.MovesLeft; i++ {\n\t\t\t\tfiring()\n\t\t\t\t\n\t\t\t\tif turn.X == gconfig.Width-1 && turn.Y == gconfig.Height-1 {\n\t\t\t\t\tmaintactic()\n\t\t\t\t\tbreak\n\t\t\t\t} else if turn.X != gconfig.Width-1 && turn.Y != gconfig.Height-1 {\n\t\t\t\t\tturn.Move(Kiai.SouthEast)\n\t\t\t\t} else if turn.X == gconfig.Width-1 && turn.Y != gconfig.Height-1 {\n\t\t\t\t\tturn.Move(Kiai.South)\n\t\t\t\t} else if turn.X != gconfig.Width-1 && turn.Y == gconfig.Height-1 {\n\t\t\t\t\tturn.Move(Kiai.East)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif path == 4 {\n\t\t\t\n\t\t\tfor i := 0; i < turn.MovesLeft; i++ {\n\t\t\t\tfiring()\n\t\t\t\t\n\t\t\t\tif turn.X == 0 && turn.Y == gconfig.Height-1 {\n\t\t\t\t\tmaintactic()\n\t\t\t\t\tbreak\n\t\t\t\t} else if turn.X != 0 && turn.Y != gconfig.Height-1 {\n\t\t\t\t\tturn.Move(Kiai.SouthWest)\n\t\t\t\t} else if turn.X == 0 && turn.Y != gconfig.Height-1 {\n\t\t\t\t\tturn.Move(Kiai.South)\n\t\t\t\t} else if turn.X != 0 && turn.Y == gconfig.Height-1 {\n\t\t\t\t\tturn.Move(Kiai.West)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n//This section just shoots randomly towards the middle of the board at the last move if someone is not seen around.\n\t\n\t\tif path == 1 {\n\t\t\tif turn.Y == 0 {\n\t\t\t\tturn.Fire(Kiai.SouthEast)\n\t\t\t} else {\n\t\t\t\tturn.Fire(Kiai.East)\n\t\t\t}\t \n\t\t} \n\t\t\n\t\tif path == 2 {\n\t\t\tif turn.X == gconfig.Width - 1 {\n\t\t\t\tturn.Fire(Kiai.SouthWest)\n\t\t\t} else {\n\t\t\t\tturn.Fire(Kiai.South)\n\t\t\t}\t\t\n\t\t}\n\t\t\n\t\tif path == 3 {\n\t\t\tif turn.Y == gconfig.Height - 1 {\n\t\t\t\tturn.Fire(Kiai.NorthWest)\n\t\t\t} else {\n\t\t\t\tturn.Fire(Kiai.West)\n\t\t\t}\n\t\t}\n\t\t\n\t\tif path == 4 {\n\t\t\tif turn.X == 0 {\n\t\t\t\tturn.Fire(Kiai.NorthEast)\n\t\t\t} else {\n\t\t\t\tturn.Fire(Kiai.North)\n\t\t\t}\n\t\t}\n\t\t\n\t\titerate += 1\n\t\tKiai.EndTurn()\n\t}\n}", "func distributeFood() {\n\n\tfor {\n\t\tselect {\n\t\tcase food := <-FoodChan:\n\t\t\tif pickCook(food) == false {\n\t\t\t\tFoodChan <- food\n\t\t\t}\n\t\tdefault:\n\t\t}\n\t}\n}", "func handlePongs(done chan bool, outFileName string) {\n\n\tvar liveHosts[] string\n\n\t// CATCH ALL RESPONSES\n\tfor pong := range pongs{\n\n\t\tif pong.Alive == true {\n\t\t\tDebug(\"Host \" + pong.IP + \" is alive!\")\n\t\t\tliveHosts = append(liveHosts, pong.IP)\n\t\t}\n\t\tif pong.Error != nil {\n\t\t} else if pong.Alive == false {\n\t\t\t//Debug(\"Host \" + pong.IP + \" is dead!\")\n\t\t}\n\t}\n\n\t// WRITE TO OUTPUT FILE\n\twriteLiveHosts(liveHosts, outFileName)\n\tdone <- true\n\t\n}", "func (d *dispatcher) bot() {\n\tgo func() {\n\t\t// run infinite loop waiting every second\n\t\tfor {\n\t\t\td.mu.Lock()\n\t\t\td.dispatch()\n\t\t\td.mu.Unlock()\n\t\t\tselect {\n\t\t\tcase <-d.poke:\n\t\t\tcase <-time.After(time.Second):\n\t\t\t}\n\t\t}\n\t}()\n}", "func (s *Server) Drain() {\n\ts.waitgroup.Wait()\n\tlog.Print(\"SSH server connections drained\")\n}", "func (sv *Server) AdvanceUntil(done chan int) {\n\tfor _, ok := <-done; !ok; _, ok = <-done {\n\t\tsv.Mg.Propose(store.Nop)\n\t}\n}", "func (w *Worker) Die() {\n\tw.Swarm.Kill(w)\n}", "func (r *Node) doCandidate() stateFunction {\n\tr.Out(\"Transitioning to CandidateState\")\n\tr.State = CandidateState\n\n\t// Foollowing &5.2\n\t// Increment currentTerm\n\tr.setCurrentTerm(r.GetCurrentTerm() + 1)\n\t// Vote for self\n\tr.setVotedFor(r.Self.GetId())\n\t// Reset election timer\n\ttimeout := randomTimeout(r.config.ElectionTimeout)\n\telectionResults := make(chan bool)\n\tfallbackChan := make(chan bool)\n\tgo r.requestVotes(electionResults, fallbackChan, r.GetCurrentTerm())\n\tfor {\n\t\tselect {\n\t\tcase shutdown := <-r.gracefulExit:\n\t\t\tif shutdown {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\tcase clientMsg := <-r.clientRequest:\n\t\t\tclientMsg.reply <- rpc.ClientReply{\n\t\t\t\tStatus: rpc.ClientStatus_ELECTION_IN_PROGRESS,\n\t\t\t\tResponse: nil,\n\t\t\t\tLeaderHint: r.Self,\n\t\t\t}\n\n\t\tcase registerMsg := <-r.registerClient:\n\t\t\tregisterMsg.reply <- rpc.RegisterClientReply{\n\t\t\t\tStatus: rpc.ClientStatus_ELECTION_IN_PROGRESS,\n\t\t\t\tClientId: 0,\n\t\t\t\tLeaderHint: r.Self,\n\t\t\t}\n\n\t\tcase voteMsg := <-r.requestVote:\n\t\t\tif r.handleCompetingRequestVote(voteMsg) {\n\t\t\t\treturn r.doFollower\n\t\t\t}\n\n\t\tcase appendMsg := <-r.appendEntries:\n\t\t\t_, toFollower := r.handleAppendEntries(appendMsg)\n\t\t\tif toFollower {\n\t\t\t\treturn r.doFollower\n\t\t\t}\n\n\t\tcase elected := <-electionResults:\n\t\t\tif elected {\n\t\t\t\treturn r.doLeader\n\t\t\t}\n\n\t\tcase toFollower := <-fallbackChan:\n\t\t\tif toFollower {\n\t\t\t\treturn r.doFollower\n\t\t\t}\n\n\t\tcase <-timeout:\n\t\t\treturn r.doCandidate\n\t\t}\n\t}\n}", "func (host *DinnerHost) AllowEating(name string) string {\n\tif host.currentlyEating >= host.maxParallel {\n\t\treturn \"E:FULL\"\n\t}\n\n\tdata := host.phiData[name]\n\n\tcanEat := data.CanEat(host.maxDinner)\n\tif canEat != \"OK\" {\n\t\treturn canEat\n\t}\n\n\tseatNumber := data.Seat()\n\tleftChop := seatNumber\n\trightChop := (seatNumber + 1) % host.tableCount\n\n\tif host.chopsticksFree[leftChop] {\n\t\thost.chopsticksFree[leftChop] = false\n\t\tdata.SetLeftChop(leftChop)\n\t}\n\tif host.chopsticksFree[rightChop] {\n\t\thost.chopsticksFree[rightChop] = false\n\t\tdata.SetRightChop(rightChop)\n\t}\n\n\tif !data.HasBothChopsticks() {\n\t\treturn \"E:CHOPSTICKS\"\n\t}\n\n\thost.currentlyEating++\n\tdata.StartedEating()\n\n\treturn \"OK\"\n}", "func (bc *BotConnection) pingpong() {\n\tdefer func() {\n\t\tlog.Println(\" pingpong: dying\")\n\t\tbc.waitGroup.Done()\n\t}()\n\n\t// Send first ping to avoid early EOF:\n\tping := struct {\n\t\tType string `json:\"type\"`\n\t}{\n\t\tType: \"ping\",\n\t}\n\terr := websocket.JSON.Send(bc.ws, &ping)\n\tif err != nil {\n\t\tlog.Printf(\" pingpong: JSON send error: %s\\n\", err)\n\t}\n\n\t// Start a timer to tick every 15 seconds:\n\tticker := time.Tick(time.Second * 15)\n\n\talive := true\n\tfor alive {\n\t\t// Wait on either the timer tick or the `die` channel:\n\t\tselect {\n\t\tcase _ = <-ticker:\n\t\t\t//log.Println(\" pingpong: ping\")\n\t\t\terr = websocket.JSON.Send(bc.ws, &ping)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\" pingpong: JSON send error: %s\\n\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// NOTE: `readIncomingMessages` will read the \"pong\" response.\n\t\t\t// Cannot issue a read here because a read is already blocking there.\n\t\t\tbreak\n\t\tcase _ = <-bc.die:\n\t\t\talive = false\n\t\t\tbreak\n\t\t}\n\t}\n}", "func testDataTransfer(t *testing.T, opts dataTransferOpts) {\n\tseeder, seederTr := newClientWithTorrent(t, testingConfig(), helloWorldTorrentFile, func(tr *Torrent) {\n\t\tassert.True(t, tr.haveAll())\n\t\trequire.NoError(t, tr.StartDataTransfer())\n\t})\n\tdefer seeder.Close()\n\t//create leechers\n\tleechers := make([]*Client, opts.numLeechers)\n\tleechAddrs := make([]string, len(leechers))\n\tfor i := range leechers {\n\t\ttcfg := testingConfig()\n\t\ttcfg.BaseDir += \"/leecher\" + strconv.Itoa(i)\n\t\tleechers[i], _ = newClientWithTorrent(t, tcfg, helloWorldTorrentFile, nil)\n\t\tleechAddrs[i] = leechers[i].addr()\n\t\tdefer leechers[i].Close()\n\t\tdefer os.RemoveAll(tcfg.BaseDir)\n\t}\n\twg := sync.WaitGroup{}\n\twg.Add(len(leechers))\n\tfor i, leecher := range leechers {\n\t\tleecherTr := leecher.Torrents()[0]\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\trequire.NoError(t, leecherTr.StartDataTransfer())\n\t\t\t<-leecherTr.DownloadedDataC\n\t\t}()\n\t\tleecherTr.AddPeers(addrsToPeers(append(leechAddrs[i+1:], seeder.addr()))...)\n\t}\n\t/*ticker := time.NewTicker(time.Second)\n\tfor {\n\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tfmt.Println(\"----------- leeecher ------------\")\n\t\t\tleechers[0].counters.Do(func(kv expvar.KeyValue) {\n\t\t\t\tfmt.Println(kv)\n\t\t\t})\n\t\t\tfmt.Println(\"----------- seederr ------------\")\n\t\t\tseeder.counters.Do(func(kv expvar.KeyValue) {\n\t\t\t\tfmt.Println(kv)\n\t\t\t})\n\t\t\tfor _, p := range leechers[0].Torrents()[0].Pieces() {\n\t\t\t\tif p.Verified() {\n\t\t\t\t\tfmt.Println(p.Index())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}*/\n\t//load seeder data\n\tdataSeeder := make([]byte, seederTr.length)\n\terr := seederTr.readBlock(dataSeeder, 0, 0)\n\trequire.NoError(t, err)\n\twg.Wait()\n\tfor _, leecher := range leechers {\n\t\tleecherTr := leecher.Torrents()[0]\n\t\tassert.True(t, leecherTr.haveAll())\n\t\ttestContents(t, dataSeeder, leecherTr)\n\t}\n}", "func (s *raftServer) lead() {\n\ts.hbTimeout.Reset(time.Duration(s.config.HbTimeoutInMillis) * time.Millisecond)\n\t// launch a goroutine to handle followersFormatInt(\n\tfollower := s.followers()\n\tnextIndex, matchIndex, aeToken := s.initLeader(follower)\n\ts.leaderId.Set(s.server.Pid())\n\n\tgo s.handleFollowers(follower, nextIndex, matchIndex, aeToken)\n\tgo s.updateLeaderCommitIndex(follower, matchIndex)\n\tfor s.State() == LEADER {\n\t\tselect {\n\t\tcase <-s.hbTimeout.C:\n\t\t\t//s.writeToLog(\"Sending hearbeats\")\n\t\t\ts.sendHeartBeat()\n\t\t\ts.hbTimeout.Reset(time.Duration(s.config.HbTimeoutInMillis) * time.Millisecond)\n\t\tcase msg := <-s.outbox:\n\t\t\t// received message from state machine\n\t\t\ts.writeToLog(\"Received message from state machine layer\")\n\t\t\ts.localLog.Append(&raft.LogEntry{Term: s.Term(), Data: msg})\n\t\tcase e := <-s.server.Inbox():\n\t\t\traftMsg := e.Msg\n\t\t\tif ae, ok := raftMsg.(AppendEntry); ok { // AppendEntry\n\t\t\t\ts.handleAppendEntry(e.Pid, &ae)\n\t\t\t} else if rv, ok := raftMsg.(RequestVote); ok { // RequestVote\n\t\t\t\ts.handleRequestVote(e.Pid, &rv)\n\t\t\t} else if entryReply, ok := raftMsg.(EntryReply); ok {\n\t\t\t\tn, found := nextIndex.Get(e.Pid)\n\t\t\t\tvar m int64\n\t\t\t\tif !found {\n\t\t\t\t\tpanic(\"Next index not found for follower \" + strconv.Itoa(e.Pid))\n\t\t\t\t} else {\n\t\t\t\t\tm, found = matchIndex.Get(e.Pid)\n\t\t\t\t\tif !found {\n\t\t\t\t\t\tpanic(\"Match index not found for follower \" + strconv.Itoa(e.Pid))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif entryReply.Success {\n\t\t\t\t\t// update nextIndex for follower\n\t\t\t\t\tif entryReply.LogIndex != HEARTBEAT {\n\t\t\t\t\t\taeToken.Set(e.Pid, 1)\n\t\t\t\t\t\tnextIndex.Set(e.Pid, max(n+1, entryReply.LogIndex+1))\n\t\t\t\t\t\tmatchIndex.Set(e.Pid, max(m, entryReply.LogIndex))\n\t\t\t\t\t\t//s.writeToLog(\"Received confirmation from \" + strconv.Itoa(e.Pid))\n\t\t\t\t\t}\n\t\t\t\t} else if s.Term() >= entryReply.Term {\n\t\t\t\t\tnextIndex.Set(e.Pid, n-1)\n\t\t\t\t} else {\n\t\t\t\t\ts.setState(FOLLOWER)\n\t\t\t\t\t// There are no other goroutines active\n\t\t\t\t\t// at this point which modify term\n\t\t\t\t\tif s.Term() >= entryReply.Term {\n\t\t\t\t\t\tpanic(\"Follower replied false even when Leader's term is not smaller\")\n\t\t\t\t\t}\n\t\t\t\t\ts.setTerm(entryReply.Term)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\ts.hbTimeout.Stop()\n}", "func (s *Stealer) Go(ctx context.Context, e *reflow.Eval) {\n\tticker := time.NewTicker(pollInterval)\n\tdefer ticker.Stop()\n\tvar n int\npoll:\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tneed := e.Need()\n\t\t\tif need.IsZero() {\n\t\t\t\tcontinue poll\n\t\t\t}\n\t\t\tn++\n\t\t\ts.Log.Debugf(\"need %v; starting new task stealing worker\", need)\n\t\t\tactx, acancel := context.WithTimeout(ctx, allocTimeout)\n\t\t\talloc, err := s.Cluster.Allocate(actx, need, s.Labels)\n\t\t\tacancel()\n\t\t\tif err != nil {\n\t\t\t\tcontinue poll\n\t\t\t}\n\t\t\tw := &worker{\n\t\t\t\tExecutor: alloc,\n\t\t\t\tEval: e,\n\t\t\t\tLog: s.Log.Tee(nil, alloc.ID()+\": \"),\n\t\t\t}\n\t\t\twctx, wcancel := context.WithCancel(ctx)\n\t\t\tgo func() {\n\t\t\t\terr := pool.Keepalive(wctx, s.Log, alloc)\n\t\t\t\tif err != wctx.Err() {\n\t\t\t\t\ts.Log.Errorf(\"worker %s died: %v\", alloc.ID(), err)\n\t\t\t\t}\n\t\t\t\twcancel()\n\t\t\t}()\n\t\t\tgo func() {\n\t\t\t\tw.Go(wctx)\n\t\t\t\twcancel()\n\t\t\t\talloc.Free(context.Background())\n\t\t\t}()\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func (notifee *Notifee) Disconnected(net network.Network, conn network.Conn) {\n\n\tnotifee.logger.Info().Msgf(\n\t\t\"Disconnected from peer %s\",\n\t\tconn.RemotePeer().Pretty(),\n\t)\n\tpinfo := notifee.myRelayPeer\n\tif conn.RemotePeer().Pretty() != pinfo.ID.Pretty() {\n\t\treturn\n\t}\n\n\tnotifee.myHost.Peerstore().AddAddrs(pinfo.ID, pinfo.Addrs, peerstore.PermanentAddrTTL)\n\tfor {\n\t\tvar err error\n\t\tselect {\n\t\tcase _, open := <-notifee.closing:\n\t\t\tif !open {\n\t\t\t\treturn\n\t\t\t}\n\t\tdefault:\n\t\t\tnotifee.logger.Warn().Msgf(\n\t\t\t\t\"Lost connection to relay peer %s, reconnecting...\",\n\t\t\t\tpinfo.ID.Pretty(),\n\t\t\t)\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), reconnectTimeout)\n\t\t\tdefer cancel()\n\t\t\tif err = notifee.myHost.Connect(ctx, pinfo); err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(1 * time.Second)\n\n\t\t}\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tnotifee.logger.Info().Msgf(\"Connection to relay peer %s reestablished\", pinfo.ID.Pretty())\n}", "func (philo philO) eat(maxeat chan string) {\n\tfor x := 0; x < 3; x++ {\n\t\tmaxeat <- philo.id\n\t\tphilo.meals++\n\t\tphilo.first.Lock()\n\t\tphilo.second.Lock()\n\t\tfmt.Printf(\"Philosopher #%s is eating a meal of rice\\n\", philo.id)\n\t\tphilo.first.Unlock()\n\t\tphilo.second.Unlock()\n\t\tfmt.Printf(\"Philosopher #%s is done eating a meal of rice\\n\", philo.id)\n\t\t<-maxeat\n\t\tif philo.meals == 3 {\n\t\t\tfmt.Printf(\"Philosopher #%s is finished eating!!!!!!\\n\", philo.id)\n\t\t}\n\t}\n}", "func (pd *philosopherData) StartedEating() {\n\tpd.eating = true\n\tpd.dinnersSpent++\n}", "func (p *RoundRobin) Run(ctx context.Context) {\n\tnotify := p.GetNotifier()\n\n\t// initial beat\n\tif p.getLeader(1) == p.GetID() {\n\t\tgo p.Propose()\n\t}\n\n\t// get initial notification\n\tn := <-notify\n\n\t// make sure that we only beat once per view, and don't beat if bLeaf.Height < vHeight\n\t// as that would cause a panic\n\tlastBeat := 1\n\tbeat := func() {\n\t\tif p.getLeader(p.GetHeight()+1) == p.GetID() && lastBeat < p.GetHeight()+1 &&\n\t\t\tp.GetHeight()+1 > p.GetVotedHeight() {\n\t\t\tlastBeat = p.GetHeight() + 1\n\t\t\tgo p.Propose()\n\t\t}\n\t}\n\n\t// set up new-view interrupt\n\tstopContext, cancel := context.WithCancel(context.Background())\n\tp.stopTimeout = cancel\n\tgo p.startNewViewTimeout(stopContext)\n\tdefer p.stopTimeout()\n\n\t// handle events from hotstuff\n\tfor {\n\t\tswitch n.Event {\n\t\tcase hotstuff.ReceiveProposal:\n\t\t\tp.resetTimer <- struct{}{}\n\t\tcase hotstuff.QCFinish:\n\t\t\tif p.GetID() != p.getLeader(p.GetHeight()+1) {\n\t\t\t\t// was leader for previous view, but not the leader for next view\n\t\t\t\t// do leader change\n\t\t\t\tgo p.SendNewView(p.getLeader(p.GetHeight() + 1))\n\t\t\t}\n\t\t\tbeat()\n\t\tcase hotstuff.ReceiveNewView:\n\t\t\tbeat()\n\t\t}\n\n\t\tvar ok bool\n\t\tselect {\n\t\tcase n, ok = <-notify:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func energyGiveout() {\n\tsetNextGiveoutTime()\n\tfor {\n\t\tif time.Now().Sub(nextGiveoutTime).Seconds() >= 0 {\n\t\t\tsetNextGiveoutTime()\n\t\t\tusers.EnergyGiveout()\n\t\t\tinsertOrUpdateUser(users.GetAllUsers()...)\n\t\t}\n\t\ttime.Sleep(time.Minute)\n\t}\n}", "func lesson56(){\n\ttick := time.Tick(100 * time.Microsecond)\n\tboom := time.After(500 * time.Microsecond)\n\t\n\tfor {\n\t\tselect {\n\t\t\tcase <- tick:\n\t\t\t\tfmt.Println(\"tick.\")\n\t\t\tcase <- boom:\n\t\t\t\tfmt.Println(\"BOOM!\")\n\t\t\t\t//break ここでbreakしてもforからは抜けない\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\" .\")\n\t\t\t\ttime.Sleep(50 * time.Microsecond)\n\t\t}\n\t}\n}", "func (joinSession *JoinSession) run() {\n\tvar allPkScripts [][]byte\n\tmissedPeers := make([]uint32, 0)\n\tvar errm error\n\t// Stop round timer\n\tdefer joinSession.roundTimeout.Stop()\nLOOP:\n\tfor {\n\t\tif len(joinSession.Peers) == 0 {\n\t\t\tlog.Infof(\"No peer connected, session %d terminates.\", joinSession.Id)\n\t\t\treturn\n\t\t}\n\t\tselect {\n\t\tcase <-joinSession.roundTimeout.C:\n\t\t\tjoinSession.mu.Lock()\n\t\t\tlog.Info(\"Timeout.\")\n\t\t\t// We use timer to control whether peers send data of round in time.\n\t\t\t// With one round of the join session, server waits maximum time\n\t\t\t// for client process is 60 seconds (setting in config file).\n\t\t\t// After that time, client still not send data,\n\t\t\t// server will consider the client is malicious and remove from the join session.\n\t\t\tfor _, peer := range joinSession.Peers {\n\t\t\t\tswitch joinSession.State {\n\t\t\t\tcase StateKeyExchange:\n\t\t\t\t\t// With state key exchange, we do not need to inform other peers,\n\t\t\t\t\t// just remove and ignore this peer.\n\t\t\t\t\tif len(peer.Pk) == 0 {\n\t\t\t\t\t\tmissedPeers = append(missedPeers, peer.Id)\n\t\t\t\t\t\t//joinSession.removePeer(peer.Id)\n\t\t\t\t\t\tlog.Infof(\"Peer id %v did not send key exchange data in time\", peer.Id)\n\t\t\t\t\t}\n\t\t\t\tcase StateDcExponential:\n\t\t\t\t\t// From this state, when one peer is malicious and terminated,\n\t\t\t\t\t// the join session has to restarted from the beginning.\n\t\t\t\t\tif len(peer.DcExpVector) == 0 {\n\t\t\t\t\t\tmissedPeers = append(missedPeers, peer.Id)\n\t\t\t\t\t\tlog.Infof(\"Peer id %v did not send dc-net exponential data in time\", peer.Id)\n\t\t\t\t\t}\n\t\t\t\tcase StateDcXor:\n\t\t\t\t\tif len(peer.DcExpVector) == 0 {\n\t\t\t\t\t\tmissedPeers = append(missedPeers, peer.Id)\n\t\t\t\t\t\tlog.Infof(\"Peer id %v did not send dc-net xor data in time\", peer.Id)\n\t\t\t\t\t}\n\t\t\t\tcase StateTxInput:\n\t\t\t\t\tif peer.TxIns == nil {\n\t\t\t\t\t\tmissedPeers = append(missedPeers, peer.Id)\n\t\t\t\t\t\tlog.Infof(\"Peer id %v did not send transaction input data in time\", peer.Id)\n\t\t\t\t\t}\n\t\t\t\tcase StateTxSign:\n\t\t\t\t\tif peer.SignedTx == nil {\n\t\t\t\t\t\tmissedPeers = append(missedPeers, peer.Id)\n\t\t\t\t\t\tlog.Infof(\"Peer id %v did not send signed transaction data in time\", peer.Id)\n\t\t\t\t\t}\n\t\t\t\tcase StateTxPublish:\n\t\t\t\t\tif joinSession.Publisher == peer.Id {\n\t\t\t\t\t\tlog.Infof(\"Peer id %v did not send the published transaction data in time\", peer.Id)\n\t\t\t\t\t\tjoinSession.removePeer(peer.Id)\n\n\t\t\t\t\t\tif len(joinSession.Peers) == 0 {\n\t\t\t\t\t\t\tlog.Infof(\"No peer connected, session %d terminates.\", joinSession.Id)\n\t\t\t\t\t\t\tjoinSession.mu.Unlock()\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Select other peer to publish transaction.\n\t\t\t\t\t\tbuffTx := bytes.NewBuffer(nil)\n\t\t\t\t\t\tbuffTx.Grow(joinSession.JoinedTx.SerializeSize())\n\t\t\t\t\t\terr := joinSession.JoinedTx.BtcEncode(buffTx, 0)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlog.Errorf(\"Cannot execute BtcEncode: %v\", err)\n\t\t\t\t\t\t\tjoinSession.terminate()\n\t\t\t\t\t\t\tjoinSession.mu.Unlock()\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tjoinTx := &pb.JoinTx{}\n\t\t\t\t\t\tjoinTx.Tx = buffTx.Bytes()\n\t\t\t\t\t\tjoinTxData, err := proto.Marshal(joinTx)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlog.Errorf(\"Can not marshal signed transaction: %v\", err)\n\t\t\t\t\t\t\tlog.Infof(\"Session terminates fail\")\n\t\t\t\t\t\t\tjoinSession.terminate()\n\t\t\t\t\t\t\tjoinSession.mu.Unlock()\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tjoinTxMsg := messages.NewMessage(messages.S_TX_SIGN, joinTxData)\n\t\t\t\t\t\tpubId := joinSession.randomPublisher()\n\t\t\t\t\t\tjoinSession.Publisher = pubId\n\t\t\t\t\t\tpublisher := joinSession.Peers[pubId]\n\t\t\t\t\t\tpublisher.writeChan <- joinTxMsg.ToBytes()\n\t\t\t\t\t\tjoinSession.roundTimeout = time.NewTimer(time.Second * time.Duration(joinSession.Config.RoundTimeOut))\n\t\t\t\t\t}\n\t\t\t\tcase StateRevealSecret:\n\t\t\t\t\tif len(peer.Vk) == 0 {\n\t\t\t\t\t\tmissedPeers = append(missedPeers, peer.Id)\n\t\t\t\t\t\tlog.Infof(\"Peer id %d did not send secret key in time\", peer.Id)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Inform to remaining peers in join session.\n\t\t\tif len(missedPeers) > 0 {\n\t\t\t\tif joinSession.State == StateKeyExchange {\n\t\t\t\t\tfor _, id := range missedPeers {\n\t\t\t\t\t\tjoinSession.removePeer(id)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tjoinSession.pushMaliciousInfo(missedPeers)\n\t\t\t\t\t// Reset join session state.\n\t\t\t\t\tjoinSession.State = StateKeyExchange\n\t\t\t\t}\n\t\t\t}\n\t\t\tjoinSession.mu.Unlock()\n\t\tcase keyExchange := <-joinSession.keyExchangeChan:\n\t\t\tjoinSession.mu.Lock()\n\t\t\tpeer := joinSession.Peers[keyExchange.PeerId]\n\t\t\tif peer == nil {\n\t\t\t\tlog.Errorf(\"Can not find join session with peer id %d\", keyExchange.PeerId)\n\t\t\t\tjoinSession.mu.Unlock()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Validate public key and ignore peer if public key is not valid.\n\t\t\tecp256 := ecdh.NewEllipticECDH(elliptic.P256())\n\t\t\t_, valid := ecp256.Unmarshal(keyExchange.Pk)\n\t\t\tif !valid {\n\t\t\t\t// Public key is invalid\n\t\t\t\tjoinSession.removePeer(keyExchange.PeerId)\n\t\t\t\tjoinSession.mu.Unlock()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tpeer.Pk = keyExchange.Pk\n\t\t\tpeer.NumMsg = keyExchange.NumMsg\n\t\t\tjoinSession.PeersMsgInfo = append(joinSession.PeersMsgInfo, &pb.PeerInfo{PeerId: peer.Id, Pk: peer.Pk, NumMsg: keyExchange.NumMsg})\n\n\t\t\tlog.Debug(\"Received DH public key exchange request from peer\", peer.Id)\n\n\t\t\t// Broadcast to all peers when there are enough public keys.\n\t\t\tif len(joinSession.Peers) == len(joinSession.PeersMsgInfo) {\n\n\t\t\t\tlog.Debug(\"Received DH public key from all peers. Broadcasting all DH public keys to all peers.\")\n\t\t\t\tlog.Debug(\"Each peer will combine their DH private key with the other public keys to derive the random bytes.\")\n\t\t\t\tlog.Debug(\"Random bytes are being used to creating padding in the DC-net.\")\n\t\t\t\tkeyex := &pb.KeyExchangeRes{\n\t\t\t\t\tPeers: joinSession.PeersMsgInfo,\n\t\t\t\t}\n\n\t\t\t\tdata, err := proto.Marshal(keyex)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"Can not marshal keyexchange: %v\", err)\n\t\t\t\t\t// Public key is invalid\n\t\t\t\t\tjoinSession.removePeer(keyExchange.PeerId)\n\t\t\t\t\tjoinSession.mu.Unlock()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tmessage := messages.NewMessage(messages.S_KEY_EXCHANGE, data)\n\t\t\t\tfor _, p := range joinSession.Peers {\n\t\t\t\t\tp.writeChan <- message.ToBytes()\n\t\t\t\t}\n\t\t\t\tjoinSession.roundTimeout = time.NewTimer(time.Second * time.Duration(joinSession.Config.RoundTimeOut))\n\t\t\t\tjoinSession.State = StateDcExponential\n\t\t\t}\n\t\t\tjoinSession.mu.Unlock()\n\t\tcase data := <-joinSession.dcExpVectorChan:\n\t\t\tjoinSession.mu.Lock()\n\t\t\tpeerInfo := joinSession.Peers[data.PeerId]\n\t\t\tif peerInfo == nil {\n\t\t\t\tlog.Debug(\"joinSession does not include peerid\", data.PeerId)\n\t\t\t\tjoinSession.mu.Unlock()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(data.Vector) < messages.PkScriptHashSize*2 {\n\t\t\t\t// Invalid dcxor vector length.\n\t\t\t\tjoinSession.mu.Unlock()\n\t\t\t\tjoinSession.pushMaliciousInfo([]uint32{data.PeerId})\n\t\t\t\tbreak LOOP\n\t\t\t}\n\t\t\tvector := make([]field.Field, 0)\n\t\t\tfor i := 0; i < int(data.Len); i++ {\n\t\t\t\tb := data.Vector[i*messages.PkScriptHashSize : (i+1)*messages.PkScriptHashSize]\n\t\t\t\tff := field.NewFF(field.FromBytes(b))\n\t\t\t\t// Validate pkscript hash\n\t\t\t\tif ff.N.Compare(field.Uint128{0, 0}) == 0 {\n\t\t\t\t\terrMsg := fmt.Sprintf(\"Client %d submitted invalid pkscript hash %s\", peerInfo.Id, ff.HexStr())\n\t\t\t\t\terrm = errors.New(errMsg)\n\t\t\t\t\tlog.Warnf(errMsg)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tvector = append(vector, ff)\n\t\t\t\t//log.Debugf(\"Received dc-net exp vector %d - %x\", peerInfo.Id, b)\n\t\t\t}\n\t\t\tif errm != nil {\n\t\t\t\tjoinSession.mu.Unlock()\n\t\t\t\tjoinSession.pushMaliciousInfo([]uint32{peerInfo.Id})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tpeerInfo.DcExpVector = vector\n\t\t\tlog.Debug(\"Received dc-net exponential from peer\", peerInfo.Id)\n\t\t\tallSubmit := true\n\t\t\tfor _, peer := range joinSession.Peers {\n\t\t\t\tif len(peer.DcExpVector) == 0 {\n\t\t\t\t\tallSubmit = false\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If all peers sent dc-net exponential vector, we need combine (sum) with the same index of each peer.\n\t\t\t// The sum of all peers will remove padding bytes that each peer has added.\n\t\t\t// And this time, we will having the real power sum of all peers.\n\t\t\tif allSubmit {\n\t\t\t\tlog.Debug(\"All peers sent dc-net exponential vector. Combine dc-net exponential from all peers to remove padding\")\n\t\t\t\tpolyDegree := len(vector)\n\t\t\t\tdcCombine := make([]field.Field, polyDegree)\n\n\t\t\t\tfor _, peer := range joinSession.Peers {\n\t\t\t\t\tfor i := 0; i < len(peer.DcExpVector); i++ {\n\t\t\t\t\t\tdcCombine[i] = dcCombine[i].Add(peer.DcExpVector[i])\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// for _, ff := range dcCombine {\n\t\t\t\t// \tlog.Debug(\"Dc-combine:\", ff.N.HexStr())\n\t\t\t\t// }\n\t\t\t\tlog.Debug(\"Will use flint to resolve polynomial to get roots as hash of pkscript\")\n\n\t\t\t\tret, roots := flint.GetRoots(field.Prime.HexStr(), dcCombine, polyDegree)\n\t\t\t\tlog.Infof(\"Func returns: %d\", ret)\n\t\t\t\tlog.Infof(\"Number roots: %d\", len(roots))\n\t\t\t\tlog.Infof(\"Roots: %v\", roots)\n\n\t\t\t\t// Check whether the polynomial could be solved or not\n\t\t\t\tif ret != 0 {\n\t\t\t\t\t// Some peers may sent incorrect dc-net expopential vector.\n\t\t\t\t\t// Peers need to reveal their secrect key.\n\t\t\t\t\tmsg := messages.NewMessage(messages.S_REVEAL_SECRET, []byte{0x00})\n\t\t\t\t\tfor _, peer := range joinSession.Peers {\n\t\t\t\t\t\tpeer.writeChan <- msg.ToBytes()\n\t\t\t\t\t}\n\t\t\t\t\tjoinSession.mu.Unlock()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Send to all peers the roots resolved\n\t\t\t\tallMsgHash := make([]byte, 0)\n\t\t\t\tfor _, root := range roots {\n\t\t\t\t\tstr := fmt.Sprintf(\"%032v\", root)\n\t\t\t\t\tbytes, _ := hex.DecodeString(str)\n\n\t\t\t\t\t// Only get correct message size\n\t\t\t\t\tif len(bytes) == messages.PkScriptHashSize {\n\t\t\t\t\t\tallMsgHash = append(allMsgHash, bytes...)\n\t\t\t\t\t} else {\n\t\t\t\t\t\terrMsg := fmt.Sprintf(\"Got pkscript hash from flint with size %d - %x. This differs with default size: %d\",\n\t\t\t\t\t\t\tlen(bytes), bytes, messages.PkScriptHashSize)\n\t\t\t\t\t\tlog.Warnf(errMsg)\n\t\t\t\t\t\terrm = errors.New(errMsg)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif errm != nil {\n\t\t\t\t\tbreak LOOP\n\t\t\t\t}\n\n\t\t\t\tmsgData := &pb.AllMessages{}\n\t\t\t\tmsgData.Len = uint32(len(roots))\n\t\t\t\tmsgData.Msgs = allMsgHash\n\t\t\t\tdata, err := proto.Marshal(msgData)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"Can not marshal all messages data: %v\", err)\n\t\t\t\t\terrm = err\n\t\t\t\t\tbreak LOOP\n\t\t\t\t}\n\n\t\t\t\tmsg := messages.NewMessage(messages.S_DC_EXP_VECTOR, data)\n\t\t\t\tfor _, peer := range joinSession.Peers {\n\t\t\t\t\tpeer.writeChan <- msg.ToBytes()\n\t\t\t\t}\n\t\t\t\tjoinSession.roundTimeout = time.NewTimer(time.Second * time.Duration(joinSession.Config.RoundTimeOut))\n\t\t\t\tjoinSession.State = StateDcXor\n\t\t\t}\n\t\t\tjoinSession.mu.Unlock()\n\t\tcase data := <-joinSession.dcXorVectorChan:\n\t\t\tjoinSession.mu.Lock()\n\t\t\tdcXor := make([][]byte, 0)\n\t\t\tif len(data.Vector) < messages.PkScriptSize*2 {\n\t\t\t\t// Invalid dcxor vector length.\n\t\t\t\tjoinSession.mu.Unlock()\n\t\t\t\tjoinSession.pushMaliciousInfo([]uint32{data.PeerId})\n\t\t\t\tbreak LOOP\n\t\t\t}\n\t\t\tfor i := 0; i < int(data.Len); i++ {\n\t\t\t\tmsg := data.Vector[i*messages.PkScriptSize : (i+1)*messages.PkScriptSize]\n\t\t\t\tdcXor = append(dcXor, msg)\n\t\t\t}\n\n\t\t\tpeer := joinSession.Peers[data.PeerId]\n\t\t\tif peer == nil {\n\t\t\t\tlog.Debug(\"joinSession %d does not include peer %d\", joinSession.Id, data.PeerId)\n\t\t\t\tjoinSession.mu.Unlock()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpeer.DcXorVector = dcXor\n\t\t\tlog.Debug(\"Received dc-net xor vector from peer\", peer.Id)\n\n\t\t\tallSubmit := true\n\t\t\tfor _, peer := range joinSession.Peers {\n\t\t\t\tif len(peer.DcXorVector) == 0 {\n\t\t\t\t\tallSubmit = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If all peers have sent dc-net xor vector, will solve xor vector to get all peers's pkscripts\n\t\t\tallPkScripts = make([][]byte, len(peer.DcXorVector))\n\t\t\tvar err error = nil\n\t\t\tif allSubmit {\n\t\t\t\tlog.Debug(\"Combine xor vector to remove padding xor and get all pkscripts hash\")\n\t\t\t\t// Each peer will send [pkscript ^ P ^ P1 ^ P2...] bytes to server.\n\t\t\t\t// Of these, Pi is random padding bytes between peer and peer i.\n\t\t\t\t// Server combines all xor vectors. Thereafter it has [pkscript ^ (P ^ P1 ^ P2...) ^ (P ^ P1 ^ P2...)] = pkscript.\n\t\t\t\t// Server can not know pkscripts belong to which peer because only a peer knows its slot index.\n\t\t\t\t// After resolving dc-net xor, just only a peer knows its own pkscript.\n\t\t\t\tfor i := 0; i < len(peer.DcXorVector); i++ {\n\t\t\t\t\tfor _, peer := range joinSession.Peers {\n\t\t\t\t\t\tallPkScripts[i], err = util.XorBytes(allPkScripts[i], peer.DcXorVector[i])\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlog.Errorf(\"error XorBytes %v\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif allSubmit {\n\t\t\t\t// Signal to all peers that server has got all pkscripts.\n\t\t\t\t// Peers will process next step\n\t\t\t\tdcXorRet := &pb.DcXorVectorResult{}\n\t\t\t\tmsgs := make([]byte, 0)\n\t\t\t\tfor _, msg := range allPkScripts {\n\t\t\t\t\t//log.Debugf(\"Pkscript %x, len msg %d\", msg, len(msg))\n\t\t\t\t\tmsgs = append(msgs, msg...)\n\t\t\t\t}\n\t\t\t\tdcXorRet.Msgs = msgs\n\t\t\t\t//log.Debugf(\"Len of dcXorRet.Msgs %d, len allPkScripts %d\", len(dcXorRet.Msgs), len(allPkScripts))\n\n\t\t\t\tdcXorData, err := proto.Marshal(dcXorRet)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"Can not marshal DcXorVectorResult: %v\", err)\n\t\t\t\t\terrm = err\n\t\t\t\t\tbreak LOOP\n\t\t\t\t}\n\n\t\t\t\tlog.Debug(\"Solved dc-net xor vector and got all pkscripts\")\n\t\t\t\tjoinSession.roundTimeout = time.NewTimer(time.Second * time.Duration(joinSession.Config.RoundTimeOut))\n\t\t\t\tjoinSession.State = StateTxInput\n\t\t\t\tmessage := messages.NewMessage(messages.S_DC_XOR_VECTOR, dcXorData)\n\t\t\t\tfor _, peer := range joinSession.Peers {\n\t\t\t\t\tpeer.writeChan <- message.ToBytes()\n\t\t\t\t}\n\t\t\t}\n\t\t\tjoinSession.mu.Unlock()\n\t\tcase txins := <-joinSession.txInputsChan:\n\t\t\tjoinSession.mu.Lock()\n\t\t\tpeer := joinSession.Peers[txins.PeerId]\n\t\t\tif peer == nil {\n\t\t\t\tlog.Debug(\"joinSession %d does not include peer %d\", joinSession.Id, txins.PeerId)\n\t\t\t\tjoinSession.mu.Unlock()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Server will use the ticket price that sent by each peer to construct the join transaction.\n\t\t\tpeer.TicketPrice = txins.TicketPrice\n\n\t\t\t// Validate ticket price\n\t\t\tif peer.TicketPrice <= 0 {\n\t\t\t\terrMsg := fmt.Sprintf(\"Peer %d sent invalid ticket price: %d\", peer.Id, peer.TicketPrice)\n\t\t\t\tlog.Warnf(errMsg)\n\t\t\t\tjoinSession.mu.Unlock()\n\t\t\t\tjoinSession.pushMaliciousInfo([]uint32{peer.Id})\n\t\t\t\tbreak LOOP\n\t\t\t}\n\n\t\t\tvar tx wire.MsgTx\n\t\t\tbuf := bytes.NewReader(txins.Txins)\n\t\t\terr := tx.BtcDecode(buf, 0)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"error BtcDecode %v\", err)\n\t\t\t\terrm = err\n\t\t\t\tbreak LOOP\n\t\t\t}\n\t\t\tpeer.TxIns = &tx\n\n\t\t\t// Validate tx input\n\t\t\terrValidation := false\n\t\t\tvar txAmount int64\n\t\t\tfor _, txin := range tx.TxIn {\n\t\t\t\tif len(txin.SignatureScript) > 0 {\n\t\t\t\t\tlog.Errorf(\"Peer %d have sent tx already signed\", peer.Id)\n\t\t\t\t\terrm = errors.New(\"\")\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ttxAmount += txin.ValueIn\n\t\t\t}\n\t\t\tif errValidation {\n\t\t\t\tjoinSession.mu.Unlock()\n\t\t\t\tjoinSession.pushMaliciousInfo([]uint32{peer.Id})\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Validate tx amount\n\t\t\ttxoutValue := (tx.TxOut[0].Value + int64(peer.NumMsg)*peer.TicketPrice)\n\t\t\tvar txinAmout float64 = float64(txAmount) / 100000000\n\t\t\tvar txoutAmount float64 = float64(txoutValue) / 100000000\n\n\t\t\tlog.Debugf(\"Peer %d, %d inputs (%f DCR), %d output for (%f DCR), fee (%f DCR)\",\n\t\t\t\tpeer.Id, len(tx.TxIn), txinAmout, len(tx.TxOut), txoutAmount, txinAmout-txoutAmount)\n\n\t\t\tif txoutAmount > txinAmout {\n\t\t\t\tlog.Errorf(\"Peer %d spent utxo amount %f greater than txin amount %f\", peer.Id, txoutAmount, txinAmout)\n\t\t\t\terrValidation = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif errValidation {\n\t\t\t\tjoinSession.mu.Unlock()\n\t\t\t\tjoinSession.pushMaliciousInfo([]uint32{peer.Id})\n\t\t\t\terrm = nil\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tallSubmit := true\n\t\t\tfor _, peer := range joinSession.Peers {\n\t\t\t\tif peer.TxIns == nil {\n\t\t\t\t\tallSubmit = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// With pkscripts solved from dc-net xor vector, we will build the transaction.\n\t\t\t// Each pkscript will be one txout with amout is ticket price + fee.\n\t\t\t// Combine with transaction input from peer, we can build unsigned transaction.\n\t\t\tvar joinedtx *wire.MsgTx\n\t\t\tif allSubmit {\n\t\t\t\tlog.Debug(\"All peers sent txin and txout change amount, will create join tx for signing\")\n\t\t\t\tfor _, peer := range joinSession.Peers {\n\t\t\t\t\tif joinedtx == nil {\n\t\t\t\t\t\tjoinedtx = peer.TxIns\n\t\t\t\t\t\tfor i := range peer.TxIns.TxIn {\n\t\t\t\t\t\t\tpeer.InputIndex = append(peer.InputIndex, i)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tendIndex := len(joinedtx.TxIn)\n\t\t\t\t\t\tjoinedtx.TxIn = append(joinedtx.TxIn, peer.TxIns.TxIn...)\n\t\t\t\t\t\tjoinedtx.TxOut = append(joinedtx.TxOut, peer.TxIns.TxOut...)\n\n\t\t\t\t\t\tfor i := range peer.TxIns.TxIn {\n\t\t\t\t\t\t\tpeer.InputIndex = append(peer.InputIndex, i+endIndex)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor _, msg := range allPkScripts {\n\t\t\t\t\ttxout := wire.NewTxOut(peer.TicketPrice, msg)\n\t\t\t\t\tjoinedtx.AddTxOut(txout)\n\t\t\t\t}\n\n\t\t\t\t// Send unsign join transaction to peers\n\t\t\t\tbuffTx := bytes.NewBuffer(nil)\n\t\t\t\tbuffTx.Grow(joinedtx.SerializeSize())\n\t\t\t\terr := joinedtx.BtcEncode(buffTx, 0)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"error BtcEncode %v\", err)\n\t\t\t\t\terrm = err\n\t\t\t\t\tbreak LOOP\n\t\t\t\t}\n\n\t\t\t\tjoinTx := &pb.JoinTx{}\n\t\t\t\tjoinTx.Tx = buffTx.Bytes()\n\t\t\t\tjoinTxData, err := proto.Marshal(joinTx)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"Can not marshal transaction: %v\", err)\n\t\t\t\t\terrm = err\n\t\t\t\t\tbreak LOOP\n\t\t\t\t}\n\t\t\t\tjoinTxMsg := messages.NewMessage(messages.S_JOINED_TX, joinTxData)\n\t\t\t\tfor _, peer := range joinSession.Peers {\n\t\t\t\t\tpeer.writeChan <- joinTxMsg.ToBytes()\n\t\t\t\t}\n\t\t\t\tlog.Debug(\"Server built join tx from txin that just received, txout is created from the resolved pkscripts and ticket price\")\n\t\t\t\tlog.Debug(\"Broadcast the joint transaction to all peers.\")\n\t\t\t\tjoinSession.roundTimeout = time.NewTimer(time.Second * time.Duration(joinSession.Config.RoundTimeOut))\n\t\t\t\tjoinSession.State = StateTxSign\n\t\t\t}\n\t\t\tjoinSession.mu.Unlock()\n\t\tcase signedTx := <-joinSession.txSignedTxChan:\n\t\t\t// Each peer after received unsigned join transaction then sign their own transaction input\n\t\t\t// and send to server\n\t\t\tjoinSession.mu.Lock()\n\t\t\tpeer := joinSession.Peers[signedTx.PeerId]\n\t\t\tif peer == nil {\n\t\t\t\tlog.Debug(\"joinSession %d does not include peer %d\", joinSession.Id, signedTx.PeerId)\n\t\t\t\tjoinSession.mu.Unlock()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar tx wire.MsgTx\n\t\t\treader := bytes.NewReader(signedTx.Tx)\n\t\t\terr := tx.BtcDecode(reader, 0)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Can not decode transaction: %v\", err)\n\t\t\t\tlog.Infof(\"Session %d terminates fail\", joinSession.Id)\n\t\t\t\terrm = err\n\t\t\t\tbreak LOOP\n\t\t\t}\n\t\t\tif peer.SignedTx != nil {\n\t\t\t\tjoinSession.mu.Unlock()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpeer.SignedTx = &tx\n\t\t\tlog.Debug(\"Received signed transaction from peer\", peer.Id)\n\n\t\t\t// Validate signed tx to match with previous sent txin\n\t\t\ti := 0\n\t\t\terrValidation := false\n\t\t\tfor _, idx := range peer.InputIndex {\n\t\t\t\tif tx.TxIn[idx].ValueIn != peer.TxIns.TxIn[i].ValueIn ||\n\t\t\t\t\ttx.TxIn[idx].PreviousOutPoint.Hash.String() != peer.TxIns.TxIn[i].PreviousOutPoint.Hash.String() ||\n\t\t\t\t\ttx.TxIn[idx].PreviousOutPoint.Index != peer.TxIns.TxIn[i].PreviousOutPoint.Index ||\n\t\t\t\t\tlen(tx.TxIn[idx].SignatureScript) == 0 {\n\t\t\t\t\tlog.Errorf(\"Peer %d sent invalid signed tx data\", peer.Id)\n\t\t\t\t\terrValidation = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ti++\n\t\t\t}\n\t\t\tif errValidation {\n\t\t\t\tjoinSession.mu.Unlock()\n\t\t\t\tjoinSession.pushMaliciousInfo([]uint32{peer.Id})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Join signed transaction from each peer to one transaction.\n\t\t\tif joinSession.JoinedTx == nil {\n\t\t\t\tjoinSession.JoinedTx = tx.Copy()\n\t\t\t} else {\n\t\t\t\tfor _, index := range peer.InputIndex {\n\t\t\t\t\tjoinSession.JoinedTx.TxIn[index] = tx.TxIn[index]\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tallSubmit := true\n\t\t\tfor _, peer := range joinSession.Peers {\n\t\t\t\tif peer.SignedTx == nil {\n\t\t\t\t\tallSubmit = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif allSubmit {\n\t\t\t\t// Send the joined transaction to all peer in join session.\n\t\t\t\t// Random select peer to publish transaction.\n\t\t\t\t// TODO: publish transaction from server\n\t\t\t\tlog.Info(\"Applied signatures from all peers.\")\n\n\t\t\t\tbuffTx := bytes.NewBuffer(nil)\n\t\t\t\tbuffTx.Grow(joinSession.JoinedTx.SerializeSize())\n\n\t\t\t\terr := joinSession.JoinedTx.BtcEncode(buffTx, 0)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"Cannot execute BtcEncode: %v\", err)\n\t\t\t\t\tlog.Infof(\"Session %d terminates fail\", joinSession.Id)\n\t\t\t\t\terrm = err\n\t\t\t\t\tbreak LOOP\n\t\t\t\t}\n\t\t\t\tpublished := false\n\t\t\t\tif joinSession.Config.ServerPublish {\n\t\t\t\t\t// publish transaction from server\n\t\t\t\t\turl := \"https://testnet.dcrdata.org/insight/api/tx/send\"\n\t\t\t\t\tlog.Infof(\"Will broadcast transaction via %s\", url)\n\t\t\t\t\tcnt := 0\n\t\t\t\t\tfor {\n\t\t\t\t\t\terr := publishTx(joinSession.JoinedTx, url)\n\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\tmsg := messages.NewMessage(messages.S_TX_PUBLISH_RESULT, buffTx.Bytes())\n\t\t\t\t\t\t\tfor _, peer := range joinSession.Peers {\n\t\t\t\t\t\t\t\tpeer.writeChan <- msg.ToBytes()\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tjoinSession.State = StateCompleted\n\t\t\t\t\t\t\tjoinSession.mu.Unlock()\n\t\t\t\t\t\t\tlog.Infof(\"Transaction %s was published.\", joinSession.JoinedTx.TxHash().String())\n\t\t\t\t\t\t\tlog.Info(\"Broadcast the joint transaction to all peers.\")\n\t\t\t\t\t\t\tpublished = true\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlog.Warnf(\"Can not publish transaction from server side: %v\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcnt++\n\t\t\t\t\t\tif cnt == 3 {\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttime.Sleep(time.Second * 5)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif published {\n\t\t\t\t\tlog.Infof(\"Session %d terminates successfully.\", joinSession.Id)\n\t\t\t\t\tbreak LOOP\n\t\t\t\t}\n\t\t\t\tlog.Warnf(\"Will publish from client side.\")\n\t\t\t\tjoinTx := &pb.JoinTx{}\n\t\t\t\tjoinTx.Tx = buffTx.Bytes()\n\t\t\t\tjoinTxData, err := proto.Marshal(joinTx)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"Can not marshal signed transaction: %v\", err)\n\t\t\t\t\tlog.Infof(\"Session %d terminates fail.\", joinSession.Id)\n\t\t\t\t\terrm = err\n\t\t\t\t\tbreak LOOP\n\t\t\t\t}\n\n\t\t\t\tjoinTxMsg := messages.NewMessage(messages.S_TX_SIGN, joinTxData)\n\t\t\t\tpubId := joinSession.randomPublisher()\n\t\t\t\tjoinSession.Publisher = pubId\n\t\t\t\tpublisher := joinSession.Peers[pubId]\n\t\t\t\tlog.Infof(\"Peer %d is randomly selected to publish transaction %s\", pubId, joinSession.JoinedTx.TxHash().String())\n\t\t\t\tpublisher.writeChan <- joinTxMsg.ToBytes()\n\t\t\t\tjoinSession.roundTimeout = time.NewTimer(time.Second * time.Duration(joinSession.Config.RoundTimeOut/3))\n\t\t\t\tjoinSession.State = StateTxPublish\n\t\t\t}\n\t\t\tjoinSession.mu.Unlock()\n\t\tcase pubResult := <-joinSession.txPublishResultChan:\n\t\t\t// Random peer has published transaction, send back to other peers for purchase ticket\n\t\t\tjoinSession.mu.Lock()\n\t\t\tmsg := messages.NewMessage(messages.S_TX_PUBLISH_RESULT, pubResult.Tx)\n\t\t\tfor _, peer := range joinSession.Peers {\n\t\t\t\tpeer.writeChan <- msg.ToBytes()\n\t\t\t}\n\t\t\tjoinSession.State = StateCompleted\n\t\t\tjoinSession.mu.Unlock()\n\t\t\tlog.Info(\"Broadcast the join transaction to all peers.\")\n\t\t\tlog.Infof(\"Session %d terminates successfully.\", joinSession.Id)\n\t\t\tbreak LOOP\n\t\tcase rvSecret := <-joinSession.revealSecretChan:\n\t\t\t// Save verify key\n\t\t\tjoinSession.mu.Lock()\n\t\t\tpeer := joinSession.Peers[rvSecret.PeerId]\n\t\t\tif peer == nil {\n\t\t\t\tjoinSession.mu.Unlock()\n\t\t\t\tlog.Debug(\"joinSession %d does not include peer %d\", joinSession.Id, rvSecret.PeerId)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpeer.Vk = rvSecret.Vk\n\t\t\tlog.Debugf(\"Peer %d submit verify key %x\", peer.Id, peer.Vk)\n\n\t\t\tallSubmit := true\n\t\t\tfor _, peer := range joinSession.Peers {\n\t\t\t\tif len(peer.Vk) == 0 {\n\t\t\t\t\tallSubmit = false\n\t\t\t\t}\n\t\t\t}\n\t\t\tmaliciousIds := make([]uint32, 0)\n\t\t\tif allSubmit {\n\t\t\t\t// Replay all message protocol to find the malicious peers.\n\t\t\t\t// Create peer's random bytes for dc-net exponential and dc-net xor.\n\t\t\t\treplayPeers := make(map[uint32]map[uint32]*PeerReplayInfo, 0)\n\t\t\t\tecp256 := ecdh.NewEllipticECDH(elliptic.P256())\n\n\t\t\t\t// We use simple method by generating key pair of server\n\t\t\t\t// then compare share key with each peer.\n\t\t\t\tfor _, p := range joinSession.Peers {\n\t\t\t\t\tpeerPrivKey := ecp256.UnmarshalPrivateKey(p.Vk)\n\t\t\t\t\tpeerPubKey, _ := ecp256.Unmarshal(p.Pk)\n\t\t\t\t\tserverPrivKey, serverPubKey, err := ecp256.GenerateKey(crand.Reader)\n\n\t\t\t\t\tshareKey1, err := ecp256.GenSharedSecret(peerPrivKey, serverPubKey)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\terrMsg := fmt.Sprintf(\"Can not generate shared secret key: %v\", err)\n\t\t\t\t\t\tlog.Errorf(errMsg)\n\t\t\t\t\t\terrm = errors.New(errMsg)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tshareKey2, err := ecp256.GenSharedSecret(serverPrivKey, peerPubKey)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\terrMsg := fmt.Sprintf(\"Can not generate shared secret key: %v\", err)\n\t\t\t\t\t\tlog.Errorf(errMsg)\n\t\t\t\t\t\terrm = errors.New(errMsg)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\n\t\t\t\t\tif bytes.Compare(shareKey1, shareKey2) != 0 {\n\t\t\t\t\t\tmaliciousIds = append(maliciousIds, p.Id)\n\t\t\t\t\t\tlog.Infof(\"Peer %d is malicious - sent invalid public/verify key pair.\", p.Id)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif errm != nil {\n\t\t\t\t\tbreak LOOP\n\t\t\t\t}\n\n\t\t\t\tfor _, p := range joinSession.Peers {\n\t\t\t\t\treplayPeer := make(map[uint32]*PeerReplayInfo)\n\t\t\t\t\tpVk := ecp256.UnmarshalPrivateKey(p.Vk)\n\t\t\t\t\tfor _, op := range joinSession.Peers {\n\t\t\t\t\t\tif p.Id == op.Id {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\topeerInfo := &PeerReplayInfo{}\n\t\t\t\t\t\topPk, _ := ecp256.Unmarshal(op.Pk)\n\n\t\t\t\t\t\t// Generate shared key with other peer from peer's private key and other peer's public key\n\t\t\t\t\t\tsharedKey, err := ecp256.GenSharedSecret32(pVk, opPk)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\terrMsg := fmt.Sprintf(\"Can not generate shared secret key: %v\", err)\n\t\t\t\t\t\t\tlog.Errorf(errMsg)\n\t\t\t\t\t\t\terrm = errors.New(errMsg)\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\topeerInfo.SharedKey = sharedKey\n\t\t\t\t\t\topeerInfo.Id = op.Id\n\t\t\t\t\t\treplayPeer[op.Id] = opeerInfo\n\t\t\t\t\t}\n\t\t\t\t\tif errm != nil {\n\t\t\t\t\t\tbreak LOOP\n\t\t\t\t\t}\n\t\t\t\t\treplayPeers[p.Id] = replayPeer\n\t\t\t\t\tjoinSession.TotalMsg += int(p.NumMsg)\n\t\t\t\t}\n\n\t\t\t\t// Maintain a counter the number incorrect share key of each peer.\n\t\t\t\t// If one peer with more than one incorrect share key then\n\t\t\t\t// the peer is malicious.\n\t\t\t\t// compareCount := make(map[uint32]int)\n\t\t\t\t// for pid, replayPeer := range replayPeers {\n\t\t\t\t// \tfor opid, opReplayPeer := range replayPeers {\n\t\t\t\t// \t\tif pid == opid {\n\t\t\t\t// \t\t\tcontinue\n\t\t\t\t// \t\t}\n\n\t\t\t\t// \t\tpInfo := opReplayPeer[pid]\n\t\t\t\t// \t\topInfo := replayPeer[opid]\n\t\t\t\t// \t\tif bytes.Compare(pInfo.SharedKey, opInfo.SharedKey) != 0 {\n\t\t\t\t// \t\t\tlog.Debugf(\"compare vk %x of peer %d with vk %x of peer %d\", pInfo.SharedKey, pInfo.Id, opInfo.SharedKey, opInfo.Id)\n\t\t\t\t// \t\t\t// Increase compare counter\n\t\t\t\t// \t\t\tif _, ok := compareCount[pid]; ok {\n\t\t\t\t// \t\t\t\tcompareCount[pid] = compareCount[pid] + 1\n\t\t\t\t// \t\t\t} else {\n\t\t\t\t// \t\t\t\tcompareCount[pid] = 1\n\t\t\t\t// \t\t\t}\n\n\t\t\t\t// \t\t\tif _, ok := compareCount[opid]; ok {\n\t\t\t\t// \t\t\t\tcompareCount[opid] = compareCount[opid] + 1\n\t\t\t\t// \t\t\t} else {\n\t\t\t\t// \t\t\t\tcompareCount[opid] = 1\n\t\t\t\t// \t\t\t}\n\t\t\t\t// \t\t}\n\t\t\t\t// \t}\n\t\t\t\t// }\n\n\t\t\t\t// for pid, count := range compareCount {\n\t\t\t\t// \tlog.Debug(\"Peer %d, compare counter %d\", pid, count)\n\t\t\t\t// \t// Total number checking of share key is wrong\n\t\t\t\t// \t// means this peer submit invalid pk/vk key pair.\n\t\t\t\t// \tif count >= len(joinSession.Peers)-1 {\n\t\t\t\t// \t\t// Peer is malicious\n\t\t\t\t// \t\tmaliciousIds = append(maliciousIds, pid)\n\t\t\t\t// \t\tlog.Infof(\"Peer %d is malicious - sent invalid public/verify key pair\", pid)\n\t\t\t\t// \t}\n\t\t\t\t// }\n\n\t\t\t\t// Share keys are correct. Check dc-net exponential and dc-net xor vector.\n\t\t\t\tpeerSlotInfos := make(map[uint32]*PeerSlotInfo, 0)\n\t\t\t\tfor pid, pInfo := range joinSession.Peers {\n\t\t\t\t\treplayPeer := replayPeers[pid]\n\n\t\t\t\t\texpVector := make([]field.Field, len(pInfo.DcExpVector))\n\t\t\t\t\tcopy(expVector, pInfo.DcExpVector)\n\t\t\t\t\tslotInfo := &PeerSlotInfo{Id: pid}\n\t\t\t\t\tfor opid, opInfo := range replayPeer {\n\t\t\t\t\t\tdcexpRng, err := chacharng.RandBytes(opInfo.SharedKey, messages.ExpRandSize)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tlog.Errorf(\"Can generate random bytes: %v\", err)\n\t\t\t\t\t\t\t\terrm = err\n\t\t\t\t\t\t\t\tbreak LOOP\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdcexpRng = append([]byte{0, 0, 0, 0}, dcexpRng...)\n\n\t\t\t\t\t\t// For random byte of Xor vector, we get the same size of pkscript is 25 bytes\n\t\t\t\t\t\tdcXorRng, err := chacharng.RandBytes(opInfo.SharedKey, messages.PkScriptSize)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tlog.Errorf(\"Can generate random bytes: %v\", err)\n\t\t\t\t\t\t\t\terrm = err\n\t\t\t\t\t\t\t\tbreak LOOP\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tpadding := field.NewFF(field.FromBytes(dcexpRng))\n\t\t\t\t\t\tfor i := 0; i < int(pInfo.NumMsg); i++ {\n\t\t\t\t\t\t\tif pid > opid {\n\t\t\t\t\t\t\t\texpVector[i] = expVector[i].Sub(padding)\n\t\t\t\t\t\t\t} else if pid < opid {\n\t\t\t\t\t\t\t\texpVector[i] = expVector[i].Add(padding)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\topInfo.DcExpPadding = padding\n\t\t\t\t\t\topInfo.DcXorRng = dcXorRng\n\t\t\t\t\t}\n\n\t\t\t\t\t// Now we have real exponential vector without padding.\n\t\t\t\t\t// If dc-net exponential is valid then polynomial of peer could be solved.\n\t\t\t\t\tlog.Debug(\"Check the validity of dc-net exponential of peer by resolving polynomial.\")\n\t\t\t\t\tif pInfo.NumMsg > 1 {\n\t\t\t\t\t\tret, roots := flint.GetRoots(field.Prime.HexStr(), expVector[:pInfo.NumMsg], int(pInfo.NumMsg))\n\t\t\t\t\t\tlog.Debugf(\"Func returns of peer %d: %d\", ret, pid)\n\t\t\t\t\t\tlog.Debugf(\"Number roots: %d\", len(roots))\n\t\t\t\t\t\tlog.Debugf(\"Roots: %v\", roots)\n\n\t\t\t\t\t\tif ret != 0 {\n\t\t\t\t\t\t\t// This peer is malicious.\n\t\t\t\t\t\t\tmaliciousIds = append(maliciousIds, pid)\n\t\t\t\t\t\t\tlog.Infof(\"Peer is malicious: %d\", pid)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Build the dc-net exponential from messages and padding then compare dc-net vector.\n\t\t\t\t\t\tlog.Infof(\"Total msg: %d\", joinSession.TotalMsg)\n\t\t\t\t\t\tsentVector := make([]field.Field, joinSession.TotalMsg)\n\n\t\t\t\t\t\tmsgHash := make([]field.Uint128, 0)\n\t\t\t\t\t\tfor _, s := range roots {\n\t\t\t\t\t\t\tn, err := field.Uint128FromString(s)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tlog.Errorf(\"Can not parse from string %v\", err)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tff := field.NewFF(n)\n\t\t\t\t\t\t\tfor i := 0; i < joinSession.TotalMsg; i++ {\n\t\t\t\t\t\t\t\tsentVector[i] = sentVector[i].Add(ff.Exp(uint64(i + 1)))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tmsgHash = append(msgHash, n)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tslotInfo.PkScriptsHash = msgHash\n\n\t\t\t\t\t\t// Padding with random number generated with secret key seed.\n\t\t\t\t\t\tfor i := 0; i < int(joinSession.TotalMsg); i++ {\n\t\t\t\t\t\t\t// Padding with other peers.\n\t\t\t\t\t\t\treplayPeer := replayPeers[pid]\n\t\t\t\t\t\t\tfor opId, opInfo := range replayPeer {\n\t\t\t\t\t\t\t\tif pid > opId {\n\t\t\t\t\t\t\t\t\tsentVector[i] = sentVector[i].Add(opInfo.DcExpPadding)\n\t\t\t\t\t\t\t\t} else if pid < opId {\n\t\t\t\t\t\t\t\t\tsentVector[i] = sentVector[i].Sub(opInfo.DcExpPadding)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor i := 0; i < int(joinSession.TotalMsg); i++ {\n\t\t\t\t\t\t\tlog.Debugf(\"Exp vector af padding %x\", sentVector[i].N.GetBytes())\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor i := 0; i < int(joinSession.TotalMsg); i++ {\n\t\t\t\t\t\t\t//log.Debugf(\"compare original %x - new build dc-net %x\", pInfo.DcExpVector[i].N.GetBytes(), sentVector[i].N.GetBytes())\n\t\t\t\t\t\t\tif bytes.Compare(pInfo.DcExpVector[i].N.GetBytes(), sentVector[i].N.GetBytes()) != 0 {\n\t\t\t\t\t\t\t\t// malicious peer\n\t\t\t\t\t\t\t\tlog.Debugf(\"Compare dc-net vector, peer is malicious: %d\", pid)\n\t\t\t\t\t\t\t\tmaliciousIds = append(maliciousIds, pid)\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpeerSlotInfos[slotInfo.Id] = slotInfo\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\t// Check whether peer dc-net vector matches with vector has sent to server.\n\t\t\t\t\tif pInfo.NumMsg == 1 {\n\t\t\t\t\t\tsentVector := make([]field.Field, joinSession.TotalMsg)\n\t\t\t\t\t\tff := expVector[0]\n\t\t\t\t\t\tslotInfo.PkScriptsHash = []field.Uint128{ff.N}\n\t\t\t\t\t\tfor i := 0; i < joinSession.TotalMsg; i++ {\n\t\t\t\t\t\t\tsentVector[i] = sentVector[i].Add(ff.Exp(uint64(i + 1)))\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor i := 0; i < int(joinSession.TotalMsg); i++ {\n\t\t\t\t\t\t\tlog.Debugf(\"Exp vector bf padding %x\", sentVector[i].N.GetBytes())\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Padding with random number generated with secret key seed.\n\t\t\t\t\t\tfor i := 0; i < int(joinSession.TotalMsg); i++ {\n\t\t\t\t\t\t\t// Padding with other peers.\n\t\t\t\t\t\t\treplayPeer := replayPeers[pid]\n\t\t\t\t\t\t\tfor opId, opInfo := range replayPeer {\n\t\t\t\t\t\t\t\tif pid > opId {\n\t\t\t\t\t\t\t\t\tsentVector[i] = sentVector[i].Add(opInfo.DcExpPadding)\n\t\t\t\t\t\t\t\t} else if pid < opId {\n\t\t\t\t\t\t\t\t\tsentVector[i] = sentVector[i].Sub(opInfo.DcExpPadding)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor i := 0; i < int(joinSession.TotalMsg); i++ {\n\t\t\t\t\t\t\tlog.Debugf(\"Exp vector af padding %x\", sentVector[i].N.GetBytes())\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor i := 0; i < int(joinSession.TotalMsg); i++ {\n\t\t\t\t\t\t\tlog.Debugf(\"compare original %x - new build dc-net %x\", pInfo.DcExpVector[i].N.GetBytes(), sentVector[i].N.GetBytes())\n\t\t\t\t\t\t\tif bytes.Compare(pInfo.DcExpVector[i].N.GetBytes(), sentVector[i].N.GetBytes()) != 0 {\n\t\t\t\t\t\t\t\t// malicious peer\n\t\t\t\t\t\t\t\tlog.Debugf(\"Compare dc-net vector, peer is malicious: %d\", pid)\n\t\t\t\t\t\t\t\tmaliciousIds = append(maliciousIds, pid)\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpeerSlotInfos[slotInfo.Id] = slotInfo\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\tlog.Debug(\"join state\", joinSession.getStateString())\n\n\t\t\t\tif joinSession.State == StateTxInput || joinSession.State == StateRevealSecret {\n\t\t\t\t\t// Client can not find message at dc-net xor round.\n\t\t\t\t\t// We have found all msg hash. Identify the peer's slot index.\n\t\t\t\t\tallMsgHash := make([]field.Uint128, 0)\n\t\t\t\t\tfor _, slotInfo := range peerSlotInfos {\n\t\t\t\t\t\tallMsgHash = append(allMsgHash, slotInfo.PkScriptsHash...)\n\t\t\t\t\t}\n\t\t\t\t\tsort.Slice(allMsgHash, func(i, j int) bool {\n\t\t\t\t\t\treturn allMsgHash[i].Compare(allMsgHash[j]) < 0\n\t\t\t\t\t})\n\n\t\t\t\t\tfor i, msg := range allMsgHash {\n\t\t\t\t\t\tlog.Debugf(\"All msg, msghash :%x, Index: %d\", msg.GetBytes(), i)\n\t\t\t\t\t}\n\n\t\t\t\t\tlog.Debugf(\"len(allMsgHash) %d, len(peerSlotInfos) %d\", len(allMsgHash), len(peerSlotInfos))\n\t\t\t\t\tfor _, slotInfo := range peerSlotInfos {\n\t\t\t\t\t\tslotInfo.SlotIndex = make([]int, 0)\n\t\t\t\t\t\tfor _, msg := range slotInfo.PkScriptsHash {\n\t\t\t\t\t\t\tfor i := 0; i < len(allMsgHash); i++ {\n\t\t\t\t\t\t\t\tif msg.Compare(allMsgHash[i]) == 0 {\n\t\t\t\t\t\t\t\t\tlog.Debugf(\"Peer: %d, msghash :%x, Index: %d\", slotInfo.Id, msg.GetBytes(), i)\n\t\t\t\t\t\t\t\t\tslotInfo.SlotIndex = append(slotInfo.SlotIndex, i)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif len(slotInfo.SlotIndex) != len(slotInfo.PkScriptsHash) {\n\t\t\t\t\t\t\t// Can not find all mesages hash of peer. Terminates fail.\n\t\t\t\t\t\t\tlog.Debug(\"len(slotInfo.SlotIndex) != len(slotInfo.MsgHash)\")\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlog.Debugf(\"Peer %d, slotInfo.SlotIndex %v\", slotInfo.Id, slotInfo.SlotIndex)\n\t\t\t\t\t}\n\n\t\t\t\t\tfor _, slotInfo := range peerSlotInfos {\n\t\t\t\t\t\tslotInfo.PkScripts = make([][]byte, 0)\n\t\t\t\t\t\tfor i, realMsg := range joinSession.Peers[slotInfo.Id].DcXorVector {\n\t\t\t\t\t\t\tlog.Debugf(\"Peer %d, index: %d, dcxorvector message %x\", slotInfo.Id, i, realMsg)\n\t\t\t\t\t\t\tvar err error\n\t\t\t\t\t\t\treplayPeer := replayPeers[slotInfo.Id]\n\t\t\t\t\t\t\tfor _, replay := range replayPeer {\n\t\t\t\t\t\t\t\tlog.Debugf(\"Real message %x, replay.DcXorRng %x\", realMsg, replay.DcXorRng)\n\t\t\t\t\t\t\t\trealMsg, err = util.XorBytes(realMsg, replay.DcXorRng)\n\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t// Can not xor\n\t\t\t\t\t\t\t\t\tlog.Errorf(\"Can not xor: %v\", err)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tlog.Debugf(\"Real message %x\", realMsg)\n\t\t\t\t\t\t\tslotInfo.PkScripts = append(slotInfo.PkScripts, realMsg)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfor _, slotInfo := range peerSlotInfos {\n\t\t\t\t\tLOOPRV:\n\t\t\t\t\t\tfor i := 0; i < len(slotInfo.PkScripts); i++ {\n\t\t\t\t\t\t\tisSlot := false\n\t\t\t\t\t\t\tfor j := 0; j < len(slotInfo.SlotIndex); j++ {\n\t\t\t\t\t\t\t\tif i == slotInfo.SlotIndex[j] {\n\t\t\t\t\t\t\t\t\tlog.Debugf(\"SlotIndex: %d\", i)\n\t\t\t\t\t\t\t\t\tripemdHash := ripemd128.New()\n\t\t\t\t\t\t\t\t\t_, err := ripemdHash.Write(slotInfo.PkScripts[i])\n\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\t// Can not write hash\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\thash := ripemdHash.Sum127(nil)\n\t\t\t\t\t\t\t\t\tlog.Debugf(\"msgHash: %x, realmsg: %x, hash real msg: %x\",\n\t\t\t\t\t\t\t\t\t\tallMsgHash[i].GetBytes(), slotInfo.PkScripts[i], hash)\n\t\t\t\t\t\t\t\t\tif bytes.Compare(allMsgHash[i].GetBytes(), hash) != 0 {\n\t\t\t\t\t\t\t\t\t\t// This is malicious peer\n\t\t\t\t\t\t\t\t\t\tlog.Infof(\"Peer %d sent invalid dc-net xor vector on non-slot %d\", slotInfo.Id, i)\n\t\t\t\t\t\t\t\t\t\tmaliciousIds = append(maliciousIds, slotInfo.Id)\n\t\t\t\t\t\t\t\t\t\tbreak LOOPRV\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tisSlot = true\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif !isSlot {\n\t\t\t\t\t\t\t\tsample := \"00000000000000000000000000000000000000000000000000\"\n\t\t\t\t\t\t\t\tpkScript := hex.EncodeToString(slotInfo.PkScripts[i])\n\t\t\t\t\t\t\t\tif strings.Compare(sample, pkScript) != 0 {\n\t\t\t\t\t\t\t\t\tlog.Infof(\"Peer %d sent invalid dc-net xor vector on non-slot %d\", slotInfo.Id, i)\n\t\t\t\t\t\t\t\t\tmaliciousIds = append(maliciousIds, slotInfo.Id)\n\t\t\t\t\t\t\t\t\tbreak LOOPRV\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlog.Debugf(\"End check dc-xor\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tjoinSession.maliciousFinding = false\n\t\t\tjoinSession.mu.Unlock()\n\n\t\t\tif len(maliciousIds) > 0 {\n\t\t\t\tjoinSession.pushMaliciousInfo(maliciousIds)\n\t\t\t}\n\t\tcase data := <-joinSession.msgNotFoundChan:\n\t\t\tjoinSession.mu.Lock()\n\t\t\tpeerInfo := joinSession.Peers[data.PeerId]\n\t\t\tif peerInfo == nil {\n\t\t\t\tlog.Debug(\"joinSession %d does not include peer %d\", joinSession.Id, data.PeerId)\n\t\t\t\tjoinSession.mu.Unlock()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Reveal verify key to find the malicious.\n\t\t\tmsg := messages.NewMessage(messages.S_REVEAL_SECRET, []byte{0x00})\n\t\t\tfor _, peer := range joinSession.Peers {\n\t\t\t\tpeer.writeChan <- msg.ToBytes()\n\t\t\t}\n\t\t\tjoinSession.roundTimeout = time.NewTimer(time.Second * time.Duration(joinSession.Config.RoundTimeOut))\n\t\t\tjoinSession.State = StateRevealSecret\n\t\t\tjoinSession.mu.Unlock()\n\t\t}\n\t}\n\tif errm != nil {\n\t\tlog.Errorf(\"Session %d terminate fail with error %v\", errm)\n\t\tjoinSession.mu.Unlock()\n\t\tjoinSession.terminate()\n\t}\n\n}", "func (s *Swarm) DialPeer(ctx context.Context, p peer.ID) (network.Conn, error) {\n\t// Avoid typed nil issues.\n\tc, err := s.dialPeer(ctx, p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c, nil\n}", "func main() {\n\n\tfmt.Println(\"Portfolio One: Go² by Sean Hinchee (Group 20)\")\n\n\t/* configure buffered channels, init http handlers, start concurrent game manager */\n\tmoveChan = make(chan Move, 5)\n\tboardChan = make(chan Board, 5)\n\treqChan = make(chan int, 5)\n\tkillChan = make(chan bool, 3)\n\tactiveChan = make(chan Act, 5)\n\tstrChan = make(chan string, 5)\n\tgetActiveChan = make(chan bool, 5)\n\n\thttp.HandleFunc(\"/main/\", mainHandler)\n\thttp.HandleFunc(\"/black/\", blackHandler)\n\thttp.HandleFunc(\"/white/\", whiteHandler)\n\thttp.HandleFunc(\"/game/\", gameHandler)\n\thttp.HandleFunc(\"/move/\", moveHandler)\n\thttp.HandleFunc(\"/kill/\", killHandler)\n\thttp.HandleFunc(\"/over/\", overHandler)\n\thttp.HandleFunc(\"/string/\", gameInst)\n\thttp.HandleFunc(\"/\", mainHandler)\n\n\tgo gameManager()\n\n\n\terr := http.ListenAndServe(\":13337\", nil)\n\tcheck(err)\n\n\ta := true\n\tfor a {\n\t\tselect {\n\t\tcase a = <- killChan:\n\t\tdefault:\n\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t}\n\t}\n}", "func main() {\n\tctx := context.Background()\n\tctx, cancel := context.WithTimeout(ctx, 2*time.Second)\n\n\tdefer cancel()\n\n\ttalkAfter(ctx, 6*time.Second, \"Holis\")\n}", "func NewDinnerHostPtr(tableCount, maxParallel, maxDinner int) *DinnerHost {\n\thost := new(DinnerHost)\n\thost.Init(tableCount, maxParallel, maxDinner)\n\treturn host\n}", "func ward(done <-chan struct{}, interval time.Duration) <-chan struct{} {\n\theartbeat := make(chan struct{})\n\tlog.Println(\"ward: hello\")\n\tpulse := time.Tick(interval)\n\tvar i int\n\tgo func() {\n\t\tfor {\n\t\t\tif i == 2 {\n\t\t\t\t// break things on purpose\n\t\t\t\t// to simulate some kind of\n\t\t\t\t// death spiral\n\t\t\t\tlog.Println(\"ward: death spiral\")\n\t\t\t\tpulse = nil\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase <-done:\n\t\t\t\tlog.Println(\"ward: halting\")\n\t\t\t\treturn\n\t\t\tcase <-pulse:\n\t\t\t\tlog.Println(\"ward: pulse\")\n\t\t\t\tselect {\n\t\t\t\tcase heartbeat <- struct{}{}:\n\t\t\t\t\ti++\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\treturn heartbeat\n}", "func (s *BasemumpsListener) EnterHalt_(ctx *Halt_Context) {}", "func (s *Server) run() {\n\tgo s.runProto()\n\tfor {\n\t\tif s.PeerCount() < s.MinPeers {\n\t\t\ts.discovery.RequestRemote(s.AttemptConnPeers)\n\t\t}\n\t\tif s.discovery.PoolCount() < minPoolCount {\n\t\t\ts.broadcastHPMessage(NewMessage(CMDGetAddr, payload.NewNullPayload()))\n\t\t}\n\t\tselect {\n\t\tcase <-s.quit:\n\t\t\treturn\n\t\tcase p := <-s.register:\n\t\t\ts.lock.Lock()\n\t\t\ts.peers[p] = true\n\t\t\ts.lock.Unlock()\n\t\t\tpeerCount := s.PeerCount()\n\t\t\ts.log.Info(\"new peer connected\", zap.Stringer(\"addr\", p.RemoteAddr()), zap.Int(\"peerCount\", peerCount))\n\t\t\tif peerCount > s.MaxPeers {\n\t\t\t\ts.lock.RLock()\n\t\t\t\t// Pick a random peer and drop connection to it.\n\t\t\t\tfor peer := range s.peers {\n\t\t\t\t\t// It will send us unregister signal.\n\t\t\t\t\tgo peer.Disconnect(errMaxPeers)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ts.lock.RUnlock()\n\t\t\t}\n\t\t\tupdatePeersConnectedMetric(s.PeerCount())\n\n\t\tcase drop := <-s.unregister:\n\t\t\ts.lock.Lock()\n\t\t\tif s.peers[drop.peer] {\n\t\t\t\tdelete(s.peers, drop.peer)\n\t\t\t\ts.lock.Unlock()\n\t\t\t\ts.log.Warn(\"peer disconnected\",\n\t\t\t\t\tzap.Stringer(\"addr\", drop.peer.RemoteAddr()),\n\t\t\t\t\tzap.Error(drop.reason),\n\t\t\t\t\tzap.Int(\"peerCount\", s.PeerCount()))\n\t\t\t\taddr := drop.peer.PeerAddr().String()\n\t\t\t\tif drop.reason == errIdenticalID {\n\t\t\t\t\ts.discovery.RegisterBadAddr(addr)\n\t\t\t\t} else if drop.reason == errAlreadyConnected {\n\t\t\t\t\t// There is a race condition when peer can be disconnected twice for the this reason\n\t\t\t\t\t// which can lead to no connections to peer at all. Here we check for such a possibility.\n\t\t\t\t\tstillConnected := false\n\t\t\t\t\ts.lock.RLock()\n\t\t\t\t\tverDrop := drop.peer.Version()\n\t\t\t\t\taddr := drop.peer.PeerAddr().String()\n\t\t\t\t\tif verDrop != nil {\n\t\t\t\t\t\tfor peer := range s.peers {\n\t\t\t\t\t\t\tver := peer.Version()\n\t\t\t\t\t\t\t// Already connected, drop this connection.\n\t\t\t\t\t\t\tif ver != nil && ver.Nonce == verDrop.Nonce && peer.PeerAddr().String() == addr {\n\t\t\t\t\t\t\t\tstillConnected = true\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ts.lock.RUnlock()\n\t\t\t\t\tif !stillConnected {\n\t\t\t\t\t\ts.discovery.UnregisterConnectedAddr(addr)\n\t\t\t\t\t\ts.discovery.BackFill(addr)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\ts.discovery.UnregisterConnectedAddr(addr)\n\t\t\t\t\ts.discovery.BackFill(addr)\n\t\t\t\t}\n\t\t\t\tupdatePeersConnectedMetric(s.PeerCount())\n\t\t\t} else {\n\t\t\t\t// else the peer is already gone, which can happen\n\t\t\t\t// because we have two goroutines sending signals here\n\t\t\t\ts.lock.Unlock()\n\t\t\t}\n\t\t}\n\t}\n}", "func Touch(noodles map[string]chan gotocol.Message) {\n\tvar msg gotocol.Message\n\tnames := make([]string, len(noodles)) // indexable name list\n\tlistener := make(chan gotocol.Message)\n\tgraphml.Setup()\n\tgraphjson.Setup()\n\tfmt.Println(\"Hello\")\n\ti := 0\n\tfor name, noodle := range noodles {\n\t\tgraphml.WriteNode(name)\n\t\tgraphjson.WriteNode(name)\n\t\tnoodle <- gotocol.Message{gotocol.Hello, listener, name}\n\t\tnames[i] = name\n\t\ti = i + 1\n\t}\n\tfmt.Println(\"Talk amongst yourselves for\", ChatSleep)\n\trand.Seed(int64(len(noodles)))\n\tstart := time.Now()\n\tfor i := 0; i < len(names); i++ {\n\t\t// for each pirate tell them about two other random pirates\n\t\tnoodle := noodles[names[i]] // lookup the channel\n\t\t// pick a first random pirate to tell this one about\n\t\ttalkto := names[rand.Intn(len(names))]\n\t\tnoodle <- gotocol.Message{gotocol.NameDrop, noodles[talkto], talkto}\n\t\t// pick a second random pirate to tell this one about\n\t\ttalkto = names[rand.Intn(len(names))]\n\t\tnoodle <- gotocol.Message{gotocol.NameDrop, noodles[talkto], talkto}\n\t\t// send this pirate a random amount of GoldCoin up to 100\n\t\tgold := fmt.Sprintf(\"%d\", rand.Intn(100))\n\t\tnoodle <- gotocol.Message{gotocol.GoldCoin, listener, gold}\n\t\t// tell this pirate to start chatting with friends every 1-60s\n\t\tdelay := fmt.Sprintf(\"%ds\", 1+rand.Intn(59))\n\t\tnoodle <- gotocol.Message{gotocol.Chat, nil, delay}\n\t}\n\td := time.Since(start)\n\tfmt.Println(\"Delivered\", 4*len(names), \"messages in\", d)\n\tif ChatSleep >= time.Millisecond {\n\t\ttime.Sleep(ChatSleep)\n\t}\n\tfmt.Println(\"Go away\")\n\tfor _, noodle := range noodles {\n\t\tnoodle <- gotocol.Message{gotocol.Goodbye, nil, \"beer volcano\"}\n\t}\n\tfor len(noodles) > 0 {\n\t\tmsg = <-listener\n\t\t// fmt.Println(msg)\n\t\tswitch msg.Imposition {\n\t\tcase gotocol.Inform:\n\t\t\tgraphml.Write(msg.Intention)\n\t\t\tgraphjson.Write(msg.Intention)\n\t\tcase gotocol.Goodbye:\n\t\t\tdelete(noodles, msg.Intention)\n\t\t\tfmt.Printf(\"Pirate population: %v \\r\", len(noodles))\n\t\t}\n\t}\n\tfmt.Println(\"\\nExit\")\n\tgraphml.Close()\n\tgraphjson.Close()\n}", "func wierdServer(w http.ResponseWriter, req *http.Request) {\n\tnotify := w.(http.CloseNotifier).CloseNotify()\n\n\tgo func() {\n\n\t}()\n\n\theadOrTails := rand.Intn(2)\n\n\tif headOrTails == 0 {\n\t\tlog.Printf(\"Go! slow %v\\n\", headOrTails)\n\t\tselect {\n\t\tcase <-notify:\n\t\t\tlog.Println(\"Http connection just closed\")\n\t\tcase <-time.After(6 * time.Second):\n\t\t\tfmt.Fprintf(w, \"Go! slow %v\\n\", headOrTails)\n\n\t\t}\n\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, \"Go! quick %v\\n\", headOrTails)\n\tlog.Printf(\"Go! quick %v\\n\", headOrTails)\n\treturn\n}", "func (s *raftServer) serve() {\n\ts.writeToLog(\"Started serve\")\n\tfor {\n\t\tselect {\n\t\tcase e := <-s.server.Inbox():\n\t\t\t// received a message on server's inbox\n\t\t\tmsg := e.Msg\n\t\t\tif ae, ok := msg.(AppendEntry); ok { // AppendEntry\n\t\t\t\tacc := s.handleAppendEntry(e.Pid, &ae)\n\t\t\t\tif acc {\n\t\t\t\t\tcandidateTimeout := time.Duration(s.duration + s.rng.Int63n(RandomTimeoutRange))\n\t\t\t\t\t// reset election timer if valid message received from server\n\t\t\t\t\ts.eTimeout.Reset(candidateTimeout * time.Millisecond)\n\t\t\t\t}\n\t\t\t} else if rv, ok := msg.(RequestVote); ok { // RequestVote\n\t\t\t\ts.handleRequestVote(e.Pid, &rv) // reset election timeout here too ? To avoid concurrent elections ?\n\t\t\t}\n\n\t\t\t// TODO handle EntryReply message\n\n\t\tcase <-s.eTimeout.C:\n\t\t\t// received timeout on election timer\n\t\t\ts.writeToLog(\"Starting Election\")\n\t\t\t// TODO: Use glog\n\t\t\ts.startElection()\n\t\t\ts.writeToLog(\"Election completed\")\n\t\t\tif s.isLeader() {\n\t\t\t\ts.hbTimeout.Reset(time.Duration(s.hbDuration) * time.Millisecond)\n\t\t\t\ts.eTimeout.Stop() // leader should not time out for election\n\t\t\t}\n\t\tcase <-s.hbTimeout.C:\n\t\t\ts.writeToLog(\"Sending hearbeats\")\n\t\t\ts.sendHeartBeat()\n\t\t\ts.hbTimeout.Reset(time.Duration(s.hbDuration) * time.Millisecond)\n\t\tdefault:\n\t\t\ttime.Sleep(1 * time.Millisecond) // sleep to avoid busy looping\n\t\t}\n\t}\n}", "func Client(otherServer string, doExit <-chan struct{},\n\ttickerDuration time.Duration) {\n\tvar (\n\t\tgpsCoord gps.GPSCoord\n\t\tticker *time.Ticker\n\t\ttransport *http.Transport = &http.Transport{\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tDial: (&net.Dialer{\n\t\t\t\tTimeout: 20 * time.Second,\n\t\t\t\tKeepAlive: 30 * time.Second,\n\t\t\t}).Dial,\n\t\t\tTLSClientConfig: nil,\n\t\t\tTLSHandshakeTimeout: 5 * time.Second,\n\t\t\t//Use compression:\n\t\t\tDisableCompression: false,\n\t\t\t//TCP connections are reused:\n\t\t\tDisableKeepAlives: false,\n\t\t\tResponseHeaderTimeout: 5 * time.Second,\n\t\t}\n\t\tclient *http.Client = &http.Client{\n\t\t\tTransport: transport,\n\t\t\t//Timeout duration:\n\t\t\tTimeout: 20 * time.Second,\n\t\t}\n\t\tbuf bytes.Buffer\n\t\tdecoder *json.Decoder\n\t\tfetchUrl string\n\t\tr *http.Response\n\t\terr error\n\t)\n\n\tbuf.WriteString(otherServer)\n\tbuf.WriteString(EndPointPath)\n\tfetchUrl = buf.String()\n\n\tticker = time.NewTicker(tickerDuration)\n\tfor {\n\t\tselect {\n\t\tcase _ = <-doExit:\n\t\t\tticker.Stop()\n\t\t\tticker = nil\n\t\t\ttransport = nil\n\t\t\tclient = nil\n\t\t\treturn\n\t\tcase _ = <-ticker.C:\n\t\t\tif r, err = client.Get(buf.String()); err != nil {\n\t\t\t\tlogging.Printf(\"ERROR, othergps: fetching %s: %s\\n\",\n\t\t\t\t\tfetchUrl, err.Error())\n\t\t\t\tgpsCoord.FetchUrl = fetchUrl\n\t\t\t\tgpsCoord.FetchError = err.Error()\n\t\t\t\tcache.OtherGPS.SetGPSCoord(gpsCoord)\n\t\t\t\tcontinue //reloops in the for loop\n\t\t\t}\n\n\t\t\tif r.Body == nil {\n\t\t\t\tmsg := \"ERROR No HTTP body in reponse from otherservers /otherserver HTTP endpoint\"\n\t\t\t\tlogging.Printf(msg)\n\t\t\t\tgpsCoord.FetchUrl = fetchUrl\n\t\t\t\tgpsCoord.FetchError = err.Error()\n\t\t\t\tcache.OtherGPS.SetGPSCoord(gpsCoord)\n\t\t\t\tcontinue //reloops in the for loop\n\t\t\t}\n\n\t\t\tdecoder = json.NewDecoder(r.Body)\n\t\t\tif err = decoder.Decode(&gpsCoord); err != nil {\n\t\t\t\tformat := \"ERROR during othergps gpsd JSON document decoding %s: %s\\n\"\n\t\t\t\treportedErr := fmt.Errorf(format, fetchUrl, err.Error())\n\t\t\t\tlogging.Printf(\"%s\\n\", reportedErr.Error())\n\t\t\t\tgpsCoord.FetchUrl = fetchUrl\n\t\t\t\tgpsCoord.FetchError = reportedErr.Error()\n\t\t\t\tcache.OtherGPS.SetGPSCoord(gpsCoord)\n\t\t\t\tcontinue //reloops in the for loop\n\t\t\t}\n\n\t\t\t//else: success!\n\t\t\tgpsCoord.FetchUrl = \"\"\n\t\t\tgpsCoord.FetchError = \"\"\n\t\t\tcache.OtherGPS.SetGPSCoord(gpsCoord)\n\t\t}\n\n\t\tif r != nil {\n\t\t\tio.Copy(ioutil.Discard, r.Body)\n\t\t\tr.Body.Close()\n\t\t}\n\t}\n}", "func attack(attacker Attack, next, quit <-chan bool, results chan<- result, timeout time.Duration) {\n\tfor {\n\t\tselect {\n\t\tcase <-next:\n\t\t\tbegin := time.Now()\n\t\t\tdone := make(chan DoResult)\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\t\t\tdefer cancel()\n\t\t\tgo func() {\n\t\t\t\tdone <- attacker.Do(ctx)\n\t\t\t}()\n\t\t\tvar dor DoResult\n\t\t\t// either get the result from the attacker or from the timeout\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tdor = DoResult{RequestLabel: \"timeout\", Error: errAttackDoTimedOut}\n\t\t\tcase dor = <-done:\n\t\t\t}\n\t\t\tend := time.Now()\n\t\t\tresults <- result{\n\t\t\t\tdoResult: dor,\n\t\t\t\tbegin: begin,\n\t\t\t\tend: end,\n\t\t\t\telapsed: end.Sub(begin),\n\t\t\t}\n\t\tcase <-quit:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (pd *philosopherData) FinishedEating() {\n\tpd.eating = false\n\tpd.leftChopstick = -1\n\tpd.rightChopstick = -1\n\tpd.finishedAt = time.Now()\n}", "func (ds *fakeDebugSession) doContinue() {\n\tvar e dap.Message\n\tds.bpSetMux.Lock()\n\tif ds.bpSet == 0 {\n\t\t// Pretend that the program is running.\n\t\t// The delay will allow for all in-flight responses\n\t\t// to be sent before termination.\n\t\ttime.Sleep(1000 * time.Millisecond)\n\t\te = &dap.TerminatedEvent{\n\t\t\tEvent: *newEvent(\"terminated\"),\n\t\t}\n\t} else {\n\t\te = &dap.StoppedEvent{\n\t\t\tEvent: *newEvent(\"stopped\"),\n\t\t\tBody: dap.StoppedEventBody{Reason: \"breakpoint\", ThreadId: 1, AllThreadsStopped: true},\n\t\t}\n\t\tds.bpSet--\n\t}\n\tds.bpSetMux.Unlock()\n\tds.send(e)\n}", "func (s *BaseLittleDuckListener) ExitCte(ctx *CteContext) {}", "func (srv *IOServerInstance) dPing(ctx context.Context) *system.MemberResult {\n\trank, err := srv.GetRank()\n\tif err != nil {\n\t\treturn nil // no rank to return result for\n\t}\n\n\tif !srv.isReady() {\n\t\treturn system.NewMemberResult(rank, \"ping\", nil, system.MemberStateStopped)\n\t}\n\n\tresChan := make(chan *system.MemberResult)\n\tgo func() {\n\t\tdresp, err := srv.CallDrpc(drpc.ModuleMgmt, drpc.MethodPingRank, nil)\n\t\tresChan <- drespToMemberResult(rank, \"ping\", dresp, err, system.MemberStateReady)\n\t}()\n\n\tselect {\n\tcase <-ctx.Done():\n\t\tif ctx.Err() == context.DeadlineExceeded {\n\t\t\treturn system.NewMemberResult(rank, \"ping\", ctx.Err(),\n\t\t\t\tsystem.MemberStateUnresponsive)\n\t\t}\n\t\treturn nil // shutdown\n\tcase result := <-resChan:\n\t\treturn result\n\t}\n}", "func (t *Tracker) Pong() {\n\t// acquire mutex\n\tt.mutex.Lock()\n\tdefer t.mutex.Unlock()\n\n\t// decrement\n\tt.pings--\n}", "func (host *DinnerHost) Init(tableCount, maxParallel, maxDinner int) {\n\thost.phiData = make(map[string]*philosopherData)\n\thost.requestChannel = make(chan string)\n\thost.finishChannel = make(chan string)\n\thost.maxParallel = maxParallel\n\tif host.maxParallel > tableCount {\n\t\thost.maxParallel = tableCount\n\t}\n\thost.maxDinner = maxDinner\n\thost.currentlyEating = 0\n\thost.tableCount = tableCount\n\thost.chopsticksFree = make([]bool, 5)\n\tfor i := range host.chopsticksFree {\n\t\thost.chopsticksFree[i] = true\n\t}\n\trand.Seed(time.Now().Unix())\n\thost.freeSeats = rand.Perm(tableCount)\n}", "func (pb *PhilosopherBase) CheckEating() {\n\t// Check the primary invariant - neither neighbor should be eating, and I should hold\n\t// both forks\n\tAssert(\n\t\tfunc() bool {\n\t\t\treturn pb.LeftPhilosopher().GetState() != philstate.Eating &&\n\t\t\t\tpb.RightPhilosopher().GetState() != philstate.Eating\n\t\t},\n\t\t\"eat while a neighbor is eating\",\n\t)\n\n\tAssert(\n\t\tfunc() bool {\n\t\t\treturn pb.LeftFork().IsHeldBy(pb.ID) &&\n\t\t\t\tpb.RightFork().IsHeldBy(pb.ID)\n\t\t},\n\t\t\"eat without holding forks\",\n\t)\n}", "func (d *Death) FallOnSword() {\n\tselect {\n\tcase d.callChannel <- struct{}{}:\n\tdefault:\n\t}\n}", "func (vs *ViewServer) tick() {\n\t\n\tvs.viewMu.Lock()\n\n\t// Primary !== \"\"\n\t// See if any server died\n\tfor k, v := range vs.pingKeeper{\n\t\tserver := k\n\t\tdifference := time.Since(v)\n\t\tif difference > PingInterval * DeadPings {\n\t\t\tswitch server {\n\t\t\tcase vs.currentView.Primary:\n\t\t\t\ttestLog(\"TICKED PRIMARY DIED \" + convertView(vs.currentView))\n\t\t\t\t// Primary died\n\t\t\t\t// Check if acked is true\n//\t\t\t\tfmt.Println(\"Primary: \", vs.currentView.Primary, \" died\")\n\t\t\t\tif vs.acked {\n\t\t\t\t\t// Check if backup is available\n\t\t\t\t\tif vs.currentView.Backup != \"\" {\n//\t\t\t\t\t\tfmt.Println(\"Put backup: \", vs.currentView.Backup, \" in\")\n\t\t\t\t\t\t// Turn backup into primary\n\t\t\t\t\t\tvs.currentView.Primary = vs.currentView.Backup\n\t\t\t\t\t\tvs.currentView.Backup = \"\"\n\n\t\t\t\t\t\t// Turn idle into backup\n\t\t\t\t\t\tif len(vs.idle) > 0 {\n//\t\t\t\t\t\t\tfmt.Println(\"TEST #150: \", vs.currentView)\n\t\t\t\t\t\t\tvs.currentView.Backup = vs.idle[0]\n//\t\t\t\t\t\t\tfmt.Println(\"TEST #151: \", vs.currentView)\n\t\t\t\t\t\t\tvs.idle = vs.idle[1:]\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tvs.acked = false\n\t\t\t\t\t\tvs.pingKeeper[k] = time.Now()\n\t\t\t\t\t\tvs.increaseViewNum();\n\t\t\t\t\t\ttestLog(\"ACKED = TRUE && PRIMARY DIED -> New view is \" + convertView(vs.currentView))\n\t\t\t\t\t}\n//\t\t\t\t\tfmt.Println(\"TEST #1: \", vs.currentView)\n\t\t\t\t} else {\n\t\t\t\t\t// crash!!!!\n\t\t\t\t}\n\n\t\t\tcase vs.currentView.Backup:\n\t\t\t\t// Backup died\n\t\t\t\t// Check if acked is true\n//\t\t\t\tfmt.Println(\"Backup: \", vs.currentView.Backup, \" died\")\n\t\t\t\ttestLog(\"TICKED BACKUP DIED \" + convertView(vs.currentView))\n\t\t\t\tif vs.acked {\n//\t\t\t\t\tfmt.Println(\"TEST #180: \", vs.currentView)\n\t\t\t\t\tvs.currentView.Backup = \"\"\n\t\t\t\t\tif len(vs.idle) > 0 {\n\t\t\t\t\t\tvs.currentView.Backup = vs.idle[0]\n//\t\t\t\t\t\tfmt.Println(\"TEST #2: \", vs.currentView)\n\t\t\t\t\t\tvs.idle = vs.idle[1:]\n\t\t\t\t\t}\n\t\t\t\t\tvs.acked = false\n\t\t\t\t\tvs.increaseViewNum();\n\t\t\t\t\ttestLog(\"ACKED = TRUE && BACKUP DIED -> New view is \" + convertView(vs.currentView))\n\t\t\t\t} else {\n\t\t\t\t\t// crash!!!!\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\t// Idle died\n\t\t\t\t// Delete from idle\n\t\t\t\tfor i, idleServer := range vs.idle {\n\t\t\t\t\tif server == idleServer {\n\t\t\t\t\t\tvs.idle = append(vs.idle[0:i], vs.idle[i+1:]...)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvs.viewMu.Unlock()\n}", "func carveRoutine() {\n msSleep(10)\n carvePaths(0, 0)\n finishChan <- struct{}{}\n}", "func elevatorDriver() {\n\tgoToFloor(0)\n\n\tfor {\n\t\tcurrentFloor, _ := store.GetCurrentFloor(selfHostname)\n\t\tif store.IsExistingHallCall(elevators.HallCall_s{Floor: currentFloor, Direction: elevators.DirectionBoth}) {\n\t\t\topenAndCloseDoors(currentFloor)\n\n\t\t\tstore.RemoveHallCalls(selfHostname, currentFloor)\n\t\t\torder_distributor.ShouldSendStateUpdate <- true\n\t\t}\n\n\t\tnextFloor := next_floor.GetNextFloor()\n\t\tif nextFloor != next_floor.NoNextFloor {\n\t\t\tgoToFloor(nextFloor)\n\t\t}\n\t\t<-store.ShouldRecalculateNextFloorChannel\n\t}\n}", "func tickGame() {\n\tfor {\n\t\tif isPlaying {\n\t\t\tmutex.Lock()\n\t\t\tfor _, node := range nodes {\n\t\t\t\tplayerIndex := string(node.Id[len(node.Id)-1])\n\t\t\t\tdirection := node.Direction\n\t\t\t\tx := node.CurrLoc.X\n\t\t\t\ty := node.CurrLoc.Y\n\t\t\t\tnew_x := node.CurrLoc.X\n\t\t\t\tnew_y := node.CurrLoc.Y\n\n\t\t\t\t// only predict for live nodes\n\t\t\t\tif isPlaying && node.IsAlive {\n\t\t\t\t\t// Path prediction\n\t\t\t\t\tboard[y][x] = \"t\" + playerIndex // Change position to be a trail.\n\t\t\t\t\tswitch direction {\n\t\t\t\t\tcase DIRECTION_UP:\n\t\t\t\t\t\tnew_y = intMax(0, y-1)\n\t\t\t\t\tcase DIRECTION_DOWN:\n\t\t\t\t\t\tnew_y = intMin(BOARD_SIZE-1, y+1)\n\t\t\t\t\tcase DIRECTION_LEFT:\n\t\t\t\t\t\tnew_x = intMax(0, x-1)\n\t\t\t\t\tcase DIRECTION_RIGHT:\n\t\t\t\t\t\tnew_x = intMin(BOARD_SIZE-1, x+1)\n\t\t\t\t\t}\n\n\t\t\t\t\tif nodeHasCollided(x, y, new_x, new_y) {\n\t\t\t\t\t\tlocalLog(\"NODE \" + node.Id + \" IS DEAD\")\n\t\t\t\t\t\tif isLeader() && node.Id == nodeId && node.IsAlive {\n\t\t\t\t\t\t\tnode.IsAlive = false\n\t\t\t\t\t\t\taliveNodes = aliveNodes - 1\n\t\t\t\t\t\t\tlocalLog(\"IM LEADER AND IM DEAD REPORTING TO FRONT END\")\n\t\t\t\t\t\t\tnotifyPlayerDeathToJS()\n\t\t\t\t\t\t\treportASorrowfulDeathToPeers(node)\n\t\t\t\t\t\t} else if isLeader() {\n\t\t\t\t\t\t\t// we tell peers who the dead node is.\n\t\t\t\t\t\t\tnode.IsAlive = false\n\t\t\t\t\t\t\taliveNodes = aliveNodes - 1\n\t\t\t\t\t\t\tlocalLog(\"Leader sending death report \", node.Id)\n\t\t\t\t\t\t\treportASorrowfulDeathToPeers(node)\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// We don't update the position to a new value\n\t\t\t\t\t\tboard[y][x] = getPlayerState(node.Id)\n\t\t\t\t\t\tif haveIWon() {\n\t\t\t\t\t\t\tlocalLog(\"Leader won\")\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Update player's new position.\n\t\t\t\t\t\tboard[new_y][new_x] = getPlayerState(node.Id)\n\t\t\t\t\t\tnode.CurrLoc.X = new_x\n\t\t\t\t\t\tnode.CurrLoc.Y = new_y\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tmutex.Unlock()\n\t\t}\n\t\trenderGame()\n\t\ttime.Sleep(tickRate)\n\t}\n}", "func PickWinner(w http.ResponseWriter, r *http.Request) {\n\n\ttblTickets := db.Table(\"Tickets\")\n\ttblWinners := db.Table(\"Winners\")\n\n\tvar tickets []pb.TicketReply_Ticket\n\terr := tblTickets.Scan().All(&tickets)\n\tif err != nil {\n\t\tfmt.Printf(err.Error())\n\t}\n\n\tvar moneyPot int64 = PRIZE\n\ttk := new(s.Tickets)\n\twinners := tk.GetWinners()\n\tif len(winners) > 0 {\n\t\tpastWinner := winners[0]\n\t\tfmt.Println(pastWinner)\n\t\tif !pastWinner.Claimed {\n\t\t\tmoneyPot = moneyPot + pastWinner.MoneyPot\n\t\t}\n\t}\n\n\tfmt.Printf(\"We have %d raffle tickets in the pot\\n\", len(tickets))\n\n\trd := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tvar luckyTicket = &tickets[rd.Intn(len(tickets))]\n\tfmt.Println(\"Magic 8-Ball says:\", luckyTicket.GetEmail())\n\n\tvar TimeNow = time.Now().Unix()\n\tstrTimeNow := strconv.FormatInt(TimeNow, 10)\n\tvar winner = &pb.WinnerReply_Winner{\n\t\tWinnerID: TimeNow,\n\t\tDateTime: strTimeNow,\n\t\tEntrants: strconv.Itoa(len(tickets)),\n\t\tWinningTicket: luckyTicket,\n\t\tClaimed: false,\n\t\tMoneyPot: moneyPot,\n\t}\n\ttblWinners.Put(winner).Run()\n\n\tdeleteExpiredTickets()\n\n\temailUsers(moneyPot)\n\n}", "func main() {\n\tquit := make(chan string)\n\tjane := boring(\"Jane!\")\n\tdaniel := boring(\"Daniel!\")\n\tother := boring(\"Timeout\")\n\n\tc := fanInSelect(jane, daniel)\n\ttimeOut(other, quit)\n\tfor i := 0; i < 5; i++ {\n\t\tfmt.Println(<-c, \"\\n\")\n\t}\n\n\tquit <- \"Bye!\"\n\tfmt.Printf(\"Timeout says: %q\\n\", <-quit)\n}", "func main() {\n\tfmt.Printf(\"Let's play some Chess!\\n♔ ♕ ♖ ♗ ♘ ♙ ♚ ♛ ♜ ♝ ♞ ♟\\n\")\n\t// initialize the board and place the pieces\n\tplacePieces(sessionPlayers)\n\n\t//To play the game, you can import the package, and wrapped in a loop around `IsGameEnded()` -\n\tfor !IsGameEnded() {\n\t\tplayer1.MovePiece(\"queen\", \"f6\")\n\t\tplayer2.MovePiece(\"bishop\", \"a8\")\n\t\tplayer1.MovePiece(\"pawn\", \"h4\")\n\t\tplayer1.KillKing() // Let's make player1 lose the game\n\t\tplayer1.MovePiece(\"king\", \"h6\") // Won't be evaluated\n\t}\n\tfmt.Printf(\"The game has ended!\\nThe winner is: %s\\n\", sessionPlayers[0].GetName())\n\n\t/* Another option, is to check each one of the moves (e.g - send all moves to channel and recive one by one to MovePiece(), etc).\n\t The function will return an error if the game already ended */\n\tplacePieces(sessionPlayers)\n\tif err := player1.MovePiece(\"queen\", \"f6\"); err != nil {\n\t\tfmt.Println(err)\n\t}\n\t/*\n\t\tSome more moves\n\t*/\n\tplayer1.KillKing()\n\tif err := player1.MovePiece(\"bishop\", \"a8\"); err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func (m *Manager) StartOutgoingManager() {\n\tretry := 5\n\n\tfor {\n\t\t// this loop ensures that we always reach out as the outgoing partner whenever needed\n\t\terr := m.Run()\n\n\t\tif err != nil {\n\t\t\tlog.LogWarn(\"failed to connect to partner, will retry...\")\n\t\t} else {\n\t\t\tlog.LogInfo(\"startOutgoingPartnerManager retrying...\")\n\t\t}\n\n\t\t<-time.After(time.Duration(time.Second * time.Duration(retry)))\n\t\tretry *= 2\n\t}\n}", "func (t *Truck) Diliver() bool {\n\tfmt.Println(\"Dilivering via Truck\")\n\treturn true\n}", "func moveDown(e *Elevator) *Elevator {\n\ttempArray := e.floorList\n\tfor i := e.floor; i > tempArray[len(tempArray)-1]; i-- {\n\t\tcurrentDoor := findDoorFromDoorsListById(e.floor, &e.floorDoorsList) // finding doors by id\n\t\tif currentDoor != nil && currentDoor.status == doorOpened || e.elevatorDoor.status == doorOpened {\n\t\t\tfmt.Println(\" Doors are open, closing doors before move down\")\n\t\t\tcloseDoors(e)\n\t\t}\n\t\tfmt.Printf(\"Moving elevator%s%d <down> from floor %d to floor %d\\n\", string(e.column.name), e.id, i, (i - 1))\n\t\tnextFloor := (i - 1)\n\t\te.floor = nextFloor\n\t\tupdateDisplays(e.floor, e)\n\n\t\tif contains(tempArray, nextFloor) {\n\t\t\topenDoors(e)\n\t\t\tdeleteFloorFromList(nextFloor, e)\n\t\t\tmanageButtonStatusOff(nextFloor, e)\n\t\t}\n\t}\n\tif len(e.floorList) == 0 {\n\t\te.status = elevatorIdle\n\t} else {\n\t\te.status = elevatorUp\n\t\tfmt.Println(\" Elevator is now going \" + e.status)\n\t}\n\n\treturn e\n}", "func (s *BaseLittleDuckListener) EnterCte(ctx *CteContext) {}", "func (me *Mgr) doPing() {\n\tfor !me.stopped {\n\t\tme.workers.Scan(func(id string, w interface{}) {\n\t\t\terr := w.(*Worker).Ping()\n\t\t\tif err != DEADERR {\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// dead\n\t\t\tme.deadChan <- id\n\t\t\tme.deadWorkers.Set(id, []byte(\"OK\"))\n\t\t\tme.workers.Delete(id)\n\t\t})\n\t\ttime.Sleep(15 * time.Second)\n\t}\n}", "func Loth(user string, loth *eribo.Loth, isNew bool, targets []*eribo.Player) string {\n\tswitch {\n\tcase loth == nil:\n\t\tmsg := `Unable to find eligible target.`\n\n\t\treturn clean(msg)\n\tcase loth != nil && !isNew:\n\t\tmsg := `Current 'lee of the hour is %s. Time left is %s.`\n\n\t\treturn fmt.Sprintf(clean(msg), loth.Name, loth.TimeLeft())\n\tcase loth != nil && isNew && user == loth.Name && len(targets) == 1:\n\t\tmsg := `/me looks around the room while performing calculations and\n\t\tseeking potentials targets. After a few seconds it stops and stares at\n\t\twhat seems to be the only eligible target. It grabs %s and injects them\n\t\twith a powerful serum which numbs their strength and reflexes but\n\t\tsharply increases their sensitivity. It leaves the victim half\n\t\tincapacitated on the floor then proceeds to announce to the whole room:\n\t\t\"New 'lee of the hour is %s!\"`\n\n\t\treturn fmt.Sprintf(clean(msg), loth.Name, loth.Name)\n\tcase loth != nil && isNew && user == loth.Name && len(targets) != 1:\n\t\tmsg := `/me appears to be malfunctioning as it doesn't seem to be\n\t\tseeking for other targets and turns towards the person that issued the\n\t\tcommand. It grabs %s and injects them with the serum instead!`\n\n\t\treturn fmt.Sprintf(clean(msg), loth.Name)\n\tcase loth != nil && isNew && user != loth.Name:\n\t\tmsg := `/me grabs %s and injects them with a powerful serum which numbs\n\t\ttheir strength and reflexes but sharply increases their sensitivity. It\n\t\tleaves the victim half incapacitated on the floor then proceeds to\n\t\tannounce to the whole room: \"New 'lee of the hour is %s!\"`\n\n\t\treturn fmt.Sprintf(clean(msg), loth.Name, loth.Name)\n\tdefault:\n\t\treturn fmt.Sprintf(\"/me looks confused and doesn't do anything at all.\")\n\t}\n}", "func (_GameJam *GameJamTransactor) PayoutWinner(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _GameJam.contract.Transact(opts, \"payoutWinner\")\n}", "func (storeShelf *inventory)CokeDelivery(){\n\tfor i := 0; i < 20; i++ {\n\t\tstoreShelf.inventoryCokeCount +=24\n\t\tstoreShelf.costCoke += 6.0\n\t\ttime.Sleep(5000 * time.Millisecond)\n\t\tfmt.Println(\"24 cans of Coke added to the shelf by the stocker\")\n\t}\n}", "func Lift(c <-chan struct{}) DoneChan { return DoneChan(c) }", "func (t *Transport) Dial() (net.Conn, error) {\n\t// Cleanup functions to run before returning, in case of an error.\n\tvar cleanup []func()\n\tdefer func() {\n\t\t// Run cleanup in reverse order, as defer does.\n\t\tfor i := len(cleanup) - 1; i >= 0; i-- {\n\t\t\tcleanup[i]()\n\t\t}\n\t}()\n\n\t// Prepare to collect remote WebRTC peers.\n\tsnowflakes, err := NewPeers(t.dialer)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcleanup = append(cleanup, func() { snowflakes.End() })\n\n\t// Use a real logger to periodically output how much traffic is happening.\n\tsnowflakes.BytesLogger = NewBytesSyncLogger()\n\n\tlog.Printf(\"---- SnowflakeConn: begin collecting snowflakes ---\")\n\tgo connectLoop(snowflakes)\n\n\t// Create a new smux session\n\tlog.Printf(\"---- SnowflakeConn: starting a new session ---\")\n\tpconn, sess, err := newSession(snowflakes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcleanup = append(cleanup, func() {\n\t\tpconn.Close()\n\t\tsess.Close()\n\t})\n\n\t// On the smux session we overlay a stream.\n\tstream, err := sess.OpenStream()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Begin exchanging data.\n\tlog.Printf(\"---- SnowflakeConn: begin stream %v ---\", stream.ID())\n\tcleanup = append(cleanup, func() { stream.Close() })\n\n\t// All good, clear the cleanup list.\n\tcleanup = nil\n\treturn &SnowflakeConn{Stream: stream, sess: sess, pconn: pconn, snowflakes: snowflakes}, nil\n}", "func boardLoop() {\n\tvar winner models.Winner = models.NoWinner\n\n\tfor {\n\t\ttime.Sleep(speed)\n\n\t\tboardLock.Lock()\n\t\tif winner == models.NoWinner {\n\t\t\twinner, _ = board.Advance()\n\t\t}\n\t\tif gameType == Server {\n\t\t\t*boardOutput <- board\n\t\t}\n\n\t\tboardLock.Unlock()\n\t}\n}", "func (_GameJam *GameJamTransactorSession) PayoutWinner() (*types.Transaction, error) {\n\treturn _GameJam.Contract.PayoutWinner(&_GameJam.TransactOpts)\n}", "func (mgr *manager) step_Winddown() mgr_step {\n\tif len(mgr.wards) == 0 {\n\t\treturn mgr.step_Terminated\n\t}\n\n\tselect {\n\tcase childDone := <-mgr.ctrlChan_childDone:\n\t\tmgr.reapChild(childDone)\n\t\treturn mgr.step_Winddown\n\n\tcase <-mgr.ctrlChan_quit.Selectable():\n\t\tmgr.cancelAll()\n\t\treturn mgr.step_Quitting\n\tcase <-mgr.reportingTo.QuitCh():\n\t\tmgr.cancelAll()\n\t\treturn mgr.step_Quitting\n\t}\n}", "func (ponger *Ponger) Handle(_ phi.Task, message phi.Message) {\n\tswitch message := message.(type) {\n\tcase Ping:\n\t\tfmt.Println(\"Received Ping!\")\n\t\ttime.Sleep(WAIT_MILLIS * time.Millisecond)\n\t\tmessage.Responder <- Pong{}\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unexpected message type %T\", message))\n\t}\n}", "func (c *Conn) joinChennel() {\n\ttime.Sleep(time.Second * 2)\n\tc.SendMsg(c.joinMsg)\n}", "func (dm *DMMasterClient) EvictDMMasterLeader(retryOpt *utils.RetryOption) error {\n\treturn nil\n}", "func send(h p2p.Host, peer p2p.Peer, message []byte, lostPeer chan p2p.Peer) {\n\t// Add attack code here.\n\t//attack.GetInstance().Run()\n\tbackoff := p2p.NewExpBackoff(250*time.Millisecond, 5*time.Second, 2)\n\n\tfor trial := 0; trial < 3; trial++ {\n\t\terr := h.SendMessage(peer, message)\n\t\t// No need to retry if new stream error or no error\n\t\tif err == nil || err == p2p.ErrNewStream {\n\t\t\tif trial > 0 {\n\t\t\t\tlog.Warn(\"retry send\", \"rety\", trial)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tlog.Info(\"sleeping before trying to send again\",\n\t\t\t\"duration\", backoff.Cur, \"addr\", net.JoinHostPort(peer.IP, peer.Port))\n\t\tbackoff.Sleep()\n\t}\n\tlog.Error(\"gave up sending a message\", \"addr\", net.JoinHostPort(peer.IP, peer.Port))\n\n\tif lostPeer != nil {\n\t\t// Notify lostPeer channel\n\t\tlostPeer <- peer\n\t}\n}", "func poke(conn *ExtendedConnection) {\n\tconn.Counter += 1\n\tfmt.Println(\"Poke-Event triggered! Counter:\", conn.Counter)\n\tconn.answer(\"Ouch I am sensible!\")\n}", "func (t *Tournament) End() {\n\tif !t.hasEnded() {\n\t\tn := t.generateWinnerNum()\n\n\t\tt.Winner = Winner{\n\t\t\tPlayer: t.Participants[n],\n\t\t\tPrize: t.Deposit,\n\t\t}\n\n\t\tt.Participants[n].Fund(t.Deposit)\n\t\tt.Balance = 0\n\t}\n}", "func (s *Server) DialZK(ctx context.Context, wg *sync.WaitGroup, c *kafkazk.Config) error {\n\tif s.test {\n\t\ts.ZK = &kafkazk.Mock{}\n\t\treturn nil\n\t}\n\n\twg.Add(1)\n\n\t// Init.\n\tzk, err := kafkazk.NewHandler(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.ZK = zk\n\n\t// Test readiness.\n\tzkReadyWait := 250 * time.Millisecond\n\ttime.Sleep(zkReadyWait)\n\n\tif !zk.Ready() {\n\t\treturn fmt.Errorf(\"failed to dial ZooKeeper in %s\", zkReadyWait)\n\t}\n\n\tlog.Printf(\"Connected to ZooKeeper: %s\\n\", c.Connect)\n\n\t// Pass the Handler to the underlying TagHandler Store\n\t// and call the Init procedure.\n\t// TODO this needs to go somewhere else.\n\ts.Tags.Store.(*ZKTagStorage).ZK = zk\n\tif err := s.Tags.Store.(*ZKTagStorage).Init(); err != nil {\n\t\treturn fmt.Errorf(\"failed to initialize ZooKeeper TagStorage backend\")\n\t}\n\n\t// Shutdown procedure.\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tzk.Close()\n\t\twg.Done()\n\t}()\n\n\treturn nil\n}", "func roller(coco chan<- Choco, speed float64) {\n\tfor i := 0; i < chocolateCount; i++ {\n\t\ttime.Sleep(time.Duration(500/speed) * time.Millisecond)\n\t\tfmt.Printf(\"[%-6s] -> choco (%d)\\n\", \"Roller\", i)\n\t\tcoco <- Choco{ID: i, TimeStamp: time.Now()}\n\t}\n\tclose(coco)\n}", "func (pb *PhilosopherBase) StartEating() {\n\tpb.WriteString(\"starts eating\")\n\tpb.DelaySend(pb.EatRange, NewState{NewState: philstate.Thinking})\n}" ]
[ "0.5729119", "0.5635951", "0.56148916", "0.559557", "0.5228737", "0.52256316", "0.51586217", "0.5119277", "0.4931039", "0.49038693", "0.4749317", "0.47387576", "0.47223052", "0.4682754", "0.46815524", "0.4660881", "0.46517307", "0.46229792", "0.46051443", "0.45768726", "0.45766753", "0.4537217", "0.4535885", "0.45139366", "0.4512331", "0.44951305", "0.44839403", "0.44831356", "0.44349512", "0.44319457", "0.4431445", "0.4424713", "0.4382404", "0.43760866", "0.43557313", "0.43454152", "0.4329471", "0.43140015", "0.43077618", "0.43069547", "0.4300374", "0.42982182", "0.42881873", "0.4277871", "0.4275736", "0.42713374", "0.42644352", "0.42610475", "0.4260818", "0.42411673", "0.4226869", "0.42186546", "0.4218591", "0.42182994", "0.4210445", "0.42062482", "0.41973934", "0.4193283", "0.41878444", "0.4181476", "0.4181432", "0.41803297", "0.4179148", "0.41740403", "0.41608787", "0.41539302", "0.41417181", "0.41395253", "0.41371065", "0.41352355", "0.41326898", "0.41316018", "0.41233212", "0.41213405", "0.41190454", "0.4117879", "0.41170835", "0.4113712", "0.41117483", "0.4110292", "0.41097257", "0.41062123", "0.40984252", "0.40846947", "0.40794945", "0.4075662", "0.40711224", "0.40704763", "0.40641105", "0.4060751", "0.4058944", "0.40513065", "0.40497825", "0.4048416", "0.40464857", "0.40448713", "0.4043623", "0.40421706", "0.40408292", "0.4039949" ]
0.7880031
0
ID Application's transaction handler callback
func TxHandler(tx dto.Transaction, state state.State) error { // deserialize the requested operation in the transaction var op *Operation var err error if op, err = DecodeOperation(tx.Request().Payload); err != nil { logger.Debug("Operation decode failed: %s", err) return err } // handle the opcode specific operation switch op.OpCode { case OpCodeRegisterAttribute: err = registerAttribute(op.Args, NewIdState(tx.Request().SubmitterId, state)) case OpCodeEndorseAttribute: err = endorseAttribute(op.Args, NewIdState(tx.Request().SubmitterId, state)) default: err = fmt.Errorf("unsupported op-code: %d", op.OpCode) } return err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (srv *Server) walletTransactionHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {\n\t// Parse the id from the url.\n\tvar id types.TransactionID\n\tjsonID := \"\\\"\" + ps.ByName(\"id\") + \"\\\"\"\n\terr := id.UnmarshalJSON([]byte(jsonID))\n\tif err != nil {\n\t\twriteError(w, \"error after call to /wallet/history: \"+err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\ttxn, ok := srv.wallet.Transaction(id)\n\tif !ok {\n\t\twriteError(w, \"error when calling /wallet/transaction/$(id): transaction not found\", http.StatusBadRequest)\n\t\treturn\n\t}\n\twriteJSON(w, WalletTransactionGETid{\n\t\tTransaction: txn,\n\t})\n}", "func Transaction(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tt, ctx := orm.NewTransaction(r.Context())\n\t\tdefer func() {\n\t\t\tif rec := recover(); rec != nil {\n\t\t\t\tt.Rollback()\n\t\t\t\t// Panic to let recoverer handle 500\n\t\t\t\tpanic(rec)\n\t\t\t} else {\n\t\t\t\terr := t.Commit()\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t}\n\treturn http.HandlerFunc(fn)\n}", "func Transaction(fn func (tx *sql.Tx) (interface{}, *sql.Stmt, error)) (interface{}, error) {\n\n\tdefer func(){\n\t\tstr := recover()\n\t\tif str != nil{\n\t\t\tlog.Println(\"panic occur: \", str)\n\t\t}\n\t}()\n\n\tlog.Println(\"opening connection database\")\n\n\tdb, err := GetConnection()\n\tif err != nil {\n\t\tlog.Println(\"could not open connection\", err)\n\t\treturn nil, err\n\t}\n\tdefer func(){\n\t\tlog.Println(\"m=Transaction,msg=closing connection\")\n\t\tdb.Close()\n\t}()\n\n\tlog.Println(\"begin transaction\")\n\ttx,err := db.Begin()\n\tif err != nil {\n\t\tlog.Println(\"could not open transaction\", err)\n\t\treturn nil, err\n\t}\n\n\tlog.Println(\"calling callback\")\n\tit, stm, err := fn(tx)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\tlog.Println(\"could not run stm\", err)\n\t\treturn nil, err\n\t}\n\tdefer func(){\n\t\tlog.Println(\"closed stm\")\n\t\tstm.Close()\n\t}()\n\tlog.Println(\"callback successfull called, commiting\")\n\terr = tx.Commit()\n\tlog.Println(\"transaction commited\")\n\tif err != nil {\n\t\tlog.Println(\"could not commit transaction\", err)\n\t\treturn nil, err\n\t}\n\n\treturn it, err\n}", "func TxReceiverHandler(w http.ResponseWriter, r *http.Request) {\n\t// receive the payload and read\n\tvar tx TxReceiver\n\tif !ReadRESTReq(w, r, &tx) {\n\t\tWriteErrorResponse(w, http.StatusBadRequest, \"Cannot read request\")\n\t}\n\n\t// create a new pending transaction\n\tuserTx := core.NewPendingTx(tx.From, tx.To, core.TX_TRANSFER_TYPE, tx.Signature, tx.Message)\n\n\t// add the transaction to pool\n\terr := core.DBInstance.InsertTx(&userTx)\n\tif err != nil {\n\t\tWriteErrorResponse(w, http.StatusBadRequest, \"Cannot read request\")\n\t}\n\n\toutput, err := json.Marshal(userTx)\n\tif err != nil {\n\t\tWriteErrorResponse(w, http.StatusBadRequest, \"Unable to marshall account\")\n\t}\n\n\t// write headers and data\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t_, _ = w.Write(output)\n\treturn\n}", "func createTransaction(\n\tctx context.Context,\n\tdb storage.Database,\n\tappserviceID string,\n) (\n\ttransactionJSON []byte,\n\ttxnID, maxID int,\n\teventsRemaining bool,\n\terr error,\n) {\n\t// Retrieve the latest events from the DB (will return old events if they weren't successfully sent)\n\ttxnID, maxID, events, eventsRemaining, err := db.GetEventsWithAppServiceID(ctx, appserviceID, transactionBatchSize)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"appservice\": appserviceID,\n\t\t}).WithError(err).Fatalf(\"appservice worker unable to read queued events from DB\")\n\n\t\treturn\n\t}\n\n\t// Check if these events do not already have a transaction ID\n\tif txnID == -1 {\n\t\t// If not, grab next available ID from the DB\n\t\ttxnID, err = db.GetLatestTxnID(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, 0, 0, false, err\n\t\t}\n\n\t\t// Mark new events with current transactionID\n\t\tif err = db.UpdateTxnIDForEvents(ctx, appserviceID, maxID, txnID); err != nil {\n\t\t\treturn nil, 0, 0, false, err\n\t\t}\n\t}\n\n\tvar ev []*gomatrixserverlib.HeaderedEvent\n\tfor i := range events {\n\t\tev = append(ev, &events[i])\n\t}\n\n\t// Create a transaction and store the events inside\n\ttransaction := gomatrixserverlib.ApplicationServiceTransaction{\n\t\tEvents: gomatrixserverlib.HeaderedToClientEvents(ev, gomatrixserverlib.FormatAll),\n\t}\n\n\ttransactionJSON, err = json.Marshal(transaction)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (s *PollVoteStore) Transaction(callback func(*PollVoteStore) error) error {\n\tif callback == nil {\n\t\treturn kallax.ErrInvalidTxCallback\n\t}\n\n\treturn s.Store.Transaction(func(store *kallax.Store) error {\n\t\treturn callback(&PollVoteStore{store})\n\t})\n}", "func (m *Manager) RunInTransaction(ctx *context.Context, f func(tctx *context.Context) error) error {\n\ttx, err := m.db.Beginx()\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn fmt.Errorf(\"error when creating transction: %v\", err)\n\t}\n\n\tctx = NewContext(ctx, tx)\n\terr = m.acknowledgeService.Prepare(ctx)\n\tif err != nil {\n\t\tfmt.Printf(\"\\n[Commerce-Kit - RunInTransaction - Prepare] Error: %v\\n\", err)\n\t}\n\terr = f(ctx)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\tm.acknowledgeService.Acknowledge(ctx, \"rollback\", err.Error())\n\t\treturn err\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\tm.acknowledgeService.Acknowledge(ctx, \"rollback\", fmt.Sprintf(\"Error when commiting: %s\", err.Error()))\n\t\treturn fmt.Errorf(\"error when committing transaction: %v\", err)\n\t}\n\tm.acknowledgeService.Acknowledge(ctx, \"commit\", \"\")\n\tm.publishQueryModelEvents(ctx)\n\n\treturn nil\n}", "func (dao *InfoDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {\n\treturn dao.Ctx(ctx).Transaction(ctx, f)\n}", "func (s *SessionStore) Transaction(callback func(*SessionStore) error) error {\n\tif callback == nil {\n\t\treturn kallax.ErrInvalidTxCallback\n\t}\n\n\treturn s.Store.Transaction(func(store *kallax.Store) error {\n\t\treturn callback(&SessionStore{store})\n\t})\n}", "func (_AnchorChain *AnchorChainTransactor) Callback(opts *bind.TransactOpts, state bool, _result []string) (*types.Transaction, error) {\n\treturn _AnchorChain.contract.Transact(opts, \"callback\", state, _result)\n}", "func (h *Handler) txHandler(t Transaction, resultComm chan tx, comm chan txComm) {\n\tresp := make(chan tx)\n\tgo h.readPhase(t, resp)\n\tstate := Active\n\tfor {\n\t\tselect {\n\t\tcase result := <-resp:\n\t\t\tif state == Active {\n\t\t\t\tstate = Committed\n\t\t\t\tresultComm <- result\n\t\t\t}\n\t\t\t// right now we do not handle the aborted case,\n\t\t\t// i guess this Tx will just never send a result to the\n\t\t\t// txsHandler, which is Ok\n\t\tcase txMsg := <-comm:\n\t\t\t// Something that sucks with this one is that\n\t\t\t// we do not stop the actual call\n\t\t\t//\n\t\t\t// @TODO: Get a reference to the go routine and try to kill\n\t\t\t// it off somehow\n\t\t\tif txMsg.msg == Abort {\n\t\t\t\tif state == Committed {\n\t\t\t\t\ttxMsg.resp <- TooLate\n\t\t\t\t} else if state == Active || state == Aborted {\n\t\t\t\t\tstate = Aborted\n\t\t\t\t\ttxMsg.resp <- Success\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *PersonStore) Transaction(callback func(*PersonStore) error) error {\n\tif callback == nil {\n\t\treturn kallax.ErrInvalidTxCallback\n\t}\n\n\treturn s.Store.Transaction(func(store *kallax.Store) error {\n\t\treturn callback(&PersonStore{store})\n\t})\n}", "func (s *UserStore) Transaction(callback func(*UserStore) error) error {\n\tif callback == nil {\n\t\treturn kallax.ErrInvalidTxCallback\n\t}\n\n\treturn s.Store.Transaction(func(store *kallax.Store) error {\n\t\treturn callback(&UserStore{store})\n\t})\n}", "func (eventService *EventService) transactionCommit(call otto.FunctionCall) (result otto.Value) {\n\tlogger.Debug(\"Entering EventService.transactionCommit\", call)\n\tdefer func() { logger.Debug(\"Exiting EventService.transactionCommit\", result) }()\n\n\tcallback := call.Argument(0)\n\n\tvalue, err := call.This.Object().Call(\"serializeBuffer\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif len(value.String()) > 0 {\n\t\tlogger.Debug(\"Emitting event from EventService.transactionCommit\", value.String())\n\t\teventService.Stub.SetEvent(\"composer\", []byte(value.String()))\n\t}\n\n\t_, err = callback.Call(callback, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn otto.UndefinedValue()\n}", "func (s *PollStore) Transaction(callback func(*PollStore) error) error {\n\tif callback == nil {\n\t\treturn kallax.ErrInvalidTxCallback\n\t}\n\n\treturn s.Store.Transaction(func(store *kallax.Store) error {\n\t\treturn callback(&PollStore{store})\n\t})\n}", "func (dao *PagesDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {\n\treturn dao.Ctx(ctx).Transaction(ctx, f)\n}", "func (_AnchorChain *AnchorChainSession) Callback(state bool, _result []string) (*types.Transaction, error) {\n\treturn _AnchorChain.Contract.Callback(&_AnchorChain.TransactOpts, state, _result)\n}", "func (_AnchorChain *AnchorChainTransactorSession) Callback(state bool, _result []string) (*types.Transaction, error) {\n\treturn _AnchorChain.Contract.Callback(&_AnchorChain.TransactOpts, state, _result)\n}", "func TransactionHandler(w http.ResponseWriter, r *http.Request) {\n\taction := r.URL.Path[len(\"/api/transactions\"):]\n\n\tlog.Println(\"Handling method\", r.Method, \"with action\", action)\n\n\tswitch r.Method {\n\tcase \"POST\":\n\t\tswitch action {\n\t\tcase \"\": // Create new transaction\n\t\t\tbody, err := ioutil.ReadAll(r.Body)\n\t\t\tif err != nil {\n\t\t\t\tcreateJsonErrorResponse(w, r, http.StatusInternalServerError, ErrorForm, err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvar t TransactionResponse\n\n\t\t\terr = json.Unmarshal(body, &t)\n\t\t\tif err != nil {\n\t\t\t\tcreateJsonErrorResponse(w, r, http.StatusInternalServerError, ErrorJson, err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpass := []byte(t.Password)\n\n\t\t\ttx, e := createAndBroadcastTx(t.Recipient, *big.NewInt(t.Amount), pass)\n\n\t\t\tvar jsonResponse TransactionResponse\n\t\t\tif e == nil {\n\t\t\t\tjsonResponse = TransactionResponse{Amount: t.Amount, Recipient: t.Recipient, Status: ResponseOk, Hash: hex.EncodeToString(tx.Hash())}\n\t\t\t} else {\n\t\t\t\tjsonResponse = TransactionResponse{Amount: t.Amount, Recipient: t.Recipient, Status: ResponseFailed, ErrorText: e.Error()}\n\t\t\t}\n\n\t\t\tres, err := json.Marshal(jsonResponse)\n\t\t\tif err != nil {\n\t\t\t\tcreateJsonErrorResponse(w, r, http.StatusInternalServerError, ErrorJson, err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfmt.Fprintf(w, string(res))\n\t\tdefault:\n\t\t\tcreateJsonErrorResponse(w, r, http.StatusNotFound, Error404, fmt.Sprint(\"No action: \", r.Method, action))\n\t\t}\n\tcase \"GET\":\n\t\tswitch action {\n\t\tcase \"\":\n\t\t\tvar txs []TransactionJson\n\t\t\tfor _, tx := range Config.DeserializedTxs {\n\t\t\t\ttxs = append(txs, EncodeToFriendlyStruct(tx))\n\n\t\t\t}\n\n\t\t\tif len(txs) == 0 {\n\t\t\t\tfmt.Fprintf(w, string(\"[]\"))\n\t\t\t} else {\n\n\t\t\t\tres, err := json.Marshal(txs)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(\"Nope\", err.Error())\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprintf(w, string(res))\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\tdefault:\n\t\tcreateJsonErrorResponse(w, r, http.StatusNotFound, Error404, fmt.Sprint(\"No action: \", r.Method, action))\n\n\t}\n}", "func (s *CRDBStorage) inTransaction(ctx context.Context, callback func(tx *sql.Tx) error) error {\n\ttx, err := s.DB.BeginTx(ctx, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not begin transaction: %v\", err)\n\t}\n\tif err := callback(tx); err != nil {\n\t\treturn rollback(tx, err)\n\t}\n\tif err := tx.Commit(); err != nil {\n\t\treturn fmt.Errorf(\"could not commit transaction: %v\", err)\n\t}\n\n\treturn nil\n}", "func (s *Server) handleTransaction(client string, req *pb.Command) (err error) {\n\t// Get the transfer from the original command, will panic if nil\n\ttransfer := req.GetTransfer()\n\tmsg := fmt.Sprintf(\"starting transaction of %0.2f from %s to %s\", transfer.Amount, transfer.Account, transfer.Beneficiary)\n\ts.updates.Broadcast(req.Id, msg, pb.MessageCategory_LEDGER)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Handle Demo UI errors before the account lookup\n\tif transfer.OriginatingVasp != \"\" && transfer.OriginatingVasp != s.vasp.Name {\n\t\tlog.Info().Str(\"requested\", transfer.OriginatingVasp).Str(\"local\", s.vasp.Name).Msg(\"requested originator does not match local VASP\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrWrongVASP, \"message sent to the wrong originator VASP\"),\n\t\t)\n\t}\n\n\t// Lookup the account associated with the transfer originator\n\tvar account Account\n\tif err = LookupAccount(s.db, transfer.Account).First(&account).Error; err != nil {\n\t\tif errors.Is(err, gorm.ErrRecordNotFound) {\n\t\t\tlog.Info().Str(\"account\", transfer.Account).Msg(\"not found\")\n\t\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\t\tpb.Errorf(pb.ErrNotFound, \"account not found\"),\n\t\t\t)\n\t\t}\n\t\treturn fmt.Errorf(\"could not fetch account: %s\", err)\n\t}\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"account %04d accessed successfully\", account.ID), pb.MessageCategory_LEDGER)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Lookup the wallet of the beneficiary\n\tvar beneficiary Wallet\n\tif err = LookupBeneficiary(s.db, transfer.Beneficiary).First(&beneficiary).Error; err != nil {\n\t\tif errors.Is(err, gorm.ErrRecordNotFound) {\n\t\t\tlog.Info().Str(\"beneficiary\", transfer.Beneficiary).Msg(\"not found\")\n\t\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\t\tpb.Errorf(pb.ErrNotFound, \"beneficiary wallet not found\"),\n\t\t\t)\n\t\t}\n\t\treturn fmt.Errorf(\"could not fetch beneficiary wallet: %s\", err)\n\t}\n\n\tif transfer.CheckBeneficiary {\n\t\tif transfer.BeneficiaryVasp != beneficiary.Provider.Name {\n\t\t\tlog.Info().\n\t\t\t\tStr(\"expected\", transfer.BeneficiaryVasp).\n\t\t\t\tStr(\"actual\", beneficiary.Provider.Name).\n\t\t\t\tMsg(\"check beneficiary failed\")\n\t\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\t\tpb.Errorf(pb.ErrWrongVASP, \"beneficiary wallet does not match beneficiary vasp\"),\n\t\t\t)\n\t\t}\n\t}\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"wallet %s provided by %s\", beneficiary.Address, beneficiary.Provider.Name), pb.MessageCategory_BLOCKCHAIN)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// TODO: lookup peer from cache rather than always doing a directory service lookup\n\tvar peer *peers.Peer\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"search for %s in directory service\", beneficiary.Provider.Name), pb.MessageCategory_TRISADS)\n\tif peer, err = s.peers.Search(beneficiary.Provider.Name); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not search peer from directory service\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not search peer from directory service\"),\n\t\t)\n\t}\n\tinfo := peer.Info()\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"identified TRISA remote peer %s at %s via directory service\", info.ID, info.Endpoint), pb.MessageCategory_TRISADS)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\tvar signKey *rsa.PublicKey\n\ts.updates.Broadcast(req.Id, \"exchanging peer signing keys\", pb.MessageCategory_TRISAP2P)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\tif signKey, err = peer.ExchangeKeys(true); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not exchange keys with remote peer\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not exchange keyrs with remote peer\"),\n\t\t)\n\t}\n\n\t// Prepare the transaction\n\t// Save the pending transaction and increment the accounts pending field\n\txfer := Transaction{\n\t\tEnvelope: uuid.New().String(),\n\t\tAccount: account,\n\t\tAmount: decimal.NewFromFloat32(transfer.Amount),\n\t\tDebit: true,\n\t\tCompleted: false,\n\t}\n\n\tif err = s.db.Save(&xfer).Error; err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save transaction\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not save transaction\"),\n\t\t)\n\t}\n\n\t// Save the pending transaction on the account\n\t// TODO: remove pending transactions\n\taccount.Pending++\n\tif err = s.db.Save(&account).Error; err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save originator account\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not save originator account\"),\n\t\t)\n\t}\n\n\ts.updates.Broadcast(req.Id, \"ready to execute transaction\", pb.MessageCategory_BLOCKCHAIN)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Create an identity and transaction payload for TRISA exchange\n\ttransaction := &generic.Transaction{\n\t\tTxid: fmt.Sprintf(\"%d\", xfer.ID),\n\t\tOriginator: account.WalletAddress,\n\t\tBeneficiary: beneficiary.Address,\n\t\tAmount: float64(transfer.Amount),\n\t\tNetwork: \"TestNet\",\n\t\tTimestamp: xfer.Timestamp.Format(time.RFC3339),\n\t}\n\tidentity := &ivms101.IdentityPayload{\n\t\tOriginator: &ivms101.Originator{},\n\t\tOriginatingVasp: &ivms101.OriginatingVasp{},\n\t}\n\tif identity.OriginatingVasp.OriginatingVasp, err = s.vasp.LoadIdentity(); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not load originator vasp\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not load originator vasp\"),\n\t\t)\n\t}\n\n\tidentity.Originator = &ivms101.Originator{\n\t\tOriginatorPersons: make([]*ivms101.Person, 0, 1),\n\t\tAccountNumbers: []string{account.WalletAddress},\n\t}\n\tvar originator *ivms101.Person\n\tif originator, err = account.LoadIdentity(); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not load originator identity\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not load originator identity\"),\n\t\t)\n\t}\n\tidentity.Originator.OriginatorPersons = append(identity.Originator.OriginatorPersons, originator)\n\n\tpayload := &protocol.Payload{}\n\tif payload.Transaction, err = anypb.New(transaction); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not serialize transaction payload\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not serialize transaction payload\"),\n\t\t)\n\t}\n\tif payload.Identity, err = anypb.New(identity); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not serialize identity payload\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not serialize identity payload\"),\n\t\t)\n\t}\n\n\ts.updates.Broadcast(req.Id, \"transaction and identity payload constructed\", pb.MessageCategory_TRISAP2P)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Secure the envelope with the remote beneficiary's signing keys\n\tvar envelope *protocol.SecureEnvelope\n\tif envelope, err = handler.New(xfer.Envelope, payload, nil).Seal(signKey); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not create or sign secure envelope\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not create or sign secure envelope\"),\n\t\t)\n\t}\n\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"secure envelope %s sealed: encrypted with AES-GCM and RSA - sending ...\", envelope.Id), pb.MessageCategory_TRISAP2P)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Conduct the TRISA transaction, handle errors and send back to user\n\tif envelope, err = peer.Transfer(envelope); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not perform TRISA exchange\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, err.Error()),\n\t\t)\n\t}\n\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"received %s information exchange reply from %s\", envelope.Id, peer.String()), pb.MessageCategory_TRISAP2P)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Open the response envelope with local private keys\n\tvar opened *handler.Envelope\n\tif opened, err = handler.Open(envelope, s.trisa.sign); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not unseal TRISA response\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, err.Error()),\n\t\t)\n\t}\n\n\t// Verify the contents of the response\n\tpayload = opened.Payload\n\tif payload.Identity.TypeUrl != \"type.googleapis.com/ivms101.IdentityPayload\" {\n\t\tlog.Warn().Str(\"type\", payload.Identity.TypeUrl).Msg(\"unsupported identity type\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"unsupported identity type\", payload.Identity.TypeUrl),\n\t\t)\n\t}\n\n\tif payload.Transaction.TypeUrl != \"type.googleapis.com/trisa.data.generic.v1beta1.Transaction\" {\n\t\tlog.Warn().Str(\"type\", payload.Transaction.TypeUrl).Msg(\"unsupported transaction type\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"unsupported transaction type\", payload.Transaction.TypeUrl),\n\t\t)\n\t}\n\n\tidentity = &ivms101.IdentityPayload{}\n\ttransaction = &generic.Transaction{}\n\tif err = payload.Identity.UnmarshalTo(identity); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not unmarshal identity\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, err.Error()),\n\t\t)\n\t}\n\tif err = payload.Transaction.UnmarshalTo(transaction); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not unmarshal transaction\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, err.Error()),\n\t\t)\n\t}\n\n\ts.updates.Broadcast(req.Id, \"successfully decrypted and parsed secure envelope\", pb.MessageCategory_TRISAP2P)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Update the completed transaction and save to disk\n\txfer.Beneficiary = Identity{\n\t\tWalletAddress: transaction.Beneficiary,\n\t}\n\txfer.Completed = true\n\txfer.Timestamp, _ = time.Parse(time.RFC3339, transaction.Timestamp)\n\n\t// Serialize the identity information as JSON data\n\tvar data []byte\n\tif data, err = json.Marshal(identity); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save transaction\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not marshal IVMS 101 identity\"),\n\t\t)\n\t}\n\txfer.Identity = string(data)\n\n\tif err = s.db.Save(&xfer).Error; err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save transaction\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, err.Error()),\n\t\t)\n\t}\n\n\t// Save the pending transaction on the account\n\t// TODO: remove pending transactions\n\taccount.Pending--\n\taccount.Completed++\n\taccount.Balance.Sub(xfer.Amount)\n\tif err = s.db.Save(&account).Error; err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save transaction\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, err.Error()),\n\t\t)\n\t}\n\n\tmsg = fmt.Sprintf(\"transaction %04d complete: %s transfered from %s to %s\", xfer.ID, xfer.Amount.String(), xfer.Originator.WalletAddress, xfer.Beneficiary.WalletAddress)\n\ts.updates.Broadcast(req.Id, msg, pb.MessageCategory_BLOCKCHAIN)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"%04d new account balance: %s\", account.ID, account.Balance), pb.MessageCategory_LEDGER)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\trep := &pb.Message{\n\t\tType: pb.RPC_TRANSFER,\n\t\tId: req.Id,\n\t\tTimestamp: time.Now().Format(time.RFC3339),\n\t\tCategory: pb.MessageCategory_LEDGER,\n\t\tReply: &pb.Message_Transfer{Transfer: &pb.TransferReply{\n\t\t\tTransaction: xfer.Proto(),\n\t\t}},\n\t}\n\n\treturn s.updates.Send(client, rep)\n}", "func (dao *ConfigAuditProcessDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {\n\treturn dao.Ctx(ctx).Transaction(ctx, f)\n}", "func inTx(txCallback func(tx *sql.Tx) error) (err error) {\n\tvar tx *sql.Tx\n\n\tif tx, err = DbFacade.SqlDb.Begin(); err != nil {\n\t\treturn\n\t}\n\n\t/**\n\t * The transaction result by whether or not the callback has error\n\t */\n\tdefer func() {\n\t\tif err == nil {\n\t\t\ttx.Commit()\n\t\t} else {\n\t\t\ttx.Rollback()\n\t\t}\n\t}()\n\t// :~)\n\n\terr = txCallback(tx)\n\n\treturn\n}", "func (ap *DBApplier) handleTxnOp(ctx context.Context, meta txn.Meta, op db.Oplog) error {\n\tif meta.IsAbort() {\n\t\tif err := ap.txnBuffer.PurgeTxn(meta); err != nil {\n\t\t\treturn fmt.Errorf(\"can not clean txn buffer after rollback cmd: %w\", err)\n\t\t}\n\t}\n\tif err := ap.txnBuffer.AddOp(meta, op); err != nil {\n\t\treturn fmt.Errorf(\"can not append command to txn buffer: %w\", err)\n\t}\n\n\tif !meta.IsCommit() {\n\t\treturn nil\n\t}\n\n\tif err := ap.applyTxn(ctx, meta); err != nil {\n\t\treturn err\n\t}\n\n\tif err := ap.txnBuffer.PurgeTxn(meta); err != nil {\n\t\treturn fmt.Errorf(\"txn buffer failed to purge: %w\", err)\n\t}\n\n\treturn nil\n}", "func main() {\n\tif err := DoMain(); err != nil {\n\t\tlog.Fatalf(\"transaction: %v\", err)\n\t}\n}", "func (s *PetStore) Transaction(callback func(*PetStore) error) error {\n\tif callback == nil {\n\t\treturn kallax.ErrInvalidTxCallback\n\t}\n\n\treturn s.Store.Transaction(func(store *kallax.Store) error {\n\t\treturn callback(&PetStore{store})\n\t})\n}", "func (s *PollOptionStore) Transaction(callback func(*PollOptionStore) error) error {\n\tif callback == nil {\n\t\treturn kallax.ErrInvalidTxCallback\n\t}\n\n\treturn s.Store.Transaction(func(store *kallax.Store) error {\n\t\treturn callback(&PollOptionStore{store})\n\t})\n}", "func HandleTx(cmd *cobra.Command, txEvent rpctypes.ResultEvent) error {\n\treturn nil\n}", "func (ingest *Ingestion) Transaction(\n\tid int64,\n\ttx *core.Transaction,\n\tfee *core.TransactionFee,\n) error {\n\n\tsql := ingest.transactionInsertBuilder(id, tx, fee)\n\t_, err := ingest.DB.Exec(sql)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (dao *SysConfigDao) Transaction(ctx context.Context, f func(ctx context.Context, tx gdb.TX) error) (err error) {\n\treturn dao.Ctx(ctx).Transaction(ctx, f)\n}", "func (db *database) Transact(txHandler func(tx *sqlx.Tx) error) (err error) {\n\t// Start the transaction and receive a transaction handle.\n\ttx, err := db.Beginx()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to begin transaction\")\n\t}\n\n\t// Add deferred handler to clean up this transaction.\n\tdefer func() { err = db.cleanupTransaction(tx, err) }()\n\n\t// Call the transaction handler.\n\terr = txHandler(tx)\n\n\t// Remember, deferred cleanup ALWAYS runs after this.\n\treturn\n}", "func (m DBTransactionMiddleware) Handle() gin.HandlerFunc {\r\n\tm.logger.Zap.Info(\"setting up database transaction middleware\")\r\n\r\n\treturn func(c *gin.Context) {\r\n\t\ttxHandle := m.db.DB.Begin()\r\n\t\tm.logger.Zap.Info(\"beginning database transaction\")\r\n\r\n\t\tdefer func() {\r\n\t\t\tif r := recover(); r != nil {\r\n\t\t\t\ttxHandle.Rollback()\r\n\t\t\t}\r\n\t\t}()\r\n\r\n\t\tc.Set(constants.DBTransaction, txHandle)\r\n\t\tc.Next()\r\n\r\n\t\tif utils.StatusInList(c.Writer.Status(), []int{http.StatusOK, http.StatusCreated}) {\r\n\t\t\tm.logger.Zap.Info(\"committing transactions\")\r\n\t\t\tif err := txHandle.Commit().Error; err != nil {\r\n\t\t\t\tm.logger.Zap.Error(\"trx commit error: \", err)\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tm.logger.Zap.Info(\"rolling back transaction due to status code: \", c.Writer.Status())\r\n\t\t\ttxHandle.Rollback()\r\n\t\t}\r\n\t}\r\n}", "func GetTransactionHandler(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\t// retrieve the parameters\n\tparam := make(map[string]uint64)\n\tfor _, key := range []string{\"blockId\", \"txId\"} {\n\t\tparam[key], _ = strconv.ParseUint(vars[\"blockId\"], 10, 64)\n\t}\n\n\ttmp := atomic.LoadUint64(&lastBlock)\n\tif param[\"blockId\"] > tmp {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\terr := fmt.Errorf(\"requested id %d latest %d\", param[\"blockId\"], lastBlock)\n\t\tlog.Println(err.Error())\n\t\t_, _ = w.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\t// retuning anything in the body regardless of any error code\n\t// it may contain\n\t_, _, body, _ := dataCollection.GetTransaction(param[\"blockId\"], param[\"txId\"], config.DefaultRequestsTimeout)\n\twriteResponse(body, &w)\n}", "func (h *hotsContext) txn(ctx context.Context, fn func(txn *sqlx.Tx) error) error {\n\treturn retry(func() error {\n\t\ttxn, err := h.x.BeginTxx(ctx, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = fn(txn)\n\t\tif err == nil {\n\t\t\treturn txn.Commit()\n\t\t}\n\t\ttxn.Rollback()\n\t\treturn err\n\t})\n}", "func (db *DB) Transaction(fc func(db *DB) error) (err error) {\n\tpanicked := true\n\ttx := &DB{db.DB.Begin()}\n\n\tdefer func() {\n\t\t// Make sure to rollback when panic, Block error or Commit error\n\t\tif panicked || err != nil {\n\t\t\ttx.Rollback()\n\t\t}\n\t}()\n\n\terr = fc(tx)\n\tif err == nil {\n\t\terr = tx.DB.Commit().Error\n\t}\n\tpanicked = false\n\treturn\n}", "func (c *BsnCommitTxHandler) Handle(requestContext *RequestContext, clientContext *ClientContext) {\n\t//txnID := requestContext.Response.TransactionID\n\t//GatewayLog.Logs( \"CommitTxHandler Handle TXID 发送交易\",txnID)\n\t//Register Tx event\n\n\t//reg, statusNotifier, err := clientContext.EventService.RegisterTxStatusEvent(string(txnID)) // TODO: Change func to use TransactionID instead of string\n\t//if err != nil {\n\t//\trequestContext.Error = errors.Wrap(err, \"error registering for TxStatus event\")\n\t//\treturn\n\t//}\n\t//defer clientContext.EventService.Unregister(reg)\n\n\tres, err := createAndSendBsnTransaction(clientContext.Transactor, requestContext.Response.Proposal, requestContext.Response.Responses)\n\n\t//GatewayLog.Logs( \"CommitTxHandler Handle 交易结束\")\n\tif err != nil {\n\t\trequestContext.Error = errors.Wrap(err, \"CreateAndSendTransaction failed\")\n\t\treturn\n\t}\n\t//requestContext.Response.TxValidationCode = 0\n\t//GatewayLog.Logs( \"requestContext.Response.Payload :\",string(requestContext.Response.Payload))\n\t//GatewayLog.Logs( \"requestContext.Response.BlockNumber :\",string(requestContext.Response.BlockNumber))\n\t//GatewayLog.Logs( \"requestContext.Response.ChaincodeStatus :\",string(requestContext.Response.ChaincodeStatus))\n\t//select {\n\t//case txStatus := <-statusNotifier:\n\t//\t//GatewayLog.Logs(\"statusNotifier 结果接收 \",&txStatus)\n\t//\trequestContext.Response.TxValidationCode = txStatus.TxValidationCode\n\t//\trequestContext.Response.BlockNumber=txStatus.BlockNumber\n\t//\tif txStatus.TxValidationCode != pb.TxValidationCode_VALID {\n\t//\t\trequestContext.Error = status.New(status.EventServerStatus, int32(txStatus.TxValidationCode),\n\t//\t\t\t\"received invalid transaction\", nil)\n\t//\t\treturn\n\t//\t}\n\t//case <-requestContext.Ctx.Done():\n\t//\trequestContext.Error = status.New(status.ClientStatus, status.Timeout.ToInt32(),\n\t//\t\t\"Execute didn't receive block event\", nil)\n\t//\treturn\n\t//}\n\n\t//Delegate to next step if any\n\tif res != nil {\n\t\trequestContext.Response.OrderDataLen = res.DataLen\n\t}\n\n\tif c.next != nil {\n\t\tc.next.Handle(requestContext, clientContext)\n\t}\n}", "func inTx(txCallback func(tx *sql.Tx) error) (err error) {\n\tvar tx *sql.Tx\n\n\tif tx, err = DB.Begin()\n\t\terr != nil {\n\t\treturn\n\t}\n\n\t/**\n\t * The transaction result by whether or not the callback has error\n\t */\n\tdefer func() {\n\t\tif err == nil {\n\t\t\ttx.Commit()\n\t\t} else {\n\t\t\ttx.Rollback()\n\t\t}\n\t}()\n\t// :~)\n\n\terr = txCallback(tx)\n\n\treturn\n}", "func Transaction(ctx context.Context, driver Driver, opts *TxOptions,\n\thandler func(driver Driver) error) error {\n\n\tif driver == nil {\n\t\treturn errors.Wrap(ErrInvalidDriver, \"makroud: cannot create a transaction\")\n\t}\n\n\ttx, err := driver.Begin(ctx, opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = handler(tx)\n\tif err != nil {\n\n\t\tthr := tx.Rollback()\n\t\tif thr != nil && driver.HasObserver() {\n\t\t\tthr = errors.Wrap(thr, \"makroud: trying to rollback transaction\")\n\t\t\tdriver.Observer().OnRollback(thr, nil)\n\t\t}\n\n\t\treturn err\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func OnReceived(input []byte) error {\n\tmessage := string(input)\n\tvar data types.SendData\n\terr := json.Unmarshal([]byte(message), &data)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttxsToApprove := types.List{}\n\ttxsToApprove.Append(types.NewHashHex(data.Parent))\n\ttxsToApprove.Append(types.NewHashHex(data.Reference))\n\n\tgrpcResult := callApp(fmt.Sprintf(\"%v\", data.Data))\n\th := types.NewHashHex(grpcResult)\n\tlog.Printf(\"\\n Grpc result: %s\\n\", h)\n\n\t// Transaction\n\ttx := types.Transaction{}\n\ttx.Trunk = txsToApprove.Index(0)\n\ttx.Branch = txsToApprove.Index(1)\n\t// timestamp\n\ttx.Timestamp = data.Timestamp\n\ttx.DataHash = h\n\n\t// todo: POW\n\n\t// tx hash\n\ttxBytes, err := tx.Bytes()\n\tif err != nil {\n\t\tlog.Printf(\"Transaction to bytes failed: %s\\n\", err)\n\t\treturn err\n\t}\n\n\ttxHash := types.Sha256(txBytes)\n\thashBytes := txHash.Bytes()\n\n\tif sn.Dag.Contains(txHash) {\n\t\tfmt.Printf(\"tx [%s] already exist.\", txHash.String())\n\t\treturn nil\n\t}\n\n\t// Save to dag\n\terr = sn.Dag.Add(txHash, &tx)\n\tif err != nil {\n\t\tlog.Printf(\"Dag add tx failed: %s\\n\", err)\n\t\treturn err\n\t}\n\n\t// Save to db\n\terr = sn.Store.Save(hashBytes, txBytes)\n\tif err != nil {\n\t\tlog.Printf(\"Save data to database failed: %v\\n\", err)\n\t}\n\tlog.Printf(\"Store to database successed!\\n\")\n\n\tbroadcast(message)\n\n\treturn nil\n}", "func (db *DB) Transaction(ctx context.Context, fn TxHandlerFunc) error {\n\tdb.mu.Lock()\n\tdefer db.mu.Unlock()\n\n\torigin, err := db.master.BeginTx(ctx, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to begin transaction: %v\", err)\n\t}\n\ttx := &Tx{origin}\n\n\tif err := fn(ctx, tx); err != nil {\n\t\tif re := tx.parent.Rollback(); re != nil {\n\t\t\tif re.Error() != sql.ErrTxDone.Error() {\n\t\t\t\treturn fmt.Errorf(\"fialed to rollback: %v\", err)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"failed to execcute transaction: %v\", err)\n\t}\n\treturn tx.parent.Commit()\n}", "func (s *Session) Transaction(f func(*Session) (interface{}, error)) (interface{}, error) {\n\terr := s.Begin()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\td, err := f(s)\n\tif err != nil {\n\t\ts.RollBack()\n\t} else {\n\t\ts.Commit()\n\t}\n\treturn d, err\n}", "func (s *server) handleUpdateTransactions(w http.ResponseWriter, r *http.Request) {\n\n\tvar ctx = r.Context()\n\n\tvar message = new(ledger.WebhookMessage)\n\terr := json.NewDecoder(r.Body).Decode(message)\n\tif err != nil {\n\t\ts.logger.WithError(err).Error()\n\t\ts.writeError(ctx, w, http.StatusBadRequest, errors.New(\"failed to decode request body\"))\n\t\treturn\n\t}\n\n\titemID := chi.URLParam(r, \"itemID\")\n\tif itemID == \"\" {\n\t\ts.writeError(ctx, w, http.StatusBadRequest, errors.New(\"itemID is required\"))\n\t\treturn\n\t}\n\n\taccountID := chi.URLParam(r, \"accountID\")\n\tif accountID == \"\" {\n\t\ts.writeError(ctx, w, http.StatusBadRequest, errors.New(\"accountID is required\"))\n\t\treturn\n\t}\n\n\tmessage.ItemID = itemID\n\tmessage.Options = &ledger.WebhookMessageOptions{\n\t\tAccountIDs: []string{accountID},\n\t}\n\n\terr = s.importer.PublishCustomWebhookMessage(ctx, message)\n\tif err != nil {\n\t\ts.logger.WithError(err).Error()\n\t\ts.writeError(ctx, w, http.StatusBadRequest, errors.New(\"failed to process refresh request\"))\n\t\treturn\n\t}\n\n\ts.writeResponse(ctx, w, http.StatusNoContent, nil)\n}", "func (s *StatsPeriodStore) Transaction(callback func(*StatsPeriodStore) error) error {\n\tif callback == nil {\n\t\treturn kallax.ErrInvalidTxCallback\n\t}\n\n\treturn s.Store.Transaction(func(store *kallax.Store) error {\n\t\treturn callback(&StatsPeriodStore{store})\n\t})\n}", "func send(\n\tclient *http.Client,\n\tappservice config.ApplicationService,\n\ttxnID int,\n\ttransaction []byte,\n) (err error) {\n\t// PUT a transaction to our AS\n\t// https://matrix.org/docs/spec/application_service/r0.1.2#put-matrix-app-v1-transactions-txnid\n\taddress := fmt.Sprintf(\"%s/transactions/%d?access_token=%s\", appservice.URL, txnID, url.QueryEscape(appservice.HSToken))\n\treq, err := http.NewRequest(\"PUT\", address, bytes.NewBuffer(transaction))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer checkNamedErr(resp.Body.Close, &err)\n\n\t// Check the AS received the events correctly\n\tif resp.StatusCode != http.StatusOK {\n\t\t// TODO: Handle non-200 error codes from application services\n\t\treturn fmt.Errorf(\"non-OK status code %d returned from AS\", resp.StatusCode)\n\t}\n\n\treturn nil\n}", "func AliceWithdrawFromTxAPIHandler(w http.ResponseWriter, r *http.Request) {\n\tLog := Logger.NewSessionLogger()\n\n\tvar plog PodLog\n\tplog.Result = LOG_RESULT_FAILED\n\tplog.Operation = LOG_OPERATION_TYPE_ALICE_WITHDRAW_FROM_TX\n\n\tdefer func() {\n\t\terr := insertLogToDB(plog)\n\t\tif err != nil {\n\t\t\tLog.Warnf(\"insert log error! %v\", err)\n\t\t\treturn\n\t\t}\n\t\tnodeRecovery(w, Log)\n\t}()\n\n\tsessionID := r.FormValue(\"session_id\")\n\tLog.Infof(\"start withdraw eth from transaction in contract...sessionID=%v\", sessionID)\n\tplog.Detail = fmt.Sprintf(\"sessionID=%v\", sessionID)\n\n\tif sessionID == \"\" {\n\t\tLog.Warnf(\"invalid sessionID. sessionID=%v\", sessionID)\n\t\tfmt.Fprintf(w, RESPONSE_INCOMPLETE_PARAM)\n\t\treturn\n\t}\n\ttx, rs, err := loadAliceFromDB(sessionID)\n\tif err != nil {\n\t\tLog.Warnf(\"failed to load transaction info from db. sessionID=%v, err=%v\", sessionID, err)\n\t\tfmt.Fprintf(w, RESPONSE_READ_DATABASE_FAILED)\n\t\treturn\n\t}\n\tif !rs {\n\t\tLog.Warnf(\"no transaction info loaded. sessionID=%v,\", sessionID)\n\t\tfmt.Fprintf(w, RESPONSE_NO_NEED_TO_WITHDRAW)\n\t\treturn\n\t}\n\tif tx.SubMode != TRANSACTION_SUB_MODE_COMPLAINT {\n\t\tLog.Warnf(\"the mode does not need withdraw eth.\")\n\t\tfmt.Fprintf(w, RESPONSE_NO_NEED_TO_WITHDRAW)\n\t\treturn\n\t}\n\tLog.Debugf(\"start send transaction to withdraw eth...sessionID=%v\", sessionID)\n\tt := time.Now()\n\ttxid, err := settleDealForComplaint(sessionID, tx.AliceAddr, tx.BobAddr)\n\tif err != nil {\n\t\tLog.Warnf(\"failed to withdraw eth for Alice from contract. err=%v\", err)\n\t\tfmt.Fprintf(w, RESPONSE_READ_CONTRACT_FAILED)\n\t\treturn\n\t}\n\tLog.Debugf(\"success to send transaction to withdraw eth...txid=%v, sessionID=%v, time cost=%v\", txid, sessionID, time.Since(t))\n\n\tplog.Result = LOG_RESULT_SUCCESS\n\tfmt.Fprintf(w, fmt.Sprintf(RESPONSE_SUCCESS, \"send transaction for withdrawing from contract...\"))\n\treturn\n}", "func (db *database) Transact(txHandler func(tx *sqlx.Tx) error) (err error) {\n\ttx, err := db.Beginx()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to begin transaction\")\n\t}\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\t_ = tx.Rollback()\n\t\t\tpanic(r)\n\t\t}\n\n\t\tif err != nil {\n\t\t\t_ = tx.Rollback()\n\t\t\treturn\n\t\t}\n\n\t\ttx.Commit()\n\t}()\n\n\terr = txHandler(tx)\n\treturn\n}", "func (cb *callBack) OnTransactionComplete(zcnTxn *zcncore.Transaction, status int) {\n\tcb.sendCompleteCall()\n\n\terr := zcnTxn.GetTransactionError()\n\tif err == \"\" {\n\t\terr = \"no error\"\n\t}\n\n\tlog.Logger.Debug(\"Transaction completed\",\n\t\tzap.String(\"status\", TxnStatus(status).String()),\n\t\tzap.Any(\"txn_hash\", zcnTxn.GetTransactionHash()),\n\t\tzap.String(\"error\", err),\n\t)\n}", "func HandleTransactionUpdate(authToken string, cb func(t TransactionUpdate)) http.HandlerFunc {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != http.MethodPost {\n\t\t\tw.Header().Set(\"ALLOW\", \"POST\")\n\t\t\thttp.Error(w, \"Unsupported method\", http.StatusMethodNotAllowed)\n\t\t\treturn\n\t\t}\n\t\tif authToken != \"\" && r.Header.Get(\"Authorization\") != authToken {\n\t\t\thttp.Error(w, \"Unauthorized\", http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t\tvar t TransactionUpdate\n\t\tbodyDec := json.NewDecoder(r.Body)\n\t\tdefer r.Body.Close()\n\n\t\terr := bodyDec.Decode(&t)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tcb(t)\n\t}\n\treturn fn\n}", "func (m Middleware) Tx(db *sql.DB) TxFunc {\n\treturn func(f func(tx daos.Transaction, w http.ResponseWriter, r *http.Request) error) http.HandlerFunc {\n\t\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\t\tt, err := db.Begin()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tdefer func() {\n\t\t\t\tl := m.log.WithRequest(r)\n\t\t\t\tif p := recover(); p != nil {\n\t\t\t\t\tt.Rollback()\n\t\t\t\t\tl.Info(\"transaction rollbacked\")\n\t\t\t\t\tpanic(p)\n\t\t\t\t} else if err != nil {\n\t\t\t\t\tt.Rollback()\n\t\t\t\t\tl.Info(\"transaction rollbacked\")\n\t\t\t\t\tpanic(err)\n\t\t\t\t} else {\n\t\t\t\t\terr = t.Commit()\n\t\t\t\t\tl.Info(\"transaction commited\")\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\terr = f(t, w, r)\n\t\t}\n\t}\n}", "func (app *application) SaveTransaction(txn models.Transaction) (int, error) {\n\tid, err := app.DB.InsertTransaction(txn)\n\tif err != nil {\n\t\tapp.errorLog.Println(err)\n\t\treturn 0, err\n\t}\n\n\treturn id, nil\n}", "func UnknownTransactionHandler(ctx CustomTransactionContextInterface) error {\n\tfcn, args := ctx.GetStub().GetFunctionAndParameters()\n\n\treturn fmt.Errorf(\"Invalid function %s passed with args %v\", fcn, args)\n}", "func (app *application) SaveTransaction(txn models.Transaction) (int, error) {\n\tid, err := app.DB.InsertTransaction(txn)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn id, nil\n}", "func (a *Application) Commit() abci.ResponseCommit {\n\tvar err error\n\tdefer func(begin time.Time) {\n\t\tlvs := []string{\"method\", \"Commit\", \"error\", fmt.Sprint(err != nil)}\n\t\tcommittedBlockCount.With(lvs...).Add(1)\n\t\tcommitBlockLatency.With(lvs...).Observe(time.Since(begin).Seconds())\n\t}(time.Now())\n\n\tappHash, _, err := a.Store.SaveVersion()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\theight := a.curBlockHeader.GetHeight()\n\n\tif err := a.EvmAuxStore.SaveChildTxRefs(a.childTxRefs); err != nil {\n\t\t// TODO: consider panic instead\n\t\tlog.Error(\"Failed to save Tendermint -> EVM tx hash refs\", \"height\", height, \"err\", err)\n\t}\n\ta.childTxRefs = nil\n\n\t// Update the index before emitting events in case the subscribers attempt to lookup the\n\t// block by number as soon as they receive an event.\n\tif a.BlockIndexStore != nil {\n\t\ta.BlockIndexStore.SetBlockHashAtHeight(uint64(height), a.curBlockHash)\n\t}\n\n\t// Update the last block header before emitting events in case the subscribers attempt to access\n\t// the latest committed state as soon as they receive an event.\n\ta.lastBlockHeader = a.curBlockHeader\n\n\tgo func(height int64, blockHeader abci.Header, committedTxs []CommittedTx) {\n\t\tif err := a.EventHandler.EmitBlockTx(uint64(height), blockHeader.Time); err != nil {\n\t\t\tlog.Error(\"Emit Block Event error\", \"err\", err)\n\t\t}\n\t\tif err := a.EventHandler.LegacyEthSubscriptionSet().EmitBlockEvent(blockHeader); err != nil {\n\t\t\tlog.Error(\"Emit Block Event error\", \"err\", err)\n\t\t}\n\t\tif err := a.EventHandler.EthSubscriptionSet().EmitBlockEvent(blockHeader); err != nil {\n\t\t\tlog.Error(\"Emit Block Event error\", \"err\", err)\n\t\t}\n\t\tfor _, tx := range committedTxs {\n\t\t\tif err := a.EventHandler.LegacyEthSubscriptionSet().EmitTxEvent(tx.result.Data, tx.result.Info); err != nil {\n\t\t\t\tlog.Error(\"Emit Tx Event error\", \"err\", err)\n\t\t\t}\n\n\t\t\tif len(tx.txHash) > 0 {\n\t\t\t\tif err := a.EventHandler.EthSubscriptionSet().EmitTxEvent(tx.txHash); err != nil {\n\t\t\t\t\tlog.Error(\"failed to emit tx event to subscribers\", \"err\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}(height, a.curBlockHeader, a.committedTxs)\n\ta.committedTxs = nil\n\n\tif err := a.Store.Prune(); err != nil {\n\t\tlog.Error(\"failed to prune app.db\", \"err\", err)\n\t}\n\n\treturn abci.ResponseCommit{\n\t\tData: appHash,\n\t}\n}", "func Transaction(db *sql.DB, f func()) {\n\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr := tx.Rollback()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tpanic(r)\n\t\t} else {\n\t\t\terr = tx.Commit()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t}()\n\tf()\n}", "func acceptTxn(req *http.Request, client *aero.Client, incomingTxn *webTxn) (err error) {\n\t// read and decode txn\n\terr = json.NewDecoder(req.Body).Decode(&incomingTxn)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// store the incoming txn in Aerospike\n\tkey, err := aero.NewKey(namespace, setName, incomingTxn.SellerID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tincomingBinMap := aero.BinMap{\n\t\tuserIDBin: incomingTxn.UserID,\n\t\tsetNameBin: setName,\n\t\tamountBin: incomingTxn.Amount,\n\t}\n\n\terr = client.Put(nil, key, incomingBinMap)\n\n\treturn\n}", "func processTxHandler(w http.ResponseWriter, r *http.Request) {\n\tif r.URL.Path != \"/processTx/\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\tif r.Method != \"POST\" { // expecting POST method\n\t\thttp.Error(w, \"Invalid request method.\", 405)\n\t\treturn\n\t}\n\n\tdecoder := json.NewDecoder(r.Body)\n\tvar txIn TxInput\n\n\terr := decoder.Decode(&txIn)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer r.Body.Close()\n\n\t// fmt.Printf(\"\\nTX input:\\n%+v\\n\", txIn)\n\n\ttxResultStr := processTx(&txIn)\n\n\tfmt.Fprintf(w, \"%s\", txResultStr)\n}", "func transact(dbh modl.SqlExecutor, fn func(dbh modl.SqlExecutor) error) error {\n\tvar sharedTx bool\n\ttx, sharedTx := dbh.(*modl.Transaction)\n\tif !sharedTx {\n\t\tvar err error\n\t\ttx, err = dbh.(*modl.DbMap).Begin()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer func() {\n\t\t\tif err != nil {\n\t\t\t\ttx.Rollback()\n\t\t\t}\n\t\t}()\n\t}\n\n\tif err := fn(tx); err != nil {\n\t\treturn err\n\t}\n\n\tif !sharedTx {\n\t\tif err := tx.Commit(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func TransactionUpdate(c *gin.Context) {\n\tvar t models.Transaction\n\tvar newT models.Transaction\n\n\tif database.DBCon.First(&t, c.Param(\"id\")).RecordNotFound() {\n\t\tc.AbortWithError(http.StatusNotFound, appError.RecordNotFound).\n\t\t\tSetMeta(appError.RecordNotFound)\n\t\treturn\n\t}\n\n\t// Ensure current user is creator of transaction\n\tif t.CreatorID != c.Keys[\"CurrentUserID\"].(uint) {\n\t\tc.AbortWithError(appError.InsufficientPermission.Status, appError.InsufficientPermission).\n\t\t\tSetMeta(appError.InsufficientPermission)\n\t\treturn\n\t}\n\n\tbuffer, err := ioutil.ReadAll(c.Request.Body)\n\n\tif err != nil {\n\t\tc.AbortWithError(http.StatusNotAcceptable, err)\n\t}\n\n\terr2 := jsonapi.Unmarshal(buffer, &newT)\n\n\tif err2 != nil {\n\t\tc.AbortWithError(http.StatusInternalServerError, err).\n\t\t\tSetMeta(appError.JSONParseFailure)\n\t\treturn\n\t}\n\n\tt.Type = newT.Type\n\tt.Amount = newT.Amount\n\tt.Memo = newT.Memo\n\tt.RecipientID = newT.RecipientID\n\tt.SenderID = newT.SenderID\n\n\t// Validate our new transaction\n\tisValid, errApp := t.Validate()\n\n\tif isValid == false {\n\t\tc.AbortWithError(errApp.Status, errApp).\n\t\t\tSetMeta(errApp)\n\t\treturn\n\t}\n\n\tdatabase.DBCon.Save(&t)\n\n\tdatabase.DBCon.First(&t.Recipient, t.RecipientID)\n\tdatabase.DBCon.First(&t.Sender, t.SenderID)\n\tdatabase.DBCon.First(&t.Creator, t.CreatorID)\n\n\tdata, err := jsonapi.Marshal(&t)\n\n\tif err != nil {\n\t\tc.AbortWithError(http.StatusInternalServerError, err).\n\t\t\tSetMeta(appError.JSONParseFailure)\n\t\treturn\n\t}\n\n\tc.Data(http.StatusOK, \"application/vnd.api+json\", data)\n}", "func (s *Service) TapdCallBack(c context.Context, body io.ReadCloser) (err error) {\n\n\tvar (\n\t\tURLs []string\n\t\tjsonByte []byte\n\t\teventRequest *model.EventRequest\n\t\teventInterface = make(map[string]interface{})\n\t\tcreatedTime time.Time\n\t\tworkspaceID int\n\t\teventID int\n\t)\n\n\tif jsonByte, err = ioutil.ReadAll(body); err != nil {\n\t\treturn\n\t}\n\n\t//get event\n\tif err = json.Unmarshal(jsonByte, &eventRequest); err != nil {\n\t\treturn\n\t}\n\n\tif eventRequest.Secret != s.c.Tapd.CallbackToken {\n\t\terr = ecode.Unauthorized\n\t\treturn\n\t}\n\n\tif err = json.Unmarshal(jsonByte, &eventInterface); err != nil {\n\t\treturn\n\t}\n\n\t// add log\n\tworkspaceID, _ = strconv.Atoi(eventRequest.WorkspaceID)\n\teventID, _ = strconv.Atoi(eventRequest.EventID)\n\n\teventLog := &model.EventLog{\n\t\tEvent: string(eventRequest.Event),\n\t\tWorkspaceID: workspaceID,\n\t\tEventID: eventID,\n\t}\n\tif err = s.dao.AddEventLog(eventLog); err != nil {\n\t\treturn\n\t}\n\n\t//handle special param\n\tif createdTime, err = time.Parse(\"2006-01-02 15:04:05\", eventRequest.Created); err != nil {\n\t\treturn\n\t}\n\teventInterface[\"id\"] = eventRequest.EventID\n\teventInterface[\"created\"] = createdTime.Unix()\n\n\tif URLs, err = s.GetEnableHookURL(c, eventRequest.Event, workspaceID); err != nil {\n\t\treturn\n\t}\n\n\tfor _, URL := range URLs {\n\t\ts.transferChan.Do(context.Background(), func(c context.Context) {\n\t\t\ts.dao.CallHookUrlAsForm(context.Background(), URL, eventInterface)\n\t\t})\n\t}\n\treturn\n}", "func (adapter *GORMAdapter) DoInTransaction(fc func(tx orm.ORM) error) (err error) {\n\tgormTxFunc := func(tx *gorm.DB) error {\n\t\treturn fc(NewGORM(tx))\n\t}\n\n\treturn adapter.db.Transaction(gormTxFunc)\n}", "func (c *Connection) Transaction(fn func(*Connection) error) error {\n\td := c.C.Begin()\n\tif err := fn(&Connection{C: d, log: c.log}); err != nil {\n\t\td.Rollback()\n\t\treturn err\n\t}\n\td.Commit()\n\treturn nil\n}", "func Transaction(rt *Runtime, c chan goengage.Fundraise) (err error) {\n\trt.Log.Println(\"Transaction: start\")\n\tfor true {\n\t\tr, ok := <-c\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\n\t\trt.Log.Printf(\"%v Transaction\\n\", r.ActivityID)\n\t\tif rt.GoodYear(r.ActivityDate) {\n\t\t\tif len(r.Transactions) != 0 {\n\t\t\t\tfor _, c := range r.Transactions {\n\t\t\t\t\tc.ActivityID = r.ActivityID\n\t\t\t\t\trt.DB.Create(&c)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\trt.Log.Println(\"Transaction: end\")\n\treturn nil\n}", "func (c *Operation) callback(w http.ResponseWriter, r *http.Request) { //nolint: funlen,gocyclo\n\tif len(r.URL.Query()[\"error\"]) != 0 {\n\t\tif r.URL.Query()[\"error\"][0] == \"access_denied\" {\n\t\t\thttp.Redirect(w, r, c.homePage, http.StatusTemporaryRedirect)\n\t\t}\n\t}\n\n\ttk, err := c.tokenIssuer.Exchange(r)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to exchange code for token: %s\", err.Error())\n\t\tc.writeErrorResponse(w, http.StatusBadRequest,\n\t\t\tfmt.Sprintf(\"failed to exchange code for token: %s\", err.Error()))\n\n\t\treturn\n\t}\n\n\t// user info from token will be used for to retrieve data from cms\n\tinfo, err := c.tokenResolver.Resolve(tk.AccessToken)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to get token info: %s\", err.Error())\n\t\tc.writeErrorResponse(w, http.StatusBadRequest,\n\t\t\tfmt.Sprintf(\"failed to get token info: %s\", err.Error()))\n\n\t\treturn\n\t}\n\n\tuserID, subject, err := c.getCMSData(tk, \"email=\"+info.Subject, info.Scope)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to get cms data: %s\", err.Error())\n\t\tc.writeErrorResponse(w, http.StatusBadRequest,\n\t\t\tfmt.Sprintf(\"failed to get cms data: %s\", err.Error()))\n\n\t\treturn\n\t}\n\n\tcallbackURLCookie, err := r.Cookie(callbackURLCookie)\n\tif err != nil && !errors.Is(err, http.ErrNoCookie) {\n\t\tc.writeErrorResponse(w, http.StatusBadRequest,\n\t\t\tfmt.Sprintf(\"failed to get authMode cookie: %s\", err.Error()))\n\n\t\treturn\n\t}\n\n\tif callbackURLCookie != nil && callbackURLCookie.Value != \"\" {\n\t\ttxnID := uuid.NewString()\n\t\tdata := txnData{\n\t\t\tUserID: userID,\n\t\t\tScope: info.Scope,\n\t\t\tToken: tk.AccessToken,\n\t\t}\n\n\t\tdataBytes, mErr := json.Marshal(data)\n\t\tif mErr != nil {\n\t\t\tc.writeErrorResponse(w, http.StatusInternalServerError,\n\t\t\t\tfmt.Sprintf(\"failed to marshal txn data: %s\", mErr.Error()))\n\t\t\treturn\n\t\t}\n\n\t\terr = c.store.Put(txnID, dataBytes)\n\t\tif err != nil {\n\t\t\tc.writeErrorResponse(w, http.StatusInternalServerError,\n\t\t\t\tfmt.Sprintf(\"failed to save txn data: %s\", err.Error()))\n\n\t\t\treturn\n\t\t}\n\n\t\thttp.Redirect(w, r, callbackURLCookie.Value+\"?txnID=\"+txnID, http.StatusTemporaryRedirect)\n\n\t\treturn\n\t}\n\n\tvcsProfileCookie, err := r.Cookie(vcsProfileCookie)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to get cookie: %s\", err.Error())\n\t\tc.writeErrorResponse(w, http.StatusBadRequest,\n\t\t\tfmt.Sprintf(\"failed to get cookie: %s\", err.Error()))\n\n\t\treturn\n\t}\n\n\tcred, err := c.prepareCredential(subject, info.Scope, vcsProfileCookie.Value)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to create credential: %s\", err.Error())\n\t\tc.writeErrorResponse(w, http.StatusInternalServerError,\n\t\t\tfmt.Sprintf(\"failed to create credential: %s\", err.Error()))\n\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\n\tt, err := template.ParseFiles(c.didAuthHTML)\n\tif err != nil {\n\t\tlogger.Errorf(err.Error())\n\t\tc.writeErrorResponse(w, http.StatusInternalServerError,\n\t\t\tfmt.Sprintf(\"unable to load html: %s\", err.Error()))\n\n\t\treturn\n\t}\n\n\tif err := t.Execute(w, map[string]interface{}{\n\t\t\"Path\": generate + \"?\" + \"profile=\" + vcsProfileCookie.Value,\n\t\t\"Cred\": string(cred),\n\t}); err != nil {\n\t\tlogger.Errorf(fmt.Sprintf(\"failed execute qr html template: %s\", err.Error()))\n\t}\n}", "func HandleCallback(db *sqlx.DB) echo.HandlerFunc {\n\tsettings.DB = db\n\treturn auth.BuildCallbackHandler(settings)\n}", "func (c *Conn) Transaction(fn func(*Conn) error) error {\r\n\tvar (\r\n\t\ttx = c.Begin()\r\n\t\tconn = &Conn{}\r\n\t)\r\n\tcopier.Copy(conn, c)\r\n\tconn.DB = tx\r\n\tif err := fn(conn); err != nil {\r\n\t\ttx.Rollback()\r\n\t\treturn err\r\n\t}\r\n\ttx.Commit()\r\n\treturn nil\r\n}", "func (s *SmartContract) Transfer(ctx contractapi.TransactionContextInterface, recipient string, amount int) error {\n\n\t// Get ID of submitting client identity\n\tclientID, err := ctx.GetClientIdentity().GetID()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get client id: %v\", err)\n\t}\n\n\terr = transferHelper(ctx, clientID, recipient, amount)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to transfer: %v\", err)\n\t}\n\n\t// Emit the Transfer event\n\ttransferEvent := event{clientID, recipient, amount}\n\ttransferEventJSON, err := json.Marshal(transferEvent)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to obtain JSON encoding: %v\", err)\n\t}\n\terr = ctx.GetStub().SetEvent(\"Transfer\", transferEventJSON)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to set event: %v\", err)\n\t}\n\n\treturn nil\n}", "func (*txDriver) Commit() error { return nil }", "func (*txDriver) Commit() error { return nil }", "func (context *Context) Transaction(req map[string]interface{}) (rsp map[string]interface{}, err error) {\n\t// Handle the special case where we are just processing a response\n\tvar reqJSON []byte\n\tif req == nil {\n\t\treqJSON = []byte(\"\")\n\t} else {\n\n\t\t// Marshal the request to JSON\n\t\treqJSON, err = note.JSONMarshal(req)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"error marshaling request for module: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t}\n\n\t// Perform the transaction\n\trspJSON, err2 := context.TransactionJSON(reqJSON)\n\tif err2 != nil {\n\t\terr = fmt.Errorf(\"error from TransactionJSON: %s\", err2)\n\t\treturn\n\t}\n\n\t// Unmarshal for convenience of the caller\n\terr = note.JSONUnmarshal(rspJSON, &rsp)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"error unmarshaling reply from module: %s %s: %s\", err, note.ErrCardIo, rspJSON)\n\t\treturn\n\t}\n\n\t// Done\n\treturn\n}", "func (o *PluginDnsClient) OnTxEvent(event transport.SocketEventType) { /* No Tx event expected */ }", "func (e *NotificationEvents) OnTranscodeUpdate(fn func(n NotificationContainer)) {\n\te.events[\"transcodeSession.update\"] = fn\n}", "func TransactionDelete(c *gin.Context) {\n\tvar t models.Transaction\n\tif database.DBCon.First(&t, c.Param(\"id\")).RecordNotFound() {\n\t\tc.AbortWithError(http.StatusNotFound, appError.RecordNotFound).\n\t\t\tSetMeta(appError.RecordNotFound)\n\t\treturn\n\t}\n\n\t// Ensure current user is creator of transaction\n\tif t.CreatorID != c.Keys[\"CurrentUserID\"].(uint) {\n\t\tc.AbortWithError(appError.InsufficientPermission.Status, appError.InsufficientPermission).\n\t\t\tSetMeta(appError.InsufficientPermission)\n\t\treturn\n\t}\n\n\tdatabase.DBCon.Delete(&t)\n\n\tc.JSON(http.StatusOK, gin.H{\"meta\": gin.H{\"success\": true}})\n}", "func CommitingTransaction(s *System, state TransactionState) system.ReceiverFunction {\n\treturn func(context system.Context) system.ReceiverFunction {\n\t\tstate.Mark(context.Data)\n\n\t\tif !state.IsNegotiationFinished() {\n\t\t\treturn CommitingTransaction(s, state)\n\t\t}\n\n\t\tif state.FailedResponses > 0 {\n\t\t\tlog.Debug().Msgf(\"%s/Commit Rejected Some [total: %d, accepted: %d, rejected: %d]\", state.Transaction.IDTransaction, len(state.Negotiation), state.FailedResponses, state.OkResponses)\n\n\t\t\tstate.Transaction.State = model.StatusRejected\n\n\t\t\terr := persistence.UpdateTransaction(s.Storage, &state.Transaction)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error().Err(err).Msgf(\"%s/Commit failed to update transaction\", state.Transaction.IDTransaction)\n\t\t\t\ts.SendMessage(\n\t\t\t\t\tRespTransactionRefused+\" \"+state.Transaction.IDTransaction,\n\t\t\t\t\tstate.ReplyTo,\n\t\t\t\t\tcontext.Receiver,\n\t\t\t\t)\n\t\t\t\ts.UnregisterActor(context.Sender.Name)\n\t\t\t\treturn CommitingTransaction(s, state)\n\t\t\t}\n\n\t\t\tlog.Debug().Msgf(\"%s/Commit -> %s/Rollback\", state.Transaction.IDTransaction, state.Transaction.IDTransaction)\n\n\t\t\tstate.ChangeStage(ROLLBACK)\n\n\t\t\tfor account, task := range state.Negotiation {\n\t\t\t\ts.SendMessage(\n\t\t\t\t\tRollbackOrder+\" \"+task,\n\t\t\t\t\tsystem.Coordinates{\n\t\t\t\t\t\tRegion: \"VaultUnit/\" + account.Tenant,\n\t\t\t\t\t\tName: account.Name,\n\t\t\t\t\t},\n\t\t\t\t\tcontext.Receiver,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\treturn RollbackingTransaction(s, state)\n\t\t}\n\n\t\tlog.Debug().Msgf(\"%s/Commit Accepted All\", state.Transaction.IDTransaction)\n\n\t\tstate.Transaction.State = model.StatusCommitted\n\n\t\terr := persistence.UpdateTransaction(s.Storage, &state.Transaction)\n\n\t\tif err != nil {\n\t\t\ts.SendMessage(\n\t\t\t\tRespTransactionRefused+\" \"+state.Transaction.IDTransaction,\n\t\t\t\tstate.ReplyTo,\n\t\t\t\tcontext.Receiver,\n\t\t\t)\n\n\t\t\tlog.Warn().Msgf(\"%s/Commit failed to commit transaction\", state.Transaction.IDTransaction)\n\n\t\t\ts.UnregisterActor(context.Sender.Name)\n\t\t\treturn CommitingTransaction(s, state)\n\t\t}\n\n\t\ts.SendMessage(\n\t\t\tRespCreateTransaction+\" \"+state.Transaction.IDTransaction,\n\t\t\tstate.ReplyTo,\n\t\t\tcontext.Receiver,\n\t\t)\n\n\t\ts.Metrics.TransactionCommitted(len(state.Transaction.Transfers))\n\n\t\tlog.Info().Msgf(\"New Transaction %s Committed\", state.Transaction.IDTransaction)\n\t\tlog.Debug().Msgf(\"%s/Commit -> Terminal\", state.Transaction.IDTransaction)\n\n\t\ts.UnregisterActor(context.Sender.Name)\n\t\treturn CommitingTransaction(s, state)\n\t}\n}", "func TransactionMiddleware() middleware.TransactionMiddleware {\n\tdb := gormer.GetDB()\n\ttxnDataSQL := gormrepo.NewTxnDataSQL(db)\n\ttransactionMiddleware := middleware.NewTransactionMiddleware(txnDataSQL)\n\treturn transactionMiddleware\n}", "func (h *TransactionHandler) sendTransaction(userbank_id int, transaction_id int, totalAmount int) error {\r\n\tjsonW := &SendTransaction{\r\n\t\tUserBankID: userbank_id,\r\n\t\tTransactionID: transaction_id,\r\n\t\tAmount: totalAmount,\r\n\t}\r\n\r\n\tjsonR, _ := json.Marshal(jsonW)\r\n\tjsonStr := []byte(string(jsonR))\r\n\r\n\treq, _ := http.NewRequest(\"POST\", h.Config.BankAPIUrl+\"/transaction\", bytes.NewBuffer(jsonStr))\r\n\treq.Header.Set(\"Content-Type\", \"application/json\")\r\n\r\n\tclient := &http.Client{}\r\n\t_, err2 := client.Do(req)\r\n\r\n\tif err2 != nil {\r\n\t\treturn errors.New(\"Gagal menghubungkan ke server 2\")\r\n\t}\r\n\r\n\treturn nil\r\n}", "func (c *Conn) Transaction(t TransactionType, f func(c *Conn) error) error {\n\tvar err error\n\tif c.nTransaction == 0 {\n\t\terr = c.BeginTransaction(t)\n\t} else {\n\t\terr = c.Savepoint(strconv.Itoa(int(c.nTransaction)))\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.nTransaction++\n\tdefer func() {\n\t\tc.nTransaction--\n\t\tif err != nil {\n\t\t\t_, ko := err.(*ConnError)\n\t\t\tif c.nTransaction == 0 || ko {\n\t\t\t\t_ = c.Rollback()\n\t\t\t} else {\n\t\t\t\tif rerr := c.RollbackSavepoint(strconv.Itoa(int(c.nTransaction))); rerr != nil {\n\t\t\t\t\tLog(-1, rerr.Error())\n\t\t\t\t} else if rerr := c.ReleaseSavepoint(strconv.Itoa(int(c.nTransaction))); rerr != nil {\n\t\t\t\t\tLog(-1, rerr.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif c.nTransaction == 0 {\n\t\t\t\terr = c.Commit()\n\t\t\t} else {\n\t\t\t\terr = c.ReleaseSavepoint(strconv.Itoa(int(c.nTransaction)))\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\t_ = c.Rollback()\n\t\t\t}\n\t\t}\n\t}()\n\terr = f(c)\n\treturn err\n}", "func Handler(req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {\n\t// Log body and pass to the DAO\n\tfmt.Printf(\"Received body: %v\\n\", req)\n\n\trequest := new(vm.GeneralRequest)\n\tresponse := request.Validate(req.Body)\n\tif response.Code != 0 {\n\t\treturn events.APIGatewayProxyResponse{Body: response.Marshal(), StatusCode: 500}, nil\n\t}\n\n\trequest.Date = time.Now().Unix()\n\n\tvar mainTable = \"main\"\n\tif value, ok := os.LookupEnv(\"dynamodb_table_main\"); ok {\n\t\tmainTable = value\n\t}\n\n\t// insert data into the DB\n\tdal.Insert(mainTable, request)\n\n\t// Log and return result\n\tfmt.Println(\"Wrote item: \", request)\n\treturn events.APIGatewayProxyResponse{Body: response.Marshal(), StatusCode: 200}, nil\n}", "func (p DbPlugin) OnException(c *revel.Controller, err interface{}) {\n\tif c.Txn == nil {\n\t\treturn\n\t}\n\tif err := c.Txn.Rollback(); err != nil {\n\t\tif err != sql.ErrTxDone {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}", "func (app *JSONStoreApplication) DeliverTx(tx types.RequestDeliverTx) types.ResponseDeliverTx {\n\t return types.ResponseDeliverTx{Code: code.CodeTypeOK}\n\n\t var temp interface{}\n\t err := json.Unmarshal(tx.Tx, &temp)\n\n\t if err != nil {\n\t\t return types.ResponseDeliverTx{Code: code.CodeTypeEncodingError,Log: fmt.Sprint(err)}\n\t }\n\n\t message := temp.(map[string]interface{})\n\n\t PublicKey := message[\"publicKey\"].(string)\n\n\t count := checkUserPublic(db,PublicKey)\n \n\t if count != 0 {\n //var temp2 interface{}\n\t\t//userInfo := message[\"userInfo\"].(map[string]interface{})\n\t\t// err2 := json.Unmarshal([]byte(message[\"userInfo\"].(string)), &temp2)\n // message2 := temp2.(map[string]interface{})\n\t\t//if err2 != nil {\n\t\t//\tpanic(err.Error)\n\t\t//}\n \n\t\tvar user User\n\t\tuser.ID = message[\"id\"].(int)\n\t\tuser.PublicKey = message[\"public_key\"].(string)\n\t\tuser.Role = message[\"role\"].(int)\n\n\t\tfmt.Printf(user.PublicKey)\n \n\t\t// log.PrintIn(\"id: \", user.ID, \"public_key: \", user.PublicKey, \"role: \", user.Role)\n\n\t\tstmt, err := db.Prepare(\"INSERT INTO user(id, public_key, role) VALUES(?,?,?)\")\n\n\t\tif err != nil {\n\t\t\tpanic(err.Error)\n\t\t}\n\t\t\t\n\t\tstmt.Exec(user.ID, user.PublicKey, user.Role)\n\n\t\t// log.PrintIn(\"insert result: \", res.LastInsertId())\n\n\t\treturn types.ResponseDeliverTx{Code: code.CodeTypeOK}\n\t } else {\n\t\treturn types.ResponseDeliverTx{Code: code.CodeTypeBadData}\n\t }\n\t \n\t// var types interface{}\n\t// errType := json.Unmarshall(message[\"types\"].(string), &types)\n\t \n\t// if errType != nil {\n\t// \t panic(err.Error)\n\t// }\n\n\t// switch types[\"types\"] {\n\t// \tcase \"createUser\":\n\t// \t\tentity := types[\"entity\"].(map[string]interface{})\n\n\t// \t\tvar user User\n\t// \t\tuser.ID = entity[\"id\"].(int)\n\t// \t\tuser.PublicKey = entity[\"publicKey\"].(string)\n\t// \t\tuser.Role = entity[\"role\"].(int)\n\t// }\n}", "func (ap *DBApplier) handleNonTxnOp(ctx context.Context, op db.Oplog) error {\n\tif !ap.preserveUUID {\n\t\tvar err error\n\t\top, err = filterUUIDs(op)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"can not filter UUIDs from op '%+v', error: %+v\", op, err)\n\t\t}\n\t}\n\n\t// TODO: wait for index building\n\tif op.Operation == \"c\" && op.Object[0].Key == \"commitIndexBuild\" {\n\t\tcollName, indexes, err := indexSpecFromCommitIndexBuilds(op)\n\t\tif err != nil {\n\t\t\treturn NewOpHandleError(op, err)\n\t\t}\n\t\tdbName, _ := util.SplitNamespace(op.Namespace)\n\t\treturn ap.db.CreateIndexes(ctx, dbName, collName, indexes)\n\t}\n\tif op.Operation == \"c\" && op.Object[0].Key == \"createIndexes\" {\n\t\tcollName, indexes, err := indexSpecsFromCreateIndexes(op)\n\t\tif err != nil {\n\t\t\treturn NewOpHandleError(op, err)\n\t\t}\n\t\tdbName, _ := util.SplitNamespace(op.Namespace)\n\t\treturn ap.db.CreateIndexes(ctx, dbName, collName,\n\t\t\t[]client.IndexDocument{indexes})\n\t}\n\n\t//tracelog.DebugLogger.Printf(\"applying op: %+v\", op)\n\tif err := ap.db.ApplyOp(ctx, op); err != nil {\n\t\t// we ignore some errors (for example 'duplicate key error')\n\t\t// TODO: check after TOOLS-2041\n\t\tif !ap.shouldIgnore(op.Operation, err) {\n\t\t\treturn NewOpHandleError(op, err)\n\t\t}\n\t\ttracelog.WarningLogger.Printf(\"apply error is skipped: %+v\\nop:\\n%+v\", err, op)\n\t}\n\treturn nil\n}", "func (trd *trxDispatcher) process(evt *eventTrx) {\n\t// send the transaction out for burns processing\n\tselect {\n\tcase trd.outTransaction <- evt:\n\tcase <-trd.sigStop:\n\t\treturn\n\t}\n\n\t// process transaction accounts; exit if terminated\n\tvar wg sync.WaitGroup\n\tif !trd.pushAccounts(evt, &wg) {\n\t\treturn\n\t}\n\n\t// process transaction logs; exit if terminated\n\tfor _, lg := range evt.trx.Logs {\n\t\tif !trd.pushLog(lg, evt.blk, evt.trx, &wg) {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// store the transaction into the database once the processing is done\n\t// we spawn a lot of go-routines here, so we should test the optimal queue length above\n\tgo trd.waitAndStore(evt, &wg)\n\n\t// broadcast new transaction; if it can not be broadcast quickly, skip\n\tselect {\n\tcase trd.onTransaction <- evt.trx:\n\tcase <-time.After(200 * time.Millisecond):\n\tcase <-trd.sigStop:\n\t}\n}", "func (_UpkeepRegistrationRequests *UpkeepRegistrationRequestsTransactor) OnTokenTransfer(opts *bind.TransactOpts, arg0 common.Address, amount *big.Int, data []byte) (*types.Transaction, error) {\n\treturn _UpkeepRegistrationRequests.contract.Transact(opts, \"onTokenTransfer\", arg0, amount, data)\n}", "func (e *engineImpl) txn(c context.Context, jobID string, txn txnCallback) error {\n\tc = logging.SetField(c, \"JobID\", jobID)\n\tfatal := false\n\tattempt := 0\n\terr := datastore.Get(c).RunInTransaction(func(c context.Context) error {\n\t\tattempt++\n\t\tif attempt != 1 {\n\t\t\tlogging.Warningf(c, \"Retrying transaction...\")\n\t\t}\n\t\tds := datastore.Get(c)\n\t\tstored := CronJob{JobID: jobID}\n\t\terr := ds.Get(&stored)\n\t\tif err != nil && err != datastore.ErrNoSuchEntity {\n\t\t\treturn err\n\t\t}\n\t\tmodified := stored\n\t\terr = txn(c, &modified, err == datastore.ErrNoSuchEntity)\n\t\tif err != nil && err != errSkipPut {\n\t\t\tfatal = !errors.IsTransient(err)\n\t\t\treturn err\n\t\t}\n\t\tif err != errSkipPut && !modified.isEqual(&stored) {\n\t\t\treturn ds.Put(&modified)\n\t\t}\n\t\treturn nil\n\t}, &defaultTransactionOptions)\n\tif err != nil {\n\t\tlogging.Errorf(c, \"Job transaction failed: %s\", err)\n\t\tif fatal {\n\t\t\treturn err\n\t\t}\n\t\t// By now err is already transient (since 'fatal' is false) or it is commit\n\t\t// error (i.e. produced by RunInTransaction itself, not by its callback).\n\t\t// Need to wrap commit errors too.\n\t\treturn errors.WrapTransient(err)\n\t}\n\tif attempt > 1 {\n\t\tlogging.Infof(c, \"Committed on %d attempt\", attempt)\n\t}\n\treturn nil\n}", "func (l *EventLogger) InitTransaction() (id TransactionId) {\n\tl.Lock()\n\n\tfor ; id == 0; id = TransactionId(rand.Uint64()) {\n\t}\n\n\tl.transacting = id\n\treturn\n}", "func (_UpkeepRegistrationRequests *UpkeepRegistrationRequestsSession) OnTokenTransfer(arg0 common.Address, amount *big.Int, data []byte) (*types.Transaction, error) {\n\treturn _UpkeepRegistrationRequests.Contract.OnTokenTransfer(&_UpkeepRegistrationRequests.TransactOpts, arg0, amount, data)\n}", "func TransactionCreate(c *gin.Context) {\n\tvar t models.Transaction\n\tbuffer, err := ioutil.ReadAll(c.Request.Body)\n\tif err != nil {\n\t\tc.AbortWithError(http.StatusNotAcceptable, err)\n\t}\n\n\terr2 := jsonapi.Unmarshal(buffer, &t)\n\n\tif err2 != nil {\n\t\tparseFail := appError.JSONParseFailure\n\t\tparseFail.Detail = err2.Error()\n\t\tc.AbortWithError(http.StatusMethodNotAllowed, err2).\n\t\t\tSetMeta(parseFail)\n\t\treturn\n\t}\n\n\tt.CreatorID = c.Keys[\"CurrentUserID\"].(uint)\n\n\t// Validate our new transaction\n\tisValid, errApp := t.Validate()\n\n\tif isValid == false {\n\t\tc.AbortWithError(errApp.Status, errApp).\n\t\t\tSetMeta(errApp)\n\t\treturn\n\t}\n\n\tdatabase.DBCon.Create(&t)\n\n\tdatabase.DBCon.First(&t.Recipient, t.RecipientID)\n\tdatabase.DBCon.First(&t.Sender, t.SenderID)\n\tdatabase.DBCon.First(&t.Creator, t.CreatorID)\n\n\tdata, err := jsonapi.Marshal(&t)\n\n\tif err != nil {\n\t\tc.AbortWithError(http.StatusInternalServerError, err).\n\t\t\tSetMeta(appError.JSONParseFailure)\n\t\treturn\n\t}\n\n\tc.Data(http.StatusCreated, \"application/vnd.api+json\", data)\n}", "func (app *JSONStateApplication) DeliverTx(txBytes []byte) types.ResponseDeliverTx {\n\ttx := &transaction.Transaction{}\n\tif err := tx.FromBytes(txBytes); err != nil {\n\t\treturn types.ResponseDeliverTx{Code: code.CodeTypeBadData, Tags: nil}\n\t}\n\tswitch tx.Type {\n\tcase transaction.AccountAdd:\n\t\t{\n\t\t\tif err := deliverAccountAddTransaction(tx, app.store); err != nil {\n\t\t\t\treturn types.ResponseDeliverTx{Code: code.CodeTypeBadData, Tags: nil, Log:err.Error()}\n\t\t\t}\n\t\t}\n\n\tcase transaction.AccountDel:\n\t\t{\n\t\t\tif err := deliverAccountDelTransaction(tx, app.store); err != nil {\n\t\t\t\treturn types.ResponseDeliverTx{Code: code.CodeTypeBadData, Tags: nil, Log:err.Error()}\n\t\t\t}\n\t\t}\n\tcase transaction.AttendPatient:\n\t\t{\n\t\t\tif err := deliverAttendPatientTransaction(tx, app.store, app.db); err != nil {\n\t\t\t\treturn types.ResponseDeliverTx{Code: code.CodeTypeBadData, Tags: nil, Log:err.Error()}\n\t\t\t}\n\t\t}\t\n\tcase transaction.SecretAdd:\n\t\t{\n\t\t\tif err := deliverSecretAddTransaction(tx, app.store); err != nil {\n\t\t\t\treturn types.ResponseDeliverTx{Code: code.CodeTypeBadData, Tags: nil, Log:err.Error()}\n\t\t\t}\n\t\t}\n\tcase transaction.SecretUpdate:\n\t\t{\n\t\t\tif err := deliverSecretUpdateTransaction(tx, app.store); err != nil {\n\t\t\t\treturn types.ResponseDeliverTx{Code: code.CodeTypeBadData, Tags: nil, Log:err.Error()}\n\t\t\t}\n\t\t}\n\tcase transaction.SecretDel:\n\t\t{\n\t\t\tif err := deliverSecretDelTransaction(tx, app.store); err != nil {\n\t\t\t\treturn types.ResponseDeliverTx{Code: code.CodeTypeBadData, Tags: nil, Log:err.Error()}\n\t\t\t}\n\t\t}\n\tcase transaction.SecretShare:\n\t\t{\n\t\t\tif err := deliverSecretShareTransaction(tx, app.store); err != nil {\n\t\t\t\treturn types.ResponseDeliverTx{Code: code.CodeTypeBadData, Tags: nil, Log:err.Error()}\n\t\t\t}\n\t\t}\n\tcase transaction.PatientAdd:\n\t\t{\n\t\t\tif err := deliverPatientAddTransaction(tx, app.store, app.db); err != nil{\n\t\t\t\treturn types.ResponseDeliverTx{Code: code.CodeTypeBadData, Tags: nil, Log:err.Error()}\n\t\t\t}\n\t\t}\n\tcase transaction.DoctorAdd:\n\t\t{\n\t\t\tif err := deliverDoctorAddTransaction(tx, app.store, app.db); err != nil{\n\t\t\t\treturn types.ResponseDeliverTx{Code: code.CodeTypeBadData, Tags: nil, Log:err.Error()}\n\t\t\t}\n\t\t}\n\tcase transaction.MedicalAppointmentAdd:\n\t\t{\n\t\t\tif err := deliverMedicalAppointmentAddTransaction(tx, app.store, app.db); err != nil{\n\t\t\t\treturn types.ResponseDeliverTx{Code: code.CodeTypeBadData, Tags: nil, Log:err.Error()}\n\t\t\t}\n\t\t}\t\n\t}\n\t\n\treturn types.ResponseDeliverTx{Code: code.CodeTypeOK, Tags: nil}\n}", "func (srv *Server) walletTransactionsAddrHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {\n\t// Parse the address being input.\n\tjsonAddr := \"\\\"\" + ps.ByName(\"addr\") + \"\\\"\"\n\tvar addr types.UnlockHash\n\terr := addr.UnmarshalJSON([]byte(jsonAddr))\n\tif err != nil {\n\t\twriteError(w, \"error after call to /wallet/transactions: \"+err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tconfirmedATs := srv.wallet.AddressTransactions(addr)\n\tunconfirmedATs := srv.wallet.AddressUnconfirmedTransactions(addr)\n\twriteJSON(w, WalletTransactionsGETaddr{\n\t\tConfirmedTransactions: confirmedATs,\n\t\tUnconfirmedTransactions: unconfirmedATs,\n\t})\n}", "func (s *searcher) Transaction(resp http.ResponseWriter, req *http.Request) {\n\tsearchTerms := mux.Vars(req)\n\n\ttransactionID := searchTerms[\"transaction_id\"]\n\tif len(transactionID) == 0 {\n\t\tresp.WriteHeader(http.StatusBadRequest)\n\t\tresp.Write([]byte(\"transaction ID is empty\"))\n\t\treturn\n\t}\n\n\tif len(transactionID) != 64 {\n\t\tresp.WriteHeader(http.StatusBadRequest)\n\t\tresp.Write([]byte(\"transaction ID is not 64 characters\"))\n\t\treturn\n\t}\n\n\tfileName, transactionIndex, err := s.searchIndex.GetTransactionPathByID(transactionID)\n\tif err != nil {\n\t\tresp.WriteHeader(http.StatusInternalServerError)\n\t\tresp.Write([]byte(fmt.Sprintf(\"error finding transaction: %s\", err.Error())))\n\t\treturn\n\t}\n\n\ttransactions, err := s.searchIndex.GetTransactionsFromSingleFile(fileName, []int{transactionIndex})\n\tif err != nil {\n\t\tresp.WriteHeader(http.StatusInternalServerError)\n\t\tresp.Write([]byte(fmt.Sprintf(\"error finding transaction: %s\", err.Error())))\n\t\treturn\n\t}\n\n\tresultBytes, err := json.Marshal(transactions)\n\tif err != nil {\n\t\tresp.WriteHeader(http.StatusInternalServerError)\n\t\tresp.Write([]byte(fmt.Sprintf(\"error marshallig transaction to json: %s\", err.Error())))\n\t\treturn\n\t}\n\n\tresp.WriteHeader(http.StatusOK)\n\tresp.Write(resultBytes)\n}", "func (cdt *SqlDBTx) TxEnd(txFunc func() error) error {\n\treturn nil\n}", "func (_m *Repository) CommitTransaction(ctx context.Context) {\n\t_m.Called(ctx)\n}", "func (conn *RealBackend) Commit() {\n}", "func (this *BasicHandler) Commit() error {\n\terr := this.tx.Commit()\n\tif err != nil {\n\t\treturn err\n\t}\n\tthis.tx, err = this.db.Beginx()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (w *Wallit) TxHandler(incomingTxAndHeight chan lnutil.TxAndHeight) {\n\tfor {\n\t\ttxah := <-incomingTxAndHeight\n\t\tw.Ingest(txah.Tx, txah.Height)\n\t\tlogging.Infof(\"got tx %s at height %d\\n\",\n\t\t\ttxah.Tx.TxHash().String(), txah.Height)\n\t}\n}", "func (_EthCrossChain *EthCrossChainCaller) TransactionId(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _EthCrossChain.contract.Call(opts, out, \"TransactionId\")\n\treturn *ret0, err\n}", "func (_UpkeepRegistrationRequests *UpkeepRegistrationRequestsTransactorSession) OnTokenTransfer(arg0 common.Address, amount *big.Int, data []byte) (*types.Transaction, error) {\n\treturn _UpkeepRegistrationRequests.Contract.OnTokenTransfer(&_UpkeepRegistrationRequests.TransactOpts, arg0, amount, data)\n}", "func Transaction(c *gin.Context) {\n\n\tt_type,_ := strconv.Atoi(c.PostForm(\"transaction_type\")) // 1 : sales , 2 : missing products (hilang)\n\tstatus := 1\n\tmessage := \"Success\"\n var responseTransaction ResponseTransaction\n\tvar newstocks int\n\tvar products Products\n\tvar products_arr []Products\n\tvar stock_ins_arr []Stock_Ins\n\tvar stock_outs Stock_Outs\n\tvar stock_ins Stock_Ins\n\tvar note string\n\ttransaction_id := \"\"\n\tsellPrice,_ := strconv.Atoi(c.PostForm(\"sell_price\"))\n\tvar buyPrice int\n\tqtY,_ := strconv.Atoi(c.PostForm(\"qty\"))\n\tcurrentdatetime := time.Now().Format(\"2006-01-02 15:04:05\")\n\tdb := InitDb() //db intiate\n\t//get data products\n\tdb.Where(\"sku = ?\", c.PostForm(\"sku\")).First(&products).Limit(1).Scan(&products_arr)\n\n\t//check if the sku is exist?\n\tif(len(products_arr) > 0) {\n\t\ttx := db.Begin()\n\n\t\t/**\n\t * Identify product is gone / transaction by sales\n\t */\n\n\t\tif (t_type == 1) {\n\n\t\t\ttransaction_id = generateTransactionID()\n\n\t\t\t//get data products\n\t\t\tdb.Where(\"sku = ?\", c.PostForm(\"sku\")).First(&stock_ins).Limit(1).Scan(&stock_ins_arr)\n\n\t\t\t// get the data stock after transaction\n\t\t\tfor i,element := range stock_ins_arr{\n\t\t\t\tif (i == 0) {\n\t\t\t\t\tbuyPrice = element.Buy_Price\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnote = \"Pesanan \"+transaction_id\n\t\t\ttransactions := Transactions{Id:transaction_id,Buy_Price:buyPrice,Sell_Price:sellPrice,Qty:qtY,Sku:c.PostForm(\"sku\"),Created_Date:currentdatetime}\n\t\t\tif err := tx.Create(&transactions).Error; err != nil {\n\t\t\t\ttx.Rollback()\n\t\t\t\tstatus = 0\n\t\t\t\tmessage = \"failed to insert data transaction\"\n\t\t\t}\n\n\n\t\t} else if (t_type == 2) {\n\n\t\t\tnote = \"Barang Hilang\"\n\n\t\t}\n\t\t//insert data to stock_outs\n\t\tstock_outs = Stock_Outs{Sku:c.PostForm(\"sku\"),Created_Date:currentdatetime,Qty:qtY,Note:note,Transaction_Id:transaction_id}\n\t\tif err := tx.Create(&stock_outs).Error; err != nil {\n\t\t\ttx.Rollback()\n\t\t\tstatus = 0\n\t\t\tmessage = \"failed to insert data stocks_outs\"\n\t\t}\n\n\t\t// get the data stock after transaction\n\t\tfor i,element := range products_arr{\n\t\t\tif (i == 0) {\n\t\t\t\tnewstocks = element.Stocks - qtY\n\t\t\t}\n\t\t}\n\n\t\t//update product stocks in table products\n\t\tif err := tx.Model(&products).Where(\"sku = ?\", c.PostForm(\"sku\")).Update(\"stocks\", newstocks).Error; err != nil {\n\t\t\ttx.Rollback()\n\t\t\tstatus = 0\n\t\t\tmessage = \"failed to update data products\"\n\t\t}\n\n\n\t\t//transaction commit\n\t\ttx.Commit()\n\t}else{\n\t\tstatus = 0\n\t\tmessage = \"SKU Not found!\"\n\t}\n\n\tif status == 1{\n\t\tresponseTransaction = ResponseTransaction{Status:status,Message:message,Data:DataTransaction{Sku:c.PostForm(\"sku\"),Buy_Price:buyPrice,Sell_Price:sellPrice,Created_Date:currentdatetime,Product_name:c.PostForm(\"product_name\"),Stocks:newstocks,Transaction_Id:transaction_id}}\n\t}else{\n\t\tresponseTransaction = ResponseTransaction{Status:status,Message:message}\n\t}\n\n\t// Close connection database\n\tdefer db.Close()\n\tc.JSON(200, responseTransaction)\n}", "func (controller *AccountController) DoTransaction(ctx *gin.Context) {\n\tsourceID, ok := ctx.GetPostForm(\"sourceid\")\n\tif !ok {\n\t\tlog.WithFields(log.Fields{\"URL\": ctx.Request.URL.String()}).Warn(\"No SourceID found in postform\")\n\n\t\terrResp, _ := restapi.NewErrorResponse(\"No sourceID given\").Marshal()\n\t\tfmt.Fprint(ctx.Writer, string(errResp))\n\t\tctx.Abort()\n\t\treturn\n\t}\n\n\ttargetID, ok := ctx.GetPostForm(\"targetid\")\n\tif !ok {\n\t\tlog.WithFields(log.Fields{\"URL\": ctx.Request.URL.String()}).Warn(\"No TargetID found in postform\")\n\n\t\terrResp, _ := restapi.NewErrorResponse(\"No targetID given\").Marshal()\n\t\tfmt.Fprint(ctx.Writer, string(errResp))\n\t\tctx.Abort()\n\t\treturn\n\t}\n\n\tamount, err := strconv.Atoi(ctx.PostForm(\"amount\"))\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\"URL\": ctx.Request.URL.String()}).Warn(\"No int amount found in postform\")\n\n\t\tresponse, _ := restapi.NewErrorResponse(\"No valid diff value\").Marshal()\n\t\tfmt.Fprint(ctx.Writer, string(response))\n\t\tctx.Abort()\n\t\treturn\n\t}\n\n\tinfo, err := authStuff.GetLoginInfoFromCtx(ctx)\n\tif err != nil {\n\t\tresponse, _ := restapi.NewErrorResponse(err.Error()).Marshal()\n\t\tfmt.Fprint(ctx.Writer, string(response))\n\t\tctx.Abort()\n\t\treturn\n\t}\n\n\tif err := controller.service.Transaction(sourceID, targetID, info.Name, amount); err == nil {\n\t\tresponse, _ := restapi.NewOkResponse(\"\").Marshal()\n\t\tfmt.Fprint(ctx.Writer, string(response))\n\t\tctx.Next()\n\t} else {\n\t\tlog.WithFields(log.Fields{\"user\": info.Name}).WithError(err).Error(\"Transaction Error\")\n\n\t\tresponse, _ := restapi.NewErrorResponse(err.Error()).Marshal()\n\t\tfmt.Fprint(ctx.Writer, string(response))\n\t\tctx.Abort()\n\t\treturn\n\t}\n}", "func baz(w http.ResponseWriter, _ *http.Request) {\n\tlog.Println(\"baz\")\n\tdefer func() {\n\t\tlog.Println(\"baz done\")\n\t}()\n\n\t// ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tsess := conn.NewSession(nil)\n\ttx, err := sess.BeginTx(ctx, nil)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\t// no defer rollback\n\n\t_, err = tx.SelectBySql(\"select id from user where id = ? for update\", userID).ReturnInt64()\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tpanic(errors.New(\"panic here\"))\n}", "func DoInTransaction(atomicAction func(conn runner.Connection) error) error {\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer tx.AutoRollback()\n\n\terr = atomicAction(tx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = tx.Commit()\n\treturn err\n}" ]
[ "0.5869467", "0.5867833", "0.5804374", "0.57200927", "0.56971574", "0.5694462", "0.56834024", "0.5682376", "0.56608206", "0.56506705", "0.56494004", "0.56396836", "0.5632023", "0.56066495", "0.558995", "0.55495995", "0.55495113", "0.5503615", "0.5499464", "0.5494148", "0.54741085", "0.5473594", "0.5460463", "0.54575884", "0.54492426", "0.54294837", "0.54256374", "0.53787655", "0.5358715", "0.53513765", "0.5349681", "0.5346998", "0.5341363", "0.53355765", "0.5322995", "0.53211933", "0.5287318", "0.5272745", "0.52320015", "0.52264947", "0.52238166", "0.5219629", "0.5209863", "0.52004784", "0.51923877", "0.5190335", "0.51835006", "0.51771915", "0.5166748", "0.5148478", "0.51387775", "0.5136109", "0.513544", "0.51269686", "0.5116107", "0.5112039", "0.51040995", "0.5100731", "0.5089089", "0.5086621", "0.50602245", "0.5052906", "0.5039053", "0.50375575", "0.5021055", "0.5017698", "0.5017646", "0.5017646", "0.5008322", "0.49883056", "0.49706534", "0.49683174", "0.4961248", "0.4955251", "0.49444786", "0.4943303", "0.49419087", "0.49402013", "0.49397615", "0.49335602", "0.4933318", "0.4932501", "0.49187237", "0.49142084", "0.49078518", "0.49024352", "0.49003994", "0.48929593", "0.48888257", "0.48824465", "0.48803824", "0.48741412", "0.48722133", "0.4871084", "0.48588553", "0.48540577", "0.48448366", "0.48387387", "0.48383456", "0.483428" ]
0.5647915
11
Connect return a connection to a postgres database wi
func NewDatabaseClient() *DbClient { DSN, ok := os.LookupEnv("PGSQL_DSN") if !ok { DSN = "postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable" } db, err := sqlx.Connect("postgres", DSN) if err != nil { log.Fatal("[db] Fatal Error, cannot open postgres database ", err) } err = db.Ping() if err != nil { log.Fatal("[db] Ping Error", err) } minConfirmations, ok := os.LookupEnv("GETH_MIN_CONFIRMATIONS") if !ok { minConfirmations = "6" } nConfirmations, _ := strconv.Atoi(minConfirmations) return &DbClient{DSN, db, nConfirmations} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func dbConnect() *sql.DB {\n\tdb, err := sql.Open(\"postgres\",\n\t\tfmt.Sprintf(\"user=%s password=%s dbname=%s host=%s port=%s sslmode=%s\",\n\t\t\tPG_USER,\n\t\t\tPG_PASSWORD,\n\t\t\tPG_DB,\n\t\t\tPG_HOST,\n\t\t\tPG_PORT,\n\t\t\tPG_SSL,\n\t\t))\n\tif err != nil {\n\t\tlog.Fatalf(\"ERROR: Error connecting to Postgres => %s\", err.Error())\n\t}\n\tlog.Printf(\"PQ Database connection made to %s\", PG_DB)\n\treturn db\n}", "func (db *Postgres) connect() error {\n\tdbMap, err := gosql.Open(\"postgres\", db.URI)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"Failed to open database with uri: %s\", db.URI)\n\t}\n\n\t// Configure the database mapping object\n\tdb.DbMap = &gorp.DbMap{Db: dbMap, Dialect: gorp.PostgresDialect{}}\n\n\t// Verify database\n\terr = db.ping()\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"Failed to ping database with uri: %s\", db.URI)\n\t}\n\n\treturn nil\n}", "func connectPostgres(dsn string) (*postgresConnection, error) {\n\treturn newPostgresConnection(dsn)\n}", "func connectDb() *sql.DB {\n\tconnStr := \"user=postgres dbname=postgres sslmode=disable port=5000\"\n\tdb, err := sql.Open(\"postgres\", connStr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn db\n}", "func connectDB() error {\n\t// define login variables\n\thost := config.Get(\"postgresql\", \"host\")\n\tport := config.Get(\"postgresql\", \"port\")\n\tssl := config.Get(\"postgresql\", \"ssl\")\n\tdatabase := config.Get(\"postgresql\", \"database\")\n\tusername := config.Get(\"postgresql\", \"username\")\n\tpassword := config.Get(\"postgresql\", \"password\")\n\n\t// connect and return error\n\treturn db.Connect(host, port, ssl, database, username, password)\n}", "func connectPG(user, password, host, port, dbName, sslmode string) (*pg.DB, error) {\n\topt, err := pg.ParseURL(\n\t\tfmt.Sprintf(\"postgres://%s:%s@%s:%s/%s?sslmode=%s\",\n\t\t\tuser, password, host, port, dbName, sslmode))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pg.Connect(opt), nil\n}", "func PGSQLConnect() *PostgreSQLConnection {\n\tif connection == nil {\n\t\tdbHost := configuration.Database.Host\n\t\tdbPort := configuration.Database.Port\n\t\tdbUser := configuration.Database.User\n\t\tdbPassword := configuration.Database.Password\n\t\tdatabase := configuration.Database.DatabaseName\n\n\t\tconn := fmt.Sprintf(\"host=%s port=%s user=%s password=%s database=%s\"+\n\t\t\t\" sslmode=disable\", dbHost, dbPort, dbUser, dbPassword, database)\n\n\t\tdb, err := sql.Open(\"postgres\", conn)\n\n\t\t// Based on the users of the application\n\t\tdb.SetMaxOpenConns(10)\n\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[!] Couldn't connect to the database. Reason %v\\n\", err)\n\t\t\treturn nil\n\t\t}\n\n\t\terr = db.Ping()\n\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[!] Couldn't ping to the database. Reason %v\\n\", err)\n\t\t\treturn nil\n\t\t}\n\t\tconnection = &PostgreSQLConnection{}\n\t\tconnection.db = db\n\t}\n\n\treturn connection\n}", "func Connect(p *DBConfig) (*sql.DB, error) {\n\tconnStr := fmt.Sprintf(connFmt, p.Host, p.Port, p.User, p.Pass, p.DB)\n\tdb, err := sql.Open(\"postgres\", connStr)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = db.Ping(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func Connect(connstr string) (*sql.DB, error) {\n\tdb, err := sql.Open(\"postgres\", connstr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func connect(ctx context.Context, config string) (*sql.DB, error) {\n\tdb, err := sql.Open(\"postgres\", config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"connect open: %v\", err)\n\t}\n\tif _, err := db.ExecContext(ctx, `SELECT 1`); err != nil {\n\t\treturn nil, fmt.Errorf(\"connect select: %v\", err)\n\t}\n\treturn db, nil\n}", "func dbConnect(dbConnParams string) *sql.DB {\n\tdb, err := sql.Open(\"postgres\", dbConnParams) // this opens a connection and adds to the pool\n\terrMsgHandler(fmt.Sprintf(\"Failed to connect to the database\"), err)\n\n\t// connect to the database\n\terr = db.Ping() // this validates that the opened connection \"db\" is actually working\n\terrMsgHandler(fmt.Sprintf(\"The database connection is no longer open\"), err)\n\n\tfmt.Println(\"Successfully connected to the database\")\n\treturn db\n}", "func connectDatabase(connectionURL string) *sql.DB {\n\tdb, err := sql.Open(\"postgres\", connectionURL)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn db\n}", "func PgConn(dataSourceName string) *sql.DB {\n\tvar err error\n\tfmt.Println(\"connecting...\")\n\tdbDriver, err = sql.Open(\"postgres\", dataSourceName)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\t//defer db.Close()\n\n\tif err = dbDriver.Ping(); err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tfmt.Println(\"#****Successfully connected*****#\")\n\treturn dbDriver\n}", "func Connect() (db *sql.DB) {\n\tvar err error\n\n\tconnStr := \"password='postgres' dbname=lost sslmode=disable\"\n\tDB, err = sql.Open(\"postgres\", connStr)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlog.Println(\"Connect to postgress success\")\n\n\treturn DB\n}", "func ConnectPostgres(d ConnParams) (db *sql.DB, err error) {\n\tif d.Port == 0 {\n\t\td.Port = 5432\n\t}\n\n\t// connect_timeout\n\t//\n\t// https://www.postgresql.org/docs/9.6/static/libpq-connect.html#LIBPQ-CONNECT-CONNECT-TIMEOUT\n\t// Maximum wait for connection, in seconds (write as a decimal integer string). Zero or not\n\t// specified means wait indefinitely. It is not recommended to use a timeout of less than 2\n\t// seconds.\n\t//\n\t// statement_timeout\n\t//\n\t// https://www.postgresql.org/docs/9.6/static/runtime-config-client.html#GUC-STATEMENT-TIMEOUT\n\t// Abort any statement that takes more than the specified number of milliseconds, starting from\n\t// the time the command arrives at the server from the client.\n\tconnParams := fmt.Sprintf(\n\t\t\"user=%s password=%s dbname=%s sslmode=disable host=%s port=%d connect_timeout=%d statement_timeout=%d\",\n\t\td.Username,\n\t\td.Password,\n\t\td.DatabaseName,\n\t\td.Host,\n\t\td.Port,\n\t\tint(d.ConnectTimeout.Seconds()),\n\t\tint(d.StatementTimeout.Seconds()*1000),\n\t)\n\n\tif db, err = sql.Open(PostgresDriver, connParams); err != nil {\n\t\treturn nil, err\n\t}\n\n\tdb.SetMaxIdleConns(d.MaxIdleConnections)\n\tdb.SetMaxOpenConns(d.MaxOpenConnections)\n\treturn\n}", "func Connect(c *config.Config) (*sql.DB, error) {\n\tstr := fmt.Sprintf(\"postgres://%s:%s@%s:%s/%s?sslmode=disable\", c.DatabaseUser, c.DatabasePassword, c.DatabaseHost, c.DatabasePort, c.DatabaseName)\n\tdb, err := sql.Open(\"postgres\", str)\n\n\tif err != nil {\n\t\tlog.Print(err)\n\t}\n\n\treturn db, err\n}", "func Connect() *sql.DB {\n\tfmtStr := \"host=%s port=%s user=%s \" +\n\t\t\"password=%s dbname=%s sslmode=disable\"\n\tpsqlInfo := fmt.Sprintf(\n\t\tfmtStr,\n\t\tos.Getenv(\"PG_HOST\"),\n\t\tos.Getenv(\"PG_PORT\"),\n\t\tos.Getenv(\"PG_USER\"),\n\t\tos.Getenv(\"PG_PASSWORD\"),\n\t\tos.Getenv(\"PG_DBNAME\"),\n\t)\n\tdb, err := sql.Open(\"postgres\", psqlInfo)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn db\n}", "func (c *client) connect() error {\n\tvar connection *sql.DB\n\tvar err error\n\tif os.Getenv(\"MODE\") == \"development\" {\n\t\tvar connectionString = fmt.Sprintf(\n\t\t\t\"host=%s port=%s user=%s password=%s dbname=%s sslmode=disable\",\n\t\t\tos.Getenv(\"PGHOST\"),\n\t\t\tos.Getenv(\"PGPORT\"),\n\t\t\tos.Getenv(\"PGUSER\"),\n\t\t\tos.Getenv(\"PGPASSWORD\"),\n\t\t\tos.Getenv(\"PGDATABASE\"),\n\t\t)\n\t\tc.connectionString = connectionString\n\t\tconnection, err = sql.Open(\"postgres\", connectionString)\n\t} else if os.Getenv(\"MODE\") == \"production\" {\n\t\tconnection, err = sql.Open(\"postgres\", os.Getenv(\"DATABASE_URL\"))\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"connection to pg failed: %v\", err)\n\t}\n\n\tc.db = connection\n\n\tfmt.Println(\"postgres connection established...\")\n\treturn nil\n}", "func Connect() (*DB, error) {\n\tpsqlInfo := fmt.Sprintf(\"host=db port=5432 user=ggp-user password=password dbname=development_db sslmode=disable\")\n\tdb, err := gorm.Open(\"postgres\", psqlInfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = db.DB().Ping()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &DB{DB: db}, nil\n}", "func createConnection() *sql.DB {\n\t// load .env file\n\terr := godotenv.Load(\".env\")\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Error loading .env file\")\n\t}\n\n\t// Open the connection\n\tdb, err := sql.Open(\"postgres\", os.Getenv(\"POSTGRES_URL\"))\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// check the connection\n\terr = db.Ping()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(\"Successfully connected!\")\n\t// return the connection\n\treturn db\n}", "func Connect() *sql.DB {\n\tdbinfo := fmt.Sprintf(\"user=%s password=%s dbname=%s sslmode=disable\", DbUser, DbPassword, DbName)\n\n\tdb, _ := sql.Open(\"postgres\", dbinfo)\n\n\treturn db\n}", "func Connect() *pg.DB {\n\topt := &pg.Options{\n\t\tAddr: \"localhost:5432\",\n\t\tUser: \"postgres\",\n\t\tPassword: \"changeme\",\n\t\tDatabase: \"auth_db\",\n\t}\n\t//create db pointer\n\tvar db *pg.DB = pg.Connect(opt)\n\tif db == nil {\n\t\tlog.Printf(\"Failed to connect to db\\n\")\n\t\tos.Exit(401)\n\t}\n\tlog.Printf(\"Connected to db\\n\")\n\treturn db\n}", "func Connect() (*sql.DB, error) {\n\tpsqlInfo := fmt.Sprintf(\"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable\", host, port, user, password, dbname)\n\tdb, err := sql.Open(\"postgres\", psqlInfo)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// defer db.Close()\n\n\terr = db.Ping()\n\tif err != nil {\n\t\treturn nil, err\n\n\t}\n\tfmt.Println(\"Connection to database was successful\")\n\treturn db, err\n}", "func DBconnect() *sql.DB{\n\tvar err error\n\tpsqlInfo := fmt.Sprintf(\"host=%s port=%s user=%s \"+\n\t\t\"password=%s dbname=%s sslmode=disable\", dbhost, dbport, dbuser, dbpass, dbname)\n\n\tdb, err := sql.Open(\"postgres\", psqlInfo)\n\tif err != nil {\n\t\t//using panic may not be best practice\n\t\tpanic(err)\n\t}\n\terr = db.Ping()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(\"Successfully connected to Posgres DB!\")\n\treturn db\n}", "func connect(dsn string) (*sqlx.DB, error) {\n\tdb, err := sqlx.Connect(\"postgres\", dsn)\n\tif err != nil {\n\t\tlog.Log.Err(err).Msg(\"error initializing database connection\")\n\t\treturn nil, err\n\t}\n\treturn db, nil\n}", "func Connect(host string, port int, user, password, dbname string, sslmode bool) (*sql.DB, error) {\n\n\tconnStr := fmt.Sprintf(\"host=%s port=%d user=%s password=%s dbname=%s\", host, port, user, password, dbname)\n\tif sslmode {\n\t\tconnStr += \" sslmode=require\"\n\t}\n\n\tvar err error\n\tdb, err = sql.Open(\"postgres\", connStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = db.Ping()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func (p PostgresProvider) Connect(config *gormx.DatabaseConfig) (*gorm.DB, error) {\n\tif config.Dialect == gormx.DriverPostgres {\n\t\tif db, err := gorm.Open(pg.New(pg.Config{DSN: config.DSN}), &gorm.Config{\n\t\t\tLogger: gormx.DefaultLogger(&config.Logger),\n\t\t}); err == nil {\n\t\t\tif sqlDB, err := db.DB(); err == nil {\n\t\t\t\tif config.MaxIdle > 0 {\n\t\t\t\t\tsqlDB.SetMaxIdleConns(config.MaxIdle)\n\t\t\t\t}\n\t\t\t\tif config.MaxOpen > 0 && config.MaxOpen > config.MaxIdle {\n\t\t\t\t\tsqlDB.SetMaxOpenConns(100)\n\t\t\t\t}\n\t\t\t\tif config.MaxLifetime > 0 {\n\t\t\t\t\tsqlDB.SetConnMaxLifetime(time.Duration(config.MaxLifetime) * time.Second)\n\t\t\t\t}\n\t\t\t\treturn db, nil\n\t\t\t} else {\n\t\t\t\treturn nil, errors.New(\"open DB failed\")\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Errorf(\"connect db failed: error=%s\", err.Error())\n\t\t}\n\t\treturn nil, errors.New(\"connect db failed\")\n\t}\n\treturn nil, errors.New(\"driver is not postgres\")\n}", "func createConnection() *sql.DB {\n\t// load .env file\n\terr := godotenv.Load(\".env\")\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Error loading .env file\")\n\t}\n\n\t// Open the connection\n\tusername := os.Getenv(\"db_user\")\n\tpassword := os.Getenv(\"db_pass\")\n\tdbName := os.Getenv(\"db_name\")\n\tdbHost := os.Getenv(\"db_host\")\n\tdbURI := fmt.Sprintf(\"host=%s user=%s dbname=%s sslmode=disable password=%s\", dbHost, username, dbName, password) //Build connection string\n\n\tdb, err := sql.Open(\"postgres\", dbURI)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// check the connection\n\terr = db.Ping()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(\"Successfully connected!\")\n\t// return the connection\n\treturn db\n}", "func ConnectDB() *sql.DB {\n\n\tvar err error\n\n\t// Connect to the Postgres Database\n\tdb, err = sql.Open(\"postgres\", \"user=rodrigovalente password=password host=localhost port=5432 dbname=api_jwt sslmode=disable\")\n\tlogFatal(err)\n\n\treturn db\n\n}", "func (pg *postgresDatabase) Connect() error {\n\tdb, err := gorm.Open(\"postgres\", pg.cfg.Info())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tpg.db = db\n\treturn nil\n}", "func Connect() (db *pg.DB) {\n\tdb = pg.Connect(&pg.Options{\n\t\tUser: info.User,\n\t\tDatabase: info.Database,\n\t})\n\n\treturn db\n}", "func Connect(connStr string) (*sqlx.DB, error) {\n\tdb, err := sqlx.Open(\"postgres\", connStr)\n\tif err != nil {\n\t\treturn db, err\n\t}\n\n\terr = db.Ping()\n\tif err != nil {\n\t\treturn db, err\n\t}\n\n\treturn db, nil\n}", "func OpenConnection() *sql.DB {\r\n\tpsqlInfo := fmt.Sprintf(\"user=%s \"+\"password=%s dbname=%s sslmode=disable\", user, password, dbname)\r\n\tdb, err := sql.Open(\"postgres\", psqlInfo)\r\n\tcheckErr(err)\r\n\terr = db.Ping()\r\n\tcheckErr(err)\r\n\t//fmt.Println(\"Connected!\")\r\n\treturn db\r\n}", "func connectDB(name, user, password string) (*sql.DB, error) {\n\tdb, err := sql.Open(\"postgres\", fmt.Sprintf(\"user=%s dbname=%s password=%s sslmode=disable\", user, name, password))\n\treturn db, err\n}", "func Connect() *sql.DB {\n\tURL := fmt.Sprintf(\"user=%s password=%s dbname=%s sslmode=%s\", configs.Database.User, configs.Database.Pass, configs.Database.Name, \"disable\")\n\tdb, err := sql.Open(\"postgres\", URL)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn nil\n\t}\n\treturn db\n}", "func Connect(cf *SQLConfig) (*DB, error) {\n\tconnectionString := fmt.Sprintf(\"postgres://%v:%v@%v:%v/%v?sslmode=%v\", cf.Username, cf.Password, cf.Host, cf.Post, cf.Database, cf.SSLMode)\n\tdb, err := sql.Open(\"postgres\", connectionString)\n\tif err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tpingErr := db.Ping()\n\t\tif pingErr != nil {\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Cannot connect to database. Error: %s\", pingErr.Error()))\n\t\t} else {\n\t\t\treturn &DB{db}, nil\n\t\t}\n\t}\n}", "func connectToDatabase(conf base.Configuration) *sql.DB {\n\tdataSourceName := fmt.Sprintf(\"host=%s port=%s dbname=%s sslmode=%s user=%s password=%s\",\n\t\tconf.DbHost, conf.DbPort, conf.DbName, conf.DbSSLMode, conf.DbUser, conf.DbPassword)\n\tdb, err := sql.Open(\"postgres\", dataSourceName)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = db.Ping()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn db\n}", "func Connect() *gorm.DB {\n\tdsn := fmt.Sprintf(\n\t\t\"host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=America/Bogota\",\n\t\tconfig.Load(\"DB_HOST\"), config.Load(\"DB_USER\"), config.Load(\"DB_PWD\"), config.Load(\"DB_NAME\"),\n\t\tconfig.Load(\"DB_PORT\"),\n\t)\n\n\tdb, err := gorm.Open(postgres.Open(dsn), &gorm.Config{\n\t\tQueryFields: true,\n\t})\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn db\n}", "func (ctrl *PGCtrl) Connect(cfg *Config) error {\n\tvar err error\n\tconnStr := fmt.Sprintf(\"postgres://%s:%s@%s/%s?sslmode=disable\", cfg.pgUser, cfg.pgPass, cfg.pgHost, cfg.pgDB)\n\tctrl.conn, err = sql.Open(\"postgres\", connStr)\n\treturn err\n}", "func connect(ctx context.Context, conf *config.DatabaseConf) (*DB, error) {\n\tpgxConf, err := pgxpool.ParseConfig(conf.Url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpgxConf.MaxConns = conf.MaxConns\n\n\tpool, err := pgxpool.ConnectConfig(ctx, pgxConf)\n\treturn &DB{Pool: pool}, err\n}", "func DbConnect() {\n\tpostgresHost, _ := os.LookupEnv(\"CYCLING_BLOG_DB_SERVICE_SERVICE_HOST\")\n\tpostgresPort := 5432\n\tpostgresUser, _ := os.LookupEnv(\"POSTGRES_USER\")\n\tpostgresPassword, _ := os.LookupEnv(\"PGPASSWORD\")\n\tpostgresName, _ := os.LookupEnv(\"POSTGRES_DB\")\n\n\tenv := ENV{Host: postgresHost, Port: postgresPort, User: postgresUser, Password: postgresPassword, Dbname: postgresName}\n\n\tpsqlInfo := fmt.Sprintf(\"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable\", env.Host, env.Port, env.User, env.Password, env.Dbname)\n\tdb, err := sql.Open(\"postgres\", psqlInfo)\n\tif err != nil {\n\t\tlog.Panic(\"DbConnect: unable to connect to database\", err)\n\t}\n\tDB = db\n\tfmt.Println(\"Successfully connected!\")\n}", "func OpenConnection(props *DbProperties) *sql.DB {\n\tpsqlInfo := fmt.Sprintf(\"host=%s port=%s user=%s password=%s dbname=%s sslmode=disable\",\n\t\tprops.Host, props.Port, props.User, props.Password, props.Dbname)\n\n\tdb, err := sql.Open(\"postgres\", psqlInfo)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = db.Ping()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn db\n}", "func Connect() error {\n\n\tdb, err := sql.Open(\"postgres\", config.Get().DatabaseConnection)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = db.Ping()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdatabase = db\n\treturn nil\n}", "func Connect(connURL string) (*sql.DB, error) {\n\tconn, err := sql.Open(\"postgres\", connURL)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to connect to database at %q: %v\", connURL, err)\n\t}\n\n\treturn conn, nil\n}", "func (node *PostgresNode) Connect(dbname string) *sql.DB {\n\tconninfo := fmt.Sprintf(\"postgres://%s@%s:%d/%s?sslmode=disable\",\n\t\tnode.user, node.host, node.Port, dbname)\n\n\tdb, err := sql.Open(\"postgres\", conninfo)\n\tif err != nil {\n\t\tlog.Panic(\"Can't connect to database: \", err)\n\t}\n\n\tnode.connections = append(node.connections, db)\n\treturn db\n}", "func Connect() (*gorm.DB, error) {\n\n\tdb, err := gorm.Open(\"postgres\", config.ConnectionString)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func Connect() (*pg.DB, error) {\n\tvar (\n\t\tconn *pg.DB\n\t\tn int\n\t)\n\taddr := fmt.Sprintf(\"%s:%v\", \"192.168.0.103\", 6001)\n\tconn = pg.Connect(&pg.Options{\n\t\tAddr: addr,\n\t\tUser: User,\n\t\tPassword: Password,\n\t\tDatabase: DatabaseName,\n\t})\n\t_, err := conn.QueryOne(pg.Scan(&n), \"SELECT 1\")\n\tif err != nil {\n\t\treturn conn, fmt.Errorf(\"Error conecting to DB. addr: %s, user: %s, db: %s,%v\", addr, User, DatabaseName, err)\n\t}\n\n\tif err := createSchema(conn); err != nil {\n\t\treturn conn, fmt.Errorf(\"Error creating DB schemas. %v\", err)\n\t}\n\treturn conn, nil\n}", "func NewConnection(cfg config.PostgresConfig) (client *sqlt.DB, err error) {\n\tDSN := fmt.Sprintf(\"host=%s port=5432 dbname=%s user=%s password=%s sslmode=disable\", cfg.Host, cfg.Name, cfg.User, cfg.Password)\n\n\tclient, err = sqlt.Open(\"postgres\", DSN)\n\tif err != nil {\n\t\treturn\n\t}\n\tclient.SetMaxOpenConnections(100)\n\treturn\n}", "func Connect() (*sql.DB, error) {\n\thost := viper.GetString(\"google.cloudsql.host\")\n\tname := viper.GetString(\"google.cloudsql.name\")\n\tuser := viper.GetString(\"google.cloudsql.user\")\n\tpass := viper.GetString(\"google.cloudsql.pass\")\n\tdsn := fmt.Sprintf(\"host=%s dbname=%s user=%s password=%s sslmode=disable\",\n\t\thost, name, user, pass)\n\tdb, err := sql.Open(\"cloudsqlpostgres\", dsn)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while connecting to cloudsql: %v\", err)\n\t}\n\tlog.Printf(\"Connected to cloudsql %q\", host)\n\treturn db, nil\n}", "func NewConnection(cfg *Config, l *zap.Logger) (db *pg.DB, err error) {\n\tif cfg == nil {\n\t\terr = ErrEmptyConfig\n\t\treturn\n\t}\n\n\tif l == nil {\n\t\terr = ErrEmptyLogger\n\t\treturn\n\t}\n\n\topts := &pg.Options{\n\t\tAddr: cfg.Hostname,\n\t\tUser: cfg.Username,\n\t\tPassword: cfg.Password,\n\t\tDatabase: cfg.Database,\n\t\tPoolSize: cfg.PoolSize,\n\t}\n\n\tif cfg.Debug {\n\t\tl.Debug(\"Connect to PostgreSQL\",\n\t\t\tzap.String(\"hostname\", cfg.Hostname),\n\t\t\tzap.String(\"username\", cfg.Username),\n\t\t\tzap.String(\"password\", cfg.Password),\n\t\t\tzap.String(\"database\", cfg.Database),\n\t\t\tzap.Int(\"pool_size\", cfg.PoolSize),\n\t\t\tzap.Any(\"options\", cfg.Options))\n\t}\n\n\tif opts.TLSConfig, err = ssl(cfg.Options); err != nil {\n\t\treturn nil, err\n\t}\n\n\tdb = pg.Connect(opts)\n\tif _, err = db.ExecOne(\"SELECT 1\"); err != nil {\n\t\treturn nil, errors.Wrap(err, \"can't connect to postgres\")\n\t}\n\n\tif cfg.Debug {\n\t\th := new(Hook)\n\t\th.After = func(ctx context.Context, e *pg.QueryEvent) error {\n\t\t\tquery, qErr := e.FormattedQuery()\n\t\t\tl.Debug(\"pg query\",\n\t\t\t\tzap.String(\"query\", string(query)),\n\t\t\t\tzap.Duration(\"query_time\", time.Since(h.StartAt)),\n\t\t\t\tzap.Any(\"params\", e.Params),\n\t\t\t\tzap.NamedError(\"format_error\", qErr),\n\t\t\t\tzap.Error(e.Err))\n\n\t\t\treturn e.Err\n\t\t}\n\t\tdb.AddQueryHook(h)\n\t}\n\n\treturn\n}", "func newDbConnection(connStr string) *sql.DB {\n\tdb, err := sql.Open(\"postgres\", connStr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = db.Ping()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"[es] new db connection established.\")\n\treturn db\n}", "func ConnectPostgres(ctx context.Context, poolConfig *pgxpool.Config) (*pgx.Conn, error) {\n\tconnConfig := poolConfig.ConnConfig.Copy()\n\tconnConfig.Database = \"postgres\"\n\n\tif poolConfig.BeforeConnect != nil {\n\t\tif err := poolConfig.BeforeConnect(ctx, connConfig); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t}\n\n\tconn, err := pgx.ConnectConfig(ctx, connConfig)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tif poolConfig.AfterConnect != nil {\n\t\tif err := poolConfig.AfterConnect(ctx, conn); err != nil {\n\t\t\tconn.Close(ctx)\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t}\n\n\treturn conn, nil\n}", "func createConnPostgres(desc string, maxIdle, maxConn int) (*sql.DB, error) {\n\t// val := url.Values{}\n\t// val.Add(\"TimeZone\", \"Asia/Jakarta\")\n\t// dsn := fmt.Sprintf(\"%s&%s\", desc, val.Encode())\n\tsqlDb, err := sql.Open(`postgres`, desc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = sqlDb.Ping()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsqlDb.SetMaxIdleConns(maxIdle)\n\tsqlDb.SetMaxOpenConns(maxConn)\n\n\treturn sqlDb, nil\n}", "func newPostgresConnection(dsn string) (*postgresConnection, error) {\n\tconn := postgresConnection{\n\t\tDSN: dsn,\n\t\tDB: nil,\n\t}\n\tdb, err := conn.open()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not open postgres db connection, err = %w\", err)\n\t}\n\tconn.DB = db\n\tif err := conn.Check(); err != nil {\n\t\treturn nil, fmt.Errorf(\"postgres db connection check failed, err = %w\", err)\n\t}\n\treturn &conn, nil\n}", "func Connect() (*sqlx.DB, error) {\n\tpsqlInfo := fmt.Sprintf(\"host=%s port=%d user=%s \"+\n\t\t\"password=%s dbname=%s sslmode=disable\",\n\t\thost, port, user, password, dbname)\n\n\tdb, err := sqlx.Connect(\"postgres\", psqlInfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = db.Ping()\n\tif err != nil {\n\t\tdb.Close()\n\t\treturn nil, err\n\t}\n\tlogrus.Debugf(\"Successfully connected to database %s\", psqlInfo)\n\treturn db, nil\n}", "func (pg *PostgresqlDb)Open() *domain.ErrHandler {\n connErr:= pg.config() \n if connErr != nil {\n return connErr\n }\n var err error\n psqlInfo := fmt.Sprintf(\"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable\", pg.host, pg.port, pg.user, pg.pass, pg.dbname)\n pg.conn, err = sql.Open(\"postgres\", psqlInfo)\n if err != nil {\n return &domain.ErrHandler{1, \"func (pg PostgresqlDb)\", \"Open\", err.Error()}\n }\n err = pg.conn.Ping()\n if err != nil {\n return &domain.ErrHandler{1, \"func (pg PostgresqlDb)\", \"Open\", err.Error()}\n }\n connErr = pg.initDb()\n if connErr != nil {\n return connErr\n }\n return nil\n}", "func (c *Postgres) Connect(ctx Ctx, goose *goosepkg.Instance) (_ *sql.DB, _ *schemaver.SchemaVer, err error) {\n\tlog := structlog.FromContext(ctx, nil)\n\n\tcfg := c.PostgresConfig.Clone()\n\tcfg.DefaultTransactionIsolation = sql.LevelDefault\n\tcfg.StatementTimeout = postgresStatementTimeout\n\tcfg.LockTimeout = postgresLockTimeout\n\tcfg.IdleInTransactionSessionTimeout = postgresIdleInTransactionSessionTimeout\n\terr = cfg.UpdateConnectTimeout(ctx)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdb, err := sql.Open(\"postgres\", cfg.FormatDSN())\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"sql.Open: %w\", err)\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tlog.WarnIfFail(db.Close)\n\t\t}\n\t}()\n\n\tif cfg.ConnectTimeout != 0 {\n\t\tvar cancel func()\n\t\tctx, cancel = context.WithTimeout(ctx, cfg.ConnectTimeout)\n\t\tdefer cancel()\n\t}\n\terr = db.PingContext(ctx)\n\tfor err != nil {\n\t\tnextErr := db.PingContext(ctx)\n\t\tif errors.Is(nextErr, context.DeadlineExceeded) || errors.Is(nextErr, context.Canceled) {\n\t\t\treturn nil, nil, fmt.Errorf(\"db.Ping: %w\", err)\n\t\t}\n\t\terr = nextErr\n\t}\n\n\tgooseMu.Lock()\n\tdefer gooseMu.Unlock()\n\tmust.NoErr(goose.SetDialect(\"postgres\"))\n\t_, _ = goose.EnsureDBVersion(db) // Race on CREATE TABLE, so allowed to fail.\n\n\tver, err := schemaver.NewAt(\"goose-\" + cfg.FormatURL())\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn db, ver, nil\n}", "func connection()(db *sql.DB, err error){\n\tdb, err = sql.Open(\"postgres\", config.getUrlConnection(\"postgres\"))\n\tif err != nil {\n\t\tfmt.Println(\"error\")\n\t\tdb.Close()\n\t}\n\treturn\n}", "func psqlDB() (*sql.DB) {\n\t// fmt.Println(port, host, user, password, dbname);\n\tpsqlInfo := fmt.Sprintf(\"port=%d host=%s user=%s \" +\n\t\t\"password=%s dbname=%s sslmode=disable\",\n\t\tport, host, user, password, dbname)\n\n\tdb, err := sql.Open(\"postgres\", psqlInfo)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\t// err = db.Ping()\n\t// if err != nil {\n\t// \tpanic(err)\n\t// }\n\t// fmt.Println(\"Successfully Connected!\")\n\treturn db\n}", "func ConnectPostgreSQL() (err error) {\n\tpgPoolConfig := pgx.ConnPoolConfig{*pgConfig, Conf.Pg.NumConnections, nil, 2 * time.Second}\n\tpdb, err = pgx.NewConnPool(pgPoolConfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Couldn't connect to PostgreSQL server: %v\\n\", err)\n\t}\n\n\t// Log successful connection\n\tlog.Printf(\"Connected to PostgreSQL server: %v:%v\\n\", Conf.Pg.Server, uint16(Conf.Pg.Port))\n\n\treturn nil\n}", "func ConnectDb () (*sql.DB, error) {\n\tvar Db *sql.DB\n\tvar err error\n\tpsqlconn := fmt.Sprintf(\"host = %s port = %d user = %s dbname = %s sslmode = disable\", host, port, user, dbname)\n\tDb, err = sql.Open(\"postgres\", psqlconn)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err = Db.Ping(); err != nil {\n\t\treturn nil, err\n\t\tDb.Close()\n\t}\n\tfmt.Println(\"psql connected\")\n\treturn Db, nil\n}", "func newPostgresConnection(cmd *cobra.Command, kind string) (*sqlx.DB, error) {\n\thost, _ := cmd.Flags().GetString(\"postgres-host\")\n\tport, _ := cmd.Flags().GetInt(\"postgres-port\")\n\tsslmode, _ := cmd.Flags().GetString(\"postgres-sslmode\")\n\n\tuser, _ := cmd.Flags().GetString(kind + \"-postgres-user\")\n\tif user == \"\" {\n\t\treturn nil, errors.Errorf(\"flag must not be empty: %s-postgres-user\", kind)\n\t}\n\n\tpassword, _ := cmd.Flags().GetString(kind + \"-postgres-password\")\n\tif password == \"\" {\n\t\treturn nil, errors.Errorf(\"flag must not be empty: %s-postgres-password\", kind)\n\t}\n\n\tdbname, _ := cmd.Flags().GetString(kind + \"-postgres-name\")\n\tif dbname == \"\" {\n\t\treturn nil, errors.Errorf(\"flag must not be empty: %s-postgres-name\", kind)\n\t}\n\n\t// use default dbname, if not provided\n\tif dbname == \"\" {\n\t\tdbname = user\n\t}\n\n\treturn pq.NewConnection(user, password, dbname, host, sslmode, port)\n}", "func ConnectPQ() (*sql.DB, error) {\n\thost := os.Getenv(\"YAGPDB_TEST_PQ_HOST\")\n\tif host == \"\" {\n\t\thost = \"localhost\"\n\t}\n\tuser := os.Getenv(\"YAGPDB_TEST_PQ_USER\")\n\tif user == \"\" {\n\t\tuser = \"yagpdb_test\"\n\t}\n\n\tdbPassword := os.Getenv(\"YAGPDB_TEST_PQ_PASSWORD\")\n\tsslMode := os.Getenv(\"YAGPDB_TEST_PQ_SSLMODE\")\n\tif sslMode == \"\" {\n\t\tsslMode = \"disable\"\n\t}\n\n\tdbName := os.Getenv(\"YAGPDB_TEST_PQ_DB\")\n\tif dbName == \"\" {\n\t\tdbName = \"yagpdb_test\"\n\t}\n\n\tif !strings.Contains(dbName, \"test\") {\n\t\tpanic(\"Test database name has to contain 'test'T this is a safety measure to protect against running tests on production systems.\")\n\t}\n\n\tconnStr := fmt.Sprintf(\"host=%s user=%s dbname=%s sslmode=%s password='%s'\", host, user, dbName, sslMode, dbPassword)\n\tconnStrPWCensored := fmt.Sprintf(\"host=%s user=%s dbname=%s sslmode=%s password='%s'\", host, user, dbName, sslMode, \"***\")\n\tfmt.Println(\"Postgres connection string being used: \" + connStrPWCensored)\n\n\tconn, err := sql.Open(\"postgres\", connStr)\n\treturn conn, err\n}", "func (c *postgresConnection) open() (*sql.DB, error) {\n\treturn sql.Open(\"postgres\", c.DSN)\n}", "func dbconn() (db *sql.DB) {\n\tdbDriver := \"mysql\"\n dbUser := \"root\"\n dbPass := \"\"\n\tdbName := \"pmi\"\n\tdb, err := sql.Open(dbDriver, dbUser+\":\"+dbPass+\"@/\"+dbName)\n\tif err != nil {\n panic(err.Error())\n }\n return db\n}", "func ConnectDB() *sql.DB {\n\tpgURL, _ := pq.ParseURL(os.Getenv(\"DATABASE_URL\"))\n\tdb, _ := sql.Open(\"postgres\", pgURL)\n\n\terr := db.Ping() // check connection to db and log error\n\tLogFatal(err)\n\n\treturn db\n}", "func Connect(ctx context.Context, cfg Config) (*DB, error) {\n\tpool, err := pgxpool.New(ctx, ConnString(cfg))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"database connection error: %w\", err)\n\t}\n\tdb := DB{pool}\n\n\treturn &db, nil\n}", "func ConnectDB() *sql.DB {\n\n\t// connString := fmt.Sprintf(\"%s/%s/@//****:****/%s\",\n\t// dbusername,\n\t// dbpassword,\n\t// dbsid)\n\n\t// db, err := sql.Open(\"goracle\", connString)\n\tdb, err := sql.Open(\n\t\t\"godror\", \"plnadmin/plnadmin@apkt_dev\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn db\n}", "func Connect(dbCfg config.DBConfig) (*sql.DB, error) {\n\t// Assemble database connection string\n\tsqlConnStr := fmt.Sprintf(\"host=%s port=%d dbname=%s user=%s \"+\n\t\t\"sslmode=disable\", dbCfg.DBHost, dbCfg.DBPort,\n\t\tdbCfg.DBName, dbCfg.DBUsername)\n\n\tif len(dbCfg.DBPassword) > 0 {\n\t\tsqlConnStr += fmt.Sprintf(\" password=%s\", dbCfg.DBPassword)\n\t}\n\n\t// Connect to database\n\tdb, err := sql.Open(\"postgres\", sqlConnStr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error opening connection to database: %s\",\n\t\t\terr.Error())\n\t}\n\n\t// Check connection\n\terr = db.Ping()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error checking connection: %s\", err.Error())\n\t}\n\n\treturn db, nil\n}", "func DBConnect() (err error) {\n\turi := fmt.Sprintf(\n\t\t\"postgres://%s:%s@%s:%s/archive?sslmode=disable\",\n\t\tos.Getenv(\"POSTGRES_USER\"),\n\t\tos.Getenv(\"POSTGRES_PASSWORD\"),\n\t\tos.Getenv(\"POSTGRES_HOST\"),\n\t\tos.Getenv(\"POSTGRES_PORT\"),\n\t)\n\tdb, err = sql.Open(\"postgres\", uri)\n\treturn err\n}", "func OpenConnection() *sql.DB {\n\terr := godotenv.Load(\"ENV.env\")\n\tif err != nil {\n\t\tlog.Fatal(\"Error loading env file \\n\", err)\n\t}\n\tvar db *sql.DB\n\n\tdsn := fmt.Sprintf(\"host=%s user=%s password=%s dbname=%s port=%s sslmode=disable\",\n\t\tos.Getenv(\"DB_HOST\"),os.Getenv(\"DB_USERNAME\"), os.Getenv(\"DB_PASSWORD\"), os.Getenv(\"DB_NAME\"), os.Getenv(\"DB_PORT\"))\n\n\tlog.Print(\"Connecting to PostgreSQL DB...\")\n\tdb, err = sql.Open(\"postgres\",dsn)\n\n\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to connect to database. \\n\", err)\n\t\tos.Exit(2)\n\n\t}\n\tlog.Println(\"connected\")\n\treturn db;\n\n}", "func Connect(username string, password string, db string, poolSize int, schema string, hostname string, port int) {\n CAFile := \"root.crt\"\n CACert, err := ioutil.ReadFile(CAFile)\n if err != nil {\n log.Errorf(\"failed to load server certificate: %v\", err)\n }\n\n CACertPool := x509.NewCertPool()\n\tCACertPool.AppendCertsFromPEM(CACert)\n\t tlsConfig := &tls.Config{\n RootCAs: CACertPool,\n\t\tInsecureSkipVerify: true,\n\t\t// ServerName: \"localhost\",\n }\n\tcreateSchemaStatement := fmt.Sprintf(\"CREATE SCHEMA IF NOT EXISTS \\\"%s\\\";\", schema)\n\tuseSchemaStatement := fmt.Sprintf(\"SET SEARCH_PATH = \\\"%s\\\";\", schema)\n\tdbConn = pg.Connect(&pg.Options{\n\t\tAddr: fmt.Sprintf(\"%s:%d\", hostname, port),\n\t\tUser: username,\n\t\tPassword: password,\n\t\tDatabase: db,\n\t\tPoolSize: poolSize,\n TLSConfig: tlsConfig,\n\t\tOnConnect: func(ctx context.Context, conn *pg.Conn) error {\n\t\t\t_, err := conn.Exec(createSchemaStatement)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\t_, err = conn.Exec(useSchemaStatement)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t})\n}", "func GetConnectionDB() *sql.DB {\n\t// dsn := \"postgres://postgres:[email protected]:5432/go_api_rest?sslmode=disable\"\n\tdsn := \"postgres://vzmemnlocgrknl:ff0e6b953b864cbb9e23f46dfe47ef2e86ca389fae4a3cddbe30ba91725ed058@ec2-52-202-185-87.compute-1.amazonaws.com:5432/ddk2ombgpk8bdq\"\n\tdb, err := sql.Open(\"postgres\", dsn)\n\tif err != nil {\n\t\tlog.Fatal(fmt.Sprintf(\"Error al conectar BD: %s\", err))\n\t}\n\treturn db\n}", "func NewConnection(user, password, name, port, host string, l interfaces.Logger) *sqlx.DB {\n\tdbConnection := fmt.Sprintf(\"user=%s password=%s dbname=%s port=%s host=%s sslmode=disable\",\n\t\tuser, password, name, port, host)\n\n\tl.Info(\"DB CONN\", \"host\", host, \"port\", port)\n\n\tvar db *sqlx.DB\n\tvar err error\n\tif db, err = sqlx.Connect(\"postgres\", dbConnection); err != nil {\n\t\tl.Panic(\"DB CONN FAILED\", \"error\", err.Error())\n\t}\n\n\treturn db\n}", "func PostgreSQLConnectionString(user, password, hostname, port, dbname, sslmode string) string {\n\ts, _ := pq.ParseURL(\n\t\tfmt.Sprintf(\n\t\t\t\"postgres://%s:%s@%s:%s/%s?sslmode=%s\",\n\t\t\tuser,\n\t\t\tpassword,\n\t\t\thostname,\n\t\t\tport,\n\t\t\tdbname,\n\t\t\tsslmode,\n\t\t),\n\t)\n\treturn s\n}", "func Connect(user string, password string, host string, port int, schema string, dsn string) (*sql.DB, error) {\n\tvar err error\n\tvar connString bytes.Buffer\n\n\tpara := map[string]interface{}{}\n\tpara[\"User\"] = user\n\tpara[\"Pass\"] = password\n\tpara[\"Host\"] = host\n\tpara[\"Port\"] = port\n\tpara[\"Schema\"] = schema\n\n\ttmpl, err := template.New(\"dbconn\").Option(\"missingkey=zero\").Parse(dsn)\n\tif err != nil {\n\t\tlog.Error().Err(err).Msg(\"tmpl parse\")\n\t\treturn nil, err\n\t}\n\n\terr = tmpl.Execute(&connString, para)\n\tif err != nil {\n\t\tlog.Error().Err(err).Msg(\"tmpl execute\")\n\t\treturn nil, err\n\t}\n\n\tlog.Debug().Str(\"dsn\", connString.String()).Msg(\"connect to db\")\n\tdb, err := sql.Open(\"mysql\", connString.String())\n\tif err != nil {\n\t\tlog.Error().Err(err).Msg(\"mysql connect\")\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func Connect(c *Config) (*sql.DB, error) {\n\n\tdb, err := sql.Open(\"sqlserver\", generateConnectionString(c))\n\tif err != nil {\n\t\tlog.Fatal(\"Error creating connection pool: \" + err.Error())\n\t}\n\treturn db, nil\n}", "func dbConn(dbUrl string) {\n\tvar err error\n\tconn, err = pgx.Connect(context.Background(), dbUrl)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to connect to database: %v\\n\", err)\n\t}\n}", "func connect() {\n\tconn, err := http.NewConnection(http.ConnectionConfig{\n\t\tEndpoints: []string{hlp.Conf.DB.URL},\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to create HTTP connection: %v\", err)\n\t}\n\n\tclient, err := driver.NewClient(driver.ClientConfig{\n\t\tConnection: conn,\n\t\tAuthentication: driver.BasicAuthentication(\n\t\t\thlp.Conf.DB.User,\n\t\t\thlp.Conf.DB.Pass,\n\t\t),\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to create new client: %v\", err)\n\t}\n\n\tctx := context.Background()\n\tdb, err := client.Database(ctx, \"cardo_dev\")\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to open database: %v\", err)\n\t}\n\n\tDatabase = db\n}", "func (d *pgDriver) open(ctx context.Context, u *url.URL) (sqlbk.DB, error) {\n\tconnConfig, err := pgx.ParseConfig(u.String())\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tconnConfig.Logger = d.sqlLogger\n\n\t// extract the user from the first client certificate in TLSConfig.\n\tif connConfig.TLSConfig != nil {\n\t\tconnConfig.User, err = tlsConfigUser(connConfig.TLSConfig)\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\tif connConfig.User == \"\" {\n\t\t\treturn nil, trace.BadParameter(\"storage backend certificate CommonName field is blank; database username is required\")\n\t\t}\n\t}\n\n\t// Attempt to create backend database if it does not exist.\n\terr = d.maybeCreateDatabase(ctx, connConfig)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\t// Open connection/pool for backend database.\n\tdb, err := sql.Open(\"pgx\", stdlib.RegisterConnConfig(connConfig))\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\t// Configure the connection pool.\n\tdb.SetConnMaxIdleTime(d.cfg.ConnMaxIdleTime)\n\tdb.SetConnMaxLifetime(d.cfg.ConnMaxLifetime)\n\tdb.SetMaxIdleConns(d.cfg.MaxIdleConns)\n\tdb.SetMaxOpenConns(d.cfg.MaxOpenConns)\n\n\tpgdb := &pgDB{\n\t\tDB: db,\n\t\tpgDriver: d,\n\t\treadOnlyOpts: &sql.TxOptions{ReadOnly: true},\n\t\treadWriteOpts: &sql.TxOptions{},\n\t}\n\n\terr = pgdb.migrate(ctx)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\treturn pgdb, nil\n}", "func Connect() (err error) {\n\tDB, err := sql.Open(\"postgres\", fmt.Sprintf(config.ConfigData.Postgres.Host,\n\t\tconfig.ConfigData.Postgres.User,\n\t\tconfig.ConfigData.Postgres.DBName,\n\t\tconfig.ConfigData.Postgres.Password,\n\t\tconfig.ConfigData.Postgres.Port,\n\t\t\"disable\"))\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"sql open connect\")\n\t}\n\n\tif err = DB.Ping(); err != nil {\n\t\treturn errors.Wrap(err, \"db ping\")\n\t}\n\treturn nil\n}", "func Conn() (*sql.DB, error) {\n\tdb, err := sql.Open(\"postgres\", \"postgres://postgres:changeme@localhost/garages?sslmode=disable\")\n\tif err != nil {\n\t\tfmt.Println(`Could not connect to db`)\n\t\treturn nil, err\n\t}\n\n\tif err := db.Ping(); err != nil {\n\t\tfmt.Println(`Could not connect to db`)\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func ConnectToPostgres(conf *PostgresConfig, models []interface{}) (*gorm.DB, error) {\n\tdb, err := gorm.Open(\n\t\t\"postgres\",\n\t\tfmt.Sprintf(\n\t\t\t\"host=%s port=%d user=%s dbname=%s password=%s sslmode=disable\",\n\t\t\tconf.Host, conf.Port, conf.User, conf.Database, conf.Password,\n\t\t),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdb.AutoMigrate(models...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn db, nil\n}", "func (d *DBGenerator) connect(ctx context.Context) error {\n\tif d.Conn == nil {\n\t\tconnStr := fmt.Sprintf(\"vertica://%s:%s@%s:%d/%s?tlsmode=%s\",\n\t\t\td.Opts.User, d.Opts.Password, d.Opts.Host, d.Opts.Port, d.Opts.DBName, d.Opts.TLSMode,\n\t\t)\n\t\tconn, err := sql.Open(\"vertica\", connStr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\td.Conn = conn\n\t}\n\n\treturn d.Conn.PingContext(ctx)\n}", "func Connect() (db *pg.DB, err error) {\n\topts := &pg.Options{\n\t\tUser: \"NAME\",\n\t\tPassword: \"PASSWORD\",\n\t\tAddr: \"ADDR\",\n\t\tDatabase: \"NAME\",\n\t}\n\n\tif db = pg.Connect(opts); db == nil {\n\t\terr = errors.New(\"Failed To Connect To Database.\")\n\t}\n\treturn\n}", "func (c *Client) Connect() (*DBConnection, error) {\n\tdbRegistryLock.Lock()\n\tdefer dbRegistryLock.Unlock()\n\n\tdsn := c.config.connStr(c.databaseName)\n\tconn, found := dbRegistry[dsn]\n\tif !found {\n\t\tdb, err := sql.Open(proxyDriverName, dsn)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error connecting to PostgreSQL server %s: %w\", c.config.Host, err)\n\t\t}\n\n\t\t// We don't want to retain connection\n\t\t// So when we connect on a specific database which might be managed by terraform,\n\t\t// we don't keep opened connection in case of the db has to be dopped in the plan.\n\t\tdb.SetMaxIdleConns(0)\n\t\tdb.SetMaxOpenConns(c.config.MaxConns)\n\n\t\tconn = &DBConnection{\n\t\t\tdb,\n\t\t\tc,\n\t\t}\n\t\tdbRegistry[dsn] = conn\n\t}\n\n\treturn conn, nil\n}", "func getConn() *gorm.DB {\n\tdsn := \"host=localhost user=hello password=hello dbname=hello port=15432 sslmode=disable TimeZone=Asia/Shanghai\"\n\tdb, _ := gorm.Open(postgres.Open(dsn), &gorm.Config{})\n\n\treturn db\n\t// sqlDB, err := db.DB()\n\n\t// // SetMaxIdleConns 设置空闲连接池中连接的最大数量\n\t// sqlDB.SetMaxIdleConns(10)\n\t// // SetMaxOpenConns 设置打开数据库连接的最大数量。\n\t// sqlDB.SetMaxOpenConns(100)\n\n\t// // SetConnMaxLifetime 设置了连接可复用的最大时间。\n\t// sqlDB.SetConnMaxLifetime(time.Hour)\n}", "func Connect(fromStdin bool) *Database {\n\tdb := pg.Connect(&pg.Options{\n\t\tUser: \"postgres\",\n\t\tPassword: common.GetEnv(\"DB_PASSWORD\"),\n\t\tDatabase: common.DatabaseName,\n\t})\n\treturn &Database{db, CONNECTED, sync.Mutex{}}\n}", "func ConnectPostgresDB(dbLogMode bool) *gorm.DB {\n\treturn connect(\n\t\tenvironments.PostgresHost,\n\t\tenvironments.PostgresPort,\n\t\tenvironments.PostgresUser,\n\t\tenvironments.PostgresPassword,\n\t\tenvironments.PostgresDB,\n\t\tdbLogMode,\n\t)\n}", "func Conecta() *sql.DB {\n\tconexao := \"user=postgres dbname=alura password=admin host=localhost sslmode=disable\"\n\tdb, err := sql.Open(\"postgres\", conexao)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\treturn db\n}", "func NewPostgresConnection() (c *PostgresConnection, err error) {\n\n\tfmt.Println(\"Connecting to PostgreSQL database ...\")\n\n\tdriver := os.Getenv(\"DRIVER\")\n\thost := os.Getenv(\"HOST\")\n\tport := os.Getenv(\"PORT\")\n\tuser := os.Getenv(\"USER\")\n\tpassword := os.Getenv(\"PASSWORD\")\n\tdbname := os.Getenv(\"DBNAME\")\n\n\tconnectionString := fmt.Sprintf(\"host=%s port=%s user=%s \"+\n\t\t\"password=%s dbname=%s sslmode=disable\", host, port, user, password, dbname)\n\n\tfmt.Println(connectionString)\n\tdb, err := sql.Open(driver, connectionString)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = db.Ping()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfmt.Println(\"Connected!\")\n\n\treturn &PostgresConnection{db}, nil\n}", "func (db *DB) Connect() error {\n\tvar dbInfo string = fmt.Sprintf(\"user=%s password=%s dbname=%s sslmode=disable\", db.user, db.password, db.name)\n\td, err := sql.Open(\"postgres\", dbInfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdb.db = d\n\treturn nil\n}", "func Connect() (*pg.DB, error) {\n\toptions, err := pg.ParseURL(os.Getenv(\"DATABASE_URL\"))\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdb := pg.Connect(options)\n\tdb.AddQueryHook(dbLogger{})\n\treturn db, nil\n}", "func Connect(configuration *config.Database) (*gorm.DB, error) {\n\tdsn := \"tcp://\" + configuration.Host + \":\" + configuration.Port + \"?database=\" + configuration.DB + \"&read_timeout=10\"\n\tdb, err := gorm.Open(clickhouse.Open(dsn), &gorm.Config{})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func TestConnect(t *testing.T) {\n\t// First get some ENV variabeles\n\thost := os.Getenv(\"POSTGRES_HOST\")\n\tuser := os.Getenv(\"POSTGRES_USER\")\n\tport := os.Getenv(\"POSTGRES_PORT\")\n\tpassword := os.Getenv(\"POSTGRES_PASS\")\n\tdbname := os.Getenv(\"POSTGRES_DB\")\n\n\tpsqlConnection := fmt.Sprintf(\"host=%s port=%s user=%s password=%s dbname=%s sslmode=disable\", host, port, user, password, dbname)\n\n\t// open the DB connection\n\tdb, err := sql.Open(\"postgres\", psqlConnection)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// Make sure connection really works\n\terr = db.Ping()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func DbConn() (db *sql.DB) {\n\t//var host = \"tcp(192.168.0.14)\"\n\tvar host = \"tcp(192.168.0.12)\"\n\t// var host = \"tcp(127.0.0.1)\"\n\tdbname := \"dbaexperience\"\n\tdb, err := sql.Open(config.DbDriver, fmt.Sprintf(\"%s:%s@%s/%s\", config.DbUser, config.DbPass, host, dbname))\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn db\n}", "func OpenPostgreDatabase(user, pwd, dbname string) (*sql.DB, error){\n\tconnectionString := getPostgresConnectionString(user, pwd, dbname)\n\treturn sql.Open(\"postgres\", connectionString)\n}", "func Connect() {\n\tconString := env.GetEnvOrPanic(\"POSTGRES_URL\")\n\n\t// open a db connection\n\n\tdb, err := gorm.Open(\"postgres\", conString)\n\tif err != nil {\n\t\tlog.Println(\"db err: \", err)\n\t\tconn = nil\n\t\treturn\n\t}\n\tdb.DB().SetMaxIdleConns(0)\n\tconn = db\n}", "func ConnectDB() (*sql.DB, error) {\n\tpgURL, err := pq.ParseURL(os.Getenv(\"SQL_URL\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdb, err := sql.Open(\"postgres\", pgURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = db.Ping()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func ConnectarBD() *sql.DB {\n\n\tvar err error\n\n\tBDInfo := fmt.Sprintf(\"user=%s password=%s host=%s port=%v dbname=%s sslmode=disable\", os.Getenv(\"BD_USUARIO\"), os.Getenv(\"BD_SENHA\"), os.Getenv(\"BD_HOST\"), os.Getenv(\"BD_PORTA\"), os.Getenv(\"BD_NOME\"))\n\tdb, err := sql.Open(\"pgx\", BDInfo)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// BDInfo := fmt.Sprintf(\"user=%s password=%s host=%s port=%v dbname=%s sslmode=disable\", os.Getenv(\"DB_USER\"), os.Getenv(\"DB_PASS\"), os.Getenv(\"BD_HOST\"), os.Getenv(\"BD_PORTA\"), os.Getenv(\"BD_NOME\"))\n\t// db, err := sql.Open(\"postgres\", BDInfo)\n\t// if err != nil {\n\t// \tpanic(err)\n\t// }\n\n\treturn db\n}", "func (d DbConfig) Connect() (*gorm.DB, error) {\n\t/*\n\t * We will build the connection string\n\t * Then will connect to the database\n\t */\n\tcStr := fmt.Sprintf(\"host=%s port=%s dbname=%s user=%s password=%s sslmode=disable\",\n\t\td.Host, d.Port, d.Database, d.Username, d.Password)\n\n\treturn gorm.Open(\"postgres\", cStr)\n}" ]
[ "0.8093835", "0.79845643", "0.78859067", "0.7837119", "0.7728203", "0.7727059", "0.7719656", "0.76921105", "0.7682899", "0.7656938", "0.76550114", "0.76358366", "0.7627754", "0.76153827", "0.7606507", "0.7604759", "0.75778633", "0.7569244", "0.75617576", "0.75186545", "0.7513679", "0.74965733", "0.7483705", "0.7479207", "0.74640375", "0.7463778", "0.73916286", "0.7387007", "0.73838365", "0.73818356", "0.7364836", "0.7357396", "0.7351879", "0.7337525", "0.7333185", "0.73274547", "0.7323377", "0.7310814", "0.73006946", "0.729648", "0.7268884", "0.72594637", "0.72542715", "0.7237495", "0.7215358", "0.721285", "0.72053325", "0.72024184", "0.71871305", "0.7186975", "0.71756655", "0.71739066", "0.71682525", "0.71678734", "0.7166283", "0.7165563", "0.7144066", "0.71211433", "0.71097493", "0.7084207", "0.70791817", "0.7078933", "0.70391905", "0.7038312", "0.7034479", "0.7020405", "0.70179963", "0.70028764", "0.69974065", "0.6997203", "0.6985505", "0.6982515", "0.6979794", "0.69750345", "0.69673", "0.6962504", "0.6960198", "0.6959592", "0.6951951", "0.69412285", "0.69267964", "0.6919987", "0.6917188", "0.6915425", "0.69092", "0.6904002", "0.6894008", "0.6893774", "0.68925035", "0.68831646", "0.686702", "0.6862716", "0.68612033", "0.6857647", "0.68373734", "0.6826337", "0.68086535", "0.6802259", "0.67986166", "0.67930603", "0.6791529" ]
0.0
-1
Get just the metric name
func getMetricName(line string) string { fields := strings.Fields(line) metric := fields[0] reg := regexp.MustCompile(`{`) metric = reg.Split(metric, -1)[0] return metric }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *Metric) GetName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Name\n}", "func (m *MyMetric) Name() string {\n\treturn m.NameStr\n}", "func (m *Metric) GetName() string {\n\tif m == nil || m.Name == nil {\n\t\treturn \"\"\n\t}\n\treturn *m.Name\n}", "func metricName(s string) string {\n\treturn strings.ReplaceAll(s, \"/\", \"_\")\n}", "func MetricName(measurement, fieldKey string, valueType telegraf.ValueType) string {\n\tswitch valueType {\n\tcase telegraf.Histogram, telegraf.Summary:\n\t\tswitch {\n\t\tcase strings.HasSuffix(fieldKey, \"_bucket\"):\n\t\t\tfieldKey = strings.TrimSuffix(fieldKey, \"_bucket\")\n\t\tcase strings.HasSuffix(fieldKey, \"_sum\"):\n\t\t\tfieldKey = strings.TrimSuffix(fieldKey, \"_sum\")\n\t\tcase strings.HasSuffix(fieldKey, \"_count\"):\n\t\t\tfieldKey = strings.TrimSuffix(fieldKey, \"_count\")\n\t\t}\n\t}\n\n\tif measurement == \"prometheus\" {\n\t\treturn fieldKey\n\t}\n\treturn measurement + \"_\" + fieldKey\n}", "func GetMetricLabel(metric string) string {\n\treturn metricLabel[metric]\n}", "func getPromMetricName(desc *otlp.MetricDescriptor, ns string) string {\n\n\tif desc == nil {\n\t\treturn \"\"\n\t}\n\t// whether _total suffix should be applied\n\tisCounter := desc.Type == otlp.MetricDescriptor_MONOTONIC_INT64 ||\n\t\tdesc.Type == otlp.MetricDescriptor_MONOTONIC_DOUBLE\n\n\tb := strings.Builder{}\n\n\tb.WriteString(ns)\n\n\tif b.Len() > 0 {\n\t\tb.WriteString(delimeter)\n\t}\n\tb.WriteString(desc.GetName())\n\n\t// Including units makes two metrics with the same name and label set belong to two different TimeSeries if the\n\t// units are different.\n\t/*\n\t\tif b.Len() > 0 && len(desc.GetUnit()) > 0{\n\t\t\tfmt.Fprintf(&b, delimeter)\n\t\t\tfmt.Fprintf(&b, desc.GetUnit())\n\t\t}\n\t*/\n\n\tif b.Len() > 0 && isCounter {\n\t\tb.WriteString(delimeter)\n\t\tb.WriteString(totalStr)\n\t}\n\treturn sanitize(b.String())\n}", "func (r *reducer) name() string { return r.stmt.Source.(*Measurement).Name }", "func (o MrScalarTerminationPolicyStatementOutput) MetricName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MrScalarTerminationPolicyStatement) string { return v.MetricName }).(pulumi.StringOutput)\n}", "func (r *Rule) MetricName() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"metricName\"])\n}", "func (m *ccMetric) Name() string {\n\treturn m.name\n}", "func (b *Plain) Metric() string {\n\treturn b.section + \".\" + b.operation\n}", "func (o MetricIdentifierOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MetricIdentifier) string { return v.Name }).(pulumi.StringOutput)\n}", "func (o TopicRuleErrorActionCloudwatchMetricOutput) MetricName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleErrorActionCloudwatchMetric) string { return v.MetricName }).(pulumi.StringOutput)\n}", "func (o ExternalMetricSourceOutput) MetricName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ExternalMetricSource) string { return v.MetricName }).(pulumi.StringOutput)\n}", "func (o ExternalMetricStatusOutput) MetricName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ExternalMetricStatus) string { return v.MetricName }).(pulumi.StringOutput)\n}", "func (o MrScalarTaskScalingDownPolicyOutput) MetricName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MrScalarTaskScalingDownPolicy) string { return v.MetricName }).(pulumi.StringOutput)\n}", "func (m *metricEventDimensions) Name() string {\n\treturn m.nameField\n}", "func (o ObjectMetricSourceOutput) MetricName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ObjectMetricSource) string { return v.MetricName }).(pulumi.StringOutput)\n}", "func (o TopicRuleCloudwatchMetricOutput) MetricName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleCloudwatchMetric) string { return v.MetricName }).(pulumi.StringOutput)\n}", "func (o MrScalarCoreScalingDownPolicyOutput) MetricName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MrScalarCoreScalingDownPolicy) string { return v.MetricName }).(pulumi.StringOutput)\n}", "func (o ExternalMetricSourcePatchOutput) MetricName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ExternalMetricSourcePatch) *string { return v.MetricName }).(pulumi.StringPtrOutput)\n}", "func (o ObjectMetricStatusOutput) MetricName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ObjectMetricStatus) string { return v.MetricName }).(pulumi.StringOutput)\n}", "func (o ElastigroupMultipleMetricsMetricOutput) MetricName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ElastigroupMultipleMetricsMetric) string { return v.MetricName }).(pulumi.StringOutput)\n}", "func (ms MetricDescriptor) Name() string {\n\treturn (*ms.orig).Name\n}", "func (o ObjectMetricSourcePatchOutput) MetricName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ObjectMetricSourcePatch) *string { return v.MetricName }).(pulumi.StringPtrOutput)\n}", "func (o ElastigroupScalingDownPolicyOutput) MetricName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingDownPolicy) string { return v.MetricName }).(pulumi.StringOutput)\n}", "func (md *pcpMetricDesc) Name() string {\n\treturn md.name\n}", "func (o ExternalMetricStatusPatchOutput) MetricName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ExternalMetricStatusPatch) *string { return v.MetricName }).(pulumi.StringPtrOutput)\n}", "func (o ElastigroupScalingTargetPolicyOutput) MetricName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingTargetPolicy) string { return v.MetricName }).(pulumi.StringOutput)\n}", "func (o *UsageTopAvgMetricsHour) GetMetricName() string {\n\tif o == nil || o.MetricName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.MetricName\n}", "func MetricNameFromMetric(m model.Metric) (model.LabelValue, error) {\n\tif value, found := m[model.MetricNameLabel]; found {\n\t\treturn value, nil\n\t}\n\treturn \"\", fmt.Errorf(\"no MetricNameLabel for chunk\")\n}", "func MetricName(metrics map[string]metricSource.MetricData) string {\n\tif metric, ok := metrics[firstTarget]; ok {\n\t\treturn metric.Name\n\t}\n\treturn \"\"\n}", "func (o ObjectMetricStatusPatchOutput) MetricName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ObjectMetricStatusPatch) *string { return v.MetricName }).(pulumi.StringPtrOutput)\n}", "func (o SolutionConfigHpoConfigPropertiesHpoObjectivePropertiesOutput) MetricName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v SolutionConfigHpoConfigPropertiesHpoObjectiveProperties) *string { return v.MetricName }).(pulumi.StringPtrOutput)\n}", "func (o PodsMetricSourceOutput) MetricName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v PodsMetricSource) string { return v.MetricName }).(pulumi.StringOutput)\n}", "func (o PodsMetricSourcePatchOutput) MetricName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v PodsMetricSourcePatch) *string { return v.MetricName }).(pulumi.StringPtrOutput)\n}", "func (m *MeasurementStatus) Name() string {\n return m.data.Name\n}", "func (o SolutionConfigAutoMlConfigPropertiesOutput) MetricName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v SolutionConfigAutoMlConfigProperties) *string { return v.MetricName }).(pulumi.StringPtrOutput)\n}", "func (o MrScalarTaskScalingUpPolicyOutput) MetricName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MrScalarTaskScalingUpPolicy) string { return v.MetricName }).(pulumi.StringOutput)\n}", "func (o MrScalarCoreScalingUpPolicyOutput) MetricName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MrScalarCoreScalingUpPolicy) string { return v.MetricName }).(pulumi.StringOutput)\n}", "func (o PodsMetricStatusOutput) MetricName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v PodsMetricStatus) string { return v.MetricName }).(pulumi.StringOutput)\n}", "func (o ApplicationMetricDescriptionOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationMetricDescription) *string { return v.Name }).(pulumi.StringPtrOutput)\n}", "func (o AiEndpointDeployedModelDedicatedResourceAutoscalingMetricSpecOutput) MetricName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v AiEndpointDeployedModelDedicatedResourceAutoscalingMetricSpec) *string { return v.MetricName }).(pulumi.StringPtrOutput)\n}", "func (o ServiceLoadMetricDescriptionOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ServiceLoadMetricDescription) string { return v.Name }).(pulumi.StringOutput)\n}", "func TestMetricName(t *testing.T) {\n\ttcs := []struct {\n\t\tprefix string\n\t\tname string\n\t\twantMetric string\n\t\twantLabel string\n\t}{\n\t\t{\n\t\t\tprefix: \"serverStatus.metrics.commands.saslStart.\",\n\t\t\tname: \"total\",\n\t\t\twantMetric: \"mongodb_ss_metrics_commands_saslStart_total\",\n\t\t},\n\t\t{\n\t\t\tprefix: \"serverStatus.metrics.commands._configsvrShardCollection.\",\n\t\t\tname: \"failed\",\n\t\t\twantMetric: \"mongodb_ss_metrics_commands_configsvrShardCollection_failed\",\n\t\t},\n\t\t{\n\t\t\tprefix: \"serverStatus.wiredTiger.lock.\",\n\t\t\tname: \"metadata lock acquisitions\",\n\t\t\twantMetric: \"mongodb_ss_wt_lock_metadata_lock_acquisitions\",\n\t\t},\n\t\t{\n\t\t\tprefix: \"serverStatus.wiredTiger.perf.\",\n\t\t\tname: \"file system write latency histogram (bucket 5) - 500-999ms\",\n\t\t\twantMetric: \"mongodb_ss_wt_perf\",\n\t\t\twantLabel: \"perf_bucket\",\n\t\t},\n\t\t{\n\t\t\tprefix: \"serverStatus.wiredTiger.transaction.\",\n\t\t\tname: \"rollback to stable updates removed from lookaside\",\n\t\t\twantMetric: \"mongodb_ss_wt_txn_rollback_to_stable_updates_removed_from_lookaside\",\n\t\t},\n\t}\n\n\tfor _, tc := range tcs {\n\t\tmetric, label := nameAndLabel(tc.prefix, tc.name)\n\t\tassert.Equal(t, tc.wantMetric, metric, tc.prefix+tc.name)\n\t\tassert.Equal(t, tc.wantLabel, label, tc.prefix+tc.name)\n\t}\n}", "func (o PodsMetricStatusPatchOutput) MetricName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v PodsMetricStatusPatch) *string { return v.MetricName }).(pulumi.StringPtrOutput)\n}", "func (m Measurement) Name() string {\n\treturn m.name\n}", "func (o ContainerResourceMetricSourceOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ContainerResourceMetricSource) string { return v.Name }).(pulumi.StringOutput)\n}", "func (o ContainerResourceMetricSourceOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ContainerResourceMetricSource) string { return v.Name }).(pulumi.StringOutput)\n}", "func customMetric(name string) string {\n\treturn fmt.Sprintf(\"custom.googleapis.com/%s\", DotSlashes(name))\n}", "func (m *Metric) StackdriverName() string {\n\treturn fmt.Sprintf(\"custom.googleapis.com/datadog/%s\", m.Name)\n}", "func (o SolutionConfigHpoConfigPropertiesHpoObjectivePropertiesPtrOutput) MetricName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *SolutionConfigHpoConfigPropertiesHpoObjectiveProperties) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.MetricName\n\t}).(pulumi.StringPtrOutput)\n}", "func (o MetricDescriptorOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v MetricDescriptor) *string { return v.Name }).(pulumi.StringPtrOutput)\n}", "func (o ResourceMetricStatusOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ResourceMetricStatus) string { return v.Name }).(pulumi.StringOutput)\n}", "func (o ResourceMetricStatusOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ResourceMetricStatus) string { return v.Name }).(pulumi.StringOutput)\n}", "func metricString(ns []string) string {\n\treturn strings.Join(ns, \"/\")\n}", "func (o *UpdateMetricRulesetRequest) GetMetricName() string {\n\tif o == nil || isNil(o.MetricName) {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.MetricName\n}", "func (o MetricIdentifierPatchOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v MetricIdentifierPatch) *string { return v.Name }).(pulumi.StringPtrOutput)\n}", "func (o ExternalMetricSourcePatchPtrOutput) MetricName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ExternalMetricSourcePatch) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.MetricName\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ElastigroupScalingUpPolicyOutput) MetricName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingUpPolicy) string { return v.MetricName }).(pulumi.StringOutput)\n}", "func (o SpansMetricOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *SpansMetric) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (o ResourceMetricSourceOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ResourceMetricSource) string { return v.Name }).(pulumi.StringOutput)\n}", "func (o ResourceMetricSourceOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ResourceMetricSource) string { return v.Name }).(pulumi.StringOutput)\n}", "func (o ObjectMetricSourcePatchPtrOutput) MetricName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ObjectMetricSourcePatch) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.MetricName\n\t}).(pulumi.StringPtrOutput)\n}", "func (myprovider *ElasticWorkerMetricsProvider) GetMetricByName(name types.NamespacedName, info provider.CustomMetricInfo, metricSelector labels.Selector) (*custom_metrics.MetricValue, error) {\n klog.Infof(\"Attempt to retrieve metric: %v for resource: %v with metricSelector: %v\",info, name, metricSelector)\n value, err := myprovider.valueFor(info, name.Namespace, name.Name)\n if err != nil {\n return nil, err\n }\n return myprovider.metricFor(value, name, info)\n}", "func (o *SecurityMonitoringRuleCase) GetName() string {\n\tif o == nil || o.Name == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Name\n}", "func (o ContainerResourceMetricStatusOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ContainerResourceMetricStatus) string { return v.Name }).(pulumi.StringOutput)\n}", "func (o ContainerResourceMetricStatusOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ContainerResourceMetricStatus) string { return v.Name }).(pulumi.StringOutput)\n}", "func (b *Plain) MetricWithSuffix() string {\n\treturn b.section + \"-\" + operationsStatus[b.success] + \".\" + b.operation\n}", "func (o ExternalMetricSourcePtrOutput) MetricName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ExternalMetricSource) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.MetricName\n\t}).(pulumi.StringPtrOutput)\n}", "func (o SolutionConfigAutoMlConfigPropertiesPtrOutput) MetricName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *SolutionConfigAutoMlConfigProperties) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.MetricName\n\t}).(pulumi.StringPtrOutput)\n}", "func metricKey(s string) string {\n\tin := []rune(s)\n\tvar out []rune\n\n\tfor i, r := range in {\n\t\tif !unicode.In(r, unicode.Letter, unicode.Number) {\n\t\t\tout = append(out, '_')\n\t\t\tcontinue\n\t\t}\n\t\tlr := unicode.ToLower(r)\n\t\t// Add an underscore if the current rune:\n\t\t// - is uppercase\n\t\t// - not the first rune\n\t\t// - is followed or preceded by a lowercase rune\n\t\t// - was not preceded by an underscore in the output\n\t\tif r != lr &&\n\t\t\ti > 0 &&\n\t\t\t(i+1) < len(in) &&\n\t\t\t(unicode.IsLower(in[i+1]) || unicode.IsLower(in[i-1])) &&\n\t\t\tout[len(out)-1] != '_' {\n\t\t\tout = append(out, '_')\n\t\t}\n\t\tout = append(out, lr)\n\t}\n\treturn string(out)\n}", "func (o ObjectMetricSourcePtrOutput) MetricName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ObjectMetricSource) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.MetricName\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ExternalMetricStatusPatchPtrOutput) MetricName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ExternalMetricStatusPatch) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.MetricName\n\t}).(pulumi.StringPtrOutput)\n}", "func (o TopicRuleErrorActionCloudwatchMetricPtrOutput) MetricName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TopicRuleErrorActionCloudwatchMetric) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.MetricName\n\t}).(pulumi.StringPtrOutput)\n}", "func (m Metric) String() string {\n\tswitch m {\n\tcase MetricCPUPercentAllocation:\n\t\treturn \"cpu_percent_allocation\"\n\tcase MetricGPUPercentAllocation:\n\t\treturn \"gpu_percent_allocation\"\n\tcase MetricMemoryPercentAllocation:\n\t\treturn \"memory_percent_allocation\"\n\tcase MetricEphemeralStoragePercentAllocation:\n\t\treturn \"ephemeral_storage_percent_allocation\"\n\tcase MetricPodPercentAllocation:\n\t\treturn \"pod_percent_allocation\"\n\t}\n\n\treturn \"unknown\"\n}", "func (s MpuSensor) GetName() string {\n\treturn \"Ac-Mg-Gy\"\n}", "func (m *Metric) Label() string {\n\treturn \"metric\"\n}", "func TestGenerateMetricName(t *testing.T) {\n\tpacket := collectd.Packet{\n\t\tPlugin: \"irq\",\n\t\tType: \"irq\",\n\t\tTypeInstance: \"7\",\n\t}\n\tname := coco.MetricName(packet)\n\texpected := 2\n\tactual := strings.Count(name, \"/\")\n\tif actual != expected {\n\t\tt.Errorf(\"Expected %d / separators, got %d\", expected, actual)\n\t}\n\n\tpacket = collectd.Packet{\n\t\tPlugin: \"load\",\n\t\tType: \"load\",\n\t}\n\tname = coco.MetricName(packet)\n\texpected = 1\n\tactual = strings.Count(name, \"/\")\n\tif actual != expected {\n\t\tt.Errorf(\"Expected %d / separators, got %d\", expected, actual)\n\t}\n}", "func (o ObjectMetricStatusPatchPtrOutput) MetricName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ObjectMetricStatusPatch) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.MetricName\n\t}).(pulumi.StringPtrOutput)\n}", "func (o PodsMetricSourcePatchPtrOutput) MetricName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *PodsMetricSourcePatch) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.MetricName\n\t}).(pulumi.StringPtrOutput)\n}", "func (o TopicRuleErrorActionTimestreamDimensionOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleErrorActionTimestreamDimension) string { return v.Name }).(pulumi.StringOutput)\n}", "func sanitizeMetricName(namespace string, v *view.View) string {\n\tif namespace != \"\" {\n\t\tnamespace = strings.Replace(namespace, \" \", \"\", -1)\n\t\treturn sanitizeString(namespace) + \".\" + sanitizeString(v.Name)\n\t}\n\treturn sanitizeString(v.Name)\n}", "func (e *Measurement) GetName() string {\n\treturn \"properties\"\n}", "func (o ExternalMetricStatusPtrOutput) MetricName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ExternalMetricStatus) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.MetricName\n\t}).(pulumi.StringPtrOutput)\n}", "func (o MetricIdentifierPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *MetricIdentifier) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Name\n\t}).(pulumi.StringPtrOutput)\n}", "func (o TopicRuleCloudwatchMetricPtrOutput) MetricName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TopicRuleCloudwatchMetric) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.MetricName\n\t}).(pulumi.StringPtrOutput)\n}", "func (p *parser) metric() labels.Labels {\n\tname := \"\"\n\tvar m labels.Labels\n\n\tt := p.peek().typ\n\tif t == itemIdentifier || t == itemMetricIdentifier {\n\t\tname = p.next().val\n\t\tt = p.peek().typ\n\t}\n\tif t != itemLeftBrace && name == \"\" {\n\t\tp.errorf(\"missing metric name or metric selector\")\n\t}\n\tif t == itemLeftBrace {\n\t\tm = p.labelSet()\n\t}\n\tif name != \"\" {\n\t\tm = append(m, labels.Label{Name: labels.MetricName, Value: name})\n\t\tsort.Sort(m)\n\t}\n\treturn m\n}", "func (o ObjectMetricStatusPtrOutput) MetricName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ObjectMetricStatus) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.MetricName\n\t}).(pulumi.StringPtrOutput)\n}", "func (o MetricDescriptorResponseOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MetricDescriptorResponse) string { return v.Name }).(pulumi.StringOutput)\n}", "func (*systemPodMetricsMeasurement) String() string {\n\treturn systemPodMetricsName\n}", "func (m *Metric) String() string {\n\treturn fmt.Sprintf(\"%#v\", m)\n}", "func (o PodsMetricStatusPatchPtrOutput) MetricName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *PodsMetricStatusPatch) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.MetricName\n\t}).(pulumi.StringPtrOutput)\n}", "func (o TopicRuleTimestreamDimensionOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleTimestreamDimension) string { return v.Name }).(pulumi.StringOutput)\n}", "func (m *Float64Measure) Name() string {\n\treturn m.desc.name\n}", "func (mt MessageType) MetricLabel() string {\n\tswitch mt {\n\tcase None:\n\t\treturn \"none\"\n\tcase IfId:\n\t\treturn \"ifid_push\"\n\tcase Ack:\n\t\treturn \"ack_push\"\n\tcase HPSegReg:\n\t\treturn \"hp_seg_reg_push\"\n\tcase HPSegRequest:\n\t\treturn \"hp_seg_req\"\n\tcase HPSegReply:\n\t\treturn \"hp_seg_push\"\n\tcase HPCfgRequest:\n\t\treturn \"hp_cfg_req\"\n\tcase HPCfgReply:\n\t\treturn \"hp_cfg_push\"\n\tdefault:\n\t\treturn \"unknown_mt\"\n\t}\n}", "func (p Prometheus) Name() string {\n\treturn \"Prometheus probe for \" + p.URL + \" [\" + p.Key + \"]\"\n}", "func (m *AssignedEntitiesWithMetricTile) Name() *string {\n\treturn m.nameField\n}", "func (ms MetricDescriptor) Unit() string {\n\treturn (*ms.orig).Unit\n}" ]
[ "0.7088392", "0.70682275", "0.6989944", "0.6754656", "0.67541057", "0.6734059", "0.67125016", "0.6706927", "0.66925615", "0.66604143", "0.6653637", "0.66212684", "0.6587156", "0.6557264", "0.6536429", "0.6534748", "0.65219533", "0.64998996", "0.64918053", "0.64916193", "0.64703953", "0.64363825", "0.6434946", "0.6416906", "0.641395", "0.6399106", "0.63903916", "0.63792825", "0.6373247", "0.6365059", "0.634633", "0.63444763", "0.63300776", "0.6316448", "0.6275691", "0.6267447", "0.6262416", "0.62553537", "0.6242451", "0.6239016", "0.61835706", "0.61651725", "0.6159747", "0.61538345", "0.6143346", "0.6135244", "0.61331314", "0.6110499", "0.60955477", "0.60955477", "0.6088778", "0.6063282", "0.6058881", "0.6058187", "0.60574865", "0.60574865", "0.6043825", "0.60428435", "0.6040659", "0.6031986", "0.60231113", "0.6022831", "0.60180753", "0.60180753", "0.6017498", "0.5995477", "0.59924996", "0.59858096", "0.59858096", "0.5969981", "0.5967951", "0.596666", "0.5964156", "0.5945473", "0.59216315", "0.5916938", "0.59119725", "0.5911799", "0.5910653", "0.59072375", "0.5904698", "0.5891789", "0.5877555", "0.58713555", "0.58595866", "0.5842561", "0.58356506", "0.58252215", "0.58147407", "0.58108044", "0.5809914", "0.5809842", "0.57985294", "0.5762089", "0.5754362", "0.57478243", "0.57342434", "0.57305765", "0.57299787", "0.5712746" ]
0.74981976
0
Sent updates the metrics for having sent [msg].
func (m *Metrics) Sent(msg message.OutboundMessage) { op := msg.Op() msgMetrics := m.MessageMetrics[op] if msgMetrics == nil { m.Log.Error( "unknown message being sent", zap.Stringer("messageOp", op), ) return } msgMetrics.NumSent.Inc() msgMetrics.SentBytes.Add(float64(len(msg.Bytes()))) // assume that if [saved] == 0, [msg] wasn't compressed if saved := msg.BytesSavedCompression(); saved != 0 { msgMetrics.SavedSentBytes.Observe(float64(saved)) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (f *fakeDiskUpdateWatchServer) SendMsg(m interface{}) error { return nil }", "func (client *Client) sendMessage(msg interface{}) {\n\tstr, err := json.Marshal(msg)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\ts := string(str)\n\tmetrics.SendMessage(len(s))\n\tclient.socketTx <- s\n}", "func (h *mysqlMetricStore) sendmessage() {\n\th.lock.Lock()\n\tdefer h.lock.Unlock()\n\tvar caches = new(MonitorMessageList)\n\tfor _, v := range h.PathCache {\n\t\t_, avg, max := calculate(&v.ResTime)\n\t\tmm := MonitorMessage{\n\t\t\tServiceID: h.ServiceID,\n\t\t\tPort: h.Port,\n\t\t\tMessageType: \"mysql\",\n\t\t\tKey: v.Key,\n\t\t\tHostName: h.HostName,\n\t\t\tCount: v.Count,\n\t\t\tAbnormalCount: v.UnusualCount,\n\t\t\tAverageTime: Round(avg, 2),\n\t\t\tMaxTime: Round(max, 2),\n\t\t\tCumulativeTime: Round(avg*float64(v.Count), 2),\n\t\t}\n\t\tcaches.Add(&mm)\n\t}\n\tsort.Sort(caches)\n\tif caches.Len() > 20 {\n\t\th.monitorMessageManage.Send(caches.Pop(20))\n\t\treturn\n\t}\n\th.monitorMessageManage.Send(caches)\n}", "func (h *mysqlMetricStore) sendstatsd() {\n\th.lock.Lock()\n\tdefer h.lock.Unlock()\n\tvar total int64\n\tfor k, v := range h.sqlRequestSize {\n\t\th.statsdclient.Incr(\"request.\"+k, int64(v))\n\t\ttotal += int64(v)\n\t\th.sqlRequestSize[k] = 0\n\t}\n\th.statsdclient.Incr(\"request.total\", int64(total))\n\tmin, avg, max := calculate(&h.requestTimes)\n\th.statsdclient.FGauge(\"requesttime.min\", min)\n\th.statsdclient.FGauge(\"requesttime.avg\", avg)\n\th.statsdclient.FGauge(\"requesttime.max\", max)\n\th.statsdclient.Gauge(\"request.client\", int64(len(h.IndependentIP)))\n}", "func (r *Raft) sendMsg(m pb.Message) {\n\tr.msgs = append(r.msgs, m)\n}", "func WriteMsg(ctx context.Context, crawlabIndex string, es *elastic.Client, when time.Time, msg string) error {\n\tvals := make(map[string]interface{})\n\tvals[\"@timestamp\"] = when.Format(time.RFC3339)\n\tvals[\"@msg\"] = msg\n\tuid := uuid.NewV4().String()\n\t_, err := es.Index().Index(crawlabIndex).Id(uid).BodyJson(vals).Refresh(\"wait_for\").Do(ctx)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\treturn err\n}", "func (s *sendClient) sendMetrics(buf []byte) error {\n\treq, err := http.NewPushRequest(s.writeURL.String(), s.apiKey, s.hostname, buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = http.DoPushRequest(s.writeClient, req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func sendMsg(conn *net.UDPConn, raddr net.UDPAddr, query interface{}) {\n\ttotalSent.Add(1)\n\tvar b bytes.Buffer\n\tif err := bencode.Marshal(&b, query); err != nil {\n\t\treturn\n\t}\n\tif n, err := conn.WriteToUDP(b.Bytes(), &raddr); err != nil {\n\t\tlogger.Infof(\"DHT: node write failed to %+v, error=%s\", raddr, err)\n\t} else {\n\t\ttotalWrittenBytes.Add(int64(n))\n\t}\n\treturn\n}", "func updateMessageStats(w io.Writer, update tgbotapi.Update, username string) {\n\tif update.Message.From != nil && update.Message.Chat.UserName == username {\n\t\tif saved, err := saveStats(w, &update); err != nil {\n\t\t\tlog.Println(T(\"stats_error_saving\"), err.Error(), saved)\n\t\t}\n\t}\n}", "func (ms *msgSender) SendMessage(ctx context.Context, p peer.ID, pmes *pb.Message) error {\n\tctx, _ = tag.New(ctx, kadmetrics.UpsertMessageType(pmes))\n\tdefer stats.Record(ctx, kadmetrics.SentMessages.M(1))\n\n\ts, err := ms.h.NewStream(ctx, p, ms.protocols...)\n\tif err != nil {\n\t\tstats.Record(ctx, kadmetrics.SentMessageErrors.M(1))\n\t\treturn err\n\t}\n\tdefer func() { _ = s.Close() }()\n\n\tif err = protoio.NewDelimitedWriter(s).WriteMsg(pmes); err != nil {\n\t\tstats.Record(ctx, kadmetrics.SentMessageErrors.M(1))\n\t\treturn err\n\t}\n\n\tstats.Record(ctx, kadmetrics.SentBytes.M(int64(pmes.Size())))\n\treturn nil\n}", "func (b *BandwidthCollector) LogSentMessage(int64) {}", "func (reporter *ProgressReporter) sendUpdates() {\n\tb := reporter.serialize()\n\tfmt.Println(string(b))\n\tgo reporter.postProgressToURL(b)\n}", "func (metrics *Metrics) Send(name string, value int) error {\n\t// Avoid crash\n\tif !metrics.Ready {\n\t\treturn fmt.Errorf(\"metrics are not ready\")\n\t}\n\tmData := metrics.metricFormat(name, value)\n\tif metrics.Protocol == \"udp\" {\n\t\tfmt.Fprintf(metrics.conn, mData)\n\t} else if metrics.Protocol == \"tcp\" {\n\t\tbuf := bytes.NewBufferString(\"\")\n\t\tbuf.WriteString(mData)\n\t\t_, err := metrics.conn.Write(buf.Bytes())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func ws_SendMsg(ws *websocket.Conn, send_channel SendChannel) {\n\tfor {\n\t\tselect {\n\t\tcase send_msg := <-send_channel.containers:\n\t\t\tlog.Printf(\"[%s] containers sendMessage= \", __FILE__, send_msg)\n\t\t\twebsocket.JSON.Send(ws, send_msg)\n\t\tcase send_msg := <-send_channel.updateinfo:\n\t\t\tlog.Printf(\"[%s] update sendMessage=\", __FILE__, send_msg)\n\t\t}\n\t}\n}", "func (r *Raft) sendHeartbeat(to uint64) {\n\t//r.Prs[to].Next = r.RaftLog.LastIndex() + 1\n\tmsg := r.buildMsgWithoutData(pb.MessageType_MsgHeartbeat, to, false)\n\t//msg.Entries = entryValuesToPoints(r.RaftLog.entries[len(r.RaftLog.entries)-1:])\n\n\tr.appendMsg(msg)\n\t// Your Code Here (2A).\n}", "func (s *ClientState) send(msg MsgBody) error {\n\tb, err := json.Marshal(msg)\n\tif err != nil {\n\t\tlogError(\"could not marshal message: %s\", err)\n\t\treturn err\n\t}\n\tlogDebug(\"sending message\")\n\ts.ws.SetWriteDeadline(time.Now().Add(WEBSOCKET_WRITE_TIMEOUT))\n\terr = s.ws.WriteMessage(websocket.TextMessage, b)\n\tif err != nil {\n\t\tlogError(\"could not send message: %s\", err)\n\t\treturn err\n\t}\n\tlogDebug(\"sent: %s\", string(b))\n\treturn nil\n}", "func (d *Dao) SendMessage(mids []int64, msg string, contest *mdlesp.Contest) (err error) {\n\tparams := url.Values{}\n\tparams.Set(\"mid_list\", xstr.JoinInts(mids))\n\tparams.Set(\"title\", d.c.Rule.AlertTitle)\n\tparams.Set(\"mc\", d.c.Message.MC)\n\tparams.Set(\"data_type\", _notify)\n\tparams.Set(\"context\", msg)\n\tvar res struct {\n\t\tCode int `json:\"code\"`\n\t}\n\terr = d.messageHTTPClient.Post(context.Background(), d.c.Message.URL, \"\", params, &res)\n\tif err != nil {\n\t\tlog.Error(\"SendMessage d.messageHTTPClient.Post(%s) error(%+v)\", d.c.Message.URL+\"?\"+params.Encode(), err)\n\t\treturn\n\t}\n\tif res.Code != 0 {\n\t\tlog.Error(\"SendMessage url(%s) res code(%d)\", d.c.Message.URL+\"?\"+params.Encode(), res.Code)\n\t\terr = ecode.Int(res.Code)\n\t}\n\treturn\n}", "func logSentMetric(metric string) {\n\tif *logSent {\n\t\tfmt.Printf(\"%s\\n\", metric)\n\t}\n}", "func (s *sendClient) sendMetrics(buf []byte) error {\n\tlog.Debugln(\"start sending metrics\")\n\n\treq, err := http.NewRequest(\"POST\", s.writeURL.String(), bytes.NewReader(buf))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/text\")\n\treq.Header.Set(\"User-Agent\", \"pgSCV\")\n\treq.Header.Add(\"X-Weaponry-Api-Key\", s.apiKey)\n\n\tq := req.URL.Query()\n\tq.Add(\"timestamp\", fmt.Sprintf(\"%d\", time.Now().UnixNano()/1000000))\n\tq.Add(\"extra_label\", fmt.Sprintf(\"instance=%s\", s.hostname))\n\treq.URL.RawQuery = q.Encode()\n\n\tctx, cancel := context.WithTimeout(context.Background(), s.timeout)\n\tdefer cancel()\n\n\treq = req.WithContext(ctx)\n\n\tresp, err := s.Client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\t_, _ = io.Copy(io.Discard, resp.Body)\n\t\t_ = resp.Body.Close()\n\t}()\n\n\tif resp.StatusCode/100 != 2 {\n\t\tscanner := bufio.NewScanner(io.LimitReader(resp.Body, 512))\n\t\tline := \"\"\n\t\tif scanner.Scan() {\n\t\t\tline = scanner.Text()\n\t\t}\n\t\treturn fmt.Errorf(\"server returned HTTP status %s: %s\", resp.Status, line)\n\t}\n\n\tlog.Debugln(\"sending metrics finished successfully: server returned HTTP status \", resp.Status)\n\treturn nil\n}", "func (c *client) writeMsg(msg Message, ackChan chan Message, ticker *time.Ticker) {\n\tbyteMsg, _ := json.Marshal(&msg)\n\tvar currentBackOff int = 0\n\tvar epochsPassed int = 0\n\tc.conn.Write(byteMsg)\n\n\t// indicate that we have written in this epoch\n\tselect {\n\tcase c.writtenChan <- true:\n\tdefault:\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-c.lostCxn:\n\t\t\treturn\n\t\tcase <-ackChan:\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\t// handle exponential backoff rules\n\t\t\tif epochsPassed == currentBackOff {\n\t\t\t\tc.conn.Write(byteMsg)\n\t\t\t\tselect {\n\t\t\t\tcase c.writtenChan <- true:\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t\tepochsPassed = 0\n\t\t\t\tif currentBackOff != c.maxBackOff {\n\t\t\t\t\tif currentBackOff == 0 {\n\t\t\t\t\t\tcurrentBackOff = 1\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcurrentBackOff *= 2\n\t\t\t\t\t\tif currentBackOff > c.maxBackOff {\n\t\t\t\t\t\t\tcurrentBackOff = c.maxBackOff\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tepochsPassed++\n\t\t\t}\n\t\t}\n\t}\n}", "func sendToWs(msg network.Message, update bool, s *session, messagesDb *MsgDb) {\n\tmsgNum := msg.Seqnum\n\twsMsg := wsMessage{Src: msg.Src, Dst: msg.Dst,\n\t\tMsgNumber: strconv.FormatUint(msgNum, 10), Payload: string(msg.Payload)}\n\ts.logger.Debug(\"sending json message to WS\", zap.Any(\"msg\", wsMsg))\n\tif update {\n\t\t(*messagesDb)[msgNum] = msg\n\t}\n\n\tif err := s.conn.WriteJSON(wsMsg); err != nil {\n\t\ts.logger.Error(\"failed to send json message\", zap.Error(err))\n\t\treturn\n\t}\n}", "func (s *Sender) sendMsg(connID string, msg interface{}) error {\n\tdata, err := json.Marshal(msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.send(connID, data)\n}", "func (this *InfluxdbBackend) Send(items []*cmodel.MetricValue) {\n\tfor _, item := range items {\n\t\tmyItem := item\n\t\tmyItem.Timestamp = item.Timestamp\n\n\t\tisSuccess := this.queue.PushFront(myItem)\n\n\t\t// statistics\n\t\tif !isSuccess {\n\t\t\tthis.dropCounter.Incr()\n\t\t}\n\t}\n}", "func (c Client) Send(bucket string, aggCnt int64, metrics ...Metric) {\n\tif !c.opened {\n\t\treturn\n\t}\n\tif aggCnt == 0 {\n\t\treturn // nothing aggregated\n\t}\n\tsgl := smm.NewSGL(int64(msize))\n\tdefer sgl.Free()\n\n\tbucket = strings.ReplaceAll(bucket, \":\", \"_\")\n\tfor _, m := range metrics {\n\t\tc.appendMetric(m, sgl, bucket, aggCnt)\n\t}\n\tif sgl.Len() > 0 {\n\t\tbytes := sgl.Bytes()\n\t\tmsize = cos.Max(msize, len(bytes))\n\t\t_, err := c.conn.Write(bytes)\n\t\tif err != nil {\n\t\t\tif cnt := errcnt.Inc(); cnt > maxNumErrs {\n\t\t\t\tglog.Errorf(\"Sending to StatsD failed: %v (%d)\", err, cnt)\n\t\t\t\tc.conn.Close()\n\t\t\t\tc.opened = false\n\t\t\t}\n\t\t}\n\t}\n}", "func (mgr *DataCheckMgr) SendMsg(msg *DataCheckMsg) error {\n\n\tblog.V(3).Infof(\"data checker: send an msg to datacheck manager\")\n\n\tselect {\n\tcase mgr.msgQueue <- msg:\n\tdefault:\n\t\tblog.Error(\"data checker: send an msg to datacheck manager fail\")\n\t\treturn fmt.Errorf(\"data checker: mgr queue is full now\")\n\t}\n\n\treturn nil\n}", "func (d *Dao) Send(c context.Context, mc, title, msg string, mid int64) (err error) {\n\tparams := url.Values{}\n\tparams.Set(\"type\", \"json\")\n\tparams.Set(\"source\", \"1\")\n\tparams.Set(\"data_type\", \"4\")\n\tparams.Set(\"mc\", mc)\n\tparams.Set(\"title\", title)\n\tparams.Set(\"context\", msg)\n\tparams.Set(\"mid_list\", strconv.FormatInt(mid, 10))\n\tvar res struct {\n\t\tCode int `json:\"code\"`\n\t}\n\tif err = d.client.Post(c, d.uri, \"\", params, &res); err != nil {\n\t\tlog.Error(\"message url(%s) error(%v)\", d.uri+\"?\"+params.Encode(), err)\n\t\treturn\n\t}\n\tlog.Info(\"SendSysNotify url: (%s)\", d.uri+\"?\"+params.Encode())\n\tif res.Code != 0 {\n\t\tlog.Error(\"message url(%s) error(%v)\", d.uri+\"?\"+params.Encode(), res.Code)\n\t\terr = fmt.Errorf(\"message send failed\")\n\t}\n\treturn\n}", "func (s *sender) sendMetrics(ctx context.Context, flds fields) ([]metricPair, error) {\n\tvar (\n\t\tbody strings.Builder\n\t\terrs error\n\t\tdroppedRecords []metricPair\n\t\tcurrentRecords []metricPair\n\t)\n\n\tfor _, record := range s.metricBuffer {\n\t\tvar formattedLine string\n\t\tvar err error\n\n\t\tswitch s.config.MetricFormat {\n\t\tcase PrometheusFormat:\n\t\t\tformattedLine = s.prometheusFormatter.metric2String(record)\n\t\tcase Carbon2Format:\n\t\t\tformattedLine = carbon2Metric2String(record)\n\t\tcase GraphiteFormat:\n\t\t\tformattedLine = s.graphiteFormatter.metric2String(record)\n\t\tdefault:\n\t\t\terr = fmt.Errorf(\"unexpected metric format: %s\", s.config.MetricFormat)\n\t\t}\n\n\t\tif err != nil {\n\t\t\tdroppedRecords = append(droppedRecords, record)\n\t\t\terrs = multierr.Append(errs, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tar, err := s.appendAndSend(ctx, formattedLine, MetricsPipeline, &body, flds)\n\t\tif err != nil {\n\t\t\terrs = multierr.Append(errs, err)\n\t\t\tif ar.sent {\n\t\t\t\tdroppedRecords = append(droppedRecords, currentRecords...)\n\t\t\t}\n\n\t\t\tif !ar.appended {\n\t\t\t\tdroppedRecords = append(droppedRecords, record)\n\t\t\t}\n\t\t}\n\n\t\t// If data was sent, cleanup the currentTimeSeries counter\n\t\tif ar.sent {\n\t\t\tcurrentRecords = currentRecords[:0]\n\t\t}\n\n\t\t// If log has been appended to body, increment the currentTimeSeries\n\t\tif ar.appended {\n\t\t\tcurrentRecords = append(currentRecords, record)\n\t\t}\n\t}\n\n\tif body.Len() > 0 {\n\t\tif err := s.send(ctx, MetricsPipeline, strings.NewReader(body.String()), flds); err != nil {\n\t\t\terrs = multierr.Append(errs, err)\n\t\t\tdroppedRecords = append(droppedRecords, currentRecords...)\n\t\t}\n\t}\n\n\treturn droppedRecords, errs\n}", "func (s *Service) SendMessage(c context.Context, aid int64, stat *artmdl.Stats) (err error) {\n\tvar (\n\t\ttitle, msg string\n\t\tmeta *artmdl.Meta\n\t\tmax int64\n\t)\n\tif exist, _ := s.dao.ExpireMaxLikeCache(c, aid); exist {\n\t\tmax, _ = s.dao.MaxLikeCache(c, aid)\n\t}\n\tif (stat.Like <= max) || (!shouldNofify(stat.Like)) {\n\t\treturn\n\t}\n\tif meta, err = s.ArticleMeta(c, aid); (err != nil) || (meta == nil) {\n\t\treturn\n\t}\n\tmid := meta.Author.Mid\n\tif len(s.c.Article.MessageMids) > 0 {\n\t\tvar exist bool\n\t\tfor _, m := range s.c.Article.MessageMids {\n\t\t\tif m == mid {\n\t\t\t\texist = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !exist {\n\t\t\treturn\n\t\t}\n\t}\n\ttitle = fmt.Sprintf(\"有%v人点赞了你的专栏文章\", stat.Like)\n\tmsg = fmt.Sprintf(\"有%v个小伙伴点赞你投稿的专栏文章“#{%s}{\\\"http://www.bilibili.com/read/cv%d\\\"}”~快去看看吧!#{点击前往}{\\\"http://www.bilibili.com/read/cv%d\\\"}\", stat.Like, meta.Title, aid, aid)\n\terr = s.dao.SendMessage(c, _likeMessage, mid, aid, title, msg)\n\tcache.Save(func() {\n\t\ts.dao.SetMaxLikeCache(context.TODO(), aid, stat.Like)\n\t})\n\treturn\n}", "func (r *Raft) sendMsgLocally(m pb.Message) {\n\tr.Step(m)\n}", "func (c *Controller) sendOneConsumeCustomMetric(w http.ResponseWriter, customMetricName string, delta int, durationSec int) {\n\tdefer c.waitGroup.Done()\n\tquery := createConsumerURL(BumpMetricAddress)\n\t_, err := http.PostForm(query,\n\t\turl.Values{MetricNameQuery: {customMetricName}, DurationSecQuery: {strconv.Itoa(durationSec)}, DeltaQuery: {strconv.Itoa(delta)}})\n\tc.responseWriterLock.Lock()\n\tdefer c.responseWriterLock.Unlock()\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"Failed to connect to consumer: %v\\n\", err)\n\t\treturn\n\t}\n\tfmt.Fprintf(w, \"Bumped metric %s by %d\\n\", customMetricName, delta)\n}", "func (s *DevStat) Send() {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tvar fields map[string]interface{}\n\n\tactiveTag := \"true\"\n\tconnectedTag := \"true\"\n\tswitch {\n\tcase !s.DeviceActive:\n\t\tactiveTag = \"false\"\n\t\tconnectedTag = \"false\"\n\t\tfields = s.getStatusFields()\n\t\ts.log.Info(\"STATS SEND NOT ACTIVE\")\n\tcase s.DeviceActive && s.DeviceConnected:\n\t\tactiveTag = \"true\"\n\t\tconnectedTag = \"true\"\n\t\ts.log.Infof(\"STATS SNMP GET: snmp polling took [%f seconds] SNMP: Gets [%d] , Processed [%d], Errors [%d]\", s.Counters[CycleGatherDuration], s.Counters[SnmpOIDGetAll], s.Counters[SnmpOIDGetProcessed], s.Counters[SnmpOIDGetErrors])\n\t\ts.log.Infof(\"STATS SNMP FILTER: filter polling took [%f seconds] \", s.Counters[FilterDuration])\n\t\ts.log.Infof(\"STATS INFLUX: influx send took [%f seconds]\", s.Counters[BackEndSentDuration])\n\t\tfields = s.getMetricFields()\n\tcase s.DeviceActive && !s.DeviceConnected:\n\t\tactiveTag = \"true\"\n\t\tconnectedTag = \"false\"\n\t\ts.log.Info(\"STATS SEND NOT CONNECTED\")\n\t\tfields = s.getStatusFields()\n\tdefault:\n\t\ts.log.Error(\"STATS mode unknown\")\n\t\treturn\n\t}\n\n\tif s.selfmon != nil {\n\t\ts.selfmon.AddDeviceMetrics(s.id, fields, s.TagMap, map[string]string{\"device_active\": activeTag, \"device_connected\": connectedTag})\n\t}\n}", "func (n *Notifier) SendMessage(msg string) {\n\tn.notificationMessages <- msg\n}", "func (ch *Checker) MarkAsSent(msg any) error {\n\treturn ch.cache.Set(objecthash.Hash(msg), []byte(`t`))\n}", "func (s *Socket) WriteMsg() {\r\n\tfor {\r\n\t\tselect {\r\n\t\tcase data := <-s.WriteChan:\r\n\t\t\tpref := intToBytes(len(data))\r\n\t\t\tvar buffer bytes.Buffer\r\n\t\t\tbuffer.Write(pref)\r\n\t\t\tbuffer.Write(data)\r\n\t\t\t_, err := s.Conn.Write(buffer.Bytes())\r\n\t\t\tif err != nil {\r\n\t\t\t\tfmt.Println(\"Send Error,\", err)\r\n\t\t\t}\r\n\t\tcase <-s.Ctx.Done():\r\n\t\t\tfmt.Println(\"Quit WriteMsg()\")\r\n\t\t\treturn\r\n\t\t}\r\n\t}\r\n}", "func (mt *Metrics) Send() []error {\n\tif Mail == \"\" || Token == \"\" {\n\t\treturn errAccessCredentials\n\t}\n\n\terr := validateMetrics(mt)\n\n\tif err != nil {\n\t\treturn []error{err}\n\t}\n\n\tif len(mt.queue) == 0 {\n\t\treturn nil\n\t}\n\n\tmt.lastSendingDate = time.Now().Unix()\n\n\tdata := convertMeasurementSlice(mt.queue)\n\n\tmt.queue = make([]Measurement, 0)\n\n\terrs := execRequest(mt.Engine, req.POST, APIEndpoint+\"/v1/metrics/\", data)\n\n\tmt.execErrorHandler(errs)\n\n\treturn errs\n}", "func (bot *SlackBot) sendMessage(msg Message) error {\n\tmsg.ID = atomic.AddUint64(&counter, 1)\n\terr := websocket.JSON.Send(bot.ws, msg)\n\treturn err\n}", "func (s *Websocket) broadcast(msg models.Message) {\n\ts.hmu.RLock()\n\n\tfor _, receiver := range s.hub {\n\t\tif err := receiver.Conn.WriteJSON(msg); err != nil {\n\t\t\ts.logger.Errorf(\"error sending message: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t}\n\n\ts.history = append(s.history, msg)\n\tif err := s.historyRepo.Add(msg); err != nil {\n\t\ts.logger.Errorf(\"error writing history to db: %v\", err)\n\t}\n\n\ts.hmu.RUnlock()\n}", "func (s *Sender) sendMessage(ctx context.Context, req *tg.MessagesSendMessageRequest) (tg.UpdatesClass, error) {\n\tif req.RandomID == 0 {\n\t\tid, err := crypto.RandInt64(s.rand)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"generate random_id\")\n\t\t}\n\t\treq.RandomID = id\n\t}\n\n\treturn s.raw.MessagesSendMessage(ctx, req)\n}", "func (wechatPush *WechatPush) WriteMsg(when time.Time, msg string, level int) error {\n\tif level > wechatPush.Level {\n\t\treturn nil\n\t}\n\n\tdata := InitPushData(msg)\n\n\tfor _, id := range wechatPush.WechatIds {\n\t\terr := wechatPush.message.Push(id, \"\", wechatPush.TmpId, data)\n\t\tfmt.Printf(\"push data to user:%v, error:%v\\n\", id, err)\n\t}\n\treturn nil\n}", "func (monitor *Monitor) SendMetric(delay int64) error {\n\tif monitor.MetricID == 0 {\n\t\treturn nil\n\t}\n\n\tjsonBytes, _ := json.Marshal(&map[string]interface{}{\n\t\t\"value\": delay,\n\t})\n\n\tresp, _, err := monitor.config.makeRequest(\"POST\", \"/metrics/\"+strconv.Itoa(monitor.MetricID)+\"/points\", jsonBytes)\n\tif err != nil || resp.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"Could not log data point!\\n%v\\n\", err)\n\t}\n\n\treturn nil\n}", "func (coord *Coordinator) SendMsg(source, counterparty *TestChain, counterpartyClientID string, msg sdk.Msg) error {\n\treturn coord.SendMsgs(source, counterparty, counterpartyClientID, []sdk.Msg{msg})\n}", "func (syn *kubeSyncer) sendUpdates(kvps []model.KVPair) {\n\tupdates := syn.convertKVPairsToUpdates(kvps)\n\n\t// Send to the callback and update the tracker.\n\tsyn.callbacks.OnUpdates(updates)\n\tsyn.updateTracker(updates)\n}", "func (d delegate) NotifyMsg(data []byte) {}", "func (kv *DisKV) sendUpdates(servers []string, msg map[string]string, shards []int,\n\tclients map[int64]int, view int, gid int64) {\n\targs := &UpdateArgs{View: view, Data: msg, Shards: shards, From: kv.gid, Clients: clients}\n\n\tfor {\n\t\tfor _, srv := range servers {\n\t\t\tvar reply UpdateReply\n\t\t\tok := call(srv, \"DisKV.Update\", args, &reply)\n\t\t\tif ok && reply.Err == OK {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n}", "func (*RegDBService) UpdateMsg(msg string, regID int) error {\n\terr := rdb.Table(\"ownerReg\").Where(\"id=?\", regID).Update(\"msg\", msg).Error\n\treturn err\n}", "func sendMetricToStats(metric Metric) {\n\n\trand.Seed(time.Now().UnixNano())\n\tvar metricValue int\n\tswitch metric.metricType {\n\tcase \"c\":\n\t\tmetricValue = 1\n\tcase \"g\":\n\t\tmetricValue = rand.Intn(100)\n\tcase \"ms\":\n\t\tmetricValue = rand.Intn(1000)\n\tcase \"s\":\n\t\tmetricValue = rand.Intn(100)\n\t}\n\tstringValue := fmt.Sprintf(\"%s:%d|%s\", metric.key, metricValue, metric.metricType)\n\t// Send to the designated connection\n\tswitch metric.connectionType {\n\tcase ConnectionTypeTcp:\n\t\tc, err := net.Dial(\"tcp\", fmt.Sprintf(\"%s:%d\", *statsHost, *statsPortTcp))\n\t\tconnectionCountTcp++\n\t\tif err == nil {\n\t\t\tc.Write([]byte(stringValue + \"\\n\"))\n\t\t\tlogSentMetric(stringValue)\n\t\t\tdefer c.Close()\n\t\t} else {\n\t\t\tconnectionErrorTcp++\n\t\t\treturn\n\t\t}\n\tcase ConnectionTypeTcpPool:\n\t\tc, err := tcpPool.GetConnection(logger)\n\t\tconnectionCountTcpPool++\n\t\tif err == nil {\n\t\t\t_, err := c.Write([]byte(stringValue + \"\\n\"))\n\t\t\tlogSentMetric(stringValue)\n\t\t\tif err != nil {\n\t\t\t\tconnectionErrorTcpPool++\n\t\t\t\tdefer tcpPool.ReleaseConnection(c, true, logger)\n\t\t\t} else {\n\t\t\t\tdefer tcpPool.ReleaseConnection(c, false, logger)\n\t\t\t}\n\t\t} else {\n\t\t\tconnectionErrorTcp++\n\t\t\treturn\n\t\t}\n\tcase ConnectionTypeUdp:\n\t\tc, err := net.Dial(\"udp\", fmt.Sprintf(\"%s:%d\", *statsHost, *statsPortUdp))\n\t\tconnectionCountUdp++\n\t\tif err == nil {\n\t\t\tc.Write([]byte(stringValue))\n\t\t\tlogSentMetric(stringValue)\n\t\t\tdefer c.Close()\n\t\t} else {\n\t\t\tconnectionErrorUdp++\n\t\t\treturn\n\t\t}\n\tcase ConnectionTypeUnix:\n\t\tc, err := net.Dial(\"unix\", *statsSock)\n\t\tconnectionCountUnix++\n\t\tif err == nil {\n\t\t\tc.Write([]byte(stringValue))\n\t\t\tlogSentMetric(stringValue)\n\t\t\tdefer c.Close()\n\t\t} else {\n\t\t\tconnectionErrorUnix++\n\t\t\treturn\n\t\t}\n\tcase ConnectionTypeUnixPool:\n\t\tc, err := unixPool.GetConnection(logger)\n\t\tconnectionCountUnixPool++\n\t\tif err == nil {\n\t\t\t_, err := c.Write([]byte(stringValue + \"\\n\"))\n\t\t\tlogSentMetric(stringValue)\n\t\t\tif err != nil {\n\t\t\t\tconnectionErrorUnixPool++\n\t\t\t\tdefer unixPool.ReleaseConnection(c, true, logger)\n\t\t\t} else {\n\t\t\t\tdefer unixPool.ReleaseConnection(c, false, logger)\n\t\t\t}\n\t\t} else {\n\t\t\tconnectionErrorUnixPool++\n\t\t\treturn\n\t\t}\n\t}\n}", "func publishUpdate(msg string) {\n\thub.broadcast <- []byte(msg)\n}", "func (s *session) send(buf []byte) error {\n\tselect {\n\tcase s.clientActivityC <- true:\n\tdefault:\n\t}\n\n\t_, err := s.backendConn.Write(buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.scheduler.IncrementTx(*s.backend, uint(len(buf)))\n\n\tif s.maxRequests > 0 {\n\t\tif atomic.AddUint64(&s._sentRequests, 1) >= s.maxRequests {\n\t\t\ts.stop()\n\t\t}\n\t}\n\n\treturn nil\n}", "func (s *swarmImpl) SendMessage(req SendMessageReq) {\n\ts.sendMsgRequests <- req\n}", "func (hm *HM) send(dest, msgID uint8, msg interface{}) {\n\t// First encode the message\n\tvar buf bytes.Buffer\n\te := gob.NewEncoder(&buf)\n\tif err := e.Encode(msg); err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar mbuf []byte\n\tif hm.vecLog != nil {\n\t\tevent := \"Tx \" + msgName[msgID]\n\t\ttmp := make([]byte, buf.Len())\n\t\tbuf.Read(tmp[:])\n\t\tgobuf := hm.vecLog.PrepareSend(event, tmp)\n\t\tmbuf = make([]byte, 3+len(gobuf))\n\t\tmbuf[0], mbuf[1], mbuf[2] = dest, hm.pid, msgID\n\t\tcopy(mbuf[3:], gobuf)\n\t} else {\n\t\tmbuf = make([]byte, 3+buf.Len())\n\t\tmbuf[0], mbuf[1], mbuf[2] = dest, hm.pid, msgID\n\t\tbuf.Read(mbuf[3:])\n\t}\n\t// Prepend the dest id, msgType, and src id to the encoded gob\n\thm.LogMsg(\"Send[%d]:Msg[%s],%v\", dest, msgName[msgID], msg)\n\thm.txChan <- mbuf\n}", "func (s *ScrubWriter) WriteMsg(m *dns.Msg) error {\n\tstate := Request{Req: s.req, W: s.ResponseWriter}\n\tstate.SizeAndDo(m)\n\tstate.Scrub(m)\n\treturn s.ResponseWriter.WriteMsg(m)\n}", "func (d *destination) sendMetrics(ctx context.Context) {\nsendLoop:\n\tfor {\n\t\tselect {\n\t\tcase request := <-d.sendChannel:\n\n\t\t\t// Only collect timing metrics once every `statsInterval`.\n\t\t\tshouldCalculateMetrics := false\n\t\t\tselect {\n\t\t\tcase <-d.statsTicker.C:\n\t\t\t\tshouldCalculateMetrics = true\n\t\t\tdefault:\n\t\t\t\t// Do nothing.\n\t\t\t}\n\n\t\t\tvar bufferTime time.Time\n\t\t\tif shouldCalculateMetrics {\n\t\t\t\tbufferTime = time.Now()\n\t\t\t}\n\t\t\terr := d.client.Send(request.Metric)\n\t\t\tvar sendTime time.Time\n\t\t\tif shouldCalculateMetrics {\n\t\t\t\tsendTime = time.Now()\n\t\t\t}\n\t\t\tif err == io.EOF {\n\t\t\t\td.logger.WithError(err).Debug(\"failed to forward metric\")\n\t\t\t\td.statsd.Count(\n\t\t\t\t\t\"veneur_proxy.forward.metrics_count\", 1,\n\t\t\t\t\t[]string{\"error:eof\"}, 1.0)\n\t\t\t\tbreak sendLoop\n\t\t\t} else if err != nil {\n\t\t\t\td.logger.WithError(err).Debug(\"failed to forward metric\")\n\t\t\t\td.statsd.Count(\n\t\t\t\t\t\"veneur_proxy.forward.metrics_count\", 1,\n\t\t\t\t\t[]string{\"error:forward\"}, 1.0)\n\t\t\t} else {\n\t\t\t\td.statsd.Count(\n\t\t\t\t\t\"veneur_proxy.forward.metrics_count\", 1,\n\t\t\t\t\t[]string{\"error:false\"}, 1.0)\n\t\t\t}\n\n\t\t\tif shouldCalculateMetrics {\n\t\t\t\tdestinationTag := \"destination:\" + d.address\n\t\t\t\td.statsd.Gauge(\n\t\t\t\t\t\"veneur_proxy.forward.buffer_size\",\n\t\t\t\t\tfloat64(len(d.sendChannel)), []string{destinationTag}, 1.0)\n\t\t\t\td.statsd.Gauge(\n\t\t\t\t\t\"veneur_proxy.forward.buffer_latency_ns\",\n\t\t\t\t\tfloat64(bufferTime.Sub(request.Timestamp).Nanoseconds()),\n\t\t\t\t\t[]string{destinationTag}, 1.0)\n\t\t\t\td.statsd.Gauge(\n\t\t\t\t\t\"veneur_proxy.forward.send_latency_ns\",\n\t\t\t\t\tfloat64(sendTime.Sub(request.Timestamp).Nanoseconds()),\n\t\t\t\t\t[]string{destinationTag}, 1.0)\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\tbreak sendLoop\n\t\t}\n\t}\n\n\t// Remove the destination from the consistent hash such that no more metrics\n\t// can be written to the channel. This call blocks until the destination\n\t// has been successfully removed.\n\td.destinationHash.RemoveDestination(d.address)\n\n\t// Signal that this destination should no longer be written to.\n\tclose(d.closedChannel)\n\n\td.statsTicker.Stop()\n\n\terr := d.client.CloseSend()\n\tif err != nil {\n\t\td.logger.WithError(err).Error(\"failed to close stream\")\n\t}\n\terr = d.connection.Close()\n\tif err != nil {\n\t\td.logger.WithError(err).Error(\"failed to close connection\")\n\t}\n\n\td.statsd.Count(\n\t\t\"veneur_proxy.forward.metrics_count\", int64(len(d.sendChannel)),\n\t\t[]string{\"error:dropped\"}, 1.0)\n\n\t// Notify the hash that resources for this connection have been cleaned up\n\t// so it can block until all connections are done cleaning up on exit.\n\td.destinationHash.ConnectionClosed()\n}", "func (s *InMemorySender) Send(msg message.Composer) {\n\tif !s.Level().ShouldLog(msg) {\n\t\treturn\n\t}\n\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tif len(s.buffer) < cap(s.buffer) {\n\t\ts.buffer = append(s.buffer, msg)\n\t} else {\n\t\ts.buffer[s.head] = msg\n\t}\n\ts.head = (s.head + 1) % cap(s.buffer)\n\n\ts.totalBytesSent += int64(len(msg.String()))\n}", "func (l *loggingServerStream) SendMsg(m interface{}) error {\n\terr := l.ServerStream.SendMsg(m)\n\tif l.li.LogStreamSendMsg {\n\t\tlogProtoMessageAsJSON(l.entry, m, status.Code(err), \"value\", \"StreamSend\")\n\t}\n\treturn err\n}", "func handlerMsg(msg []byte) {\n\tchats <- string(msg)\n}", "func sendmsg(s int, msg *unix.Msghdr, flags int) (n int, err error)", "func SendMsg(summary, body string) (id uint32, err error) {\n\treturn note.SendMsg(summary, body)\n}", "func SendMessage(conn net.Conn, message msg.FromServer) {\n\tlog.Printf(\"SendMessage() to addr: %v Worker:%v\\n\", conn.RemoteAddr().String(), message.DstWorker)\n\toutBuf := Logger.PrepareSend(fmt.Sprintf(\"Sending-%v-Message\", msg.TypeStr(message.Type)), message)\n\t// log.Printf(\"%v\\n\", outBuf)\n\tvar msgSize uint16\n\tmsgSize = uint16(len(outBuf))\n\tsizeBuf := make([]byte, 2)\n\tbinary.LittleEndian.PutUint16(sizeBuf, uint16(msgSize))\n\toutBuf = append(sizeBuf, outBuf...)\n\tsize, err := conn.Write(outBuf)\n\tcheckErr(err)\n\tif size != len(outBuf) {\n\t\tlog.Fatal(\"size of message out != size written\")\n\t}\n}", "func (sender *Sess) SendMessage(logEvent logevent.LogEvent) error {\n\tif sender.hecClient == nil {\n\t\treturn errors.New(\"SendMessage() called before OpenSvc()\")\n\t}\n\thecEvents := []*hec.Event{\n\t\tsender.formatLogEvent(logEvent),\n\t}\n\tsender.tracePretty(\"TRACE_SENDHEC time =\",\n\t\tlogEvent.Content.Time.UTC().Format(time.RFC3339),\n\t\t\" hecEvents =\", hecEvents)\n\terr := sender.hecClient.WriteBatch(hecEvents)\n\treturn err\n}", "func (nf *NetFlowV5Target) SendStats(stats flow.Stats) {\n}", "func SendMsg(message string) {\n\tbotMutex.Lock()\n\tdefer botMutex.Unlock()\n\tif !messageReceived {\n\t\tlog.Println(\n\t\t\t\"Write a message to the bot for specifying notifiable chat ID\",\n\t\t)\n\t\treturn\n\t}\n\tmsg := tgbotapi.NewMessage(notifiableChatID, message)\n\t_, err := bot.Send(msg)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func (m *MajsoulChannel) sendMsg(stop chan struct{}) {\n\tinterrupt := make(chan os.Signal, 1)\n\tsignal.Notify(interrupt, os.Interrupt)\n\n\tfor {\n\t\tselect {\n\t\tcase <-interrupt:\n\t\t\treturn\n\t\tcase <-stop:\n\t\t\treturn\n\t\tcase out := <-m.outgoing:\n\t\t\terr := m.Connection.WriteMessage(out.MsgType, out.Msg)\n\t\t\tif err != nil {\n\t\t\t\tm.Close(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tswitch out.MsgType {\n\t\t\tcase websocket.PingMessage:\n\t\t\t\tm.timeLastPingSent = time.Now()\n\t\t\t\tlog.Println(\"Ping sent\")\n\t\t\tcase websocket.PongMessage:\n\t\t\t\tlog.Println(\"Pong sent\")\n\t\t\tcase websocket.CloseMessage:\n\t\t\t\tlog.Println(\"Close sent\")\n\t\t\tdefault:\n\t\t\t\tlog.Println(\"Message sent: \", out.Msg)\n\t\t\t}\n\t\t}\n\t}\n}", "func (w *dataWriter) send(msg *fnpb.Elements) error {\n\trecordStreamSend(msg)\n\tif err := w.ch.client.Send(msg); err != nil {\n\t\tif err == io.EOF {\n\t\t\tlog.Warnf(context.TODO(), \"dataWriter[%v;%v] EOF on send; fetching real error\", w.id, w.ch.id)\n\t\t\terr = nil\n\t\t\tfor err == nil {\n\t\t\t\t// Per GRPC stream documentation, if there's an EOF, we must call Recv\n\t\t\t\t// until a non-nil error is returned, to ensure resources are cleaned up.\n\t\t\t\t// https://godoc.org/google.golang.org/grpc#ClientConn.NewStream\n\t\t\t\t_, err = w.ch.client.Recv()\n\t\t\t}\n\t\t}\n\t\tlog.Warnf(context.TODO(), \"dataWriter[%v;%v] error on send: %v\", w.id, w.ch.id, err)\n\t\tw.ch.terminateStreamOnError(err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c messageHandler) send(m interface{}) {\n\n\t// encodes a struct as req by making sure that\n\t// all struct fields start with a lowercase character, as expected by\n\t// the Scrolls server.\n\tvar encode func(reflect.Value) req\n\tencode = func(v reflect.Value) req {\n\t\tout := req{}\n\n\t\tt := v.Type()\n\t\tfor i := 0; i < v.NumField(); i++ {\n\t\t\tval := v.Field(i)\n\n\t\t\tname := t.Field(i).Name\n\t\t\tname = strings.ToLower(name[:1]) + name[1:]\n\n\t\t\tswitch val.Kind() {\n\t\t\tcase reflect.String:\n\t\t\t\tout[name] = val.String()\n\t\t\tcase reflect.Int:\n\t\t\t\tout[name] = strconv.Itoa(int(val.Int()))\n\t\t\tcase reflect.Struct:\n\t\t\t\tout[name] = encode(val)\n\t\t\tcase reflect.Slice:\n\t\t\t\tn := val.Len()\n\t\t\t\tarr := make([]interface{}, n)\n\t\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\t\tarr[i] = encode(val.Index(i))\n\t\t\t\t}\n\t\t\t\tout[name] = arr\n\t\t\tdefault:\n\t\t\t\tlog.Fatalln(\"send: struct contains unhandled field type\", val.Kind())\n\t\t\t}\n\t\t}\n\n\t\treturn out\n\t}\n\n\treq := encode(reflect.ValueOf(m))\n\treq[\"msg\"] = reflect.TypeOf(m).Name()[1:]\n\n\tc.encoder.Encode(req)\n}", "func SendMetrics(ws *websocket.Conn, userID string, tasks map[string]demand.Task) error {\n\tvar err error = nil\n\tvar index int = 0\n\n\tmetrics := metrics{\n\t\tTasks: make([]taskMetrics, len(tasks)),\n\t\tCreatedAt: time.Now().Unix(),\n\t}\n\n\tfor name, task := range tasks {\n\t\tmetrics.Tasks[index] = taskMetrics{App: name, RunningCount: task.Running, PendingCount: task.Requested}\n\t\tindex++\n\t}\n\n\tpayload := metricsPayload{\n\t\tUser: userID,\n\t\tMetrics: metrics,\n\t}\n\n\tb, err := json.Marshal(payload)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to encode API json. %v\", err)\n\t}\n\n\t_, err = ws.Write(b)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to send metrics: %v\", err)\n\t}\n\n\treturn err\n}", "func writeStatMessage(payload string, currentMessage *bytes.Buffer) *bytes.Buffer {\n\t// 11 -event type - 7 - 5 \"Stat\" 20\n\t// 13 -content-type -7 -8 \"text/xml\" 25\n\t// 13 -message-type -7 5 \"event\" 22\n\t// This is predefined from AMZ protocol found here:\n\t// https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectSELECTContent.html\n\theaderLen := len(statHeaders)\n\n\tcurrentMessage.Write(writePayloadSize(len(payload), headerLen))\n\n\tcurrentMessage.Write(writeHeaderSize(headerLen))\n\n\tcurrentMessage.Write(writeCRC(currentMessage.Bytes()))\n\n\tcurrentMessage.Write(statHeaders)\n\n\t// This part is where the payload is written, this will be only one row, since\n\t// we're sending one message at a types\n\tcurrentMessage.Write(writePayload(payload))\n\n\t// Now we do a CRC check on the entire messages\n\tcurrentMessage.Write(writeCRC(currentMessage.Bytes()))\n\treturn currentMessage\n\n}", "func (s *server)TransMsg(ctx context.Context, msgSend *pb.MessageSend)(*pb.MessageRet, error){\n\tstart:=time.Now().UnixNano()\n\t//log.Println(\"node:\",s.NodeID,\":Reciving from node:\",msgSend.NodeID)\n\t//if msgSend.Type == 0{\n\t\t//log.Println(msgSend.Type,msgSend.Term,msgSend.LogIndex,msgSend.LogTerm,msgSend.CommitIndex,msgSend.NodeID)\n\t//}\n\t//log.Println(s.simple_raftlog_length,s.CommitIndex,s.currentTerm,s.votes,s.lastApplied,s.votedFor)\n\tvar msgRet pb.MessageRet\n\t/*\n\tResetClock()\n\tmsgRet.Success = 1\n\tmsgRet.Term = msgSend.Term\n\t*/\n\tswitch msgSend.Type{\n\t\tcase 0:msgRet.Type = 0\n\t\tcase 1:msgRet.Type = 1\n\t\tcase 2:msgRet.Type = 2\n\t}\n\tif msgSend.Term > s.currentTerm {\n\t\t//log.Println(\"i am out-of-date\")\n\t\tserverLock.Lock()\n\t\ts.currentTerm = msgSend.Term\n\t\tserverLock.Unlock()\n\t\tResetClock()\n\t\ts.BecomeFollower()\n\t}\n\tmsgRet.Term = s.currentTerm\n\tswitch msgSend.Type {\n\t\tcase 1://voteRPC\n\t\t\tserverLock.RLock()\n\t\t\tif msgSend.Term < s.currentTerm {\n\t\t\t\tserverLock.RUnlock()\n\t\t\t\t//log.Println(\"node:\",s.NodeID,\"lower term, reject\",msgSend.NodeID)\n\t\t\t\tmsgRet.Success = 0\n\t\t\t}else {\n\t\t\t\tif s.votedFor == 0 || s.votedFor == msgSend.NodeID{\n\t\t\t\t\tserverLock.RUnlock()\n\t\t\t\t\tif s.IsUpToDate(msgSend.LogTerm,msgSend.LogIndex){\n\t\t\t\t\t\tserverLock.Lock()\n\t\t\t\t\t\ts.votedFor = msgSend.NodeID\n\t\t\t\t\t\tserverLock.Unlock()\n\t\t\t\t\t\tmsgRet.Success = 1\n\t\t\t\t\t}else{\n\t\t\t\t\t\t//log.Println(\"node:\",s.NodeID,\"out-of-date, reject\",msgSend.NodeID)\n\t\t\t\t\t\tmsgRet.Success = 0\n\t\t\t\t\t}\n\t\t\t\t}else {\n\t\t\t\t\tserverLock.RUnlock()\n\t\t\t\t\t//log.Println(\"node:\",s.NodeID,\"have votedFor other, reject\",msgSend.NodeID)\n\t\t\t\t\tmsgRet.Success = 0\n\t\t\t\t}\n\t\t\t}\n\t\tdefault://heartbeat or appendEntry RPC\n\t\t\tif msgSend.Term < s.currentTerm {\n\t\t\t\t//log.Println(\"out-of-date,reject\")\n\t\t\t\tmsgRet.Success = 0\n\t\t\t}else {\n\t\t\t\tResetClock()\n\t\t\t\t//if msgSend.Type!=2{\n\t\t\t\t\t//log.Println(\"oh it is here:111\")\n\t\t\t\t//}\n\t\t\t\ts.CheckSendIndex(msgSend.CommitIndex)\n\t\t\t\t//log.Println(msgSend.CommitIndex,s.CommitIndex,s.simple_raftlog_length)\n\t\t\t\ts.leaderId = msgSend.NodeID\n\t\t\t\t//log.Println(\"lock check\")\n\t\t\t\tlogLock.RLock()\n\t\t\t\t//log.Println(\"msg check\")\n\t\t\t\tif s.simple_raftlog_length < msgSend.LogIndex {\n\t\t\t\t\t//didn't exist a Entry in the previous one\n\t\t\t\t\t//log.Println(\"too advanced\")\n\t\t\t\t\tlogLock.RUnlock()\n\t\t\t\t\tmsgRet.Success = 0\n\t\t\t\t}else if s.simple_raftlog_length >= msgSend.LogIndex && \n\t\t\t\tmsgSend.LogTerm != s.simple_raftlog_Term[msgSend.LogIndex]{\n\t\t\t\t\t//there is a conflict,delete all entries in Index and after it,\n\t\t\t\t\t//and we can't append this entry\n\t\t\t\t\t//log.Println(\"conflict,reject\")\n\t\t\t\t\tlogLock.RUnlock()\n\t\t\t\t\tlogLock.Lock()\n\t\t\t\t\ts.simple_raftlog_length = msgSend.LogIndex - 1\n\t\t\t\t\tlogLock.Unlock()\n\t\t\t\t\tmsgRet.Success = 0\n\t\t\t\t}else{\n\t\t\t\t\tif msgSend.Type!=2{\n\t\t\t\t\t\t//log.Println(\"oh it is here:133\")\n\t\t\t\t\t}\n\t\t\t\t\tmsgRet.Success = 1//actually mgsSend.LogIndex = msgSend.Entry.Index - 1\n\t\t\t\t\tif msgSend.Type != 2 &&\n\t\t\t\t\t s.simple_raftlog_length >= msgSend.Entry.Index &&\n\t\t\t\t\t msgSend.Entry.Term != s.simple_raftlog_Term[msgSend.Entry.Index]{\n\t\t\t\t\t\t//unmatch the new one,conflict delete all,then append\n\t\t\t\t\t\t//log.Println(\"unmatch the new one,delete and then append\")\n\t\t\t\t\t\tlogLock.RUnlock()\n\t\t\t\t\t\tlogLock.Lock()\n\t\t\t\t\t\ts.simple_raftlog_length = msgSend.LogIndex\n\t\t\t\t\t\tlogLock.Unlock()\n\t\t\t\t\t\ts.AddEntry(msgSend.Entry.Key,msgSend.Entry.Value,msgSend.Entry.Term)\n\t\t\t\t\t}else if msgSend.Type != 2 && \n\t\t\t\t\ts.simple_raftlog_length >= msgSend.Entry.Index && \n\t\t\t\t\tmsgSend.Entry.Term == s.simple_raftlog_Term[msgSend.Entry.Index]{\n\t\t\t\t\t\t//log.Println(\"not the new one,don't have to append\")\n\t\t\t\t\t\tlogLock.RUnlock()//not the new entry,and we don't need to delete\n\t\t\t\t\t}else if msgSend.Type != 2 && s.simple_raftlog_length == msgSend.LogIndex {\n\t\t\t\t\t\t//log.Println(\"yes it is a new one,append\")\n\t\t\t\t\t\tlogLock.RUnlock()//new one, and there is not conflict\n\t\t\t\t\t\ts.AddEntry(msgSend.Entry.Key,msgSend.Entry.Value,msgSend.Entry.Term)\n\t\t\t\t\t}else {//it is heartbeat\n\t\t\t\t\t\tif msgSend.Type != 2{\n\t\t\t\t\t\t\t//log.Println(\"bug:it is not heartbeat!!\")\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlogLock.RUnlock()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//if msgSend.Type!=2{\n\t\t\t\t//\tlog.Println(\"oh it is here:155\")\n\t\t\t\t//}\n\t\t\t}\n\t}\n\t//log.Println(\"Transback message\")\n\tend:=time.Now().UnixNano()\n\tTransMsgTime += (end - start)\n\treturn &msgRet,nil\n}", "func send_msg_per_time(number int, duration int) {\n\tsleep := time.Duration(int64(float64(duration) / float64(number) * 1000)) * time.Millisecond\n\n\tvar count = 0\n\n\tfor count < number {\n\t\tcount++\n\t\tfmt.Printf(\"Message number %s of %s (%s)\\n\", strconv.Itoa(count), strconv.Itoa(number), time.Now().Format(\"15:04:05.00000\"))\n\t\ttime.Sleep(sleep)\n\t}\n}", "func UpdateCount(w http.ResponseWriter, r *http.Request) {\n\n\tvar message Message\n\t_ = json.NewDecoder(r.Body).Decode(&message)\n\tid := message.ID\n\t\n\twrite(id, read(id) + message.Count) \n\n\t//broadcast in background routine\n\tgo func(msg Message) {\n broadcast(msg)\n\t}(message)\n\t\n\tfmt.Println(\"Broadcast done\")\n\tjson.NewEncoder(w).Encode(Message{ID : id, Count : read(id)})\n}", "func (r *Raft) send(serverId int, msg interface{}) {\n\tport := r.ClusterConfigObj.Servers[serverId].LogPort\n\t//added to reduce conns!\n\tconn := r.getSenderConn(serverId)\n\tif conn == nil {\n\t\tconn = r.makeConnection(port)\n\t\tif conn == nil {\n\t\t\treturn //returns cz it will retry making connection in next HB\n\t\t} else {\n\t\t\tr.setSenderConn(serverId, conn)\n\t\t}\n\t}\n\t//if conn has been closed by server(but still present in my map) or it crashed(so this conn is meaningless now),\n\t//encode will throw error, then set the conn map as nil for this\n\terr := r.EncodeInterface(conn, msg)\n\tif err != 0 {\n\t\tr.setSenderConn(serverId, nil)\n\t}\n\n}", "func sendMetricToStats(metric Metric) {\n\tvar payload string\n\tfmt.Printf(\"Sending metric %s.%s to stats on conn %d\\n\", metric.metricType, metric.key, metric.connectionType)\n\n\trand.Seed(time.Now().UnixNano())\n\n\tif metric.metricType == \"ms\" {\n\t\tpayload = fmt.Sprintf(\"%s:%d|ms\", metric.key, rand.Intn(1000))\n\t} else if metric.metricType == \"c\" {\n\t\tpayload = fmt.Sprintf(\"%s:1|c\", metric.key)\n\t} else {\n\t\tpayload = fmt.Sprintf(\"%s:%d|g\", metric.key, rand.Intn(100))\n\t}\n\n\t//sv := strconv.FormatFloat(float64(v), 'f', 6, 32)\n\t//payload := fmt.Sprintf(\"%s %s %s\", key, sv, t)\n\t//Trace.Printf(\"Payload: %v\", payload)\n\n\t// Send to the connection\n\tvar sendErr error\n\tswitch metric.connectionType {\n\tcase 1:\n\t\tc, err := net.Dial(\"tcp\", fmt.Sprintf(\"%s:%d\", *statsHost, *statsPortTcp))\n\t\tsendErr = err\n\t\tif err == nil {\n\t\t\tfmt.Fprintf(c, payload)\n\t\t\tdefer c.Close()\n\t\t}\n\tcase 2:\n\t\tc, err := net.Dial(\"udp\", fmt.Sprintf(\"%s:%d\", *statsHost, *statsPortUdp))\n\t\tsendErr = err\n\t\tif err == nil {\n\t\t\tfmt.Fprintf(c, payload)\n\t\t\tdefer c.Close()\n\t\t}\n\tcase 3:\n\t\tc, err := net.Dial(\"unix\", *statsSock)\n\t\tsendErr = err\n\t\tif err == nil {\n\t\t\tfmt.Fprintf(c, payload)\n\t\t\tdefer c.Close()\n\t\t}\n\t}\n\tif sendErr != nil {\n\t\tfmt.Println(\"Could not connect to remote stats server\")\n\t\treturn\n\t}\n\n}", "func (cl CellAdvisor) SendMessage(cmd byte, data string) (int, error) {\n\n\tsendingMsg := []byte{'C', cmd, 0x01, 0x01}\n\tif data != \"\" {\n\t\tsendingMsg = append(sendingMsg, []byte(data)...)\n\t}\n\t//append checksum\n\tsendingMsg = append(sendingMsg, getChecksum(sendingMsg))\n\tsendingMsg = maskingCommandCharacter(sendingMsg)\n\tsendingMsg = append(append([]byte{0x7f}, sendingMsg...), 0x7e)\n\n\tnum, err := cl.writer.Write(sendingMsg)\n\t//num, err := fmt.Fprintf(cl.writer, string(sendingMsg))\n\terr = cl.writer.Flush()\n\treturn num, err\n}", "func (s *Subscriber) writeMessage() {\n ticker := time.NewTicker(pingPeriod)\n defer func() {\n ticker.Stop()\n s.close()\n }()\n for {\n select {\n case m, ok := <- s.send:\n if !ok {\n s.write(websocket.CloseMessage, []byte{})\n return\n }\n if err := s.write(websocket.TextMessage, m); err != nil {\n return\n }\n case <-ticker.C:\n if err := s.write(websocket.PingMessage, []byte{}); err != nil {\n return\n }\n }\n }\n}", "func MetricsSendStats(Segment *Segment, Subnet *Subnet, Duration time.Duration) (err error) {\n\tif !o.MetricsEnabled {\n\t\treturn\n\t}\n\n\tTags := map[string]string{\n\t\t\"ServerID\": o.ServerID,\n\t\t\"SegmentId\": strconv.Itoa(Segment.Id),\n\t\t\"SegmentName\": Segment.Name,\n\t\t\"Subnet\": Subnet.NetStr,\n\t}\n\n\tFields := map[string]interface{}{\n\t\t\"Duration\": int(Duration.Nanoseconds() / 1000),\n\t\t\"LeasesTotal\": Subnet.Capacity(),\n\t\t\"LeasesActive\": Subnet.LeasesActive(),\n\t\t\"LeasesExpired\": Subnet.LeasesExpired(),\n\t}\n\n\tInfluxDB.SendMetric(&metrics.InfluxDBMetric{\n\t\tMeasurement: o.MetricsMeasurementStats,\n\t\tTimestamp: time.Now(),\n\n\t\tTags: Tags,\n\t\tFields: Fields,\n\t})\n\n\treturn\n}", "func (m *Manager) SendMessage(msgData []byte, to ...identity.ID) {\n\tmsg := &pb.Message{Data: msgData}\n\tm.send(marshal(msg), to...)\n}", "func (this_node *Node) SendMessage(recvID int, amount int) {\n\tthis_node.canProceed.RLock()\n\tthis_node.canRecv.Lock()\n\tif amount > this_node.balance {\n\t\tfmt.Printf(\"ERR_SEND\\n\")\n\t} else {\n\t\tthis_node.outChannels[recvID] <- amount\n\t\tthis_node.balance -= amount\n\t}\n\tthis_node.canRecv.Unlock()\n\tthis_node.canProceed.RUnlock()\n}", "func putMsg(conn net.Conn, msg string){\n\tfmt.Printf(\"C %s\\n\", msg)\n\tio.WriteString(conn, msg)//send our message\n}", "func (r *logReporter) Send(s model.SpanModel) {\n\tvar t []model.SpanModel\n\tt = append(t, s)\n\tif b, err := json.Marshal(t); err == nil {\n\t\tr.logger.Info(string(b))\n\t}\n}", "func (s *Sender) Send(msg *Message) (*Response, error) {\n\tif err := checkSender(s); err != nil {\n\t\treturn nil, err\n\t} else if err := checkMessage(msg); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Send the message for the first time.\n\tresp, err := s.SendNoRetry(msg)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if resp.Failure == 0 {\n\t\t//no errors\n\t\treturn resp, nil\n\t}\n\t\n\tif msg.RegistrationIDs == nil{\n\t\tif len(resp.Results) == 1{\n\t\t\tresp.Results[0].OldRegistrationID = msg.To\n\t\t}else{\n\t\t\treturn resp, errors.New(\"Incorrect result\")\n\t\t}\t\n\t}else{\n\t\tif len(resp.Results) == len(msg.RegistrationIDs){\n\t\t\tl := len(resp.Results)\n\t\t\tfor i := 0; i < l; i++{\n\t\t\t\tresp.Results[i].OldRegistrationID = msg.RegistrationIDs[i]\n\t\t\t}\n\t\t}else{\n\t\t\treturn resp, errors.New(\"Incorrect result\")\n\t\t}\n\t}\n\n\treturn resp, nil\n}", "func sendMessage(conn net.Conn, dest string, s string) {\n\tparts := strings.Split(s, \"\\n\")\n\tfor i := 0; i < len(parts); i++ {\n\t\tif parts[i] != \"\" {\n\t\t\tsend(conn, \"NOTICE %s :%s\", dest, parts[i])\n\t\t}\n\t}\n}", "func (t *Topic) Send(m *lobby.Message) error {\n\tcol := t.session.DB(\"\").C(colMessages)\n\n\tvar raw interface{}\n\n\tvalid, err := ValidateBytes(m.Value)\n\tif err == nil {\n\t\terr := json.Unmarshal(valid, &raw)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to unmarshal json\")\n\t\t}\n\t} else {\n\t\traw = m.Value\n\t}\n\n\terr = col.Insert(&message{Group: m.Group, Topic: t.name, Value: raw})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to insert of update\")\n\t}\n\n\treturn nil\n}", "func (e *Engine) SendMessage(msg *Message) error {\n\treturn e.messages.Send(msg)\n}", "func (_m *ITaskActions) SendUpdate() {\n\t_m.Called()\n}", "func (c *Connection) SendMsg(msg *Message) error {\n\tc.SetWriteDeadline(CalDeadline(10))\n\tencoder := gob.NewEncoder(c)\n\terr := encoder.Encode(&msg)\n\treturn err\n}", "func sendMessageToSlavesOnUpdate(totalOrderListChan <-chan def.Elevators, mutex *sync.Mutex) {\n\n\tfor {\n\t\tselect {\n\t\tcase totalOrderList := <-totalOrderListChan:\n\t\t\tif len(totalOrderList.OrderMap) != 0 {\n\t\t\t\tmsg := def.MSG_to_slave{Elevators: totalOrderList}\n\t\t\t\tfmt.Println(\"Message sent to slave:\", msg)\n\t\t\t\tnetwork.SendToSlave(msg, mutex)\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n}", "func (c *conn) WriteMsg(data ...[]byte) (int, error) {\n\treturn c.base.WriteMsg(data...)\n}", "func updateMetric(msg events.PubSubMessage) {\n\tswitch msg.Kind {\n\tcase announcements.NamespaceAdded:\n\t\tmetricsstore.DefaultMetricsStore.MonitoredNamespaceCounter.Inc()\n\tcase announcements.NamespaceDeleted:\n\t\tmetricsstore.DefaultMetricsStore.MonitoredNamespaceCounter.Dec()\n\t}\n}", "func sendMsg(useBase bool, baseCmd byte, cmd byte, msg proto.Message, conn *UniqueConnection) {\n\tdata, err := proto.Marshal(msg)\n\tif err != nil {\n\t\tTimeEncodedPrintln(\"marshaling error: \", err)\n\t\tlog.Fatal(\"marshaling error: \", err)\n\t}\n\tlength := int32(len(data)) + 1\n\n\tif useBase {\n\t\tlength = length + 1\n\t}\n\n\tif BYPASS_CONNECTION_SERVER {\n\t\tlength = length + 8\n\t}\n\n\tif DEBUG_SENDING_MESSAGE {\n\t\tTimeEncodedPrintln(\"sending message base length: \", length, \" command / command / message: \", baseCmd, cmd, msg)\n\t}\n\n\tbuf := new(bytes.Buffer)\n\n\tbinary.Write(buf, binary.LittleEndian, length)\n\tif useBase {\n\t\tbinary.Write(buf, binary.LittleEndian, baseCmd)\n\t}\n\n\tbinary.Write(buf, binary.LittleEndian, cmd)\n\tif BYPASS_CONNECTION_SERVER {\n\t\tif DEBUG_SENDING_MESSAGE {\n\t\t\tTimeEncodedPrintln(\"Send extra 8 bytes: \", conn.Identifier)\n\t\t}\n\t\tbinary.Write(buf, binary.LittleEndian, int64(conn.Identifier))\n\t}\n\tbuf.Write(data)\n\tn, err := conn.Connection.Write(buf.Bytes())\n\tif DEBUG_SENDING_MESSAGE {\n\t\tfmt.Println(\"Sent\", n, \"bytes\", \"encounter error:\", err)\n\t}\n}", "func (s *session) send(msg json.RawMessage) {\n\ts.conn.Send(msg)\n}", "func (mc *MsgCache) WriteMsg(msg *Msg) bool {\n\n\tif mc.cache == nil {\n\t\tmc.cache = make([]*Msg, 0, 8)\n\t}\n\n\tmin := sort.Search(len(mc.cache), func(mid int) bool {\n\t\treturn mc.comparator(msg.key, mc.cache[mid].key) <= 0\n\t})\n\t//if cache contain the key. replace it\n\tif min != len(mc.cache) && mc.comparator(msg.key, mc.cache[min].key) == 0 {\n\t\tmc.cache[min].value = msg.value\n\t\tmc.cache[min].msgType = msg.msgType\n\t\tmc.size += (msg.Size() - mc.cache[min].Size())\n\t\treturn false\n\t} else {\n\t\t//insert value to slice\n\t\tmc.cache = append(mc.cache, nil)\n\t\tcopy(mc.cache[min+1:], mc.cache[min:])\n\t\tmc.cache[min] = msg\n\t\tmc.size += msg.Size()\n\t\treturn true\n\t}\n}", "func pushMetrics(producer *sarama.Producer, mode string) {\n\n\t// The list of metrics we want to filter out of the total stats dump from haproxy\n\twantedMetrics := []string{ \"Scur\", \"Qcur\",\"Smax\",\"Slim\",\"Weight\",\"Qtime\",\"Ctime\",\"Rtime\",\"Ttime\",\"Req_rate\",\"Req_rate_max\",\"Req_tot\",\"Rate\",\"Rate_lim\",\"Rate_max\" }\n\n\t// get metrics every second, for ever.\n\tfor {\n\n\t\t\tstats, _ := GetStats(\"all\")\n\t\t localTime := int64(time.Now().Unix())\n\n\n\t\t// for each proxy in the stats dump, pick out the wanted metrics, parse them and send 'm to Kafka\n\t\t\tfor _,proxy := range stats {\n\n\t\t\t\t// filter out the metrics for haproxy's own stats page\n\t\t\t\tif (proxy.Pxname != \"stats\") {\n\n\t\t\t\t\t// loop over all wanted metrics for the current proxy\n\t\t\t\t\tfor _,metric := range wantedMetrics {\n\n\t\t\t\t\t\tfullMetricName := proxy.Pxname + \".\" + strings.ToLower(proxy.Svname) + \".\" + strings.ToLower(metric)\n\t\t\t\t\t\tfield := reflect.ValueOf(proxy).FieldByName(metric).String()\n\t\t\t\t\t\tif (field != \"\") {\n\n\t\t\t\t\t\t\tmetricValue,_ := strconv.Atoi(field)\n\n\t\t\t\t\t\t\tmetricObj := Metric{fullMetricName, metricValue, localTime}\n\t\t\t\t\t\t\tjsonObj, _ := json.MarshalIndent(metricObj, \"\", \" \")\n\n\t\t\t\t\t\t\terr := producer.SendMessage(mode+\".\"+\"all\", sarama.StringEncoder(\"lbmetrics\"), sarama.StringEncoder(jsonObj))\n\t\t\t\t\t\t\tif err != nil {\n\n\t\t\t\t\t\t\t\tlog.Error(\"Error sending message to Kafka \" + err.Error())\n\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tlog.Debug(\"Successfully sent message to Kafka on topic: \" + mode + \".\" + \"all\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\ttime.Sleep(3000 * time.Millisecond)\n\t}\n}", "func (c clientImpl) Send(msgs ...Message) (int, error) {\r\n\tvar k int\r\n\tvar msg Message\r\n\tfor k, msg = range msgs {\r\n\t\terr := c.Write(msg)\r\n\t\tif err != nil {\r\n\t\t\treturn k - 1, err\r\n\t\t}\r\n\t}\r\n\treturn k, nil\r\n}", "func (f *fakeDiskUpdateWatchServer) RecvMsg(m interface{}) error { return nil }", "func (m *Metrics) SendFailed(msg message.OutboundMessage) {\n\top := msg.Op()\n\tmsgMetrics := m.MessageMetrics[op]\n\tif msgMetrics == nil {\n\t\tm.Log.Error(\n\t\t\t\"unknown message failed to be sent\",\n\t\t\tzap.Stringer(\"messageOp\", op),\n\t\t)\n\t\treturn\n\t}\n\tmsgMetrics.NumFailed.Inc()\n}", "func sendHeartBeat(members map[string]Entry, selfName string) {\n\tm := createMessage(\"gossip\", members)\n\tb, err := json.Marshal(m)\n\tkMembers := pickAdresses(members, K, selfName)\n\tlogError(err)\n\tfor i := range kMembers {\n\t\trecipientId := kMembers[i]\n\n\t\t//split to timestamp and ip address\n\t\ta := strings.Split(recipientId, \"#\")\n\t\t//memberIp = ip\n\t\trecipientIp := a[1]\n\t\t//retrieve a UDPaddr\n\t\trecipientAddr, err := net.ResolveUDPAddr(\"udp\", recipientIp+\":\"+PORT)\n\t\tlogError(err)\n\t\tconn, err := net.DialUDP(\"udp\", nil, recipientAddr)\n\t\tif !logError(err) {\n\t\t\tconn.Write(b)\n\t\t\tconn.Close()\n\t\t}\n\t}\n}", "func (i *Info) SendMsg(msg Models.Message, dest string) error {\n\tconnOut, err := net.DialTimeout(\"tcp\", i.IP+\":\"+dest, time.Duration(10)*time.Second)\n\tif err != nil {\n\t\tif _, ok := err.(net.Error); ok {\n\t\t\tfmt.Printf(\"Couldn't send go to %s:%s \\n\", i.IP, dest)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := json.NewEncoder(connOut).Encode(&msg); err != nil {\n\t\tfmt.Printf(\"Couldn't enncode message %v \\n\", msg)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *ClientStream) SendMsg(m interface{}) error {\n\treturn s.writeMessage(m, false)\n}", "func (h *Handler) handleMsg(msg message.InboundMessage) error {\n\tstartTime := h.clock.Time()\n\n\tisPeriodic := isPeriodic(msg)\n\tif isPeriodic {\n\t\th.ctx.Log.Verbo(\"Forwarding message to consensus: %s\", msg)\n\t} else {\n\t\th.ctx.Log.Debug(\"Forwarding message to consensus: %s\", msg)\n\t}\n\n\th.ctx.Lock.Lock()\n\tdefer h.ctx.Lock.Unlock()\n\n\tvar (\n\t\terr error\n\t\top = msg.Op()\n\t)\n\tswitch op {\n\tcase message.Notify:\n\t\tvmMsg := msg.Get(message.VMMessage).(uint32)\n\t\terr = h.engine.Notify(common.Message(vmMsg))\n\tcase message.GossipRequest:\n\t\terr = h.engine.Gossip()\n\tcase message.Timeout:\n\t\terr = h.engine.Timeout()\n\tdefault:\n\t\terr = h.handleConsensusMsg(msg)\n\t}\n\n\tendTime := h.clock.Time()\n\t// If the message was caused by another node, track their CPU time.\n\tif op != message.Notify && op != message.GossipRequest && op != message.Timeout {\n\t\tnodeID := msg.NodeID()\n\t\th.cpuTracker.UtilizeTime(nodeID, startTime, endTime)\n\t}\n\n\t// Track how long the operation took.\n\thistogram := h.metrics.messages[op]\n\thistogram.Observe(float64(endTime.Sub(startTime)))\n\n\tmsg.OnFinishedHandling()\n\n\tif isPeriodic {\n\t\th.ctx.Log.Verbo(\"Finished handling message: %s\", op)\n\t} else {\n\t\th.ctx.Log.Debug(\"Finished handling message: %s\", op)\n\t}\n\treturn err\n}", "func (s *Websocket) direct(msg models.Message) {\n\ts.hmu.RLock()\n\tuserFrom, okFrom := s.hub[msg.Sender]\n\tuserTo, okTo := s.hub[msg.Receiver]\n\ts.hmu.RUnlock()\n\n\tif !okFrom {\n\t\ts.logger.Errorf(\"unnown user from send message: %s\", msg.Sender)\n\t\treturn\n\t}\n\n\tif !okTo {\n\t\ts.logger.Errorf(\"unnown user to send message: %s\", msg.Receiver)\n\t\treturn\n\t}\n\n\t// Write to sender\n\tif err := userFrom.Conn.WriteJSON(msg); err != nil {\n\t\ts.logger.Errorf(\"error sending message: %v\", err)\n\t}\n\n\t// Write to receiver\n\tif err := userTo.Conn.WriteJSON(msg); err != nil {\n\t\ts.logger.Errorf(\"error sending message: %v\", err)\n\t}\n}", "func (p *AsyncProducer) Send(msg string) {\n\tm := fmt.Sprintf(\"[%s] [%s] %s\",\n\t\ttime.Now().Format(time.RFC3339), p.loggerID, msg)\n\tmsgBytes, err := json.Marshal(m)\n\tif err != nil {\n\t\tlog.Println(\"Failed json encoding kafka log msg: \", err)\n\t\treturn\n\t}\n\tmsgLog := sarama.ProducerMessage{\n\t\tTopic: topic,\n\t\t// Key: sarama.StringEncoder(),\n\t\tTimestamp: time.Now(),\n\t\tValue: sarama.ByteEncoder(msgBytes),\n\t}\n\tp.prodr.Input() <- &msgLog\n}" ]
[ "0.6522442", "0.6383854", "0.62789243", "0.62672144", "0.61907643", "0.61150897", "0.6095663", "0.60505706", "0.6014298", "0.5998422", "0.5993758", "0.5962349", "0.5953531", "0.59097695", "0.5851445", "0.5850117", "0.5830223", "0.5828544", "0.58172476", "0.58084667", "0.5777062", "0.5775901", "0.576238", "0.57614326", "0.57386166", "0.5699146", "0.56981057", "0.5693156", "0.5658179", "0.5657767", "0.5651569", "0.5641779", "0.5638627", "0.56295764", "0.5616587", "0.5616411", "0.5615189", "0.5612852", "0.5604559", "0.560016", "0.55987674", "0.55972177", "0.55925405", "0.55820525", "0.5574018", "0.5572729", "0.55723614", "0.55720454", "0.55690795", "0.5566177", "0.55657595", "0.55532825", "0.55445963", "0.55307907", "0.5522546", "0.55041385", "0.5503141", "0.54996586", "0.5498063", "0.5488224", "0.5473652", "0.5468309", "0.5466589", "0.54466784", "0.54430586", "0.54299587", "0.54294497", "0.5424105", "0.5422253", "0.5404556", "0.5403442", "0.5402769", "0.53997624", "0.5396471", "0.5393558", "0.5387087", "0.5384733", "0.5382753", "0.5381081", "0.5379517", "0.5377305", "0.53748", "0.536381", "0.53615576", "0.5355867", "0.5353388", "0.5353296", "0.53464764", "0.5345666", "0.5342974", "0.5337228", "0.5337033", "0.53356385", "0.5333671", "0.53301996", "0.5315773", "0.5312227", "0.5307207", "0.52955186", "0.52951515" ]
0.6813388
0
SendFailed updates the metrics for having failed to send [msg].
func (m *Metrics) SendFailed(msg message.OutboundMessage) { op := msg.Op() msgMetrics := m.MessageMetrics[op] if msgMetrics == nil { m.Log.Error( "unknown message failed to be sent", zap.Stringer("messageOp", op), ) return } msgMetrics.NumFailed.Inc() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (manager *Manager) sendFailedEvent(msg string, projectUpdateID string) {\n\tevent := &automate_event.EventMsg{\n\t\tEventID: createEventUUID(),\n\t\tType: &automate_event.EventType{Name: automate_event_type.ProjectRulesUpdateFailed},\n\t\tPublished: ptypes.TimestampNow(),\n\t\tProducer: &automate_event.Producer{\n\t\t\tID: event_ids.ComplianceInspecReportProducerID,\n\t\t},\n\t\tData: &_struct.Struct{\n\t\t\tFields: map[string]*_struct.Value{\n\t\t\t\tproject_update_tags.ProjectUpdateIDTag: {\n\t\t\t\t\tKind: &_struct.Value_StringValue{\n\t\t\t\t\t\tStringValue: projectUpdateID,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"message\": {\n\t\t\t\t\tKind: &_struct.Value_StringValue{\n\t\t\t\t\t\tStringValue: msg,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tpubReq := &automate_event.PublishRequest{Msg: event}\n\t_, err := manager.eventServiceClient.Publish(context.Background(), pubReq)\n\tif err != nil {\n\t\tlogrus.Warnf(\"Publishing status event %v\", err)\n\t}\n}", "func (n *NotifyMail) ResendFailed() {\n\n\tvar mails []M.Mail\n\n\terr := n.store.GetFailed(&mails, 100)\n\n\tif err != nil {\n\t\tn.errChan.In() <- err\n\t\treturn\n\t}\n\n\tif len(mails) > 0 {\n\t\tn.notifChan.In() <- fmt.Sprintf(\"Resending %d failed mails\", len(mails))\n\t}\n\n\tfor _, mail := range mails {\n\t\tn.sendChan <- mail\n\t}\n\n}", "func TestSendFailed(t *testing.T) {\n\tdoh, _ := NewTransport(testURL, ips, nil, nil, nil)\n\ttransport := doh.(*transport)\n\trt := makeTestRoundTripper()\n\ttransport.client.Transport = rt\n\n\trt.err = errors.New(\"test\")\n\t_, err := doh.Query(simpleQueryBytes)\n\tvar qerr *queryError\n\tif err == nil {\n\t\tt.Error(\"Send failure should be reported\")\n\t} else if !errors.As(err, &qerr) {\n\t\tt.Errorf(\"Wrong error type: %v\", err)\n\t} else if qerr.status != SendFailed {\n\t\tt.Errorf(\"Wrong error status: %d\", qerr.status)\n\t} else if !errors.Is(qerr, rt.err) {\n\t\tt.Errorf(\"Underlying error is not retained\")\n\t}\n}", "func (a *AutoRollNotifier) SendLastNFailed(ctx context.Context, n int, url string) {\n\ta.send(ctx, &tmplVars{\n\t\tIssueURL: url,\n\t\tN: n,\n\t}, subjectTmplLastNFailed, bodyTmplLastNFailed, notifier.SEVERITY_ERROR, MSG_TYPE_LAST_N_FAILED, nil)\n}", "func sendErrorMessage(s *dgo.Session, c string, m string) {\n\ts.ChannelMessageSend(c, m)\n}", "func (s *syncRatio) ReportFailedSync() {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\ts.failedSyncs++\n}", "func (s *Session) setFailed(failures []string) {\n\ts.Failures = append(s.Failures, failures...)\n\ts.Status = \"failed\"\n}", "func (w *reqResWriter) failed(err error) error {\n\tif w.err != nil {\n\t\treturn w.err\n\t}\n\n\tw.mex.shutdown()\n\tw.err = err\n\treturn w.err\n}", "func failed(msg string) (int, bool) {\n\tlog.Printf(\"Error message: %q\\n\", msg)\n\treturn 0, false\n}", "func (m Progress) UpdateFailed(failures map[types.ContainerID]error) {\n\tfor id, err := range failures {\n\t\tupdate := m[id]\n\t\tupdate.error = err\n\t\tupdate.state = FailedState\n\t}\n}", "func (hs *HealthStatusInfo) PublishFailed() {\n\ths.lock()\n\tdefer hs.unLock()\n\tMQTTHealth.PublishFailures++\n\tMQTTHealth.lastPublishErrorTime = time.Now()\n}", "func (m *manager) sendErr(w http.ResponseWriter, errorCode int64, errorData interface{}) {\n\tw.WriteHeader(http.StatusInternalServerError)\n\tenc := json.NewEncoder(w)\n\tenc.Encode(map[string]interface{}{\n\t\t\"ok\": false,\n\t\t\"error_code\": errorCode,\n\t\t\"error_data\": errorData,\n\t})\n}", "func (hs *HealthStatusInfo) SubscribeFailed() {\n\ths.lock()\n\tdefer hs.unLock()\n\tMQTTHealth.SubscribeFailures++\n\tMQTTHealth.lastSubscribeErrorTime = time.Now()\n}", "func (email *Email) MarkFail(client *redis.Client) {\n\tfmt.Println(\"Email Sent\")\n}", "func (a *AutoRollNotifier) SendNewFailure(ctx context.Context, id, url string) {\n\ta.send(ctx, &tmplVars{\n\t\tIssueID: id,\n\t\tIssueURL: url,\n\t}, subjectTmplNewFailure, bodyTmplNewFailure, notifier.SEVERITY_WARNING, MSG_TYPE_NEW_FAILURE, nil)\n}", "func (c *context) Failed(msg string) {\n\tc.writer.WriteHeader(http.StatusBadRequest)\n\tfmt.Fprint(c.writer, msg)\n}", "func (s *LatencyFaultStrategy) UpdateSendStats(stats SendStats) {\n\tlatency := stats.latency\n\tif stats.isFail {\n\t\tlatency = 30 * time.Second\n\t}\n\tvar invalidDuration time.Duration\n\tfor i, max := range latencyMax {\n\t\tif latency >= max {\n\t\t\tinvalidDuration = notAvailable[i]\n\t\t}\n\t}\n\n\tif item, ok := s.latencyTable.Load(stats.BrokerName); ok {\n\t\titem.(*latencyItem).started = time.Now()\n\t\titem.(*latencyItem).latency = invalidDuration\n\t} else {\n\t\titem := &latencyItem{\n\t\t\tstats.BrokerName,\n\t\t\ttime.Now(),\n\t\t\tinvalidDuration,\n\t\t}\n\t\ts.latencyTable.Store(stats.BrokerName, item)\n\t}\n}", "func (n *NameService) ReportFailedNode(nodeID fred.NodeID, kg fred.KeygroupName, id string) error {\n\n}", "func ReportFailure(action string, label string) {\n\tactionlabel := getLabel(action, label)\n\tif metricEnabled() {\n\t\tmetrics.GopherActions.WithLabelValues(\"failure\", actionlabel).Inc()\n\t}\n}", "func (p *PoolShard) markFailed(failed bool) {\n\tif failed {\n\t\ts := atomic.AddUint32(&p.fails, 1)\n\t\tif s == p.maxFails {\n\t\t\tselect {\n\t\t\tcase p.dpool.suspectShards <- p:\n\t\t\tdefault: /*do nothing*/\n\t\t\t}\n\t\t}\n\t} else {\n\t\tatomic.StoreUint32(&p.fails, 0)\n\t}\n}", "func TestSendError(t *testing.T) {\n\terr := SendError(\"Send Error\", \"https://status.btfs.io\", \"my peer id\", \"my HValue\")\n\tif err != nil {\n\t\tt.Errorf(\"Send error message to status server failed, reason: %v\", err)\n\t} else {\n\t\tt.Log(\"Send error message to status server successfully!\")\n\t}\n}", "func (s *sender) sendMetrics(ctx context.Context, flds fields) ([]metricPair, error) {\n\tvar (\n\t\tbody strings.Builder\n\t\terrs error\n\t\tdroppedRecords []metricPair\n\t\tcurrentRecords []metricPair\n\t)\n\n\tfor _, record := range s.metricBuffer {\n\t\tvar formattedLine string\n\t\tvar err error\n\n\t\tswitch s.config.MetricFormat {\n\t\tcase PrometheusFormat:\n\t\t\tformattedLine = s.prometheusFormatter.metric2String(record)\n\t\tcase Carbon2Format:\n\t\t\tformattedLine = carbon2Metric2String(record)\n\t\tcase GraphiteFormat:\n\t\t\tformattedLine = s.graphiteFormatter.metric2String(record)\n\t\tdefault:\n\t\t\terr = fmt.Errorf(\"unexpected metric format: %s\", s.config.MetricFormat)\n\t\t}\n\n\t\tif err != nil {\n\t\t\tdroppedRecords = append(droppedRecords, record)\n\t\t\terrs = multierr.Append(errs, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tar, err := s.appendAndSend(ctx, formattedLine, MetricsPipeline, &body, flds)\n\t\tif err != nil {\n\t\t\terrs = multierr.Append(errs, err)\n\t\t\tif ar.sent {\n\t\t\t\tdroppedRecords = append(droppedRecords, currentRecords...)\n\t\t\t}\n\n\t\t\tif !ar.appended {\n\t\t\t\tdroppedRecords = append(droppedRecords, record)\n\t\t\t}\n\t\t}\n\n\t\t// If data was sent, cleanup the currentTimeSeries counter\n\t\tif ar.sent {\n\t\t\tcurrentRecords = currentRecords[:0]\n\t\t}\n\n\t\t// If log has been appended to body, increment the currentTimeSeries\n\t\tif ar.appended {\n\t\t\tcurrentRecords = append(currentRecords, record)\n\t\t}\n\t}\n\n\tif body.Len() > 0 {\n\t\tif err := s.send(ctx, MetricsPipeline, strings.NewReader(body.String()), flds); err != nil {\n\t\t\terrs = multierr.Append(errs, err)\n\t\t\tdroppedRecords = append(droppedRecords, currentRecords...)\n\t\t}\n\t}\n\n\treturn droppedRecords, errs\n}", "func ReportFailure(errorMessages []string) error {\n\twriteLog(\"DEBUG: Reporting FAILURE\")\n\n\t// make a new report without errors\n\tnewReport := status.NewReport(errorMessages)\n\n\t// send it\n\treturn sendReport(newReport)\n}", "func (r *reporter) Fail() {\n\tatomic.StoreInt32(&r.failed, 1)\n}", "func (ps *raftFollowerStats) Fail() {\n\tps.Counts.Fail++\n}", "func (_BaseAccessWallet *BaseAccessWalletCaller) ExecStatusSendFail(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _BaseAccessWallet.contract.Call(opts, &out, \"execStatusSendFail\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (s *DeleteAwsLogSourceOutput) SetFailed(v []*string) *DeleteAwsLogSourceOutput {\n\ts.Failed = v\n\treturn s\n}", "func (s *ChangeMessageVisibilityBatchOutput) SetFailed(v []*BatchResultErrorEntry) *ChangeMessageVisibilityBatchOutput {\n\ts.Failed = v\n\treturn s\n}", "func (s *CreateAwsLogSourceOutput) SetFailed(v []*string) *CreateAwsLogSourceOutput {\n\ts.Failed = v\n\treturn s\n}", "func (c *Consumer) reportError(d string, errmsg string, err error) {\n\t//c.status.ErrorCount.Add(1)\n\tlog.Errorf(\"%s when processing %s: %s\", errmsg, d, err)\n}", "func (c *Counter) IncrFailure(topic string) {\n\tif _, ok := c.topicStats[topic]; !ok {\n\t\tc.topicStats[topic] = &stats{}\n\t}\n\tc.topicStats[topic].failure++\n}", "func (mt *Metrics) Send() []error {\n\tif Mail == \"\" || Token == \"\" {\n\t\treturn errAccessCredentials\n\t}\n\n\terr := validateMetrics(mt)\n\n\tif err != nil {\n\t\treturn []error{err}\n\t}\n\n\tif len(mt.queue) == 0 {\n\t\treturn nil\n\t}\n\n\tmt.lastSendingDate = time.Now().Unix()\n\n\tdata := convertMeasurementSlice(mt.queue)\n\n\tmt.queue = make([]Measurement, 0)\n\n\terrs := execRequest(mt.Engine, req.POST, APIEndpoint+\"/v1/metrics/\", data)\n\n\tmt.execErrorHandler(errs)\n\n\treturn errs\n}", "func (s *ObjectiveStatusCounters) SetFailed(v int64) *ObjectiveStatusCounters {\n\ts.Failed = &v\n\treturn s\n}", "func (s *DeleteMessageBatchOutput) SetFailed(v []*BatchResultErrorEntry) *DeleteMessageBatchOutput {\n\ts.Failed = v\n\treturn s\n}", "func (c *Controller) setSyncFailedStatus(helmRequest *appv1.HelmRequest, err error) error {\n\tc.sendFailedSyncEvent(helmRequest, err)\n\tclient := c.getAppClient(helmRequest)\n\torigin, errI := client.AppV1().HelmRequests(helmRequest.Namespace).Get(helmRequest.Name, metav1.GetOptions{})\n\tif errI != nil {\n\t\treturn errI\n\t}\n\n\trequest := origin.DeepCopy()\n\trequest.Status.Reason = err.Error()\n\trequest.Status.Phase = appv1.HelmRequestFailed\n\treturn helm.UpdateHelmRequestStatus(client, request)\n\n}", "func (c *ConcurrentRetrier) Failed() {\n\tdefer c.Unlock()\n\tc.Lock()\n\tc.failureCount++\n}", "func (s *schedule) AppendFailure(n uint64, event *event.Event) {\n\ts.n = n\n\ts.event = event\n\tfor i := range s.occurred {\n\t\ts.occurred[i] = false\n\t}\n\ts.append = true\n}", "func (s *ResourceCountsSummary) SetFailed(v int64) *ResourceCountsSummary {\n\ts.Failed = &v\n\treturn s\n}", "func (b *BandwidthCollector) LogSentMessage(int64) {}", "func logFailure(message string, w http.ResponseWriter, r *http.Request, statusCode int) {\n\n\t// Default status code\n\tif statusCode < 100 {\n\t\tstatusCode = 400\n\t}\n\n\tremoteHost := getHost(r)\n\tfor _, logAgent := range appConfig.LogEndpoints {\n\t\tif !strings.Contains(logAgent, \"/patroneos/fail2ban-relay\") {\n\t\t\tlogAgent += \"/patroneos/fail2ban-relay\"\n\t\t}\n\t\tlogEvent := Log{\n\t\t\tHost: remoteHost,\n\t\t\tSuccess: false,\n\t\t\tMessage: message,\n\t\t}\n\t\tbody, err := json.Marshal(logEvent)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error marshalling failure message %s\", err)\n\t\t}\n\t\t_, err = client.Post(logAgent, \"application/json\", bytes.NewBuffer(body))\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t}\n\t}\n\trequestBytes, _ := ioutil.ReadAll(r.Body)\n\tlog.Printf(\"Failure: %s %d %s %s %s\", remoteHost, statusCode, message, r.URL.String(), requestBytes)\n\tif w != nil {\n\t\terrorBody, _ := json.Marshal(ErrorMessage{Message: message, Code: statusCode})\n\t\tw.Header().Add(\"X-REJECTED-BY\", \"patroneos\")\n\t\tw.Header().Add(\"CONTENT-TYPE\", \"application/json\")\n\n\t\tinjectHeaders(w.Header())\n\t\tw.WriteHeader(statusCode)\n\t\t_, err := w.Write(errorBody)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error writing response body %s\", err)\n\t\t}\n\t}\n}", "func (a *AutoRollNotifier) SendRollCreationFailed(ctx context.Context, err error) {\n\ta.send(ctx, &tmplVars{\n\t\tMessage: err.Error(),\n\t}, subjectTmplRollCreationFailed, bodyTmplRollCreationFailed, notifier.SEVERITY_ERROR, MSG_TYPE_ROLL_CREATION_FAILED, nil)\n}", "func (s *SendMessageBatchOutput) SetFailed(v []*BatchResultErrorEntry) *SendMessageBatchOutput {\n\ts.Failed = v\n\treturn s\n}", "func (this *SyncFlightInfo) MarkFailedNode() {\n\tthis.lock.Lock()\n\tdefer this.lock.Unlock()\n\tthis.failedNodes[this.nodeId] += 1\n\tthis.totalFailed++\n}", "func (m *CloudPcBulkActionSummary) SetFailedCount(value *int32)() {\n err := m.GetBackingStore().Set(\"failedCount\", value)\n if err != nil {\n panic(err)\n }\n}", "func (j *JSendBuilderBuffer) Fail(data interface{}) JSendBuilder {\n\tj.Set(FieldStatus, StatusFail)\n\tj.Data(data)\n\treturn j\n}", "func (c *RegionCache) OnSendFailForBatchRegions(bo *Backoffer, store *tikv.Store, regionInfos []RegionInfo, scheduleReload bool, err error) {\n\tmetrics.RegionCacheCounterWithSendFail.Add(float64(len(regionInfos)))\n\tif !store.IsTiFlash() {\n\t\tlogutil.Logger(bo.GetCtx()).Info(\"Should not reach here, OnSendFailForBatchRegions only support TiFlash\")\n\t\treturn\n\t}\n\tlogutil.Logger(bo.GetCtx()).Info(\"Send fail for \" + strconv.Itoa(len(regionInfos)) + \" regions, will switch region peer for these regions. Only first \" + strconv.Itoa(mathutil.Min(10, len(regionInfos))) + \" regions will be logged if the log level is higher than Debug\")\n\tfor index, ri := range regionInfos {\n\t\tif ri.Meta == nil {\n\t\t\tcontinue\n\t\t}\n\t\tc.OnSendFailForTiFlash(bo.TiKVBackoffer(), store, ri.Region, ri.Meta, scheduleReload, err, !(index < 10 || log.GetLevel() <= zap.DebugLevel))\n\t}\n}", "func (s *sendClient) sendMetrics(buf []byte) error {\n\tlog.Debugln(\"start sending metrics\")\n\n\treq, err := http.NewRequest(\"POST\", s.writeURL.String(), bytes.NewReader(buf))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/text\")\n\treq.Header.Set(\"User-Agent\", \"pgSCV\")\n\treq.Header.Add(\"X-Weaponry-Api-Key\", s.apiKey)\n\n\tq := req.URL.Query()\n\tq.Add(\"timestamp\", fmt.Sprintf(\"%d\", time.Now().UnixNano()/1000000))\n\tq.Add(\"extra_label\", fmt.Sprintf(\"instance=%s\", s.hostname))\n\treq.URL.RawQuery = q.Encode()\n\n\tctx, cancel := context.WithTimeout(context.Background(), s.timeout)\n\tdefer cancel()\n\n\treq = req.WithContext(ctx)\n\n\tresp, err := s.Client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\t_, _ = io.Copy(io.Discard, resp.Body)\n\t\t_ = resp.Body.Close()\n\t}()\n\n\tif resp.StatusCode/100 != 2 {\n\t\tscanner := bufio.NewScanner(io.LimitReader(resp.Body, 512))\n\t\tline := \"\"\n\t\tif scanner.Scan() {\n\t\t\tline = scanner.Text()\n\t\t}\n\t\treturn fmt.Errorf(\"server returned HTTP status %s: %s\", resp.Status, line)\n\t}\n\n\tlog.Debugln(\"sending metrics finished successfully: server returned HTTP status \", resp.Status)\n\treturn nil\n}", "func (f *Sink) recoverFailed(endpoint *Endpoint) {\n\t// Ignore if we haven't failed\n\tif !endpoint.IsAlive() {\n\t\treturn\n\t}\n\n\tendpoint.mutex.Lock()\n\tendpoint.status = endpointStatusIdle\n\tendpoint.mutex.Unlock()\n\n\tf.failedList.Remove(&endpoint.failedElement)\n\tf.markReady(endpoint)\n}", "func (st *Status) AddFailedServer(host *Host, err error) {\n\tif _, ok := st.Errors[host.Name]; !ok {\n\t\tst.Errors[host.Name] = []error{}\n\t}\n\tst.Errors[host.Name] = append(st.Errors[host.Name], err)\n\n\t// Increase failed host counter\n\tif _, ok := st.FailedHosts.Servers[host.Name]; !ok {\n\t\tst.FailedHosts.Servers[host.Name] = 1\n\t} else {\n\t\tst.FailedHosts.Servers[host.Name]++\n\t}\n}", "func (f *formatter) Failed(_ *godog.Scenario, st *godog.Step, _ *godog.StepDefinition, err error) {\n\tdetails := &StatusDetails{\n\t\tMessage: err.Error(),\n\t}\n\n\tstep := f.step(st)\n\tstep.Status = Failed\n\tstep.StatusDetails = details\n\n\tf.res.Steps = append(f.res.Steps, step)\n\tf.res.Status = Failed\n\tf.res.StatusDetails = details\n}", "func MessageNotSent(sms *structures.SMSMessage, session *mgo.Session) (err error) {\n\tlog.Println(\"--- updateMessageStatus \")\n\tchange := mgo.Change{\n\t\tUpdate: bson.M{\"$set\": bson.M{\n\t\t\t\"retries\": sms.Retries,\n\t\t}},\n\t}\n\t_, err = session.DB(dbName).C(\"queue\").Find(bson.M{\"_id\": sms.ID}).Apply(change, nil)\n\treturn\n}", "func EventFailedLabelsUpdateMsg(err error) string {\n\treturn fmt.Sprintf(\"Error updating local object labels: %v\", err)\n}", "func (t *Transaction) Failed() {\n\terr := Transactions.UpdateId(t.ID, bson.M{\"$set\": bson.M{\"status\": \"failed\"}})\n\tif err != nil {\n\t\tlog.Println(\"[MONGO] ERROR SETTING STATUS AS FAILED:\", err.Error())\n\t}\n\tt.Log(\"FAILED\")\n}", "func (f *Sink) moveFailed(endpoint *Endpoint) {\n\t// Should never get here if we're closing, caller should check IsClosing()\n\tif !endpoint.IsAlive() {\n\t\treturn\n\t}\n\n\tif endpoint.isReady {\n\t\tf.readyList.Remove(&endpoint.readyElement)\n\t\tendpoint.isReady = false\n\t}\n\n\tif endpoint.IsFull() {\n\t\tf.fullList.Remove(&endpoint.readyElement)\n\t}\n\n\tendpoint.mutex.Lock()\n\tendpoint.status = endpointStatusFailed\n\tendpoint.averageLatency = 0\n\tendpoint.mutex.Unlock()\n\n\tf.failedList.PushFront(&endpoint.failedElement)\n}", "func (queue *Queue) RequeueFailed() error {\n\tl := queue.GetFailedLength()\n\t// TODO implement this in lua\n\tfor l > 0 {\n\t\terr := queue.redisClient.RPopLPush(queueFailedKey(queue.Name), queueInputKey(queue.Name)).Err()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tqueue.incrRate(queueInputRateKey(queue.Name), 1)\n\t\tl--\n\t}\n\treturn nil\n}", "func reportError(d string, errmsg string, err error) {\n\tstatus.ErrorCount.Mark(1)\n\tlog.Debugf(\"%s when processing %s: %s\", errmsg, d, err)\n}", "func (t *TestCase) MarkFailed(message, output string) {\n\tt.FailureOutput = &FailureOutput{\n\t\tMessage: message,\n\t\tOutput: output,\n\t}\n}", "func Failed(c *gin.Context, code int, message string) {\n\tJSON(c, Response{\n\t\tCode: code,\n\t\tMessage: message,\n\t\tData: nil,\n\t})\n}", "func (t *Timer) healthcheckfail(writer http.ResponseWriter, request *http.Request) {\n\tif t.isFinished {\n\t\twriter.WriteHeader(400)\n\t} else {\n\t\twriter.WriteHeader(200)\n\t}\n}", "func (dn *DNode) replicateFailedRequest(sb *syncBufferState) error {\n\tswitch sb.clusterType {\n\tcase meta.ClusterTypeTstore:\n\t\treturn dn.replicateFailedPoints(sb)\n\tcase meta.ClusterTypeKstore:\n\t\treturn dn.replicateFailedWrite(sb)\n\tdefault:\n\t\tdn.logger.Fatalf(\"unknown cluster type: %+v in sync buffer\", sb)\n\t}\n\treturn nil\n}", "func SendError(conn net.Conn,name string, msg string){\n\n\tdataMap:=make(map[string]interface{})\n\tdataMap[\"type\"]=\"error\"\n\tdataMap[\"name\"]=name\n\tdataMap[\"msg\"]=msg\n\tSendJSONData(conn,dataMap)\n\n\n}", "func MetricInitiateAccountRegistrationFailed(provider string) {\n\tswitch strings.ToUpper(provider) {\n\tcase serviceprovider.FACEBOOK:\n\t\tPrometheusRegisterFacebookFailedTotal.Inc()\n\tcase serviceprovider.GOOGLE:\n\t\tPrometheusRegisterGoogleFailedTotal.Inc()\n\tdefault:\n\t\tPrometheusRegisterDefaultFailedTotal.Inc()\n\t}\n}", "func (r *SyncResult) Fail(err error, msg string) {\n\tr.Error, r.Message = err, msg\n}", "func (dc *DatadogCollector) IncrementFailures() {\n\t_ = dc.client.Count(dmFailures, 1, dc.tags, 1.0)\n}", "func SendError(w http.ResponseWriter, status int, errMsg string) {\n header(w, status)\n data := ErrJson {\n Status: status,\n Error: errMsg,\n }\n json.NewEncoder(w).Encode(data)\n}", "func incrFailedRequestStatDelta() {\n\tStatMu.Mutex.Lock()\n\n\t// increment the requests counter\n\t*(StatMu.InstanceStat.FailedRequests) = *(StatMu.InstanceStat.FailedRequests) + uint64(1)\n\tStatMu.Mutex.Unlock()\n\n}", "func (w *Watcher) sendError(err error) bool {\n\tselect {\n\tcase w.Errors <- err:\n\t\treturn true\n\tcase <-w.done:\n\t\treturn false\n\t}\n}", "func (q *Queue) RequeueFailed() error {\n\tl := q.GetFailedLength()\n\t// TODO implement this in lua\n\tfor l > 0 {\n\t\terr := q.redisClient.RPopLPush(queueFailedKey(q.Name), queueInputKey(q.Name)).Err()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tq.incrRate(queueInputRateKey(q.Name), 1)\n\t\tl--\n\t}\n\treturn nil\n}", "func (c *Conn) TempfailMsg(format string, elems ...interface{}) {\n\tswitch c.curcmd {\n\tcase HELO, EHLO:\n\t\tc.replyMulti(421, format, elems...)\n\tcase AUTH:\n\t\tc.authDone(false)\n\t\tc.replyMulti(454, format, elems...)\n\tcase MAILFROM, RCPTTO, DATA:\n\t\tc.replyMulti(450, format, elems...)\n\t}\n\tc.replied = true\n}", "func (ctx *UpdateListenContext) OKFailed(r *AntRegResultFailed) error {\n\tctx.ResponseData.Header().Set(\"Content-Type\", \"vnd.ant.reg.result+json\")\n\treturn ctx.ResponseData.Service.Send(ctx.Context, 200, r)\n}", "func sendErrorMessage(w io.Writer, err error) {\n\tif err == nil {\n\t\tpanic(errors.Wrap(err, \"Cannot send error message if error is nil\"))\n\t}\n\tfmt.Printf(\"ERROR: %+v\\n\", err)\n\twriteJSON(w, map[string]string{\n\t\t\"status\": \"error\",\n\t\t\"message\": err.Error(),\n\t})\n}", "func sendWithRetry(s *Sms) {\n\tret := send(s)\n\tretry := 0\n\tfor ; !ret && retry < MAX_RETRY; retry++ {\n\t\ttime.Sleep(WAIT_TIME)\n\t\tret = send(s)\n\t}\n\tlog.Printf(\"%t|%d|%s|%s|%s|%s|%s|%d\\n\", ret, retry, s.from, s.task, s.relayName, s.mobile, s.message, s.count)\n}", "func (us *URLStore) FailedCall(u *model.URL) error {\n\tu.FailedCall++\n\tvar err error\n\terr = us.db.Save(u).Error\n\tif u.FailedCall >= u.Threshold {\n\t\tu.Alert, err = us.GetAlert(u.ID)\n\t\tif err != nil && !gorm.IsRecordNotFoundError(err) {\n\t\t\treturn err\n\t\t}\n\t\tif gorm.IsRecordNotFoundError(err) {\n\t\t\tu.Alert = model.NewAlert(\"Critical threshold violated\", u.FailedCall, u.ID)\n\t\t} else {\n\t\t\tu.Alert.FailedCall = u.FailedCall\n\t\t}\n\t\treturn us.db.Save(u.Alert).Error\n\t}\n\treturn err\n}", "func (TransferStatus) Failed() TransferStatus { return TransferStatus(-1) }", "func (r *Reconciler) fail(instance *bucketv1alpha1.Bucket, reason, msg string) (reconcile.Result, error) {\n\tinstance.Status.SetCondition(corev1alpha1.NewCondition(corev1alpha1.Failed, reason, msg))\n\treturn resultRequeue, r.Update(ctx, instance)\n}", "func sendFollowUsernameFail(conn *userConn, username, reason string) {\n\tvar msg cliproto_down.FollowUsernameFailed\n\tmsg.Username = new(string)\n\tmsg.Reason = new(string)\n\tmsg.FirstUnapplied = new(uint64)\n\t*msg.Username = username\n\t*msg.Reason = reason\n\t*msg.FirstUnapplied = store.InstructionFirstUnapplied()\n\n\tconn.conn.SendProto(4, &msg)\n}", "func sendFollowUserIdFail(conn *userConn, userId uint64, reason string) {\n\tvar msg cliproto_down.FollowUserIdFailed\n\tmsg.UserId = new(uint64)\n\tmsg.Reason = new(string)\n\tmsg.FirstUnapplied = new(uint64)\n\t*msg.UserId = userId\n\t*msg.Reason = reason\n\t*msg.FirstUnapplied = store.InstructionFirstUnapplied()\n\n\tconn.conn.SendProto(5, &msg)\n}", "func (queue *Queue) ResetFailed() error {\n\treturn queue.redisClient.Del(queueFailedKey(queue.Name)).Err()\n}", "func (h *Handler) reportMsgResult(\n\tfiksMsg fiksMessage,\n\tstatus MessageType,\n\tbody string,\n) (err error) {\n\tlog := fiksMsg.LoggerWithFields()\n\n\t// Inform FIKS about data processing status\n\tmetaData := fiksMsgMetadata{\n\t\tResponseToMsgID: fiksMsg.GetMeldingID(),\n\t\tSenderAccountID: fiksMsg.GetClientID(),\n\t\tRecipientAccountID: fiksMsg.GetAvsenderID(),\n\t\tMessageType: string(status),\n\t}\n\n\tlog.Debugf(\"Reporting status '%s' to FIKS.\", status)\n\n\tvar encryptedData io.Reader\n\n\t// If message type failed, error msg (body) should be included\n\tif status == MessageTypeFailed {\n\t\tencryptedData, err = h.createEncryptedBody(status, body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// send message to FIKS\n\tsendErr := h.Sender.Send(metaData, encryptedData)\n\tif sendErr != nil {\n\t\treturn fmt.Errorf(\"could not send message to FIKS: %s\", sendErr.Error())\n\t}\n\n\tlog.Debugf(\"Successfully sent message to FIKS.\")\n\treturn nil\n}", "func (monitor *Monitor) SendMetric(delay int64) error {\n\tif monitor.MetricID == 0 {\n\t\treturn nil\n\t}\n\n\tjsonBytes, _ := json.Marshal(&map[string]interface{}{\n\t\t\"value\": delay,\n\t})\n\n\tresp, _, err := monitor.config.makeRequest(\"POST\", \"/metrics/\"+strconv.Itoa(monitor.MetricID)+\"/points\", jsonBytes)\n\tif err != nil || resp.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"Could not log data point!\\n%v\\n\", err)\n\t}\n\n\treturn nil\n}", "func (w *filePoller) sendErr(e error, chClose <-chan struct{}) error {\n\tselect {\n\tcase w.errors <- e:\n\tcase <-chClose:\n\t\treturn fmt.Errorf(\"closed\")\n\t}\n\treturn nil\n}", "func (cc *CosmosProvider) LogFailedTx(res *provider.RelayerTxResponse, err error, msgs []provider.RelayerMessage) {\n\t// Include the chain_id\n\tfields := []zapcore.Field{zap.String(\"chain_id\", cc.ChainId())}\n\n\t// Extract the channels from the events, if present\n\tif res != nil {\n\t\tchannels := getChannelsIfPresent(res.Events)\n\t\tfields = append(fields, channels...)\n\t}\n\tfields = append(fields, msgTypesField(msgs))\n\n\tif err != nil {\n\n\t\tif errors.Is(err, chantypes.ErrRedundantTx) {\n\t\t\tcc.log.Debug(\"Redundant message(s)\", fields...)\n\t\t\treturn\n\t\t}\n\n\t\t// Make a copy since we may continue to the warning\n\t\terrorFields := append(fields, zap.Error(err))\n\t\tcc.log.Error(\n\t\t\t\"Failed sending cosmos transaction\",\n\t\t\terrorFields...,\n\t\t)\n\n\t\tif res == nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tif res.Code != 0 {\n\t\tif sdkErr := cc.sdkError(res.Codespace, res.Code); err != nil {\n\t\t\tfields = append(fields, zap.NamedError(\"sdk_error\", sdkErr))\n\t\t}\n\t\tfields = append(fields, zap.Object(\"response\", res))\n\t\tcc.log.Warn(\n\t\t\t\"Sent transaction but received failure response\",\n\t\t\tfields...,\n\t\t)\n\t}\n}", "func (hs *HealthStatusInfo) DBWriteFailed() {\n\ths.lock()\n\tdefer hs.unLock()\n\tDBHealth.DBWriteFailures++\n\tDBHealth.lastReadWriteErrorTime = time.Now()\n}", "func sendApiError(ctx echo.Context, code int, message string) error {\n\tapiErr := Error{\n\t\tCode: int32(code),\n\t\tMessage: message,\n\t}\n\terr := ctx.JSON(code, apiErr)\n\treturn err\n}", "func (r *reqResReader) failed(err error) error {\n\tif r.err != nil {\n\t\treturn r.err\n\t}\n\n\tr.mex.shutdown()\n\tr.err = err\n\treturn r.err\n}", "func MetricLoginFailed(provider string) {\n\tswitch strings.ToUpper(provider) {\n\tcase serviceprovider.FACEBOOK:\n\t\tPrometheusFacebookFailedTotal.Inc()\n\tcase serviceprovider.GOOGLE:\n\t\tPrometheusGoogleFailedTotal.Inc()\n\tdefault:\n\t\tPrometheusDefaultFailedTotal.Inc()\n\t}\n}", "func RegisterFailedScaleUp(reason FailedScaleUpReason, gpuResourceName, gpuType string) {\n\tfailedScaleUpCount.WithLabelValues(string(reason)).Inc()\n\tif gpuType != gpu.MetricsNoGPU {\n\t\tfailedGPUScaleUpCount.WithLabelValues(string(reason), gpuResourceName, gpuType).Inc()\n\t}\n}", "func (h *mysqlMetricStore) sendmessage() {\n\th.lock.Lock()\n\tdefer h.lock.Unlock()\n\tvar caches = new(MonitorMessageList)\n\tfor _, v := range h.PathCache {\n\t\t_, avg, max := calculate(&v.ResTime)\n\t\tmm := MonitorMessage{\n\t\t\tServiceID: h.ServiceID,\n\t\t\tPort: h.Port,\n\t\t\tMessageType: \"mysql\",\n\t\t\tKey: v.Key,\n\t\t\tHostName: h.HostName,\n\t\t\tCount: v.Count,\n\t\t\tAbnormalCount: v.UnusualCount,\n\t\t\tAverageTime: Round(avg, 2),\n\t\t\tMaxTime: Round(max, 2),\n\t\t\tCumulativeTime: Round(avg*float64(v.Count), 2),\n\t\t}\n\t\tcaches.Add(&mm)\n\t}\n\tsort.Sort(caches)\n\tif caches.Len() > 20 {\n\t\th.monitorMessageManage.Send(caches.Pop(20))\n\t\treturn\n\t}\n\th.monitorMessageManage.Send(caches)\n}", "func sendErrorResponse(func_name string, w http.ResponseWriter, http_code int, resp_body string, log_message string) {\n\tutils.Log(fmt.Sprintf(\"%s: %s\", func_name, log_message))\n\tw.WriteHeader(http_code)\n\tw.Write([]byte(resp_body))\n\treturn\n}", "func (r *reportErr) report(event *event, message string, err error, errCode string) (response, error) {\n\tm := fmt.Sprintf(\"Unable to complete request; %s error\", message)\n\tr.metricsPublisher.PublishExceptionMetric(time.Now(), string(event.Action), err)\n\treturn newFailedResponse(cfnerr.New(serviceInternalError, m, err), event.BearerToken), err\n}", "func (s *schedule) EnqueueFailure(n uint64, event *event.Event) {\n\ts.n = n\n\ts.event = event\n\tfor i := range s.occurred {\n\t\ts.occurred[i] = false\n\t}\n}", "func (q *Queue) ResetFailed() error {\n\treturn q.redisClient.Del(queueFailedKey(q.Name)).Err()\n}", "func RecordFailure(agentName string, errcode types.CipherError) {\n\tmutex.Lock()\n\tdefer mutex.Unlock()\n\tmaybeInit(agentName)\n\tm := metrics[agentName]\n\tm.FailureCount++\n\tm.LastFailure = time.Now()\n\tm.TypeCounters[errcode]++\n\tmetrics[agentName] = m\n}", "func (c *Client) SendMissedSubscriber(email, name, reference string, campaigns []common.Campaign, address common.Address) error {\n\tmessage := \"Missed out on subscriber. Out of zone.\"\n\tattachment := slack.Attachment{\n\t\tFallback: fmt.Sprintf(\"%s out of zone\", email),\n\t\tTitle: fmt.Sprintf(\"%s - <https://eatgigamunch.com/admin/n/subscriber/%s|%s>\", name, email, email),\n\t\tFields: []slack.AttachmentField{\n\t\t\tslack.AttachmentField{\n\t\t\t\tTitle: \"Email\",\n\t\t\t\tValue: fmt.Sprintf(\"<https://eatgigamunch.com/admin/n/subscriber/%s|%s>\", email, email),\n\t\t\t\tShort: true,\n\t\t\t},\n\t\t\tslack.AttachmentField{\n\t\t\t\tTitle: \"Name\",\n\t\t\t\tValue: name,\n\t\t\t\tShort: true,\n\t\t\t},\n\t\t\tslack.AttachmentField{\n\t\t\t\tTitle: \"Reference\",\n\t\t\t\tValue: reference,\n\t\t\t\tShort: false,\n\t\t\t},\n\t\t\tslack.AttachmentField{\n\t\t\t\tTitle: \"Address\",\n\t\t\t\tValue: address.StringNoAPT(),\n\t\t\t\tShort: false,\n\t\t\t},\n\t\t},\n\t\tColor: \"#F57F17\",\n\t}\n\tfor _, campaign := range campaigns {\n\t\tattachment.Fields = append(attachment.Fields, slack.AttachmentField{\n\t\t\tTitle: \"Campaign\",\n\t\t\tValue: fmt.Sprintf(\"Source: %s\\nMedium: %s\\nCampaign: %s\\n\", campaign.Source, campaign.Medium, campaign.Campaign),\n\t\t\tShort: true,\n\t\t})\n\t}\n\tattachments := []slack.Attachment{\n\t\tattachment,\n\t}\n\n\treturn c.sendAttachmentsMessage(subscriberUpdateChannel, message, attachments)\n}", "func sendReport(s status.Report) error {\n\n\twriteLog(\"DEBUG: Sending report with error length of:\", len(s.Errors))\n\twriteLog(\"DEBUG: Sending report with ok state of:\", s.OK)\n\n\t// marshal the request body\n\tb, err := json.Marshal(s)\n\tif err != nil {\n\t\twriteLog(\"ERROR: Failed to marshal status JSON:\", err)\n\t\treturn fmt.Errorf(\"error mashaling status report json: %w\", err)\n\t}\n\n\t// fetch the server url\n\turl, err := getKuberhealthyURL()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to fetch the kuberhealthy url: %w\", err)\n\t}\n\twriteLog(\"INFO: Using kuberhealthy reporting URL:\", url)\n\n\t// send to the server\n\t// TODO - retry logic? Maybe we want this to be sensitive on a failure...\n\tresp, err := http.Post(url, \"application/json\", bytes.NewBuffer(b))\n\tif err != nil {\n\t\twriteLog(\"ERROR: got an error sending POST to kuberhealthy:\", err.Error())\n\t\treturn fmt.Errorf(\"bad POST request to kuberhealthy status reporting url: %w\", err)\n\t}\n\n\t// make sure we got a 200 and consider it an error otherwise\n\tif resp.StatusCode != http.StatusOK {\n\t\twriteLog(\"ERROR: got a bad status code from kuberhealthy:\", resp.StatusCode, resp.Status)\n\t\treturn fmt.Errorf(\"bad status code from kuberhealthy status reporting url: [%d] %s \", resp.StatusCode, resp.Status)\n\t}\n\twriteLog(\"INFO: Got a good http return status code from kuberhealthy URL:\", url)\n\n\treturn err\n}", "func (s *Sender) SendNoRetry(msg *Message) (*MulticastResult, error) {\n\tif len(msg.RegistrationIds) == 0 {\n\t\treturn nil, errors.New(\"RegistrationIds cannot be empty\")\n\t}\n\tb, err := json.Marshal(msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tres, err := s.post(GCMSendEndpoint, \"application/json\", bytes.NewReader(b))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn res, err\n}", "func (r *Reconciler) fail(instance *gcpv1alpha1.Provider, reason, msg string) (reconcile.Result, error) {\n\tinstance.Status.UnsetAllDeprecatedConditions()\n\tinstance.Status.SetFailed(reason, msg)\n\treturn resultRequeue, r.Update(context.TODO(), instance)\n}", "func (c *Conn) sendInvalidate(msg []byte) error {\n\tswitch err := c.writeToKernel(msg); err {\n\tcase syscall.ENOENT:\n\t\treturn ErrNotCached\n\tdefault:\n\t\treturn err\n\t}\n}", "func (w *Watcher) sendError(err error) bool {\n\tselect {\n\tcase w.Errors <- err:\n\t\treturn true\n\tcase <-w.quit:\n\t}\n\treturn false\n}", "func failed(e error) {\n\tfmt.Println(\"FAILED\")\n\tfmt.Println(\"Details:\", e.Error())\n}" ]
[ "0.66038764", "0.5997243", "0.58393395", "0.5770509", "0.57672864", "0.5630328", "0.55844474", "0.5581725", "0.5542058", "0.55405325", "0.5511217", "0.545069", "0.5447061", "0.5438914", "0.5420753", "0.53787696", "0.5372408", "0.5328645", "0.52515656", "0.5246661", "0.52458334", "0.5231161", "0.52065563", "0.5194794", "0.5184472", "0.51812345", "0.517473", "0.51626307", "0.515572", "0.51535904", "0.5123782", "0.512109", "0.51131105", "0.50931495", "0.50801975", "0.5072898", "0.507164", "0.50679135", "0.5054692", "0.50528175", "0.5052744", "0.50524145", "0.50442564", "0.5044049", "0.50415295", "0.50302744", "0.50241387", "0.50131184", "0.5003681", "0.50026613", "0.5002195", "0.50012654", "0.499865", "0.49935994", "0.49925995", "0.49811164", "0.4980172", "0.49765563", "0.49753696", "0.496345", "0.49585122", "0.4958294", "0.4953431", "0.49478254", "0.4941862", "0.4940815", "0.49315408", "0.4927985", "0.49279422", "0.49214512", "0.49089703", "0.49075267", "0.4902091", "0.4899297", "0.4897607", "0.48961252", "0.48949367", "0.48926538", "0.48830214", "0.48806196", "0.48756623", "0.4873641", "0.4865958", "0.48625496", "0.48588657", "0.48546135", "0.4845358", "0.48444206", "0.48432085", "0.4842254", "0.48360586", "0.4834636", "0.4828773", "0.4824711", "0.48221716", "0.4816575", "0.48122615", "0.48071554", "0.48064563", "0.4792468" ]
0.8125336
0
Status checks the status of the service
func (h HealthController) Status(c *gin.Context) { c.JSON(200, gin.H{ "status": "ok", }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Reconciler) CheckServiceStatus(srv *corev1.Service, status *nbv1.ServiceStatus, portName string) {\n\n\tlog := r.Logger.WithField(\"func\", \"CheckServiceStatus\").WithField(\"service\", srv.Name)\n\t*status = nbv1.ServiceStatus{}\n\tservicePort := nb.FindPortByName(srv, portName)\n\tproto := \"http\"\n\tif strings.HasSuffix(portName, \"https\") {\n\t\tproto = \"https\"\n\t}\n\n\t// Node IP:Port\n\t// Pod IP:Port\n\tpods := corev1.PodList{}\n\tpodsListOptions := &client.ListOptions{\n\t\tNamespace: r.Request.Namespace,\n\t\tLabelSelector: labels.SelectorFromSet(srv.Spec.Selector),\n\t}\n\terr := r.Client.List(r.Ctx, podsListOptions, &pods)\n\tif err == nil {\n\t\tfor _, pod := range pods.Items {\n\t\t\tif pod.Status.Phase == corev1.PodRunning {\n\t\t\t\tif pod.Status.HostIP != \"\" {\n\t\t\t\t\tstatus.NodePorts = append(\n\t\t\t\t\t\tstatus.NodePorts,\n\t\t\t\t\t\tfmt.Sprintf(\"%s://%s:%d\", proto, pod.Status.HostIP, servicePort.NodePort),\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tif pod.Status.PodIP != \"\" {\n\t\t\t\t\tstatus.PodPorts = append(\n\t\t\t\t\t\tstatus.PodPorts,\n\t\t\t\t\t\tfmt.Sprintf(\"%s://%s:%s\", proto, pod.Status.PodIP, servicePort.TargetPort.String()),\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Cluster IP:Port (of the service)\n\tif srv.Spec.ClusterIP != \"\" {\n\t\tstatus.InternalIP = append(\n\t\t\tstatus.InternalIP,\n\t\t\tfmt.Sprintf(\"%s://%s:%d\", proto, srv.Spec.ClusterIP, servicePort.Port),\n\t\t)\n\t\tstatus.InternalDNS = append(\n\t\t\tstatus.InternalDNS,\n\t\t\tfmt.Sprintf(\"%s://%s.%s:%d\", proto, srv.Name, srv.Namespace, servicePort.Port),\n\t\t)\n\t}\n\n\t// LoadBalancer IP:Port (of the service)\n\tif srv.Status.LoadBalancer.Ingress != nil {\n\t\tfor _, lb := range srv.Status.LoadBalancer.Ingress {\n\t\t\tif lb.IP != \"\" {\n\t\t\t\tstatus.ExternalIP = append(\n\t\t\t\t\tstatus.ExternalIP,\n\t\t\t\t\tfmt.Sprintf(\"%s://%s:%d\", proto, lb.IP, servicePort.Port),\n\t\t\t\t)\n\t\t\t}\n\t\t\tif lb.Hostname != \"\" {\n\t\t\t\tstatus.ExternalDNS = append(\n\t\t\t\t\tstatus.ExternalDNS,\n\t\t\t\t\tfmt.Sprintf(\"%s://%s:%d\", proto, lb.Hostname, servicePort.Port),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\t// External IP:Port (of the service)\n\tif srv.Spec.ExternalIPs != nil {\n\t\tfor _, ip := range srv.Spec.ExternalIPs {\n\t\t\tstatus.ExternalIP = append(\n\t\t\t\tstatus.ExternalIP,\n\t\t\t\tfmt.Sprintf(\"%s://%s:%d\", proto, ip, servicePort.Port),\n\t\t\t)\n\t\t}\n\t}\n\n\tlog.Infof(\"Collected addresses: %+v\", status)\n}", "func (client *Client) ServiceStatus(request *ServiceStatusRequest) (response *ServiceStatusResponse, err error) {\nresponse = CreateServiceStatusResponse()\nerr = client.DoAction(request, response)\nreturn\n}", "func Example_checkStatus() {\n\t//Create client.\n\tc := APIClient{\n\t\tClient: client.New(\n\t\t\tfunc(c *client.Client) {\n\t\t\t\tc.User = \"myusername\"\n\t\t\t\tc.Password = \"mypassword\"\n\t\t\t},\n\t\t),\n\t\tBaseUrl: \"https://url.to.publit\",\n\t}\n\n\t// Check if service is up.\n\tok := c.StatusCheck()\n\n\tif !ok {\n\t\tlog.Fatal(\"Service is not up.\")\n\t}\n\n\tlog.Println(\"Service is up!\")\n\n\t// Do something\n}", "func CheckService(client *nomad.Client, opts *CheckServiceOpts) Status {\n\tjobInfo, _, err := client.Jobs().Info(opts.Job, &nomad.QueryOptions{})\n\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), \"404\") {\n\t\t\tprintln(\"job '\", opts.Job, \"' not found\")\n\t\t\treturn CRITICAL\n\t\t}\n\n\t\tprintln(err.Error())\n\t\treturn UNKNOWN\n\t}\n\n\tsummary, _, _ := client.Jobs().Summary(*jobInfo.ID, nil)\n\tdeployment, _, _ := client.Jobs().LatestDeployment(*jobInfo.ID, &nomad.QueryOptions{})\n\n\tif deployment == nil {\n\t\tdeployment = &nomad.Deployment{}\n\t}\n\n\tstatus := OK\n\tprintln(\"status=\" + *jobInfo.Status)\n\n\tif *jobInfo.Status != \"running\" {\n\t\tstatus = CRITICAL\n\t}\n\n\tif *jobInfo.Type != opts.Type {\n\t\tprintln(\"type is not '\" + opts.Type + \"'\")\n\t\tstatus = CRITICAL\n\t}\n\n\tfor key, value := range deployment.TaskGroups {\n\t\trunning := summary.Summary[key].Running\n\t\tdesired := value.DesiredTotal\n\n\t\tif running < desired {\n\t\t\tprintln(key+\".summary.running=\"+strconv.Itoa(running), \"<\", key+\".desiredTotal=\"+strconv.Itoa(desired))\n\t\t\tstatus = CRITICAL\n\t\t} else {\n\t\t\tprintln(key+\".summary.running=\"+strconv.Itoa(running), \">=\", key+\".desiredTotal=\"+strconv.Itoa(desired))\n\t\t}\n\n\t}\n\n\tprintln(createJobLink(client.Address(), *jobInfo.ID))\n\tfor key, value := range jobInfo.Meta {\n\t\tif strings.HasPrefix(key, \"OWNER\") {\n\t\t\tprintln(\"owner=\" + value)\n\t\t}\n\t}\n\n\treturn status\n}", "func (dateService) Status(ctx context.Context) (string, error) {\n\treturn \"ok\", nil\n}", "func ServiceStatus(serviceName string) string {\n\treturn \"\"\n}", "func (fsm *DeployFSMContext) checkServiceReady() (bool, error) {\n\truntime := fsm.Runtime\n\t// do not check if nil for compatibility\n\tif fsm.Deployment.Extra.ServicePhaseStartAt != nil {\n\t\tstartCheckPoint := fsm.Deployment.Extra.ServicePhaseStartAt.Add(30 * time.Second)\n\t\tif time.Now().Before(startCheckPoint) {\n\t\t\tfsm.pushLog(fmt.Sprintf(\"checking too early, delay to: %s\", startCheckPoint.String()))\n\t\t\t// too early to check\n\t\t\treturn false, nil\n\t\t}\n\t}\n\tisReplicasZero := false\n\tfor _, s := range fsm.Spec.Services {\n\t\tif s.Deployments.Replicas == 0 {\n\t\t\tisReplicasZero = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif isReplicasZero {\n\t\tfsm.pushLog(\"checking status by inspect\")\n\t\t// we do double check to prevent `fake Healthy`\n\t\t// runtime.ScheduleName must have\n\t\tsg, err := fsm.getServiceGroup()\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\treturn sg.Status == \"Ready\" || sg.Status == \"Healthy\", nil\n\t}\n\n\t// 获取addon状态\n\tserviceGroup, err := fsm.getServiceGroup()\n\tif err != nil {\n\t\tfsm.pushLog(fmt.Sprintf(\"获取service状态失败,%s\", err.Error()))\n\t\treturn false, nil\n\t}\n\tfsm.pushLog(fmt.Sprintf(\"checking status: %s, servicegroup: %v\", serviceGroup.Status, runtime.ScheduleName))\n\t// 如果状态是failed,说明服务或者job运行失败\n\tif serviceGroup.Status == apistructs.StatusFailed {\n\t\treturn false, errors.New(serviceGroup.LastMessage)\n\t}\n\t// 如果状态是ready或者healthy,说明服务已经发起来了\n\truntimeStatus := apistructs.RuntimeStatusUnHealthy\n\tif serviceGroup.Status == apistructs.StatusReady || serviceGroup.Status == apistructs.StatusHealthy {\n\t\truntimeStatus = apistructs.RuntimeStatusHealthy\n\t}\n\truntimeItem := fsm.Runtime\n\tif runtimeItem.Status != runtimeStatus {\n\t\truntimeItem.Status = runtimeStatus\n\t\tif err := fsm.db.UpdateRuntime(runtime); err != nil {\n\t\t\tlogrus.Errorf(\"failed to update runtime status changed, runtime: %v, err: %v\", runtime.ID, err.Error())\n\t\t\treturn false, nil\n\t\t}\n\t}\n\tif runtimeStatus == apistructs.RuntimeStatusHealthy {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}", "func (ac *ApiConfig) CheckStatus(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != http.MethodGet {\n\t\thttp.Error(w, r.Method+\" is not available\", http.StatusInternalServerError)\n\t\tzerolog.Error().Msg(r.Method + \" is not available\")\n\t\treturn\n\t}\n\n\tstat := &models.StatusIdentifier{\n\t\tOk: true,\n\t\tMessage: \"Everything is alright\",\n\t}\n\n\terr := dResponseWriter(w, stat, http.StatusOK)\n\tif err != nil {\n\t\tzerolog.Error().Msg(err.Error())\n\t\treturn\n\t}\n\n\treturn\n}", "func (s *Service) CheckStatus() bool {\n\t_, err := exec.Command(SERVICE, s.name, STATUS).Output()\n\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (s *taskService) checkBasicStatus(c context.Context, date time.Time) (ok bool, err error) {\n\treturn s.dp.SendBasicDataRequest(c, fmt.Sprintf(\"{\\\"select\\\": [], \\\"where\\\":{\\\"job_name\\\":{\\\"in\\\":[\\\"ucs_%s\\\"]}}}\", date.Format(\"20060102\")))\n}", "func (c *Client) Status() error {\n\tclient, err := c.client(false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trel, err := url.Parse(\"status\")\n\tif err != nil {\n\t\t// This indicates a programming error.\n\t\tpanic(err)\n\t}\n\n\tresp, err := client.Get(c.baseURL.ResolveReference(rel).String())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusNoContent {\n\t\treturn ErrInvalidServiceBehavior\n\t}\n\treturn nil\n}", "func getServiceCheckStatus(state string, mapping map[string]string) servicecheck.ServiceCheckStatus {\n\tswitch mapping[state] {\n\tcase \"ok\":\n\t\treturn servicecheck.ServiceCheckOK\n\tcase \"warning\":\n\t\treturn servicecheck.ServiceCheckWarning\n\tcase \"critical\":\n\t\treturn servicecheck.ServiceCheckCritical\n\t}\n\treturn servicecheck.ServiceCheckUnknown\n}", "func (s *Server) Check(ctx context.Context, in *grpc_health_v1.HealthCheckRequest) (*grpc_health_v1.HealthCheckResponse, error) {\n\tresp := &grpc_health_v1.HealthCheckResponse{}\n\tif len(in.Service) == 0 || in.Service == serviceName {\n\t\tresp.Status = grpc_health_v1.HealthCheckResponse_SERVING\n\t}\n\treturn resp, nil\n}", "func (c *QueueController) checkAndUpdateServiceHealth(exitCode errors.ExitCode) {\n\tvar svcStatusErr error\n\tmarkUnhealthy := false\n\tif c.isCriticalError(exitCode) {\n\t\tsvcStatusErr = fmt.Errorf(\"critical error (%d) occurred. Marking worker unhealthy\", exitCode)\n\t\tmarkUnhealthy = true\n\t}\n\tif c.isPersistentError(exitCode) {\n\t\tsvcStatusErr = fmt.Errorf(\"errors (%d) occurred multiple times in a row. Marking worker unhealthy\", exitCode)\n\t\tmarkUnhealthy = true\n\t}\n\tif markUnhealthy {\n\t\tsvcStatus := c.statusManager.svcStatus\n\t\tsvcStatus.IsHealthy = false\n\t\tsvcStatus.Error = svcStatusErr\n\t\tc.statusManager.UpdateService(svcStatus)\n\t\tc.inv.stat.Gauge(stats.WorkerUnhealthy).Update(1)\n\t}\n}", "func (avisess *AviSession) CheckControllerStatus() (bool, *http.Response, error) {\n\turl := avisess.prefix + \"/api/cluster/status\"\n\tvar isControllerUp bool\n\tfor round := 0; round < avisess.ctrlStatusCheckRetryCount; round++ {\n\t\tcheckReq, err := http.NewRequest(\"GET\", url, nil)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"CheckControllerStatus Error %v while generating http request.\", err)\n\t\t\treturn false, nil, err\n\t\t}\n\t\t//Getting response from controller's API\n\t\tif stateResp, err := avisess.client.Do(checkReq); err == nil {\n\t\t\tdefer stateResp.Body.Close()\n\t\t\t//Checking controller response\n\t\t\tif stateResp.StatusCode != 503 && stateResp.StatusCode != 502 && stateResp.StatusCode != 500 {\n\t\t\t\tisControllerUp = true\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tglog.Infof(\"CheckControllerStatus Error while generating http request %d %v\",\n\t\t\t\t\tstateResp.StatusCode, err)\n\t\t\t}\n\t\t} else {\n\t\t\tglog.Errorf(\"CheckControllerStatus Error while generating http request %v %v\", url, err)\n\t\t}\n\t\t// if controller status check interval is not set during client init, use the default SDK\n\t\t// behaviour.\n\t\tif avisess.ctrlStatusCheckRetryInterval == 0 {\n\t\t\ttime.Sleep(getMinTimeDuration((time.Duration(math.Exp(float64(round))*3) * time.Second), (time.Duration(30) * time.Second)))\n\t\t} else {\n\t\t\t// controller status will be polled at intervals specified during client init.\n\t\t\ttime.Sleep(time.Duration(avisess.ctrlStatusCheckRetryInterval) * time.Second)\n\t\t}\n\t\tglog.Errorf(\"CheckControllerStatus Controller %v Retrying. round %v..!\", url, round)\n\t}\n\treturn isControllerUp, &http.Response{Status: \"408 Request Timeout\", StatusCode: 408}, nil\n}", "func (c *Client) Status(ctx context.Context) error {\n\treturn c.PingContext(ctx)\n}", "func (jj *Juju) Status(user, service string) (*simplejson.Json, error) {\n //TODO Without id, should return every services matching {user}-*, not everything\n id := jj.id(user, service)\n args := []string{\"status\", \"--format\", \"json\"}\n if service != \"\" {\n args = append(args, id)\n }\n log.Infof(\"fetch juju status (%s)\\n\", id)\n\n cmd := exec.Command(\"juju\", args...)\n output, err := cmd.CombinedOutput()\n if err != nil {\n return EmptyJSON(), err\n }\n log.Debugf(\"successful request: %v\\n\", string(output))\n\n jsonOutput, err := simplejson.NewJson(output)\n if err != nil {\n return EmptyJSON(), err\n }\n\n mapping, _ := vmSshForward(user, jj.Controller, jsonOutput)\n jsonOutput.Set(\"ssh-port\", mapping)\n\n return jsonOutput, err\n}", "func checkStatus() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tc.JSON(http.StatusOK, \"Server is running successfully !!!!!\")\n\t}\n}", "func checkServiceRequestStatus(config Config, requestID string) (string, string, error) {\n\n\turl := \"api/service_requests/\" + requestID\n\trequest, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\tlog.Printf(\"[ERROR] Error in creating http Request %s\", err)\n\t\treturn \"\", \"\", fmt.Errorf(\"[ERROR] Error in creating http Request %s\", err)\n\t}\n\tresponse, err := config.GetResponse(request)\n\tif err != nil {\n\t\tlog.Printf(\"[ERROR] Error in getting response %s\", err)\n\t\treturn \"\", \"\", fmt.Errorf(\"[ERROR] Error in getting response %s\", err)\n\t}\n\n\tdata := string(response)\n\t// get request status\n\tstatusFromResult := gjson.Get(data, \"status\")\n\tstatus := statusFromResult.String()\n\n\t// get request_state\n\trequestStateFromResult := gjson.Get(data, \"request_state\")\n\trequestState := requestStateFromResult.String()\n\n\treturn status, requestState, nil\n}", "func CheckStatus(w http.ResponseWriter, r *http.Request) {\n\tjson.NewEncoder(w).Encode(Status{Message : \"Alive\"})\n}", "func (a *Api) Status(w http.ResponseWriter, r *http.Request) error {\n\treturn nil\n}", "func checkStatus() error {\n\tif kvstoreEnabled() {\n\t\tif client := kvstore.Client(); client == nil {\n\t\t\treturn fmt.Errorf(\"kvstore client not configured\")\n\t\t} else if _, err := client.Status(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif _, err := k8s.Client().Discovery().ServerVersion(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Status(expected int) echo.Checker {\n\texpectedStr := \"\"\n\tif expected > 0 {\n\t\texpectedStr = strconv.Itoa(expected)\n\t}\n\treturn Each(func(r echoClient.Response) error {\n\t\tif r.Code != expectedStr {\n\t\t\treturn fmt.Errorf(\"expected response code `%s`, got %q. Response: %s\", expectedStr, r.Code, r)\n\t\t}\n\t\treturn nil\n\t})\n}", "func (s *Shell) Status(_ *cli.Context) error {\n\tresp, err := s.HTTP.Get(\"/health?full=1\", nil)\n\tif err != nil {\n\t\treturn s.errorOut(err)\n\t}\n\tdefer func() {\n\t\tif cerr := resp.Body.Close(); cerr != nil {\n\t\t\terr = multierr.Append(err, cerr)\n\t\t}\n\t}()\n\n\treturn s.renderAPIResponse(resp, &HealthCheckPresenters{})\n}", "func (env *Env) getServiceStatus(w http.ResponseWriter, r *http.Request) (error, int) {\n\tserviceName, err := httputil.ParseQuery(r, \"serviceName\")\n\tif err != nil {\n\t\treturn err, http.StatusBadRequest\n\t}\n\n\tserviceStatus, err := env.serviceRepo.GetServiceStatus(serviceName)\n\tif err != nil {\n\t\treturn err, http.StatusInternalServerError\n\t}\n\treturn httputil.SendJSON(w, serviceStatus)\n}", "func (_SmartTgStats *SmartTgStatsCaller) Status(opts *bind.CallOpts) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _SmartTgStats.contract.Call(opts, out, \"status\")\n\treturn *ret0, err\n}", "func Status() error {\n\treturn err\n}", "func status(cmd *cobra.Command, _ []string) error {\n\tif err := daemonStatus(cmd); err != nil {\n\t\treturn err\n\t}\n\n\tif err := connectorStatus(cmd); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func checkStatus(currentStatus, wantedStatus int8) (err error) {\n\tswitch currentStatus {\n\tcase constant.RUNNING_STATUS_PREPARING:\n\t\terr = ErrSchedulerBeingInitilated\n\tcase constant.RUNNING_STATUS_STARTING:\n\t\terr = ErrSchedulerBeingStarted\n\tcase constant.RUNNING_STATUS_STOPPING:\n\t\terr = ErrSchedulerBeingStopped\n\tcase constant.RUNNING_STATUS_PAUSING:\n\t\terr = ErrSchedulerBeingPaused\n\t}\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif currentStatus == constant.RUNNING_STATUS_UNPREPARED &&\n\t\twantedStatus != constant.RUNNING_STATUS_PREPARING {\n\t\terr = ErrSchedulerNotInitialized\n\t\treturn\n\t}\n\n\tif currentStatus == constant.RUNNING_STATUS_STOPPED {\n\t\terr = ErrSchedulerStopped\n\t\treturn\n\t}\n\n\tswitch wantedStatus {\n\tcase constant.RUNNING_STATUS_PREPARING:\n\t\tif currentStatus != constant.RUNNING_STATUS_UNPREPARED {\n\t\t\terr = ErrSchedulerInitialized\n\t\t}\n\tcase constant.RUNNING_STATUS_STARTING:\n\t\tif currentStatus != constant.RUNNING_STATUS_PREPARED {\n\t\t\terr = ErrSchedulerStarted\n\t\t}\n\tcase constant.RUNNING_STATUS_PAUSING:\n\t\tif currentStatus != constant.RUNNING_STATUS_STARTED {\n\t\t\terr = ErrSchedulerNotStarted\n\t\t}\n\tcase constant.RUNNING_STATUS_STOPPING:\n\t\tif currentStatus != constant.RUNNING_STATUS_STARTED &&\n\t\t\tcurrentStatus != constant.RUNNING_STATUS_PAUSED {\n\t\t\terr = ErrSchedulerNotStarted\n\t\t}\n\tdefault:\n\t\terr = ErrStatusUnsupported\n\t}\n\treturn\n}", "func (s *svc) Status() router.Status {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\t// check if its stopped\n\tselect {\n\tcase <-s.exit:\n\t\treturn router.Status{\n\t\t\tCode: router.Stopped,\n\t\t\tError: nil,\n\t\t}\n\tdefault:\n\t\t// don't block\n\t}\n\n\t// check the remote router\n\trsp, err := s.router.Status(context.Background(), &pb.Request{}, s.callOpts...)\n\tif err != nil {\n\t\treturn router.Status{\n\t\t\tCode: router.Error,\n\t\t\tError: err,\n\t\t}\n\t}\n\n\tcode := router.Running\n\tvar serr error\n\n\tswitch rsp.Status.Code {\n\tcase \"running\":\n\t\tcode = router.Running\n\tcase \"advertising\":\n\t\tcode = router.Advertising\n\tcase \"stopped\":\n\t\tcode = router.Stopped\n\tcase \"error\":\n\t\tcode = router.Error\n\t}\n\n\tif len(rsp.Status.Error) > 0 {\n\t\tserr = errors.New(rsp.Status.Error)\n\t}\n\n\treturn router.Status{\n\t\tCode: code,\n\t\tError: serr,\n\t}\n}", "func (c *Collection) Status(w http.ResponseWriter, req *http.Request) {\n\t// responds with current status of the analysis\n\t// checks systemtap is running, this is probably done via global variable?\n}", "func (ds *dockerService) Status(_ context.Context, r *runtimeapi.StatusRequest) (*runtimeapi.StatusResponse, error) {\n\truntimeReady := &runtimeapi.RuntimeCondition{\n\t\tType: runtimeapi.RuntimeReady,\n\t\tStatus: true,\n\t}\n\tnetworkReady := &runtimeapi.RuntimeCondition{\n\t\tType: runtimeapi.NetworkReady,\n\t\tStatus: true,\n\t}\n\tconditions := []*runtimeapi.RuntimeCondition{runtimeReady, networkReady}\n\tif _, err := ds.client.Version(); err != nil {\n\t\truntimeReady.Status = false\n\t\truntimeReady.Reason = \"DockerDaemonNotReady\"\n\t\truntimeReady.Message = fmt.Sprintf(\"docker: failed to get docker version: %v\", err)\n\t}\n\n\tstatus := &runtimeapi.RuntimeStatus{Conditions: conditions}\n\treturn &runtimeapi.StatusResponse{Status: status}, nil\n}", "func (p *Plugin) Status(ctx context.Context, in *plugin.StatusRequest) (*plugin.StatusResponse, error) {\n\terr := p.Service.Status(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &plugin.StatusResponse{}, nil\n}", "func (s *SystemService) Status() (status *ServiceStatus, err error) {\n\tname := s.Command.Name\n\tstatus = &ServiceStatus{}\n\n\tlogger.Log(\"connecting to service manager: \", name)\n\n\t// Connect to Windows service manager\n\tm, err := mgr.Connect()\n\tif err != nil {\n\t\tlogger.Log(\"error connecting to service manager: \", err)\n\t\treturn status, fmt.Errorf(\"could not connect to service manager: %v\", err)\n\t}\n\tdefer m.Disconnect()\n\n\tlogger.Log(\"opening system service\")\n\n\t// Open the service so we can manage it\n\tsrv, err := m.OpenService(name)\n\tif err != nil {\n\t\tlogger.Log(\"error opening service: \", err)\n\t\treturn status, fmt.Errorf(\"could not access service: %v\", err)\n\t}\n\tdefer srv.Close()\n\n\tstat, err := srv.Query()\n\tif err != nil {\n\t\tlogger.Log(\"error getting service status: \", err)\n\t\treturn status, fmt.Errorf(\"could not get service status: %v\", err)\n\t}\n\n\tlogger.Logf(\"service status: %#v\", stat)\n\n\tstatus.PID = int(stat.ProcessId)\n\tstatus.Running = stat.State == svc.Running\n\treturn status, nil\n}", "func checkrequestStatus(d *schema.ResourceData, config Config, requestID string, timeOut int) error {\n\ttimeout := time.After(time.Duration(timeOut) * time.Second)\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(1 * time.Second):\n\t\t\tstatus, state, err := checkServiceRequestStatus(config, requestID)\n\t\t\tif err == nil {\n\t\t\t\tif state == \"finished\" && status == \"Ok\" {\n\t\t\t\t\tlog.Println(\"[DEBUG] Service order added SUCCESSFULLY\")\n\t\t\t\t\td.SetId(requestID)\n\t\t\t\t\treturn nil\n\t\t\t\t} else if status == \"Error\" {\n\t\t\t\t\tlog.Println(\"[ERROR] Failed\")\n\t\t\t\t\treturn fmt.Errorf(\"[Error] Failed execution\")\n\t\t\t\t} else {\n\t\t\t\t\tlog.Println(\"[DEBUG] Request state is :\", state)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase <-timeout:\n\t\t\tlog.Println(\"[DEBUG] Timeout occured\")\n\t\t\treturn fmt.Errorf(\"[ERROR] Timeout\")\n\t\t}\n\t}\n}", "func (adm *AdminClient) ServiceStatus() (ServiceStatusMetadata, error) {\n\n\t// Prepare web service request\n\treqData := requestData{}\n\treqData.queryValues = make(url.Values)\n\treqData.queryValues.Set(\"service\", \"\")\n\treqData.customHeaders = make(http.Header)\n\treqData.customHeaders.Set(minioAdminOpHeader, \"status\")\n\n\t// Execute GET on bucket to list objects.\n\tresp, err := adm.executeMethod(\"GET\", reqData)\n\tdefer closeResponse(resp)\n\tif err != nil {\n\t\treturn ServiceStatusMetadata{}, err\n\t}\n\n\t// Check response http status code\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn ServiceStatusMetadata{}, httpRespToErrorResponse(resp)\n\t}\n\n\t// Unmarshal the server's json response\n\tvar serviceStatus ServiceStatusMetadata\n\n\trespBytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn ServiceStatusMetadata{}, err\n\t}\n\n\terr = json.Unmarshal(respBytes, &serviceStatus)\n\tif err != nil {\n\t\treturn ServiceStatusMetadata{}, err\n\t}\n\n\treturn serviceStatus, nil\n}", "func CheckAliveStatus(devs DevsResponse, name string) {\n\tfor i := 0; i < len(devs.Devs); i++ {\n\t\tvar dev = &devs.Devs[i]\n\t\tif dev.Status != \"Alive\" {\n\t\t\t//Send the restart command\n\t\t\tlog.Printf(\"Dev #%s on %s got %s status so sending restart command\\n\", dev.GPU, name, dev.Status)\n\t\t\trestartMiner(name)\n\t\t}\n\t}\n}", "func (f *FakeTunnel) CheckStatus() error {\n\treturn nil\n}", "func CheckStatus(uri string) error {\n\tvar err error\n\tvar S Status\n\n\tresp, err := http.Get(uri)\n\tif err != nil {\n\t\terror2.LogError(err)\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\t_ = resp.Body.Close()\n\t}()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tjsonUnmarshalErr := json.Unmarshal(body, S)\n\tif err == nil && jsonUnmarshalErr == nil && S.Status == \"ok\" {\n\t\treturn nil\n\t}\n\n\terr = errors.New(\"unable to complete status request\")\n\terror2.LogError(err)\n\treturn err\n}", "func (r *ManagedServiceGetResponse) Status() int {\n\tif r == nil {\n\t\treturn 0\n\t}\n\treturn r.status\n}", "func (h Handler) Status(w http.ResponseWriter, r *http.Request) {\n\tresponses := h.healthchecker.Status()\n\tfor _, r := range responses {\n\t\tif r.Error != nil {\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n}", "func (c *cephStatusChecker) checkStatus() {\n\tlogger.Debugf(\"checking health of cluster\")\n\tstatus, err := client.Status(c.context, c.namespace, true)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to get ceph status. %+v\", err)\n\t\treturn\n\t}\n\n\tlogger.Debugf(\"Cluster status: %+v\", status)\n\tif err := c.updateCephStatus(&status); err != nil {\n\t\tlogger.Errorf(\"failed to query cluster status in namespace %s\", c.namespace)\n\t}\n}", "func Status(args ...string) {\n runInstances(\"Status\", func(i int, id string) error {\n on := running()\n logger.Log(fmt.Sprintf(\"Container ID: %s\\n\", id))\n logger.Log(fmt.Sprintf(\" Running: %s\\n\", strconv.FormatBool(on)))\n\n if on {\n net := networkSettings(i)\n logger.Log(fmt.Sprintf(\" IP: %s\\n\", net.Ip))\n logger.Log(fmt.Sprintf(\" Public Port: %s\\n\", net.Public.tcp))\n logger.Log(fmt.Sprintf(\"Private Port: %s\\n\", net.Private.tcp))\n }\n\n return nil\n })\n}", "func TestServiceStatusHandler(t *testing.T) {\n\ttestServicesCmdHandler(statusCmd, t)\n}", "func GetStatus(\n\tprincipal savedstate.Principal,\n\titself string,\n\ttmpDir string,\n\ttimeout time.Duration,\n\tlogger *structlog.Logger,\n) (statusType, statusType) {\n\tstatus := getStatus(principal.ID)\n\tif status < StatusUpdated || status == StatusReady {\n\t\treturn StatusReady, status\n\t}\n\n\tclusterName := principal.Sess.Name + \".\" + principal.Sess.Domain\n\tif strings.HasSuffix(clusterName, \".\") {\n\t\tclusterName = clusterName[:len(clusterName)-1]\n\t}\n\tapiHost := \"api.\" + clusterName\n\n\tres, err := net.LookupHost(apiHost)\n\tif err != nil {\n\t\tlogger.Debug(\"Kubernetes API host has not domain resolve\", \"Host\", apiHost)\n\t\treturn StatusReady, status\n\t}\n\tlogger.Debug(\"Kubernetes API host resolved to\", res)\n\n\thomeDir := filepath.Join(tmpDir, principal.ID)\n\n\t// Validate //////////////////////////////////////////////////////////////\n\tcmdParams := []string{\n\t\t\"--kopsValidate\",\n\t\tfmt.Sprintf(\"--name=%v\", clusterName),\n\t\tfmt.Sprintf(\"--state=s3://%v\", principal.Sess.Bucket),\n\t\tfmt.Sprintf(\"--timeout=%v\", timeout),\n\t}\n\n\tlogger.Debug(\"Calling Kops validate\", \"params\", cmdParams)\n\n\tcmd := exec.Command(itself, cmdParams...) // #nosec\n\tcmd.Env = []string{\n\t\tfmt.Sprintf(\"HOME=%v\", homeDir),\n\t\t// ToDo: replace with file in $HOME\n\t\tfmt.Sprintf(\"AWS_ACCESS_KEY=%v\", principal.Sess.AccessKey),\n\t\tfmt.Sprintf(\"AWS_SECRET_KEY=%v\", principal.Sess.SecretKey),\n\t}\n\n\tcmdOut, err := cmd.CombinedOutput()\n\n\tif err != nil {\n\t\tlogger.PrintErr(\"Kops validate failed\", \"err\", err, \"out\", string(cmdOut))\n\t\treturn StatusReady, status\n\t}\n\n\tlogger.Debug(\"Kops validate done\", \"out\", string(cmdOut))\n\n\tif !readyRegexp.Match(cmdOut) {\n\t\tlogger.Debug(\"Cluster is not ready yet\", \"total\", StatusReady, \"current\", status)\n\t\treturn StatusReady, status\n\t}\n\n\tsetStatus(principal.ID, StatusReady)\n\n\tlogger.Info(\"Cluster ready\")\n\n\treturn StatusReady, StatusReady\n}", "func (self *client) GetStatus() {\n\n}", "func GetStatus(cfg *Config) Status {\n\tnow := time.Now().Unix()\n\n\ts := Status{\n\t\tPID: os.Getpid(),\n\t\tService: \"list-service\",\n\t}\n\n\ts.Status = \"ok\"\n\ts.Version = Version()\n\ts.CPUs = runtime.NumCPU()\n\ts.GoVers = runtime.Version()\n\ts.TimeStamp = now\n\ts.UpTime = now - InstanceStartTime\n\ts.LogLevel = log.GetLevel()\n\n\tif host, err := os.Hostname(); err == nil {\n\t\ts.Hostname = host\n\t}\n\n\treturn s\n}", "func RunStatus(cmd *cobra.Command, args []string) {\n\tc := LoadOperatorConf(cmd)\n\tLoadAdmissionConf(c)\n\tutil.KubeCheck(c.NS)\n\tif util.KubeCheck(c.SA) && util.KubeCheck(c.SAEndpoint) {\n\t\t// in OLM deployment the roles and bindings have generated names\n\t\t// so we list and lookup bindings to our service account to discover the actual names\n\t\tDetectRole(c)\n\t\tDetectClusterRole(c)\n\t}\n\tutil.KubeCheck(c.Role)\n\tutil.KubeCheck(c.RoleBinding)\n\tutil.KubeCheck(c.RoleEndpoint)\n\tutil.KubeCheck(c.RoleBindingEndpoint)\n\tutil.KubeCheck(c.ClusterRole)\n\tutil.KubeCheck(c.ClusterRoleBinding)\n\tutil.KubeCheckOptional(c.WebhookConfiguration)\n\tutil.KubeCheckOptional(c.WebhookSecret)\n\tutil.KubeCheckOptional(c.WebhookService)\n\tnoDeploy, _ := cmd.Flags().GetBool(\"no-deploy\")\n\tif !noDeploy {\n\t\tutil.KubeCheck(c.Deployment)\n\t}\n}", "func (sry *Sryun) Status(user *model.User, repo *model.Repo, build *model.Build, link string) error {\n\treturn nil\n}", "func statusCheck(w http.ResponseWriter, r *http.Request) {\n\tLog.Printf(\"/status\")\n\tproxiStatus.IndexSize = repo.GetIndexSize()\n\tstatus,_ := json.Marshal(proxiStatus)\n\tio.WriteString(w, string(status))\n}", "func (dstv Dstv) Status(serialNumber string) (*StatusResponse, error) {\n\tdstv.AddQueryData(paymenex.PActId, \"STATUS\")\n\tdstv.AddQueryData(paymenex.PSerialNumber, serialNumber)\n\txml, err := dstv.MakeRequest()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// writeFile(\"status.xml\", xml) // DEBUG\n\tresponse := new(StatusResponse)\n\tok := dstv.ParseAndVerifyResponse(xml, response)\n\tif !ok {\n\t\treturn response, errors.New(errVerifyMsg)\n\t}\n\treturn response, nil\n}", "func StatusCheck(ctx context.Context, db *DB) error {\n\tctx, span := otel.Tracer(\"database\").Start(ctx, \"foundation.database.statuscheck\")\n\tdefer span.End()\n\n\t// First check we can ping the database.\n\tvar pingError error\n\tfor attempts := 1; ; attempts++ {\n\t\tpingError = db.Ping(ctx)\n\t\tif pingError == nil {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(time.Duration(attempts) * 100 * time.Millisecond)\n\t\tif ctx.Err() != nil {\n\t\t\treturn ctx.Err()\n\t\t}\n\t}\n\n\t// Make sure we didn't timeout or be cancelled.\n\tif ctx.Err() != nil {\n\t\treturn ctx.Err()\n\t}\n\n\t// Run a simple query to determine connectivity. Running this query forces\n\t// a round trip to the database.\n\tconst q = `SELECT true`\n\tvar tmp bool\n\treturn db.QueryRow(ctx, q).Scan(&tmp)\n}", "func (b *baseSysInit) Status(svcName string) (Status, error) {\n\tb.StatusCmd.AppendArgs(sysInitCmdArgs(b.sysInitType, svcName, \"status\")...)\n\tstatus, err := b.StatusCmd.RunCombined()\n\tif err != nil {\n\t\treturn Unknown, err\n\t}\n\tswitch {\n\tcase strings.Contains(status, svcStatusOut[\"running\"][b.sysInitType]):\n\t\treturn Running, nil\n\tcase strings.Contains(status, svcStatusOut[\"stopped\"][b.sysInitType]):\n\t\treturn Stopped, nil\n\t}\n\treturn Unknown, fmt.Errorf(\"Unable to determine %s status\", svcName)\n}", "func Status(status string) error {\n\treturn SdNotify(\"STATUS=\" + status)\n}", "func vgStatusCheck(id string, powerClient *v.IBMPIVolumeGroupClient) {\n\tfor start := time.Now(); time.Since(start) < time.Second*30; {\n\t\ttime.Sleep(10 * time.Second)\n\t\tvg, err := powerClient.GetDetails(id)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tif vg.Status == \"available\" {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (i IDology) CheckStatus(referenceID string) (res common.KYCResult, err error) {\n\terr = errors.New(\"IDology doesn't support a verification status check\")\n\treturn\n}", "func (s *Service) Status(ctx context.Context) *sdk.MonitoringStatus {\n\treturn s.NewMonitoringStatus()\n}", "func getStatus(pods []*v1.Pod) (succeeded, failed int32) {\n\tsucceeded = int32(filterPods(pods, v1.PodSucceeded))\n\tfailed = int32(filterPods(pods, v1.PodFailed))\n\treturn\n}", "func (h HealthController) Status(c *gin.Context) {\n\tc.String(http.StatusOK, \"Working!\")\n}", "func (s *TiFlashSpec) Status(ctx context.Context, timeout time.Duration, tlsCfg *tls.Config, pdList ...string) string {\n\tstoreAddr := utils.JoinHostPort(s.Host, s.FlashServicePort)\n\tstate := checkStoreStatus(ctx, storeAddr, tlsCfg, pdList...)\n\tif s.Offline && strings.ToLower(state) == \"offline\" {\n\t\tstate = \"Pending Offline\" // avoid misleading\n\t}\n\treturn state\n}", "func CheckServerStatus(sConf *genconf.ServerConf) error {\n\tsList := make([]string, 0)\n\tfor _, sv := range sConf.Adapters {\n\t\tsList = append(sList, sv.Endpoint)\n\t}\n\tsList = append(sList, sConf.LocalEndpoint)\n\tfor _, sv := range sList {\n\t\tnetwork, host, port := \"\", \"\", \"\"\n\t\tarr := strings.Fields(sv)\n\t\tfor i := range arr {\n\t\t\tif i == 0 {\n\t\t\t\tnetwork = arr[0]\n\t\t\t} else if arr[i] == \"-h\" && i+1 < len(arr) {\n\t\t\t\thost = arr[i+1]\n\t\t\t} else if arr[i] == \"-p\" && i+1 < len(arr) {\n\t\t\t\tport = arr[i+1]\n\t\t\t}\n\t\t}\n\t\tif network == \"\" || host == \"\" || port == \"\" {\n\t\t\treturn fmt.Errorf(\"host/port or network can not be empty\")\n\t\t}\n\t\tif err := checkAddr(network, host+\":\"+port); err != nil {\n\t\t\treturn fmt.Errorf(\"Connect failed %s:%v\", sv, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (api *API) Status(request *restful.Request, response *restful.Response) {\n\tresponse.WriteHeader(http.StatusOK)\n}", "func (s *Server) HandleGetServicesStatus() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer utils.CloseTheCloser(r.Body)\n\n\t\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\t\tdefer cancel()\n\n\t\t// Verify token\n\t\t_, err := s.auth.VerifyToken(utils.GetToken(r))\n\t\tif err != nil {\n\t\t\t_ = helpers.Logger.LogError(helpers.GetRequestID(ctx), \"Failed to apply service\", err, nil)\n\t\t\t_ = helpers.Response.SendErrorResponse(ctx, w, http.StatusUnauthorized, err)\n\t\t\treturn\n\t\t}\n\n\t\t// var result []interface{}\n\t\tvars := mux.Vars(r)\n\t\tprojectID := vars[\"project\"]\n\t\tserviceID, serviceIDExists := r.URL.Query()[\"serviceId\"]\n\t\tversion, versionExists := r.URL.Query()[\"version\"]\n\n\t\tresult, err := s.driver.GetServiceStatus(ctx, projectID)\n\t\tif err != nil {\n\t\t\t_ = helpers.Logger.LogError(helpers.GetRequestID(ctx), \"Failed to get service status\", err, nil)\n\t\t\t_ = helpers.Response.SendErrorResponse(ctx, w, http.StatusUnauthorized, err)\n\t\t\treturn\n\t\t}\n\n\t\tarr := make([]interface{}, 0)\n\t\tif serviceIDExists && versionExists {\n\t\t\tfor _, serviceStatus := range result {\n\t\t\t\tif serviceStatus.ServiceID == serviceID[0] && serviceStatus.Version == version[0] {\n\t\t\t\t\tarr = append(arr, serviceStatus)\n\t\t\t\t}\n\t\t\t}\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t_ = json.NewEncoder(w).Encode(model.Response{Result: arr})\n\t\t\treturn\n\t\t}\n\n\t\tif serviceIDExists {\n\t\t\tfor _, serviceStatus := range result {\n\t\t\t\tif serviceStatus.ServiceID == serviceID[0] {\n\t\t\t\t\tarr = append(arr, serviceStatus)\n\t\t\t\t}\n\t\t\t}\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t_ = json.NewEncoder(w).Encode(model.Response{Result: arr})\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\t_ = json.NewEncoder(w).Encode(model.Response{Result: result})\n\t}\n}", "func (manager *NetworkPolicyManager) CheckUpdatedService(serv, prev *core_v1.Service) {\n\tlogger.Infof(\"[Network Policies Manager](CheckUpdatedService) Service %s has been updated. Going to check for policies...\", serv.Name)\n\tmanager.checkService(serv, \"update\")\n}", "func (o LookupServiceResultOutput) Status() ServiceStatusResponseOutput {\n\treturn o.ApplyT(func(v LookupServiceResult) ServiceStatusResponse { return v.Status }).(ServiceStatusResponseOutput)\n}", "func GetStatusOfSomeService(serviceName string) *service.Status {\n\tsrv := service.NewDefaultService(serviceName)\n\tstatus, _ := srv.Status()\n\treturn status\n}", "func (s *Service) Status(ctx context.Context) *sdk.MonitoringStatus {\n\tm := s.NewMonitoringStatus()\n\n\tif !s.Cfg.EnableLogProcessing {\n\t\treturn m\n\t}\n\tdb := s.mustDBWithCtx(ctx)\n\n\tnbCompleted, err := storage.CountItemCompleted(db)\n\tm.AddLine(addMonitoringLine(nbCompleted, \"items/completed\", err, sdk.MonitoringStatusOK))\n\n\tnbIncoming, err := storage.CountItemIncoming(db)\n\tm.AddLine(addMonitoringLine(nbIncoming, \"items/incoming\", err, sdk.MonitoringStatusOK))\n\n\tm.AddLine(s.LogCache.Status(ctx)...)\n\tm.AddLine(s.getStatusSyncLogs()...)\n\n\tfor _, st := range s.Units.Storages {\n\t\tm.AddLine(st.Status(ctx)...)\n\t\tsize, err := storage.CountItemUnitByUnit(db, st.ID())\n\t\tif nbCompleted-size >= 100 {\n\t\t\tm.AddLine(addMonitoringLine(size, \"backend/\"+st.Name()+\"/items\", err, sdk.MonitoringStatusWarn))\n\t\t} else {\n\t\t\tm.AddLine(addMonitoringLine(size, \"backend/\"+st.Name()+\"/items\", err, sdk.MonitoringStatusOK))\n\t\t}\n\t}\n\n\tm.AddLine(s.DBConnectionFactory.Status(ctx))\n\n\treturn m\n}", "func (m *hostConfiguredContainer) Status() error {\n\t// If container does not exist, skip checking the status of it, as it won't work.\n\tif !m.container.Status().Exists() {\n\t\treturn fmt.Errorf(\"can't check status of non existing container\")\n\t}\n\n\treturn m.withForwardedRuntime(m.container.UpdateStatus)\n}", "func (s *Service) Status() (string, time.Time) {\n\tif m := s.mgr; m != nil {\n\t\tm.lock()\n\t\tdefer m.unlock()\n\t}\n\treturn s.reason, s.stamp\n}", "func (s *Server) Status(c *gin.Context) {\n\tc.JSON(200, system.Info())\n}", "func (t *Tileset) CheckJobStatus() error {\n\tfmt.Println(\"Awaiting job completion. This may take some time...\")\n\tfor {\n\t\tstatusResponse := &StatusResponse{}\n\t\tres, err := t.base.SimpleGET(t.postURL() + \"/status\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tjson.Unmarshal(res, statusResponse)\n\t\tif statusResponse.Status == \"failed\" {\n\t\t\tfmt.Println(\"Job failed\")\n\t\t\treturn nil\n\t\t}\n\t\tif statusResponse.Status == \"success\" {\n\t\t\tfmt.Println(\"Job complete\")\n\t\t\treturn nil\n\t\t}\n\t\tfmt.Println(statusResponse.Status)\n\t\ttime.Sleep(5 * time.Second)\n\n\t}\n\n}", "func TestStatus(t *testing.T) {\n\tassertion, router := test.Init(t)\n\n\tBindAPI(router)\n\tsession := test.NewSession(router)\n\n\tdatabase.Write.Create(&models.Good{\n\t\tProductID: 3,\n\t\tPosition: \"regal 1\",\n\t})\n\tdatabase.Write.Create(&models.Good{\n\t\tProductID: 3,\n\t\tPosition: \"regal 2\",\n\t})\n\tdatabase.Write.Create(&models.Good{\n\t\tProductID: 1,\n\t\tPosition: \"regal 10\",\n\t})\n\n\tr, w := session.JSONRequest(\"GET\", \"/api/status\", nil)\n\tresult := r.(map[string]interface{})\n\tassertion.Equal(http.StatusOK, w.StatusCode)\n\tassertion.Equal(\"running\", result[\"status\"])\n\n\tdb := result[\"database\"].(map[string]interface{})\n\tassertion.Equal(true, db[\"read\"])\n\tassertion.Equal(true, db[\"write\"])\n\n\tgood := result[\"good\"].(map[string]interface{})\n\tassertion.Equal(float64(3), good[\"count\"])\n\tassertion.Equal(float64(1.5), good[\"avg\"])\n\n\ttest.Close()\n}", "func (a *adapter) checkServicesReadiness(ctx context.Context) {\n\t// checks the kafka readiness\n\tgo a.checkKafkaReadiness(ctx)\n\n\t// checks the kv-store readiness\n\tgo a.checkKvStoreReadiness(ctx)\n}", "func (c *rpcServices) UpdateStatus(rpcService *v1.RpcService) (result *v1.RpcService, err error) {\n\tresult = &v1.RpcService{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"rpcservices\").\n\t\tName(rpcService.Name).\n\t\tSubResource(\"status\").\n\t\tBody(rpcService).\n\t\tDo().\n\t\tInto(result)\n\treturn\n}", "func runStatus(args []string) int {\n\n\treturn 0\n}", "func TestStatus() {\n\tfmt.Println(\"\")\n\tfmt.Println(\"=============================================================================================\")\n\tfmt.Printf(\"TOTAL TEST SUITES : %d\\n\", counters.suitesCount)\n\tfmt.Printf(\"TOTAL TEST CASES : %d\\n\", counters.testCaseCount)\n\tfmt.Printf(\"TOTAL TEST METHODS : %d\\n\", counters.methodsCount)\n\tfmt.Printf(\"TOTAL TEST METHODS PASS : %d\\n\", counters.methodsPassedCount)\n\tfmt.Printf(\"TOTAL TEST METHODS FAIL : %d\\n\", counters.methodsFailedCount)\n\tfmt.Println(\"\")\n\tif TestPassed {\n\t\tfmt.Println(\"TEST STATUS : PASS\")\n\t} else {\n\t\tfmt.Println(\"TEST STATUS : FAIL\")\n\t}\n\tfmt.Println(\"=============================================================================================\")\n\tfmt.Println(\"\")\n}", "func status(ctx *cli.Context) error {\n\t// Create a wrapper around the checkpoint oracle contract\n\taddr, oracle := newContract(newRPCClient(ctx.GlobalString(nodeURLFlag.Name)))\n\tfmt.Printf(\"Oracle => %s\\n\", addr.Hex())\n\tfmt.Println()\n\n\t// Retrieve the list of authorized signers (admins)\n\tadmins, err := oracle.Contract().GetAllAdmin(nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor i, admin := range admins {\n\t\tfmt.Printf(\"Admin %d => %s\\n\", i+1, admin.Hex())\n\t}\n\tfmt.Println()\n\n\t// Retrieve the latest checkpoint\n\tindex, checkpoint, height, err := oracle.Contract().GetLatestCheckpoint(nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"Checkpoint (published at #%d) %d => %s\\n\", height, index, common.Hash(checkpoint).Hex())\n\n\treturn nil\n}", "func (controller *playgroundController) CheckStatus(ctx context.Context, info *pb.CheckStatusRequest) (*pb.CheckStatusResponse, error) {\n\tpipelineId, err := uuid.Parse(info.PipelineUuid)\n\terrorMessage := \"Error during getting status of the code processing\"\n\tif err != nil {\n\t\tlogger.Errorf(\"%s: CheckStatus(): pipelineId has incorrect value and couldn't be parsed as uuid value: %s\", info.PipelineUuid, err.Error())\n\t\treturn nil, cerrors.InvalidArgumentError(errorMessage, \"pipelineId has incorrect value and couldn't be parsed as uuid value: %s\", info.PipelineUuid)\n\t}\n\tstatus, err := code_processing.GetProcessingStatus(ctx, controller.cacheService, pipelineId, errorMessage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &pb.CheckStatusResponse{Status: status}, nil\n}", "func (c *APIClient) StatusCheck() (bool, error) {\n\turl, err := c.compileStatusCheckURL()\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t// Use CallRaw since no authentication is needed for status check.\n\tr, err := c.Client.CallRaw(req)\n\tc.addResponseCode(r.StatusCode)\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif r.StatusCode != http.StatusOK {\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}", "func (c *tpmManagerBinary) status(ctx context.Context) ([]byte, error) {\n\treturn c.call(ctx, \"status\")\n}", "func (o ServiceOutput) Status() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Service) pulumi.StringOutput { return v.Status }).(pulumi.StringOutput)\n}", "func (r *client) Status(ctx context.Context) (*pb.SystemStatus, error) {\n\tresp, err := r.AgentClient.Status(ctx, &pb.StatusRequest{}, r.callOptions...)\n\tif err != nil {\n\t\treturn nil, ConvertGRPCError(err)\n\t}\n\treturn resp.Status, nil\n}", "func (ts testState) statusUpdated(ctx context.Context, client kubernetesClient, phase string) error {\n\tpvcs := []string{ts.pvc, withMigrationSuffix(ts.pvc)}\n\tfor _, pvcName := range pvcs {\n\t\tpvc, err := client.GetPVC(ctx, pvcName, ts.namespace)\n\t\tif err != nil && !apierrors.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\t\tif apierrors.IsNotFound(err) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif pvc.Annotations[completedMigrationPhase] != phase {\n\t\t\treturn errors.Errorf(\"phase incorrect. expected=%v, got=%v\",\n\t\t\t\tphase, pvc.Annotations[completedMigrationPhase])\n\t\t}\n\n\t}\n\treturn nil\n}", "func (r *ManagedServiceUpdateResponse) Status() int {\n\tif r == nil {\n\t\treturn 0\n\t}\n\treturn r.status\n}", "func checkProcessStatus() error {\n\tstatus := serverProcessStatus.Val()\n\tif status > 0 {\n\t\tswitch status {\n\t\tcase adminActionRestarting:\n\t\t\treturn gerror.NewCode(gcode.CodeInvalidOperation, \"server is restarting\")\n\n\t\tcase adminActionShuttingDown:\n\t\t\treturn gerror.NewCode(gcode.CodeInvalidOperation, \"server is shutting down\")\n\t\t}\n\t}\n\treturn nil\n}", "func TestStatusShouldPass1(t *testing.T) {\n\tstatusCode, body, err := get(\"/\")\n\tif err != nil {\n\t\tt.Errorf(\"ERROR: error trying to get\\n\\t%v\\n\", err)\n\t}\n\tif statusCode != http.StatusOK {\n\t\tt.Errorf(\"ERROR: status returned should be 200 OK\\n\\t%v\\n\", string(body))\n\t}\n\tif len(body) == 0 {\n\t\tt.Fatalf(\"ERROR: body should not be nil!\\n\")\n\t}\n\n\tstatus := struct {\n\t\tStatus string `json:\"status\"`\n\t\tCount int64 `json:\"totalSuccessfulAnalyses\"`\n\t\tHookCount int64 `json:\"hookedRequests\"`\n\t}{}\n\terr = json.Unmarshal(body, &status)\n\tif err != nil {\n\t\tt.Fatalf(\"ERROR: error unmarshalling JSON response\\n\\t%v\\n\", err)\n\t}\n\n\tif status.Status != \"Up\" {\n\t\tt.Errorf(\"ERROR: health check status should be 'Up'\\n\\t%+v\\n\", status)\n\t}\n}", "func GetServiceStatus(name string) (string, error) {\n\tfmt.Printf(\"Executing GetServiceStatus for: %s\\n\", name)\n\n\tvar status string\n\tm, err := mgr.Connect()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer m.Disconnect()\n\ts, err := m.OpenService(name)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer s.Close()\n\n\tstate, err := s.Query()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tswitch state.State {\n\tdefault:\n\t\tstatus = \"Huh?\"\n\tcase 0:\n\t\tstatus = \"unknown\"\n\tcase 1:\n\t\tstatus = \"stopped\"\n\tcase 2:\n\t\tstatus = \"start_pending\"\n\tcase 3:\n\t\tstatus = \"stop_pending\"\n\tcase 4:\n\t\tstatus = \"running\"\n\tcase 5:\n\t\tstatus = \"continue_pending\"\n\tcase 6:\n\t\tstatus = \"pause_pending\"\n\tcase 7:\n\t\tstatus = \"paused\"\n\tcase 8:\n\t\tstatus = \"service_not_found\"\n\tcase 9:\n\t\tstatus = \"server_not_found\"\n\t}\n\n\tfmt.Printf(\"State returned is: %v\\n\", status)\n\treturn status, nil\n}", "func (c *Client) Status() (*http.Response, error) {\n\tresp, err := c.get(\"/status\", nil)\n\tif err != nil &&\n\t\t(strings.Contains(err.Error(), \"EOF\") || strings.Contains(err.Error(), \"refused\")) {\n\t\treturn nil, fmt.Errorf(\"daemon on remote %s appears offline or inaccessible\", c.Name)\n\t}\n\treturn resp, err\n}", "func (cli *CLI) SystemStatus() {\n\ts := system.New(types.NamespacedName{Namespace: cli.Namespace, Name: cli.SystemName}, cli.Client, scheme.Scheme, nil)\n\ts.Load()\n\n\t// TEMPORARY ? check PVCs here because we couldn't own them in openshift\n\t// See https://github.com/noobaa/noobaa-operator/issues/12\n\tfor i := range s.CoreApp.Spec.VolumeClaimTemplates {\n\t\tt := &s.CoreApp.Spec.VolumeClaimTemplates[i]\n\t\tpvc := &corev1.PersistentVolumeClaim{\n\t\t\tTypeMeta: metav1.TypeMeta{Kind: \"PersistentVolumeClaim\"},\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: t.Name + \"-\" + cli.SystemName + \"-core-0\",\n\t\t\t\tNamespace: cli.Namespace,\n\t\t\t},\n\t\t}\n\t\tutil.KubeCheck(cli.Client, pvc)\n\t}\n\n\t// sys := cli.LoadSystemDefaults()\n\t// util.KubeCheck(cli.Client, sys)\n\tif s.NooBaa.Status.Phase == nbv1.SystemPhaseReady {\n\t\tcli.Log.Printf(\"✅ System Phase is \\\"%s\\\"\\n\", s.NooBaa.Status.Phase)\n\t\tsecretRef := s.NooBaa.Status.Accounts.Admin.SecretRef\n\t\tsecret := &corev1.Secret{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: secretRef.Name,\n\t\t\t\tNamespace: secretRef.Namespace,\n\t\t\t},\n\t\t}\n\t\tutil.KubeCheck(cli.Client, secret)\n\n\t\tcli.Log.Println(\"\")\n\t\tcli.Log.Println(\"#------------------#\")\n\t\tcli.Log.Println(\"#- Mgmt Addresses -#\")\n\t\tcli.Log.Println(\"#------------------#\")\n\t\tcli.Log.Println(\"\")\n\n\t\tcli.Log.Println(\"ExternalDNS :\", s.NooBaa.Status.Services.ServiceMgmt.ExternalDNS)\n\t\tcli.Log.Println(\"ExternalIP :\", s.NooBaa.Status.Services.ServiceMgmt.ExternalIP)\n\t\tcli.Log.Println(\"NodePorts :\", s.NooBaa.Status.Services.ServiceMgmt.NodePorts)\n\t\tcli.Log.Println(\"InternalDNS :\", s.NooBaa.Status.Services.ServiceMgmt.InternalDNS)\n\t\tcli.Log.Println(\"InternalIP :\", s.NooBaa.Status.Services.ServiceMgmt.InternalIP)\n\t\tcli.Log.Println(\"PodPorts :\", s.NooBaa.Status.Services.ServiceMgmt.PodPorts)\n\n\t\tcli.Log.Println(\"\")\n\t\tcli.Log.Println(\"#----------------#\")\n\t\tcli.Log.Println(\"#- S3 Addresses -#\")\n\t\tcli.Log.Println(\"#----------------#\")\n\t\tcli.Log.Println(\"\")\n\n\t\tcli.Log.Println(\"ExternalDNS :\", s.NooBaa.Status.Services.ServiceS3.ExternalDNS)\n\t\tcli.Log.Println(\"ExternalIP :\", s.NooBaa.Status.Services.ServiceS3.ExternalIP)\n\t\tcli.Log.Println(\"NodePorts :\", s.NooBaa.Status.Services.ServiceS3.NodePorts)\n\t\tcli.Log.Println(\"InternalDNS :\", s.NooBaa.Status.Services.ServiceS3.InternalDNS)\n\t\tcli.Log.Println(\"InternalIP :\", s.NooBaa.Status.Services.ServiceS3.InternalIP)\n\t\tcli.Log.Println(\"PodPorts :\", s.NooBaa.Status.Services.ServiceS3.PodPorts)\n\n\t\tcli.Log.Println(\"\")\n\t\tcli.Log.Println(\"#---------------#\")\n\t\tcli.Log.Println(\"#- Credentials -#\")\n\t\tcli.Log.Println(\"#---------------#\")\n\t\tcli.Log.Println(\"\")\n\t\tfor key, value := range secret.Data {\n\t\t\tcli.Log.Printf(\"%s: %s\\n\", key, string(value))\n\t\t}\n\t\tcli.Log.Println(\"\")\n\t} else {\n\t\tcli.Log.Printf(\"❌ System Phase is \\\"%s\\\"\\n\", s.NooBaa.Status.Phase)\n\n\t}\n}", "func (svc Service) statusHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tjson := GetStatusAsJSON()\n\tfmt.Println(json)\n\tfmt.Fprintf(w, \"%s\\n\\r\", json)\n}", "func statusChanged(status PingerTaskStatus) bool {\n\treturn status.Consecutive == 1 && status.LatestResult.Status != ping.StatusUnknown\n}", "func serviceStatus(servers ServersUI) map[string]*systemd.UnitStatus {\n\tvar mutex sync.Mutex\n\tvar wg sync.WaitGroup\n\tret := map[string]*systemd.UnitStatus{}\n\tfor _, server := range servers {\n\t\twg.Add(1)\n\t\tgo func(server string) {\n\t\t\tdefer wg.Done()\n\t\t\tallServices := getStatus(server)\n\t\t\tmutex.Lock()\n\t\t\tdefer mutex.Unlock()\n\t\t\tfor _, status := range allServices {\n\t\t\t\tif status.Status != nil {\n\t\t\t\t\tret[server+\":\"+status.Status.Name] = status\n\t\t\t\t}\n\t\t\t}\n\t\t}(server.Name)\n\t}\n\twg.Wait()\n\n\treturn ret\n}", "func (s *ServiceStorage) WatchStatus(ctx context.Context, service chan *types.Service) error {\n\n\tlog.V(logLevel).Debug(\"storage:etcd:service:> watch service\")\n\n\tconst filter = `\\b\\/` + serviceStorage + `\\/(.+):(.+)/status\\b`\n\tclient, destroy, err := getClient(ctx)\n\tif err != nil {\n\t\tlog.V(logLevel).Errorf(\"storage:etcd:service:> watch service err: %s\", err.Error())\n\t\treturn err\n\t}\n\tdefer destroy()\n\n\tr, _ := regexp.Compile(filter)\n\tkey := keyCreate(serviceStorage)\n\tcb := func(action, key string, _ []byte) {\n\t\tkeys := r.FindStringSubmatch(key)\n\t\tif len(keys) < 3 {\n\t\t\treturn\n\t\t}\n\n\t\tif action == \"delete\" {\n\t\t\treturn\n\t\t}\n\n\t\tif d, err := s.Get(ctx, keys[1], keys[2]); err == nil {\n\t\t\tservice <- d\n\t\t}\n\t}\n\n\tif err := client.Watch(ctx, key, filter, cb); err != nil {\n\t\tlog.V(logLevel).Errorf(\"storage:etcd:service:> watch service err: %s\", err.Error())\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *SailTrim) Status(ctx context.Context, opt StatusOption) error {\n\t_sv, err := s.conf.loadService()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to load service config\")\n\t}\n\tout, err := s.svc.GetContainerServicesWithContext(ctx, &lightsail.GetContainerServicesInput{\n\t\tServiceName: _sv.ContainerServiceName,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tsv := out.ContainerServices[0]\n\tif opt.Detail {\n\t\tfmt.Print(MarshalJSONString(sv))\n\t\treturn nil\n\t}\n\n\tp := func(k, v string) {\n\t\tfmt.Printf(\"%-17s %s\\n\", k, v)\n\t}\n\tp(\"ServiceName:\", *sv.ContainerServiceName)\n\tp(\"State:\", *sv.State)\n\tp(\"Power:\", *sv.Power)\n\tp(\"Scale:\", strconv.FormatInt(*sv.Scale, 10))\n\tp(\"URL:\", *sv.Url)\n\tfor _, ns := range sv.PublicDomainNames {\n\t\tfor _, n := range ns {\n\t\t\tp(\"PublicDomainName:\", *n)\n\t\t}\n\t}\n\tp(\"IsDisabled:\", strconv.FormatBool(*sv.IsDisabled))\n\treturn nil\n}", "func checkJobStatus(jobQueue *jobqueue.Client, t *jobqueue.Task) (bool, error) {\n\tif t.Job.Status != jobqueue.JobStatusNew {\n\t\treturn true, fmt.Errorf(\"bad job status: %s\", t.Job.Status)\n\t}\n\tif t.Job.Action != \"select-hypervisor\" {\n\t\treturn true, fmt.Errorf(\"bad action: %s\", t.Job.Action)\n\t}\n\treturn false, nil\n}", "func (r *TokenExpiredRepair) Status() (bool, error) {\n\trequest := req.Status{\n\t\tItem: req.MachineStatus,\n\t\tMachineName: r.MachineName,\n\t}\n\n\tif err := r.Klient.RemoteStatus(request); err != nil {\n\t\t// If the error is not what this repairer is designed to handle, return ok.\n\t\t// This seems counter intuitive, but if this Status() returns false, it is\n\t\t// expected to fix the error. We don't know what that error is, so we shouldn't\n\t\t// report a bad status. Log it, for debugging purposes though, and hope the\n\t\t// next repairer in the list knows how to deal with this issue.\n\t\tkErr, ok := err.(*kite.Error)\n\t\tif !ok || kErr.Type != kiteerrortypes.AuthErrTokenIsExpired {\n\t\t\tr.Log.Warning(\"Encountered error not in scope of this repair. err:%s\", err)\n\t\t\treturn true, nil\n\t\t}\n\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}", "func (s *Simple) SystemStatus(req *acomm.Request) (interface{}, *url.URL, error) {\n\tvar args SystemStatusArgs\n\tif err := req.UnmarshalArgs(&args); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif args.GuestID == \"\" {\n\t\treturn nil, nil, errors.New(\"missing guest_id\")\n\t}\n\n\t// Prepare multiple requests\n\tmultiRequest := acomm.NewMultiRequest(s.tracker, 0)\n\n\tcpuReq, err := acomm.NewRequest(\"CPUInfo\", s.tracker.URL().String(), \"\", &CPUInfoArgs{GuestID: args.GuestID}, nil, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdiskReq, err := acomm.NewRequest(\"DiskInfo\", s.tracker.URL().String(), \"\", &DiskInfoArgs{GuestID: args.GuestID}, nil, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\trequests := map[string]*acomm.Request{\n\t\t\"CPUInfo\": cpuReq,\n\t\t\"DiskInfo\": diskReq,\n\t}\n\n\tfor name, req := range requests {\n\t\tif err := multiRequest.AddRequest(name, req); err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif err := acomm.Send(s.config.CoordinatorURL(), req); err != nil {\n\t\t\tmultiRequest.RemoveRequest(req)\n\t\t\tcontinue\n\t\t}\n\t}\n\n\t// Wait for the results\n\tresponses := multiRequest.Responses()\n\tresult := &SystemStatusResult{}\n\n\tif resp, ok := responses[\"CPUInfo\"]; ok {\n\t\tif err := resp.UnmarshalResult(&(result.CPUs)); err != nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"name\": \"CPUInfo\",\n\t\t\t\t\"resp\": resp,\n\t\t\t\t\"error\": err,\n\t\t\t}).Error(\"failed to unarshal result\")\n\t\t}\n\t}\n\n\tif resp, ok := responses[\"DiskInfo\"]; ok {\n\t\tif err := resp.UnmarshalResult(&(result.Disks)); err != nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"name\": \"DiskInfo\",\n\t\t\t\t\"resp\": resp,\n\t\t\t\t\"error\": err,\n\t\t\t}).Error(\"failed to unarshal result\")\n\t\t}\n\t}\n\n\treturn result, nil, nil\n}", "func checkInstallStatus(cs kube.Cluster) error {\n\tscopes.Framework.Infof(\"checking IstioOperator CR status\")\n\tgvr := schema.GroupVersionResource{\n\t\tGroup: \"install.istio.io\",\n\t\tVersion: \"v1alpha1\",\n\t\tResource: \"istiooperators\",\n\t}\n\n\tvar unhealthyCN []string\n\tretryFunc := func() error {\n\t\tus, err := cs.GetUnstructured(gvr, IstioNamespace, \"test-istiocontrolplane\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get istioOperator resource: %v\", err)\n\t\t}\n\t\tusIOPStatus := us.UnstructuredContent()[\"status\"]\n\t\tif usIOPStatus == nil {\n\t\t\tif _, err := cs.CoreV1().Services(OperatorNamespace).Get(context.TODO(), \"istio-operator\",\n\t\t\t\tkubeApiMeta.GetOptions{}); err != nil {\n\t\t\t\treturn fmt.Errorf(\"istio operator svc is not ready: %v\", err)\n\t\t\t}\n\t\t\tif _, err := cs.CheckPodsAreReady(kube2.NewPodFetch(cs.Accessor, OperatorNamespace)); err != nil {\n\t\t\t\treturn fmt.Errorf(\"istio operator pod is not ready: %v\", err)\n\t\t\t}\n\n\t\t\treturn fmt.Errorf(\"status not found from the istioOperator resource\")\n\t\t}\n\t\tusIOPStatus = usIOPStatus.(map[string]interface{})\n\t\tiopStatusString, err := json.Marshal(usIOPStatus)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to marshal istioOperator status: %v\", err)\n\t\t}\n\t\tstatus := &api.InstallStatus{}\n\t\tjspb := jsonpb.Unmarshaler{AllowUnknownFields: true}\n\t\tif err := jspb.Unmarshal(bytes.NewReader(iopStatusString), status); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unmarshal istioOperator status: %v\", err)\n\t\t}\n\t\terrs := util.Errors{}\n\t\tunhealthyCN = []string{}\n\t\tif status.Status != api.InstallStatus_HEALTHY {\n\t\t\terrs = util.AppendErr(errs, fmt.Errorf(\"got IstioOperator status: %v\", status.Status))\n\t\t}\n\n\t\tfor cn, cnstatus := range status.ComponentStatus {\n\t\t\tif cnstatus.Status != api.InstallStatus_HEALTHY {\n\t\t\t\tunhealthyCN = append(unhealthyCN, cn)\n\t\t\t\terrs = util.AppendErr(errs, fmt.Errorf(\"got component: %s status: %v\", cn, cnstatus.Status))\n\t\t\t}\n\t\t}\n\t\treturn errs.ToError()\n\t}\n\terr := retry.UntilSuccess(retryFunc, retry.Timeout(retryTimeOut), retry.Delay(retryDelay))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"istioOperator status is not healthy: %v\", err)\n\t}\n\treturn nil\n}", "func (h *Handler) UpdateStatus(w http.ResponseWriter, r *http.Request) {\n\n\tcmd := sigstat.Command{\n\t\tStatus: \"running\",\n\t}\n\n\th.client.CommandService().UpdateStatus(cmd)\n}", "func PingService(url string, expectedStatus int) (*http.Response, error) {\n\tresponse, err := http.Get(url)\n\n\tif err != nil {\n\t\tlog.Println(\"Failure to get make request\")\n\t\treturn nil, err\n\t}\n\n\tif response.StatusCode != expectedStatus {\n\t\terr := fmt.Errorf(\"Expected Status %d Actual Status %d\", expectedStatus, response.StatusCode)\n\t\treturn nil, err\n\t}\n\n\treturn response, nil\n}" ]
[ "0.76031595", "0.7590077", "0.7186525", "0.7040751", "0.69706374", "0.68412334", "0.68269354", "0.6699858", "0.66703784", "0.65752125", "0.657377", "0.6545057", "0.65449893", "0.651675", "0.64959073", "0.64491725", "0.6444791", "0.6409749", "0.6403865", "0.63967973", "0.6395133", "0.638237", "0.6378214", "0.6372563", "0.634926", "0.63428366", "0.63091516", "0.6293141", "0.6289087", "0.62681973", "0.62678653", "0.626592", "0.62608296", "0.62517416", "0.6248482", "0.6241975", "0.6231105", "0.6227635", "0.62249494", "0.6217848", "0.6217696", "0.619759", "0.61952835", "0.61561286", "0.6148124", "0.6134273", "0.6115367", "0.6109854", "0.60894775", "0.6085598", "0.6082383", "0.6075419", "0.6073474", "0.60635", "0.6057027", "0.60512364", "0.60508466", "0.60489154", "0.6035945", "0.60359323", "0.60348254", "0.60344946", "0.60289025", "0.6022014", "0.60209155", "0.6020653", "0.6007157", "0.59805024", "0.5979435", "0.597527", "0.59590334", "0.5949615", "0.5948467", "0.59437454", "0.5939491", "0.5934911", "0.5928399", "0.59257996", "0.59113866", "0.59059644", "0.59013397", "0.590073", "0.58967936", "0.5893328", "0.58928925", "0.5884198", "0.5882602", "0.58817345", "0.587948", "0.58794683", "0.587908", "0.5878242", "0.5874786", "0.58744717", "0.587179", "0.5870148", "0.5867283", "0.58672357", "0.5864469", "0.58637166" ]
0.600257
67
/ The closest equivalent to sysinfo in Mac OS X is sysctl / MIB. It doesn't return a sysinfo struct directly, but most of the values in that structure are available as sysctl keys. For instance: uptime is approximated by kern.boottime (although that reflects the actual boot time, not the running time) loads is available as vm.loadavg totalram = hw.memsize (in bytes) freeram, sharedram, and bufferram are complicated, as the XNU memory manager works differently from Linux's. I'm not sure if the closest equivalent values ("active" and "inactive" memory) are exposed. totalswap and freeswap are reflected in vm.swapusage. (But note that OS X allocates swap space dynamically.) procs doesn't appear to have any equivalent. totalhigh and freehigh are specific to i386 Linux 21:47 up 10 days, 6:47, 6 users, load averages: 1.99 2.17 2.09 time now, time since boot, ???, of users, load average TODO: for loadavg, use '/proc/loadavg' ?
func main() { boottime, err := coreutils.BootTime() if err != nil { panic(err) } now := time.Now() fmt.Println(boottime) delta := now.Sub(boottime) fmt.Println(delta) load, err := coreutils.LoadAvg() if err != nil { panic(err) } fmt.Printf("%.2f %.2f %.2f\n", load[0], load[1], load[2]) totalram := coreutils.Totalram() fmt.Println("total ram: ", totalram) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func SystemInfo() string {\n\n\tvar si SysInfo\n\tvar m runtime.MemStats\n\truntime.ReadMemStats(&m)\n\tsi.AllocMemory = m.Alloc\n\tsi.AllocMemoryMB = btomb(m.Alloc)\n\tsi.TotalAllocMemory = m.TotalAlloc\n\tsi.TotalAllocMemoryMB = btomb(m.TotalAlloc)\n\tsi.TotalSystemMemory = m.Sys\n\tsi.TotalSystemMemoryMB = btomb(m.Sys)\n\tc, _ := cpu.Info()\n\n\tsi.CPUs = c[0].Cores\n\n\tsi.GolangVersion = runtime.Version()\n\tsi.ContainerHostName, _ = os.Hostname()\n\tsi.CurrentUTC = time.Now().UTC()\n\n\tsi.CurrentLocalTime = time.Now().Local()\n\n\tconst (\n\t\tB = 1\n\t\tKB = 1024 * B\n\t\tMB = 1024 * KB\n\t\tGB = 1024 * MB\n\t)\n\n\tv, _ := mem.VirtualMemory()\n\tfmt.Printf(\"Total: %v, Free:%v, UsedPercent:%f%%\\n\", v.Total, v.Free, v.UsedPercent)\n\n\ttype InfoStat struct {\n\t\tHostname string `json:\"hostname\"`\n\t\tUptime uint64 `json:\"uptime\"`\n\t\tBootTime uint64 `json:\"bootTime\"`\n\t\tProcs uint64 `json:\"procs\"` // number of processes\n\t\tOS string `json:\"os\"` // ex: freebsd, linux\n\t\tPlatform string `json:\"platform\"` // ex: ubuntu, linuxmint\n\t\tPlatformFamily string `json:\"platformFamily\"` // ex: debian, rhel\n\t\tPlatformVersion string `json:\"platformVersion\"` // version of the complete OS\n\t\tKernelVersion string `json:\"kernelVersion\"` // version of the OS kernel (if available)\n\t\tVirtualizationSystem string `json:\"virtualizationSystem\"`\n\t\tVirtualizationRole string `json:\"virtualizationRole\"` // guest or host\n\t\tHostID string `json:\"hostid\"` // ex: uuid\n\t}\n\n\tvar his *host.InfoStat\n\this, _ = host.Info()\n\n\tsi.Uptime = his.Uptime\n\n\tsi.OperatingSystem = his.OS\n\tsi.Platform = his.Platform\n\tsi.PlatformFamily = his.PlatformFamily\n\tsi.PlatformVersion = his.PlatformVersion\n\tsi.VirtualSystem = his.VirtualizationSystem\n\tsi.VirtualRole = his.VirtualizationRole\n\tsi.HostID = his.HostID\n\tsi.HostName = his.Hostname\n\tsi.BootTime = strconv.FormatUint(his.BootTime, 10)\n\tsi.KernelVersion = his.KernelVersion\n\n\tsi.UptimeDays = si.Uptime / (60 * 60 * 24)\n\tsi.UptimeHours = (si.Uptime - (si.UptimeDays * 60 * 60 * 24)) / (60 * 60)\n\tsi.UptimeMinutes = ((si.Uptime - (si.UptimeDays * 60 * 60 * 24)) - (si.UptimeHours * 60 * 60)) / 60\n\tinterfaces, err := net.Interfaces()\n\n\tif err == nil {\n\t\tfor i, interfac := range interfaces {\n\t\t\tif interfac.Name == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\taddrs := interfac.Addrs\n\t\t\tsi.NetworkInterfaces[i].Name = interfac.Name\n\t\t\tsi.NetworkInterfaces[i].HardwareAddress = string(interfac.HardwareAddr)\n\t\t\tfor x, addr := range addrs {\n\t\t\t\tif addr.String() != \"\" {\n\t\t\t\t\tsi.NetworkInterfaces[i].IPAddresses[x].IPAddress = addr.String()\n\t\t\t\t} else {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvar paths [10]string\n\tpaths[0] = \"/\"\n\n\tfor i, path := range paths {\n\t\tdisk := DiskUsage(path)\n\t\tsi.Disk[i].Path = path\n\t\tsi.Disk[i].All = float64(disk.All) / float64(GB)\n\t\tsi.Disk[i].Used = float64(disk.Used) / float64(GB)\n\t\tsi.Disk[i].Free = float64(disk.Free) / float64(GB)\n\t}\n\n\tstrJSON, err := json.Marshal(si)\n\tcheckErr(err)\n\n\treturn string(strJSON)\n}", "func SysMem() (total uint64, free uint64, err error) {\n\tf, err := os.Open(\"/proc/meminfo\")\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\tpending := len(procMemFields)\n\tscan := bufio.NewScanner(f)\n\tfor scan.Scan() {\n\t\tfields := strings.Split(scan.Text(), \":\")\n\t\tif len(fields) != 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tname := strings.TrimSpace(fields[0])\n\t\tmemKB := strings.Fields(strings.TrimSpace(fields[1]))[0]\n\t\tif _, ok := procMemFields[name]; !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar mem uint64\n\t\tmem, err = strconv.ParseUint(memKB, 10, 64)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"invalid mem field:%s val:%s (%s)\", name, memKB, err)\n\t\t\treturn\n\t\t}\n\n\t\tmem = mem * 1024\n\t\tswitch name {\n\t\tcase \"MemTotal\":\n\t\t\ttotal = mem\n\t\tcase \"MemFree\", \"Buffers\", \"Cached\":\n\t\t\tfree += mem\n\t\t}\n\n\t\tpending--\n\t\tif pending == 0 {\n\t\t\treturn\n\t\t}\n\t}\n\n\tif err = scan.Err(); err != nil {\n\t\treturn\n\t}\n\n\terr = fmt.Errorf(\"unable to get required mem fields\")\n\treturn\n}", "func (this *hardware) sysinfo_() *syscall.Sysinfo_t {\n\tinfo := syscall.Sysinfo_t{}\n\tif err := syscall.Sysinfo(&info); err != nil {\n\t\tthis.log.Error(\"<hw.linux>sysinfo: %v\", err)\n\t\treturn nil\n\t} else {\n\t\treturn &info\n\t}\n}", "func GetSysMemoryMiB() uint64 {\n\treturn memory.TotalMemory() / 1048576 // bytes to MiB\n}", "func sysctlbyname(name string, data interface{}) (err error) {\n\tval, err := syscall.Sysctl(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbuf := []byte(val)\n\n\tswitch v := data.(type) {\n\tcase *uint64:\n\t\t*v = *(*uint64)(unsafe.Pointer(&buf[0]))\n\t\treturn\n\t}\n\n\tbbuf := bytes.NewBuffer([]byte(val))\n\treturn binary.Read(bbuf, binary.LittleEndian, data)\n}", "func getSystemData() map[string]string {\n\thost, err := os.Hostname()\n\tif err != nil {\n\t\thost = \"\"\n\t}\n\tmemstats := &runtime.MemStats{}\n\truntime.ReadMemStats(memstats)\n\tmem := fmt.Sprintf(\"Used: %s | Allocated: %s | Used-Heap: %s | Allocated-Heap: %s\",\n\t\tformatBytes(int64(memstats.Alloc)),\n\t\tformatBytes(int64(memstats.TotalAlloc)),\n\t\tformatBytes(int64(memstats.HeapAlloc)),\n\t\tformatBytes(int64(memstats.HeapSys)))\n\tplatform := fmt.Sprintf(\"Host: %s | OS: %s | Arch: %s\",\n\t\thost,\n\t\truntime.GOOS,\n\t\truntime.GOARCH)\n\tgoruntime := fmt.Sprintf(\"Version: %s | CPUs: %s\", runtime.Version(), strconv.Itoa(runtime.NumCPU()))\n\treturn map[string]string{\n\t\t\"PLATFORM\": platform,\n\t\t\"RUNTIME\": goruntime,\n\t\t\"MEM\": mem,\n\t}\n}", "func ProcMeminfo(c *gin.Context) {\n\tres := CmdExec(\"cat /proc/meminfo | head -n 2| awk '{print $2}'\")\n\ttotalMem, _ := strconv.Atoi(res[0])\n\tfreeMem, _ := strconv.Atoi(res[1])\n\tusedMem := totalMem - freeMem\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"totalMem\": totalMem,\n\t\t\"usedMem\": usedMem,\n\t})\n}", "func ProcInfo() ([]Win32_PerfFormattedData_PerfOS_System, error) {\n\treturn ProcInfoWithContext(context.Background())\n}", "func (i *Info) Sys() interface{} {\n\tattributes := map[string]interface{}{}\n\n\tt, err := times.Stat(i.syspath)\n\tif err != nil {\n\t\tlog.Printf(\"could not stat times for %s: %s\", err, i.syspath)\n\t}\n\tif err == nil {\n\t\tattributes[\"accessed\"] = t.AccessTime().In(time.UTC).Format(\"2006-01-02T15:04:05.000Z\")\n\t\tattributes[\"modified\"] = t.ModTime().In(time.UTC).Format(\"2006-01-02T15:04:05.000Z\")\n\t\tif t.HasChangeTime() {\n\t\t\tattributes[\"changed\"] = t.ChangeTime().In(time.UTC).Format(\"2006-01-02T15:04:05.000Z\")\n\t\t}\n\t\tif t.HasBirthTime() {\n\t\t\tattributes[\"created\"] = t.BirthTime().In(time.UTC).Format(\"2006-01-02T15:04:05.000Z\")\n\t\t}\n\t}\n\treturn attributes\n}", "func getMemUsage(memStat types.MemoryStats) uint64 {\n\t// Version 1 of the Linux cgroup API uses total_inactive_file\n\tif v, ok := memStat.Stats[\"total_inactive_file\"]; ok && v < memStat.Usage {\n\t\treturn memStat.Usage - v\n\t}\n\n\t// Version 2 of the Linux cgroup API uses inactive_file\n\tif v := memStat.Stats[\"inactive_file\"]; v < memStat.Usage {\n\t\treturn memStat.Usage - v\n\t}\n\n\treturn memStat.Usage\n}", "func OSInfo() (info *OS, err error) {\n\t//nolint:staticcheck,nolintlint\n\tmetadata, err := monitoring.GetOSRelease()\n\tif err != nil { //nolint:staticcheck,nolintlint\n\t\treturn nil, trace.Wrap(err)\n\t}\n\treturn &OS{\n\t\tID: metadata.ID,\n\t\tVersion: metadata.VersionID,\n\t\tLike: metadata.Like,\n\t}, nil\n}", "func SystemMemoryKB() (int, error) {\n\tdata, err := ioutil.ReadFile(procMeminfoPath)\n\tif err != nil {\n\t\treturn 0, errors.Wrapf(err, \"failed to read %q\", procMeminfoPath)\n\t}\n\treturn proc.ParseMemInfoMemTotal(bytes.NewReader(data))\n}", "func printSysstat(v *gocui.View, s stat.Stat) error {\n\tvar err error\n\n\t/* line1: current time and load average */\n\t_, err = fmt.Fprintf(v, \"pgcenter: %s, load average: %.2f, %.2f, %.2f\\n\",\n\t\ttime.Now().Format(\"2006-01-02 15:04:05\"),\n\t\ts.LoadAvg.One, s.LoadAvg.Five, s.LoadAvg.Fifteen)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t/* line2: cpu usage */\n\t_, err = fmt.Fprintf(v, \" %%cpu: \\033[37;1m%4.1f\\033[0m us, \\033[37;1m%4.1f\\033[0m sy, \\033[37;1m%4.1f\\033[0m ni, \\033[37;1m%4.1f\\033[0m id, \\033[37;1m%4.1f\\033[0m wa, \\033[37;1m%4.1f\\033[0m hi, \\033[37;1m%4.1f\\033[0m si, \\033[37;1m%4.1f\\033[0m st\\n\",\n\t\ts.CpuStat.User, s.CpuStat.Sys, s.CpuStat.Nice, s.CpuStat.Idle,\n\t\ts.CpuStat.Iowait, s.CpuStat.Irq, s.CpuStat.Softirq, s.CpuStat.Steal)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t/* line3: memory usage */\n\t_, err = fmt.Fprintf(v, \" MiB mem: \\033[37;1m%6d\\033[0m total, \\033[37;1m%6d\\033[0m free, \\033[37;1m%6d\\033[0m used, \\033[37;1m%8d\\033[0m buff/cached\\n\",\n\t\ts.Meminfo.MemTotal, s.Meminfo.MemFree, s.Meminfo.MemUsed,\n\t\ts.Meminfo.MemCached+s.Meminfo.MemBuffers+s.Meminfo.MemSlab)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t/* line4: swap usage, dirty and writeback */\n\t_, err = fmt.Fprintf(v, \"MiB swap: \\033[37;1m%6d\\033[0m total, \\033[37;1m%6d\\033[0m free, \\033[37;1m%6d\\033[0m used, \\033[37;1m%6d/%d\\033[0m dirty/writeback\\n\",\n\t\ts.Meminfo.SwapTotal, s.Meminfo.SwapFree, s.Meminfo.SwapUsed,\n\t\ts.Meminfo.MemDirty, s.Meminfo.MemWriteback)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func sysctlbyname(name string, data interface{}) error {\n\tif val, err := syscall.Sysctl(name); err != nil {\n\t\treturn err\n\t} else {\n\t\tbuf := []byte(val)\n\t\tswitch v := data.(type) {\n\t\tcase *uint64:\n\t\t\t*v = *(*uint64)(unsafe.Pointer(&buf[0]))\n\t\t\treturn nil\n\t\tcase []byte:\n\t\t\tfor i := 0; i < len(val) && i < len(v); i++ {\n\t\t\t\tv[i] = val[i]\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\tbbuf := bytes.NewBuffer([]byte(val))\n\t\treturn binary.Read(bbuf, binary.LittleEndian, data)\n\t}\n}", "func Sysctl(name string) (string, error) {\n\tpath := filepath.Clean(filepath.Join(\"/proc\", \"sys\", strings.Replace(name, \".\", \"/\", -1)))\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn \"\", trace.ConvertSystemError(err)\n\t}\n\tif len(data) == 0 {\n\t\treturn \"\", trace.BadParameter(\"empty output from sysctl\")\n\t}\n\treturn string(data[:len(data)-1]), nil\n}", "func (c *EcomClient) SysInfo() (*SysInfo, error) {\n\turi := c.endpoint + \"/sysinfo\"\n\treq, err := http.NewRequest(\"GET\", uri, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"http new request failed: %w\", err)\n\t}\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treq.Header.Set(\"Authorization\", \"Bearer \"+c.jwt)\n\treq.Header.Set(\"User-Agent\", fmt.Sprintf(\"ecom/%s\", Version))\n\tres, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"HTTP GET to %v failed: %w\", uri, err)\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode >= 400 {\n\t\treturn nil, fmt.Errorf(\"%s\", res.Status)\n\t}\n\n\tvar sysInfo SysInfo\n\tif err := json.NewDecoder(res.Body).Decode(&sysInfo); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to decode url %s: %w\", uri, err)\n\t}\n\treturn &sysInfo, nil\n}", "func (s *Tplink) SystemInfo() (SysInfo, error) {\n\tvar (\n\t\tpayload getSysInfo\n\t\tjsonResp SysInfo\n\t)\n\n\tj, _ := json.Marshal(payload)\n\n\tdata := encrypt(string(j))\n\tresp, err := send(s.Host, data)\n\tif err != nil {\n\t\treturn jsonResp, err\n\t}\n\n\tif err := json.Unmarshal([]byte(decrypt(resp)), &jsonResp); err != nil {\n\t\treturn jsonResp, err\n\t}\n\treturn jsonResp, nil\n}", "func ProcessStateSysUsage(p *os.ProcessState,) interface{}", "func getNVMCapacities() (uint64, uint64, error) {\n\tvar caps C.struct_device_capacities\n\terr := C.nvm_get_nvm_capacities(&caps)\n\tif err != C.NVM_SUCCESS {\n\t\tklog.Warningf(\"Unable to get NVM capacity. Status code: %d\", err)\n\t\treturn uint64(0), uint64(0), fmt.Errorf(\"Unable to get NVM capacity. Status code: %d\", err)\n\t}\n\treturn uint64(caps.memory_capacity), uint64(caps.app_direct_capacity), nil\n}", "func GetStat() map[string]interface{} {\n\tvar m runtime.MemStats\n\truntime.ReadMemStats(&m)\n\t// For info on each, see: https://golang.org/pkg/runtime/#MemStats\n\talloc := m.Alloc / 1024 / 1024\n\ttotalAlloc := m.TotalAlloc / 1024 / 1024\n\tsys := m.Sys / 1024 / 1024\n\tday, hour, min, sec := reqcounter.GetCounters()\n\treturn map[string]interface{}{\n\t\t\"alloc\": alloc,\n\t\t\"total_alloc\": totalAlloc,\n\t\t\"sys\": sys,\n\t\t\"requests_per_day\": day,\n\t\t\"requests_per_hour\": hour,\n\t\t\"requests_per_minute\": min,\n\t\t\"requests_per_second\": sec,\n\t}\n}", "func (hdlr *prochdlr) memInfo() (*MemoryInfo, error) {\r\n\tcounters := winapi.ProcessMemoryCountersEx{}\r\n\tsize := uint32(unsafe.Sizeof(counters))\r\n\terr := winapi.GetProcessMemoryInfo(hdlr.handler, &counters, size)\r\n\tif err != nil {\r\n\t\treturn nil, errors.Wrap(err, \"get process memory info\")\r\n\t}\r\n\r\n\tminfo := MemoryInfo{\r\n\t\tWorkingSetSize: counters.WorkingSetSize,\r\n\t\tQuotaPagedPoolUsage: counters.QuotaPagedPoolUsage,\r\n\t\tQuotaNonPagedPoolUsage: counters.QuotaNonPagedPoolUsage,\r\n\t\tPrivateUsage: counters.PrivateUsage,\r\n\t}\r\n\r\n\treturn &minfo, nil\r\n}", "func getSystemTimes() (*SystemTimes, error) {\n\tvar idleTime, kernelTime, userTime syscall.Filetime\n\n\tres, _, err1 := procGetSystemTimes.Call(\n\t\tuintptr(unsafe.Pointer(&idleTime)),\n\t\tuintptr(unsafe.Pointer(&kernelTime)),\n\t\tuintptr(unsafe.Pointer(&userTime)))\n\tif res != 1 {\n\t\treturn nil, err1\n\t}\n\n\tidle := fileTimeToInt64(idleTime)\n\tuser := fileTimeToInt64(userTime)\n\tkernel := fileTimeToInt64(kernelTime)\n\tsystem := (kernel - idle)\n\n\ttimes := &SystemTimes{\n\t\tIdleTime: idle,\n\t\tKernelTime: system,\n\t\tUserTime: user,\n\t}\n\n\tpslog.WithFieldsF(func() logrus.Fields {\n\t\treturn logrus.Fields{\n\t\t\t\"systemKernelTime\": times.KernelTime,\n\t\t\t\"systemUserTime\": times.UserTime,\n\t\t\t\"systemIdleTime\": times.IdleTime,\n\t\t\t\"rawSystemKernelTime\": kernelTime,\n\t\t\t\"rawSystemUserTime\": userTime,\n\t\t\t\"rawSystemIdleTime\": idleTime,\n\t\t}\n\t}).Debug(\"Raw process numbers.\")\n\n\treturn times, nil\n}", "func GetKernelInfo() string {\n\tcmd := exec.Command(\"uname\", \"-a\")\n\n\tvar out bytes.Buffer\n\tcmd.Stdout = &out\n\n\terr := cmd.Run()\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn out.String()\n}", "func (s Sysinfo) Procs() uint64 {\n\treturn s.procs\n}", "func (s *Sysinfo) Update() {\n\tinfo := syscall.Sysinfo_t{}\n\terr := syscall.Sysinfo(&info)\n\tif err != nil {\n\t\tlog.Printf(\"Sysinfo call failed: %s\", err.Error())\n\t\treturn\n\t}\n\n\ts.uptime = uint64(info.Uptime)\n\ts.memTotal = info.Totalram\n\ts.memFree = info.Freeram\n\ts.memShared = info.Sharedram\n\ts.memBuffer = info.Bufferram\n\ts.swapTotal = info.Totalswap\n\ts.swapFree = info.Freeswap\n\ts.load = info.Loads\n\ts.procs = uint64(info.Procs)\n}", "func (s Sysinfo) MemTotal() uint64 {\n\treturn s.memTotal\n}", "func (context *context) SystemInfo() string {\n\treturn fmt.Sprintf(\"system_info: n_threads = %d / %d | %s\\n\",\n\t\tcontext.params.Threads(),\n\t\truntime.NumCPU(),\n\t\twhisper.Whisper_print_system_info(),\n\t)\n}", "func getSwapInfo(m meminfomap) (*swapInfo, error) {\n\tfields := []string{\n\t\t\"SwapTotal\",\n\t\t\"SwapFree\",\n\t}\n\tif missingRequiredFields(m, fields) {\n\t\treturn nil, fmt.Errorf(\"missing required fields from meminfo\")\n\t}\n\t// These values are expressed in kibibytes, convert to the desired unit\n\tswapTotal := m[\"SwapTotal\"] << KB\n\tswapUsed := (m[\"SwapTotal\"] - m[\"SwapFree\"]) << KB\n\tswapFree := m[\"SwapFree\"] << KB\n\n\tsi := swapInfo{\n\t\tTotal: swapTotal,\n\t\tUsed: swapUsed,\n\t\tFree: swapFree,\n\t}\n\treturn &si, nil\n}", "func ReadMemInfo() (*MemInfo, error) {\n\tMemTotal, MemFree, err := getMemInfo()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getting memory totals %w\", err)\n\t}\n\tSwapTotal, SwapFree, err := getSwapInfo()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getting swap totals %w\", err)\n\t}\n\n\tif MemTotal < 0 || MemFree < 0 || SwapTotal < 0 || SwapFree < 0 {\n\t\treturn nil, errors.New(\"getting system memory info\")\n\t}\n\n\tmeminfo := &MemInfo{}\n\t// Total memory is total physical memory less than memory locked by kernel\n\tmeminfo.MemTotal = MemTotal\n\tmeminfo.MemFree = MemFree\n\tmeminfo.SwapTotal = SwapTotal\n\tmeminfo.SwapFree = SwapFree\n\n\treturn meminfo, nil\n}", "func GetMemoryInfo() (total, available int) {\n\n\tfile, err := os.Open(\"/proc/meminfo\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\ttotal, available = getMemoryInfo(file)\n\n\t_ = file.Close()\n\n\treturn\n}", "func ReadSysInfo() SysInfo {\n\t//creates a logging file when error occurs\n\tf, err := os.OpenFile(\"info.log\", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer f.Close()\n\tlog.SetOutput(f)\n\n\t//initialize SysInfo Struct\n\tsystemInfoLoc := os.ExpandEnv(\"$HOME/systemvar.txt\")\n\tfile, err := os.Open(systemInfoLoc)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer file.Close()\n\tscanner := bufio.NewReader(file)\n\tvar txthold string\n\tcounter := 0\n\tsysInfo := SysInfo{}\n\tfor {\n\t\tcounter++\n\t\ttxthold, err = scanner.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\t//adds the substring because txthold grabs the \\n value and increases the length by 1 or makes a new line\n\t\tif counter == 1 {\n\t\t\tsysInfo.SystemUser = txthold[0 : len(txthold)-1]\n\t\t} else if counter == 2 {\n\t\t\tsysInfo.SystemKernel = txthold[0 : len(txthold)-1]\n\t\t} else if counter == 3 {\n\t\t\tsysInfo.SystemKernelRelease = txthold[0 : len(txthold)-1]\n\t\t} else if counter == 4 {\n\t\t\tsysInfo.SystemKernelVersion = txthold[0 : len(txthold)-1]\n\t\t} else if counter == 5 {\n\t\t\tsysInfo.SystemArch = txthold[0 : len(txthold)-1]\n\t\t} else if counter == 6 {\n\t\t\tsysInfo.SystemProcessor = txthold[0 : len(txthold)-1]\n\t\t} else if counter == 7 {\n\t\t\tsysInfo.SystemHardwarePlatform = txthold[0 : len(txthold)-1]\n\t\t} else if counter == 8 {\n\t\t\tsysInfo.SystemOS = txthold[0 : len(txthold)-1]\n\t\t}\n\t}\n\tif err != io.EOF {\n\t\tfmt.Printf(\"failed: %v\\n\", err)\n\t}\n\treturn sysInfo\n}", "func (s Sysinfo) MemUsed() uint64 {\n\treturn s.MemTotal() - s.MemFree()\n}", "func GetProcessStats(pid int) (ProcessStats, error) {\n\t// Open the process.\n\tprocess, err := syscall.OpenProcess(processQueryLimitedInformation, false, uint32(pid))\n\tif err != nil {\n\t\treturn ProcessStats{}, nil\n\t}\n\tdefer syscall.CloseHandle(process)\n\n\t// Get memory info.\n\tpsapi := syscall.NewLazyDLL(\"psapi.dll\")\n\tgetProcessMemoryInfo := psapi.NewProc(\"GetProcessMemoryInfo\")\n\tmemoryInfo := processMemoryCounters{\n\t\tcb: 72,\n\t}\n\tres, _, _ := getProcessMemoryInfo.Call(uintptr(process), uintptr(unsafe.Pointer(&memoryInfo)), uintptr(memoryInfo.cb))\n\tif res == 0 {\n\t\treturn ProcessStats{}, nil\n\t}\n\n\t// Get CPU info.\n\tcreationTime1 := &syscall.Filetime{}\n\texitTime1 := &syscall.Filetime{}\n\tkernelTime1 := &syscall.Filetime{}\n\tuserTime1 := &syscall.Filetime{}\n\terr = syscall.GetProcessTimes(process, creationTime1, exitTime1, kernelTime1, userTime1)\n\tif err != nil {\n\t\treturn ProcessStats{RSSMemory: float64(memoryInfo.WorkingSetSize)}, nil\n\t}\n\t<-time.After(time.Millisecond * 50) // Not the most accurate, but it'll do.\n\tcreationTime2 := &syscall.Filetime{}\n\texitTime2 := &syscall.Filetime{}\n\tkernelTime2 := &syscall.Filetime{}\n\tuserTime2 := &syscall.Filetime{}\n\terr = syscall.GetProcessTimes(process, creationTime2, exitTime2, kernelTime2, userTime2)\n\tif err != nil {\n\t\treturn ProcessStats{RSSMemory: float64(memoryInfo.WorkingSetSize)}, nil\n\t}\n\tcpuTime := float64((userTime2.Nanoseconds() - userTime1.Nanoseconds()) / int64(runtime.NumCPU()))\n\n\treturn ProcessStats{\n\t\tRSSMemory: float64(memoryInfo.WorkingSetSize),\n\t\tCPUUsage: cpuTime / 500000, // Conversion: (cpuTime / (50*1000*1000)) * 100\n\t}, nil\n}", "func (fs *FS) fsInfo(ctx context.Context, path string) (int64, int64, int64, int64, int64, int64, error) {\n\tstatfs := &unix.Statfs_t{}\n\terr := unix.Statfs(path, statfs)\n\tif err != nil {\n\t\treturn 0, 0, 0, 0, 0, 0, err\n\t}\n\n\t// Available is blocks available * fragment size\n\tavailable := int64(statfs.Bavail) * int64(statfs.Bsize)\n\n\t// Capacity is total block count * fragment size\n\tcapacity := int64(statfs.Blocks) * int64(statfs.Bsize)\n\n\t// Usage is block being used * fragment size (aka block size).\n\tusage := (int64(statfs.Blocks) - int64(statfs.Bfree)) * int64(statfs.Bsize)\n\n\tinodes := int64(statfs.Files)\n\tinodesFree := int64(statfs.Ffree)\n\tinodesUsed := inodes - inodesFree\n\n\treturn available, capacity, usage, inodes, inodesFree, inodesUsed, nil\n}", "func (info *unixFileInfo) Sys() interface{} {\n\tif info == nil {\n\t\treturn nil\n\t}\n\treturn &info.sys\n}", "func GetSysStat(info os.FileInfo) *syscall.Stat_t {\n\tif stat, ok := info.Sys().(*syscall.Stat_t); ok {\n\t\treturn stat\n\t}\n\treturn nil\n}", "func (ac *activeClient) OSInfo(c *ishell.Context) {\n\tc.ProgressBar().Indeterminate(true)\n\tc.ProgressBar().Start()\n\tr := shared.OSInfo{}\n\n\tif err := ac.RPC.Call(\"API.GetOSInfo\", void, &r); err != nil {\n\t\tc.ProgressBar().Final(yellow(\"[\"+ac.Data().Name+\"] \") + red(\"[!] Could not collect information on client OSInfo:\", err))\n\t\tc.ProgressBar().Stop()\n\t\treturn\n\t}\n\n\tc.ProgressBar().Final(yellow(\"[\"+ac.Data().Name+\"] \") + green(\"[+] OSInfo collection finished\"))\n\tc.ProgressBar().Stop()\n\n\tc.Println(green(\"Runtime: \"), r.Runtime)\n\tc.Println(green(\"Arch: \"), r.OSArch)\n\tc.Println(green(\"OS: \"), r.OSName)\n\tc.Println(green(\"OS Version: \"), r.OSVersion)\n}", "func getCPUStats() (userCPU, systemCPU float64) {\n\treturn 0.0, 0.0\n}", "func GetRuntimes(ctx *Context) (map[string]interface{}, error) {\n\tm := make(map[string]interface{})\n\t// m[\"locationCount\"] = len(ctx.Sys.locationsMap)\n\tm[\"goroutines\"] = runtime.NumGoroutine()\n\tm[\"cgos\"] = runtime.NumCgoCall()\n\tm[\"goversion\"] = runtime.Version()\n\n\tvar memStats runtime.MemStats\n\truntime.ReadMemStats(&memStats)\n\tm[\"memstats\"] = memStats\n\n\treturn m, nil\n}", "func CurrentSlaveInfo() SlaveInfo {\n\tvar memAmount int\n\tif memStr := os.Getenv(\"JOB_MEM_LIMIT\"); memStr != \"\" {\n\t\tvar err error\n\t\tmemAmount, err = strconv.Atoi(memStr)\n\t\tif err != nil {\n\t\t\tpanic(\"invalid JOB_MEM_LIMIT: \" + memStr)\n\t\t}\n\t} else {\n\t\tmem := sigar.Mem{}\n\t\tmem.Get()\n\t\tmemAmount = int(mem.Total >> 20)\n\t}\n\treturn SlaveInfo{\n\t\tNumCPU: runtime.NumCPU(),\n\t\tMaxProcs: runtime.GOMAXPROCS(0),\n\t\tTotalMem: memAmount,\n\t\tOS: runtime.GOOS,\n\t\tArch: runtime.GOARCH,\n\t}\n}", "func readMemInfo() (*Memory, error) {\n\tfile, err := os.Open(\"/proc/meminfo\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\treturn parseMemInfo(file)\n}", "func ProcessStat(pid int32) ProcessInfo {\n\t//pro := getSelfProcess()\n\tpro, _ := process.NewProcess(pid)\n\tprocessinfo := new(ProcessInfo)\n\n\tprocessinfo.Name, _ = pro.Name()\n\tprocessinfo.Pid = int32(os.Getpid())\n\tprocessinfo.Ppid, _ = pro.Ppid()\n\tprocessinfo.Exe, _ = pro.Exe()\n\tprocessinfo.Cmdline, _ = pro.Cmdline()\n\tprocessinfo.CmdlineSlice, _ = pro.CmdlineSlice()\n\tprocessinfo.CreateTime, _ = pro.CreateTime()\n\tprocessinfo.Cwd, _ = pro.Cwd()\n\tprocessinfo.Parent, _ = pro.Parent()\n\tprocessinfo.Status, _ = pro.Status()\n\tprocessinfo.Uids, _ = pro.Uids()\n\tprocessinfo.Gids, _ = pro.Gids()\n\tprocessinfo.Terminal, _ = pro.Terminal()\n\tprocessinfo.Nice, _ = pro.Nice()\n\tprocessinfo.IOnice, _ = pro.IOnice()\n\tprocessinfo.Rlimit, _ = pro.Rlimit()\n\tprocessinfo.IOCounters, _ = pro.IOCounters()\n\tprocessinfo.NumCtxSwitches, _ = pro.NumCtxSwitches()\n\tprocessinfo.NumFDs, _ = pro.NumFDs()\n\tprocessinfo.NumThreads, _ = pro.NumThreads()\n\tprocessinfo.Threads, _ = pro.Threads()\n\tprocessinfo.Times, _ = pro.Times()\n\tprocessinfo.CPUAffinity, _ = pro.CPUAffinity()\n\tprocessinfo.MemoryInfo, _ = pro.MemoryInfo()\n\tprocessinfo.MemoryInfoEx, _ = pro.MemoryInfoEx()\n\tprocessinfo.Children, _ = pro.Children()\n\tprocessinfo.OpenFiles, _ = pro.OpenFiles()\n\tprocessinfo.Connections, _ = pro.Connections()\n\tprocessinfo.NetIOCounters, _ = pro.NetIOCounters(true)\n\tprocessinfo.IsRunning, _ = pro.IsRunning()\n\tprocessinfo.MemoryMaps, _ = pro.MemoryMaps(true)\n\n\tpStatus := processinfo.Status\n\tswitch {\n\tcase pStatus == \"S\":\n\t\tpStatus = \"Status: sleeping\"\n\tcase pStatus == \"R\":\n\t\tpStatus = \"Status: running\"\n\tcase pStatus == \"T\":\n\t\tpStatus = \"Status: stopped\"\n\tcase pStatus == \"I\":\n\t\tpStatus = \"Status: idle\"\n\tcase pStatus == \"Z\":\n\t\tpStatus = \"Status: Zombie\"\n\tcase pStatus == \"W\":\n\t\tpStatus = \"Status: waiting\"\n\tcase pStatus == \"L\":\n\t\tpStatus = \"Status: locked\"\n\t}\n\tprocessinfo.ReadableStatus = pStatus\n\trunning_since_seconds := processinfo.CreateTime\n\trunning_since := humanize.RelTime(time.Unix(running_since_seconds/1000, 0), time.Now(), \"ago\", \"error\")\n\tprocessinfo.ReadableSince = fmt.Sprintf(\"Started %v\", running_since)\n\n\tp := ProcessInfo(*processinfo)\n\n\treturn p\n}", "func GetSystemMemory() *System {\n\tinfo, err := mem.VirtualMemory()\n\tif err != nil {\n\t\tfmt.Printf(\"mem.VirtualMemory error: %v\\n\", err)\n\t\treturn &System{}\n\t}\n\n\treturn &System{\n\t\tTotal: info.Total >> 20,\n\t\tFree: info.Free >> 20,\n\t\tUsagePercent: info.UsedPercent,\n\t}\n}", "func (cg *CGroup) GetMemoryStats() (map[string]uint64, error) {\n\tvar (\n\t\terr error\n\t\tstats string\n\t)\n\n\tout := make(map[string]uint64)\n\n\tversion := cgControllers[\"memory\"]\n\tswitch version {\n\tcase Unavailable:\n\t\treturn nil, ErrControllerMissing\n\tcase V1, V2:\n\t\tstats, err = cg.rw.Get(version, \"memory\", \"memory.stat\")\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, stat := range strings.Split(stats, \"\\n\") {\n\t\tfield := strings.Split(stat, \" \")\n\n\t\tswitch field[0] {\n\t\tcase \"total_active_anon\", \"active_anon\":\n\t\t\tout[\"active_anon\"], _ = strconv.ParseUint(field[1], 10, 64)\n\t\tcase \"total_active_file\", \"active_file\":\n\t\t\tout[\"active_file\"], _ = strconv.ParseUint(field[1], 10, 64)\n\t\tcase \"total_inactive_anon\", \"inactive_anon\":\n\t\t\tout[\"inactive_anon\"], _ = strconv.ParseUint(field[1], 10, 64)\n\t\tcase \"total_inactive_file\", \"inactive_file\":\n\t\t\tout[\"inactive_file\"], _ = strconv.ParseUint(field[1], 10, 64)\n\t\tcase \"total_unevictable\", \"unevictable\":\n\t\t\tout[\"unevictable\"], _ = strconv.ParseUint(field[1], 10, 64)\n\t\tcase \"total_writeback\", \"file_writeback\":\n\t\t\tout[\"writeback\"], _ = strconv.ParseUint(field[1], 10, 64)\n\t\tcase \"total_dirty\", \"file_dirty\":\n\t\t\tout[\"dirty\"], _ = strconv.ParseUint(field[1], 10, 64)\n\t\tcase \"total_mapped_file\", \"file_mapped\":\n\t\t\tout[\"mapped\"], _ = strconv.ParseUint(field[1], 10, 64)\n\t\tcase \"total_rss\": // v1 only\n\t\t\tout[\"rss\"], _ = strconv.ParseUint(field[1], 10, 64)\n\t\tcase \"total_shmem\", \"shmem\":\n\t\t\tout[\"shmem\"], _ = strconv.ParseUint(field[1], 10, 64)\n\t\tcase \"total_cache\", \"file\":\n\t\t\tout[\"cache\"], _ = strconv.ParseUint(field[1], 10, 64)\n\t\t}\n\t}\n\n\t// Calculated values\n\tout[\"active\"] = out[\"active_anon\"] + out[\"active_file\"]\n\tout[\"inactive\"] = out[\"inactive_anon\"] + out[\"inactive_file\"]\n\n\treturn out, nil\n}", "func getCPUUtilization() (*define.CPUUsage, error) {\n\tbuf, err := unix.SysctlRaw(\"kern.cp_time\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"reading sysctl kern.cp_time: %w\", err)\n\t}\n\n\tvar total uint64 = 0\n\tvar times [unix.CPUSTATES]uint64\n\n\tfor i := 0; i < unix.CPUSTATES; i++ {\n\t\tval := *(*uint64)(unsafe.Pointer(&buf[8*i]))\n\t\ttimes[i] = val\n\t\ttotal += val\n\t}\n\treturn &define.CPUUsage{\n\t\tUserPercent: timeToPercent(times[unix.CP_USER], total),\n\t\tSystemPercent: timeToPercent(times[unix.CP_SYS], total),\n\t\tIdlePercent: timeToPercent(times[unix.CP_IDLE], total),\n\t}, nil\n}", "func GetMemInfoUsageKB() (int64, error) {\n\tmeminfoPath := system.GetProcFilePath(system.ProcMemInfoName)\n\tmemInfo, err := readMemInfo(meminfoPath)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tusage := int64(memInfo.MemTotal - memInfo.MemAvailable)\n\treturn usage, nil\n}", "func (p *ProcessState) Sys() interface{} {\n\treturn nil // TODO\n}", "func GetTotalSystemMemory() uint64 {\n\treturn 0\n}", "func (r *Registry) MsgInfo(ctx context.Context) *linux.MsgInfo {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\n\tvar messages, bytes uint64\n\tr.reg.ForAllObjects(\n\t\tfunc(o ipc.Mechanism) {\n\t\t\tq := o.(*Queue)\n\t\t\tq.mu.Lock()\n\t\t\tmessages += q.messageCount\n\t\t\tbytes += q.byteCount\n\t\t\tq.mu.Unlock()\n\t\t},\n\t)\n\n\treturn &linux.MsgInfo{\n\t\tMsgPool: int32(r.reg.ObjectCount()),\n\t\tMsgMap: int32(messages),\n\t\tMsgTql: int32(bytes),\n\t\tMsgMax: linux.MSGMAX,\n\t\tMsgMnb: linux.MSGMNB,\n\t\tMsgMni: linux.MSGMNI,\n\t\tMsgSsz: linux.MSGSSZ,\n\t\tMsgSeg: linux.MSGSEG,\n\t}\n}", "func GetSystemCPUUsage() (uint64, error) {\n\tvar line string\n\tf, err := os.Open(\"/proc/stat\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tbufReader := bufio.NewReaderSize(nil, 128)\n\tdefer func() {\n\t\tbufReader.Reset(nil)\n\t\tf.Close()\n\t}()\n\tbufReader.Reset(f)\n\terr = nil\n\tfor err == nil {\n\t\tline, err = bufReader.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tparts := strings.Fields(line)\n\t\tswitch parts[0] {\n\t\tcase \"cpu\":\n\t\t\tif len(parts) < 8 {\n\t\t\t\treturn 0, fmt.Errorf(\"bad format of cpu stats\")\n\t\t\t}\n\t\t\tvar totalClockTicks uint64\n\t\t\tfor _, i := range parts[1:8] {\n\t\t\t\tv, err := strconv.ParseUint(i, 10, 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn 0, fmt.Errorf(\"error parsing cpu stats\")\n\t\t\t\t}\n\t\t\t\ttotalClockTicks += v\n\t\t\t}\n\t\t\treturn (totalClockTicks * nanoSecondsPerSecond) /\n\t\t\t\tclockTicksPerSecond, nil\n\t\t}\n\t}\n\treturn 0, fmt.Errorf(\"bad stats format\")\n}", "func getServerStatsMemory(printDetails bool){\n\n\t/*\n\tresident, virtual, err := getServerStatsMemory(true)\n\tif err == nil {\n\t\tfmt.Printf(\"phys. Memory is %v - of data stock size of %v (useful only on mongod)\\n\",resident, virtual)\n\t} else {\n\t\tfmt.Println(\"no mem info\", err )\n\t}\n\t*/\n\t\n}", "func ProcStat(c *gin.Context) {\n\tres := CmdExec(\"cat /proc/stat | head -n 1 | awk '{$1=\\\"\\\";print}'\")\n\tresArray := strings.Split(res[0], \" \")\n\tvar cpu []int64\n\tvar totalcpu, idlecpu int64\n\tfor _, v := range resArray {\n\t\ttemp, err := strconv.ParseInt(v, 10, 64)\n\t\tif err == nil {\n\t\t\tcpu = append(cpu, temp)\n\t\t\ttotalcpu = totalcpu + temp\n\t\t}\n\t}\n\tidlecpu = cpu[3]\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"totalcpu\": totalcpu,\n\t\t\"idlecpu\": idlecpu,\n\t})\n}", "func GetSysMetric() (*SysMetric, error) {\n\tvar m SysMetric\n\n\tcpu, err := cpu.Get()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tm.CPUCores = cpu.CPUCount\n\n\tmemory, err := memory.Get()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tm.MemoryBytes = memory.Total\n\tm.MemoryBytesUsed = memory.Used\n\n\tm.DiskBytes = getDiskSizeTotal(C.Dir)\n\tm.DiskBytesUsed = getDiskSizeUsed(C.Dir)\n\n\treturn &m, nil\n}", "func cmdInfo() {\n\tif err := vbm(\"showvminfo\", B2D.VM); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (fs *fileStat) Sys() any {\n\treturn &syscall.Win32FileAttributeData{\n\t\tFileAttributes: fs.FileAttributes,\n\t\tCreationTime: fs.CreationTime,\n\t\tLastAccessTime: fs.LastAccessTime,\n\t\tLastWriteTime: fs.LastWriteTime,\n\t\tFileSizeHigh: fs.FileSizeHigh,\n\t\tFileSizeLow: fs.FileSizeLow,\n\t}\n}", "func LogCurrentSystemLoad(logFunc LogFunc) {\n\tloadInfo, err := load.Avg()\n\tif err == nil {\n\t\tlogFunc(\"Load 1-min: %.2f 5-min: %.2f 15min: %.2f\",\n\t\t\tloadInfo.Load1, loadInfo.Load5, loadInfo.Load15)\n\t}\n\n\tmemInfo, err := mem.VirtualMemory()\n\tif err == nil && memInfo != nil {\n\t\tlogFunc(\"Memory: Total: %d Used: %d (%.2f%%) Free: %d Buffers: %d Cached: %d\",\n\t\t\ttoMB(memInfo.Total), toMB(memInfo.Used), memInfo.UsedPercent, toMB(memInfo.Free), toMB(memInfo.Buffers), toMB(memInfo.Cached))\n\t}\n\n\tswapInfo, err := mem.SwapMemory()\n\tif err == nil && swapInfo != nil {\n\t\tlogFunc(\"Swap: Total: %d Used: %d (%.2f%%) Free: %d\",\n\t\t\ttoMB(swapInfo.Total), toMB(swapInfo.Used), swapInfo.UsedPercent, toMB(swapInfo.Free))\n\t}\n\n\tprocs, err := process.Processes()\n\tif err == nil {\n\t\tfor _, p := range procs {\n\t\t\tcpuPercent, _ := p.CPUPercent()\n\t\t\tif cpuPercent > cpuWatermark {\n\t\t\t\tname, _ := p.Name()\n\t\t\t\tstatus, _ := p.Status()\n\t\t\t\tmemPercent, _ := p.MemoryPercent()\n\t\t\t\tcmdline, _ := p.Cmdline()\n\n\t\t\t\tmemExt := \"\"\n\t\t\t\tif memInfo, err := p.MemoryInfo(); memInfo != nil && err == nil {\n\t\t\t\t\tmemExt = fmt.Sprintf(\"RSS: %d VMS: %d Data: %d Stack: %d Locked: %d Swap: %d\",\n\t\t\t\t\t\ttoMB(memInfo.RSS), toMB(memInfo.VMS), toMB(memInfo.Data),\n\t\t\t\t\t\ttoMB(memInfo.Stack), toMB(memInfo.Locked), toMB(memInfo.Swap))\n\t\t\t\t}\n\n\t\t\t\tlogFunc(\"NAME %s STATUS %s PID %d CPU: %.2f%% MEM: %.2f%% CMDLINE: %s MEM-EXT: %s\",\n\t\t\t\t\tname, status, p.Pid, cpuPercent, memPercent, cmdline, memExt)\n\t\t\t}\n\t\t}\n\t}\n}", "func systemMemoryMonitor(logger *logrus.Logger, wg *sync.WaitGroup, done chan struct{}, kill chan struct{}) {\n\tdefer wg.Done()\n\tdefer close(kill)\n\n\tvar swapUsedBaseline uint64 = math.MaxUint64\n\n\tfor {\n\t\tselect {\n\t\tcase <-done:\n\t\t\treturn\n\t\tcase <-time.After(1 * time.Second):\n\t\t}\n\n\t\tctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)\n\t\tmemStat, err := mem.VirtualMemoryWithContext(ctx)\n\n\t\tif err != nil {\n\t\t\tlogger.WithError(err).Debugf(\"Failed to retrieve memory usage.\")\n\t\t}\n\n\t\tcancel()\n\n\t\tctx, cancel = context.WithTimeout(context.Background(), 100*time.Millisecond)\n\t\tswapStat, err := mem.SwapMemoryWithContext(ctx)\n\n\t\tif err != nil {\n\t\t\tlogger.WithError(err).Debugf(\"Failed to retrieve swap usage.\")\n\t\t}\n\n\t\tcancel()\n\n\t\tswapUsed := uint64(0)\n\t\tif swapStat.Used < swapUsedBaseline {\n\t\t\tswapUsed = swapStat.Used\n\t\t} else {\n\t\t\tswapUsed = swapStat.Used - swapUsedBaseline\n\t\t}\n\n\t\tused := float64(memStat.Used+swapUsed) / float64(memStat.Total)\n\t\tlogger.Debugf(\n\t\t\t\"Memory usage: %.2f%% - RAM %s / Swap %s.\",\n\t\t\tused*100,\n\t\t\thumanBytes(memStat.Used),\n\t\t\thumanBytes(swapUsed),\n\t\t)\n\n\t\tif used > 0.9 {\n\t\t\treturn\n\t\t}\n\t}\n}", "func RamUsage() {\r\n v, _ := mem.VirtualMemory()\r\n fmt.Printf(\"RAM{ Total: %v, Free:%v, UsedPercent:%f%%}\\n\", v.Total, v.Free, v.UsedPercent)\r\n}", "func perfInfo() ([]win32_SystemProcessorPerformanceInformation, error) {\n\t// Make maxResults large for safety.\n\t// We can't invoke the api call with a results array that's too small.\n\t// If we have more than 2056 cores on a single host, then it's probably the future.\n\tmaxBuffer := 2056\n\t// buffer for results from the windows proc\n\tresultBuffer := make([]win32_SystemProcessorPerformanceInformation, maxBuffer)\n\t// size of the buffer in memory\n\tbufferSize := uintptr(win32_SystemProcessorPerformanceInfoSize) * uintptr(maxBuffer)\n\t// size of the returned response\n\tvar retSize uint32\n\n\t// Invoke windows api proc.\n\t// The returned err from the windows dll proc will always be non-nil even when successful.\n\t// See https://godoc.org/golang.org/x/sys/windows#LazyProc.Call for more information\n\tretCode, _, err := common.ProcNtQuerySystemInformation.Call(\n\t\twin32_SystemProcessorPerformanceInformationClass, // System Information Class -> SystemProcessorPerformanceInformation\n\t\tuintptr(unsafe.Pointer(&resultBuffer[0])), // pointer to first element in result buffer\n\t\tbufferSize, // size of the buffer in memory\n\t\tuintptr(unsafe.Pointer(&retSize)), // pointer to the size of the returned results the windows proc will set this\n\t)\n\n\t// check return code for errors\n\tif retCode != 0 {\n\t\treturn nil, fmt.Errorf(\"call to NtQuerySystemInformation returned %d. err: %s\", retCode, err.Error())\n\t}\n\n\t// calculate the number of returned elements based on the returned size\n\tnumReturnedElements := retSize / win32_SystemProcessorPerformanceInfoSize\n\n\t// trim results to the number of returned elements\n\tresultBuffer = resultBuffer[:numReturnedElements]\n\n\treturn resultBuffer, nil\n}", "func sysAlloc(n uintptr, sysStat *uint64) unsafe.Pointer {\n\tp := mmap(nil, n, _PROT_READ|_PROT_WRITE, _MAP_ANON|_MAP_PRIVATE, -1, 0)\n\tif uintptr(p) < 4096 {\n\t\tif uintptr(p) == _EACCES {\n\t\t\tprint(\"runtime: mmap: access denied\\n\")\n\t\t\texit(2)\n\t\t}\n\t\tif uintptr(p) == _EAGAIN {\n\t\t\tprint(\"runtime: mmap: too much locked memory (check 'ulimit -l').\\n\")\n\t\t\texit(2)\n\t\t}\n\t\treturn nil\n\t}\n\tmSysStatInc(sysStat, n)\n\treturn p\n}", "func (i *Info) Sys() interface{} {\n\treturn nil\n}", "func sysctl(mib []C.int, old *byte, oldlen *uintptr,\n\tnew *byte, newlen uintptr) (err error) {\n\tvar p0 unsafe.Pointer\n\tp0 = unsafe.Pointer(&mib[0])\n\t_, _, e1 := syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(p0),\n\t\tuintptr(len(mib)),\n\t\tuintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)),\n\t\tuintptr(unsafe.Pointer(new)), uintptr(newlen))\n\tif e1 != 0 {\n\t\terr = e1\n\t}\n\treturn\n}", "func GetFSInfo(path string) (total, available int) {\n\ttotal = -1\n\tavailable = -1\n\tvar buf syscall.Statfs_t\n\n\tif syscall.Statfs(path, &buf) != nil {\n\t\treturn\n\t}\n\n\tif buf.Bsize <= 0 {\n\t\treturn\n\t}\n\n\ttotal = int((uint64(buf.Bsize) * buf.Blocks) / (1000 * 1000))\n\tavailable = int((uint64(buf.Bsize) * buf.Bavail) / (1000 * 1000))\n\n\treturn\n}", "func hwinfo() string {\n\tb1, err := exec.Command(\"vcgencmd\", \"measure_clock\", \"arm\").Output()\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tb2, err := exec.Command(\"vcgencmd\", \"measure_clock\", \"core\").Output()\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tif len(b1) < 17 || len(b2) < 17 {\n\t\treturn \"bad len\"\n\t}\n\treturn fmt.Sprintf(\"arm=%sMhz core=%sMHz\", b1[14:17], b2[13:16])\n}", "func (fs FS) Meminfo() (Meminfo, error) {\n\tb, err := util.ReadFileNoStat(fs.proc.Path(\"meminfo\"))\n\tif err != nil {\n\t\treturn Meminfo{}, err\n\t}\n\n\tm, err := parseMemInfo(bytes.NewReader(b))\n\tif err != nil {\n\t\treturn Meminfo{}, fmt.Errorf(\"failed to parse meminfo: %w\", err)\n\t}\n\n\treturn *m, nil\n}", "func ReadMemInfo() *map[string]uint64 {\n\tdata, err := os.ReadFile(\"/proc/meminfo\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tresult := map[string]uint64{}\n\tfor _, line := range strings.Split(string(data), \"\\n\") {\n\t\tkey, value := parseMemInfoLine(line)\n\t\tif key != \"\" {\n\t\t\tresult[key] = value\n\t\t}\n\t}\n\treturn &result\n}", "func GetSysCPUCount() int {\n\treturn runtime.NumCPU()\n}", "func printMemUsage() string {\n\tvar m runtime.MemStats\n\truntime.ReadMemStats(&m)\n\t// For info on each, see: https://golang.org/pkg/runtime/#MemStats\n\treturn fmt.Sprintf(\"Alloc = %v MiB\\tTotalAlloc = %v MiB\\tSys = %v MiB\\tNumGC = %v\\n\", bToMb(m.Alloc),\n\t\tbToMb(m.TotalAlloc), bToMb(m.Sys), m.NumGC)\n}", "func getBoottime() (int64, error) {\n\n\t//this seems to be how dmesg -T does it\n\t//This is dmesg's 'faillback' method as getting access to clock_gettime() from go is more trouble than it's worth.\n\ttv := &syscall.Timeval{}\n\terr := syscall.Gettimeofday(tv)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tinfo := &syscall.Sysinfo_t{}\n\tsyscall.Sysinfo(info)\n\n\treturn (tv.Sec - info.Uptime), nil\n}", "func extraServiceInfo() map[string]interface{} {\n\textraInfo := make(map[string]interface{})\n\textraInfo[\"uptime\"] = time.Now().Round(time.Second).Sub(startTime).String()\n\textraInfo[\"hit count: /profiler/info.html\"] = atomic.LoadUint64(&infoHTMLHitCount)\n\textraInfo[\"hit count: /profiler/info\"] = atomic.LoadUint64(&infoHitCount)\n\treturn extraInfo\n}", "func getOSInfo(c context.Context, b *buildbotBuild, m *buildbotMaster) (\n\tfamily, version string) {\n\t// Fetch the master info from datastore if not provided.\n\tif m.Name == \"\" {\n\t\tlogging.Infof(c, \"Fetching info for master %s\", b.Master)\n\t\tentry := buildbotMasterEntry{Name: b.Master}\n\t\terr := ds.Get(c, &entry)\n\t\tif err != nil {\n\t\t\tlogging.WithError(err).Errorf(\n\t\t\t\tc, \"Encountered error while fetching entry for %s\", b.Master)\n\t\t\treturn\n\t\t}\n\t\terr = decodeMasterEntry(c, &entry, m)\n\t\tif err != nil {\n\t\t\tlogging.WithError(err).Warningf(\n\t\t\t\tc, \"Failed to decode master information for OS info on master %s\", b.Master)\n\t\t\treturn\n\t\t}\n\t\tif entry.Internal && !b.Internal {\n\t\t\tlogging.Errorf(c, \"Build references an internal master, but build is not internal.\")\n\t\t\treturn\n\t\t}\n\t}\n\n\ts, ok := m.Slaves[b.Slave]\n\tif !ok {\n\t\tlogging.Warningf(c, \"Could not find slave %s in master %s\", b.Slave, b.Master)\n\t\treturn\n\t}\n\thostInfo := map[string]string{}\n\tfor _, v := range strings.Split(s.Host, \"\\n\") {\n\t\tif info := strings.SplitN(v, \":\", 2); len(info) == 2 {\n\t\t\thostInfo[info[0]] = strings.TrimSpace(info[1])\n\t\t}\n\t}\n\t// Extract OS and OS Family\n\tif v, ok := hostInfo[\"os family\"]; ok {\n\t\tfamily = v\n\t}\n\tif v, ok := hostInfo[\"os version\"]; ok {\n\t\tversion = v\n\t}\n\treturn\n}", "func (proc *Process) getDetails(cmdline string) error {\n\n\tmem := sigar.ProcMem{}\n\tif err := mem.Get(proc.Pid); err != nil {\n\t\treturn fmt.Errorf(\"error getting process mem for pid=%d: %v\", proc.Pid, err)\n\t}\n\tproc.Mem = &ProcMemStat{\n\t\tSize: mem.Size,\n\t\tRss: mem.Resident,\n\t\tShare: mem.Share,\n\t}\n\n\tcpu := sigar.ProcTime{}\n\tif err := cpu.Get(proc.Pid); err != nil {\n\t\treturn fmt.Errorf(\"error getting process cpu time for pid=%d: %v\", proc.Pid, err)\n\t}\n\tproc.Cpu = &ProcCpuTime{\n\t\tStart: cpu.FormatStartTime(),\n\t\tTotal: cpu.Total,\n\t\tUser: cpu.User,\n\t\tSystem: cpu.Sys,\n\t}\n\n\tif cmdline == \"\" {\n\t\targs := sigar.ProcArgs{}\n\t\tif err := args.Get(proc.Pid); err != nil {\n\t\t\treturn fmt.Errorf(\"error getting process arguments for pid=%d: %v\", proc.Pid, err)\n\t\t}\n\t\tproc.CmdLine = strings.Join(args.List, \" \")\n\t} else {\n\t\tproc.CmdLine = cmdline\n\t}\n\n\treturn nil\n}", "func GetNVMInfo() (info.NVMInfo, error) {\n\tnvmInfo := info.NVMInfo{}\n\t// Initialize libipmctl library.\n\tcErr := C.nvm_init()\n\tif cErr != C.NVM_SUCCESS {\n\t\tklog.Warningf(\"libipmctl initialization failed with status %d\", cErr)\n\t\treturn info.NVMInfo{}, fmt.Errorf(\"libipmctl initialization failed with status %d\", cErr)\n\t}\n\tdefer C.nvm_uninit()\n\n\tvar err error\n\tnvmInfo.MemoryModeCapacity, nvmInfo.AppDirectModeCapacity, err = getNVMCapacities()\n\tif err != nil {\n\t\treturn info.NVMInfo{}, fmt.Errorf(\"Unable to get NVM capacities, err: %s\", err)\n\t}\n\n\tnvmInfo.AvgPowerBudget, err = getNVMAvgPowerBudget()\n\tif err != nil {\n\t\treturn info.NVMInfo{}, fmt.Errorf(\"Unable to get NVM average power budget, err: %s\", err)\n\t}\n\treturn nvmInfo, nil\n}", "func (r *Registry) IPCInfo(ctx context.Context) *linux.MsgInfo {\n\treturn &linux.MsgInfo{\n\t\tMsgPool: linux.MSGPOOL,\n\t\tMsgMap: linux.MSGMAP,\n\t\tMsgMax: linux.MSGMAX,\n\t\tMsgMnb: linux.MSGMNB,\n\t\tMsgMni: linux.MSGMNI,\n\t\tMsgSsz: linux.MSGSSZ,\n\t\tMsgTql: linux.MSGTQL,\n\t\tMsgSeg: linux.MSGSEG,\n\t}\n}", "func (s *Stats) GetMemoryInfo(logMemory, logGoMemory bool) {\n\n if logGoMemory {\n if s.GoInfo == nil {\n s.initGoInfo()\n }\n\n runtime.ReadMemStats(s.GoInfo.Memory.mem)\n s.GoInfo.GoRoutines = runtime.NumGoroutine()\n s.GoInfo.Memory.Alloc = s.GoInfo.Memory.mem.Alloc\n s.GoInfo.Memory.HeapAlloc = s.GoInfo.Memory.mem.HeapAlloc\n s.GoInfo.Memory.HeapSys = s.GoInfo.Memory.mem.HeapSys\n\n if s.GoInfo.Memory.LastGC != s.GoInfo.Memory.mem.LastGC {\n s.GoInfo.Memory.LastGC = s.GoInfo.Memory.mem.LastGC\n s.GoInfo.Memory.NumGC = s.GoInfo.Memory.mem.NumGC - s.GoInfo.Memory.lastNumGC\n s.GoInfo.Memory.lastNumGC = s.GoInfo.Memory.mem.NumGC\n s.GoInfo.Memory.LastGCPauseDuration = s.GoInfo.Memory.mem.PauseNs[(s.GoInfo.Memory.mem.NumGC+255)%256]\n } else {\n s.GoInfo.Memory.NumGC = 0\n s.GoInfo.Memory.LastGCPauseDuration = 0\n }\n }\n\n if logMemory {\n\n if s.MemInfo == nil {\n s.MemInfo = new(MemInfo)\n }\n\n s.MemInfo.Memory, _ = mem.VirtualMemory()\n s.MemInfo.Swap, _ = mem.SwapMemory()\n }\n}", "func Info(path string) (int64, int64, int64, int64, int64, int64, error) {\n\tstatfs := &unix.Statfs_t{}\n\terr := unix.Statfs(path, statfs)\n\tif err != nil {\n\t\treturn 0, 0, 0, 0, 0, 0, err\n\t}\n\n\t// Available is blocks available * fragment size\n\tavailable := int64(statfs.Bavail) * int64(statfs.Bsize)\n\n\t// Capacity is total block count * fragment size\n\tcapacity := int64(statfs.Blocks) * int64(statfs.Bsize)\n\n\t// Usage is block being used * fragment size (aka block size).\n\tusage := (int64(statfs.Blocks) - int64(statfs.Bfree)) * int64(statfs.Bsize)\n\n\tinodes := int64(statfs.Files)\n\tinodesFree := int64(statfs.Ffree)\n\tinodesUsed := inodes - inodesFree\n\n\treturn available, capacity, usage, inodes, inodesFree, inodesUsed, nil\n}", "func getMainMemInfo(m meminfomap) (*mainMemInfo, error) {\n\tfields := []string{\n\t\t\"MemTotal\",\n\t\t\"MemFree\",\n\t\t\"Buffers\",\n\t\t\"Cached\",\n\t\t\"Shmem\",\n\t\t\"SReclaimable\",\n\t\t\"MemAvailable\",\n\t}\n\tif missingRequiredFields(m, fields) {\n\t\treturn nil, fmt.Errorf(\"missing required fields from meminfo\")\n\t}\n\n\t// These values are expressed in kibibytes, convert to the desired unit\n\tmemTotal := m[\"MemTotal\"] << KB\n\tmemFree := m[\"MemFree\"] << KB\n\tmemShared := m[\"Shmem\"] << KB\n\tmemCached := (m[\"Cached\"] + m[\"SReclaimable\"]) << KB\n\tmemBuffers := (m[\"Buffers\"]) << KB\n\tmemUsed := memTotal - memFree - memCached - memBuffers\n\tmemAvailable := m[\"MemAvailable\"] << KB\n\n\tmmi := mainMemInfo{\n\t\tTotal: memTotal,\n\t\tUsed: memUsed,\n\t\tFree: memFree,\n\t\tShared: memShared,\n\t\tCached: memCached,\n\t\tBuffers: memBuffers,\n\t\tAvailable: memAvailable,\n\t}\n\treturn &mmi, nil\n}", "func getCpuMem() (float64, float64) {\n\tvar sumCPU, sumMEM float64\n\tcmd := exec.Command(\"ps\", \"aux\") // ps aux is the command used to get cpu and ram usage\n\tvar out bytes.Buffer\n\tcmd.Stdout = &out //catching the command output\n\terr := cmd.Run() //running the command\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor {\n\t\tline, err := out.ReadString('\\n') //breaking the output in lines\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\ttokens := strings.Split(line, \" \") //spliting each output line\n\t\tft := make([]string, 0)\n\t\tfor _, t := range tokens {\n\t\t\tif t != \"\" && t != \"\\t\" {\n\t\t\t\tft = append(ft, t) //for each line there is a buffer (ft) that keeps all the parameters\n\t\t\t}\n\t\t}\n\t\tif cpu, err := strconv.ParseFloat(ft[2], 32); err == nil { // parsing the cpu variable, as string, to float\n\t\t\tsumCPU += cpu //all the cpu's used capacity at the instant\n\t\t}\n\t\tif mem, err := strconv.ParseFloat(ft[3], 32); err == nil { // parsing the ram variable, as string, to float\n\t\t\tsumMEM += mem //all the ram's used capacity at the instant\n\t\t}\n\t}\n\tlog.Println(\"Used CPU\", sumCPU/8, \"%\", \" Used Memory RAM\", sumMEM, \"%\")\n\treturn sumCPU / 8, sumMEM //the cpu's total used capacity is splitted by 8 because its the total number of my PC's cores\n\t//otherwise, we would see outputs bigger than 100%\n}", "func report(p *rc.Process, wallTime time.Duration) {\n\tsv, err := p.SystemVersion()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tss, err := p.SystemStatus()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tproc, err := p.Stop()\n\tif err != nil {\n\t\treturn\n\t}\n\n\trusage, ok := proc.SysUsage().(*syscall.Rusage)\n\tif !ok {\n\t\treturn\n\t}\n\n\tlog.Println(\"Version:\", sv.Version)\n\tlog.Println(\"Alloc:\", ss.Alloc/1024, \"KiB\")\n\tlog.Println(\"Sys:\", ss.Sys/1024, \"KiB\")\n\tlog.Println(\"Goroutines:\", ss.Goroutines)\n\tlog.Println(\"Wall time:\", wallTime)\n\tlog.Println(\"Utime:\", time.Duration(rusage.Utime.Nano()))\n\tlog.Println(\"Stime:\", time.Duration(rusage.Stime.Nano()))\n\tif runtime.GOOS == \"darwin\" {\n\t\t// Darwin reports in bytes, Linux seems to report in KiB even\n\t\t// though the manpage says otherwise.\n\t\trusage.Maxrss /= 1024\n\t}\n\tlog.Println(\"MaxRSS:\", rusage.Maxrss, \"KiB\")\n\n\tfmt.Printf(\"%s,%d,%d,%d,%.02f,%.02f,%.02f,%d\\n\",\n\t\tsv.Version,\n\t\tss.Alloc/1024,\n\t\tss.Sys/1024,\n\t\tss.Goroutines,\n\t\twallTime.Seconds(),\n\t\ttime.Duration(rusage.Utime.Nano()).Seconds(),\n\t\ttime.Duration(rusage.Stime.Nano()).Seconds(),\n\t\trusage.Maxrss)\n}", "func GetRuntimeStats() (result map[string]float64) {\n\truntime.ReadMemStats(memStats)\n\n\tnow = time.Now()\n\tdiffTime = now.Sub(lastSampleTime).Seconds()\n\n\tresult = map[string]float64{\n\t\t\"alloc\": float64(memStats.Alloc),\n\t\t\"frees\": float64(memStats.Frees),\n\t\t\"gc.pause_total\": float64(memStats.PauseTotalNs) / nsInMs,\n\t\t\"heap.alloc\": float64(memStats.HeapAlloc),\n\t\t\"heap.objects\": float64(memStats.HeapObjects),\n\t\t\"mallocs\": float64(memStats.Mallocs),\n\t\t\"stack\": float64(memStats.StackInuse),\n\t}\n\n\tif lastPauseNs > 0 {\n\t\tpauseSinceLastSample = memStats.PauseTotalNs - lastPauseNs\n\t\tresult[\"gc.pause_per_second\"] = float64(pauseSinceLastSample) / nsInMs / diffTime\n\t}\n\n\tlastPauseNs = memStats.PauseTotalNs\n\n\tnbGc = memStats.NumGC - lastNumGc\n\tif lastNumGc > 0 {\n\t\tresult[\"gc.gc_per_second\"] = float64(nbGc) / diffTime\n\t}\n\n\t// Collect GC pauses\n\tif nbGc > 0 {\n\t\tif nbGc > 256 {\n\t\t\tnbGc = 256\n\t\t}\n\n\t\tvar i uint32\n\n\t\tfor i = 0; i < nbGc; i++ {\n\t\t\tidx := int((memStats.NumGC-uint32(i))+255) % 256\n\t\t\tpause := float64(memStats.PauseNs[idx])\n\t\t\tresult[\"gc.pause\"] = pause / nsInMs\n\t\t}\n\t}\n\n\t// Store last values\n\tlastNumGc = memStats.NumGC\n\tlastSampleTime = now\n\n\treturn result\n}", "func TestGetProgInfo(t *testing.T) {\n\tdisableFunc, err := enableBPFStats()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer disableFunc()\n\n\tspecs, err := newGetproginfoSpecs()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tprog, err := ebpf.NewProgram(specs.ProgramOpen)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer prog.Close()\n\n\tlink, err := link.AttachRawTracepoint(link.RawTracepointOptions{\n\t\tName: \"sys_enter\",\n\t\tProgram: prog,\n\t})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif link == nil {\n\t\tt.Fatal(\"no link\")\n\t}\n\tdefer link.Close()\n\n\tf, err := os.Open(\"/etc/os-release\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tf.Close()\n\n\tstats, err := getProgramStats(prog.FD())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif stats.RunCount == 0 {\n\t\tt.Errorf(\"run count should be non-zero\")\n\t}\n\tif stats.RunTime == 0 {\n\t\tt.Errorf(\"run time should be non-zero\")\n\t}\n}", "func GetSystemCpuUsage() (uint64, error) {\n\tvar (\n\t\tline string\n\t\tf *os.File\n\t\tusage uint64 = 0\n\t\terr error\n\t)\n\tif f, err = os.Open(\"/proc/stat\"); err != nil {\n\t\treturn 0, err\n\t}\n\tbufReader := bufio.NewReaderSize(nil, 128)\n\tdefer func() {\n\t\tbufReader.Reset(nil)\n\t\tf.Close()\n\t}()\n\tbufReader.Reset(f)\n\tfor err == nil {\n\t\tif line, err = bufReader.ReadString('\\n'); err != nil {\n\t\t\terr = errors.WithStack(err)\n\t\t\treturn 0, err\n\t\t}\n\t\tarray := strings.Fields(line)\n\t\tswitch array[0] {\n\t\tcase \"cpu\": //只统计cpu那行的数据\n\t\t\tif len(array) < 8 {\n\t\t\t\terr = errors.WithStack(fmt.Errorf(\"bad format of cpu stats\"))\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t\tvar totalClockTicks uint64\n\t\t\tfor _, i := range array[1:8] {\n\t\t\t\tvar v uint64\n\t\t\t\tif v, err = strconv.ParseUint(i, 10, 64); err != nil {\n\t\t\t\t\terr = errors.WithStack(fmt.Errorf(\"error parsing cpu stats\"))\n\t\t\t\t\treturn 0, err\n\t\t\t\t}\n\t\t\t\ttotalClockTicks += v\n\t\t\t}\n\t\t\tusage = (totalClockTicks * nanoSecondsPerSecond) / clockTicksPerSecond\n\t\t\treturn usage, nil\n\t\t}\n\t}\n\terr = errors.Errorf(\"bad stats format\")\n\treturn 0, err\n}", "func (*procSysctl) GetSysctl(sysctl string) (string, error) {\n\tdata, err := os.ReadFile(path.Join(sysctlBase, sysctl))\n\tif err != nil {\n\t\treturn \"-1\", err\n\t}\n\tval := strings.Trim(string(data), \" \\n\")\n\treturn val, nil\n}", "func (s Sysinfo) Uptime() uint64 {\n\treturn s.uptime\n}", "func (p *UserAgent) OSInfo() OSInfo {\n\t// Special case for iPhone weirdness\n\tos := strings.Replace(p.os, \"like Mac OS X\", \"\", 1)\n\tos = strings.Replace(os, \"CPU\", \"\", 1)\n\tos = strings.Trim(os, \" \")\n\n\tosSplit := strings.Split(os, \" \")\n\n\t// Special case for x64 edition of Windows\n\tif os == \"Windows XP x64 Edition\" {\n\t\tosSplit = osSplit[:len(osSplit)-2]\n\t}\n\n\tname, version := osName(osSplit)\n\n\t// Special case for names that contain a forward slash version separator.\n\tif strings.Contains(name, \"/\") {\n\t\ts := strings.Split(name, \"/\")\n\t\tname = s[0]\n\t\tversion = s[1]\n\t}\n\n\t// Special case for versions that use underscores\n\tversion = strings.Replace(version, \"_\", \".\", -1)\n\n\treturn OSInfo{\n\t\tFullName: p.os,\n\t\tName: name,\n\t\tVersion: version,\n\t}\n}", "func rcMemStats(ctx context.Context, in Params) (out Params, err error) {\n\tout = make(Params)\n\tvar m runtime.MemStats\n\truntime.ReadMemStats(&m)\n\tout[\"Alloc\"] = m.Alloc\n\tout[\"TotalAlloc\"] = m.TotalAlloc\n\tout[\"Sys\"] = m.Sys\n\tout[\"Mallocs\"] = m.Mallocs\n\tout[\"Frees\"] = m.Frees\n\tout[\"HeapAlloc\"] = m.HeapAlloc\n\tout[\"HeapSys\"] = m.HeapSys\n\tout[\"HeapIdle\"] = m.HeapIdle\n\tout[\"HeapInuse\"] = m.HeapInuse\n\tout[\"HeapReleased\"] = m.HeapReleased\n\tout[\"HeapObjects\"] = m.HeapObjects\n\tout[\"StackInuse\"] = m.StackInuse\n\tout[\"StackSys\"] = m.StackSys\n\tout[\"MSpanInuse\"] = m.MSpanInuse\n\tout[\"MSpanSys\"] = m.MSpanSys\n\tout[\"MCacheInuse\"] = m.MCacheInuse\n\tout[\"MCacheSys\"] = m.MCacheSys\n\tout[\"BuckHashSys\"] = m.BuckHashSys\n\tout[\"GCSys\"] = m.GCSys\n\tout[\"OtherSys\"] = m.OtherSys\n\treturn out, nil\n}", "func (m *DeviceOperatingSystemSummary) GetMacOSCount()(*int32) {\n val, err := m.GetBackingStore().Get(\"macOSCount\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int32)\n }\n return nil\n}", "func TermInfo() (cols, lines int, err error) {\n\tcolsBytes, err := sh.Command(\"tput\", \"cols\").Output()\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\n\tlinesBytes, err := sh.Command(\"tput\", \"lines\").Output()\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\n\tcols, err = strconv.Atoi(string(colsBytes[:len(colsBytes)-1]))\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\n\tlines, err = strconv.Atoi(string(linesBytes[:len(linesBytes)-1]))\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\n\treturn cols, lines, nil\n}", "func procMem(_ int) (ProcMemStats, error) {\n\treturn ProcMemStats{}, nil\n}", "func (h *Handler) Info(c router.Control) {\n\thost, _ := os.Hostname()\n\tm := new(runtime.MemStats)\n\truntime.ReadMemStats(m)\n\n\tc.Code(http.StatusOK)\n\tc.Body(Status{\n\t\tHost: host,\n\t\tVersion: version.RELEASE,\n\t\tCommit: version.COMMIT,\n\t\tRepo: version.REPO,\n\t\tCompiler: runtime.Version(),\n\t\tRuntime: Runtime{\n\t\t\tCPU: runtime.NumCPU(),\n\t\t\tMemory: fmt.Sprintf(\"%.2fMB\", float64(m.Sys)/(1<<(10*2))),\n\t\t\tGoroutines: runtime.NumGoroutine(),\n\t\t},\n\t\tState: State{\n\t\t\tMaintenance: h.maintenance,\n\t\t\tUptime: time.Now().Sub(h.stats.startTime).String(),\n\t\t},\n\t\tRequests: Requests{\n\t\t\tDuration: Duration{\n\t\t\t\tAverage: h.stats.requests.Duration.Average,\n\t\t\t\tMax: h.stats.requests.Duration.Max,\n\t\t\t},\n\t\t\tCodes: Codes{\n\t\t\t\tC2xx: h.stats.requests.Codes.C2xx,\n\t\t\t\tC4xx: h.stats.requests.Codes.C4xx,\n\t\t\t\tC5xx: h.stats.requests.Codes.C5xx,\n\t\t\t},\n\t\t},\n\t})\n}", "func (s Sysinfo) MemFree() uint64 {\n\treturn s.memFree + s.memBuffer\n}", "func GetMemStats() string {\n\tvar memstats runtime.MemStats\n\truntime.ReadMemStats(&memstats)\n\treturn fmt.Sprintf(\"Alloc: %s, Sys: %s, GC: %d, PauseTotalNs: %dns\", humanize.Bytes(memstats.Alloc), humanize.Bytes(memstats.Sys), memstats.NumGC, memstats.PauseTotalNs)\n}", "func (s *Stats) GetAllCPUInfo() {\n s.GetCPUInfo()\n s.GetCPUTimes()\n}", "func (socket *MockSocket) SystemInfo() *socket.SystemInfoProtocol {\n\treturn socket.systemInfo\n}", "func GetSystemState(config config.ServerConfig, logger *util.Logger) (system state.SystemState) {\n\tdbHost := config.GetDbHost()\n\tif config.SystemType == \"amazon_rds\" {\n\t\tsystem = rds.GetSystemState(config, logger)\n\t} else if config.SystemType == \"google_cloudsql\" {\n\t\tsystem.Info.Type = state.GoogleCloudSQLSystem\n\t} else if config.SystemType == \"azure_database\" {\n\t\tsystem.Info.Type = state.AzureDatabaseSystem\n\t} else if config.SystemType == \"heroku\" {\n\t\tsystem.Info.Type = state.HerokuSystem\n\t} else if config.SystemType == \"crunchy_bridge\" {\n\t\t// We are assuming container apps are used, which means the collector\n\t\t// runs on the database server itself and can gather local statistics\n\t\tsystem = selfhosted.GetSystemState(config, logger)\n\t\tsystem.Info.Type = state.CrunchyBridgeSystem\n\t} else if dbHost == \"\" || dbHost == \"localhost\" || dbHost == \"127.0.0.1\" || config.AlwaysCollectSystemData {\n\t\tsystem = selfhosted.GetSystemState(config, logger)\n\t}\n\n\tsystem.Info.SystemID = config.SystemID\n\tsystem.Info.SystemScope = config.SystemScope\n\n\treturn\n}", "func (h *HUOBI) GetSystemStatusInfo(ctx context.Context, code currency.Pair) (SystemStatusData, error) {\n\tvar resp SystemStatusData\n\tcodeValue, err := h.FormatSymbol(code, asset.CoinMarginedFutures)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\tparams := url.Values{}\n\tparams.Set(\"contract_code\", codeValue)\n\tpath := common.EncodeURLValues(huobiSwapSystemStatus, params)\n\treturn resp, h.SendHTTPRequest(ctx, exchange.RestFutures, path, &resp)\n}", "func GetOSInfo() (*OSInfo, error) {\n\t// for log detail\n\tvar keyPrefix string = `regedit:LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion`\n\n\tk, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion`, registry.QUERY_VALUE)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getOSInfo, open Windows %s failed: %w\", keyPrefix, err)\n\t}\n\tdefer k.Close()\n\n\tbuildNumber, _, err := k.GetStringValue(\"CurrentBuildNumber\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getOSInfo, get %s\\\\CurrentBuildNumber failed: %w\", keyPrefix, err)\n\t}\n\n\tmajorVersionNumber, _, err := k.GetIntegerValue(\"CurrentMajorVersionNumber\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getOSInfo, get %s\\\\CurrentMajorVersionNumber failed: %w\", keyPrefix, err)\n\t}\n\n\tminorVersionNumber, _, err := k.GetIntegerValue(\"CurrentMinorVersionNumber\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getOSInfo, get %s\\\\CurrentMinorVersionNumber failed: %w\", keyPrefix, err)\n\t}\n\n\trevision, _, err := k.GetIntegerValue(\"UBR\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getOSInfo, get %s\\\\UBR failed: %w\", keyPrefix, err)\n\t}\n\n\tproductName, _, err := k.GetStringValue(\"ProductName\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getOSInfo, get %s\\\\ProductName failed: %w\", keyPrefix, err)\n\t}\n\n\treturn &OSInfo{\n\t\tBuildNumber: buildNumber,\n\t\tProductName: productName,\n\t\tMajorVersion: majorVersionNumber,\n\t\tMinorVersion: minorVersionNumber,\n\t\tUBR: revision,\n\t}, nil\n}", "func (c *CmdReal) GetSysProcAttr() *syscall.SysProcAttr {\n\treturn c.cmd.SysProcAttr\n}", "func sysAlloc(n uintptr, sysStat *sysMemStat) unsafe.Pointer {\n\tp, err := mmap(nil, n, _PROT_READ|_PROT_WRITE, _MAP_ANON|_MAP_PRIVATE, -1, 0)\n\tif err != 0 {\n\t\tif err == _EACCES {\n\t\t\tprint(\"runtime: mmap: access denied\\n\")\n\t\t\texit(2)\n\t\t}\n\t\tif err == _EAGAIN {\n\t\t\tprint(\"runtime: mmap: too much locked memory (check 'ulimit -l').\\n\")\n\t\t\texit(2)\n\t\t}\n\t\treturn nil\n\t}\n\tsysStat.add(int64(n))\n\treturn p\n}", "func meminfo() (meminfomap, error) {\n\tbuf, err := os.ReadFile(meminfoFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn meminfoFromBytes(buf)\n}", "func PrintMemUsage() {\n\tvar m runtime.MemStats\n\truntime.ReadMemStats(&m)\n\n\tfmt.Printf(\"Alloc = %v MiB\", m.Alloc/1024/1024)\n\tfmt.Printf(\" TotalAlloc = %v MiB\", m.TotalAlloc/1024/1024)\n\tfmt.Printf(\" Sys = %v MiB\", m.Sys/1024/1024)\n\tfmt.Printf(\" NumGC = %v\\n\", m.NumGC)\n}" ]
[ "0.760528", "0.6609513", "0.65242136", "0.6216078", "0.6216058", "0.62136495", "0.6112163", "0.59639126", "0.5962498", "0.5933598", "0.59277123", "0.5890014", "0.58580357", "0.5852476", "0.5814482", "0.5764758", "0.5745017", "0.5726905", "0.57179374", "0.5708677", "0.5706408", "0.5702947", "0.56638175", "0.5663732", "0.5637914", "0.5602699", "0.5600038", "0.5590411", "0.5589106", "0.5542071", "0.5541688", "0.5532331", "0.55314684", "0.55291873", "0.5524138", "0.5509223", "0.55056554", "0.54998106", "0.5493482", "0.54923266", "0.54920614", "0.54862976", "0.54798335", "0.5473798", "0.5462962", "0.5450949", "0.54482406", "0.54469985", "0.5439803", "0.5437238", "0.5436596", "0.54332405", "0.5421197", "0.5414685", "0.54049563", "0.540195", "0.5357396", "0.5352738", "0.5345989", "0.53376687", "0.533526", "0.5333017", "0.53310895", "0.533085", "0.5308192", "0.52981997", "0.52941513", "0.5287331", "0.5285544", "0.52841026", "0.5282668", "0.5277708", "0.5273307", "0.52693427", "0.5268486", "0.52678925", "0.52675486", "0.5265969", "0.52595437", "0.52592784", "0.52590793", "0.52577305", "0.52549917", "0.5242559", "0.5239427", "0.523847", "0.5194056", "0.51926476", "0.5181549", "0.5181464", "0.51787597", "0.5167793", "0.5153807", "0.5147983", "0.5143972", "0.51413864", "0.5130631", "0.51253474", "0.5121186", "0.5120273", "0.51183885" ]
0.0
-1
ClientDefault returns an hardened TLS configuration for mTLS connection
func ClientDefault(certPath, keyPath, caPath string) *tls.Config { // Load our TLS key pair to use for authentication cert, err := tls.LoadX509KeyPair(certPath, keyPath) if err != nil { log.Fatalln("Unable to load cert", err) } // Load our CA certificate clientCACert, err := ioutil.ReadFile(caPath) if err != nil { log.Fatal("Unable to open cert", err) } // Append client certificate to cert pool clientCertPool := x509.NewCertPool() clientCertPool.AppendCertsFromPEM(clientCACert) // Build default TLS configuration config := &tls.Config{ // Perfect Forward Secrecy + ECDSA only CipherSuites: []uint16{ tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, }, // Force server cipher suites PreferServerCipherSuites: true, // TLS 1.2 only MinVersion: tls.VersionTLS12, // Client certificate to use Certificates: []tls.Certificate{cert}, // Root CA of the client certificate RootCAs: clientCertPool, } // Parse CommonName and SubjectAlternateName config.BuildNameToCertificate() // Return configuration return config }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func serverDefault() *tls.Config {\n\treturn &tls.Config{\n\t\t// Avoid fallback to SSL protocols < TLS1.0\n\t\tMinVersion: tls.VersionTLS10,\n\t\tPreferServerCipherSuites: true,\n\t\tCipherSuites: tlsconfig.DefaultServerAcceptedCiphers,\n\t}\n}", "func newDefaultTLSConfig(cert *tls.Certificate) (*tls.Config, error) {\n\ttlsConfig := &tls.Config{\n\t\tMinVersion: tls.VersionTLS12,\n\t\t// Prioritize cipher suites sped up by AES-NI (AES-GCM)\n\t\tCipherSuites: []uint16{\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,\n\t\t},\n\t\tPreferServerCipherSuites: true,\n\t\t// Use curves which have assembly implementations\n\t\tCurvePreferences: []tls.CurveID{\n\t\t\ttls.CurveP256,\n\t\t\ttls.X25519,\n\t\t},\n\t\tCertificates: []tls.Certificate{*cert},\n\t\t// HTTP/2 must be enabled manually when using http.Serve\n\t\tNextProtos: []string{\"h2\"},\n\t}\n\ttlsConfig.BuildNameToCertificate()\n\treturn tlsConfig, nil\n}", "func defaultTLSConfig(c Config) (*tls.Config, error) {\n\tt := &tls.Config{}\n\turl, err := url.Parse(c.URL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif url.Scheme == \"https\" {\n\t\tt.InsecureSkipVerify = c.AllowInsureTLS\n\t}\n\treturn t, nil\n}", "func (ctx *CliContext) GetDefaultTLSConfig() *TLSConfig {\n\treturn &TLSConfig{ServerName: \"localhost\"}\n}", "func newClientTLSConfig(certPEM, keyPEM, caPEM []byte) (*tls.Config, error) {\n\treturn newBaseTLSConfig(certPEM, keyPEM, caPEM)\n}", "func (client *Client) tlsConfig() *tls.Config {\n\ttlsConfig := &tls.Config{\n\t\tClientSessionCache: tls.NewLRUClientSessionCache(1000),\n\t\tSuppressServerNameInClientHandshake: true,\n\t\tInsecureSkipVerify: client.InsecureSkipVerify,\n\t}\n\t// Note - we need to suppress the sending of the ServerName in the client\n\t// handshake to make host-spoofing work with Fastly. If the client Hello\n\t// includes a server name, Fastly checks to make sure that this matches the\n\t// Host header in the HTTP request and if they don't match, it returns a\n\t// 400 Bad Request error.\n\tif client.RootCA != \"\" {\n\t\tcaCert, err := keyman.LoadCertificateFromPEMBytes([]byte(client.RootCA))\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Unable to load root ca cert: %s\", err)\n\t\t}\n\t\ttlsConfig.RootCAs = caCert.PoolContainingCert()\n\t}\n\treturn tlsConfig\n}", "func DefaultGetHTTPClient() *http.Client {\n\tif InsecureTLS {\n\t\treturn &http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true}}}\n\t}\n\treturn &http.Client{}\n}", "func getDefaultTransport(tlsConfig *tls.Config) (*http.Transport, error) {\n\ttr := &http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDialContext: (&net.Dialer{\n\t\t\tTimeout: 30 * time.Second,\n\t\t\tKeepAlive: 30 * time.Second,\n\t\t\tDualStack: true,\n\t\t}).DialContext,\n\t\tMaxIdleConns: 100,\n\t\tIdleConnTimeout: 90 * time.Second,\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\tExpectContinueTimeout: 1 * time.Second,\n\t\tTLSClientConfig: tlsConfig,\n\t}\n\tif err := http2.ConfigureTransport(tr); err != nil {\n\t\treturn nil, errors.Wrap(err, \"error configuring transport\")\n\t}\n\treturn tr, nil\n}", "func TLS(v *tls.Config) Configer {\n\treturn func(c *clientv3.Config) {\n\t\tc.TLS = v\n\t}\n}", "func getDefaultClient() Client {\n\treturn Client{\n\t\tServerKey: midtrans.ServerKey,\n\t\tClientKey: midtrans.ClientKey,\n\t\tEnv: midtrans.Environment,\n\t\tHttpClient: midtrans.GetHttpClient(midtrans.Environment),\n\t\tOptions: &midtrans.ConfigOptions{\n\t\t\tPaymentOverrideNotification: midtrans.PaymentOverrideNotification,\n\t\t\tPaymentAppendNotification: midtrans.PaymentAppendNotification,\n\t\t},\n\t}\n}", "func getClientTLSConfig() (*tls.Config, error) {\n\t// XXX Add flags for server cert path.\n\tcaCert, err := ioutil.ReadFile(\"./certs/server.cert\")\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Creating TLS config failed\")\n\t}\n\tcertPool := x509.NewCertPool()\n\tcertPool.AppendCertsFromPEM(caCert)\n\treturn &tls.Config{RootCAs: certPool}, nil\n}", "func getTLSConfig(c *Config) (*tls.Config, error) {\n\tcfg := &tls.Config{\n\t\tCurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},\n\t\tPreferServerCipherSuites: true,\n\t\tMinVersion: tls.VersionTLS12,\n\t\tClientAuth: tls.NoClientCert,\n\t}\n\n\t// @step: load the server certificates\n\tif c.TLSCert != \"\" && c.TLSKey != \"\" {\n\t\tcert, err := tls.LoadX509KeyPair(c.TLSCert, c.TLSKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcfg.Certificates = []tls.Certificate{cert}\n\t}\n\n\treturn cfg, nil\n}", "func GetTLSConfigForTLSMockServer() *tls.Config {\n\treturn native.GetTLSConfig()\n}", "func newServerTLSConfig(certPEM, keyPEM, caPEM []byte) (*tls.Config, error) {\n\tcfg, err := newBaseTLSConfig(certPEM, keyPEM, caPEM)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcfg.ClientAuth = tls.VerifyClientCertIfGiven\n\tcfg.ClientCAs = cfg.RootCAs\n\t// Use the default cipher suite from golang (RC4 is going away in 1.5).\n\t// Prefer the server-specified suite.\n\tcfg.PreferServerCipherSuites = true\n\t// Should we disable session resumption? This may break forward secrecy.\n\t// cfg.SessionTicketsDisabled = true\n\treturn cfg, nil\n}", "func defaultClient(skipverify bool) *http.Client {\n\tclient := &http.Client{}\n\tclient.Transport = defaultTransport(skipverify)\n\treturn client\n}", "func initClient(protocol string) {\n\tclientConf = GetDefaultClientConfig()\n\tif protocol == \"\" {\n\t\treturn\n\t}\n\n\t// load client config from rootConfig.Protocols\n\t// default use dubbo\n\tif config.GetApplicationConfig() == nil {\n\t\treturn\n\t}\n\tif config.GetRootConfig().Protocols == nil {\n\t\treturn\n\t}\n\n\tprotocolConf := config.GetRootConfig().Protocols[protocol]\n\tif protocolConf == nil {\n\t\tlogger.Info(\"use default getty client config\")\n\t\treturn\n\t} else {\n\t\t//client tls config\n\t\ttlsConfig := config.GetRootConfig().TLSConfig\n\t\tif tlsConfig != nil {\n\t\t\tclientConf.SSLEnabled = true\n\t\t\tclientConf.TLSBuilder = &getty.ClientTlsConfigBuilder{\n\t\t\t\tClientKeyCertChainPath: tlsConfig.TLSCertFile,\n\t\t\t\tClientPrivateKeyPath: tlsConfig.TLSKeyFile,\n\t\t\t\tClientTrustCertCollectionPath: tlsConfig.CACertFile,\n\t\t\t}\n\t\t}\n\t\t//getty params\n\t\tgettyClientConfig := protocolConf.Params\n\t\tif gettyClientConfig == nil {\n\t\t\tlogger.Debugf(\"gettyClientConfig is nil\")\n\t\t\treturn\n\t\t}\n\t\tgettyClientConfigBytes, err := yaml.Marshal(gettyClientConfig)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\terr = yaml.Unmarshal(gettyClientConfigBytes, clientConf)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tif err := clientConf.CheckValidity(); err != nil {\n\t\tlogger.Warnf(\"[CheckValidity] error: %v\", err)\n\t\treturn\n\t}\n\tsetClientGrPool()\n\n\trand.Seed(time.Now().UnixNano())\n}", "func DefaultHTTPSClient(certPool *x509.CertPool) *http.Client {\n\ttransport := http.DefaultTransport.(*http.Transport)\n\ttransport.TLSClientConfig = &tls.Config{\n\t\tRootCAs: certPool,\n\t\tMinVersion: tls.VersionTLS13,\n\t}\n\n\treturn &http.Client{Transport: transport}\n}", "func defaultRoundTripperClient(t *tls.Config, timeout int64) *http.Client {\n\t// Ensure we use a http.Transport with proper settings: the zero values are not\n\t// a good choice, as they cause leaking connections:\n\t// https://github.com/golang/go/issues/19620\n\n\t// copy, we don't want to alter the default client's Transport\n\ttr := http.DefaultTransport.(*http.Transport).Clone()\n\ttr.ResponseHeaderTimeout = time.Duration(timeout) * time.Second\n\ttr.TLSClientConfig = t\n\n\tc := *http.DefaultClient\n\tc.Transport = tr\n\treturn &c\n}", "func DefaultClientTransport(rt http.RoundTripper) http.RoundTripper {\n\ttransport := rt.(*http.Transport)\n\t// TODO: this should be configured by the caller, not in this method.\n\tdialer := &net.Dialer{\n\t\tTimeout: 30 * time.Second,\n\t\tKeepAlive: 30 * time.Second,\n\t}\n\ttransport.Dial = dialer.Dial\n\t// Hold open more internal idle connections\n\t// TODO: this should be configured by the caller, not in this method.\n\ttransport.MaxIdleConnsPerHost = 100\n\treturn transport\n}", "func newTLSConfig(clientCert, clientKey, caCert string) (*tls.Config, error) {\n\tvalid := false\n\n\tconfig := &tls.Config{}\n\n\tif clientCert != \"\" && clientKey != \"\" {\n\t\tcert, err := tls.X509KeyPair([]byte(clientCert), []byte(clientKey))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tconfig.Certificates = []tls.Certificate{cert}\n\t\tconfig.BuildNameToCertificate()\n\t\tvalid = true\n\t}\n\n\tif caCert != \"\" {\n\t\tcaCertPool := x509.NewCertPool()\n\t\tcaCertPool.AppendCertsFromPEM([]byte(caCert))\n\t\tconfig.RootCAs = caCertPool\n\t\t// The CN of Heroku Kafka certs do not match the hostname of the\n\t\t// broker, but Go's default TLS behavior requires that they do.\n\t\tconfig.VerifyPeerCertificate = verifyCertSkipHostname(caCertPool)\n\t\tconfig.InsecureSkipVerify = true\n\t\tvalid = true\n\t}\n\n\tif !valid {\n\t\tconfig = nil\n\t}\n\n\treturn config, nil\n}", "func newTLSConfig(clientCert, clientKey, caCert string) (*tls.Config, error) {\n\tvalid := false\n\n\tconfig := &tls.Config{}\n\n\tif clientCert != \"\" && clientKey != \"\" {\n\t\tcert, err := tls.X509KeyPair([]byte(clientCert), []byte(clientKey))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tconfig.Certificates = []tls.Certificate{cert}\n\t\tconfig.BuildNameToCertificate()\n\t\tvalid = true\n\t}\n\n\tif caCert != \"\" {\n\t\tcaCertPool := x509.NewCertPool()\n\t\tcaCertPool.AppendCertsFromPEM([]byte(caCert))\n\t\tconfig.RootCAs = caCertPool\n\t\t// The CN of Heroku Kafka certs do not match the hostname of the\n\t\t// broker, but Go's default TLS behavior requires that they do.\n\t\tconfig.VerifyPeerCertificate = verifyCertSkipHostname(caCertPool)\n\t\tconfig.InsecureSkipVerify = true\n\t\tvalid = true\n\t}\n\n\tif !valid {\n\t\tconfig = nil\n\t}\n\n\treturn config, nil\n}", "func ClientTLS(certPath string, opts ...tlsOption) (c *tls.Config, err error) {\n\tvar pemData []byte\n\tif certPath != \"\" {\n\t\tpemData, err = ioutil.ReadFile(certPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tlog.Warning(\"No certificate path specified. Using development ssl certificates\")\n\t\tpemData = []byte(DevServerPem)\n\t}\n\n\tpool := x509.NewCertPool()\n\tpool.AppendCertsFromPEM(pemData)\n\tconfig := &tls.Config{RootCAs: pool}\n\n\topts = append(defaultClientTLSOptions, opts...)\n\tfor _, opt := range opts {\n\t\topt(config)\n\t}\n\treturn config, nil\n}", "func getTLSClient(config map[string]string) (http.Client) {\n // Load client cert\n cert, err := tls.LoadX509KeyPair(config[\"CERT_FILE\"], config[\"KEY_FILE\"])\n if err != nil {\n log.Fatal(err)\n }\n\n // Load CA cert\n caCert, err := ioutil.ReadFile(config[\"CA_FILE\"])\n if err != nil {\n log.Fatal(err)\n }\n caCertPool := x509.NewCertPool()\n caCertPool.AppendCertsFromPEM(caCert)\n\n // Setup HTTPS client\n tlsConfig := &tls.Config{\n Certificates: []tls.Certificate{cert},\n RootCAs: caCertPool,\n }\n tlsConfig.BuildNameToCertificate()\n transport := &http.Transport{TLSClientConfig: tlsConfig}\n client := &http.Client{Transport: transport}\n return *client\n}", "func newBaseTLSConfig(certPEM, keyPEM, caPEM []byte) (*tls.Config, error) {\n\tcert, err := tls.X509KeyPair(certPEM, keyPEM)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcertPool := x509.NewCertPool()\n\n\tif !certPool.AppendCertsFromPEM(caPEM) {\n\t\treturn nil, errors.Errorf(\"failed to parse PEM data to pool\")\n\t}\n\n\treturn &tls.Config{\n\t\tCertificates: []tls.Certificate{cert},\n\t\tRootCAs: certPool,\n\n\t\t// This is Go's default list of cipher suites (as of go 1.8.3),\n\t\t// with the following differences:\n\t\t// - 3DES-based cipher suites have been removed. This cipher is\n\t\t// vulnerable to the Sweet32 attack and is sometimes reported by\n\t\t// security scanners. (This is arguably a false positive since\n\t\t// it will never be selected: Any TLS1.2 implementation MUST\n\t\t// include at least one cipher higher in the priority list, but\n\t\t// there's also no reason to keep it around)\n\t\t// - AES is always prioritized over ChaCha20. Go makes this decision\n\t\t// by default based on the presence or absence of hardware AES\n\t\t// acceleration.\n\t\t// TODO(bdarnell): do the same detection here. See\n\t\t// https://github.com/golang/go/issues/21167\n\t\t//\n\t\t// Note that some TLS cipher suite guidance (such as Mozilla's[1])\n\t\t// recommend replacing the CBC_SHA suites below with CBC_SHA384 or\n\t\t// CBC_SHA256 variants. We do not do this because Go does not\n\t\t// currerntly implement the CBC_SHA384 suites, and its CBC_SHA256\n\t\t// implementation is vulnerable to the Lucky13 attack and is disabled\n\t\t// by default.[2]\n\t\t//\n\t\t// [1]: https://wiki.mozilla.org/Security/Server_Side_TLS#Modern_compatibility\n\t\t// [2]: https://github.com/golang/go/commit/48d8edb5b21db190f717e035b4d9ab61a077f9d7\n\t\tCipherSuites: []uint16{\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,\n\t\t\ttls.TLS_RSA_WITH_AES_128_GCM_SHA256,\n\t\t\ttls.TLS_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_RSA_WITH_AES_128_CBC_SHA,\n\t\t\ttls.TLS_RSA_WITH_AES_256_CBC_SHA,\n\t\t},\n\n\t\tMinVersion: tls.VersionTLS12,\n\t}, nil\n}", "func DefaultClientTransport(rt http.RoundTripper) http.RoundTripper {\n\ttransport, ok := rt.(*http.Transport)\n\tif !ok {\n\t\treturn rt\n\t}\n\n\t// TODO: this should be configured by the caller, not in this method.\n\tdialer := &net.Dialer{\n\t\tTimeout: 30 * time.Second,\n\t\tKeepAlive: 30 * time.Second,\n\t}\n\ttransport.Dial = dialer.Dial\n\t// Hold open more internal idle connections\n\t// TODO: this should be configured by the caller, not in this method.\n\ttransport.MaxIdleConnsPerHost = 100\n\treturn transport\n}", "func (opts *Options) ClientTLSConfig(id storj.NodeID) *tls.Config {\n\treturn opts.tlsConfig(false, verifyIdentity(id))\n}", "func (c *ClientConfig) TLSConfig() (*tls.Config, error) {\n\t// Support deprecated variable names\n\tif c.TLSCA == \"\" && c.SSLCA != \"\" {\n\t\tc.TLSCA = c.SSLCA\n\t}\n\tif c.TLSCert == \"\" && c.SSLCert != \"\" {\n\t\tc.TLSCert = c.SSLCert\n\t}\n\tif c.TLSKey == \"\" && c.SSLKey != \"\" {\n\t\tc.TLSKey = c.SSLKey\n\t}\n\n\tif c.TLSCA == \"\" && c.TLSKey == \"\" && c.TLSCert == \"\" && !c.InsecureSkipVerify {\n\t\treturn nil, nil\n\t}\n\n\ttlsConfig := &tls.Config{\n\t\tInsecureSkipVerify: c.InsecureSkipVerify,\n\t\tRenegotiation: tls.RenegotiateNever,\n\t}\n\n\tif c.TLSCA != \"\" {\n\t\tpool, err := makeCertPool([]string{c.TLSCA})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttlsConfig.RootCAs = pool\n\t}\n\n\tif c.TLSCert != \"\" && c.TLSKey != \"\" {\n\t\terr := loadCertificate(tlsConfig, c.TLSCert, c.TLSKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn tlsConfig, nil\n}", "func (m *Manager) TLSConfig() *tls.Config {\n\ttlsConf := tlsconfig.NewServerTLSConfig(tlsconfig.TLSModeServerStrict)\n\ttlsConf.NextProtos = []string{\n\t\t\"h2\", \"http/1.1\", // enable HTTP/2\n\t\tacme.ALPNProto, // enable tls-alpn ACME challenges\n\t}\n\ttlsConf.GetCertificate = m.GetCertificateFunc\n\treturn tlsConf\n}", "func (client *BaseClient) TLSClientConfig() *tls.Config {\n\treturn nil\n}", "func TLS(cCert, cKey, caCert string) (*tls.Config, error) {\n\n\ttlsConfig := tls.Config{}\n\n\t// Load client cert\n\tcert, e1 := tls.LoadX509KeyPair(cCert, cKey)\n\tif e1 != nil {\n\t\treturn &tlsConfig, e1\n\t}\n\ttlsConfig.Certificates = []tls.Certificate{cert}\n\n\t// Load CA cert\n\tcaCertR, e2 := ioutil.ReadFile(caCert)\n\tif e2 != nil {\n\t\treturn &tlsConfig, e2\n\t}\n\tcaCertPool := x509.NewCertPool()\n\tcaCertPool.AppendCertsFromPEM(caCertR)\n\ttlsConfig.RootCAs = caCertPool\n\n\ttlsConfig.BuildNameToCertificate()\n\treturn &tlsConfig, e2\n}", "func (ca *CA) getTLSConfig(auth *authority.Authority) (*tls.Config, *tls.Config, error) {\n\t// Create initial TLS certificate\n\ttlsCrt, err := auth.GetTLSCertificate()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Start tls renewer with the new certificate.\n\t// If a renewer was started, attempt to stop it before.\n\tif ca.renewer != nil {\n\t\tca.renewer.Stop()\n\t}\n\n\tca.renewer, err = NewTLSRenewer(tlsCrt, auth.GetTLSCertificate)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tca.renewer.Run()\n\n\tvar serverTLSConfig *tls.Config\n\tif ca.config.TLS != nil {\n\t\tserverTLSConfig = ca.config.TLS.TLSConfig()\n\t} else {\n\t\tserverTLSConfig = &tls.Config{\n\t\t\tMinVersion: tls.VersionTLS12,\n\t\t}\n\t}\n\n\t// GetCertificate will only be called if the client supplies SNI\n\t// information or if tlsConfig.Certificates is empty.\n\t// When client requests are made using an IP address (as opposed to a domain\n\t// name) the server does not receive any SNI and may fallback to using the\n\t// first entry in the Certificates attribute; by setting the attribute to\n\t// empty we are implicitly forcing GetCertificate to be the only mechanism\n\t// by which the server can find it's own leaf Certificate.\n\tserverTLSConfig.Certificates = []tls.Certificate{}\n\n\tclientTLSConfig := serverTLSConfig.Clone()\n\n\tserverTLSConfig.GetCertificate = ca.renewer.GetCertificateForCA\n\tclientTLSConfig.GetClientCertificate = ca.renewer.GetClientCertificate\n\n\t// initialize a certificate pool with root CA certificates to trust when doing mTLS.\n\tcertPool := x509.NewCertPool()\n\t// initialize a certificate pool with root CA certificates to trust when connecting\n\t// to webhook servers\n\trootCAsPool, err := x509.SystemCertPool()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tfor _, crt := range auth.GetRootCertificates() {\n\t\tcertPool.AddCert(crt)\n\t\trootCAsPool.AddCert(crt)\n\t}\n\n\t// adding the intermediate CA certificates to the pool will allow clients that\n\t// do mTLS but don't send an intermediate to successfully connect. The intermediates\n\t// added here are used when building a certificate chain.\n\tintermediates := tlsCrt.Certificate[1:]\n\tfor _, certBytes := range intermediates {\n\t\tcert, err := x509.ParseCertificate(certBytes)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tcertPool.AddCert(cert)\n\t\trootCAsPool.AddCert(cert)\n\t}\n\n\t// Add support for mutual tls to renew certificates\n\tserverTLSConfig.ClientAuth = tls.VerifyClientCertIfGiven\n\tserverTLSConfig.ClientCAs = certPool\n\n\tclientTLSConfig.RootCAs = rootCAsPool\n\n\treturn serverTLSConfig, clientTLSConfig, nil\n}", "func MQTTNewTLSConfig(crtPath, keyPath string, skipVerify bool) (*tls.Config, error) {\n\t// Import trusted certificates from CAfile.pem.\n\t// Alternatively, manually add CA certificates to\n\t// default openssl CA bundle.\n\tcertpool := x509.NewCertPool()\n\tpemCerts, err := ioutil.ReadFile(\"samplecerts/CAfile.pem\")\n\tif err == nil {\n\t\tcertpool.AppendCertsFromPEM(pemCerts)\n\t}\n\n\t// Import client certificate/key pair\n\tcert, err := tls.LoadX509KeyPair(crtPath, keyPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create tls.Config with desired tls properties\n\treturn &tls.Config{\n\t\t// RootCAs = certs used to verify server cert.\n\t\tRootCAs: certpool,\n\t\t// ClientAuth = whether to request cert from server.\n\t\t// Since the server is set up for SSL, this happens\n\t\t// anyways.\n\t\tClientAuth: tls.NoClientCert,\n\t\t// ClientCAs = certs used to validate client cert.\n\t\tClientCAs: nil,\n\t\t// InsecureSkipVerify = verify that cert contents\n\t\t// match server. IP matches what is in cert etc.\n\t\tInsecureSkipVerify: skipVerify,\n\t\t// Certificates = list of certs client sends to server.\n\t\tCertificates: []tls.Certificate{cert},\n\t}, nil\n}", "func ConfigureTLS(httpClient *http.Client, tlsConfig *TLSConfig) error {\n\tif tlsConfig == nil {\n\t\treturn nil\n\t}\n\tif httpClient == nil {\n\t\treturn fmt.Errorf(\"config HTTP Client must be set\")\n\t}\n\n\tvar clientCert tls.Certificate\n\tfoundClientCert := false\n\tif tlsConfig.ClientCert != \"\" || tlsConfig.ClientKey != \"\" {\n\t\tif tlsConfig.ClientCert != \"\" && tlsConfig.ClientKey != \"\" {\n\t\t\tvar err error\n\t\t\tclientCert, err = tls.LoadX509KeyPair(tlsConfig.ClientCert, tlsConfig.ClientKey)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfoundClientCert = true\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"Both client cert and client key must be provided\")\n\t\t}\n\t} else if len(tlsConfig.ClientCertPEM) != 0 || len(tlsConfig.ClientKeyPEM) != 0 {\n\t\tif len(tlsConfig.ClientCertPEM) != 0 && len(tlsConfig.ClientKeyPEM) != 0 {\n\t\t\tvar err error\n\t\t\tclientCert, err = tls.X509KeyPair(tlsConfig.ClientCertPEM, tlsConfig.ClientKeyPEM)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfoundClientCert = true\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"Both client cert and client key must be provided\")\n\t\t}\n\t}\n\n\tclientTLSConfig := httpClient.Transport.(*http.Transport).TLSClientConfig\n\trootConfig := &rootcerts.Config{\n\t\tCAFile: tlsConfig.CACert,\n\t\tCAPath: tlsConfig.CAPath,\n\t\tCACertificate: tlsConfig.CACertPEM,\n\t}\n\tif err := rootcerts.ConfigureTLS(clientTLSConfig, rootConfig); err != nil {\n\t\treturn err\n\t}\n\n\tclientTLSConfig.InsecureSkipVerify = tlsConfig.Insecure\n\n\tif foundClientCert {\n\t\tclientTLSConfig.Certificates = []tls.Certificate{clientCert}\n\t}\n\tif tlsConfig.TLSServerName != \"\" {\n\t\tclientTLSConfig.ServerName = tlsConfig.TLSServerName\n\t}\n\n\treturn nil\n}", "func (e *endpoints) getTLSConfig(ctx context.Context) func(*tls.ClientHelloInfo) (*tls.Config, error) {\n\treturn func(hello *tls.ClientHelloInfo) (*tls.Config, error) {\n\t\tcerts, roots, err := e.getCerts(ctx)\n\t\tif err != nil {\n\t\t\te.c.Log.Errorf(\"Could not generate TLS config for gRPC client %v: %v\", hello.Conn.RemoteAddr(), err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tc := &tls.Config{\n\t\t\t// When bootstrapping, the agent does not yet have\n\t\t\t// an SVID. In order to include the bootstrap endpoint\n\t\t\t// in the same server as the rest of the Node API,\n\t\t\t// request but don't require a client certificate\n\t\t\tClientAuth: tls.VerifyClientCertIfGiven,\n\n\t\t\tCertificates: certs,\n\t\t\tClientCAs: roots,\n\t\t}\n\t\treturn c, nil\n\t}\n}", "func getTLSClientOptions(tls bool) grpc.DialOption {\n\tvar opts grpc.DialOption\n\n\tif tls {\n\t\tcertFile := \"../../ssl/minica.pem\" // Certificate Authority Trust certificate\n\n\t\tcreds, sslErr := credentials.NewClientTLSFromFile(certFile, \"\")\n\t\tif sslErr == nil {\n\t\t\topts = grpc.WithTransportCredentials(creds)\n\t\t} else {\n\t\t\tlog.Fatalf(\"Filed loading certificates: %v\", sslErr)\n\t\t}\n\t} else {\n\t\topts = grpc.WithInsecure()\n\t}\n\n\treturn opts\n}", "func (c *IdentityConfig) loadClientTLSConfig(configEntity *identityConfigEntity) error {\n\t//Clients Config\n\t//resolve paths and org name\n\tconfigEntity.Client.Organization = strings.ToLower(configEntity.Client.Organization)\n\tconfigEntity.Client.TLSCerts.Client.Key.Path = pathvar.Subst(configEntity.Client.TLSCerts.Client.Key.Path)\n\tconfigEntity.Client.TLSCerts.Client.Cert.Path = pathvar.Subst(configEntity.Client.TLSCerts.Client.Cert.Path)\n\n\t//pre load client key and cert bytes\n\terr := configEntity.Client.TLSCerts.Client.Key.LoadBytes()\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to load client key\")\n\t}\n\n\terr = configEntity.Client.TLSCerts.Client.Cert.LoadBytes()\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to load client cert\")\n\t}\n\n\tc.client = &msp.ClientConfig{\n\t\tOrganization: configEntity.Client.Organization,\n\t\tLogging: configEntity.Client.Logging,\n\t\tCryptoConfig: configEntity.Client.CryptoConfig,\n\t\tCredentialStore: configEntity.Client.CredentialStore,\n\t\tTLSKey: configEntity.Client.TLSCerts.Client.Key.Bytes(),\n\t\tTLSCert: configEntity.Client.TLSCerts.Client.Cert.Bytes(),\n\t}\n\n\treturn nil\n}", "func DefaultHTTPClient() *http.Client {\n\tclient := cleanhttp.DefaultPooledClient()\n\tsetMinimumTLSVersion(client)\n\treturn client\n}", "func (t *Transport) setupDefaults() {\n\tif t.TLSClientConfig == nil {\n\t\tt.TLSClientConfig = &tls.Config{}\n\t}\n}", "func (c *Config) configureTLS(t *TLSConfig) error {\n\tif c.HttpClient == nil {\n\t\tc.HttpClient = DefaultConfig().HttpClient\n\t}\n\tclientTLSConfig := c.HttpClient.Transport.(*http.Transport).TLSClientConfig\n\n\tvar clientCert tls.Certificate\n\tfoundClientCert := false\n\n\tswitch {\n\tcase t.ClientCert != \"\" && t.ClientKey != \"\":\n\t\tvar err error\n\t\tclientCert, err = tls.LoadX509KeyPair(t.ClientCert, t.ClientKey)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfoundClientCert = true\n\t\tc.curlClientCert = t.ClientCert\n\t\tc.curlClientKey = t.ClientKey\n\tcase t.ClientCert != \"\" || t.ClientKey != \"\":\n\t\treturn fmt.Errorf(\"both client cert and client key must be provided\")\n\t}\n\n\tif t.CACert != \"\" || len(t.CACertBytes) != 0 || t.CAPath != \"\" {\n\t\tc.curlCACert = t.CACert\n\t\tc.curlCAPath = t.CAPath\n\t\trootConfig := &rootcerts.Config{\n\t\t\tCAFile: t.CACert,\n\t\t\tCACertificate: t.CACertBytes,\n\t\t\tCAPath: t.CAPath,\n\t\t}\n\t\tif err := rootcerts.ConfigureTLS(clientTLSConfig, rootConfig); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif t.Insecure {\n\t\tclientTLSConfig.InsecureSkipVerify = true\n\t}\n\n\tif foundClientCert {\n\t\t// We use this function to ignore the server's preferential list of\n\t\t// CAs, otherwise any CA used for the cert auth backend must be in the\n\t\t// server's CA pool\n\t\tclientTLSConfig.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) {\n\t\t\treturn &clientCert, nil\n\t\t}\n\t}\n\n\tif t.TLSServerName != \"\" {\n\t\tclientTLSConfig.ServerName = t.TLSServerName\n\t}\n\tc.clientTLSConfig = clientTLSConfig\n\n\treturn nil\n}", "func (ep *Endpoint) tlsConfig() (*tls.Config, error) {\n\tif ep.TLSData == nil && !ep.SkipTLSVerify {\n\t\t// there is no specific tls config\n\t\treturn nil, nil\n\t}\n\tvar tlsOpts []func(*tls.Config)\n\tif ep.TLSData != nil && ep.TLSData.CA != nil {\n\t\tcertPool := x509.NewCertPool()\n\t\tif !certPool.AppendCertsFromPEM(ep.TLSData.CA) {\n\t\t\treturn nil, errors.New(\"failed to retrieve context tls info: ca.pem seems invalid\")\n\t\t}\n\t\ttlsOpts = append(tlsOpts, func(cfg *tls.Config) {\n\t\t\tcfg.RootCAs = certPool\n\t\t})\n\t}\n\tif ep.TLSData != nil && ep.TLSData.Key != nil && ep.TLSData.Cert != nil {\n\t\tkeyBytes := ep.TLSData.Key\n\t\tpemBlock, _ := pem.Decode(keyBytes)\n\t\tif pemBlock == nil {\n\t\t\treturn nil, errors.New(\"no valid private key found\")\n\t\t}\n\t\tif x509.IsEncryptedPEMBlock(pemBlock) { //nolint:staticcheck // SA1019: x509.IsEncryptedPEMBlock is deprecated, and insecure by design\n\t\t\treturn nil, errors.New(\"private key is encrypted - support for encrypted private keys has been removed, see https://docs.docker.com/go/deprecated/\")\n\t\t}\n\n\t\tx509cert, err := tls.X509KeyPair(ep.TLSData.Cert, keyBytes)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to retrieve context tls info\")\n\t\t}\n\t\ttlsOpts = append(tlsOpts, func(cfg *tls.Config) {\n\t\t\tcfg.Certificates = []tls.Certificate{x509cert}\n\t\t})\n\t}\n\tif ep.SkipTLSVerify {\n\t\ttlsOpts = append(tlsOpts, func(cfg *tls.Config) {\n\t\t\tcfg.InsecureSkipVerify = true\n\t\t})\n\t}\n\treturn tlsconfig.ClientDefault(tlsOpts...), nil\n}", "func MQTTClientOptions() (*MQTT.ClientOptions, error) {\n\t// read config options from environment variables\n\tserver := os.Getenv(\"MQTT_SERVER\")\n\tclientID := os.Getenv(\"MQTT_CLIENT_ID\")\n\tusername := os.Getenv(\"MQTT_USERNAME\")\n\tpassword := os.Getenv(\"MQTT_PASSWORD\")\n\ttlsCert := os.Getenv(\"MQTT_CERT\")\n\ttlsKey := os.Getenv(\"MQTT_CERT_KEY\")\n\ttlsCA := os.Getenv(\"MQTT_CA_ROOT\")\n\ttlsSkipVerify := os.Getenv(\"MQTT_TLS_SKIP_VERIFY\")\n\n\tif server == \"\" {\n\t\treturn nil, fmt.Errorf(\"MQTT server is empty\")\n\t}\n\n\tif clientID == \"\" {\n\t\treturn nil, fmt.Errorf(\"MQTT clientID is empty\")\n\t}\n\n\topts := MQTT.NewClientOptions()\n\topts.AddBroker(server)\n\topts.SetClientID(clientID)\n\topts.SetKeepAlive(20 * time.Second)\n\topts.CleanSession = true\n\topts.SetPingTimeout(1 * time.Second)\n\topts.SetDefaultPublishHandler(msgHandler)\n\n\tif username != \"\" && password != \"\" {\n\t\topts.SetUsername(username)\n\t\topts.SetPassword(password)\n\t}\n\n\tvar skipVerify bool\n\tif tlsSkipVerify != \"\" {\n\t\tskipVerify = true\n\t}\n\n\tif tlsCert != \"\" && tlsKey != \"\" && tlsCA != \"\" {\n\t\ttlsConfig, err := MQTTNewTLSConfig(tlsCert, tlsKey, skipVerify)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Invalid TLS configuration: %s\", err)\n\t\t}\n\t\topts.SetTLSConfig(tlsConfig)\n\t}\n\n\treturn opts, nil\n}", "func DefaultConfig() *Config {\n\tcfg := &Config{\n\t\tuserHost: \"sms.yunpian.com\",\n\t\tsignHost: \"sms.yunpian.com\",\n\t\ttplHost: \"sms.yunpian.com\",\n\t\tsmsHost: \"sms.yunpian.com\",\n\t\tvoiceHost: \"voice.yunpian.com\",\n\t\tflowHost: \"flow.yunpian.com\",\n\t}\n\treturn cfg.WithUseSSL(true).WithHTTPClient(defaultHTTPClient())\n}", "func defaultTransport(skipverify bool) http.RoundTripper {\n\treturn &http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tInsecureSkipVerify: skipverify,\n\t\t},\n\t}\n}", "func TLSConfig() *tls.Config {\n\tif len(hostname) == 0 || len(cacertFile) == 0 ||\n\t\tlen(certFile) == 0 || len(keyFile) == 0 {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\ttls, err := LoadTLSConfig(keyFile, certFile, cacertFile)\n\tif err != nil {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\ttls.ServerName = hostname\n\treturn tls\n}", "func createTlsConfig() {\n\n}", "func NewClientMutualTLSConfig(\n\tcertFile string,\n\tkeyFile string,\n\tcaCertFile string,\n\tserverName string,\n) (*tls.Config, error) {\n\treturn newMutualTLSConfig(\n\t\tcertFile,\n\t\tkeyFile,\n\t\tcaCertFile,\n\t\tserverName,\n\t\ttrue,\n\t)\n}", "func generateTLSConfig(caCertFile string, clientCertFile string, clientKeyFile string, customVerifyFunc customVerifyFunc) (*tls.Config, error) {\n\tclientKeyPair, err := tls.LoadX509KeyPair(clientCertFile, clientKeyFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcaCertFileBytes, err := ioutil.ReadFile(caCertFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\troots := x509.NewCertPool()\n\troots.AppendCertsFromPEM(caCertFileBytes)\n\n\ttlsConfig := &tls.Config{\n\t\tCertificates: []tls.Certificate{clientKeyPair},\n\t\tRootCAs: roots,\n\t\tMinVersion: tls.VersionTLS12,\n\t\tInsecureSkipVerify: true,\n\t\t// Legacy TLS Verification using the new VerifyConnection callback\n\t\t// important for go version 1.15+ as some certificates in environments\n\t\t// that cause the new standard lib verification to fail.\n\t\t// This isn't really needed if your SSL certificates don't have the Common Name issue.\n\t\t// For more information: https://github.com/golang/go/issues/39568\n\t\tVerifyConnection: func(cs tls.ConnectionState) error {\n\t\t\tcommonName := cs.PeerCertificates[0].Subject.CommonName\n\t\t\tif commonName != cs.ServerName {\n\t\t\t\treturn fmt.Errorf(\"invalid certificate name %q, expected %q\", commonName, cs.ServerName)\n\t\t\t}\n\t\t\topts := x509.VerifyOptions{\n\t\t\t\tRoots: roots,\n\t\t\t\tIntermediates: x509.NewCertPool(),\n\t\t\t}\n\t\t\tfor _, cert := range cs.PeerCertificates[1:] {\n\t\t\t\topts.Intermediates.AddCert(cert)\n\t\t\t}\n\t\t\t_, err := cs.PeerCertificates[0].Verify(opts)\n\t\t\treturn err\n\t\t},\n\t}\n\tif customVerifyFunc != nil {\n\t\ttlsConfig.VerifyPeerCertificate = customVerifyFunc\n\t\ttlsConfig.VerifyConnection = nil\n\t}\n\ttlsConfig.BuildNameToCertificate()\n\n\treturn tlsConfig, nil\n}", "func NewClientTLSConfig(certs []tls.Certificate, rootCAPool *x509.CertPool, serverName string) (*tls.Config, error) {\n\tif rootCAPool == nil {\n\t\treturn nil, errors.New(\"valid root CA pool required\")\n\t}\n\n\treturn &tls.Config{\n\t\tServerName: serverName,\n\t\tCertificates: certs,\n\t\tRootCAs: rootCAPool,\n\t\tMinVersion: tls.VersionTLS12,\n\t}, nil\n}", "func TLSConfig() *tls.Config {\n\treturn &tls.Config{\n\t\tMinVersion: tls.VersionTLS12,\n\t\tCipherSuites: teleutils.DefaultCipherSuites(),\n\t\tPreferServerCipherSuites: true,\n\t}\n}", "func tlsClientConfig(caPath string, certPath string, keyPath, serverName string) (*tls.Config, error) {\n\tif caPath == \"\" {\n\t\treturn nil, nil\n\t}\n\n\tcaCert, err := ioutil.ReadFile(caPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcaCertPool := x509.NewCertPool()\n\tcaCertPool.AppendCertsFromPEM(caCert)\n\n\ttlsConfig := &tls.Config{\n\t\tInsecureSkipVerify: true,\n\t\tClientCAs: caCertPool,\n\t\tClientAuth: tls.RequireAndVerifyClientCert,\n\t}\n\n\tcert, err := tls.LoadX509KeyPair(certPath, keyPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttlsConfig.Certificates = []tls.Certificate{cert}\n\ttlsConfig.NextProtos = []string{\"h2\"}\n\ttlsConfig.ServerName = serverName\n\n\treturn tlsConfig, nil\n}", "func tlsConfig(caCertPath, clientCertPath, clientKeyPath string) (tconfKey string, err error) {\n\tpem, err := ioutil.ReadFile(caCertPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\trootCertPool := x509.NewCertPool()\n\tif ok := rootCertPool.AppendCertsFromPEM(pem); !ok {\n\t\treturn \"\", errCertPEM\n\t}\n\tcert, err := tls.LoadX509KeyPair(clientCertPath, clientKeyPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdbTLSConfig := &tls.Config{\n\t\tRootCAs: rootCertPool,\n\t\tCertificates: []tls.Certificate{cert},\n\t}\n\ttconfKey = \"custom\"\n\tif err := mysql.RegisterTLSConfig(tconfKey, dbTLSConfig); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn tconfKey, nil\n}", "func copyTLSConfig(cfg *tls.Config) *tls.Config {\n\treturn &tls.Config{\n\t\tCertificates: cfg.Certificates,\n\t\tCipherSuites: cfg.CipherSuites,\n\t\tClientAuth: cfg.ClientAuth,\n\t\tClientCAs: cfg.ClientCAs,\n\t\tClientSessionCache: cfg.ClientSessionCache,\n\t\tCurvePreferences: cfg.CurvePreferences,\n\t\tInsecureSkipVerify: cfg.InsecureSkipVerify,\n\t\tMaxVersion: cfg.MaxVersion,\n\t\tMinVersion: cfg.MinVersion,\n\t\tNextProtos: cfg.NextProtos,\n\t\tPreferServerCipherSuites: cfg.PreferServerCipherSuites,\n\t\tRand: cfg.Rand,\n\t\tRootCAs: cfg.RootCAs,\n\t\tServerName: cfg.ServerName,\n\t\tSessionTicketsDisabled: cfg.SessionTicketsDisabled,\n\t}\n}", "func (cfg *ConfigHttpsBasic) SetDefaultConf() {\n\tcfg.ServerCertConf = \"tls_conf/server_cert_conf.data\"\n\tcfg.TlsRuleConf = \"tls_conf/tls_rule_conf.data\"\n\tcfg.EnableSslv2ClientHello = true\n\tcfg.ClientCABaseDir = \"tls_conf/client_ca\"\n\tcfg.ClientCRLBaseDir = \"tls_conf/client_crl\"\n}", "func NewTlsConfig(t *Tls, extra ...PeerVerifier) (*tls.Config, error) {\n\tif t == nil {\n\t\treturn nil, nil\n\t}\n\n\tif len(t.CertificateFile) == 0 || len(t.KeyFile) == 0 {\n\t\treturn nil, ErrTlsCertificateRequired\n\t}\n\n\tvar nextProtos []string\n\tif len(t.NextProtos) > 0 {\n\t\tnextProtos = append(nextProtos, t.NextProtos...)\n\t} else {\n\t\t// assume http/1.1 by default\n\t\tnextProtos = append(nextProtos, \"http/1.1\")\n\t}\n\n\ttc := &tls.Config{ // nolint: gosec\n\t\tMinVersion: t.MinVersion,\n\t\tMaxVersion: t.MaxVersion,\n\t\tServerName: t.ServerName,\n\t\tNextProtos: nextProtos,\n\n\t\t// disable vulnerable ciphers\n\t\tCipherSuites: []uint16{\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n\t\t},\n\t}\n\n\t// if no MinVersion was set, default to TLS 1.2\n\tif tc.MinVersion == 0 {\n\t\ttc.MinVersion = tls.VersionTLS12\n\t}\n\n\tif pvs := NewPeerVerifiers(t.PeerVerify, extra...); len(pvs) > 0 {\n\t\ttc.VerifyPeerCertificate = pvs.VerifyPeerCertificate\n\t}\n\n\tif cert, err := tls.LoadX509KeyPair(t.CertificateFile, t.KeyFile); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\ttc.Certificates = []tls.Certificate{cert}\n\t}\n\n\tif len(t.ClientCACertificateFile) > 0 {\n\t\tcaCert, err := os.ReadFile(t.ClientCACertificateFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tcaCertPool := x509.NewCertPool()\n\t\tif !caCertPool.AppendCertsFromPEM(caCert) {\n\t\t\treturn nil, ErrUnableToAddClientCACertificate\n\t\t}\n\n\t\ttc.ClientCAs = caCertPool\n\t\ttc.ClientAuth = tls.RequireAndVerifyClientCert\n\t}\n\n\ttc.BuildNameToCertificate() // nolint: staticcheck\n\treturn tc, nil\n}", "func Client(conn net.Conn, config *tls.Config,) *tls.Conn", "func configureTLS(\n\tsaramaConf *sarama.Config, tlsConf *config.TLS,\n) (*sarama.Config, error) {\n\ttlsConfig, err := vtls.BuildTLSConfig(\n\t\ttlsConf.CertFile,\n\t\ttlsConf.KeyFile,\n\t\ttlsConf.TruststoreFile,\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tlsConfig != nil {\n\t\tsaramaConf.Net.TLS.Config = tlsConfig\n\t\tsaramaConf.Net.TLS.Enable = true\n\t}\n\n\treturn saramaConf, nil\n}", "func (f *PluginAPIClientMeta) GetTLSConfig() *TLSConfig {\n\t// If we need custom TLS configuration, then set it\n\tif f.flagCACert != \"\" || f.flagCAPath != \"\" || f.flagClientCert != \"\" || f.flagClientKey != \"\" || f.flagInsecure {\n\t\tt := &TLSConfig{\n\t\t\tCACert: f.flagCACert,\n\t\t\tCAPath: f.flagCAPath,\n\t\t\tClientCert: f.flagClientCert,\n\t\t\tClientKey: f.flagClientKey,\n\t\t\tTLSServerName: \"\",\n\t\t\tInsecure: f.flagInsecure,\n\t\t}\n\n\t\treturn t\n\t}\n\n\treturn nil\n}", "func DefaultHTTPClientFactory(cc *cli.Context) (*http.Client, error) {\n\tif cc == nil {\n\t\tlogrus.Panic(\"cli context has not been set\")\n\t}\n\tvar c http.Client\n\tcookieJar, _ := cookiejar.New(nil)\n\n\tif cc.GlobalIsSet(\"apiSession\") {\n\t\tvar cookies []*http.Cookie\n\t\tcookie := &http.Cookie{\n\t\t\tName: \"SESSION\",\n\t\t\tValue: cc.GlobalString(\"apiSession\"),\n\t\t}\n\t\tcookies = append(cookies, cookie)\n\t\tu, _ := url.Parse(os.Getenv(\"SPINNAKER_API\"))\n\t\tcookieJar.SetCookies(u, cookies)\n\t}\n\n\tc = http.Client{\n\t\tTimeout: time.Duration(cc.GlobalInt(\"clientTimeout\")) * time.Second,\n\t\tJar: cookieJar,\n\t}\n\n\tvar certPath string\n\tvar keyPath string\n\n\n\tif cc.GlobalIsSet(\"certPath\") {\n\t\tcertPath = cc.GlobalString(\"certPath\")\n\t} else if os.Getenv(\"SPINNAKER_CLIENT_CERT\") != \"\" {\n\t\tcertPath = os.Getenv(\"SPINNAKER_CLIENT_CERT\")\n\t} else {\n\t\tcertPath = \"\"\n\t}\n\tif cc.GlobalIsSet(\"keyPath\") {\n\t\tkeyPath = cc.GlobalString(\"keyPath\")\n\t} else if os.Getenv(\"SPINNAKER_CLIENT_KEY\") != \"\" {\n\t\tkeyPath = os.Getenv(\"SPINNAKER_CLIENT_KEY\")\n\t} else {\n\t\tkeyPath = \"\"\n\t}\n\tif cc.GlobalIsSet(\"iapToken\") {\n\t\tiapToken = cc.GlobalString(\"iapToken\")\n\t} else if os.Getenv(\"SPINNAKER_IAP_TOKEN\") != \"\" {\n\t\tiapToken = os.Getenv(\"SPINNAKER_IAP_TOKEN\")\n\t} else {\n\t\tiapToken = \"\"\n\t}\n\tc.Transport = &http.Transport{\n\t\tTLSClientConfig: &tls.Config{},\n\t}\n\n\tif certPath != \"\" && keyPath != \"\" {\n\t\tlogrus.Debug(\"Configuring TLS with pem cert/key pair\")\n\t\tcert, err := tls.LoadX509KeyPair(certPath, keyPath)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"loading x509 keypair\")\n\t\t}\n\n\t\tclientCA, err := ioutil.ReadFile(certPath)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"loading client CA\")\n\t\t}\n\n\t\tclientCertPool := x509.NewCertPool()\n\t\tclientCertPool.AppendCertsFromPEM(clientCA)\n\n\t\tc.Transport.(*http.Transport).TLSClientConfig.MinVersion = tls.VersionTLS12\n\t\tc.Transport.(*http.Transport).TLSClientConfig.PreferServerCipherSuites = true\n\t\tc.Transport.(*http.Transport).TLSClientConfig.Certificates = []tls.Certificate{cert}\n\t\tc.Transport.(*http.Transport).TLSClientConfig.InsecureSkipVerify = true\n\t}\n\n\tif cc.GlobalIsSet(\"insecure\") {\n\t\tc.Transport.(*http.Transport).TLSClientConfig.InsecureSkipVerify = true\n\t}\n\n\treturn &c, nil\n}", "func buildTLSConfig() *tls.Config {\n\trawTLSSetting := OptionalCLIConfigValue(\"core.ssl_verify\")\n\tif strings.EqualFold(rawTLSSetting, \"false\") {\n\t\t// 'false' (case insensitive): disable cert validation\n\t\treturn &tls.Config{InsecureSkipVerify: true}\n\t} else if strings.EqualFold(rawTLSSetting, \"true\") {\n\t\t// 'true' (case insensitive): require validation against default CAs\n\t\treturn &tls.Config{InsecureSkipVerify: false}\n\t} else if len(rawTLSSetting) != 0 {\n\t\t// '<other string>': path to local/custom cert file\n\t\tcert, err := ioutil.ReadFile(rawTLSSetting)\n\t\tif err != nil {\n\t\t\tPrintMessageAndExit(\"Unable to read from CA certificate file %s: %s\", rawTLSSetting, err)\n\t\t}\n\t\tcertPool := x509.NewCertPool()\n\t\tcertPool.AppendCertsFromPEM(cert)\n\t\treturn &tls.Config{\n\t\t\tInsecureSkipVerify: false,\n\t\t\tRootCAs: certPool,\n\t\t}\n\t} else { // len(rawTLSSetting) == 0\n\t\t// This shouldn't happen: 'dcos auth login' requires a non-empty setting.\n\t\t// Play it safe and leave cert verification enabled by default (equivalent to 'true' case)\n\t\treturn &tls.Config{InsecureSkipVerify: false}\n\t}\n}", "func (s *Server) tlsConfig() (*tls.Config, error) {\n\tc, err := tls2.GetX509KeyPair(s.config.Ssl.CertFile, s.config.Ssl.KeyFile, s.config.Ssl.KeyPassword)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error with certificate file %s: %w\", s.config.Ssl.CertFile, err)\n\t}\n\treturn &tls.Config{\n\t\tCertificates: []tls.Certificate{c},\n\t\tPreferServerCipherSuites: true,\n\t\tMinVersion: tls.VersionTLS12,\n\t}, nil\n}", "func LoadClientTLSConfig(sslCA, sslCert, sslCertKey string) (*tls.Config, error) {\n\tcertPEM, err := assetLoaderImpl.ReadFile(sslCert)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkeyPEM, err := assetLoaderImpl.ReadFile(sslCertKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcaPEM, err := assetLoaderImpl.ReadFile(sslCA)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newClientTLSConfig(certPEM, keyPEM, caPEM)\n}", "func Modern() *tls.Config {\n\treturn &tls.Config{\n\t\tMinVersion: tls.VersionTLS12,\n\t\tCurvePreferences: []tls.CurveID{\n\t\t\ttls.X25519,\n\t\t\ttls.CurveP256,\n\t\t},\n\t\tPreferServerCipherSuites: true,\n\t\tCipherSuites: []uint16{\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,\n\t\t},\n\t}\n}", "func GenTLSConfigUseCertMgrAndCertPool(\n\tm certificate.Manager,\n\troot *x509.CertPool) (*tls.Config, error) {\n\ttlsConfig := &tls.Config{\n\t\t// Can't use SSLv3 because of POODLE and BEAST\n\t\t// Can't use TLSv1.0 because of POODLE and BEAST using CBC cipher\n\t\t// Can't use TLSv1.1 because of RC4 cipher usage\n\t\tMinVersion: tls.VersionTLS12,\n\t\tClientCAs: root,\n\t\tClientAuth: tls.VerifyClientCertIfGiven,\n\t}\n\n\ttlsConfig.GetClientCertificate =\n\t\tfunc(*tls.CertificateRequestInfo) (*tls.Certificate, error) {\n\t\t\tcert := m.Current()\n\t\t\tif cert == nil {\n\t\t\t\treturn &tls.Certificate{Certificate: nil}, nil\n\t\t\t}\n\t\t\treturn cert, nil\n\t\t}\n\ttlsConfig.GetCertificate =\n\t\tfunc(*tls.ClientHelloInfo) (*tls.Certificate, error) {\n\t\t\tcert := m.Current()\n\t\t\tif cert == nil {\n\t\t\t\treturn &tls.Certificate{Certificate: nil}, nil\n\t\t\t}\n\t\t\treturn cert, nil\n\t\t}\n\n\treturn tlsConfig, nil\n}", "func DefaultClient() *Client {\n\treturn &Client{Key}\n}", "func ConfigTLS(config *appConf.Config, restConfig *restclient.Config) *tls.Config {\n\tif len(config.CertFile) != 0 && len(config.KeyFile) != 0 {\n\t\tsCert, err := tls.LoadX509KeyPair(config.CertFile, config.KeyFile)\n\t\tif err != nil {\n\t\t\tglog.Fatal(err)\n\t\t}\n\n\t\treturn &tls.Config{\n\t\t\tCertificates: []tls.Certificate{sCert},\n\t\t}\n\t}\n\n\tif len(restConfig.CertData) != 0 && len(restConfig.KeyData) != 0 {\n\t\tsCert, err := tls.X509KeyPair(restConfig.CertData, restConfig.KeyData)\n\t\tif err != nil {\n\t\t\tglog.Fatal(err)\n\t\t}\n\n\t\treturn &tls.Config{\n\t\t\tCertificates: []tls.Certificate{sCert},\n\t\t}\n\t}\n\n\tglog.Fatal(\"tls: failed to find any tls config data\")\n\treturn &tls.Config{}\n}", "func DefaultClientOptions() (clientOptions *ClientOptions) {\r\n\treturn &ClientOptions{\r\n\t\tBackOffExponentFactor: 2.0,\r\n\t\tBackOffInitialTimeout: 2 * time.Millisecond,\r\n\t\tBackOffMaximumJitterInterval: 2 * time.Millisecond,\r\n\t\tBackOffMaxTimeout: 10 * time.Millisecond,\r\n\t\tDialerKeepAlive: 20 * time.Second,\r\n\t\tDialerTimeout: 5 * time.Second,\r\n\t\tRequestRetryCount: 2,\r\n\t\tRequestTimeout: 10 * time.Second,\r\n\t\tTransportExpectContinueTimeout: 3 * time.Second,\r\n\t\tTransportIdleTimeout: 20 * time.Second,\r\n\t\tTransportMaxIdleConnections: 10,\r\n\t\tTransportTLSHandshakeTimeout: 5 * time.Second,\r\n\t\tUserAgent: defaultUserAgent,\r\n\t}\r\n}", "func TLSConfig(enabled bool, caPool *x509.CertPool) (opt urls.Option, config *tls.Config) {\n\topt = urls.Scheme(\"http\")\n\tif enabled {\n\t\topt = urls.Scheme(\"https\")\n\t\tif caPool != nil {\n\t\t\tconfig = &tls.Config{\n\t\t\t\tRootCAs: caPool,\n\t\t\t}\n\t\t} else {\n\t\t\t// do HTTPS without verifying the Mesos master certificate\n\t\t\tconfig = &tls.Config{\n\t\t\t\tInsecureSkipVerify: true,\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func GenerateTLSConfig(config TLSHelperConfig) (tlsCfg *tls.Config, reloadConfig func(), err error) {\n\twrapper := new(wrapperTLSConfig)\n\ttlsCfg = new(tls.Config)\n\twrapper.config = tlsCfg\n\n\tcert, err := parseCertificate(config.CertRequired, config.Cert, config.Key)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif cert != nil {\n\t\ttlsCfg.Certificates = []tls.Certificate{*cert}\n\t\tpool, err := generateCertPool(config.RootCACert, config.UseSystemCACerts)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tswitch config.ConfigType {\n\t\tcase TLSClientConfig:\n\t\t\ttlsCfg.RootCAs = pool\n\n\t\tcase TLSServerConfig:\n\t\t\twrapper.cert = &wrapperCert{cert: cert}\n\t\t\ttlsCfg.GetCertificate = wrapper.getCertificate\n\t\t\ttlsCfg.VerifyPeerCertificate = wrapper.verifyPeerCertificate\n\t\t\ttlsCfg.ClientCAs = pool\n\t\t\twrapper.clientCAPool = &wrapperCAPool{pool: pool}\n\t\t}\n\t}\n\n\tauth, err := setupClientAuth(config.ClientAuth)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// If the client cert is required to be checked with the CAs\n\tif auth >= tls.VerifyClientCertIfGiven {\n\t\t// A custom cert validation is set because the current implementation is\n\t\t// not thread safe, it's needed bypass that validation and manually\n\t\t// manage the different cases, for that reason, the wrapper is\n\t\t// configured with the real auth level and the tlsCfg is only set with a\n\t\t// auth level who are a simile but without the use of any CA\n\t\tif auth == tls.VerifyClientCertIfGiven {\n\t\t\ttlsCfg.ClientAuth = tls.RequestClientCert\n\t\t} else {\n\t\t\ttlsCfg.ClientAuth = tls.RequireAnyClientCert\n\t\t}\n\t\twrapper.clientAuth = auth\n\t} else {\n\t\t// it's not necessary a external validation with the CAs, so the wrapper\n\t\t// is not used\n\t\ttlsCfg.ClientAuth = auth\n\t}\n\n\ttlsCfg.MinVersion = tls.VersionTLS11\n\ttlsCfg.MaxVersion = tls.VersionTLS12\n\ttlsCfg.ServerName = config.ServerName\n\n\tif config.ConfigType == TLSClientConfig {\n\t\treturn tlsCfg, nil, nil\n\t}\n\n\twrapper.helperConfig = &config\n\treturn tlsCfg, wrapper.reloadConfig, nil\n}", "func NewClientTLSConfig(caCrtFile, certFile, keyFile string) (*tls.Config, error) {\n\ttc := &tls.Config{}\n\n\tif caCrtFile != \"\" {\n\t\tcaCrt, err := ioutil.ReadFile(caCrtFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcaCertPool := x509.NewCertPool()\n\t\tif ok := caCertPool.AppendCertsFromPEM(caCrt); !ok {\n\t\t\treturn nil, errors.New(\"failed to append CA cert as trusted cert\")\n\t\t}\n\n\t\ttc.RootCAs = caCertPool\n\t\ttc.ClientAuth = tls.RequireAndVerifyClientCert\n\t\ttc.InsecureSkipVerify = true // Not actually skipping, we check the cert in VerifyPeerCertificate\n\t\ttc.VerifyPeerCertificate = func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {\n\t\t\t// Code copy/pasted and adapted from\n\t\t\t// https://github.com/golang/go/blob/81555cb4f3521b53f9de4ce15f64b77cc9df61b9/src/crypto/tls/handshake_client.go#L327-L344, but adapted to skip the hostname verification.\n\t\t\t// See https://github.com/golang/go/issues/21971#issuecomment-412836078.\n\n\t\t\t// If this is the first handshake on a connection, process and\n\t\t\t// (optionally) verify the server's certificates.\n\t\t\tcerts := make([]*x509.Certificate, len(rawCerts))\n\t\t\tfor i, asn1Data := range rawCerts {\n\t\t\t\tcert, err := x509.ParseCertificate(asn1Data)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.New(\"bitbox/electrum: failed to parse certificate from server: \" + err.Error())\n\t\t\t\t}\n\t\t\t\tcerts[i] = cert\n\t\t\t}\n\n\t\t\topts := x509.VerifyOptions{\n\t\t\t\tRoots: caCertPool,\n\t\t\t\tCurrentTime: time.Now(),\n\t\t\t\tDNSName: \"\", // <- skip hostname verification\n\t\t\t\tIntermediates: x509.NewCertPool(),\n\t\t\t}\n\n\t\t\tfor i, cert := range certs {\n\t\t\t\tif i == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\topts.Intermediates.AddCert(cert)\n\t\t\t}\n\t\t\t_, err := certs[0].Verify(opts)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif certFile != \"\" {\n\t\tcliCrt, err := tls.LoadX509KeyPair(certFile, keyFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttc.Certificates = []tls.Certificate{cliCrt}\n\t}\n\n\treturn tc, nil\n}", "func setMinimumTLSVersion(client *http.Client) {\n\tif tr, ok := client.Transport.(*http.Transport); tr != nil && ok {\n\t\tif tr.TLSClientConfig == nil {\n\t\t\ttr.TLSClientConfig = &tls.Config{} // #nosec G402\n\t\t}\n\n\t\ttr.TLSClientConfig.MinVersion = tls.VersionTLS12\n\t}\n}", "func (rec *Recorder) GetDefaultClient() *http.Client {\n\tclient := &http.Client{\n\t\tTransport: rec,\n\t}\n\n\treturn client\n}", "func TestNewConfigTLS(t *testing.T) {\n\tconfig, err := NewConfig(\"configs/tls.yaml\")\n\trequire.NoError(t, err)\n\t// Liftbridge TLS\n\trequire.Equal(t, \"./configs/certs/server/server-key.pem\", config.TLSKey)\n\trequire.Equal(t, \"./configs/certs/server/server-cert.pem\", config.TLSCert)\n}", "func generateTLSConfig() *tls.Config {\n\tkey, err := rsa.GenerateKey(rand.Reader, 1024)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttemplate := x509.Certificate{SerialNumber: big.NewInt(1)}\n\tcertDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tkeyPEM := pem.EncodeToMemory(&pem.Block{Type: \"RSA PRIVATE KEY\", Bytes: x509.MarshalPKCS1PrivateKey(key)})\n\tcertPEM := pem.EncodeToMemory(&pem.Block{Type: \"CERTIFICATE\", Bytes: certDER})\n\n\ttlsCert, err := tls.X509KeyPair(certPEM, keyPEM)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn &tls.Config{\n\t\tCertificates: []tls.Certificate{tlsCert},\n\t\tNextProtos: []string{\"quic-echo-example\"},\n\t}\n}", "func Compatible() *tls.Config {\n\treturn &tls.Config{\n\t\tMinVersion: tls.VersionTLS10,\n\t\tCurvePreferences: []tls.CurveID{\n\t\t\ttls.X25519,\n\t\t\ttls.CurveP256,\n\t\t},\n\t\tPreferServerCipherSuites: true,\n\t\tCipherSuites: []uint16{\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,\n\t\t\ttls.TLS_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_RSA_WITH_AES_128_GCM_SHA256,\n\t\t\ttls.TLS_RSA_WITH_AES_256_CBC_SHA,\n\t\t\ttls.TLS_RSA_WITH_AES_128_CBC_SHA,\n\t\t\ttls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,\n\t\t},\n\t}\n}", "func GetTLSVersion(tr *http.Transport) string {\n switch tr.TLSClientConfig.MinVersion {\n case tls.VersionTLS10:\n return \"TLS 1.0\"\n case tls.VersionTLS11:\n return \"TLS 1.1\"\n case tls.VersionTLS12:\n return \"TLS 1.2\"\n case tls.VersionTLS13:\n return \"TLS 1.3\"\n }\n\n return \"Unknown\"\n}", "func (t *TLSServer) GetConfigForClient(info *tls.ClientHelloInfo) (*tls.Config, error) {\n\tvar clusterName string\n\tvar err error\n\tswitch info.ServerName {\n\tcase \"\":\n\t\t// Client does not use SNI, will validate against all known CAs.\n\tdefault:\n\t\tclusterName, err = apiutils.DecodeClusterName(info.ServerName)\n\t\tif err != nil {\n\t\t\tif !trace.IsNotFound(err) {\n\t\t\t\tt.log.Warningf(\"Client sent unsupported cluster name %q, what resulted in error %v.\", info.ServerName, err)\n\t\t\t\treturn nil, trace.AccessDenied(\"access is denied\")\n\t\t\t}\n\t\t}\n\t}\n\n\t// update client certificate pool based on currently trusted TLS\n\t// certificate authorities.\n\t// TODO(klizhentas) drop connections of the TLS cert authorities\n\t// that are not trusted\n\tpool, totalSubjectsLen, err := DefaultClientCertPool(t.cfg.AccessPoint, clusterName)\n\tif err != nil {\n\t\tvar ourClusterName string\n\t\tif clusterName, err := t.cfg.AccessPoint.GetClusterName(); err == nil {\n\t\t\tourClusterName = clusterName.GetClusterName()\n\t\t}\n\t\tt.log.Errorf(\"Failed to retrieve client pool for client %v, client cluster %v, target cluster %v, error: %v.\",\n\t\t\tinfo.Conn.RemoteAddr().String(), clusterName, ourClusterName, trace.DebugReport(err))\n\t\t// this falls back to the default config\n\t\treturn nil, nil\n\t}\n\n\t// Per https://tools.ietf.org/html/rfc5246#section-7.4.4 the total size of\n\t// the known CA subjects sent to the client can't exceed 2^16-1 (due to\n\t// 2-byte length encoding). The crypto/tls stack will panic if this\n\t// happens. To make the error less cryptic, catch this condition and return\n\t// a better error.\n\t//\n\t// This may happen with a very large (>500) number of trusted clusters, if\n\t// the client doesn't send the correct ServerName in its ClientHelloInfo\n\t// (see the switch at the top of this func).\n\tif totalSubjectsLen >= int64(math.MaxUint16) {\n\t\treturn nil, trace.BadParameter(\"number of CAs in client cert pool is too large and cannot be encoded in a TLS handshake; this is due to a large number of trusted clusters; try updating tsh to the latest version; if that doesn't help, remove some trusted clusters\")\n\t}\n\n\ttlsCopy := t.cfg.TLS.Clone()\n\ttlsCopy.ClientCAs = pool\n\tfor _, cert := range tlsCopy.Certificates {\n\t\tt.log.Debugf(\"Server certificate %v.\", TLSCertInfo(&cert))\n\t}\n\treturn tlsCopy, nil\n}", "func ConfigTLS(c Config) *tls.Config {\n\tsCert, err := tls.LoadX509KeyPair(c.CertFile, c.KeyFile)\n\tif err != nil {\n\t\tglog.Fatal(err)\n\t}\n\treturn &tls.Config{\n\t\tCertificates: []tls.Certificate{sCert},\n\t\t// TODO: uses mutual tls after we agree on what cert the apiserver should use.\n\t\t// ClientAuth: tls.RequireAndVerifyClientCert,\n\t}\n}", "func CustomizeTLSTransport(fedCluster *fedv1b1.KubeFedCluster, clientConfig *restclient.Config) error {\n\tclientTransportConfig, err := clientConfig.TransportConfig()\n\tif err != nil {\n\t\treturn errors.Errorf(\"Cluster %s client transport config error: %s\", fedCluster.Name, err)\n\t}\n\ttransportConfig, err := transport.TLSConfigFor(clientTransportConfig)\n\tif err != nil {\n\t\treturn errors.Errorf(\"Cluster %s transport error: %s\", fedCluster.Name, err)\n\t}\n\n\tif transportConfig != nil {\n\t\terr = CustomizeCertificateValidation(fedCluster, transportConfig)\n\t\tif err != nil {\n\t\t\treturn errors.Errorf(\"Cluster %s custom certificate validation error: %s\", fedCluster.Name, err)\n\t\t}\n\n\t\t// using the same defaults as http.DefaultTransport\n\t\tclientConfig.Transport = &http.Transport{\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tDialContext: (&net.Dialer{\n\t\t\t\tTimeout: 30 * time.Second,\n\t\t\t\tKeepAlive: 30 * time.Second,\n\t\t\t\tDualStack: true,\n\t\t\t}).DialContext,\n\t\t\tMaxIdleConns: 100,\n\t\t\tIdleConnTimeout: 90 * time.Second,\n\t\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\t\tExpectContinueTimeout: 1 * time.Second,\n\t\t\tTLSClientConfig: transportConfig,\n\t\t}\n\t\tclientConfig.TLSClientConfig = restclient.TLSClientConfig{}\n\t} else {\n\t\tclientConfig.Insecure = true\n\t}\n\n\treturn nil\n}", "func (client *BaseClient) SetTLSClientConfig(config *tls.Config) {}", "func TLSGenClient(c agent.ConfigClient, options ...tlsx.Option) (creds *tls.Config, err error) {\n\tvar (\n\t\tpool *x509.CertPool\n\t)\n\n\tif pool, err = x509.SystemCertPool(); err != nil {\n\t\treturn creds, errors.WithStack(err)\n\t}\n\n\tif systemx.FileExists(c.CA) {\n\t\tif err = LoadCert(pool, c.CA); err != nil {\n\t\t\treturn creds, errors.WithStack(err)\n\t\t}\n\t}\n\n\tcreds = &tls.Config{\n\t\tServerName: c.ServerName,\n\t\tRootCAs: pool,\n\t\tNextProtos: []string{\"bw.mux\"},\n\t\tInsecureSkipVerify: c.Credentials.Insecure,\n\t}\n\n\treturn tlsx.Clone(creds, options...)\n}", "func getUseTLS() bool {\n\toption := os.Getenv(\"HUSKYCI_CLIENT_API_USE_HTTPS\")\n\tif option == \"true\" || option == \"1\" || option == \"TRUE\" {\n\t\treturn true\n\t}\n\treturn false\n}", "func (opts *Options) ServerTLSConfig() *tls.Config {\n\treturn opts.tlsConfig(true)\n}", "func TLSConfig(crtName string, skipInsecureVerify bool) (*tls.Config, error) {\n\tappConfig, err := GetAppConfig()\n\tif err != nil {\n\t\tlog.Error(\"Get app config error.\", nil)\n\t\treturn nil, err\n\t}\n\tcertNameConfig := appConfig[crtName]\n\tif len(certNameConfig) == 0 {\n\t\tlog.Errorf(nil, \"Certificate(%s) path doesn't available in the app config.\", crtName)\n\t\treturn nil, errors.New(\"cert name configuration is not set\")\n\t}\n\n\tcrt, err := ioutil.ReadFile(certNameConfig)\n\tif err != nil {\n\t\tlog.Error(\"Unable to read certificate.\", nil)\n\t\treturn nil, err\n\t}\n\n\trootCAs := x509.NewCertPool()\n\tok := rootCAs.AppendCertsFromPEM(crt)\n\tif !ok {\n\t\tlog.Error(\"Failed to decode the certificate file.\", nil)\n\t\treturn nil, errors.New(\"failed to decode cert file\")\n\t}\n\n\tserverName := appConfig[\"server_name\"]\n\tserverNameIsValid, validateServerNameErr := validateServerName(serverName)\n\tif validateServerNameErr != nil || !serverNameIsValid {\n\t\tlog.Error(\"Validate server name error.\", nil)\n\t\treturn nil, validateServerNameErr\n\t}\n\tsslCiphers := appConfig[\"ssl_ciphers\"]\n\tif len(sslCiphers) == 0 {\n\t\treturn nil, errors.New(\"TLS cipher configuration is not recommended or invalid\")\n\t}\n\tcipherSuites := getCipherSuites(sslCiphers)\n\tif cipherSuites == nil {\n\t\treturn nil, errors.New(\"TLS cipher configuration is not recommended or invalid\")\n\t}\n\treturn &tls.Config{\n\t\tRootCAs: rootCAs,\n\t\tServerName: serverName,\n\t\tMinVersion: tls.VersionTLS12,\n\t\tCipherSuites: cipherSuites,\n\t\tInsecureSkipVerify: skipInsecureVerify,\n\t}, nil\n}", "func TestGoDefaultIsOkay(t *testing.T) {\n\tclientConf := &tls.Config{}\n\tc := connect(t, clientConf)\n\tci := pullClientInfo(c)\n\tt.Logf(\"%#v\", ci)\n\n\tif ci.Rating != okay {\n\t\tt.Errorf(\"Go client rating: want %s, got %s\", okay, ci.Rating)\n\t}\n\tif len(ci.GivenCipherSuites) == 0 {\n\t\tt.Errorf(\"no cipher suites given\")\n\t}\n\tif ci.TLSCompressionSupported {\n\t\tt.Errorf(\"TLSCompressionSupported was somehow true even though Go's TLS client doesn't support it\")\n\t}\n\tif !ci.SessionTicketsSupported {\n\t\tt.Errorf(\"SessionTicketsSupported was false but we set that in connect explicitly\")\n\t}\n}", "func newTLSConfig(target string, registry *prometheus.Registry, cfg *config.TLSConfig) (*tls.Config, error) {\n\ttlsConfig, err := config.NewTLSConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tlsConfig.ServerName == \"\" && target != \"\" {\n\t\ttargetAddress, _, err := net.SplitHostPort(target)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttlsConfig.ServerName = targetAddress\n\t}\n\n\ttlsConfig.VerifyConnection = func(state tls.ConnectionState) error {\n\t\treturn collectConnectionStateMetrics(state, registry)\n\t}\n\n\treturn tlsConfig, nil\n}", "func LoadTLSConfig(config *TLSConfig) (*tls.Config, error) {\n\tif config == nil {\n\t\treturn nil, nil\n\t}\n\n\tcertificate := config.Certificate\n\tkey := config.CertificateKey\n\trootCAs := config.CAs\n\thasCertificate := certificate != \"\"\n\thasKey := key != \"\"\n\n\tvar certs []tls.Certificate\n\tswitch {\n\tcase hasCertificate && !hasKey:\n\t\treturn nil, ErrCertificateNoKey\n\tcase !hasCertificate && hasKey:\n\t\treturn nil, ErrKeyNoCertificate\n\tcase hasCertificate && hasKey:\n\t\tcert, err := tls.LoadX509KeyPair(certificate, key)\n\t\tif err != nil {\n\t\t\tlogp.Critical(\"Failed loading client certificate\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tcerts = []tls.Certificate{cert}\n\t}\n\n\tvar roots *x509.CertPool\n\tif len(rootCAs) > 0 {\n\t\troots = x509.NewCertPool()\n\t\tfor _, caFile := range rootCAs {\n\t\t\tpemData, err := ioutil.ReadFile(caFile)\n\t\t\tif err != nil {\n\t\t\t\tlogp.Critical(\"Failed reading CA certificate: %s\", err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif ok := roots.AppendCertsFromPEM(pemData); !ok {\n\t\t\t\treturn nil, ErrNotACertificate\n\t\t\t}\n\t\t}\n\t}\n\n\tminVersion, err := parseTLSVersion(config.MinVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif minVersion == 0 {\n\t\t// require minimum TLS-1.0 if not configured\n\t\tminVersion = tls.VersionTLS10\n\t}\n\n\tmaxVersion, err := parseTLSVersion(config.MaxVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcipherSuites, err := parseTLSCipherSuites(config.CipherSuites)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcurveIDs, err := parseCurveTypes(config.CurveTypes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttlsConfig := tls.Config{\n\t\tMinVersion: minVersion,\n\t\tMaxVersion: maxVersion,\n\t\tCertificates: certs,\n\t\tRootCAs: roots,\n\t\tInsecureSkipVerify: config.Insecure,\n\t\tCipherSuites: cipherSuites,\n\t\tCurvePreferences: curveIDs,\n\t}\n\treturn &tlsConfig, nil\n}", "func NewDefaultClient(ctx context.Context) (*Client, error) {\n\tsock, token, err := DefaultSocketPath()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewClient(ctx, sock, token)\n}", "func getTLSConfig(cfg *Config) (*tls.Config, *credentials.TransportCredentials,\n\terror) {\n\n\t// Let's load our certificate first or create then load if it doesn't\n\t// yet exist.\n\tcertData, parsedCert, err := loadCertWithCreate(cfg)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// If the certificate expired or it was outdated, delete it and the TLS\n\t// key and generate a new pair.\n\tif time.Now().After(parsedCert.NotAfter) {\n\t\tlog.Info(\"TLS certificate is expired or outdated, \" +\n\t\t\t\"removing old file then generating a new one\")\n\n\t\terr := os.Remove(cfg.TLSCertPath)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\terr = os.Remove(cfg.TLSKeyPath)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\tcertData, _, err = loadCertWithCreate(cfg)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\ttlsCfg := cert.TLSConfFromCert(certData)\n\ttlsCfg.NextProtos = []string{\"h2\"}\n\trestCreds, err := credentials.NewClientTLSFromFile(\n\t\tcfg.TLSCertPath, \"\",\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn tlsCfg, &restCreds, nil\n}", "func (s *Server) generateTLSConfig(opts *TLSOptions) (*tls.Config, error) {\n\treturn generateTLSConfig(opts)\n}", "func GetDefaultClient() Client {\n\treturn defaultClient\n}", "func GetHTTPClient() *http.Client {\r\n tlsConfig := &tls.Config {\r\n InsecureSkipVerify: true, //for this test, ignore ssl certificate\r\n }\r\n\r\n tr := &http.Transport{TLSClientConfig: tlsConfig}\r\n client := &http.Client{Transport: tr}\r\n\r\n return client\r\n}", "func ConfigureTLSConfig(tlsConf *tls.Config) *tls.Config {\n\t// The tls.Config used to setup the quic.Listener needs to have the GetConfigForClient callback set.\n\t// That way, we can get the QUIC version and set the correct ALPN value.\n\treturn &tls.Config{\n\t\tGetConfigForClient: func(ch *tls.ClientHelloInfo) (*tls.Config, error) {\n\t\t\t// determine the ALPN from the QUIC version used\n\t\t\tproto := NextProtoH3\n\t\t\tval := ch.Context().Value(quic.QUICVersionContextKey)\n\t\t\tif v, ok := val.(quic.VersionNumber); ok {\n\t\t\t\tproto = versionToALPN(v)\n\t\t\t}\n\t\t\tconfig := tlsConf\n\t\t\tif tlsConf.GetConfigForClient != nil {\n\t\t\t\tgetConfigForClient := tlsConf.GetConfigForClient\n\t\t\t\tvar err error\n\t\t\t\tconf, err := getConfigForClient(ch)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif conf != nil {\n\t\t\t\t\tconfig = conf\n\t\t\t\t}\n\t\t\t}\n\t\t\tif config == nil {\n\t\t\t\treturn nil, nil\n\t\t\t}\n\t\t\tconfig = config.Clone()\n\t\t\tconfig.NextProtos = []string{proto}\n\t\t\treturn config, nil\n\t\t},\n\t}\n}", "func ValidateTLSConfig(config *schema.TLS, configDefault *schema.TLS) (err error) {\n\tif configDefault == nil {\n\t\treturn errors.New(\"must provide configDefault\")\n\t}\n\n\tif config == nil {\n\t\treturn\n\t}\n\n\tif config.ServerName == \"\" {\n\t\tconfig.ServerName = configDefault.ServerName\n\t}\n\n\tif config.MinimumVersion.Value == 0 {\n\t\tconfig.MinimumVersion.Value = configDefault.MinimumVersion.Value\n\t}\n\n\tif config.MaximumVersion.Value == 0 {\n\t\tconfig.MaximumVersion.Value = configDefault.MaximumVersion.Value\n\t}\n\n\tif config.MinimumVersion.MinVersion() < tls.VersionTLS10 {\n\t\treturn errors.New(\"option 'minimum_version' is invalid: minimum version is TLS1.0 but SSL3.0 was configured\")\n\t}\n\n\tif config.MinimumVersion.MinVersion() > config.MaximumVersion.MaxVersion() {\n\t\treturn fmt.Errorf(\"option combination of 'minimum_version' and 'maximum_version' is invalid: minimum version %s is greater than the maximum version %s\", config.MinimumVersion.String(), config.MaximumVersion.String())\n\t}\n\n\tif (config.CertificateChain.HasCertificates() || config.PrivateKey != nil) && !config.CertificateChain.EqualKey(config.PrivateKey) {\n\t\treturn errors.New(\"option 'certificates' is invalid: provided certificate does not contain the public key for the private key provided\")\n\t}\n\n\treturn nil\n}", "func TLSConfig(tc *tls.Config) ConfigOpt {\n\treturn func(c *Config) {\n\t\tc.transport.TLSClientConfig = tc\n\t}\n}", "func (o *ClientConfiguration) GetSupportSubjectDefault() string {\n\tif o == nil || o.SupportSubjectDefault.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn *o.SupportSubjectDefault.Get()\n}", "func (f *Forwarder) getTLSConfig(sess *clusterSession) (*tls.Config, bool, error) {\n\tif sess.kubeAPICreds != nil {\n\t\treturn sess.kubeAPICreds.getTLSConfig(), false, nil\n\t}\n\n\t// if the next hop supports impersonation, we can use the TLS config\n\t// of the proxy to connect to it.\n\tif f.allServersSupportImpersonation(sess) {\n\t\treturn f.cfg.ConnTLSConfig.Clone(), true, nil\n\t}\n\n\t// If the next hop does not support impersonation, we need to get a\n\t// certificate from the auth server with the identity of the user\n\t// that is requesting the connection.\n\t// TODO(tigrato): DELETE in 15.0.0\n\ttlsConfig, err := f.getOrRequestClientCreds(sess.requestContext, sess.authContext)\n\tif err != nil {\n\t\tf.log.Warningf(\"Failed to get certificate for %v: %v.\", sess.authContext, err)\n\t\treturn nil, false, trace.AccessDenied(\"access denied: failed to authenticate with auth server\")\n\t}\n\treturn tlsConfig, false, nil\n}", "func HTTPClientWithTLSConfig(conf *tls.Config) *http.Client {\n\treturn &http.Client{\n\t\tTimeout: time.Second * 20,\n\t\tTransport: &http.Transport{\n\t\t\tDial: (&net.Dialer{\n\t\t\t\tTimeout: 5 * time.Second,\n\t\t\t}).Dial,\n\t\t\tTLSHandshakeTimeout: 5 * time.Second,\n\t\t\tTLSClientConfig: conf,\n\t\t},\n\t}\n}", "func newDefaultClient() *Client {\n\tcl := &Client{\n\t\tctx: frugal.NewFContext(\"\"),\n\t\tClientSetting: &ClientSetting{\n\t\t\tAppType: model.ApplicationType_ANDROID,\n\t\t\tKeeperDir: getHomeDir() + \"/.line-keepers/\",\n\t\t\tLogger: logger.New(),\n\t\t},\n\t\tClientInfo: &ClientInfo{\n\t\t\tDevice: newLineDevice(),\n\t\t},\n\t\tTokenManager: &TokenManager{},\n\t\tProfile: &model.Profile{},\n\t\tSettings: &model.Settings{},\n\t\tHeaderFactory: &HeaderFactory{\n\t\t\tAndroidVersion: getRandomAndroidVersion(),\n\t\t\tAndroidAppVersion: getRandomAndroidAppVersion(),\n\t\t\tAndroidLiteAppVersion: getRandomAndroidLiteAppVersion(),\n\t\t},\n\t\tE2EEKeyStore: NewE2EEKeyStore(),\n\t}\n\tcl.ClientSetting.AfterTalkError = map[model.TalkErrorCode]func(err *model.TalkException) error{\n\t\tmodel.TalkErrorCode_MUST_REFRESH_V3_TOKEN: func(talkErr *model.TalkException) error {\n\t\t\terr := cl.RefreshV3AccessToken()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn xerrors.Errorf(\"update v3 access token done: %w\", talkErr)\n\t\t},\n\t}\n\treturn cl\n}", "func (a AdminAPI) GetTLS() *TLSConfig {\n\treturn &TLSConfig{\n\t\tEnabled: a.TLS.Enabled,\n\t\tRequireClientAuth: a.TLS.RequireClientAuth,\n\t\tIssuerRef: nil,\n\t\tNodeSecretRef: nil,\n\t}\n}", "func (c *Config) ClientTLSConfig() (*tls.Config, error) {\n\tclientCert, err := tls.LoadX509KeyPair(c.Copilot.ClientCertPath, c.Copilot.ClientKeyPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"loading client cert/key: %s\", err)\n\t}\n\n\tserverCABytes, err := ioutil.ReadFile(c.Copilot.ServerCACertPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"loading server CAs: %s\", err)\n\t}\n\tserverCAs := x509.NewCertPool()\n\tif ok := serverCAs.AppendCertsFromPEM(serverCABytes); !ok {\n\t\treturn nil, errors.New(\"loading server CAs: failed to find any PEM data\")\n\t}\n\n\treturn &tls.Config{\n\t\tMinVersion: tls.VersionTLS12,\n\t\tPreferServerCipherSuites: true,\n\t\tCipherSuites: []uint16{\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n\t\t},\n\t\tCurvePreferences: []tls.CurveID{tls.CurveP384},\n\t\tCertificates: []tls.Certificate{clientCert},\n\t\tRootCAs: serverCAs,\n\t}, nil\n}" ]
[ "0.7757579", "0.73898035", "0.7186819", "0.698095", "0.69737124", "0.68734145", "0.67112315", "0.670439", "0.66459376", "0.66334057", "0.65963924", "0.6532116", "0.6517969", "0.64405006", "0.64308745", "0.64007217", "0.6352451", "0.6346045", "0.63455445", "0.63204676", "0.63204676", "0.63081735", "0.6284903", "0.62804013", "0.6280311", "0.62258273", "0.62201023", "0.62180644", "0.62177575", "0.6199917", "0.61881286", "0.61697304", "0.6155046", "0.61529005", "0.6145282", "0.61311036", "0.61210585", "0.6109263", "0.6096443", "0.60834163", "0.6069589", "0.60651547", "0.6061356", "0.6050897", "0.6023292", "0.60144275", "0.60140103", "0.6013857", "0.5971888", "0.5969623", "0.59675515", "0.5964733", "0.59627366", "0.59587663", "0.5929105", "0.59253025", "0.5921441", "0.59077567", "0.58914757", "0.58905715", "0.58886313", "0.5863993", "0.58621967", "0.58567685", "0.5855269", "0.58542114", "0.5832143", "0.5830106", "0.5829401", "0.5822848", "0.58176315", "0.5814107", "0.57975", "0.5796817", "0.5796039", "0.57867384", "0.5786224", "0.57795304", "0.5771425", "0.57697296", "0.5746893", "0.57226646", "0.5715438", "0.57110673", "0.5710871", "0.57107896", "0.5709814", "0.57028335", "0.56965524", "0.569389", "0.56877464", "0.568609", "0.56770813", "0.56733096", "0.56709635", "0.5669272", "0.5667637", "0.5664769", "0.5662023", "0.5653688" ]
0.7764376
0
Reply posts a message as a reply to another message identified by an ID.
func Reply(client Replyer, ID int64, post string, dryRun bool) (*string, error) { if dryRun { result := doDryRun(post) return &result, nil } url, err := client.Reply(ID, post) if err != nil { return nil, err } result := url.String() return &result, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m Message) Reply(reply string) {\n\tmessage := &ReplyMessage{\n\t\tmsg: tgbotapi.NewMessage(m.Chat.ID, reply),\n\t}\n\tm.replies <- message\n}", "func (d *Dao) Reply(c context.Context, oid, rpID int64) (r *model.Reply, err error) {\n\tr = new(model.Reply)\n\trow := d.db.QueryRow(c, fmt.Sprintf(_selReplySQL, hit(oid)), rpID)\n\tif err = row.Scan(&r.ID, &r.Oid, &r.Type, &r.Mid, &r.Root, &r.Parent, &r.Dialog, &r.Count, &r.RCount, &r.Like, &r.Hate, &r.Floor, &r.State, &r.Attr, &r.CTime, &r.MTime); err != nil {\n\t\tif err == xsql.ErrNoRows {\n\t\t\tr = nil\n\t\t\terr = nil\n\t\t}\n\t}\n\treturn\n}", "func (m *ChatMessage) SetReplyToId(value *string)() {\n m.replyToId = value\n}", "func (o *LicenseNotificationReply) SetReplyId(v string) {\n\to.ReplyId = v\n}", "func (r *response) Reply(message string, options ...ReplyOption) error {\n\tdefaults := NewReplyDefaults(options...)\n\n\tclient := r.botCtx.Client()\n\tev := r.botCtx.Event()\n\tif ev == nil {\n\t\treturn fmt.Errorf(\"unable to get message event details\")\n\t}\n\n\topts := []slack.MsgOption{\n\t\tslack.MsgOptionText(message, false),\n\t\tslack.MsgOptionAttachments(defaults.Attachments...),\n\t\tslack.MsgOptionBlocks(defaults.Blocks...),\n\t}\n\tif defaults.ThreadResponse {\n\t\topts = append(opts, slack.MsgOptionTS(ev.TimeStamp))\n\t}\n\n\t_, _, err := client.PostMessage(\n\t\tev.Channel,\n\t\topts...,\n\t)\n\treturn err\n}", "func (c *Conversation) Reply(text string, a ...interface{}) {\n\tprefix := \"\"\n\n\tif !c.message.IsDirectMessage() {\n\t\tprefix = \"<@\" + c.message.UserID() + \">: \"\n\t}\n\n\tmsg := c.message\n\tmsg.SetText(prefix + fmt.Sprintf(text, a...))\n\n\tc.send(msg)\n}", "func (r *response) Reply(message string) {\n\t_, _ = r.client.SendMessage(r.channel, message)\n}", "func (mc *MessageContext) Reply(msg *transport.Message) error {\n\t// If this is an RPC message we should send a reply, if not just send a regular message\n\tif mc.Message.IsRequest {\n\t\tp, exists := mc.Legion.peers.Load(mc.Sender)\n\t\tif exists {\n\t\t\tp.(*Peer).QueueReply(mc.Message.RpcId, msg)\n\t\t} else {\n\t\t\treturn errors.New(\"legion: error sending reply to peer\")\n\t\t}\n\t} else {\n\t\tmc.Legion.Broadcast(msg, mc.Sender)\n\t}\n\n\treturn nil\n}", "func (bot *Bot) reply(msg *Message, text string) {\n\tgo func(msg *Message) {\n\t\tmsg.Id = atomic.AddUint64(&bot.counter, 1)\n\t\tmsg.Text = text\n\t\t_ = websocket.JSON.Send(bot.conn, msg)\n\t}(msg)\n}", "func UpdateReply(w http.ResponseWriter, r *http.Request) {\n\tsessionID := r.Header.Get(\"sessionID\")\n\tuser, err := getUserFromSession(sessionID)\n\n\tif err != nil {\n\t\tmsg := map[string]string{\"error\": \"Sorry there was an internal server error\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\tif !user.Active {\n\t\tmsg := map[string]string{\"error\": \"Sorry your account isn't activated yet\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\tid := r.URL.Query().Get(\"id\")\n\n\tif id == \"\" {\n\t\tmsg := map[string]string{\"error\": \"id required\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\tvar reply = &comments.Reply{ID: id}\n\n\terr = reply.Get()\n\n\tif err != nil {\n\t\tmsg := map[string]string{\"error\": \"Sorry there was an internal server error\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\tif user.DisplayName != reply.Username {\n\t\tmsg := map[string]string{\"error\": \"Sorry you're not authorized to view this page\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusForbidden)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\terr = json.NewDecoder(r.Body).Decode(&reply)\n\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tmsg := map[string]string{\"error\": \"Sorry there was an internal server error\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\terr = reply.Update()\n\n\tif err != nil {\n\t\tmsg := map[string]string{\"error\": \"Sorry there was an internal server error\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(reply)\n\n}", "func (r *relay) handleReply(reqId uint64, rep []byte) {\n\tr.reqLock.RLock()\n\tdefer r.reqLock.RUnlock()\n\tr.reqPend[reqId] <- rep\n}", "func (b *Bus) Reply(ctx context.Context, origin, reply *message.Message) {\n\tid := middleware.MessageCorrelationID(origin)\n\tmiddleware.SetCorrelationID(id, reply)\n\n\toriginSender := origin.Metadata.Get(MetaSender)\n\tif originSender == \"\" {\n\t\tinslogger.FromContext(ctx).Error(\"failed to send reply (no sender)\")\n\t\treturn\n\t}\n\treply.Metadata.Set(MetaReceiver, originSender)\n\treply.Metadata.Set(MetaTraceID, origin.Metadata.Get(MetaTraceID))\n\n\terr := b.pub.Publish(TopicOutgoing, reply)\n\tif err != nil {\n\t\tinslogger.FromContext(ctx).Errorf(\"can't publish message to %s topic: %s\", TopicOutgoing, err.Error())\n\t}\n}", "func (s MessageState) Reply(content string) (*disgord.Message, error) {\n\t// Don't mention the user in a DM.\n\tif !s.IsDMChannel() {\n\t\tcontent = s.Event.Message.Author.Mention() + \" \" + content\n\t}\n\n\treturn s.Send(content)\n}", "func (c *Client) Reply(req *Packet, hwAddr net.HardwareAddr, ip net.IP) error {\n\tp, err := NewPacket(OperationReply, hwAddr, ip, req.SenderHardwareAddr, req.SenderIP)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.WriteTo(p, req.SenderHardwareAddr)\n}", "func (p *Pod) ReplyTo(inReplyTo Message, msg Message) *MsgReceipt {\n\tmsg.SetReplyTo(inReplyTo.UUID())\n\n\treturn p.Send(msg)\n}", "func (app *App) Reply(msg osc.Message) error {\n\taddr, err := msg.Arguments[0].ReadString()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"reading first argument of reply\")\n\t}\n\tapp.debugf(\"received reply for %s\", addr)\n\tapp.replies <- msg\n\treturn nil\n}", "func ReplyIdent(ident string) *Reply { return &Reply{220, []string{ident}, nil} }", "func (d *DeviceBase) Reply(msgID MsgID, reply proto.Message, err error) error {\n\treturn SendReply(d.busPort, msgID, reply, err)\n}", "func (d *RMQ) SendReply(topic string) error { return nil }", "func (b *Bot) Reply(m *irc.Message, format string, v ...interface{}) error {\n\tif len(m.Params) < 1 || len(m.Params[0]) < 1 {\n\t\treturn errors.New(\"Invalid IRC message\")\n\t}\n\n\ttarget := m.Prefix.Name\n\tif b.FromChannel(m) {\n\t\ttarget = m.Params[0]\n\t}\n\n\tfullMsg := fmt.Sprintf(format, v...)\n\tfor _, resp := range strings.Split(fullMsg, \"\\n\") {\n\t\tb.Send(&irc.Message{\n\t\t\tPrefix: &irc.Prefix{},\n\t\t\tCommand: \"PRIVMSG\",\n\t\t\tParams: []string{\n\t\t\t\ttarget,\n\t\t\t\tresp,\n\t\t\t},\n\t\t})\n\t}\n\n\treturn nil\n}", "func DeleteReply(w http.ResponseWriter, r *http.Request) {\n\tsessionID := r.Header.Get(\"sessionID\")\n\tuser, err := getUserFromSession(sessionID)\n\n\tif err != nil {\n\t\tmsg := map[string]string{\"error\": \"Sorry there was an internal server error\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\tif !user.Active {\n\t\tmsg := map[string]string{\"error\": \"Sorry your account isn't activated yet\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\tid := r.URL.Query().Get(\"id\")\n\n\tif id == \"\" {\n\t\tmsg := map[string]string{\"error\": \"id required\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\tparams := mux.Vars(r)\n\tcommentID := params[\"comment_id\"]\n\n\tif commentID == \"\" {\n\t\tmsg := map[string]string{\"error\": \"comment id required\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\tvar reply = &comments.Reply{ID: id, CommentID: commentID}\n\n\terr = reply.Get()\n\n\tif err != nil {\n\t\tmsg := map[string]string{\"error\": \"Sorry there was an internal server error\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\tif user.DisplayName != reply.Username {\n\t\tmsg := map[string]string{\"error\": \"Sorry you're not authorized to view this page\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusForbidden)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\terr = reply.Delete()\n\n\tif err != nil {\n\t\tmsg := map[string]string{\"error\": \"Sorry there was an internal server error\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\tmsg := map[string]string{\"message\": \"Success!\"}\n\tw.Header().Set(\"Content-type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(msg)\n\n\treturn\n}", "func (s LoginSession) Reply(r Replier, comment string) error {\n\treq := &request{\n\t\turl: \"https://www.reddit.com/api/comment\",\n\t\tvalues: &url.Values{\n\t\t\t\"thing_id\": {r.replyID()},\n\t\t\t\"text\": {comment},\n\t\t\t\"uh\": {s.modhash},\n\t\t},\n\t\tcookie: s.cookie,\n\t\tuseragent: s.useragent,\n\t}\n\n\tbody, err := req.getResponse()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !strings.Contains(body.String(), \"data\") {\n\t\treturn errors.New(\"failed to post comment\")\n\t}\n\n\treturn nil\n}", "func (bot *Bot) reply(target string, message string) {\n\telapsedTime := time.Since(bot.lastReplyTime)\n\tif elapsedTime < (2 * time.Second) {\n\t\ttime.Sleep((2 * time.Second) - elapsedTime)\n\t}\n\tbot.ircConn.Privmsg(target, message)\n\tbot.lastReplyTime = time.Now()\n}", "func (r *Request) Reply(text string) {\n\tr.robot.adapter.Reply(r.Message, text)\n}", "func (a *HipchatAdapter) Reply(res *Response, strings ...string) error {\n\tnewStrings := make([]string, len(strings))\n\tfor _, str := range strings {\n\t\tnewStrings = append(newStrings, res.UserID()+`: `+str)\n\t}\n\n\ta.Send(res, newStrings...)\n\n\treturn nil\n}", "func (b *Bot) ReplyMessage(text, user, channel string) {\n\tb.PostMessage(fmt.Sprintf(\"<@%s> %s\", user, text), channel)\n}", "func (bot *Bot) Reply(data *ReplyCallbackData) {\n\tif data.Target != \"\" {\n\t\tbot.reply(data.Target, data.Message)\n\t}\n}", "func (ds *Dispatcher) Reply(w http.ResponseWriter, msg interface{}) int {\r\n\tmsgBytes, err := json.MarshalIndent(msg, \"\", \" \")\r\n\tif err != nil {\r\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\r\n\t\treturn 0\r\n\t}\r\n\tw.Write(msgBytes)\r\n\treturn len(msgBytes)\r\n}", "func CreateReply(w http.ResponseWriter, r *http.Request) {\n\tsessionID := r.Header.Get(\"sessionID\")\n\tuser, err := getUserFromSession(sessionID)\n\n\tif err != nil {\n\t\tmsg := map[string]string{\"error\": \"Sorry there was an internal server error\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\tif !user.Active {\n\t\tmsg := map[string]string{\"error\": \"Sorry your account isn't activated yet\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\tparams := mux.Vars(r)\n\tcommentID := params[\"comment_id\"]\n\n\tif commentID == \"\" {\n\t\tmsg := map[string]string{\"error\": \"comment id required\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\tif r.Body == nil {\n\t\tmsg := map[string]string{\"error\": \"Sorry you need to supply an item id and a comment text\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\tvar reply comments.Reply\n\n\terr = json.NewDecoder(r.Body).Decode(&reply)\n\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tmsg := map[string]string{\"error\": \"Sorry there was an error\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\treply.CommentID = commentID\n\treply.Username = user.DisplayName\n\n\terr = reply.Create()\n\n\tif err != nil {\n\t\tmsg := map[string]string{\"error\": \"Sorry there was an error\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\tmsg := map[string]string{\"message\": \"Success!\"}\n\tw.Header().Set(\"Content-type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(msg)\n\n\treturn\n\n}", "func Reply(msg string) MessageHandler {\n\treturn func(bot *Bot, evt *slack.MessageEvent) error {\n\t\tbot.Reply(evt, msg)\n\t\treturn nil\n\t}\n}", "func addReply(c *client, obj *robj) {\n\t// todo\n\treturn\n}", "func (r *Request) Reply(reply Reply) {\n\tr.c <- reply\n}", "func Reply(r *render.Render, w http.ResponseWriter, message string, code int, data ...interface{}) {\n\tr.JSON(w, code, map[string]interface{}{\n\t\t\"message\": message,\n\t\t\"code\": code,\n\t\t\"data\": data,\n\t})\n}", "func (s *server) WriteReplyMessage(w io.Writer, xid uint32, acceptType AcceptType, ret interface{}) error {\n\tvar buf bytes.Buffer\n\n\t// Header\n\theader := Message{\n\t\tXid: xid,\n\t\tType: Reply,\n\t}\n\n\tif _, err := xdr.Marshal(&buf, header); err != nil {\n\t\treturn err\n\t}\n\n\t// \"Accepted\"\n\tif _, err := xdr.Marshal(&buf, ReplyBody{Type: Accepted}); err != nil {\n\t\treturn err\n\t}\n\n\t// \"Success\"\n\tif _, err := xdr.Marshal(&buf, AcceptedReply{Type: acceptType}); err != nil {\n\t\treturn err\n\t}\n\n\t// Return data\n\tif ret != nil {\n\t\tif _, err := xdr.Marshal(&buf, ret); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t_, err := w.Write(buf.Bytes())\n\treturn err\n}", "func (m *ChatMessage) GetReplyToId()(*string) {\n return m.replyToId\n}", "func (i *Input) ReplyTo() sarah.OutputDestination {\n\treturn i.channelID\n}", "func (o *PluginDnsClient) Reply(transactionId uint16, questions []layers.DNSQuestion, socket transport.SocketApi) error {\n\n\tif !o.IsNameServer() {\n\t\treturn fmt.Errorf(\"Only Name Servers can reply!\")\n\t}\n\n\tif socket == nil {\n\t\treturn fmt.Errorf(\"Invalid Socket in Reply!\")\n\t}\n\n\trespCode := layers.DNSResponseCodeNoErr // We start with no problems.\n\n\tanswers := []layers.DNSResourceRecord{}\n\tif len(questions) > 0 {\n\t\tanswers = o.BuildAnswers(questions)\n\t\tif len(answers) == 0 {\n\t\t\trespCode = layers.DNSResponseCodeNXDomain\n\t\t}\n\t} else {\n\t\trespCode = layers.DNSResponseCodeFormErr\n\t}\n\n\tdata := o.dnsPktBuilder.BuildResponsePkt(transactionId, answers, questions, respCode)\n\ttransportErr, _ := socket.Write(data)\n\tif transportErr != transport.SeOK {\n\t\to.stats.socketWriteError++\n\t\treturn transportErr.Error()\n\t}\n\n\to.stats.pktTxDnsResponse++ // Response sent\n\to.stats.txBytes += uint64(len(data))\n\n\ttransportErr = socket.Close() // Close socket after each response, because we don't keep a flow table.\n\tif transportErr != transport.SeOK {\n\t\to.stats.socketCloseError++\n\t\treturn transportErr.Error()\n\t}\n\treturn nil\n}", "func (_m *SlackClient) Reply(event slack.MessageEvent, text string) {\n\t_m.Called(event, text)\n}", "func (d *Deogracias) CommentReply(m *reddit.Message) error {\n\terr := d.bot.Reply(m.Name, d.getReplyQuote())\n\tif err != nil {\n\t\tlog.Println(errors.WithStack(errors.Errorf(\"failed to reply back: %v\", err)))\n\t}\n\treturn nil\n}", "func (e Endpoints) ReplyTo(ctx context.Context, parentId uint, todo io.Todo) (t io.Todo, error error) {\n\trequest := ReplyToRequest{\n\t\tParentId: parentId,\n\t\tTodo: todo,\n\t}\n\tresponse, err := e.ReplyToEndpoint(ctx, request)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn response.(ReplyToResponse).T, response.(ReplyToResponse).Error\n}", "func OnIdMessageHandler(h MessageHandlerArgs) {\n\tmsg := tgbotapi.NewMessage(\n\t\th.update.Message.Chat.ID, fmt.Sprintf(\"Id: %d\", h.update.Message.Chat.ID))\n\tmsg.ReplyToMessageID = h.update.Message.MessageID\n\t_, err := h.bot.Send(msg)\n\tif err != nil {\n\t\tlogger.Warnf(\"Couldn't send message without reply to message, %s\", err)\n\t}\n}", "func (c *Connection) reply(ctx context.Context) {\n\tdefer func() {\n\t\tc.logger.Infof(\"Replyer exiting for %s\", c.name)\n\t\tc.kill(ctx)\n\t\tc.wg.Done()\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase payload, ok := <-c.repCh:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tn, err := c.conn.Write(payload)\n\t\t\tif err != nil {\n\t\t\t\tc.logger.Infof(\n\t\t\t\t\t\"Client %s cannot write reply: %s\", c.name, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif en := len(payload); en != n {\n\t\t\t\tc.logger.Infof(\n\t\t\t\t\t\"Client %s cannot write reply: written %d instead of %d bytes\",\n\t\t\t\t\tc.name, n, en)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tatomic.AddInt64(&c.numInflight, -1) // one less in flight\n\t\t}\n\t}\n}", "func (m *MailYak) ReplyTo(addr string) {\n\tm.replyTo = m.trimRegex.ReplaceAllString(addr, \"\")\n}", "func (t *Transaction) Reply(r TransactionReply) {\n\tt.c <- r\n}", "func (clt *Client) Reply(r *MessageReply) {\n\tclt.coreOut <- r\n}", "func (f *Pub) Reply(v interface{}) {\n\tf.branches.Deliver(nil, v)\n}", "func (margelet *Margelet) QuickReply(chatID int64, messageID int, message string) (tgbotapi.Message, error) {\n\tmsg := tgbotapi.NewMessage(chatID, message)\n\tmsg.ReplyToMessageID = messageID\n\treturn margelet.bot.Send(msg)\n}", "func (d *Dao) RegReply(c context.Context, maid, adid int64, replyType string) (err error) {\n\tparams := url.Values{}\n\tparams.Set(\"adid\", strconv.FormatInt(adid, 10))\n\tparams.Set(\"mid\", strconv.FormatInt(_gameOfficial, 10))\n\tparams.Set(\"oid\", strconv.FormatInt(maid, 10))\n\tparams.Set(\"type\", replyType)\n\tparams.Set(\"state\", _replyState)\n\tvar res struct {\n\t\tCode int `json:\"code\"`\n\t}\n\tif err = d.replyClient.Post(c, _replyURL, \"\", params, &res); err != nil {\n\t\tlog.Error(\"d.replyClient.Post(%s) error(%v)\", _replyURL+\"?\"+params.Encode(), err)\n\t\treturn\n\t}\n\tif res.Code != ecode.OK.Code() {\n\t\tlog.Error(\"d.replyClient.Post(%s) error(%v)\", _replyURL+\"?\"+params.Encode(), err)\n\t\terr = ecode.Int(res.Code)\n\t}\n\treturn\n}", "func (*MessageReplyHeader) TypeID() uint32 {\n\treturn MessageReplyHeaderTypeID\n}", "func (c *Client) SendMessageReply(\n\tchannelID discord.ChannelID, content string,\n\treferenceID discord.MessageID, embeds ...discord.Embed) (*discord.Message, error) {\n\n\tdata := SendMessageData{\n\t\tContent: content,\n\t\tReference: &discord.MessageReference{MessageID: referenceID},\n\t\tEmbeds: embeds,\n\t}\n\n\treturn c.SendMessageComplex(channelID, data)\n}", "func (_m *DB) ReplyById(replyId string) (*model.Reply, error) {\n\tret := _m.Called(replyId)\n\n\tvar r0 *model.Reply\n\tif rf, ok := ret.Get(0).(func(string) *model.Reply); ok {\n\t\tr0 = rf(replyId)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*model.Reply)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(replyId)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (s *svcManager) SendReply(log log.T, update *UpdateDetail) (err error) {\n\tvar svc messageService.Service\n\tpayloadB := []byte{}\n\n\tvalue := prepareReplyPayload(s.context, update)\n\tif payloadB, err = json.Marshal(value); err != nil {\n\t\treturn fmt.Errorf(\"could not marshal reply payload %v\", err.Error())\n\t}\n\tif svc, err = getMsgSvc(s.context); err != nil {\n\t\treturn fmt.Errorf(\"could not load message service %v\", err.Error())\n\t}\n\n\tpayload := string(payloadB)\n\treturn svc.SendReply(log, update.MessageID, payload)\n}", "func (m *ItemMailFoldersItemMessagesMessageItemRequestBuilder) Reply()(*ItemMailFoldersItemMessagesItemReplyRequestBuilder) {\n return NewItemMailFoldersItemMessagesItemReplyRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (t *Request) Reply(key string, data interface{}) error {\n\tdataBytes, err := json.Marshal(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = t.service.Client.SubmitResult(context.Background(), &service.SubmitResultRequest{\n\t\tExecutionID: t.executionID,\n\t\tOutputKey: key,\n\t\tOutputData: string(dataBytes),\n\t})\n\treturn err\n}", "func (c *ChannelMessage) AddReply(reply *ChannelMessage) (*MessageReply, error) {\n\tif c.Id == 0 {\n\t\treturn nil, ErrChannelMessageIdIsNotSet\n\t}\n\tmr := NewMessageReply()\n\tmr.MessageId = c.Id\n\tmr.ReplyId = reply.Id\n\tmr.CreatedAt = reply.CreatedAt\n\tif err := mr.Create(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn mr, nil\n}", "func updateUserReply(replierUserID int, postUserID int, replierMessage string, posterMessage string) {\n\t//Begin getting Users\n\treplyUser, succ1 := getUserCaller(replierUserID)\n\tif succ1 == true {\n\t\tpostUser, succ2 := getUserCaller(postUserID)\n\t\tif succ2 == true {\n\t\t\t//Poster and replier found; compile messages and send them with go routines\n\t\t\ttheMessageSend := \"Hey \" + postUser.UserName + \", \" + replyUser.UserName + \" has responded to your comment: \" +\n\t\t\t\t\"\\n\" + \"You said:\\n\" + posterMessage + \"\\nThey said:\\n\" + replierMessage + \"\\n\"\n\t\t\twg.Add(1)\n\t\t\tgo sendText(theMessageSend, postUser.PhoneACode, postUser.PhoneNumber)\n\t\t\twg.Add(1)\n\t\t\tgo sendEmail(theMessageSend, postUser.Email, \"Reply to your Post\")\n\t\t\twg.Wait()\n\t\t} else {\n\t\t\t//Failed to get original poster. End function\n\t\t}\n\t} else {\n\t\t//Failed to get replyUser. End function\n\t}\n}", "func (req *Request) Reply(code ReplyCode) error {\n\treturn req.ReplyAddr(code, nil)\n}", "func (m Message) ReplyDocument(filepath string) {\n\tmessage := &ReplyMessage{}\n\tmsg := tgbotapi.NewDocumentUpload(m.Chat.ID, filepath)\n\tmessage.msg = msg\n\tm.replies <- message\n}", "func (cache *Cache) SendReply(conn *net.UDPConn, msg api.Message, addr net.Addr) (int, error) {\n\tif cache != nil && msg.Command() == api.RespOk {\n\t\tif entry, ok := cache.M[msg.UID()]; ok {\n\t\t\tentry.Reply = msg\n\t\t}\n\t}\n\treturn conn.WriteTo(msg.Bytes(), addr)\n}", "func SendReply(channelID string, reply string) {\n\tSession.ChannelMessageSend(channelID, reply)\n}", "func (d *Dao) TxReplyForUpdate(tx *xsql.Tx, oid, rpID int64) (r *model.Reply, err error) {\n\tr = new(model.Reply)\n\trow := tx.QueryRow(fmt.Sprintf(_txSelReplySQLForUpdate, hit(oid)), rpID)\n\tif err = row.Scan(&r.ID, &r.Oid, &r.Type, &r.Mid, &r.Root, &r.Parent, &r.Dialog, &r.Count, &r.RCount, &r.Like, &r.Hate, &r.Floor, &r.State, &r.Attr, &r.CTime, &r.MTime); err != nil {\n\t\tif err == xsql.ErrNoRows {\n\t\t\tr = nil\n\t\t\terr = nil\n\t\t}\n\t}\n\treturn\n}", "func (cook SendCookie) Reply() (*SendReply, error) {\n\tbuf, err := cook.Cookie.Reply()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif buf == nil {\n\t\treturn nil, nil\n\t}\n\treturn sendReply(buf), nil\n}", "func (c *Call) Reply(code int, reply interface{}) {\n\tif c.Done() {\n\t\treturn\n\t}\n\tc.code, c.reply = code, reply\n}", "func Reply(w http.ResponseWriter, code int, data interface{}) {\n\n\tmsg, err := json.Marshal(data)\n\tif err != nil {\n\t\tError(w, err)\n\t\treturn\n\t}\n\n\th := w.Header()\n\th.Set(\"Content-Length\", strconv.Itoa(len(msg)))\n\th.Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(code)\n\tw.Write(msg)\n}", "func (o *LicenseNotificationReply) GetReplyId() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.ReplyId\n}", "func (m Message) ReplyDefault() error {\n\treturn apiError(\"ssh_message_reply_default\",\n\t\tC.ssh_message_reply_default(m.msg))\n}", "func (m *MessageReplyHeader) SetReplyToPeerID(value PeerClass) {\n\tm.Flags.Set(0)\n\tm.ReplyToPeerID = value\n}", "func (m *MessageReplyHeader) SetReplyToPeerID(value PeerClass) {\n\tm.Flags.Set(0)\n\tm.ReplyToPeerID = value\n}", "func (s *Service) ReplyContent(c context.Context, oid, rpID int64, tp int8) (r *model.Reply, err error) {\n\tif r, err = s.dao.Mc.GetReply(c, rpID); err != nil {\n\t\tlog.Error(\"replyCacheDao.GetReply(%d, %d, %d) error(%v)\", oid, rpID, tp, err)\n\t}\n\tif r == nil {\n\t\tif r, err = s.dao.Reply.Get(c, oid, rpID); err != nil {\n\t\t\tlog.Error(\"s.reply.GetReply(%d, %d) error(%v)\", oid, rpID, err)\n\t\t\treturn nil, err\n\t\t}\n\t\tif r == nil {\n\t\t\treturn nil, ecode.ReplyNotExist\n\t\t}\n\t\tif r.Content, err = s.dao.Content.Get(c, oid, rpID); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err = s.dao.Mc.AddReply(c, r); err != nil {\n\t\t\tlog.Error(\"mc.AddReply(%d,%d,%d) error(%v)\", oid, rpID, tp, err)\n\t\t\terr = nil\n\t\t}\n\t}\n\tif r.Oid != oid || r.Type != tp {\n\t\tlog.Warn(\"reply dismatches with parameter, oid: %d, rpID: %d, tp: %d, actual: %d, %d, %d\", oid, rpID, tp, r.Oid, r.RpID, r.Type)\n\t\treturn nil, ecode.RequestErr\n\t}\n\treturn r, nil\n}", "func (pkt *SubReply) ID() int {\n\treturn PacketSubReply\n}", "func (c *customerio) ReplyTo(name, email string) Mailer {\n\tc.replyTo = address{Name: name, Email: email}\n\treturn c\n}", "func (c *client) ReplyImage(ctx context.Context, replyToken, originalContentURL, previewImageURL string) error {\n\tbot, err := c.fromContext(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\timageMessage := linebot.NewImageMessage(originalContentURL, previewImageURL)\n\tif _, err := bot.ReplyMessage(replyToken, imageMessage).Do(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (d *Dao) TxReply(tx *xsql.Tx, oid, rpID int64) (r *model.Reply, err error) {\n\tr = new(model.Reply)\n\trow := tx.QueryRow(fmt.Sprintf(_selReplySQL, hit(oid)), rpID)\n\tif err = row.Scan(&r.ID, &r.Oid, &r.Type, &r.Mid, &r.Root, &r.Parent, &r.Dialog, &r.Count, &r.RCount, &r.Like, &r.Hate, &r.Floor, &r.State, &r.Attr, &r.CTime, &r.MTime); err != nil {\n\t\tif err == xsql.ErrNoRows {\n\t\t\tr = nil\n\t\t\terr = nil\n\t\t}\n\t}\n\treturn\n}", "func (c *Client) SendEmbedReply(\n\tchannelID discord.ChannelID,\n\treferenceID discord.MessageID, embeds ...discord.Embed) (*discord.Message, error) {\n\n\treturn c.SendMessageComplex(channelID, SendMessageData{\n\t\tEmbeds: embeds,\n\t\tReference: &discord.MessageReference{MessageID: referenceID},\n\t})\n}", "func (m *Message) IsReply() bool {\n\treturn m.ReplyTo != nil\n}", "func ReplyCallback(data Reply) {\n\tcallbackURL := os.Getenv(\"REPLY_CALLBACK_URL\")\n\n\tif len(callbackURL) < 1 {\n\t\tlog.Infof(\"reply url is empty. message_id:%v\", data.MessageID)\n\t\treturn\n\t}\n\n\tpayload, _ := json.Marshal([]map[string]interface{}{\n\t\tmap[string]interface{}{\n\t\t\t\"message_id\": fmt.Sprintf(\"%v\", data.MessageID),\n\t\t\t\"content\": data.Content,\n\t\t\t\"mobile\": data.Mobile,\n\t\t\t\"ext_no\": data.ExtensionNO,\n\t\t\t\"received_at\": data.ReceivedAt,\n\t\t},\n\t})\n\n\tparams := url.Values{\n\t\t\"reply\": {string(payload)},\n\t}\n\n\tresp, err := http.PostForm(callbackURL, params)\n\tif err != nil {\n\t\tlog.Errorf(\"reply callback failed, url:%v, err:%v\", callbackURL, err)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\trespBody, _ := ioutil.ReadAll(resp.Body)\n\n\tlog.Infof(\"reply callback finished, url:%v, request:%v, response:%v, status code:%v, err:%v\", callbackURL, string(payload), string(respBody), resp.StatusCode, err)\n}", "func (s *raftServer) replyTo(to int, msg interface{}) {\n\treply := &cluster.Envelope{Pid: to, Msg: msg}\n\ts.server.Outbox() <- reply\n}", "func NewReply(name string, value int64) *commands.Message {\n\treturn &commands.Message{Msg: [](*commands.Data){&commands.Data{Name: name, Value: value}}}\n}", "func (r *Request) Reply(status int) *Response {\n\treturn r.Response.Status(status)\n}", "func (req *Request) Reply(status int, body string) {\n\tif req.replied {\n\t\treq.app.Log.Critical(\"this context has already been replied to!\")\n\t}\n\treq.status = status\n\treq.contentLength = len(body)\n\treq.SetHeader(\"Date\", httpDate(req.date))\n\tif req.contentLength > 0 {\n\t\treq.SetHeader(\"Content-Type\", req.contentType)\n\t\treq.SetHeader(\"Content-Length\", strconv.Itoa(req.contentLength))\n\t}\n\tif req.status >= 400 {\n\t\treq.SetHeader(\"Connection\", \"close\")\n\t}\n\tif req.session != nil {\n\t\tsval, err := req.session.marshal(req.app.SessionKey)\n\t\tif err != nil {\n\t\t\treq.app.Log.Error(\"failed to write session: %v\", err)\n\t\t} else if len(sval) > 0 {\n\t\t\thttp.SetCookie(req.w, &http.Cookie{\n\t\t\t\tName: req.app.SessionName,\n\t\t\t\tValue: sval,\n\t\t\t\tMaxAge: persistentCookieAge,\n\t\t\t\tHttpOnly: true,\n\t\t\t})\n\t\t}\n\t}\n\treq.replied = true\n\treq.w.WriteHeader(req.status)\n\tif req.r.Method != \"HEAD\" && req.contentLength > 0 {\n\t\treq.w.Write([]byte(body))\n\t}\n}", "func (d *Dao) RegReply(c context.Context, pid, mid int64) (err error) {\n\tparams := url.Values{}\n\tparams.Set(\"mid\", strconv.FormatInt(mid, 10))\n\tparams.Set(\"oid\", strconv.FormatInt(pid, 10))\n\tparams.Set(\"type\", _replyType)\n\tparams.Set(\"state\", _replyState)\n\tvar res struct {\n\t\tCode int `json:\"code\"`\n\t}\n\tif err = d.http.Post(c, _replyURL, \"\", params, &res); err != nil {\n\t\tPromError(\"reply:打开评论\", \"d.http.Post(%s) error(%v)\", _replyURL+\"?\"+params.Encode(), err)\n\t\treturn\n\t}\n\tif res.Code != ecode.OK.Code() {\n\t\tPromError(\"reply:打开评论状态码异常\", \"d.http.Post(%s) error(%v)\", _replyURL+\"?\"+params.Encode(), err)\n\t\terr = ecode.Int(res.Code)\n\t}\n\treturn\n}", "func (h *DNSHandler) WriteReplyMsg(w dns.ResponseWriter, message *dns.Msg) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlogger.Noticef(\"Recovered in WriteReplyMsg: %s\", r)\n\t\t}\n\t}()\n\n\terr := w.WriteMsg(message)\n\tif err != nil {\n\t\tlogger.Error(err.Error())\n\t}\n}", "func (c *Client) SendTextReply(\n\tchannelID discord.ChannelID,\n\tcontent string, referenceID discord.MessageID) (*discord.Message, error) {\n\n\treturn c.SendMessageComplex(channelID, SendMessageData{\n\t\tContent: content,\n\t\tReference: &discord.MessageReference{MessageID: referenceID},\n\t})\n}", "func (m Message) Replyf(reply string, values ...interface{}) {\n\tm.Reply(fmt.Sprintf(reply, values...))\n}", "func (d *Dao) InsertReply(c context.Context, r *model.Reply) (id int64, err error) {\n\tres, err := d.db.Exec(c, fmt.Sprintf(_inSQL, hit(r.Oid)), r.ID, r.Oid, r.Type, r.Mid, r.Root, r.Parent, r.Floor, r.State, r.Attr, r.CTime, r.MTime)\n\tif err != nil {\n\t\tlog.Error(\"mysqlDB.Exec error(%v)\", err)\n\t\treturn\n\t}\n\treturn res.LastInsertId()\n}", "func (b *Bot) MentionReply(m *irc.Message, format string, v ...interface{}) error {\n\tif len(m.Params) < 1 || len(m.Params[0]) < 1 {\n\t\treturn errors.New(\"Invalid IRC message\")\n\t}\n\n\ttarget := m.Prefix.Name\n\tprefix := \"\"\n\tif b.FromChannel(m) {\n\t\ttarget = m.Params[0]\n\t\tprefix = m.Prefix.Name + \": \"\n\t}\n\n\tfullMsg := fmt.Sprintf(format, v...)\n\tfor _, resp := range strings.Split(fullMsg, \"\\n\") {\n\t\tb.Send(&irc.Message{\n\t\t\tPrefix: &irc.Prefix{},\n\t\t\tCommand: \"PRIVMSG\",\n\t\t\tParams: []string{\n\t\t\t\ttarget,\n\t\t\t\tprefix + resp,\n\t\t\t},\n\t\t})\n\t}\n\n\treturn nil\n}", "func (h *handler) writeReply(r *Reply) error {\n\tmsg := r.String()\n\th.logSend(msg)\n\t_, err := h.conn.Write([]byte(msg + \"\\r\\n\"))\n\treturn err\n}", "func ReplyWith(w http.ResponseWriter, code int, bodyType string, msg []byte) {\n\n\th := w.Header()\n\th.Set(\"Content-Length\", strconv.Itoa(len(msg)))\n\th.Set(\"Content-Type\", bodyType)\n\tw.WriteHeader(code)\n\tw.Write(msg)\n}", "func (_m *WebSocketServer) SendReply(message interface{}) {\n\t_m.Called(message)\n}", "func createOneReply(dbConn *sql.DB, replyToStatusID int, newLayer *[]int, accountIDs *[]int, visibility int, mentionedAccounts []int) {\n\taccountID := (*accountIDs)[auxiliary.RandomNonnegativeIntWithUpperBound(len(*accountIDs))]\n\tresult := mtDataGen.ReplyToStatus(dbConn, accountID, auxiliary.RandStrSeq(50), replyToStatusID, 0, mentionedAccounts)\n\tif result != -1 {\n\t\tnewReply := fmt.Sprintf(\"Create a new reply to %d\", replyToStatusID)\n\t\tfmt.Println(newReply)\n\t\t*newLayer = append(*newLayer, result)\n\t}\n}", "func (m Message) ReplySticker(filepath string) {\n\tmessage := &ReplyMessage{}\n\tmsg := tgbotapi.NewStickerUpload(m.Chat.ID, filepath)\n\tmessage.msg = msg\n\tm.replies <- message\n}", "func (pkt *SubReply) IDString() string {\n\treturn \"SubReply\"\n}", "func (ctx Context) ReplyEmbed(embed *discordgo.MessageEmbed) *discordgo.Message {\n\tmsg, err := ctx.Discord.ChannelMessageSendEmbed(ctx.TextChannel.ID, embed)\n\tif err != nil {\n\t\tlogging.Log.Error(\"Unable to send embed: \" + err.Error())\n\t\treturn nil\n\t}\n\treturn msg\n}", "func (p *responseWriter) reply(resp *http.Response) error {\n\n\tpr, pw := io.Pipe()\n\n\tgo func() {\n\t\terr := resp.Write(pw)\n\t\tpw.CloseWithError(err)\n\t}()\n\n\treq, _ := http.NewRequest(\"POST\", p.baseUrl, pr)\n\treq.Header.Set(\"Content-Type\", \"application/octet-stream\")\n\treq.Header.Set(\"Reqid\", p.reqId)\n\n\tresp, err := http.DefaultClient.Do(req)\n\tif err == nil {\n\t\tresp.Body.Close()\n\t} else {\n\t\tlog.Warn(\"unidisvr: Reply failed -\", err)\n\t}\n\tpr.CloseWithError(err)\n\treturn err\n}", "func (b *GroupsSetLongPollSettingsBuilder) MessageReply(v bool) *GroupsSetLongPollSettingsBuilder {\n\tb.Params[\"message_reply\"] = v\n\treturn b\n}", "func (t *Thread) replies(DB *gorm.DB) { DB.Debug().Model(&t).Related(&t.Replies) }", "func receiveReply(conn *Conn, p *Packet) {\n\treply <- p.Msg\n}", "func SendReply(w http.ResponseWriter, rc int, s string) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tm := UResp{Status: s, ReplyCode: rc, Timestamp: time.Now().Format(time.RFC822)}\n\tstr, err := json.Marshal(m)\n\tif nil != err {\n\t\tfmt.Fprintf(w, \"{\\n\\\"Status\\\": \\\"%s\\\"\\n\\\"Timestamp:\\\": \\\"%s\\\"\\n}\\n\",\n\t\t\t\"encoding error\", time.Now().Format(time.RFC822))\n\t} else {\n\t\tfmt.Fprintf(w, string(str))\n\t}\n}", "func (c *Comment) addReply(child *Comment, db *sql.DB) int {\n\tr := db.QueryRow(`INSERT INTO hackernews.threads (ancestor, descendant, depth)\n\t\tSELECT ancestor, $1::integer, depth + 1 FROM hackernews.threads\n\t\tWHERE descendant = $2::integer\n\t\tRETURNING id, depth;`,\n\t\tchild.ID, c.ID)\n\tvar id int\n\tvar depth int\n\tif err := r.Scan(&id, &depth); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"created reply %d (%d)\\n\", depth, child.offset)\n\treturn id\n}", "func ReplyTo(r string) RequestOption {\n\treturn func(o *RequestOptions) {\n\t\to.ReplyTo = r\n\t\to.ProcessReplies = false\n\t}\n}" ]
[ "0.68520343", "0.67098725", "0.6647516", "0.6609711", "0.65935504", "0.6560979", "0.6560151", "0.63495713", "0.6307292", "0.6239647", "0.62376815", "0.61555016", "0.6143258", "0.61258835", "0.61255115", "0.6125274", "0.6124719", "0.61244994", "0.61131173", "0.6091362", "0.60753167", "0.605886", "0.6049322", "0.6024238", "0.6022819", "0.5998922", "0.59943813", "0.59895784", "0.59552795", "0.58387715", "0.5837476", "0.58303076", "0.57989556", "0.5779821", "0.57618326", "0.57559717", "0.5750027", "0.57390356", "0.5738436", "0.57312524", "0.5692768", "0.56860673", "0.5684421", "0.567541", "0.56573117", "0.5649744", "0.56156343", "0.5606151", "0.5579083", "0.5576881", "0.55718213", "0.5556778", "0.55490494", "0.5544977", "0.5539673", "0.5508058", "0.55011016", "0.5494341", "0.5488626", "0.5478659", "0.5415496", "0.54146135", "0.54141533", "0.5413919", "0.5407818", "0.5404242", "0.5391758", "0.5391758", "0.53859186", "0.53853315", "0.53771514", "0.5374358", "0.53706056", "0.53521734", "0.5332554", "0.5331855", "0.53260636", "0.5322358", "0.5314179", "0.5294549", "0.5274801", "0.5273919", "0.5272818", "0.52690274", "0.5252834", "0.52451235", "0.5235455", "0.5215373", "0.5205175", "0.52014035", "0.5192864", "0.51876926", "0.51807725", "0.5180129", "0.5169322", "0.515347", "0.51531065", "0.51527727", "0.514668", "0.5145774" ]
0.60834444
20
Use init to parse files only once Use must to fail in init
func init() { tpl = template.Must(template.ParseGlob("./*txt")) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p *parser) init(info *token.File, src []byte) {\n\tp.file = info\n\tp.scanner.Init(p.file, src, func(pos token.Position, msg string) {\n\t\tp.err = scanner.Error{Position: pos, Message: msg}\n\t})\n\tp.next()\n}", "func initializeFileParse(filePaths []string, packageName string) ([]*res.PathInfo, *rdpb.Resources, error) {\n\trscs := &rdpb.Resources{\n\t\tPkg: packageName,\n\t}\n\n\tpifs, err := res.MakePathInfos(filePaths)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn pifs, rscs, nil\n}", "func (p *FileMap) init(skipPath string, excludedExt []string) {\n\tp.files = make(map[string]string)\n\tp.skipPath = skipPath\n\tp.excludedExt = excludedExt\n}", "func init() {\n\tloadConfigFile()\n\tSetLogLevel()\n}", "func (c *configData) init() {\n\tconst filename = \".workflow.yml\"\n\n\tc.Global = viper.New()\n\tc.Local = viper.New()\n\n\t// c.Local.SetConfigFile(\n\t// \tpath.Join(git.RootDir(), filename),\n\t// )\n\n\tc.Global.SetConfigFile(\n\t\tpath.Join(currentUser.HomeDir, filename),\n\t)\n\n\t// TODO: configs := []*viper.Viper{c.Local, c.Global}\n\tconfigs := []*viper.Viper{c.Global}\n\tfor _, v := range configs {\n\t\t_, _ = file.Touch(v.ConfigFileUsed())\n\t\tfailIfError(v.ReadInConfig())\n\t}\n\n\tfailIfError(c.validate())\n\tfailIfError(c.update())\n\tc.initJira()\n}", "func (l *Loader) init() {\n\tif l.loading == nil {\n\t\tl.loading = stringset.New(1)\n\t\tl.sources = make(map[string]string, 1)\n\t\tl.symbols = make(map[string]*Struct, 1)\n\t}\n}", "func (x *FileExtractor) init() {\n\thead := x.aws.GetHeadObject(x.ctx, x.bucket, x.key)\n\tx.size = *head.ContentLength\n\tx.fileMap = make(map[string][]*File)\n}", "func init() {\n\tflag.Parse()\n\n\tif *dataFileFlag != \"\" {\n\t\tdir, err := ioutil.ReadDir(*dataFileFlag)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tfor _, dataFile := range dir {\n\t\t\tdataFileName := dataFile.Name()\n\t\t\tfi, err := os.Open(path.Join(*dataFileFlag, dataFileName))\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tbuf := make([]byte, 1024)\n\t\t\tn, err := fi.Read(buf)\n\t\t\tMessageData[dataFileName] = buf[0:n]\n\t\t\tif err != nil && err != io.EOF {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\t_ = fi.Close()\n\t\t}\n\t}\n\n\t// Increase file descriptor limit\n\trlimit := syscall.Rlimit{Max: uint64(FileDescLimit), Cur: uint64(FileDescLimit)}\n\tif err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rlimit); err != nil {\n\t\t_, _ = fmt.Fprintf(os.Stderr, \"[error] cannot set rlimit: %s\", err)\n\t}\n}", "func init() {\n\tfor _, path := range AssetNames() {\n\t\tbytes, err := Asset(path)\n\t\tif err != nil {\n\t\t\tlog.Panicf(\"Unable to parse: path=%s, err=%s\", path, err)\n\t\t}\n\t\ttemplates.New(path).Parse(string(bytes))\n\t}\n}", "func init() {\n\tfor _, path := range AssetNames() {\n\t\tbytes, err := Asset(path)\n\t\tif err != nil {\n\t\t\tlog.Panicf(\"Unable to parse: path=%s, err=%s\", path, err)\n\t\t}\n\t\ttemplates.New(path).Parse(string(bytes))\n\t}\n}", "func init() {\n\tflag.Parse()\n}", "func init() {\n\tflag.Parse()\n}", "func init() {\n\tvar _ = remototypes.File{}\n\tvar _ = strconv.Itoa(0)\n\tvar _ = ioutil.Discard\n}", "func init() {\n\tflag.Parse()\n\n\tConfigBytes, err := ioutil.ReadFile(*ConfigFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = json.Unmarshal(ConfigBytes, &Config)\n\tif err != nil {\n\t\tpanic(err)\n\t\t// TODO: add line numbers to log so i can use log.fatal\n\t\t// https://golang.org/pkg/log/#pkg-examples\n\t\t// logger := log.New(os.Stderr, \"OH NO AN ERROR\", log.Llongfile)\n\t}\n\n\tProducts, err = search.New(Config.Search)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (c *Config) init() {\n\tif err := mkdir(c.Dir); err != nil {\n\t\tpanic(fmt.Sprintf(\"Failed to initialize dir: %s\", c.Dir))\n\t}\n\n\tif err := touchFile(c.ConfigPath()); err != nil {\n\t\tpanic(fmt.Sprintf(\"Failed to touch file: %s\", c.ConfigPath()))\n\t}\n\n\tif err := touchFile(c.DataPath()); err != nil {\n\t\tpanic(fmt.Sprintf(\"Failed to touch file: %s\", c.DataPath()))\n\t}\n}", "func (m *Manager) InitByFiles() error {\n\tkconf.Log.Debugf(\"init service manager\")\n\tfiles, err := ioutil.ReadDir(m.etcDir)\n\tif nil != err {\n\t\treturn err\n\t}\n\t// Parse schemas in batch. So we have 2 loops. First loop to collect files and the second to save the result.\n\tfor _, file := range files {\n\t\tbaseName := filepath.Base(file.Name())\n\t\tif filepath.Ext(baseName) == \".json\" {\n\t\t\terr := m.initFile(baseName)\n\t\t\tif err != nil {\n\t\t\t\tkconf.Log.Errorf(\"%v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\tm.loaded = true\n\treturn nil\n}", "func init() {\n\t// var err error\n\t// tmpl, err = template.ParseFiles(\"templates/hello.gohtml\")\n\t// if err != nil {\n\t// \tpanic(err)\n\t// }\n\ttmpl = template.Must(template.ParseGlob(\"templates/*.gohtml\"))\n\n}", "func (d *PartialDriver) Init(fsys fs.FS, path string) error {\n\tentries, err := fs.ReadDir(fsys, path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms := source.NewMigrations()\n\tfor _, e := range entries {\n\t\tif e.IsDir() {\n\t\t\tcontinue\n\t\t}\n\t\tm, err := source.DefaultParse(e.Name())\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tfile, err := e.Info()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !ms.Append(m) {\n\t\t\treturn source.ErrDuplicateMigration{\n\t\t\t\tMigration: *m,\n\t\t\t\tFileInfo: file,\n\t\t\t}\n\t\t}\n\t}\n\n\td.fsys = fsys\n\td.path = path\n\td.migrations = ms\n\treturn nil\n}", "func (decoder *BinFileDecoder) init() error {\n\t// open binary log\n\tif decoder.BinFile == nil {\n\t\tbinFile, err := os.Open(decoder.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdecoder.BinFile = binFile\n\t\tdecoder.buf = bufio.NewReader(decoder.BinFile)\n\t}\n\n\t// binary log header validate\n\theader := make([]byte, 4)\n\tif _, err := decoder.BinFile.Read(header); err != nil {\n\t\treturn err\n\t}\n\n\tif !bytes.Equal(header, binFileHeader) {\n\t\treturn fmt.Errorf(\"invalid binary log header {%x}\", header)\n\t}\n\n\tdecoder.BinaryLogInfo = &BinaryLogInfo{tableInfo: make(map[uint64]*BinTableMapEvent)}\n\treturn nil\n}", "func init() {\n\tflag.StringVar(&configFile, \"config\", \"config.toml\", \"config file name\")\n\n\tflag.Parse()\n}", "func init() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\":: \")\n\n\tif XDG_CONFIG_HOME == \"\" {\n\t\tXDG_CONFIG_HOME = filepath.Join(os.Getenv(\"HOME\"), \".config\")\n\t}\n\n\tif XDG_DATA_DIRS == \"\" {\n\t\tXDG_DATA_DIRS = \"/usr/local/share/:/usr/share\"\n\t}\n\n\tcache.actions = make(map[string]string)\n\tcache.actionFiles = make(map[string]string)\n\tcache.scriptFiles = make(map[string]string)\n\n\tconfig = os.Getenv(\"DEMLORC\")\n\tif config == \"\" {\n\t\tconfig = filepath.Join(XDG_CONFIG_HOME, application, application+\"rc\")\n\t}\n}", "func init() {\n\tconfigFile = flag.String(FILE, EMPTY_STRING, A_STRING)\n}", "func init() {\n\tinitconf(configLocation)\n}", "func init() {\n\tvar perms = map[string]os.FileMode{\n\t\t\"config.toml\": 0600,\n\t\t\"config_api_key_missing.toml\": 0600,\n\t\t\"config_api_url_missing.toml\": 0600,\n\t\t\"config_wrong_permissions.toml\": 0666,\n\t}\n\tfor fileName, mode := range perms {\n\t\terr := os.Chmod(filepath.Join(configTestFixturesDir, fileName), mode)\n\t\tif err != nil {\n\t\t\t// TODO(xor-xor): Wire up logger here.\n\t\t\tfmt.Printf(\"err: %s\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}", "func init(){\n\ttemp, _ := ioutil.ReadFile(\"templates/file2.htemplate\")\n\tfile1 = string(temp)\n}", "func init() {\n\tconfigFile, err := os.Open(\"settings/config.json\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tbyteValue, _ := ioutil.ReadAll(configFile)\n\n\terr = json.Unmarshal(byteValue, &Config)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer configFile.Close()\n}", "func (p *scopeParser) init() {\n\tp.currentScope = nil\n\tp.fileScope = &FileScope{\n\t\tVariableMap: make(map[*tree.Token]*Variable, 4),\n\t\tScopeMap: make(map[tree.Node]*Scope, 4),\n\t}\n}", "func (d *Dirs) Init(name string) {\n\n\tsetFilePath(name)\n\tpairs, err := ioutil.ReadFile(PathToFile)\n\n\tif err != nil {\n\t\t*d = make(map[string]string)\n\t\terr = ioutil.WriteFile(PathToFile, []byte(\"{}\"), 0611)\n\t\tutils.HandleErr(err, \"create a new empty json file\")\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(pairs, &d)\n\tutils.HandleErr(err, \"parse json\")\n}", "func init() {\n\n\t// 添加多核支持,适合当前 CPU 计算密集的场景。\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\n\tkingpin.Version(version)\n\tkingpin.Parse()\n\n\t// init ignore dir and file list.\n\tignoreFileList = make([]string, 0)\n\tignoreDirList = make([]string, 0)\n\n\tif len(*igFile) != 0 {\n\t\tfor _, v := range strings.Split(*igFile, \",\") {\n\t\t\tignoreFileList = append(ignoreFileList, v)\n\t\t}\n\t\tfmt.Println(\"ignoreFileList =>\", ignoreFileList)\n\t}\n\tif len(*igDir) != 0 {\n\t\tfor _, v := range strings.Split(*igDir, \",\") {\n\t\t\tignoreDirList = append(ignoreDirList, v)\n\t\t}\n\t\tfmt.Println(\"ignoreDirList =>\", ignoreDirList)\n\t}\n\n}", "func init() {\n\tlanguageFile, err := os.Open(\"settings/languages/\" + Config.General.Language + \".json\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tbyteValue, _ := ioutil.ReadAll(languageFile)\n\n\terr = json.Unmarshal(byteValue, &Language)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer languageFile.Close()\n}", "func init() {\n\t_, filename, _, _ := runtime.Caller(0)\n\tdir := path.Join(path.Dir(filename), \"..\")\n\terr := os.Chdir(dir)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func init() {\n\t_, filename, _, _ := runtime.Caller(0)\n\tdir := path.Join(path.Dir(filename), \"..\")\n\terr := os.Chdir(dir)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func init() {\n\tconffyle := os.Args[1]\n\tfic, ficerr := ioutil.ReadFile(conffyle)\n\tif ficerr != nil {\n\t\tfmt.Printf(\"error ioutil : %v \\n\", ficerr)\n\t}\n\t_ = json.Unmarshal([]byte(fic), &Conf)\n\tswitcherfyle := Conf.Switcherconf\n\tfichier, _ := ioutil.ReadFile(switcherfyle)\n\t_ = json.Unmarshal([]byte(fichier), &switchList)\n\tfmt.Printf(\"Init summary\\n=================\\n\")\n\tfmt.Printf(\"Received parameter:%v\\n\", conffyle)\n\tfmt.Printf(\"Param file title :%v\\n\", string(fic))\n\tfmt.Printf(\"Switch config file :%v\\n\", switcherfyle)\n\tfmt.Printf(\"Switch file content:%v\\n\", string(fichier))\n}", "func init() {\r\n\ttpl = template.Must(template.ParseGlob(\"templates/*\"))\r\n}", "func init() {\n\tinitTokens()\n\tvar err error\n\tLexer, err = initLexer()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func init() {\n\t_, filename, _, _ := runtime.Caller(0)\n\tdir := path.Join(path.Dir(filename), \"../..\")\n\terr := os.Chdir(dir)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func init() {\n\tsetup.PathName, _ = os.Getwd()\n}", "func init() {\n if !util.FileExists(dlog.VarDir) {\n panic(\"must run on top dir\")\n }\n}", "func Init(d int) {\n\tcountByDay = loadCountFile()\n\tlog.Info(fmt.Sprintf(\"Processing files until %d days ago\", d))\n\tprocessCDRfiles(d)\n\tlog.Info(\"Creating result file\")\n\ttoCountToFile()\n\n\tcreateResultFile()\n\tif len(filesProcessed) > 0 {\n\t\t//Backup Process\n\t\tif config.Conf.Process.Backup {\n\t\t\tcompressAllFiles()\n\t\t\tcopyFilesToBackup()\n\t\t\tremoveFiles()\n\t\t}\n\n\t\tnotifyResult()\n\t} else {\n\t\tnotifyTeam(\"<b> No files loaded! <b>\")\n\t}\n}", "func init() {\n\tprepareOptionsFromCommandline(&configFromInit)\n\tparseConfigFromEnvironment(&configFromInit)\n}", "func (dc *diskCache) init() error {\n\tfiles, err := ioutil.ReadDir(dc.dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnow := time.Now().Unix()\n\tfor _, file := range files {\n\t\tfileName := dc.fileName(file.Name())\n\t\tif file.IsDir() {\n\t\t\tcontinue\n\t\t}\n\n\t\tfi, err := GetFileTime(fileName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnode := &lru.Node{\n\t\t\tKey: file.Name(),\n\t\t\tLength: file.Size(),\n\t\t\tAccessTime: fi.AccessTime / 1e9,\n\t\t}\n\t\tif dc.lru.TTL > 0 {\n\t\t\tif fi.AccessTime/1e9+dc.lru.TTL <= time.Now().Unix() {\n\t\t\t\tos.Remove(dc.dir + file.Name())\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tnode.SetExpire(now + dc.lru.TTL)\n\t\t\t}\n\t\t}\n\n\t\tdc.lru.Add(node)\n\t\tdc.m[node.Key] = node\n\t}\n\treturn nil\n}", "func initialize() {\n\treadCommandLine()\n\n\tif *dbFlag == \"\" {\n\t\tinstallEmptyConfiguration()\n\t} else {\n\t\tlogMessage(\"Trying to load configuration from %s\", *dbFlag)\n\t\tfile, err := openFile(*dbFlag)\n\t\tif err != nil {\n\t\t\tinstallEmptyConfiguration()\n\t\t} else {\n\t\t\tputConfiguration(readFully(file))\n\t\t}\n\t}\n\n}", "func init() {\n\tcurrentDir, _ = pathhelper.GetCurrentExecDir()\n\tconfigFile = path.Join(currentDir, \"config.json\")\n}", "func init() {\n\tvar fnm string\n\n\t//This is the way to initialize a struct.\n\tConf = Config{}\n\n\t//Pass the variable as a pointer.\n\treadFlags(&fnm)\n\t\n\t//Call the function defined in config.\n\tConf.SetFileName(fnm)\n}", "func init() {\n\tbSalt, err := ioutil.ReadFile(\"./.salt\")\n\tif err != nil {\n\t\tinitErr = err\n\t\treturn\n\t}\n\tsalt = strings.TrimSpace(string(bSalt))\n}", "func init() {\n\ttmpl = template.Must(template.ParseGlob(\"templates/*\"))\n}", "func initTSFile(filepath string) {\n\tif _, err := os.Stat(filepath); os.IsNotExist(err) {\n\t\ttimestamps := []int{}\n\t\twriteTSToFile(filepath, timestamps)\n\t}\n}", "func init() {\n\tfile, err := ioutil.ReadFile(\"./token.json\")\n\tif err != nil {\n\t\tlog.Fatal(\"File doesn't exist\")\n\t}\n\tif err := json.Unmarshal(file, &BotKey); err != nil {\n\t\tlog.Fatal(\"Cannot parse token.json\")\n\t}\n}", "func (t *Torrent) Init() {\n\t// Initialize Length to total length of files when in Multiple File mode\n\tif len(t.metaInfo.Info.Files) > 0 {\n\t\tt.metaInfo.Info.Length = 0\n\t\tfor _, file := range t.metaInfo.Info.Files {\n\t\t\tt.metaInfo.Info.Length += file.Length\n\t\t}\n\t}\n\n\tnumFiles := 0\n\tif len(t.metaInfo.Info.Files) > 0 {\n\t\t// Multiple File Mode\n\t\tfor i := 0; i < len(t.metaInfo.Info.Files); i++ {\n\t\t\tnumFiles += 1\n\t\t}\n\t} else {\n\t\t// Single File Mode\n\t\tnumFiles = 1\n\t}\n\n\tlog.Printf(\"Torrent : Run : The torrent contains %d file(s), which are split across %d pieces\", numFiles, (len(t.metaInfo.Info.Pieces) / 20))\n\tlog.Printf(\"Torrent : Run : The total length of all file(s) is %d\", t.metaInfo.Info.Length)\n}", "func init() {\n\tflag.Parse()\n\n\tFormatter := new(log.TextFormatter)\n\tFormatter.TimestampFormat = time.RFC3339\n\tFormatter.FullTimestamp = true\n\tlog.SetFormatter(Formatter)\n\tif *debug {\n\t\tlog.SetLevel(log.DebugLevel)\n\t}\n\n\tlog.Infof(\"pooling option [%v]\", *poolingOption)\n\n\tf, err := os.Open(*cfgFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"init | os.Open [%s]\", err)\n\t}\n\n\tdecoder := yaml.NewDecoder(f)\n\terr = decoder.Decode(&cfg)\n\tif err != nil {\n\t\tlog.Fatalf(\"init | decoder.Decode [%s]\", err)\n\t}\n\n\tif *poolingOption != \"restore\" {\n\t\tif _, err := os.Stat(cfg.Root.Plain); os.IsNotExist(err) {\n\t\t\tlog.Fatalf(\"%s missing\", cfg.Root.Plain)\n\t\t}\n\n\t\tif _, err := os.Stat(cfg.Root.Encrypted); os.IsNotExist(err) {\n\t\t\terr = os.Mkdir(cfg.Root.Encrypted, 0755)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"init | os.Mkdir [%s]\", err)\n\t\t\t}\n\t\t}\n\t}\n}", "func init() {\n\ttpl = template.Must(template.ParseGlob(\"templates/*\"))\n}", "func init() {\n\tparser.SharedParser().RegisterFabric(UpdateFabric{})\n}", "func (s *Scanner) Init() error {\n\tfmt.Println(\"Loading Yara rules...\")\n\tif s.rulesPath != \"\" {\n\t\tif _, err := os.Stat(s.rulesPath); os.IsNotExist(err) {\n\t\t\treturn errors.New(\"The specified rules path does not exist\")\n\t\t}\n\t\treturn s.Compile()\n\t}\n\n\treturn nil\n}", "func init() {\n\tflag.DurationVar(&config.fetchTimeout, \"timeout\", 2*time.Second, \"timeout between downloading papers\")\n\tflag.StringVar(&config.conferencesFile, \"config\", \"conferences.json\", \"JSON file listing conferences\")\n\tflag.StringVar(&config.outputDirectory, \"output-dir\", \"papers\", \"output directory for storing papers\")\n\tflag.Parse()\n\n\t// create output directory\n\tif _, err := os.Stat(config.outputDirectory); os.IsNotExist(err) {\n\t\tif err := os.MkdirAll(config.outputDirectory, os.ModePerm); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n}", "func Initialize(basePath string) error {\n log(dtalog.DBG, \"Initialize(%q) called\", basePath)\n dir, err := os.Open(basePath)\n if err != nil {\n log(dtalog.ERR, \"Initialize(%q): error opening directory for read: %s\",\n basePath, err)\n return err\n }\n \n filez, err := dir.Readdirnames(0)\n if err != nil {\n log(dtalog.ERR, \"Initialize(%q): error reading from directory: %s\",\n basePath, err)\n dir.Close()\n return err\n }\n dir.Close()\n \n Paths = make([]string, 0, len(filez))\n Limbo = make(map[string]*string)\n \n for _, fname := range filez {\n pth := filepath.Join(basePath, fname)\n f, err := os.Open(pth)\n if err != nil {\n log(dtalog.WRN, \"Initialize(): error opening file %q: %s\", pth, err)\n continue\n }\n defer f.Close()\n log(dtalog.DBG, \"Initialize(): reading file %q\", pth)\n \n Paths = append(Paths, pth)\n cur_ptr := &(Paths[len(Paths)-1])\n \n dcdr := json.NewDecoder(f)\n var raw interface{}\n var raw_slice []interface{}\n var i ref.Interface\n var idx string\n for dcdr.More() {\n err = dcdr.Decode(&raw)\n if err != nil {\n log(dtalog.WRN, \"Initialize(): error decoding from file %q: %s\",\n pth, err)\n continue\n }\n raw_slice = raw.([]interface{})\n if len(raw_slice) < 2 {\n log(dtalog.WRN, \"Initialize(): in file %q: slice too short: %q\",\n pth, raw_slice)\n continue\n }\n \n idx = raw_slice[0].(string)\n i = ref.Deref(idx)\n if i == nil {\n Limbo[idx] = cur_ptr\n } else {\n i.(Interface).SetDescPage(cur_ptr)\n }\n }\n }\n return nil\n}", "func (r *objReader) init(f io.ReadSeeker, p *Package) {\n\tr.f = f\n\tr.p = p\n\tr.offset, _ = f.Seek(0, 1)\n\tr.limit, _ = f.Seek(0, 2)\n\tf.Seek(r.offset, 0)\n\tr.b = bufio.NewReader(f)\n\tr.pkgprefix = importPathToPrefix(p.ImportPath) + \".\"\n}", "func init() {\n\tglobals.Tpl = template.Must(template.ParseGlob(\"templates/*.gohtml\"))\n\t// Load env variables\n\tgotenv.Load()\n}", "func init() {\n\ttopLevelTemplates = template.Must(template.ParseGlob(\"./views/*.go.html\"))\n\tpageTemplates = template.Must(template.ParseGlob(\"./views/pages/*.go.html\"))\n}", "func initFileWatcher(configFilePath string) {\n\tvar err error\n\twatcher, err = fsnotify.NewWatcher()\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Unable To Setup Logging Config File Watcher: %v\", err))\n\t}\n\tstartWatchListener(configFilePath)\n}", "func init() {\n\thome = os.Getenv(\"HOME\")\n\tXDGHome = os.Getenv(\"XDG_CONFIG_HOME\")\n\tconfPath = path.Join(\"/etc\", programName, confName)\n\tos.Clearenv()\n\t// TODO Clean up test files\n}", "func (node *Node) init() {\n\n\t//step0. parse config\n\n\tif err := node.parseConfig(node.configFile); err != nil {\n\t\t//temp code\n\t\tlog.Panicf(\"Parse Config Error: %s\", err.Error())\n\t\treturn\n\t}\n\n\t//step1. init process runtime and update node state to NodeStateInit\n\n\t//step2. try to connecting other nodes and store the connection to internalConns\n\n\t//init finnal. update node state to NodeStateNormal\n\n}", "func init() {\n\t//allocate memory to maps\n\tusermap = make(map[string]UserData)\n\tstopwords = make(map[string]struct{})\n\tSubCommentMap = make(map[string]SubsCommentData)\n\tusagecmmts = make(map[string](map[string]SubsWordData))\n\tusagesubmstitle = make(map[string](map[string]SubsWordData))\n\tusagesubmsbody = make(map[string](map[string]SubsWordData))\n\n\t//load secret file\n\tconfigdata, err := os.Open(\"C:\\\\Users\\\\Myke\\\\Dropbox\\\\School\\\\CSCI164\\\\Project\\\\config.secret\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t//close file when program is done\n\tdefer configdata.Close()\n\n\t//load config file from json to config struct\n\tscanner := bufio.NewScanner(configdata)\n\tfor scanner.Scan() {\n\t\terr = json.Unmarshal(scanner.Bytes(), &config)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t}\n\n\t//load stopwords\n\tstopdata, err := os.Open(\"C:\\\\Users\\\\Myke\\\\Dropbox\\\\School\\\\CSCI164\\\\Project\\\\stopwords\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t//place stop words into a map\n\tscanner = bufio.NewScanner(stopdata)\n\tfor scanner.Scan() {\n\t\tvar z struct{}\n\t\tstopwords[scanner.Text()] = z\n\t}\n\n\t//close file when program is done\n\tdefer stopdata.Close()\n\n}", "func init() {\n\t//todo...\n}", "func (idx *Unique) Init() error {\n\tif _, err := os.Stat(idx.filesDir); err != nil {\n\t\treturn err\n\t}\n\n\tif err := os.MkdirAll(idx.indexRootDir, 0777); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Init() {\n\tinitOnce.Do(func() {\n\t\tflag.Var(&resourceFiles, \"res_files\", \"Resource files and asset directories to parse.\")\n\t\tflag.StringVar(&rPbOutput, \"out\", \"\", \"Path to the output proto file.\")\n\t\tflag.StringVar(&pkg, \"pkg\", \"\", \"Java package name.\")\n\t})\n}", "func initialiseFileMagic() {\n\tfor file := 1; file < 9; file++ {\n\t\tfor rank := 1; rank < 9; rank++ {\n\t\t\tFileMagic[Index[file][rank]] = FileMagicMask[file-1]\n\t\t}\n\t}\n}", "func (*FileSystemBase) Init() {\n}", "func __initialize() error {\n\n\tif nil != __file {\n\t\treturn fmt.Errorf(\"Initialize can not be called twice\")\n\t}\n\n\tf, err := os.OpenFile(\"list.csv\", os.O_RDWR|os.O_CREATE, 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t__file = f\n\n\tr := csv.NewReader(__file)\n\tt, err := r.ReadAll()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t__tasks = t\n\n\treturn nil\n}", "func initAll()", "func init() {\n\tvar err_db error\n\tfile, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)\n\tif err != nil {\n\t\tlog.Fatalln(\"Fallo al abrir el archivo de error:\", err)\n\t}\n\tInfo = log.New(os.Stdout, \"INFO: \", log.Ldate|log.Ltime|log.Lshortfile)\n\tWarning = log.New(os.Stdout, \"WARNING: \", log.Ldate|log.Ltime|log.Lshortfile)\n\tError = log.New(io.MultiWriter(file, os.Stderr), \"ERROR :\", log.Ldate|log.Ltime|log.Lshortfile)\n\tdb, err_db = sql.Open(\"sqlite3\", sql_file)\n\tif err_db != nil {\n\t\tError.Println(err_db)\n\t\tlog.Fatalln(\"Fallo al abrir el archivo de error:\", err_db)\n\t}\n\tdb.Exec(\"PRAGMA journal_mode=WAL;\")\n\tlibs.LoadSettingsLin(port_external_file, port) // Se carga el puerto del fichero portext.reg\n}", "func Initialize() {\n\tpath, _ := os.Getwd()\n\tcPath := C.CString(path)\n\tdefer C.free(unsafe.Pointer(cPath))\n\tC.MagickCoreGenesis(cPath, C.MagickFalse)\n\timg.RegisterDecodeHandler(decodeCommonFile)\n}", "func init() {\r\n\tlog.SetFlags(log.Lshortfile)\r\n}", "func (idx *Indexing) initFilesInfo() {\n\n\tfor _, file := range idx.Files {\n\t\t// Get previous file data\n\t\tprevFileData := idx.Repo.getFileInfoAsObj(file.fileUniqueKey)\n\t\tif (File{}) != prevFileData {\n\t\t\tif prevFileData.fileHash != file.fileHash && prevFileData.fileSize != file.fileSize {\n\t\t\t\tidx.Repo.deleteFileInfo(file.fileUniqueKey)\n\t\t\t\tidx.Repo.insIntoMainInfoFileTable(file)\n\t\t\t\tidx.trueIndexing(file)\n\t\t\t}\n\t\t} else {\n\t\t\tidx.Repo.insIntoMainInfoFileTable(file)\n\t\t\tidx.trueIndexing(file)\n\t\t}\n\t}\n}", "func (s *Streamer) init() error {\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.fsNotify = watcher // we closed it during Stop() process\n\n\ts.changedFileNames = make(chan string, 1000) // we closed it during Stop() process\n\n\treturn nil\n}", "func main_init()", "func init() {\n\t// set reasonable defaults\n\tsetDefaults()\n\n\t// override defaults with configuration read from configuration file\n\tviper.AddConfigPath(\"$GOPATH/src/github.com/xlab-si/emmy/config\")\n\terr := loadConfig(\"defaults\", \"yml\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func (c *PruneCommand) Init(args []string) error {\n\treturn c.fs.Parse(args)\n}", "func InitRuntimeFiles() {\n\tadd := func(fileType, dir, pattern string) {\n\t\tAddRuntimeFilesFromDirectory(fileType, filepath.Join(configDir, dir), pattern)\n\t}\n\n\tadd(RTColorscheme, \"colorschemes\", \"*.micro\")\n\tadd(RTSyntax, \"syntax\", \"*.yaml\")\n\tadd(RTHelp, \"help\", \"*.md\")\n\n\t// Search configDir for plugin-scripts\n\tfiles, _ := ioutil.ReadDir(filepath.Join(configDir, \"plugins\"))\n\tfor _, f := range files {\n\t\trealpath, _ := filepath.EvalSymlinks(filepath.Join(configDir, \"plugins\", f.Name()))\n\t\trealpathStat, _ := os.Stat(realpath)\n\t\tif realpathStat.IsDir() {\n\t\t\tscriptPath := filepath.Join(configDir, \"plugins\", f.Name(), f.Name()+\".lua\")\n\t\t\tif _, err := os.Stat(scriptPath); err == nil {\n\t\t\t\tAddRuntimeFile(RTPlugin, realFile(scriptPath))\n\t\t\t}\n\t\t}\n\t}\n\n}", "func init() {\n\terr := os.MkdirAll(util.DIR, 0755)\n\tif err != nil {\n\t\tprintln(err.Error())\n\t\tos.Exit(1)\n\t}\n}", "func init() {\n\tinitCfgDir()\n\tinitCreds()\n}", "func init() {\n\tapp.Parse(os.Args[1:])\n\tif *logging {\n\t\tf, err := os.Create(*logFile)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tlog.SetFlags(0)\n\t\tlog.SetOutput(f)\n\t} else {\n\t\tdis := ioutil.Discard\n\t\tlog.SetOutput(dis)\n\t}\n\tfmt.Println(\"Game starting\\nPoolsize :\\t\", *poolSize)\n\tfmt.Println(\"Generations :\\t\", *generations)\n\tfmt.Println(\"neuronsPL :\\t\", *neuronsPerLayer)\n}", "func init() {\n\t// Read command line flags\n\tusers := flag.Int(\"users\", 1, \"Concurrent user count, 동접 유저\")\n\tduration := flag.Int(\"duration\", 30, \"Test duration in seconds\")\n\tinterval := flag.String(\"interval\", \"1s\", `Interval for file creation(\"ns\", \"us\" (or \"µs\"), \"ms\", \"s\", \"m\", \"h\")`)\n\tsize := flag.Int64(\"size\", 1024, \"Size of file to create in bytes\")\n\tpath := flag.String(\"path\", \"\", \"[Required] Path where to create files\")\n\tflag.StringVar(&cpuprofile, \"cpuprofile\", \"\", \"write cpu profile to file\")\n\n\tflag.Parse()\n\n\tparsedInterval, err := time.ParseDuration(*interval)\n\tif err != nil || *path == \"\" {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\n\t// Pass the flag values into viper.\n\tviper.Set(\"users\", *users)\n\tviper.Set(\"duration\", *duration)\n\tviper.Set(\"interval\", parsedInterval)\n\tviper.Set(\"size\", *size)\n\tviper.Set(\"path\", *path)\n\n\tformatter := &log.TextFormatter{\n\t\tTimestampFormat: \"2006-01-02T15:04:05.000\",\n\t\tFullTimestamp: true,\n\t}\n\tlog.SetFormatter(formatter)\n\tlog.SetLevel(log.DebugLevel)\n}", "func init() {\n\t// name must be set when using Execute, can be empty when using ExecuteTemplate, because there naem must be given\n\ttpl = template.Must(template.New(\"\").Funcs(fm).ParseGlob(\"tpl/*.gohtml\"))\n}", "func (ms *ManagerService) Init(cfgfile string) {\n\tif _, err := os.Stat(cfgfile); os.IsNotExist(err) {\n\t\tlog.Fatalf(\"File '%s' does not exist.\\n\", cfgfile)\n\t} else {\n\t\tms.Config, _ = toml.LoadFile(cfgfile)\n\t}\n}", "func init() {\n\tconst (\n\t\tdefaultRsFilePath = \"./data/rslist1.txt\"\n\t\trsusage = \"File containing list of rsnumbers\"\n\t\tdefaultvcfPathPref = \"\"\n\t\tvusage = \"default path prefix for vcf files\"\n\t\tdefaultThreshold = 0.9\n\t\tthrusage = \"Prob threshold\"\n\t\tdefaultAssayTypes = \"affy,illumina,broad,metabo,exome\"\n\t\tatusage = \"Assay types\"\n\t)\n\tflag.StringVar(&rsFilePath, \"rsfile\", defaultRsFilePath, rsusage)\n\tflag.StringVar(&rsFilePath, \"r\", defaultRsFilePath, rsusage+\" (shorthand)\")\n\tflag.StringVar(&vcfPathPref, \"vcfprfx\", defaultvcfPathPref, vusage)\n\tflag.StringVar(&vcfPathPref, \"v\", defaultvcfPathPref, vusage+\" (shorthand)\")\n\tflag.Float64Var(&threshold, \"threshold\", defaultThreshold, thrusage)\n\tflag.Float64Var(&threshold, \"t\", defaultThreshold, thrusage+\" (shorthand)\")\n\tflag.StringVar(&assayTypes, \"assaytypes\", defaultAssayTypes, atusage)\n\tflag.StringVar(&assayTypes, \"a\", defaultAssayTypes, atusage+\" (shorthand)\")\n\tflag.Parse()\n}", "func Initialise(path string) error {\n\tr, err := zip.OpenReader(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer r.Close()\n\n\tfor _, ff := range fileFilters {\n\t\tfor _, file := range r.File {\n\t\t\tif file.Name == ff.Filename {\n\t\t\t\tr, err := file.Open()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tbr := bufio.NewReader(r)\n\t\t\t\tnline := 0\n\t\t\t\tfor {\n\t\t\t\t\tnline++\n\t\t\t\t\tvar line string\n\t\t\t\t\tline, err = br.ReadString('\\n')\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tif len(line) < 7 || line[0] == '#' {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tvar code uint32\n\t\t\t\t\t_, err = fmt.Sscanf(line, \"U+%X\\t\", &code)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\terr = fmt.Errorf(\"%s:%d: %s\", ff.Filename, nline, err.Error())\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tfor n, c := range line {\n\t\t\t\t\t\tif c == '\\t' {\n\t\t\t\t\t\t\tline = line[n+1:]\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfor len(line) > 0 && line[len(line)-1] == '\\n' {\n\t\t\t\t\t\tline = line[:len(line)-1]\n\t\t\t\t\t}\n\n\t\t\t\t\tif code == endOfIndex {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tidx := code2index(code)\n\t\t\t\t\tif idx > 0 {\n\t\t\t\t\t\tdatabase.Contiguous[idx].loaded = true\n\t\t\t\t\t\tdatabase.Contiguous[idx].Unicode = code\n\t\t\t\t\t\terr = ff.RecordFilter(&database.Contiguous[idx], code, strings.Split(line, \"\\t\"))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tc, _ := database.Misc[code]\n\t\t\t\t\t\tc.Unicode = code\n\t\t\t\t\t\tc.loaded = true\n\t\t\t\t\t\terr = ff.RecordFilter(&c, code, strings.Split(line, \"\\t\"))\n\t\t\t\t\t\tdatabase.Misc[code] = c\n\t\t\t\t\t}\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\terr = fmt.Errorf(\"%s:%d: %s\", ff.Filename, nline, err.Error())\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif err != io.EOF {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func init() {\n\tflag.StringVar(&configfile, \"configfile\", \"/data/config/go/best-practices/config.yml\", \"config file full path\")\n\tflag.StringVar(&loggerfile, \"loggerfile\", \"\", \"seelog config file\")\n\tflag.BoolVar(&help, \"h\", false, \"show help\")\n\tflag.IntVar(&port, \"port\", 0, \"service port to listen\")\n\tflag.Parse()\n\n\tif help {\n\t\tflag.Usage()\n\t}\n\t// init logger firstly!!!\n\tmylogger.Init(loggerfile)\n\n\tappConfig.GetConfig(configfile)\n\n\tlogger.Infof(\"Init with config:%+v\", appConfig)\n}", "func (e *EventLog) init() {\n\te.currentFileName = \"\"\n\te.fileDelimiter = \"-\"\n\te.nextFileName = e.eventLogName + e.fileDelimiter + time.Now().Format(e.datePattern)\n\tif err := e.fileSystem.MkdirAll(e.eventLogPath, appconfig.ReadWriteExecuteAccess); err != nil {\n\t\tfmt.Println(\"Failed to create directory for audits\", err)\n\t}\n\te.eventWriter()\n}", "func parseTemplates() (){\n templates = make(map[string]*template.Template)\n if files, err := ioutil.ReadDir(CONFIG.TemplatesDir) ; err != nil {\n msg := \"Error reading templates directory: \" + err.Error()\n log.Fatal(msg)\n } else {\n for _, f := range files {\n fmt.Println(f.Name())\n err = nil\n\n tpl, tplErr := template.New(f.Name()).Funcs(template.FuncMap{\n \"humanDate\": humanDate,\n \"humanSize\": humanSize,}).ParseFiles(CONFIG.TemplatesDir + \"/\" + f.Name())\n if tplErr != nil {\n log.Fatal(\"Error parsing template: \" + tplErr.Error())\n } else {\n templates[f.Name()] = tpl\n }\n }\n }\n return\n}", "func (l *Log) setup() error {\n\tfiles, err := ioutil.ReadDir(l.Dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar baseOffsets []uint64\n\tfor _, file := range files {\n\t\toffStr := strings.TrimSuffix(\n\t\t\tfile.Name(),\n\t\t\tpath.Ext(file.Name()),\n\t\t)\n\t\toff, _ := strconv.ParseUint(offStr, 10, 0)\n\t\tbaseOffsets = append(baseOffsets, off)\n\t}\n\tsort.Slice(baseOffsets, func(i, j int) bool {\n\t\treturn baseOffsets[i] < baseOffsets[j]\n\t})\n\tfor i := 0; i < len(baseOffsets); i++ {\n\t\tif err = l.newSegment(baseOffsets[i]); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// baseOffset contains dup for index and store so we skip the dup\n\t\ti++\n\t}\n\tif l.segments == nil {\n\t\tif err = l.newSegment(\n\t\t\tl.Config.Segment.InitialOffset,\n\t\t); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func init() {\n\tdb, err := versionsDBLineReader()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tvar solidityArtifactsMissing []string\n\tfor db.Scan() {\n\t\tline := strings.Fields(db.Text())\n\t\tif stripTrailingColon(line[0], \"\") != \"GETH_VERSION\" {\n\t\t\tif os.IsNotExist(utils.JustError(os.Stat(line[1]))) {\n\t\t\t\tsolidityArtifactsMissing = append(solidityArtifactsMissing, line[1])\n\t\t\t}\n\t\t}\n\t}\n\tif len(solidityArtifactsMissing) == 0 {\n\t\treturn\n\t}\n\tfmt.Printf(\"some solidity artifacts missing (%s); rebuilding...\",\n\t\tsolidityArtifactsMissing)\n\t// Don't want to run \"make wrappers-all\" here, because that would\n\t// result in an infinite loop\n\tcmd := exec.Command(\"bash\", \"-c\", compileCommand)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\tpanic(err)\n\t}\n}", "func init() {\n\t// if envFileName exists in the current directory, load it\n\tlocalEnvFile := fmt.Sprintf(\"./%s\", envFileName)\n\tif _, localEnvErr := os.Stat(localEnvFile); localEnvErr == nil {\n\t\tif loadErr := godotenv.Load(localEnvFile); loadErr != nil {\n\t\t\tstdErr.Printf(\"Could not load env file <%s>: %s\", localEnvFile, loadErr)\n\t\t}\n\t}\n\n\t// if envFileName exists in the user's home directory, load it\n\tif homeDir, homeErr := os.UserHomeDir(); homeErr == nil {\n\t\thomeEnvFile := fmt.Sprintf(\"%s/%s\", homeDir, \".xmcenv\")\n\t\tif _, homeEnvErr := os.Stat(homeEnvFile); homeEnvErr == nil {\n\t\t\tif loadErr := godotenv.Load(homeEnvFile); loadErr != nil {\n\t\t\t\tstdErr.Printf(\"Could not load env file <%s>: %s\", homeEnvFile, loadErr)\n\t\t\t}\n\t\t}\n\t}\n}", "func init() {\n\tvar err error\n\tvfs, err = statikfs.New()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (r *RulePersistence) Init() error {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\terr := r.readFromFile()\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.applyRulesInDB()\n\treturn nil\n}", "func initializeFile() {\r\n f, err := os.Create(fileName)\r\n check(err)\r\n\r\n defer f.Close()\r\n \r\n}", "func init() {\n\tif err := godotenv.Load(\"/Users/abdullahimahamed/go/src/github.com/featherr-engineering/rest-api/.env\"); err != nil {\n\t\tlog.Warn(\"File .env not found, reading configuration from ENV\")\n\t}\n\n\tlog.Info(\"Parsing ENV vars...\")\n\tdefer log.Info(\"Done Parsing ENV vars\")\n\n\tcfg = &Config{}\n\n\tif err := env.Parse(cfg); err != nil {\n\t\tlog.WithFields(log.Fields{\"Error\": err}).Warn(\"Errors Parsing Configuration\")\n\t}\n\n\treturn\n}", "func init() {\n //fmt.Println(\"init\")\n app_data.file_name = \"/tmp/roll_test/test.txt\"\n}", "func init() {\n\thome, _ := os.UserHomeDir()\n\n\tGlobalConfig = GlobalOpts{\n\t\tInstallDir: filepath.Join(home, \"probr\"),\n\t\tGodogResultsFormat: \"cucumber\",\n\t\tStartTime: time.Now(),\n\t}\n\tSetTmpDir(filepath.Join(home, \"probr\", \"tmp\")) // TODO: this needs error handling\n}", "func init() {\n\th, err := calcHashSum(*config.Promises)\n\tif err != nil {\n\t\tlog.Fatalln(\"Error:\", err)\n\t}\n\n\tfi, err := os.Stat(*config.Promises)\n\tif err != nil {\n\t\tlog.Println(\"Error:\", err)\n\t}\n\n\tvar r Report\n\tr = &Promises{\n\t\tFilename: *config.Promises,\n\t\tChecksum: h,\n\t\tOldModTime: fi.ModTime(),\n\t}\n\n\tRegister(\"promises\", r)\n}", "func (fc *FilterConfig) initFsnotifyEventHandler() {\n\tconst pauseDelay = 5 * time.Second // used to let all changes be done before reloading the file\n\tgo func() {\n\t\ttimer := time.NewTimer(0)\n\t\tdefer timer.Stop()\n\t\tfirstTime := true\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-timer.C:\n\t\t\t\tif firstTime {\n\t\t\t\t\tfirstTime = false\n\t\t\t\t} else {\n\t\t\t\t\tfc.reloadFile()\n\t\t\t\t}\n\t\t\tcase <-fc.watcher.Events:\n\t\t\t\ttimer.Reset(pauseDelay)\n\t\t\tcase err := <-fc.watcher.Errors:\n\t\t\t\tgoglog.Logger.Errorf(\"ip2location: %s\", err.Error())\n\t\t\tcase <-fc.ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}" ]
[ "0.70169306", "0.68562007", "0.65647465", "0.64986575", "0.6443658", "0.64390147", "0.6370577", "0.63616455", "0.6354852", "0.6354852", "0.63380915", "0.63380915", "0.6323095", "0.62846106", "0.6272014", "0.62482643", "0.6243898", "0.6241939", "0.6216632", "0.62120855", "0.62110656", "0.6195559", "0.61569935", "0.6156521", "0.61545527", "0.6127362", "0.6126913", "0.61208475", "0.61077046", "0.60717314", "0.6066385", "0.6066385", "0.6064415", "0.60548645", "0.6039708", "0.6027372", "0.6024906", "0.60144544", "0.5989839", "0.59789896", "0.59704655", "0.59681195", "0.59679985", "0.5965604", "0.5940993", "0.593906", "0.5929556", "0.592903", "0.59246826", "0.5916862", "0.591563", "0.5910862", "0.58987767", "0.5857039", "0.5838809", "0.58346575", "0.58295614", "0.58207756", "0.58155763", "0.5814205", "0.5813211", "0.5807968", "0.58024853", "0.5794284", "0.57929", "0.5782469", "0.5775635", "0.5775559", "0.5775461", "0.57754123", "0.5773737", "0.5769753", "0.5763305", "0.5744925", "0.5740658", "0.57405627", "0.573469", "0.57184064", "0.5715591", "0.57112837", "0.57084805", "0.5705402", "0.56987846", "0.5690676", "0.5681408", "0.5675719", "0.5674916", "0.5674711", "0.5669813", "0.56686616", "0.56681913", "0.5662478", "0.5661226", "0.5654959", "0.5649602", "0.5646846", "0.5641846", "0.5639253", "0.56390977", "0.56375676" ]
0.59843117
39
NewSCP creates an SCP command from a set of parameters.
func NewSCP(targetHost string, targetPort string, credentials entities.Credentials, source string, destination string) *SCP { return &SCP{*entities.NewSyncCommand(entities.SCP), targetHost, targetPort, credentials, source, destination} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CreateCommand(cfg Config) (Command, error) {\n\terr := cfg.CheckAndSetDefaults()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tcmd := command{\n\t\tConfig: cfg,\n\t}\n\n\tcmd.log = log.WithFields(log.Fields{\n\t\ttrace.Component: \"SCP\",\n\t\ttrace.ComponentFields: log.Fields{\n\t\t\t\"LocalAddr\": cfg.Flags.LocalAddr,\n\t\t\t\"RemoteAddr\": cfg.Flags.RemoteAddr,\n\t\t\t\"Target\": cfg.Flags.Target,\n\t\t\t\"User\": cfg.User,\n\t\t\t\"RunOnServer\": cfg.RunOnServer,\n\t\t\t\"RemoteLocation\": cfg.RemoteLocation,\n\t\t},\n\t})\n\n\treturn &cmd, nil\n}", "func NewSCPFromJSON(raw []byte) (*entities.Command, derrors.Error) {\n\tscp := &SCP{}\n\tif err := json.Unmarshal(raw, &scp); err != nil {\n\t\treturn nil, derrors.NewInvalidArgumentError(errors.UnmarshalError, err)\n\t}\n\tscp.CommandID = entities.GenerateCommandID(scp.Name())\n\tvar r entities.Command = scp\n\treturn &r, nil\n}", "func SCP(src, username, host, dst string) error {\n\tvar args []string\n\n\tif fi, err := os.Stat(src); err != nil {\n\t\treturn oops.WithMessage(err, \"failed to stat src\")\n\t} else if fi.IsDir() {\n\t\targs = append(args, \"-r\")\n\t}\n\n\targs = append(args, src, fmt.Sprintf(\"%s@%s:%s\", username, host, dst))\n\n\toutput.Debug(\"scp %s\", strings.Join(args, \" \"))\n\n\tif err := exe.Command(\"scp\", args...).Run().Err; err != nil {\n\t\treturn oops.WithMessage(err, \"failed to scp file\")\n\t}\n\n\treturn nil\n}", "func scpAction(c *cli.Context) {\n\texec := PrepareExecutor(c)\n\tsrc := c.String(\"src\")\n\tuseScp := func() {\n\t\texec.SetTransfer(src, c.String(\"dst\"))\n\t\texec.SetTransferHook(c.String(\"before\"), c.String(\"after\"))\n\t}\n\tuseP2P := func() {\n\t\tp2pMgr := p2p.GetMgr()\n\t\tp2pMgr.SetTransfer(src, c.String(\"dst\"))\n\t\terr := p2pMgr.Mkseed()\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(2)\n\t\t}\n\t\tif p2pMgr.NeedTransferFile() {\n\t\t\tremoteTmp := config.GetString(\"remote.tmpdir\")\n\t\t\texec.SetTransfer(p2pMgr.TransferFilePath(), remoteTmp)\n\t\t}\n\t\tcmd := util.WrapCmd(p2pMgr.ClientCmd(), c.String(\"before\"), c.String(\"after\"))\n\t\texec.Parameter.Cmd = cmd\n\t\texec.Parameter.Concurrency = -1\n\t}\n\tif !p2p.Available() {\n\t\tuseScp()\n\t} else if util.IsDir(src) {\n\t\tuseP2P()\n\t} else {\n\t\tstat, err := os.Lstat(src)\n\t\tif nil != err {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(2)\n\t\t}\n\t\tsize := stat.Size()\n\t\tsizeInMB := size / 1024 / 1024\n\t\ttransferTotal := sizeInMB * int64(exec.HostCount())\n\t\t// If transferTotal is less than 1 MB * 10 machine, use scp.\n\t\tif 10 > transferTotal {\n\t\t\tuseScp()\n\t\t} else {\n\t\t\tuseP2P()\n\t\t}\n\t}\n\tfailed, err := exec.Run()\n\tif nil != err {\n\t\tfmt.Println(err)\n\t\tos.Exit(2)\n\t}\n\tos.Exit(failed)\n}", "func ScpDownload(session *ssh.Session, client *ssh.Client, src, dst string, limit int, compress bool) error {\n\tr, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tbufr := bufio.NewReader(r)\n\n\tw, err := session.StdinPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tremoteArgs := make([]string, 0)\n\tif compress {\n\t\tremoteArgs = append(remoteArgs, \"-C\")\n\t}\n\tif limit > 0 {\n\t\tremoteArgs = append(remoteArgs, fmt.Sprintf(\"-l %d\", limit))\n\t}\n\tremoteCmd := fmt.Sprintf(\"scp -r %s -f %s\", strings.Join(remoteArgs, \" \"), src)\n\n\terr = session.Start(remoteCmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := ack(w); err != nil { // send an empty byte to start transfer\n\t\treturn err\n\t}\n\n\twd := dst\n\tfor firstCommand := true; ; firstCommand = false {\n\t\t// parse scp command\n\t\tline, err := bufr.ReadString('\\n')\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tswitch line[0] {\n\t\t// ignore ACK from server\n\t\tcase '\\x00':\n\t\t\tline = line[1:]\n\t\tcase '\\x01':\n\t\t\treturn fmt.Errorf(\"scp warning: %s\", line[1:])\n\t\tcase '\\x02':\n\t\t\treturn fmt.Errorf(\"scp error: %s\", line[1:])\n\t\t}\n\n\t\tswitch line[0] {\n\t\tcase 'C':\n\t\t\tmode, size, name, err := parseLine(line)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tfp := filepath.Join(wd, name)\n\t\t\t// fisrt scp command is 'C' means src is a single file\n\t\t\tif firstCommand {\n\t\t\t\tfp = dst\n\t\t\t}\n\n\t\t\ttargetFile, err := os.OpenFile(fp, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode|0700)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer targetFile.Close()\n\t\t\tif err := ack(w); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// transferring data\n\t\t\tn, err := io.CopyN(targetFile, bufr, size)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif n < size {\n\t\t\t\treturn fmt.Errorf(\"error downloading via scp, file size mismatch\")\n\t\t\t}\n\t\t\tif err := targetFile.Sync(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase 'D':\n\t\t\tmode, _, name, err := parseLine(line)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// normally, workdir is like this\n\t\t\twd = filepath.Join(wd, name)\n\n\t\t\t// fisrt scp command is 'D' means src is a dir\n\t\t\tif firstCommand {\n\t\t\t\tfi, err := os.Stat(dst)\n\t\t\t\tif err != nil && !os.IsNotExist(err) {\n\t\t\t\t\treturn err\n\t\t\t\t} else if err == nil && !fi.IsDir() {\n\t\t\t\t\treturn fmt.Errorf(\"%s cannot be an exist file\", wd)\n\t\t\t\t} else if os.IsNotExist(err) {\n\t\t\t\t\t// dst is not exist, so dst is the target dir\n\t\t\t\t\twd = dst\n\t\t\t\t} else {\n\t\t\t\t\t// dst is exist, dst/name is the target dir\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terr = utils.MkdirAll(wd, mode)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase 'E':\n\t\t\twd = filepath.Dir(wd)\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"incorrect scp command '%b', should be 'C', 'D' or 'E'\", line[0])\n\t\t}\n\n\t\terr = ack(w)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn session.Wait()\n}", "func newSFTP(host, port string, config *ssh.ClientConfig) (*sftp.Client, error) {\n\taddress := host + \":\" + port\n\n\tsshClient, err := ssh.Dial(\"tcp\", address, config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to connect: %v\", err)\n\t}\n\n\tsftp, err := sftp.NewClient(sshClient)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to open SFTP session: %v\", err)\n\t}\n\n\treturn sftp, nil\n}", "func ScpDownload(session *ssh.Session, client *ssh.Client, src, dst string, limit int, compress bool) error {\n\tr, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tbufr := bufio.NewReader(r)\n\n\tw, err := session.StdinPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcopyF := func() error {\n\t\t// parse SCP command\n\t\tline, _, err := bufr.ReadLine()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif line[0] != byte('C') {\n\t\t\treturn fmt.Errorf(\"incorrect scp command '%b', should be 'C'\", line[0])\n\t\t}\n\n\t\tmode, err := strconv.ParseUint(string(line[1:5]), 0, 32)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error parsing file mode; %s\", err)\n\t\t}\n\n\t\t// prepare dst file\n\t\ttargetPath := filepath.Dir(dst)\n\t\tif err := utils.CreateDir(targetPath); err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttargetFile, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, fs.FileMode(mode))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer targetFile.Close()\n\n\t\tsize, err := strconv.Atoi(strings.Fields(string(line))[1])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := ack(w); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// transferring data\n\t\tn, err := io.CopyN(targetFile, bufr, int64(size))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif n < int64(size) {\n\t\t\treturn fmt.Errorf(\"error downloading via scp, file size mismatch\")\n\t\t}\n\t\tif err := targetFile.Sync(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn ack(w)\n\t}\n\n\tcopyErrC := make(chan error, 1)\n\tgo func() {\n\t\tdefer w.Close()\n\t\tcopyErrC <- copyF()\n\t}()\n\n\tremoteArgs := make([]string, 0)\n\tif compress {\n\t\tremoteArgs = append(remoteArgs, \"-C\")\n\t}\n\tif limit > 0 {\n\t\tremoteArgs = append(remoteArgs, fmt.Sprintf(\"-l %d\", limit))\n\t}\n\tremoteCmd := fmt.Sprintf(\"scp %s -f %s\", strings.Join(remoteArgs, \" \"), src)\n\n\terr = session.Start(remoteCmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := ack(w); err != nil { // send an empty byte to start transfer\n\t\treturn err\n\t}\n\n\terr = <-copyErrC\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn session.Wait()\n}", "func New(config *model.SFTP) (*server.Client, error) {\n\tvar err error\n\tvar client = &Client{cfg: config}\n\tvar sshConf *ssh.ClientConfig\n\tvar sshAuth []ssh.AuthMethod\n\n\t// SSH Auth\n\tif config.Key != \"\" {\n\t\tif sshAuth, err = client.readPublicKey(config.Key, config.Password); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to read SFTP public key, %v\", err)\n\t\t}\n\t} else {\n\t\tsshAuth = []ssh.AuthMethod{\n\t\t\tssh.Password(config.Password),\n\t\t}\n\t}\n\tsshConf = &ssh.ClientConfig{\n\t\tUser: config.Username,\n\t\tAuth: sshAuth,\n\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t\tTimeout: config.Timeout * time.Second,\n\t}\n\n\tsshConf.SetDefaults()\n\tclient.ssh, err = ssh.Dial(\"tcp\", fmt.Sprintf(\"%s:%d\", config.Host, config.Port), sshConf)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot open ssh connection, %v\", err)\n\t}\n\n\tif client.sftp, err = sftp.NewClient(client.ssh, sftp.MaxPacket(config.MaxPacketSize)); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &server.Client{Handler: client}, err\n}", "func (ssh *SSHConfig) Copy(remotePath, localPath string, isUpload bool) (int, string, string, error) {\n\ttunnels, sshConfig, err := ssh.CreateTunnels()\n\tif err != nil {\n\t\treturn 0, \"\", \"\", fmt.Errorf(\"Unable to create tunnels : %s\", err.Error())\n\t}\n\n\tidentityfile, err := CreateTempFileFromString(sshConfig.PrivateKey, 0400)\n\tif err != nil {\n\t\treturn 0, \"\", \"\", fmt.Errorf(\"Unable to create temporary key file: %s\", err.Error())\n\t}\n\n\tcmdTemplate, err := template.New(\"Command\").Parse(\"scp -i {{.IdentityFile}} -P {{.Port}} {{.Options}} {{if .IsUpload}}{{.LocalPath}} {{.User}}@{{.Host}}:{{.RemotePath}}{{else}}{{.User}}@{{.Host}}:{{.RemotePath}} {{.LocalPath}}{{end}}\")\n\tif err != nil {\n\t\treturn 0, \"\", \"\", fmt.Errorf(\"Error parsing command template: %s\", err.Error())\n\t}\n\n\tvar copyCommand bytes.Buffer\n\tif err := cmdTemplate.Execute(&copyCommand, struct {\n\t\tIdentityFile string\n\t\tPort int\n\t\tOptions string\n\t\tUser string\n\t\tHost string\n\t\tRemotePath string\n\t\tLocalPath string\n\t\tIsUpload bool\n\t}{\n\t\tIdentityFile: identityfile.Name(),\n\t\tPort: sshConfig.Port,\n\t\tOptions: \"-q -oLogLevel=error -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oPubkeyAuthentication=yes -oPasswordAuthentication=no\",\n\t\tUser: sshConfig.User,\n\t\tHost: sshConfig.Host,\n\t\tRemotePath: remotePath,\n\t\tLocalPath: localPath,\n\t\tIsUpload: isUpload,\n\t}); err != nil {\n\t\treturn 0, \"\", \"\", fmt.Errorf(\"Error executing template: %s\", err.Error())\n\t}\n\n\tsshCmdString := copyCommand.String()\n\tcmd := exec.Command(\"bash\", \"-c\", sshCmdString)\n\tsshCommand := SSHCommand{\n\t\tcmd: cmd,\n\t\ttunnels: tunnels,\n\t\tkeyFile: identityfile,\n\t}\n\n\treturn sshCommand.Run()\n}", "func (scp *SCP) Run(_ string) (*entities.CommandResult, derrors.Error) {\n\n\tconn, err := connection.NewSSHConnection(\n\t\tscp.TargetHost, scp.getTargetPort(),\n\t\tscp.Credentials.Username, scp.Credentials.Password, \"\", scp.Credentials.PrivateKey)\n\tif err != nil {\n\t\treturn nil, derrors.NewInternalError(errors.SSHConnectionError, err).WithParams(scp.TargetHost)\n\t}\n\tstart := time.Now()\n\terr = conn.Copy(scp.Source, scp.Destination, false)\n\tif err != nil {\n\t\treturn nil, derrors.NewInternalError(errors.SSHConnectionError, err).WithParams(scp.TargetHost)\n\t}\n\n\treturn entities.NewSuccessCommand([]byte(scp.String() + \": OK \" + time.Since(start).String())), nil\n}", "func (client *SSHClient) Download(dst io.WriteCloser, remotePath string) error {\n\tdefer dst.Close()\n\n\tsession, err := client.cryptoClient.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer session.Close()\n\n\tackPipe, err := session.StdinPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdataPipe, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terrorChan := make(chan error, 3)\n\n\twg := sync.WaitGroup{}\n\twg.Add(3)\n\n\t// This goroutine is for writing the scp header message.\n\tgo func() {\n\t\tdefer wg.Done()\n\n\t\tdefer ackPipe.Close()\n\n\t\t// 3 ack messages; 1 to initiate, 1 for the message, 1 for the data\n\t\t// https://blogs.oracle.com/janp/entry/how_the_scp_protocol_works\n\t\tfmt.Fprintf(ackPipe, string(byte(0)))\n\t\tfmt.Fprintf(ackPipe, string(byte(0)))\n\t\tfmt.Fprintf(ackPipe, string(byte(0)))\n\t}()\n\n\t// This goroutine is for downloading the file.\n\tgo func() {\n\t\tdefer wg.Done()\n\n\t\t// First line of data is permissions, size, and name.\n\t\t// For example: C0666 14 somefile\n\t\t// Use the permissions for the file, discard size and name\n\t\t// https://blogs.oracle.com/janp/entry/how_the_scp_protocol_works\n\t\tdr := bufio.NewReader(dataPipe)\n\t\ts, err := dr.ReadString('\\n')\n\t\tif err != nil {\n\t\t\terrorChan <- err\n\t\t\treturn\n\t\t}\n\t\tscpMsgs := strings.Split(s, \" \")\n\n\t\t// Only currently support copying single files\n\t\tif len(scpMsgs) != 3 || len(scpMsgs[0]) != 5 || scpMsgs[0][0] != 'C' {\n\t\t\terrorChan <- ErrSSHInvalidMessageLength\n\t\t\treturn\n\t\t}\n\n\t\t// Get the length of the expected data; scp control messages follow.\n\t\tlength, err := strconv.ParseInt(scpMsgs[1], 10, 64)\n\t\tif err != nil {\n\t\t\terrorChan <- err\n\t\t\treturn\n\t\t}\n\n\t\t// Copy content to file\n\t\t_, err = io.CopyN(dst, dr, length)\n\t\tif err != nil {\n\t\t\terrorChan <- err\n\t\t\treturn\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tdefer wg.Done()\n\n\t\t// On the remote machine run scp in source mode to send the files.\n\t\terr := session.Run(fmt.Sprintf(\"/usr/bin/scp -f %s\", remotePath))\n\t\tif err != nil {\n\t\t\terrorChan <- err\n\t\t}\n\t}()\n\n\twg.Wait()\n\n\tselect {\n\tcase err := <-errorChan:\n\t\treturn err\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (r *ProjectsLocationsSshKeysService) Create(parent string, sshkey *SSHKey) *ProjectsLocationsSshKeysCreateCall {\n\tc := &ProjectsLocationsSshKeysCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.parent = parent\n\tc.sshkey = sshkey\n\treturn c\n}", "func Send(hostport string, config *ssh.ClientConfig, filename string, mode int, contents []byte) (err error) {\n\tclient, err := ssh.Dial(\"tcp\", hostport, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Make sure we close the client connection\n\tdefer func() {\n\t\tcloseErr := client.Close()\n\t\tif closeErr != nil {\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"%w, and failed to close ssh connection: %w\", err, closeErr)\n\t\t\t} else {\n\t\t\t\terr = fmt.Errorf(\"failed to close ssh connection: %w\", closeErr)\n\t\t\t}\n\t\t}\n\t}()\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twrite, err := session.StdinPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tread, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstream := readWriter{Reader: read, Writer: write}\n\tif err = session.Start(\"scp -qt \" + filename); err != nil {\n\t\treturn err\n\t}\n\n\terr = sendFile(stream, bytes.NewReader(contents), filename, int64(len(contents)), mode)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = write.Close(); err != nil {\n\t\treturn err\n\t}\n\n\tif err = session.Wait(); err != nil {\n\t\treturn fmt.Errorf(\"failed to wait for scp: %w\", err)\n\t}\n\n\t// Always return err so defer can change it if it's nil\n\treturn err\n}", "func newSSHProcess(client *sshRunner, info jasper.ProcessInfo) (jasper.Process, error) {\n\tif client == nil {\n\t\treturn nil, errors.New(\"SSH process needs an SSH client to run CLI commands\")\n\t}\n\treturn &sshProcess{\n\t\tclient: client,\n\t\tinfo: info,\n\t}, nil\n}", "func newCreateCmd(clientFn func() (*fic.ServiceClient, error), out io.Writer) *cobra.Command {\n\tvar (\n\t\tsrcRouterID string\n\t\tsrcGroupName string\n\t\tsrcPrimary string\n\t\tsrcSecondary string\n\t\tsrcRouteFilter string\n\t\tdestPrimary string\n\t\tdestSecondary string\n\t\tbandwidth string\n\t)\n\n\tr := regexp.MustCompile(`^[\\w&()-]{1,64}$`)\n\tvalidateSrc := func(splitSrc []string, isPrimary, hasSecondary bool) error {\n\t\t_, ipNet, err := net.ParseCIDR(splitSrc[0])\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"ipAddress must be CIDR whose subnet mask is 30, e.g. 10.0.0.1/30: received %s\", splitSrc[0])\n\t\t}\n\t\tsubNetMaskLength, _ := ipNet.Mask.Size()\n\t\tif subNetMaskLength != 30 {\n\t\t\treturn fmt.Errorf(\"subnet mask of ipAddress must be 30, e.g. 10.0.0.1/30: received %s\", splitSrc[0])\n\t\t}\n\n\t\tif !utils.StringInSlice(splitSrc[1], validPrepends) {\n\t\t\treturn fmt.Errorf(\"asPathPrepend.in must be one of %s: received %s\", validPrepends, splitSrc[1])\n\t\t}\n\n\t\tif !utils.StringInSlice(splitSrc[2], validPrepends) {\n\t\t\treturn fmt.Errorf(\"asPathPrepend.out must be one of %s: received %s\", validPrepends, splitSrc[2])\n\t\t}\n\n\t\tif isPrimary {\n\t\t\tmed, err := strconv.Atoi(splitSrc[3])\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"med.out must be numeric value: received %s\", splitSrc[3])\n\t\t\t}\n\n\t\t\tif hasSecondary {\n\t\t\t\tif !utils.IntInSlice(med, validPrimaryPairedMEDs) {\n\t\t\t\t\treturn fmt.Errorf(\"med.out in paired connection must be one of %v: received %d\", validPrimaryPairedMEDs, med)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif !utils.IntInSlice(med, validPrimarySingleMEDs) {\n\t\t\t\t\treturn fmt.Errorf(\"med.out in single connection must be one of %v: received %d\", validPrimarySingleMEDs, med)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}\n\tvalidateDest := func(splitDest []string) error {\n\t\tvlan, err := strconv.Atoi(splitDest[1])\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"vlan must be numeric value: received %s\", splitDest[1])\n\t\t}\n\t\tif vlan < 101 || vlan > 3300 {\n\t\t\treturn fmt.Errorf(\"vlan must be range of 101 to 3300: received %s\", splitDest[1])\n\t\t}\n\n\t\t_, ipNet, err := net.ParseCIDR(splitDest[2])\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"ipAddress must be CIDR whose subnet mask is 30, e.g. 10.0.0.2/30: received %s\", splitDest[2])\n\t\t}\n\t\tsubNetMaskLength, _ := ipNet.Mask.Size()\n\t\tif subNetMaskLength != 30 {\n\t\t\treturn fmt.Errorf(\"subnet mask of ipAddress must be 30, e.g. 10.0.0.2/30: received %s\", splitDest[2])\n\t\t}\n\n\t\tasn, err := strconv.Atoi(splitDest[3])\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"asn must be numeric value: received %s\", splitDest[3])\n\t\t}\n\t\tif asn < 1 || asn > 65535 {\n\t\t\treturn fmt.Errorf(\"asn must be range of 1 to 65535: received %s\", splitDest[3])\n\t\t}\n\t\treturn nil\n\t}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"create <name>\",\n\t\tShort: \"Create router to port connection\",\n\t\tExample: \"# In case of non paired-connection \\n\" +\n\t\t\t\"fic router-to-port-connections create YourConnectionName \" +\n\t\t\t\"--source-router F020123456789 \" +\n\t\t\t\"--source-group group_1 \" +\n\t\t\t\"--source-primary 10.0.0.1/30,4,4,10 \" +\n\t\t\t\"--source-route-filter fullRoute,fullRouteWithDefaultRoute \" +\n\t\t\t\"--destination-primary F010123456789,101,10.0.0.2/30,65000 \" +\n\t\t\t\"--bandwidth 10M \\n\\n\" +\n\t\t\t\"# In case of paired-connection \\n\" +\n\t\t\t\"fic router-to-port-connections create YourConnectionName \" +\n\t\t\t\"--source-router F020123456789 \" +\n\t\t\t\"--source-group group_1 \" +\n\t\t\t\"--source-primary 10.0.0.1/30,4,4,10 \" +\n\t\t\t\"--source-secondary 10.0.0.5/30,2,1 \" +\n\t\t\t\"--source-route-filter fullRoute,fullRouteWithDefaultRoute \" +\n\t\t\t\"--destination-primary F010123456789,101,10.0.0.2/30,65000 \" +\n\t\t\t\"--destination-secondary F019876543210,102,10.0.0.6/30,65000 \" +\n\t\t\t\"--bandwidth 10M\",\n\t\tArgs: cobra.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\n\t\t\tif !r.MatchString(args[0]) {\n\t\t\t\treturn fmt.Errorf(\"name of router to port connection must be composed of alpha-numeric \"+\n\t\t\t\t\t\"characters and & ( ) - _, and must have maximum length of 64 as well: received %s\", args[0])\n\t\t\t}\n\n\t\t\tif !utils.StringInSlice(srcGroupName, validGroupNames) {\n\t\t\t\treturn fmt.Errorf(\"source-group must be one of %s: received %s\", validGroupNames, srcGroupName)\n\t\t\t}\n\n\t\t\tsplitSrcPrimary := strings.Split(strings.TrimSpace(srcPrimary), \",\")\n\t\t\tsplitSrcSecondary := strings.Split(strings.TrimSpace(srcSecondary), \",\")\n\t\t\tsplitSrcRouteFilter := strings.Split(strings.TrimSpace(srcRouteFilter), \",\")\n\t\t\tsplitDestPrimary := strings.Split(strings.TrimSpace(destPrimary), \",\")\n\t\t\tsplitDestSecondary := strings.Split(strings.TrimSpace(destSecondary), \",\")\n\n\t\t\tif len(splitSrcPrimary) != 4 {\n\t\t\t\treturn fmt.Errorf(\"source-primary must have format like \"+\n\t\t\t\t\t\"<ipAddress>,<asPathPrepend.in>,<asPathPrepend.out>,<med.out>: received %s\", srcPrimary)\n\t\t\t}\n\t\t\tif err := validateSrc(splitSrcPrimary, true, srcSecondary != \"\"); err != nil {\n\t\t\t\treturn fmt.Errorf(\"in source-primary, %w\", err)\n\t\t\t}\n\n\t\t\tif len(splitDestPrimary) != 4 {\n\t\t\t\treturn fmt.Errorf(\"destination-primary must have format like \"+\n\t\t\t\t\t\"<portId>,<vlan>,<ipAddress>,<asn>: received %s\", destPrimary)\n\t\t\t}\n\t\t\tif err := validateDest(splitDestPrimary); err != nil {\n\t\t\t\treturn fmt.Errorf(\"in destination-primary, %w\", err)\n\t\t\t}\n\n\t\t\tif srcSecondary != \"\" {\n\t\t\t\tif len(splitSrcSecondary) != 3 {\n\t\t\t\t\treturn fmt.Errorf(\"source-secondary must have format like \"+\n\t\t\t\t\t\t\"<ipAddress>,<asPathPrepend.in>,<asPathPrepend.out>: received %s\", srcSecondary)\n\t\t\t\t}\n\t\t\t\tif err := validateSrc(splitSrcSecondary, false, true); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"in source-secondary, %w\", err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tredundant := false\n\t\t\tif destSecondary != \"\" {\n\t\t\t\tif len(splitDestSecondary) != 4 {\n\t\t\t\t\treturn fmt.Errorf(\"destination-secondary must have format like \"+\n\t\t\t\t\t\t\"<portId>,<vlan>,<ipAddress>,<asn>: received %s\", destSecondary)\n\t\t\t\t}\n\t\t\t\tif err := validateDest(splitDestSecondary); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"in destination-secondary, %w\", err)\n\t\t\t\t}\n\t\t\t\tredundant = true\n\t\t\t}\n\n\t\t\tif len(splitSrcRouteFilter) != 2 {\n\t\t\t\treturn fmt.Errorf(\"source-route-filter must have format like \"+\n\t\t\t\t\t\"<routeFilter.in>,<routeFilter.out>: received %s\", srcRouteFilter)\n\t\t\t}\n\t\t\tif !utils.StringInSlice(splitSrcRouteFilter[0], validRouteFilterIns) {\n\t\t\t\treturn fmt.Errorf(\"routeFilter.in must be one of %s: received %s\", validRouteFilterIns, splitSrcRouteFilter[0])\n\t\t\t}\n\t\t\tif !utils.StringInSlice(splitSrcRouteFilter[1], validRouteFilterOuts) {\n\t\t\t\treturn fmt.Errorf(\"routeFilter.out must be one of %s: received %s\", validRouteFilterOuts, splitSrcRouteFilter[1])\n\t\t\t}\n\n\t\t\tif !utils.StringInSlice(bandwidth, validBandwidths) {\n\t\t\t\treturn fmt.Errorf(\"bandwidth must be one of %s: received %s\", validBandwidths, bandwidth)\n\t\t\t}\n\n\t\t\tclient, err := clientFn()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"creating FIC client: %w\", err)\n\t\t\t}\n\n\t\t\tprependIn, prependOut := interface{}(convPrepend(splitSrcPrimary[1])), interface{}(convPrepend(splitSrcPrimary[2]))\n\t\t\tmed, _ := strconv.Atoi(splitSrcPrimary[3])\n\t\t\tvlan, _ := strconv.Atoi(splitDestPrimary[1])\n\n\t\t\tt := utils.NewTabby(out)\n\t\t\tt.AddHeader(\"id\", \"name\", \"redundant\", \"tenantId\", \"area\", \"operationStatus\", \"bandwidth\", \"operationId\")\n\n\t\t\tif !redundant {\n\t\t\t\topts := singleConn.CreateOpts{\n\t\t\t\t\tName: args[0],\n\t\t\t\t\tSource: singleConn.Source{\n\t\t\t\t\t\tRouterID: srcRouterID,\n\t\t\t\t\t\tGroupName: srcGroupName,\n\t\t\t\t\t\tRouteFilter: singleConn.RouteFilter{\n\t\t\t\t\t\t\tIn: splitSrcRouteFilter[0],\n\t\t\t\t\t\t\tOut: splitSrcRouteFilter[1],\n\t\t\t\t\t\t},\n\t\t\t\t\t\tPrimary: singleConn.SourceHAInfo{\n\t\t\t\t\t\t\tIPAddress: splitSrcPrimary[0],\n\t\t\t\t\t\t\tASPathPrepend: singleConn.ASPathPrepend{\n\t\t\t\t\t\t\t\tIn: &prependIn,\n\t\t\t\t\t\t\t\tOut: &prependOut,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tMED: &singleConn.MED{\n\t\t\t\t\t\t\t\tOut: med,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tDestination: singleConn.Destination{\n\t\t\t\t\t\tPrimary: singleConn.DestinationHAInfo{\n\t\t\t\t\t\t\tPortID: splitDestPrimary[0],\n\t\t\t\t\t\t\tVLAN: vlan,\n\t\t\t\t\t\t\tIPAddress: splitDestPrimary[2],\n\t\t\t\t\t\t\tASN: splitDestPrimary[3],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tBandwidth: bandwidth,\n\t\t\t\t}\n\n\t\t\t\tc, err := singleConn.Create(client, opts).Extract()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"calling Create router to port connection API: %w\", err)\n\t\t\t\t}\n\n\t\t\t\tt.AddLine(c.ID, c.Name, c.Redundant, c.TenantID, c.Area, c.OperationID, c.OperationStatus, c.Bandwidth)\n\t\t\t\tt.Print()\n\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tsecondPrependIn, secondPrependOut := interface{}(convPrepend(splitSrcSecondary[1])), interface{}(convPrepend(splitSrcSecondary[2]))\n\t\t\tsecondVlan, _ := strconv.Atoi(splitDestSecondary[1])\n\n\t\t\topts := pairedConn.CreateOpts{\n\t\t\t\tName: args[0],\n\t\t\t\tSource: pairedConn.Source{\n\t\t\t\t\tRouterID: srcRouterID,\n\t\t\t\t\tGroupName: srcGroupName,\n\t\t\t\t\tRouteFilter: pairedConn.RouteFilter{\n\t\t\t\t\t\tIn: splitSrcRouteFilter[0],\n\t\t\t\t\t\tOut: splitSrcRouteFilter[1],\n\t\t\t\t\t},\n\t\t\t\t\tPrimary: pairedConn.SourceHAInfo{\n\t\t\t\t\t\tIPAddress: splitSrcPrimary[0],\n\t\t\t\t\t\tASPathPrepend: pairedConn.ASPathPrepend{\n\t\t\t\t\t\t\tIn: &prependIn,\n\t\t\t\t\t\t\tOut: &prependOut,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tMED: &pairedConn.MED{\n\t\t\t\t\t\t\tOut: med,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tSecondary: pairedConn.SourceHAInfo{\n\t\t\t\t\t\tIPAddress: splitSrcSecondary[0],\n\t\t\t\t\t\tASPathPrepend: pairedConn.ASPathPrepend{\n\t\t\t\t\t\t\tIn: &secondPrependIn,\n\t\t\t\t\t\t\tOut: &secondPrependOut,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tDestination: pairedConn.Destination{\n\t\t\t\t\tPrimary: pairedConn.DestinationHAInfo{\n\t\t\t\t\t\tPortID: splitDestPrimary[0],\n\t\t\t\t\t\tVLAN: vlan,\n\t\t\t\t\t\tIPAddress: splitDestPrimary[2],\n\t\t\t\t\t\tASN: splitDestPrimary[3],\n\t\t\t\t\t},\n\t\t\t\t\tSecondary: pairedConn.DestinationHAInfo{\n\t\t\t\t\t\tPortID: splitDestSecondary[0],\n\t\t\t\t\t\tVLAN: secondVlan,\n\t\t\t\t\t\tIPAddress: splitDestSecondary[2],\n\t\t\t\t\t\tASN: splitDestSecondary[3],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tBandwidth: bandwidth,\n\t\t\t}\n\n\t\t\tc, err := pairedConn.Create(client, opts).Extract()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"calling Create router to port connection API: %w\", err)\n\t\t\t}\n\n\t\t\tt.AddLine(c.ID, c.Name, c.Redundant, c.TenantID, c.Area, c.OperationID, c.OperationStatus, c.Bandwidth)\n\t\t\tt.Print()\n\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tcmd.Flags().StringVar(&srcRouterID, \"source-router\", \"\", \"(Required) Router ID belonging to source\")\n\tcmd.Flags().StringVar(&srcGroupName, \"source-group\", \"\", \"(Required) Group Name belonging to source\")\n\tcmd.Flags().StringVar(\n\t\t&srcPrimary,\n\t\t\"source-primary\",\n\t\t\"\",\n\t\t\"(Required) Source Primary Info specified in the format <ipAddress>,<asPathPrepend.in>,<asPathPrepend.out>,<med.out>\")\n\tcmd.Flags().StringVar(\n\t\t&srcSecondary,\n\t\t\"source-secondary\",\n\t\t\"\",\n\t\t\"Source Secondary Info specified in the format <ipAddress>,<asPathPrepend.in>,<asPathPrepend.out>\")\n\tcmd.Flags().StringVar(\n\t\t&srcRouteFilter,\n\t\t\"source-route-filter\",\n\t\t\"\",\n\t\t\"(Required) Set of BGP Filter Ingress and Egress specified in the format <routeFilter.in>,<routeFilter.out>\")\n\tcmd.Flags().StringVar(\n\t\t&destPrimary,\n\t\t\"destination-primary\",\n\t\t\"\",\n\t\t\"(Required) Destination Primary Info specified in the format <portId>,<vlan>,<ipAddress>,<asn>\")\n\tcmd.Flags().StringVar(\n\t\t&destSecondary,\n\t\t\"destination-secondary\",\n\t\t\"\",\n\t\t\"Destination Secondary Info specified in the format <portId>,<vlan>,<ipAddress>,<asn>\")\n\tcmd.Flags().StringVar(&bandwidth, \"bandwidth\", \"\", \"(Required) Bandwidth of router to port connection\")\n\n\tcmd.MarkFlagRequired(\"source-router\")\n\tcmd.MarkFlagRequired(\"source-group\")\n\tcmd.MarkFlagRequired(\"source-primary\")\n\tcmd.MarkFlagRequired(\"source-rout-filter\")\n\tcmd.MarkFlagRequired(\"destination-primary\")\n\tcmd.MarkFlagRequired(\"bandwidth\")\n\n\treturn cmd\n}", "func NewSSH(keyConfig *v1alpha1.KeyConfig) *SSH {\n\tssh := &SSH{\n\t\tName: keyConfig.Name,\n\t}\n\treturn ssh\n}", "func newSSH(ip net.IPAddr, port uint16, user string, pass string, key string) *inet.SSH {\n\tvar remoteConn = new(inet.SSH)\n\tremoteConn.Make(ip.String(), strconv.FormatUint(uint64(port), 10), user, pass, key)\n\tglog.Info(\"receiver host: \" + ip.String())\n\treturn remoteConn\n}", "func (svc *SSHKeysService) Create(ctx context.Context, prj string, params *SSHKey) (*SSHKey, *http.Response, error) {\n\tret := new(SSHKey)\n\tresp, err := svc.client.resourceCreate(ctx, projectSSHKeysPath(prj), params, ret)\n\treturn ret, resp, err\n}", "func New(username string, password string) core.SSHClient {\n\treturn &sshclient{\n\t\tconfig: &ssh.ClientConfig{\n\t\t\tUser: username,\n\t\t\tAuth: []ssh.AuthMethod{\n\t\t\t\tssh.Password(password),\n\t\t\t},\n\t\t\tTimeout: 5 * time.Second,\n\t\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t\t},\n\t}\n}", "func PutFile(session *ssh.Session, path string, file []byte) error {\n\tdebugf(\"PutFile: %s\\n\", path)\n\n\tstdin, stdout, err := openPipes(session)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stdin.Close()\n\n\tcmd := \"scp -t \" + path\n\tdebugf(\"Running command: '%s'\\n\", cmd)\n\tif err = session.Start(cmd); err != nil {\n\t\treturn errors.Wrap(err, fmt.Sprintf(\"Error starting command '%s'\", cmd))\n\t}\n\n\treturn putFile(stdin, stdout, path, file)\n}", "func (c *Client) CloudProjectSSHKeyCreate(projectID, publicKey, name string) (types.CloudSSHKey, error) {\n\tdata := map[string]string{\n\t\t\"publicKey\": publicKey,\n\t\t\"name\": name,\n\t}\n\tsshkey := types.CloudSSHKey{}\n\treturn sshkey, c.Post(queryEscape(\"/cloud/project/%s/sshkey\", projectID), data, &sshkey)\n}", "func newTransfer() *cobra.Command {\n\tvar cluster []string\n\tvar timeout time.Duration\n\n\tcmd := &cobra.Command{\n\t\tUse: \"transfer <id>\",\n\t\tShort: \"transfer leadership to a new node.\",\n\t\tArgs: cobra.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tid, err := strconv.ParseUint(args[0], 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\t\t\tdefer cancel()\n\t\t\tif err := Transfer(ctx, &globalKeys, id, cluster); err != nil {\n\t\t\t\tfmt.Printf(\"transfer to node: %d failed: %v\\n\", id, err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\tflags := cmd.Flags()\n\tflags.StringSliceVarP(&cluster, \"cluster\", \"c\", clusterList(), \"addresses of existing cluster nodes\")\n\tflags.DurationVarP(&timeout, \"timeout\", \"t\", time.Second*60, \"time to wait for transfer to complete\")\n\treturn cmd\n}", "func newSshNativeTask(host string, cmd string, opt Options) func() (interface{}, error) {\n\tstate := &sshNativeTask{\n\t\tHost: host,\n\t\tCmd: cmd,\n\t\tOpts: opt,\n\t}\n\treturn state.run\n}", "func TestCircleCIPutFile(t *testing.T) {\n\t// Create ssh client config\n\tconfig := &ssh.ClientConfig{\n\t\tUser: \"root\",\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.Password(\"root\"),\n\t\t},\n\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t\tTimeout: 60 * time.Second,\n\t}\n\n\t// Create ssh connection\n\tconnection, err := ssh.Dial(\"tcp\", \"localhost:50022\", config)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Failed to dial: %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tdefer connection.Close()\n\n\t// Create scp client\n\tscp := new(scplib.SCPClient)\n\tscp.Permission = false // copy permission with scp flag\n\tscp.Connection = connection\n\n\t// Put ./passwd to remote machine `./passwd_2`\n\terr = scp.PutFile([]string{\"./passwd\"}, \"./passwd_2\")\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Failed to scp put: %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\t// show ./passwd_2\n\tsession, _ := connection.NewSession()\n\tsession.Run(\"cat ./passwd_2\")\n}", "func NewSSHCommand(p *config.KfParams) *cobra.Command {\n\tvar (\n\t\tdisableTTY bool\n\t\tcommand []string\n\t\tcontainer string\n\t)\n\n\tcmd := &cobra.Command{\n\t\tUse: \"ssh APP_NAME\",\n\t\tShort: \"Open a shell on an App instance.\",\n\t\tExample: `\n\t\t# Open a shell to a specific App\n\t\tkf ssh myapp\n\n\t\t# Open a shell to a specific Pod\n\t\tkf ssh pod/myapp-revhex-podhex\n\n\t\t# Start a different command with args\n\t\tkf ssh myapp -c /my/command -c arg1 -c arg2\n\t\t`,\n\t\tArgs: cobra.ExactArgs(1),\n\t\tLong: `\n\t\tOpens a shell on an App instance using the Pod exec endpoint.\n\n\t\tThis command mimics CF's SSH command by opening a connection to the\n\t\tKubernetes control plane which spawns a process in a Pod.\n\n\t\tThe command connects to an arbitrary Pod that matches the App's runtime\n\t\tlabels. If you want a specific Pod, use the pod/<podname> notation.\n\n\t\tNOTE: Traffic is encrypted between the CLI and the control plane, and\n\t\tbetween the control plane and Pod. A malicious Kubernetes control plane\n\t\tcould observe the traffic.\n\t\t`,\n\t\tValidArgsFunction: completion.AppCompletionFn(p),\n\t\tSilenceUsage: true,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tctx := cmd.Context()\n\t\t\tif err := p.ValidateSpaceTargeted(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstreamExec := execstreamer.Get(ctx)\n\n\t\t\tenableTTY := !disableTTY\n\t\t\tappName := args[0]\n\n\t\t\tpodSelector := metav1.ListOptions{}\n\t\t\tif strings.HasPrefix(appName, podPrefix) {\n\t\t\t\tpodName := strings.TrimPrefix(appName, podPrefix)\n\t\t\t\tpodSelector.FieldSelector = fields.OneTermEqualSelector(\"metadata.name\", podName).String()\n\t\t\t} else {\n\t\t\t\tappLabels := v1alpha1.AppComponentLabels(appName, \"app-server\")\n\t\t\t\tpodSelector.LabelSelector = labels.SelectorFromSet(appLabels).String()\n\t\t\t}\n\n\t\t\texecOpts := corev1.PodExecOptions{\n\t\t\t\tContainer: container,\n\t\t\t\tCommand: command,\n\t\t\t\tStdin: true,\n\t\t\t\tStdout: true,\n\t\t\t\tStderr: true,\n\t\t\t\tTTY: enableTTY,\n\t\t\t}\n\n\t\t\tt := term.TTY{\n\t\t\t\tOut: cmd.OutOrStdout(),\n\t\t\t\tIn: cmd.InOrStdin(),\n\t\t\t\tRaw: true,\n\t\t\t}\n\n\t\t\tsizeQueue := t.MonitorSize(t.GetSize())\n\n\t\t\tstreamOpts := remotecommand.StreamOptions{\n\t\t\t\tStdin: cmd.InOrStdin(),\n\t\t\t\tStdout: cmd.OutOrStdout(),\n\t\t\t\tStderr: cmd.ErrOrStderr(),\n\t\t\t\tTty: enableTTY,\n\t\t\t\tTerminalSizeQueue: sizeQueue,\n\t\t\t}\n\n\t\t\t// Set up a TTY locally if it's enabled.\n\t\t\tif fd, isTerm := dockerterm.GetFdInfo(streamOpts.Stdin); isTerm && enableTTY {\n\t\t\t\toriginalState, err := dockerterm.MakeRaw(fd)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tdefer dockerterm.RestoreTerminal(fd, originalState)\n\t\t\t}\n\n\t\t\treturn streamExec.Stream(ctx, podSelector, execOpts, streamOpts)\n\t\t},\n\t}\n\n\tcmd.Flags().StringArrayVarP(\n\t\t&command,\n\t\t\"command\",\n\t\t\"c\",\n\t\t[]string{\"/bin/bash\"},\n\t\t\"Command to run for the shell. Subsequent definitions will be used as args.\",\n\t)\n\n\tcmd.Flags().StringVar(\n\t\t&container,\n\t\t\"container\",\n\t\tv1alpha1.DefaultUserContainerName,\n\t\t\"Container to start the command in.\",\n\t)\n\n\tcmd.Flags().BoolVarP(\n\t\t&disableTTY,\n\t\t\"disable-pseudo-tty\",\n\t\t\"T\",\n\t\tfalse,\n\t\t\"Don't use a TTY when executing.\",\n\t)\n\n\treturn cmd\n}", "func sendScpCommandsToCopyFile(mode os.FileMode, fileName, contents string) func(io.WriteCloser) {\n\treturn func(input io.WriteCloser) {\n\n\t\toctalMode := \"0\" + strconv.FormatInt(int64(mode), 8)\n\n\t\t// Create a file at <filename> with Unix permissions set to <octalMost> and the file will be <len(content)> bytes long.\n\t\tfmt.Fprintln(input, \"C\"+octalMode, len(contents), fileName)\n\n\t\t// Actually send the file\n\t\tfmt.Fprint(input, contents)\n\n\t\t// End of transfer\n\t\tfmt.Fprint(input, \"\\x00\")\n\t}\n}", "func (c *Client) skopeoCopyCmd(src, dst string) string {\n\tcred := fmt.Sprintf(\"%s:%s\", c.username, c.password)\n\tsrc = fmt.Sprintf(\"%s%s\", c.transport, src)\n\tdst = fmt.Sprintf(\"%s%s\", c.transport, dst)\n\treturn fmt.Sprintf(\"skopeo copy --dest-creds %s %s %s\", cred, src, dst)\n}", "func newCreateCmd(pather command.Pather) *cobra.Command {\n\tnow := time.Now().UTC()\n\tvar flags struct {\n\t\tcsr bool\n\t\tprofile string\n\t\tcommonName string\n\t\tnotBefore flag.Time\n\t\tnotAfter flag.Time\n\t\tca string\n\t\tcaKey string\n\t\texistingKey string\n\t\tcurve string\n\t\tbundle bool\n\t\tforce bool\n\t}\n\tflags.notBefore = flag.Time{\n\t\tTime: now,\n\t\tCurrent: now,\n\t}\n\tflags.notAfter = flag.Time{\n\t\tCurrent: now,\n\t\tDefault: \"depends on profile\",\n\t}\n\n\tvar cmd = &cobra.Command{\n\t\tUse: \"create [flags] <subject-template> <cert-file> <key-file>\",\n\t\tShort: \"Create a certificate or certificate signing request\",\n\t\tExample: fmt.Sprintf(` %[1]s create --profile cp-root subject.tmpl cp-root.crt cp-root.key\n %[1]s create --ca cp-ca.crt --ca-key cp-ca.key subject.tmpl chain.pem cp-as.key\n %[1]s create --csr subject.tmpl chain.csr cp-as.key`,\n\t\t\tpather.CommandPath(),\n\t\t),\n\t\tLong: `'create' generates a certificate or a certificate signing request (CSR).\n\nThe command takes the following positional arguments:\n- <subject-template> is the template for the certificate subject distinguished name.\n- <crt-file> is the file path where the certificate or certificate requests is\n written to. The parent directory must exist and must be writable.\n- <key-file> is the file path where the fresh private key is written to. The\n parent directory must exist and must be writable.\n\nBy default, the command creates a SCION control-plane PKI AS certificate. Another\ncertificate type can be selected by providing the --profile flag. If a certificate\nchain is desired, specify the --bundle flag.\n\nA fresh key is created in the provided <key-file>, unless the --key flag is set.\nIf the --key flag is set, an existing private key is used and the <key-file> is\nignored.\n\nThe --ca and --ca-key flags are required if a AS certificate or CA certificate\nis being created. Otherwise, they are not allowed.\n\nThe --not-before and --not-after flags can either be a timestamp or a relative\ntime offset from the current time.\n\nA timestamp can be provided in two different formats: unix timestamp and\nRFC 3339 timestamp. For example, 2021-06-24T12:01:02Z represents 1 minute and 2\nseconds after the 12th hour of June 26th, 2021 in UTC.\n\nThe relative time offset can be formated as a time duration string with the\nfollowing units: y, w, d, h, m, s. Negative offsets are also allowed. For\nexample, -1h indicates the time of tool invocation minus one hour. Note that\n--not-after is relative to the current time if a relative time offset is used,\nand not to --not-before.\n\nThe <subject-template> is the template for the distinguished name of the\nrequested certificate and must either be a x.509 certificate or a JSON file.\nThe common name can be overridden by supplying the --common-name flag.\n\nIf it is a x.509 certificate, the subject of the template is used as the subject\nof the created certificate or certificate chain request.\n\nA valid example for a JSON formatted template:\n` + subjectHelp,\n\t\tArgs: cobra.RangeArgs(2, 3),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tif len(args) == 2 && flags.existingKey == \"\" {\n\t\t\t\treturn serrors.New(\"positional key file is required\")\n\t\t\t}\n\t\t\tct, err := parseCertType(flags.profile)\n\t\t\tif err != nil {\n\t\t\t\treturn serrors.WrapStr(\"parsing profile\", err)\n\t\t\t}\n\t\t\tsubject, err := createSubject(args[0], flags.commonName)\n\t\t\tif err != nil {\n\t\t\t\treturn serrors.WrapStr(\"creating subject\", err)\n\t\t\t}\n\n\t\t\t// Only check that the flags are set appropriately here.\n\t\t\t// Do the actual parsing after the usage help message is silenced.\n\t\t\tvar loadCA bool\n\t\t\tisSelfSigned := (ct == cppki.Root || ct == cppki.Regular || ct == cppki.Sensitive)\n\t\t\twithCA := (flags.ca != \"\" || flags.caKey != \"\")\n\t\t\tswitch {\n\t\t\tcase flags.csr && withCA:\n\t\t\t\treturn serrors.New(\"CA information set for CSR\")\n\t\t\tcase !flags.csr && isSelfSigned && withCA:\n\t\t\t\treturn serrors.New(\"CA information set for self-signed certificate\")\n\t\t\tdefault:\n\t\t\t\tloadCA = !isSelfSigned && !flags.csr\n\t\t\t}\n\n\t\t\tcmd.SilenceUsage = true\n\n\t\t\tvar privKey key.PrivateKey\n\t\t\tvar encodedKey []byte\n\t\t\tif flags.existingKey != \"\" {\n\t\t\t\tif privKey, err = key.LoadPrivateKey(flags.existingKey); err != nil {\n\t\t\t\t\treturn serrors.WrapStr(\"loading existing private key\", err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif privKey, err = key.GeneratePrivateKey(flags.curve); err != nil {\n\t\t\t\t\treturn serrors.WrapStr(\"creating fresh private key\", err)\n\t\t\t\t}\n\t\t\t\tif encodedKey, err = key.EncodePEMPrivateKey(privKey); err != nil {\n\t\t\t\t\treturn serrors.WrapStr(\"encoding fresh private key\", err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar caCertRaw []byte\n\t\t\tvar caCert *x509.Certificate\n\t\t\tvar caKey key.PrivateKey\n\t\t\tif loadCA {\n\t\t\t\tif caCertRaw, err = os.ReadFile(flags.ca); err != nil {\n\t\t\t\t\treturn serrors.WrapStr(\"read CA certificate\", err)\n\t\t\t\t}\n\t\t\t\tif caCert, err = parseCertificate(caCertRaw); err != nil {\n\t\t\t\t\treturn serrors.WrapStr(\"parsing CA certificate\", err)\n\t\t\t\t}\n\t\t\t\tif caKey, err = key.LoadPrivateKey(flags.caKey); err != nil {\n\t\t\t\t\treturn serrors.WrapStr(\"loading CA private key\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif isSelfSigned {\n\t\t\t\tcaKey = privKey\n\t\t\t}\n\n\t\t\tif flags.csr {\n\t\t\t\tcsr, err := CreateCSR(ct, subject, privKey)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn serrors.WrapStr(\"creating CSR\", err)\n\t\t\t\t}\n\t\t\t\tencodedCSR := pem.EncodeToMemory(&pem.Block{\n\t\t\t\t\tType: \"CERTIFICATE REQUEST\",\n\t\t\t\t\tBytes: csr,\n\t\t\t\t})\n\t\t\t\tif encodedCSR == nil {\n\t\t\t\t\tpanic(\"failed to encode CSR\")\n\t\t\t\t}\n\t\t\t\tcsrFile := args[1]\n\t\t\t\terr = file.WriteFile(csrFile, encodedCSR, 0644, file.WithForce(flags.force))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn serrors.WrapStr(\"writing CSR\", err)\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\"CSR successfully written to %q\\n\", csrFile)\n\t\t\t} else {\n\t\t\t\tcert, err := CreateCertificate(CertParams{\n\t\t\t\t\tType: ct,\n\t\t\t\t\tSubject: subject,\n\t\t\t\t\tPubKey: privKey.Public(),\n\t\t\t\t\tNotBefore: flags.notBefore.Time,\n\t\t\t\t\tNotAfter: notAfterFromFlags(ct, flags.notBefore, flags.notAfter),\n\t\t\t\t\tCAKey: caKey,\n\t\t\t\t\tCACert: caCert,\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn serrors.WrapStr(\"creating certificate\", err)\n\t\t\t\t}\n\t\t\t\tencodedCert := pem.EncodeToMemory(&pem.Block{\n\t\t\t\t\tType: \"CERTIFICATE\",\n\t\t\t\t\tBytes: cert,\n\t\t\t\t})\n\t\t\t\tif encodedCert == nil {\n\t\t\t\t\tpanic(\"failed to encode CSR\")\n\t\t\t\t}\n\t\t\t\tif flags.bundle {\n\t\t\t\t\tfmt.Println(\"Bundling certificate as certificate chain\")\n\t\t\t\t\tencodedCert = append(encodedCert, caCertRaw...)\n\t\t\t\t}\n\t\t\t\tcertFile := args[1]\n\t\t\t\terr = file.WriteFile(certFile, encodedCert, 0644, file.WithForce(flags.force))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn serrors.WrapStr(\"writing certificate\", err)\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\"Certificate successfully written to %q\\n\", certFile)\n\t\t\t}\n\n\t\t\tif encodedKey != nil {\n\t\t\t\tkeyFile := args[2]\n\t\t\t\tif err := file.CheckDirExists(filepath.Dir(keyFile)); err != nil {\n\t\t\t\t\treturn serrors.WrapStr(\"checking that directory of private key exists\", err)\n\t\t\t\t}\n\t\t\t\terr := file.WriteFile(keyFile, encodedKey, 0600, file.WithForce(flags.force))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn serrors.WrapStr(\"writing private key\", err)\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\"Private key successfully written to %q\\n\", keyFile)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tcmd.Flags().BoolVar(&flags.csr, \"csr\", false,\n\t\t\"Generate a certificate signign request instead of a certificate\",\n\t)\n\tcmd.Flags().StringVar(&flags.profile, \"profile\", \"cp-as\",\n\t\t\"The type of certificate to generate (cp-as|cp-ca|cp-root|sensitive-voting|regular-voting)\",\n\t)\n\tcmd.Flags().Var(&flags.notBefore, \"not-before\",\n\t\t`The NotBefore time of the certificate. Can either be a timestamp or an offset.\n\nIf the value is a timestamp, it is expected to either be an RFC 3339 formatted\ntimestamp or a unix timestamp. If the value is a duration, it is used as the\noffset from the current time.`,\n\t)\n\tcmd.Flags().Var(&flags.notAfter, \"not-after\",\n\t\t`The NotAfter time of the certificate. Can either be a timestamp or an offset.\n\nIf the value is a timestamp, it is expected to either be an RFC 3339 formatted\ntimestamp or a unix timestamp. If the value is a duration, it is used as the\noffset from the current time.`,\n\t)\n\tcmd.Flags().StringVar(&flags.commonName, \"common-name\", \"\",\n\t\t\"The common name that replaces the common name in the subject template\",\n\t)\n\tcmd.Flags().StringVar(&flags.ca, \"ca\", \"\",\n\t\t\"The path to the issuer certificate\",\n\t)\n\tcmd.Flags().StringVar(&flags.caKey, \"ca-key\", \"\",\n\t\t\"The path to the issuer private key used to sign the new certificate\",\n\t)\n\tcmd.Flags().StringVar(&flags.existingKey, \"key\", \"\",\n\t\t\"The path to the existing private key to use instead of creating a new one\",\n\t)\n\tcmd.Flags().StringVar(&flags.curve, \"curve\", \"P-256\",\n\t\t\"The elliptic curve to use (P-256|P-384|P-521)\",\n\t)\n\tcmd.Flags().BoolVar(&flags.bundle, \"bundle\", false,\n\t\t\"Bundle the certificate with the issuer certificate as a certificate chain\",\n\t)\n\tcmd.Flags().BoolVar(&flags.force, \"force\", false,\n\t\t\"Force overwritting existing files\",\n\t)\n\n\treturn cmd\n}", "func ParseScp(rawurl string) (*url.URL, error) {\n\tmatch := scpSyntax.FindAllStringSubmatch(rawurl, -1)\n\tif len(match) == 0 {\n\t\treturn nil, fmt.Errorf(\"no scp URL found in %q\", rawurl)\n\t}\n\tm := match[0]\n\treturn &url.URL{\n\t\tScheme: \"ssh\",\n\t\tUser: url.User(strings.TrimRight(m[1], \"@\")),\n\t\tHost: m[2],\n\t\tPath: m[3],\n\t}, nil\n}", "func ServersPush(src, dst string, cu *CommonUser, ipFile string, wt *sync.WaitGroup, ccons chan struct{}, crs chan machine.Result, timeout int) {\n\thosts, err := parseIpfile(ipFile, cu)\n\tif err != nil {\n\t\tlog.Error(\"Parse %s error, error=%s\", ipFile, err)\n\t\treturn\n\t}\n\n\tips := config.GetIps(hosts)\n\tlog.Info(\"[servers]=%v\", ips)\n\tfmt.Printf(\"[servers]=%v\\n\", ips)\n\n\tls := len(hosts)\n\tgo output.PrintResults2(crs, ls, wt, ccons, timeout)\n\n\tfor _, h := range hosts {\n\t\tccons <- struct{}{}\n\t\tserver := machine.NewScpServer(h.Ip, h.Port, h.User, h.Psw, \"scp\", src, dst, cu.force, timeout)\n\t\twt.Add(1)\n\t\tgo server.PRunScp(crs)\n\t}\n}", "func NewClient(sshc *ssh.Client) (cl *Client, err error) {\n\tlogp := \"New\"\n\tcl = &Client{}\n\n\tcl.sess, err = sshc.NewSession()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s: NewSession: %w\", logp, err)\n\t}\n\n\tcl.pipeIn, err = cl.sess.StdinPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s: StdinPipe: %w\", logp, err)\n\t}\n\tcl.pipeOut, err = cl.sess.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s: StdoutPipe: %w\", logp, err)\n\t}\n\tcl.pipeErr, err = cl.sess.StderrPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s: StderrPipe: %w\", logp, err)\n\t}\n\n\terr = cl.sess.RequestSubsystem(subsystemNameSftp)\n\tif err != nil {\n\t\tif err.Error() == \"ssh: subsystem request failed\" {\n\t\t\treturn nil, ErrSubsystem\n\t\t}\n\t\treturn nil, fmt.Errorf(\"%s: RequestSubsystem: %w\", logp, err)\n\t}\n\n\tcl.requestId = uint32(time.Now().Unix())\n\n\terr = cl.init()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s: %w\", logp, err)\n\t}\n\n\treturn cl, nil\n}", "func newSSHClientConfig(host string, section *SSHConfigFileSection, userName, identity string, agentForwarding bool) (*sshClientConfig, error) {\n\tvar (\n\t\tconfig *sshClientConfig\n\t\terr error\n\t)\n\n\tif section != nil {\n\t\tupdateFromSSHConfigFile(section, &host, &userName, &agentForwarding)\n\t}\n\n\tif agentForwarding {\n\t\tconfig, err = newSSHAgentConfig(userName)\n\t} else {\n\t\tconfig, err = newSSHDefaultConfig(userName, identity)\n\t}\n\n\tif config != nil {\n\t\tconfig.host = host\n\t}\n\treturn config, err\n}", "func NewSSH(user, host string, port int, privateKey []byte) (*SSH, error) {\n\treturn &SSH{\n\t\tuser: user,\n\t\thost: host,\n\t\tport: port,\n\t\tprivateKey: privateKey,\n\t}, nil\n}", "func New(addr string, username string, password string) (*SSHClient, error) {\n\tcfg := &ssh.ClientConfig{\n\t\tUser: username,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.Password(password),\n\t\t\tssh.KeyboardInteractive(func(user, instruction string, questions []string, echos []bool) ([]string, error) {\n\t\t\t\tif len(questions) == 0 {\n\t\t\t\t\treturn []string{}, nil\n\t\t\t\t}\n\t\t\t\tif len(questions) == 1 {\n\t\t\t\t\treturn []string{password}, nil\n\t\t\t\t}\n\t\t\t\treturn []string{}, fmt.Errorf(\"unsupported keyboard-interactive auth\")\n\t\t\t}),\n\t\t},\n\t\tHostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\t\treturn nil\n\t\t},\n\t\tTimeout: clientTimeout,\n\t}\n\n\taddr, err := checkAndBuildAddr(addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &SSHClient{addr: addr, config: cfg, lock: new(sync.Mutex)}, nil\n}", "func NewSSHClient(ctx context.Context, projectID string, repo Repo) *SSHClient {\n\treturn &SSHClient{\n\t\tprojectID: projectID,\n\t\trepo: repo,\n\t\tlog: logFromContext(ctx).WithField(\"project-id\", projectID),\n\t}\n}", "func (config *SFTPConfig) New(name string, params utils.Params) (source *SFTPSource, err error) {\n\tif config.Filter == nil {\n\t\tconfig.Filter = &FilterConfig{}\n\t}\n\terr = config.Format(params)\n\tif err != nil {\n\t\treturn\n\t}\n\tvar filter *Filter\n\tfilter, err = config.Filter.New()\n\tif err != nil {\n\t\treturn\n\t}\n\tlog, err := logs.NewLog(name)\n\tif err != nil {\n\t\treturn\n\t}\n\tsource = &SFTPSource{\n\t\tname: name,\n\t\tSFTPConfig: config,\n\t\tfiles: make(chan Entry),\n\t\tfilter: filter,\n\t\tlog: log,\n\t\tparams: params,\n\t}\n\treturn\n}", "func (n *Node) SCPFileToNode(localPath, remotePath string) error {\n\tsigner, err := ssh.ParsePrivateKey(n.SSHKey)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tauths := []ssh.AuthMethod{ssh.PublicKeys([]ssh.Signer{signer}...)}\n\n\tcfg := &ssh.ClientConfig{\n\t\tUser: n.SSHUser,\n\t\tAuth: auths,\n\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t}\n\tcfg.SetDefaults()\n\n\tclient, err := ssh.Dial(\"tcp\", n.PublicIPAddress+\":22\", cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer client.Close()\n\n\tsftp, err := sftp.NewClient(client)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer sftp.Close()\n\n\tlocalFile, err := os.Open(localPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer localFile.Close()\n\n\tremoteFile, err := sftp.Create(remotePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer remoteFile.Close()\n\n\tif _, err := remoteFile.ReadFrom(localFile); err != nil {\n\t\treturn err\n\t}\n\n\treturn err\n}", "func New(dst, src string) *Sync {\n\treturn &Sync{\n\t\tVerbose: true,\n\t\tDst: dst,\n\t\tSrc: src,\n\t}\n}", "func NewSshKey(ctx *pulumi.Context,\n\tname string, args *SshKeyArgs, opts ...pulumi.ResourceOpt) (*SshKey, error) {\n\tif args == nil || args.Body == nil {\n\t\treturn nil, errors.New(\"missing required argument 'Body'\")\n\t}\n\tif args == nil || args.ServerId == nil {\n\t\treturn nil, errors.New(\"missing required argument 'ServerId'\")\n\t}\n\tif args == nil || args.UserName == nil {\n\t\treturn nil, errors.New(\"missing required argument 'UserName'\")\n\t}\n\tinputs := make(map[string]interface{})\n\tif args == nil {\n\t\tinputs[\"body\"] = nil\n\t\tinputs[\"serverId\"] = nil\n\t\tinputs[\"userName\"] = nil\n\t} else {\n\t\tinputs[\"body\"] = args.Body\n\t\tinputs[\"serverId\"] = args.ServerId\n\t\tinputs[\"userName\"] = args.UserName\n\t}\n\ts, err := ctx.RegisterResource(\"aws:transfer/sshKey:SshKey\", name, true, inputs, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &SshKey{s: s}, nil\n}", "func (c *Client) Upload(local, remote string) error {\n\tclient, err := sftp.NewClient(c.SSHClient)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer client.Close()\n\n\tlocalFile, err := os.Open(local)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer localFile.Close()\n\n\tremoteFile, err := client.Create(remote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = io.Copy(remoteFile, localFile)\n\treturn err\n}", "func New(ctx context.Context, opts *Options) (blob.Storage, error) {\n\tconfig, err := createSSHConfig(opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taddr := fmt.Sprintf(\"%s:%d\", opts.Host, opts.Port)\n\n\tconn, err := ssh.Dial(\"tcp\", addr, config)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to dial [%s]: %+v\", addr, config)\n\t}\n\n\tc, err := psftp.NewClient(conn, psftp.MaxPacket(packetSize))\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to create sftp client\")\n\t}\n\n\tif _, err = c.Stat(opts.Path); err != nil {\n\t\tif isNotExist(err) {\n\t\t\tif err = c.MkdirAll(opts.Path); err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"cannot create path\")\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, errors.Wrapf(err, \"path doesn't exist: %s\", opts.Path)\n\t\t}\n\t}\n\n\tr := &sftpStorage{\n\t\tsharded.Storage{\n\t\t\tImpl: &sftpImpl{\n\t\t\t\tOptions: *opts,\n\t\t\t\tconn: conn,\n\t\t\t\tcli: c,\n\t\t\t},\n\t\t\tRootPath: opts.Path,\n\t\t\tSuffix: fsStorageChunkSuffix,\n\t\t\tShards: opts.shards(),\n\t\t},\n\t}\n\n\treturn r, nil\n}", "func create(u string) (backend.Backend, error) {\n\turl, err := url.Parse(u)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif url.Scheme == \"\" {\n\t\treturn backend.CreateLocal(url.Path)\n\t}\n\n\targs := []string{url.Host}\n\tif url.User != nil && url.User.Username() != \"\" {\n\t\targs = append(args, \"-l\")\n\t\targs = append(args, url.User.Username())\n\t}\n\targs = append(args, \"-s\")\n\targs = append(args, \"sftp\")\n\treturn backend.CreateSFTP(url.Path[1:], \"ssh\", args...)\n}", "func NewSNSTopic(properties SNSTopicProperties, deps ...interface{}) SNSTopic {\n\treturn SNSTopic{\n\t\tType: \"AWS::SNS::Topic\",\n\t\tProperties: properties,\n\t\tDependsOn: deps,\n\t}\n}", "func New(psof ...param.ParamSetOptFunc) (*param.ParamSet, error) {\n\topts := make([]param.ParamSetOptFunc, 0, len(psof)+1)\n\topts = append(opts, param.SetHelper(&phelp.SH))\n\topts = append(opts, psof...)\n\treturn param.NewSet(opts...)\n}", "func StreamConnectCommand(args []string) {\n\tif len(args) == 0 {\n\t\tlog.Fatal(\"At least one argument must be supplied to use this command\")\n\t}\n\n\tcs := strings.Join(args, \" \")\n\tpn := conf.GetConfig().Tokaido.Project.Name + \".tok\"\n\n\tutils.StreamOSCmd(\"ssh\", []string{\"-q\", \"-o UserKnownHostsFile=/dev/null\", \"-o StrictHostKeyChecking=no\", pn, \"-C\", cs}...)\n}", "func (s3pc *s3put) Execute(ctx context.Context,\n\tcomm client.Communicator, logger client.LoggerProducer, conf *internal.TaskConfig) error {\n\n\t// expand necessary params\n\tif err := s3pc.expandParams(conf); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\t// re-validate command here, in case an expansion is not defined\n\tif err := s3pc.validate(); err != nil {\n\t\treturn errors.Wrap(err, \"validating expanded parameters\")\n\t}\n\tif conf.Task.IsPatchRequest() && !s3pc.isPatchable {\n\t\tlogger.Task().Infof(\"Skipping command '%s' because it is not patchable and this task is part of a patch.\", s3pc.Name())\n\t\treturn nil\n\t}\n\tif !conf.Task.IsPatchRequest() && s3pc.isPatchOnly {\n\t\tlogger.Task().Infof(\"Skipping command '%s' because the command is patch only and this task is not part of a patch.\", s3pc.Name())\n\t\treturn nil\n\t}\n\n\t// create pail bucket\n\thttpClient := utility.GetHTTPClient()\n\thttpClient.Timeout = s3HTTPClientTimeout\n\tdefer utility.PutHTTPClient(httpClient)\n\tif err := s3pc.createPailBucket(httpClient); err != nil {\n\t\treturn errors.Wrap(err, \"connecting to S3\")\n\t}\n\n\tif err := s3pc.bucket.Check(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"checking bucket\")\n\t}\n\n\ts3pc.taskdata = client.TaskData{ID: conf.Task.Id, Secret: conf.Task.Secret}\n\n\tif !s3pc.shouldRunForVariant(conf.BuildVariant.Name) {\n\t\tlogger.Task().Infof(\"Skipping S3 put of local file '%s' for variant '%s'.\",\n\t\t\ts3pc.LocalFile, conf.BuildVariant.Name)\n\t\treturn nil\n\t}\n\n\tif s3pc.isPrivate(s3pc.Visibility) {\n\t\tlogger.Task().Infof(\"Putting private files into S3.\")\n\n\t} else {\n\t\tif s3pc.isMulti() {\n\t\t\tlogger.Task().Infof(\"Putting files matching filter '%s' into path '%s' in S3 bucket '%s'.\",\n\t\t\t\ts3pc.LocalFilesIncludeFilter, s3pc.RemoteFile, s3pc.Bucket)\n\t\t} else if s3pc.isPublic() {\n\t\t\tlogger.Task().Infof(\"Putting local file '%s' into path '%s/%s' (%s).\", s3pc.LocalFile, s3pc.Bucket, s3pc.RemoteFile, agentutil.S3DefaultURL(s3pc.Bucket, s3pc.RemoteFile))\n\t\t} else {\n\t\t\tlogger.Task().Infof(\"Putting local file '%s' into '%s/%s'.\", s3pc.LocalFile, s3pc.Bucket, s3pc.RemoteFile)\n\t\t}\n\t}\n\n\terrChan := make(chan error)\n\tgo func() {\n\t\terr := errors.WithStack(s3pc.putWithRetry(ctx, comm, logger))\n\t\tselect {\n\t\tcase errChan <- err:\n\t\t\treturn\n\t\tcase <-ctx.Done():\n\t\t\tlogger.Task().Infof(\"Context canceled waiting for s3 put: %s.\", ctx.Err())\n\t\t\treturn\n\t\t}\n\t}()\n\n\tselect {\n\tcase err := <-errChan:\n\t\treturn err\n\tcase <-ctx.Done():\n\t\tlogger.Execution().Infof(\"Canceled while running command '%s': %s.\", s3pc.Name(), ctx.Err())\n\t\treturn nil\n\t}\n\n}", "func newFilePutCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"put\",\n\t\tShort: \"run file Put gNOI RPC\",\n\t\tPreRunE: gApp.PreRunEFilePut,\n\n\t\tRunE: gApp.RunEFilePut,\n\t\tSilenceUsage: true,\n\t}\n\tgApp.InitFilePutFlags(cmd)\n\treturn cmd\n}", "func NewPsCommand() *Ps {\n\treturn &Ps{\n\t\tcommon: &commonFlags{},\n\t\tclientGetter: getter.New(),\n\t}\n}", "func NewPsCommand() *Ps {\n\treturn &Ps{\n\t\tcommon: &commonFlags{},\n\t\tclientGetter: getter.New(),\n\t}\n}", "func newSSHClient(user, pass, host string) (*ssh.Client, error) {\n\tsshConfig := &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: []ssh.AuthMethod{ssh.Password(pass)},\n\t\tHostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\t\treturn nil\n\t\t},\n\t}\n\tsshConfig.HostKeyCallback = ssh.InsecureIgnoreHostKey()\n\tclient, err := ssh.Dial(\"tcp\", host, sshConfig)\n\tif err != nil {\n\t\treturn nil, errors.New(strings.Join([]string{\"ssh dial error: \", err.Error()}, \"\"))\n\t}\n\treturn client, nil\n}", "func New(host, port, user, pass string) *SSHer {\n\treturn &SSHer{\n\t\tHost: host,\n\t\tPort: port,\n\t\tUser: user,\n\t\tPass: pass,\n\t}\n}", "func (client *SSHClient) Upload(src io.Reader, dst string, mode uint32) error {\n\tfileContent, err := ioutil.ReadAll(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsession, err := client.cryptoClient.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer session.Close()\n\n\tw, err := session.StdinPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terrorChan := make(chan error, 2)\n\tremoteDir := path.Dir(dst)\n\tremoteFileName := path.Base(dst)\n\n\twg := sync.WaitGroup{}\n\twg.Add(2)\n\n\tgo func() {\n\t\tdefer w.Close()\n\t\tdefer wg.Done()\n\n\t\t// Signals to the SSH receiver that content is being passed.\n\t\tfmt.Fprintf(w, \"C%#o %d %s\\n\", mode, len(fileContent), remoteFileName)\n\t\t_, err = io.Copy(w, bytes.NewReader(fileContent))\n\t\tif err != nil {\n\t\t\terrorChan <- err\n\t\t\treturn\n\t\t}\n\n\t\t// End SSH transfer\n\t\tfmt.Fprint(w, \"\\x00\")\n\t}()\n\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tif err := session.Run(fmt.Sprintf(\"/usr/bin/scp -t %s\", remoteDir)); err != nil {\n\t\t\terrorChan <- err\n\t\t\treturn\n\t\t}\n\t}()\n\n\twg.Wait()\n\n\tselect {\n\tcase err := <-errorChan:\n\t\treturn err\n\tdefault:\n\t\tbreak\n\t}\n\n\treturn nil\n}", "func RDTSCP() { ctx.RDTSCP() }", "func (u *SSHUploader) Put(localPath string) error {\n\treturn u.SSHConfig.Scp(localPath, u.RemoteLocation)\n}", "func NewSSHAuthMethod(identityFile, knownHostsFile []byte) (AuthMethod, error) {\n\tif len(identityFile) == 0 || len(knownHostsFile) == 0 {\n\t\treturn nil, errors.New(\"invalid identityFile, knownHostsFile options\")\n\t}\n\n\tpk, err := ssh.NewPublicKeys(\"git\", identityFile, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcallback, err := knownhosts.New(knownHostsFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpk.HostKeyCallback = callback\n\n\treturn &authMethod{\n\t\tAuthMethod: pk,\n\t\tt: gitprovider.TransportTypeGit,\n\t}, nil\n}", "func newAssign() *cobra.Command {\n\tvar cluster []string\n\tvar timeout time.Duration\n\n\troles := map[string]int{\n\t\tclient.Voter.String(): int(Voter),\n\t\tclient.Spare.String(): int(Spare),\n\t\tclient.StandBy.String(): int(Standby),\n\t}\n\tchoices := &FlagChoice{choices: mapKeys(roles), chosen: client.Voter.String()}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"assign <id>\",\n\t\tShort: \"assign a role to a node (voter, spare, or standby).\",\n\t\tArgs: cobra.MinimumNArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tr, err := nodeRole(choices.chosen)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\t\t\tdefer cancel()\n\n\t\t\tfor _, arg := range args {\n\t\t\t\tid, err := strconv.ParseUint(arg, 10, 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalln(err)\n\t\t\t\t}\n\t\t\t\tif err := Assign(ctx, &globalKeys, uint64(id), client.NodeRole(r), cluster); err != nil {\n\t\t\t\t\tlog.Fatalln(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\tflags := cmd.Flags()\n\tflags.StringSliceVarP(&cluster, \"cluster\", \"c\", clusterList(), \"addresses of existing cluster nodes\")\n\tflags.DurationVarP(&timeout, \"timeout\", \"t\", time.Second*60, \"time to wait for transfer to complete\")\n\tflags.VarP(choices, \"role\", \"r\", \"server role\")\n\treturn cmd\n}", "func New(URL, consumerKey, privateKey string) *StashConsumer {\n\ts := &StashConsumer{\n\t\tURL: URL,\n\t\tConsumerKey: consumerKey,\n\t\tPrivateRSAKey: privateKey,\n\t}\n\ts.consumer = &oauth1.Consumer{\n\t\tRequestTokenURL: URL + \"/plugins/servlet/oauth/request-token\",\n\t\tAuthorizationURL: URL + \"/plugins/servlet/oauth/authorize\",\n\t\tAccessTokenURL: URL + \"/plugins/servlet/oauth/access-token\",\n\t\tCallbackURL: oauth1.OOB,\n\t\tConsumerKey: consumerKey,\n\t\tConsumerPrivateKeyPem: privateKey,\n\t}\n\treturn s\n}", "func (scp *SCP) String() string {\n\treturn fmt.Sprintf(\"SYNC SCP %s %s:%s\", scp.Source, scp.TargetHost, scp.Destination)\n}", "func (z *zfsctl) Clone(ctx context.Context, name string, properties map[string]string, source string) *execute {\n\targs := []string{\"clone\", \"-p\"}\n\tif properties != nil {\n\t\tkv := \"-o \"\n\t\tfor k, v := range properties {\n\t\t\tkv += fmt.Sprintf(\"%s=%s \", k, v)\n\t\t}\n\t\targs = append(args, kv)\n\t}\n\targs = append(args, source, name)\n\treturn &execute{ctx: ctx, name: z.cmd, args: args}\n}", "func CreateSSHKey(label, key string) error {\n\tclient, err := NewPacketClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq := packngo.SSHKeyCreateRequest{\n\t\tKey: key,\n\t\tLabel: label,\n\t}\n\n\tk, _, err := client.SSHKeys.Create(&req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\te := MarshallAndPrint(k)\n\treturn e\n}", "func (c *Context) RDTSCP() {\n\tc.addinstruction(x86.RDTSCP())\n}", "func NewCommand(s genopts.IOStreams) *cobra.Command {\n\tcfg := newConfig(s)\n\tcmd := &cobra.Command{\n\t\tUse: \"kubectl-ssh [flags] [node-name]\",\n\t\tShort: \"SSH into a specific Kubernetes node in a cluster or into an arbitrary node matching selectors\",\n\t\tExample: fmt.Sprintf(usage, \"kubectl-ssh\"),\n\t\tSilenceUsage: true,\n\t}\n\tcmd.Flags().StringVar(&cfg.Login, \"login\", os.Getenv(\"KUBECTL_SSH_DEFAULT_USER\"),\n\t\t`Specifies the user to log in as on the remote machine (defaults to KUBECTL_SSH_DEFAULT_USER environment)`)\n\n\tr := &runner{\n\t\tconfig: cfg,\n\t}\n\tr.Bind(cmd)\n\treturn cmd\n}", "func Recv(hostport string, config *ssh.ClientConfig, filename string) (content []byte, err error) {\n\tclient, err := ssh.Dial(\"tcp\", hostport, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Make sure we close the client connection\n\tdefer func() {\n\t\tcloseErr := client.Close()\n\t\tif closeErr != nil {\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"%w, and failed to close ssh connection: %w\", err, closeErr)\n\t\t\t} else {\n\t\t\t\terr = fmt.Errorf(\"failed to close ssh connection: %w\", closeErr)\n\t\t\t}\n\t\t}\n\t}()\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twrite, err := session.StdinPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tread, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstream := readWriter{Reader: read, Writer: write}\n\n\tif err = session.Start(\"scp -qf \" + filename); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar file scpFile\n\tfile, err = readFile(stream)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = write.Close(); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to close write stream: %w\", err)\n\t}\n\n\tif err = session.Wait(); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to wait for scp: %w\", err)\n\t}\n\n\t// Set this so the defer can nil it\n\tcontent = file.Contents\n\treturn content, err\n}", "func (ks *KopiaSnapshotter) ConnectOrCreateS3WithServer(serverAddr, bucketName, pathPrefix string) (*exec.Cmd, error) {\n\treturn nil, nil\n}", "func (c *Connection) CopyFrom(hostname, path string) error {\n\tremoteCommand := fmt.Sprintf(\"scp -o StrictHostKeyChecking=no %s:%s /tmp/%s-%s\", hostname, path, hostname, filepath.Base(path))\n\tconnectString := fmt.Sprintf(\"%s@%s\", c.User, c.Host)\n\tcmd := exec.Command(\"ssh\", \"-A\", \"-i\", c.PrivateKeyPath, \"-o\", \"ConnectTimeout=30\", \"-o\", \"StrictHostKeyChecking=no\", connectString, \"-p\", c.Port, remoteCommand)\n\tutil.PrintCommand(cmd)\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tlog.Printf(\"Error output:%s\\n\", out)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (a SSHKeysApi) CreateSSHKey_1(id string, sshKey SshKeyInput) (*SshKey, *APIResponse, error) {\n\n\tvar localVarHttpMethod = strings.ToUpper(\"Post\")\n\t// create path and map variables\n\tlocalVarPath := a.Configuration.BasePath + \"/projects/{id}/ssh-keys\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"id\"+\"}\", fmt.Sprintf(\"%v\", id), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := make(map[string]string)\n\tvar localVarPostBody interface{}\n\tvar localVarFileName string\n\tvar localVarFileBytes []byte\n\t// authentication '(x_auth_token)' required\n\t// set key with prefix in header\n\tlocalVarHeaderParams[\"X-Auth-Token\"] = a.Configuration.GetAPIKeyWithPrefix(\"X-Auth-Token\")\n\t// add default headers if any\n\tfor key := range a.Configuration.DefaultHeader {\n\t\tlocalVarHeaderParams[key] = a.Configuration.DefaultHeader[key]\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/json\", }\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\n\t\t\"application/json\",\n\t\t}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &sshKey\n\tvar successPayload = new(SshKey)\n\tlocalVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\n\tvar localVarURL, _ = url.Parse(localVarPath)\n\tlocalVarURL.RawQuery = localVarQueryParams.Encode()\n\tvar localVarAPIResponse = &APIResponse{Operation: \"CreateSSHKey_0\", Method: localVarHttpMethod, RequestURL: localVarURL.String()}\n\tif localVarHttpResponse != nil {\n\t\tlocalVarAPIResponse.Response = localVarHttpResponse.RawResponse\n\t\tlocalVarAPIResponse.Payload = localVarHttpResponse.Body()\n\t}\n\n\tif err != nil {\n\t\treturn successPayload, localVarAPIResponse, err\n\t}\n\terr = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)\n\treturn successPayload, localVarAPIResponse, err\n}", "func NewSUT(runFunc RunFunc, routables []routable.Contract) (context.CancelFunc, *sync.WaitGroup, *mux.Router) {\n\tvar wg sync.WaitGroup\n\tctx, cancel := context.WithCancel(context.Background())\n\tmuxRouter := mux.NewRouter()\n\n\trunFunc(ctx, cancel, muxRouter, routables, nil)\n\n\treturn cancel, &wg, muxRouter\n}", "func ExampleDscpConfigurationClient_BeginCreateOrUpdate() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armnetwork.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpoller, err := clientFactory.NewDscpConfigurationClient().BeginCreateOrUpdate(ctx, \"rg1\", \"mydscpconfig\", armnetwork.DscpConfiguration{\n\t\tLocation: to.Ptr(\"eastus\"),\n\t\tProperties: &armnetwork.DscpConfigurationPropertiesFormat{\n\t\t\tQosDefinitionCollection: []*armnetwork.QosDefinition{\n\t\t\t\t{\n\t\t\t\t\tDestinationIPRanges: []*armnetwork.QosIPRange{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tEndIP: to.Ptr(\"127.0.10.2\"),\n\t\t\t\t\t\t\tStartIP: to.Ptr(\"127.0.10.1\"),\n\t\t\t\t\t\t}},\n\t\t\t\t\tDestinationPortRanges: []*armnetwork.QosPortRange{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tEnd: to.Ptr[int32](15),\n\t\t\t\t\t\t\tStart: to.Ptr[int32](15),\n\t\t\t\t\t\t}},\n\t\t\t\t\tMarkings: []*int32{\n\t\t\t\t\t\tto.Ptr[int32](1)},\n\t\t\t\t\tSourceIPRanges: []*armnetwork.QosIPRange{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tEndIP: to.Ptr(\"127.0.0.2\"),\n\t\t\t\t\t\t\tStartIP: to.Ptr(\"127.0.0.1\"),\n\t\t\t\t\t\t}},\n\t\t\t\t\tSourcePortRanges: []*armnetwork.QosPortRange{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tEnd: to.Ptr[int32](11),\n\t\t\t\t\t\t\tStart: to.Ptr[int32](10),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tEnd: to.Ptr[int32](21),\n\t\t\t\t\t\t\tStart: to.Ptr[int32](20),\n\t\t\t\t\t\t}},\n\t\t\t\t\tProtocol: to.Ptr(armnetwork.ProtocolTypeTCP),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tDestinationIPRanges: []*armnetwork.QosIPRange{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tEndIP: to.Ptr(\"12.0.10.2\"),\n\t\t\t\t\t\t\tStartIP: to.Ptr(\"12.0.10.1\"),\n\t\t\t\t\t\t}},\n\t\t\t\t\tDestinationPortRanges: []*armnetwork.QosPortRange{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tEnd: to.Ptr[int32](52),\n\t\t\t\t\t\t\tStart: to.Ptr[int32](51),\n\t\t\t\t\t\t}},\n\t\t\t\t\tMarkings: []*int32{\n\t\t\t\t\t\tto.Ptr[int32](2)},\n\t\t\t\t\tSourceIPRanges: []*armnetwork.QosIPRange{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tEndIP: to.Ptr(\"12.0.0.2\"),\n\t\t\t\t\t\t\tStartIP: to.Ptr(\"12.0.0.1\"),\n\t\t\t\t\t\t}},\n\t\t\t\t\tSourcePortRanges: []*armnetwork.QosPortRange{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tEnd: to.Ptr[int32](12),\n\t\t\t\t\t\t\tStart: to.Ptr[int32](11),\n\t\t\t\t\t\t}},\n\t\t\t\t\tProtocol: to.Ptr(armnetwork.ProtocolTypeUDP),\n\t\t\t\t}},\n\t\t},\n\t}, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\tres, err := poller.PollUntilDone(ctx, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to pull the result: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.DscpConfiguration = armnetwork.DscpConfiguration{\n\t// \tName: to.Ptr(\"mydscpConfig\"),\n\t// \tType: to.Ptr(\"Microsoft.Network/dscpConfiguration\"),\n\t// \tID: to.Ptr(\"/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/dscpConfiguration/mydscpConfig\"),\n\t// \tLocation: to.Ptr(\"eastus\"),\n\t// \tProperties: &armnetwork.DscpConfigurationPropertiesFormat{\n\t// \t\tAssociatedNetworkInterfaces: []*armnetwork.Interface{\n\t// \t\t},\n\t// \t\tProvisioningState: to.Ptr(armnetwork.ProvisioningStateSucceeded),\n\t// \t\tQosCollectionID: to.Ptr(\"0f8fad5b-d9cb-469f-a165-70867728950e\"),\n\t// \t\tQosDefinitionCollection: []*armnetwork.QosDefinition{\n\t// \t\t\t{\n\t// \t\t\t\tDestinationIPRanges: []*armnetwork.QosIPRange{\n\t// \t\t\t\t\t{\n\t// \t\t\t\t\t\tEndIP: to.Ptr(\"127.0.10.2\"),\n\t// \t\t\t\t\t\tStartIP: to.Ptr(\"127.0.10.1\"),\n\t// \t\t\t\t}},\n\t// \t\t\t\tDestinationPortRanges: []*armnetwork.QosPortRange{\n\t// \t\t\t\t\t{\n\t// \t\t\t\t\t\tEnd: to.Ptr[int32](62),\n\t// \t\t\t\t\t\tStart: to.Ptr[int32](61),\n\t// \t\t\t\t}},\n\t// \t\t\t\tMarkings: []*int32{\n\t// \t\t\t\t\tto.Ptr[int32](1)},\n\t// \t\t\t\t\tSourceIPRanges: []*armnetwork.QosIPRange{\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tEndIP: to.Ptr(\"127.0.0.2\"),\n\t// \t\t\t\t\t\t\tStartIP: to.Ptr(\"127.0.0.1\"),\n\t// \t\t\t\t\t}},\n\t// \t\t\t\t\tSourcePortRanges: []*armnetwork.QosPortRange{\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tEnd: to.Ptr[int32](12),\n\t// \t\t\t\t\t\t\tStart: to.Ptr[int32](11),\n\t// \t\t\t\t\t}},\n\t// \t\t\t\t\tProtocol: to.Ptr(armnetwork.ProtocolTypeTCP),\n\t// \t\t\t\t},\n\t// \t\t\t\t{\n\t// \t\t\t\t\tDestinationIPRanges: []*armnetwork.QosIPRange{\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tEndIP: to.Ptr(\"12.0.10.2\"),\n\t// \t\t\t\t\t\t\tStartIP: to.Ptr(\"12.0.10.1\"),\n\t// \t\t\t\t\t}},\n\t// \t\t\t\t\tDestinationPortRanges: []*armnetwork.QosPortRange{\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tEnd: to.Ptr[int32](52),\n\t// \t\t\t\t\t\t\tStart: to.Ptr[int32](51),\n\t// \t\t\t\t\t}},\n\t// \t\t\t\t\tMarkings: []*int32{\n\t// \t\t\t\t\t\tto.Ptr[int32](2)},\n\t// \t\t\t\t\t\tSourceIPRanges: []*armnetwork.QosIPRange{\n\t// \t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\tEndIP: to.Ptr(\"12.0.0.2\"),\n\t// \t\t\t\t\t\t\t\tStartIP: to.Ptr(\"12.0.0.1\"),\n\t// \t\t\t\t\t\t}},\n\t// \t\t\t\t\t\tSourcePortRanges: []*armnetwork.QosPortRange{\n\t// \t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\tEnd: to.Ptr[int32](12),\n\t// \t\t\t\t\t\t\t\tStart: to.Ptr[int32](11),\n\t// \t\t\t\t\t\t}},\n\t// \t\t\t\t\t\tProtocol: to.Ptr(armnetwork.ProtocolTypeUDP),\n\t// \t\t\t\t}},\n\t// \t\t\t},\n\t// \t\t}\n}", "func New(merge bool) *schg {\n\treturn &schg{services: make(map[string]string), merge: merge}\n}", "func (r Runner) ScpFile(deploymentName, source, target string) error {\n\toutput, err := r.boshExec(\"-d\", deploymentName, \"scp\", source, target)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to SCP file from %s to %s (%s): %w\", source, target, output, err)\n\t}\n\treturn nil\n}", "func NewCmdSimpleFSPs(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command {\n\treturn cli.Command{\n\t\tName: \"ps\",\n\t\tUsage: \"list running operations\",\n\t\tAction: func(c *cli.Context) {\n\t\t\tcl.ChooseCommand(&CmdSimpleFSPs{Contextified: libkb.NewContextified(g)}, \"ps\", c)\n\t\t\tcl.SetNoStandalone()\n\t\t},\n\t}\n}", "func NewSSHExecutor(c SSHConfig, sudo bool) *SSHExecutor {\n\te := new(SSHExecutor)\n\te.Initialize(c)\n\te.Locale = \"C\" // default locale, hard coded for now\n\te.Sudo = sudo\n\treturn e\n}", "func NewCmdCreateKeypair(f *util.Factory, out io.Writer) *cobra.Command {\n\toptions := &CreateKeypairOptions{}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"keypair {KEYSET | all}\",\n\t\tShort: createKeypairShort,\n\t\tLong: createKeypairLong,\n\t\tExample: createKeypairExample,\n\t\tArgs: func(cmd *cobra.Command, args []string) error {\n\t\t\toptions.ClusterName = rootCommand.ClusterName(true)\n\n\t\t\tif options.ClusterName == \"\" {\n\t\t\t\treturn fmt.Errorf(\"--name is required\")\n\t\t\t}\n\n\t\t\tif len(args) == 0 {\n\t\t\t\treturn fmt.Errorf(\"must specify name of keyset to add keypair to\")\n\t\t\t}\n\n\t\t\toptions.Keyset = args[0]\n\n\t\t\tif len(args) != 1 {\n\t\t\t\treturn fmt.Errorf(\"can only add to one keyset at a time\")\n\t\t\t}\n\n\t\t\tif options.Keyset == \"all\" {\n\t\t\t\tif options.CertPath != \"\" {\n\t\t\t\t\treturn fmt.Errorf(\"cannot specify --cert with \\\"all\\\"\")\n\t\t\t\t}\n\t\t\t\tif options.PrivateKeyPath != \"\" {\n\t\t\t\t\treturn fmt.Errorf(\"cannot specify --key with \\\"all\\\"\")\n\t\t\t\t}\n\t\t\t\tif options.Primary {\n\t\t\t\t\treturn fmt.Errorf(\"cannot specify --primary with \\\"all\\\"\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t\tValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\t\t\treturn completeCreateKeypair(cmd.Context(), f, options, args, toComplete)\n\t\t},\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn RunCreateKeypair(cmd.Context(), f, out, options)\n\t\t},\n\t}\n\n\tcmd.Flags().StringVar(&options.CertPath, \"cert\", options.CertPath, \"Path to CA certificate\")\n\tcmd.Flags().StringVar(&options.PrivateKeyPath, \"key\", options.PrivateKeyPath, \"Path to CA private key\")\n\tcmd.Flags().BoolVar(&options.Primary, \"primary\", options.Primary, \"Make the keypair the one used to issue certificates\")\n\n\treturn cmd\n}", "func copyConnect(user, host string, port int) (*sftp.Client, error) {\n\tvar (\n\t\tauth \t\t\t[]ssh.AuthMethod\n\t\taddr \t\t\tstring\n\t\tclientConfig \t*ssh.ClientConfig\n\t\tsshClient \t\t*ssh.Client\n\t\tsftpClient \t\t*sftp.Client\n\t\terr \t\t\terror\n\t)\n\tauth = make([]ssh.AuthMethod, 0)\n\ttestPrivateKeys, err := ssh.ParseRawPrivateKey([]byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEApnIg4Q/g2thAR3vAUw6EPjqgWIEJ7+FZ+AQZtHUc7b920VJI\n7JPmZ1xwdUArlCpQIMAt6mAwV9Z/C+Nc9qIpIeQwKaAd6YWVdr3jFyHLC9rqIT2g\nVifCDnMkSnV7Lvuu5QTvgURGOYpyUhUDJBdBY4YAu9q1ITy35oB0xLh1vUCwuDxI\noM5lMc+HsPjf4/SyfyAacBuoD7BvAJsxJ6xuXBaIlmWcw8o76O/Y5PGcYKPS9/bI\nrN8TrstuWILp2Nvi4WoxVMIQ98i1S6jM47arI+vNGlFrwolrCanH8GBj1NOBh4BF\nJwJisi0Z3+RrtxOVRtgZ9S/tKdK73X6EpbN4hwIDAQABAoIBAAuBRAiKgm5eGENY\nqHiVPkrW3pJ/iOJN31wnXGd+2NsOKvZZC7Vem8R1PUi9gMWjDxrUbdgPggfwSaPW\nuWxK1TEEhte5u5eSpjwo7/N/YHuXTCu0CMsrwFwjVVTYPgWHXBV0e+GhiIEdsr09\nupPaD6kDcDWL7o03lzaVlnyqi2jjXT6kUDyEFCbIAGtoxaYf3clT5e30FnyZhiCH\nm8/Qqv5M1wcVIVdsItHqMsQXQF34eT/Lg3r/Ui1bQcUldc6yYjGpC08EdDNKhGT2\nf2QwAv7UJ+GB8RNl12w3fAh3ReuiW8NEtDQ1nuSahkX5YlIWkqRDOd6Sjrg1ZkfW\nu0/zPZECgYEA2m+w90vb3ui7M/Q0AYJivo88YKhT3ismQs2+CkkgWJ7IohJj3VSh\nREljeAwEVEKv8G8lXgjTNKQ+B4sPFckIvIWGkwo7cuerIwn9n41K20oGb6gEl0jW\nmVbhv0dy6yfp8deBCOZB4YgonXWsuv4lw8DaUoakGxZgFfChjH0VvbUCgYEAwxGj\nrmq+RQWYYna9WWn2GPEJoX0SBU39pHQYBKfQ++pMIUrrryCjPvBNnIICng82RjTp\nMU8BvudvDCJgj3J79TDetBnwVt8/nAGIkleyuWzDMQwF7khBS9/TqUUqmH88GmOt\n40BPThCBx8YgKiPpmGYgPnUww1bqpvxKT9O0IssCgYEAjFH7qKD+mW9/8pwJXH7Z\n1/hDnQQE/E9TwM5SKmFXehZmZFbT+DaJckiCsXdmwIomY5nCs2mP490uS8I06pW+\nGvzbulF0ZxgTg+rDFl+5mq0u/UM9z8FmuhJp6mqHlDCLxGPf7EuePrctABm74FOr\nBtk4ZpM/kHcLOozd+lXQRZECgYBipWr26zgpQ3kaYh3DN9iiKFLMfak9UYFxRtxW\njl8a5hN1yqOBPqoPTAqTmROlxt+VhXBf5Spm1jbMFh5qrGSPTBVzUqK968wJIqVk\nDEFvj9bt2LyvEY8jxZ8OPNIbqExGtB3djEoOmj5nPoRJizu4O/0WWME+J5gmtfMG\nh3LTHQKBgDlITGqdIM4Pp54X5ppOW9S55yaAMBJUUhgUsJ73vEcQsBCZ8xkJXg/Q\nmuPfcFzSD/IgeFoWxYrJIk0CBov3ah+14z5YV1JoKIXAlL7V18f7Omaav8/bozOP\nx78MQ06CGEFRcD4LPMITxTDj6zDm1h7iPhG4m2c9Shy0rwpFmFdd\n-----END RSA PRIVATE KEY-----`))\n\tif err != nil {\n\t\t// fmt.Println(\"Unable to parse test key :\", err)\n\t\treturn nil, err\n\t}\n\ttestSingers, _ := ssh.NewSignerFromKey(testPrivateKeys)\n\tauth = append(auth, ssh.PublicKeys(testSingers))\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: \t\t\t\tuser,\n\t\tAuth: \t\t\t\tauth,\n\t\tTimeout: \t\t\t30 * time.Second,\n\t\tHostKeyCallback: \tfunc(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\t\treturn nil\n\t\t},\n\t}\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\tif sshClient, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\tif sftpClient, err = sftp.NewClient(sshClient); err != nil {\n\t\treturn nil, err\n\t}\n\treturn sftpClient, nil\n}", "func NewSSHClientConfig(user, keyFile, passworkPhrase string) (*SSHClient, error) {\n\tpublicKeyMenthod, err := publicKey(keyFile, passworkPhrase)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsshConfig := &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tpublicKeyMenthod,\n\t\t},\n\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t}\n\n\treturn &SSHClient{\n\t\tconfig: sshConfig,\n\t}, nil\n}", "func DownloadUsingScp(env *Environment) error {\n\tprivateKeyContent, err := DecodePrivateKeyFromFile(env.SshPrivateKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tkeyChain := NewKeychain(privateKeyContent)\n\tscpStorage := NewScpStorage(env.RemoteHost,\n\t\tenv.RemotePort,\n\t\tenv.RemoteUser,\n\t\tkeyChain)\n\terr = scpStorage.Connect()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = scpStorage.Pull(env.RemoteFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *service) upload(destination string, mode os.FileMode, content []byte) (err error) {\n\tdir, file := path.Split(destination)\n\tif mode == 0 {\n\t\tmode = 0644\n\t}\n\twaitGroup := &sync.WaitGroup{}\n\twaitGroup.Add(1)\n\tif strings.HasPrefix(file, \"/\") {\n\t\tfile = string(file[1:])\n\t}\n\tsession, err := c.getSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twriter, err := session.StdinPipe()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to acquire stdin\")\n\t}\n\tdefer writer.Close()\n\n\tvar transferError Errors = make(chan error, 1)\n\tdefer close(transferError)\n\tvar sessionError Errors = make(chan error, 1)\n\tdefer close(sessionError)\n\toutput, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to acquire stdout\")\n\t}\n\tgo checkOutput(output, sessionError)\n\n\tif mode >= 01000 {\n\t\tmode = storage.DefaultFileMode\n\t}\n\tfileMode := string(fmt.Sprintf(\"C%04o\", mode)[:5])\n\tcreateFileCmd := fmt.Sprintf(\"%v %d %s\\n\", fileMode, len(content), file)\n\tgo c.transferData(content, createFileCmd, writer, transferError, waitGroup)\n\tscpCommand := \"scp -qtr \" + dir\n\terr = session.Start(scpCommand)\n\tif err != nil {\n\t\treturn err\n\t}\n\twaitGroup.Wait()\n\twriterErr := writer.Close()\n\tif err := sessionError.GetError(); err != nil {\n\t\treturn err\n\t}\n\tif err := transferError.GetError(); err != nil {\n\t\treturn err\n\t}\n\tif err = session.Wait(); err != nil {\n\t\tif err := sessionError.GetError(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn err\n\t}\n\treturn writerErr\n}", "func (rs *RSSTask) New(ctx *cli.Context) (Task, error) {\n\tu, err := url.Parse(ctx.String(\"src\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\topt := &RSSOption{\n\t\tDest: ctx.String(\"dest\"),\n\t}\n\tif len(u.Scheme) <= 4 {\n\t\treturn nil, ErrRSSSchemaWrong\n\t}\n\t// get real schema, to get remote rss source\n\tu.Scheme = u.Scheme[4:]\n\topt.IsRemote = true\n\topt.Source = u.String()\n\n\treturn &RSSTask{\n\t\topt: opt,\n\t}, nil\n}", "func NewTppCredentialsParams(tppAuthenticationGroupId int64, label string, ) *TppCredentialsParams {\n\tthis := TppCredentialsParams{}\n\tthis.TppAuthenticationGroupId = tppAuthenticationGroupId\n\tthis.Label = label\n\treturn &this\n}", "func (a SSHKeysApi) CreateSSHKey(sshKey SshKeyInput) (*SshKey, *APIResponse, error) {\n\n\tvar localVarHttpMethod = strings.ToUpper(\"Post\")\n\t// create path and map variables\n\tlocalVarPath := a.Configuration.BasePath + \"/ssh-keys\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := make(map[string]string)\n\tvar localVarPostBody interface{}\n\tvar localVarFileName string\n\tvar localVarFileBytes []byte\n\t// authentication '(x_auth_token)' required\n\t// set key with prefix in header\n\tlocalVarHeaderParams[\"X-Auth-Token\"] = a.Configuration.GetAPIKeyWithPrefix(\"X-Auth-Token\")\n\t// add default headers if any\n\tfor key := range a.Configuration.DefaultHeader {\n\t\tlocalVarHeaderParams[key] = a.Configuration.DefaultHeader[key]\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/json\", }\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\n\t\t\"application/json\",\n\t\t}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &sshKey\n\tvar successPayload = new(SshKey)\n\tlocalVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\n\tvar localVarURL, _ = url.Parse(localVarPath)\n\tlocalVarURL.RawQuery = localVarQueryParams.Encode()\n\tvar localVarAPIResponse = &APIResponse{Operation: \"CreateSSHKey\", Method: localVarHttpMethod, RequestURL: localVarURL.String()}\n\tif localVarHttpResponse != nil {\n\t\tlocalVarAPIResponse.Response = localVarHttpResponse.RawResponse\n\t\tlocalVarAPIResponse.Payload = localVarHttpResponse.Body()\n\t}\n\n\tif err != nil {\n\t\treturn successPayload, localVarAPIResponse, err\n\t}\n\terr = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)\n\treturn successPayload, localVarAPIResponse, err\n}", "func New(args []string) pakelib.Command {\n\treturn &move{\n\t\targs: args,\n\t}\n}", "func ConfigureBCCSP(optsPtr **factory.FactoryOpts, mspDir, homeDir string) error {\n\tvar err error\n\tif optsPtr == nil {\n\t\treturn errors.New(\"nil argument not allowed\")\n\t}\n\topts := *optsPtr\n\tif opts == nil {\n\t\topts = &factory.FactoryOpts{}\n\t}\n\tif opts.ProviderName == \"\" {\n\t\topts.ProviderName = \"SW\"\n\t}\n\tif strings.ToUpper(opts.ProviderName) == \"SW\" {\n\t\tif opts.SwOpts == nil {\n\t\t\topts.SwOpts = &factory.SwOpts{}\n\t\t}\n\t\tif opts.SwOpts.HashFamily == \"\" {\n\t\t\topts.SwOpts.HashFamily = \"SHA2\"\n\t\t}\n\t\tif opts.SwOpts.SecLevel == 0 {\n\t\t\topts.SwOpts.SecLevel = 256\n\t\t}\n\t\tif opts.SwOpts.FileKeystore == nil {\n\t\t\topts.SwOpts.FileKeystore = &factory.FileKeystoreOpts{}\n\t\t}\n\t\t// The mspDir overrides the KeyStorePath; otherwise, if not set, set default\n\t\tif mspDir != \"\" {\n\t\t\topts.SwOpts.FileKeystore.KeyStorePath = path.Join(mspDir, \"keystore\")\n\t\t} else if opts.SwOpts.FileKeystore.KeyStorePath == \"\" {\n\t\t\topts.SwOpts.FileKeystore.KeyStorePath = path.Join(\"msp\", \"keystore\")\n\t\t}\n\t}\n\terr = makeFileNamesAbsolute(opts, homeDir)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"Failed to make BCCSP files absolute\")\n\t}\n\tlog.Debugf(\"Initializing BCCSP: %+v\", opts)\n\tif opts.SwOpts != nil {\n\t\tlog.Debugf(\"Initializing BCCSP with software options %+v\", opts.SwOpts)\n\t}\n\tif opts.Pkcs11Opts != nil {\n\t\tlog.Debugf(\"Initializing BCCSP with PKCS11 options %+v\", sanitizePKCS11Opts(*opts.Pkcs11Opts))\n\t}\n\t*optsPtr = opts\n\treturn nil\n}", "func newParallelCompositeCommand(cmds ...command) command {\n\treturn parallelCompositeCommand{\n\t\tcmds: cmds,\n\t}\n}", "func (z *zpoolctl) Create(ctx context.Context, name, options, point, root string, properties map[string]string, raid string, devs ...string) *execute {\n\targs := []string{\"create\"}\n\tif len(options) > 0 {\n\t\targs = append(args, options)\n\t}\n\tif properties != nil {\n\t\tkv := \"-o \"\n\t\tfor k, v := range properties {\n\t\t\tkv += fmt.Sprintf(\"%s=%s \", k, v)\n\t\t}\n\t\targs = append(args, kv)\n\t}\n\tif len(point) > 0 {\n\t\targs = append(args, \"-m \"+point)\n\t}\n\tif len(root) > 0 {\n\t\targs = append(args, \"-R \"+root)\n\t}\n\targs = append(args, name, raid)\n\tfor _, dev := range devs {\n\t\targs = append(args, dev)\n\t}\n\n\treturn &execute{ctx: ctx, name: z.cmd, args: args}\n}", "func NewSyncTask(src, dst *s3.Bucket) (*SyncTask, error) {\n\n\t// before starting the sync, make sure our s3 object is usable (credentials and such)\n\t_, err := src.List(\"/\", \"/\", \"/\", 1)\n\tif err != nil {\n\t\t// if we can't list, we abort right away\n\t\treturn nil, fmt.Errorf(\"couldn't list source bucket %q: %v\", src.Name, err)\n\t}\n\t_, err = dst.List(\"/\", \"/\", \"/\", 1)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"couldn't list destination bucket %q: %v\", dst.Name, err)\n\t}\n\n\treturn &SyncTask{\n\t\tRetryBase: time.Second,\n\t\tMaxRetry: 10,\n\t\tDecodePara: runtime.NumCPU(),\n\t\tSyncPara: 1000,\n\t\tSync: PutCopySyncer,\n\n\t\tsrc: src,\n\t\tdst: dst,\n\t}, nil\n}", "func newCommand(s *Set) *Command {\n\tc := new(Command)\n\tc.set = s\n\n\treturn c\n}", "func SSHCommNew(address string, config *SSHCommConfig) (result *comm, err error) {\n\t// Establish an initial connection and connect\n\tresult = &comm{\n\t\tconfig: config,\n\t\taddress: address,\n\t}\n\n\tif err = result.reconnect(); err != nil {\n\t\tresult = nil\n\t\treturn\n\t}\n\n\treturn\n}", "func ParseSCPDestination(s string) (*Destination, error) {\n\tout := reSCP.FindStringSubmatch(s)\n\tif len(out) == 0 {\n\t\treturn nil, trace.BadParameter(\"failed to parse %q, try form user@host:/path\", s)\n\t}\n\taddr, err := utils.ParseAddr(out[2])\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\treturn &Destination{Login: out[1], Host: *addr, Path: out[3]}, nil\n}", "func NewTCPCommand(out io.Writer) * cobra.Command {\n\tvar port int\n\ttcpCommand := &cobra.Command{\n\t\tUse: \"tcp\",\n\t\tShort: \"Sniffs http traffic at your local interface\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\texecutePcap(out, port)\n\t\t},\n\t}\n\n\ttcpCommand.Flags().IntVarP(&port, \"port\", \"p\", 8080, \"port to sniff traffic on\")\n\n\treturn tcpCommand\n}", "func New(p provider) *Command {\n\treturn &Command{\n\t\tctx: p,\n\t\texportPubKeyBytes: func(id string) ([]byte, error) {\n\t\t\tk, ok := p.KMS().(*localkms.LocalKMS)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"kms is not LocalKMS type\")\n\t\t\t}\n\n\t\t\treturn k.ExportPubKeyBytes(id)\n\t\t},\n\t}\n}", "func NewUpCommand() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"up [options] <sc ip:port>\",\n\t\tShort: \"Start up\",\n\t\tRun: upCommandFunc,\n\t}\n\n\tcmd.Flags().StringVarP(&upFile, \"file\", \"f\", \"sc-compose.yml\", \"the spec file of sc compose\")\n\treturn cmd\n}", "func NewSSHAuthorizationPolicy() *SSHAuthorizationPolicy {\n\n\treturn &SSHAuthorizationPolicy{\n\t\tModelVersion: 1,\n\t\tAnnotations: map[string][]string{},\n\t\tAssociatedTags: []string{},\n\t\tAuthorizedSubnets: []string{},\n\t\tExtensions: []string{},\n\t\tNormalizedTags: []string{},\n\t\tObject: [][]string{},\n\t\tPrincipals: []string{},\n\t\tMetadata: []string{},\n\t\tSubject: [][]string{},\n\t\tValidity: \"1h\",\n\t}\n}", "func (c *Connection) CopyTo(filename string) error {\n\tvar scpError error\n\tvar scpOut []byte\n\tfor i := 0; i < sshRetries; i++ {\n\t\tconnectString := fmt.Sprintf(\"%s@%s\", c.User, c.Host)\n\t\tcmd := exec.Command(\"scp\", \"-i\", c.PrivateKeyPath, \"-P\", c.Port, \"-o\", \"StrictHostKeyChecking=no\", filepath.Join(scriptsDir, filename), connectString+\":/tmp/\"+filename)\n\t\tutil.PrintCommand(cmd)\n\t\tscpOut, scpError = cmd.CombinedOutput()\n\t\tif scpError != nil {\n\t\t\tlog.Printf(\"Error output:%s\\n\", scpOut)\n\t\t\tcontinue\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn scpError\n}", "func (sshConfig *SSHConfig) Copy(reader io.Reader, remotePath string, permissions string, size int64) (err error) {\n\tif sshConfig.session == nil {\n\t\tif !sshConfig.autoOpenSession {\n\t\t\tpanic(\"No SSH session opened.\")\n\t\t}\n\t\tif err1 := sshConfig.Connect(); err1 != nil {\n\t\t\treturn err1\n\t\t}\n\t}\n\tif len(permissions) != 4 {\n\t\treturn errors.New(\"permissions need to be 4 characters\")\n\t}\n\n\tfilename := path.Base(remotePath)\n\tif filename == \"\" {\n\t\treturn errors.New(\"Remote filename is empty\")\n\t}\n\n\tdirectory := path.Dir(remotePath)\n\n\tvar (\n\t\twg sync.WaitGroup\n\t\twrittenCount int64\n\t)\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tvar w io.WriteCloser\n\t\tw, err = sshConfig.session.StdinPipe()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tdefer w.Close()\n\t\tfmt.Fprintln(w, \"C\"+permissions, size, filename)\n\t\twrittenCount, err = io.Copy(w, reader)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif writtenCount != size {\n\t\t\t// some error here\n\t\t\tmsg := fmt.Sprintf(\"Copied size: %d not equal to file size: %d\", writtenCount, size)\n\t\t\terr = errors.New(msg)\n\t\t}\n\t\tfmt.Fprint(w, \"\\x00\") // Send 0 byte to indicate EOF\n\t}()\n\n\tcmd := fmt.Sprintf(\"%s/usr/bin/scp -%st %s\", sshConfig.sudo, sshConfig.verbose, directory)\n\terr = sshConfig.session.Run(cmd)\n\twg.Wait() // waits for the coroutine to complete\n\treturn\n}", "func NewSSHKey() []byte {\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, 4096)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn x509.MarshalPKCS1PrivateKey(privateKey)\n}", "func (c *Client) CreateSSHKey(ctx context.Context, opts SSHKeyCreateOptions) (*SSHKey, error) {\n\tbody, err := json.Marshal(opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\te := \"profile/sshkeys\"\n\treq := c.R(ctx).SetResult(&SSHKey{}).SetBody(string(body))\n\tr, err := coupleAPIErrors(req.Post(e))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r.Result().(*SSHKey), nil\n}", "func New(out io.Writer, in io.Reader, hasInput bool, snptStore *snippet.Store) *cobra.Command {\n\treturn &cobra.Command{\n\t\tUse: \"copy [snippet ID | snippet name]\",\n\t\tAliases: []string{\"cp\"},\n\t\tShort: \"Copy a snippet to the clipboard\",\n\t\tLong: `\nCopy a snippet to the clipboard.\n\nIf you do not provide a snippet ID or snippet name then a prompt will be shown and you can select the snippet you want to copy to the clipboard.\n\nSnpt will read from stdin if provided and attempt to extract a snippet ID from it. The stdin should be formatted like:\n\n\tSome random string [snippet ID]\n\nSnpt will parse anything in the square brackets that appears at the end of the string. This is useful for piping into Snpt:\n\n\techo 'foo - bar baz [aff9aa71ead70963p3bfa4e49b18d27539f9d9d8]' | snpt cp`,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tsnpt, err := cliHelper.ResolveSnippet(args, hasInput, in, snptStore)\n\n\t\t\tif err != nil || snpt.GetId() == \"\" {\n\t\t\t\treturn errors.New(\"Failed to retrieve snippet from database\")\n\t\t\t}\n\n\t\t\tif err := clipboard.WriteAll(snpt.Content); err != nil {\n\t\t\t\treturn fmt.Errorf(\"Failed to copy %s to the clipboard\", snpt.GetFilename())\n\t\t\t}\n\n\t\t\tcliHelper.PrintSuccess(out, \"%s copied to the clipboard\", snpt.GetFilename())\n\n\t\t\treturn nil\n\t\t},\n\t}\n}", "func newSSHAgentConfig(userName string) (*sshClientConfig, error) {\n\tagent, err := newAgent()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig, err := sshAgentConfig(userName, agent)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &sshClientConfig{\n\t\tagent: agent,\n\t\tClientConfig: config,\n\t}, nil\n}", "func (opts *CopyCommand) Execute(args []string) error {\n\n\tconnectionOptions := &s3tools.S3ConnectionOptions{Region: &opts.Region}\n\n\tsess, err := s3tools.CreateS3Session(connectionOptions)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := s3tools.CheckOrCreateBucket(sess, opts.Bucket); err != nil {\n\t\tpanic(err)\n\t}\n\tbucketPath := fmt.Sprintf(\"%s/%s\", opts.Bucket, opts.Branch)\n\tfmt.Printf(\"Copying coverage information into %s bucket...\\n\", bucketPath)\n\n\tuploadKey := fmt.Sprintf(\"%s/coverage.xml\", opts.Branch)\n\tif err := s3tools.UploadFile(sess, opts.Bucket, uploadKey, opts.CoverageFile); err != nil {\n\t\tpanic(err)\n\t}\n\treturn nil\n}", "func ScpFileTo(t testing.TestingT, host Host, mode os.FileMode, remotePath, contents string) {\n\terr := ScpFileToE(t, host, mode, remotePath, contents)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}" ]
[ "0.63335776", "0.6195386", "0.58148247", "0.57983583", "0.5749101", "0.5542656", "0.5385175", "0.5381236", "0.5379341", "0.51879406", "0.5173655", "0.51401067", "0.5123457", "0.50670224", "0.50564516", "0.50375056", "0.50113094", "0.5000382", "0.49787205", "0.49739337", "0.49410993", "0.4928138", "0.48743972", "0.48725882", "0.48625693", "0.48148808", "0.48022875", "0.4790315", "0.47827217", "0.4776097", "0.476351", "0.47620627", "0.47422597", "0.47104686", "0.46886656", "0.46419567", "0.46418834", "0.4620286", "0.46128076", "0.46096787", "0.4599288", "0.4563372", "0.45508108", "0.4548943", "0.45475203", "0.45420077", "0.45365348", "0.4533967", "0.4533967", "0.45215365", "0.45075586", "0.44968638", "0.44954884", "0.44850743", "0.44825962", "0.44756123", "0.44750747", "0.44742402", "0.44639027", "0.44596434", "0.44571862", "0.44552833", "0.44506186", "0.44399127", "0.44256973", "0.44247538", "0.4420984", "0.4414429", "0.4412555", "0.44032496", "0.44028777", "0.43963328", "0.43883544", "0.43875596", "0.4378892", "0.43743607", "0.43651387", "0.43612307", "0.4358233", "0.43451852", "0.43348226", "0.43342835", "0.4331751", "0.4330402", "0.43270195", "0.43206528", "0.43198192", "0.4318763", "0.43184727", "0.43144888", "0.43064812", "0.4303333", "0.4298917", "0.42928421", "0.42904434", "0.42834246", "0.4281992", "0.4273031", "0.42647207", "0.4257048" ]
0.7480735
0
NewSCPFromJSON creates an SCP command from a JSON object.
func NewSCPFromJSON(raw []byte) (*entities.Command, derrors.Error) { scp := &SCP{} if err := json.Unmarshal(raw, &scp); err != nil { return nil, derrors.NewInvalidArgumentError(errors.UnmarshalError, err) } scp.CommandID = entities.GenerateCommandID(scp.Name()) var r entities.Command = scp return &r, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewSCP(targetHost string, targetPort string, credentials entities.Credentials, source string, destination string) *SCP {\n\treturn &SCP{*entities.NewSyncCommand(entities.SCP),\n\t\ttargetHost,\n\t\ttargetPort,\n\t\tcredentials,\n\t\tsource,\n\t\tdestination}\n}", "func (r *CreateAttackDownloadTaskRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"Domain\")\n\tdelete(f, \"FromTime\")\n\tdelete(f, \"ToTime\")\n\tdelete(f, \"Name\")\n\tdelete(f, \"RiskLevel\")\n\tdelete(f, \"Status\")\n\tdelete(f, \"RuleId\")\n\tdelete(f, \"AttackIp\")\n\tdelete(f, \"AttackType\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"CreateAttackDownloadTaskRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func NewCommandFromJSON(configPath, dbName string) (*Command, error) {\n\tb, err := helper.ReadFile(configPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcom := Command{}\n\tif err := com.Config.ParseJSON(b); err != nil {\n\t\treturn nil, err\n\t}\n\tif dbName != \"\" {\n\t\tcom.Config.MysqlConfig.DbName = dbName\n\t}\n\tcom.ReadAt = time.Now()\n\treturn &com, nil\n}", "func (r *PutProvisionedConcurrencyConfigRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"FunctionName\")\n\tdelete(f, \"Qualifier\")\n\tdelete(f, \"VersionProvisionedConcurrencyNum\")\n\tdelete(f, \"Namespace\")\n\tdelete(f, \"TriggerActions\")\n\tdelete(f, \"ProvisionedType\")\n\tdelete(f, \"TrackingTarget\")\n\tdelete(f, \"MinCapacity\")\n\tdelete(f, \"MaxCapacity\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"PutProvisionedConcurrencyConfigRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func NewFromJSON(data []byte) (*Conf, error) {\n\tvar c map[string]string\n\tif err := json.Unmarshal(data, &c); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Conf{c: c}, nil\n}", "func (r *StartPublishCdnStreamRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"SdkAppId\")\n\tdelete(f, \"RoomId\")\n\tdelete(f, \"RoomIdType\")\n\tdelete(f, \"AgentParams\")\n\tdelete(f, \"WithTranscoding\")\n\tdelete(f, \"AudioParams\")\n\tdelete(f, \"VideoParams\")\n\tdelete(f, \"SingleSubscribeParams\")\n\tdelete(f, \"PublishCdnParams\")\n\tdelete(f, \"SeiParams\")\n\tdelete(f, \"FeedBackRoomParams\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"StartPublishCdnStreamRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *UpdatePublishCdnStreamRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"SdkAppId\")\n\tdelete(f, \"TaskId\")\n\tdelete(f, \"SequenceNumber\")\n\tdelete(f, \"WithTranscoding\")\n\tdelete(f, \"AudioParams\")\n\tdelete(f, \"VideoParams\")\n\tdelete(f, \"SingleSubscribeParams\")\n\tdelete(f, \"PublishCdnParams\")\n\tdelete(f, \"SeiParams\")\n\tdelete(f, \"FeedBackRoomParams\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"UpdatePublishCdnStreamRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *CopyFunctionRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"FunctionName\")\n\tdelete(f, \"NewFunctionName\")\n\tdelete(f, \"Namespace\")\n\tdelete(f, \"TargetNamespace\")\n\tdelete(f, \"Description\")\n\tdelete(f, \"TargetRegion\")\n\tdelete(f, \"Override\")\n\tdelete(f, \"CopyConfiguration\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"CopyFunctionRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *CreateAccessExportRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"TopicId\")\n\tdelete(f, \"From\")\n\tdelete(f, \"To\")\n\tdelete(f, \"Query\")\n\tdelete(f, \"Count\")\n\tdelete(f, \"Format\")\n\tdelete(f, \"Order\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"CreateAccessExportRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (f *Factory) NewFromJSON(filePath string) (string, uint8, FilteredServer) {\n\tlog := f.log.WithField(\"file\", filepath.Base(filePath))\n\n\tcontent, err := os.ReadFile(filePath)\n\tif err != nil {\n\t\tlog.Fatalf(\"Cannot read file: %v\", err)\n\t}\n\n\tvar c Config\n\n\terr = json.Unmarshal(content, &c)\n\tif err != nil {\n\t\tlog.Fatalf(\"Cannot decode JSON: %v\", err)\n\t}\n\n\treturn f.newFromConfig(log, c)\n}", "func (r *StopPublishCdnStreamRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"SdkAppId\")\n\tdelete(f, \"TaskId\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"StopPublishCdnStreamRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *CreateInstanceRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"Zone\")\n\tdelete(f, \"EsVersion\")\n\tdelete(f, \"VpcId\")\n\tdelete(f, \"SubnetId\")\n\tdelete(f, \"Password\")\n\tdelete(f, \"InstanceName\")\n\tdelete(f, \"NodeNum\")\n\tdelete(f, \"ChargeType\")\n\tdelete(f, \"ChargePeriod\")\n\tdelete(f, \"RenewFlag\")\n\tdelete(f, \"NodeType\")\n\tdelete(f, \"DiskType\")\n\tdelete(f, \"DiskSize\")\n\tdelete(f, \"TimeUnit\")\n\tdelete(f, \"AutoVoucher\")\n\tdelete(f, \"VoucherIds\")\n\tdelete(f, \"EnableDedicatedMaster\")\n\tdelete(f, \"MasterNodeNum\")\n\tdelete(f, \"MasterNodeType\")\n\tdelete(f, \"MasterNodeDiskSize\")\n\tdelete(f, \"ClusterNameInConf\")\n\tdelete(f, \"DeployMode\")\n\tdelete(f, \"MultiZoneInfo\")\n\tdelete(f, \"LicenseType\")\n\tdelete(f, \"NodeInfoList\")\n\tdelete(f, \"TagList\")\n\tdelete(f, \"BasicSecurityType\")\n\tdelete(f, \"SceneType\")\n\tdelete(f, \"WebNodeTypeInfo\")\n\tdelete(f, \"Protocol\")\n\tdelete(f, \"OperationDuration\")\n\tdelete(f, \"EnableHybridStorage\")\n\tdelete(f, \"DiskEnhance\")\n\tdelete(f, \"EnableDiagnose\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"CreateInstanceRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *CreateClusterRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"ProductVersion\")\n\tdelete(f, \"EnableSupportHAFlag\")\n\tdelete(f, \"InstanceName\")\n\tdelete(f, \"InstanceChargeType\")\n\tdelete(f, \"LoginSettings\")\n\tdelete(f, \"SceneSoftwareConfig\")\n\tdelete(f, \"InstanceChargePrepaid\")\n\tdelete(f, \"SecurityGroupIds\")\n\tdelete(f, \"ScriptBootstrapActionConfig\")\n\tdelete(f, \"ClientToken\")\n\tdelete(f, \"NeedMasterWan\")\n\tdelete(f, \"EnableRemoteLoginFlag\")\n\tdelete(f, \"EnableKerberosFlag\")\n\tdelete(f, \"CustomConf\")\n\tdelete(f, \"Tags\")\n\tdelete(f, \"DisasterRecoverGroupIds\")\n\tdelete(f, \"EnableCbsEncryptFlag\")\n\tdelete(f, \"MetaDBInfo\")\n\tdelete(f, \"DependService\")\n\tdelete(f, \"ZoneResourceConfiguration\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"CreateClusterRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func CreateCommand(cfg Config) (Command, error) {\n\terr := cfg.CheckAndSetDefaults()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tcmd := command{\n\t\tConfig: cfg,\n\t}\n\n\tcmd.log = log.WithFields(log.Fields{\n\t\ttrace.Component: \"SCP\",\n\t\ttrace.ComponentFields: log.Fields{\n\t\t\t\"LocalAddr\": cfg.Flags.LocalAddr,\n\t\t\t\"RemoteAddr\": cfg.Flags.RemoteAddr,\n\t\t\t\"Target\": cfg.Flags.Target,\n\t\t\t\"User\": cfg.User,\n\t\t\t\"RunOnServer\": cfg.RunOnServer,\n\t\t\t\"RemoteLocation\": cfg.RemoteLocation,\n\t\t},\n\t})\n\n\treturn &cmd, nil\n}", "func NewFromJSON(jsonEnv map[string]interface{}) (*ChefEnvironment, util.Gerror) {\n\tenv, err := New(jsonEnv[\"name\"].(string))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = env.UpdateFromJSON(jsonEnv)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn env, nil\n}", "func (r *CreateAttackDownloadTaskResponse) FromJsonString(s string) error {\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *CreateInstanceRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"ProductId\")\n\tdelete(f, \"Software\")\n\tdelete(f, \"SupportHA\")\n\tdelete(f, \"InstanceName\")\n\tdelete(f, \"PayMode\")\n\tdelete(f, \"TimeSpan\")\n\tdelete(f, \"TimeUnit\")\n\tdelete(f, \"LoginSettings\")\n\tdelete(f, \"VPCSettings\")\n\tdelete(f, \"ResourceSpec\")\n\tdelete(f, \"COSSettings\")\n\tdelete(f, \"Placement\")\n\tdelete(f, \"SgId\")\n\tdelete(f, \"PreExecutedFileSettings\")\n\tdelete(f, \"AutoRenew\")\n\tdelete(f, \"ClientToken\")\n\tdelete(f, \"NeedMasterWan\")\n\tdelete(f, \"RemoteLoginAtCreate\")\n\tdelete(f, \"CheckSecurity\")\n\tdelete(f, \"ExtendFsField\")\n\tdelete(f, \"Tags\")\n\tdelete(f, \"DisasterRecoverGroupIds\")\n\tdelete(f, \"CbsEncrypt\")\n\tdelete(f, \"MetaType\")\n\tdelete(f, \"UnifyMetaInstanceId\")\n\tdelete(f, \"MetaDBInfo\")\n\tdelete(f, \"ApplicationRole\")\n\tdelete(f, \"SceneName\")\n\tdelete(f, \"ExternalService\")\n\tdelete(f, \"VersionID\")\n\tdelete(f, \"MultiZone\")\n\tdelete(f, \"MultiZoneSettings\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"CreateInstanceRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func fromJSON(ec *EvalCtx) {\n\tin := ec.ports[0].File\n\tout := ec.ports[1].Chan\n\n\tdec := json.NewDecoder(in)\n\tvar v interface{}\n\tfor {\n\t\terr := dec.Decode(&v)\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthrow(err)\n\t\t}\n\t\tout <- FromJSONInterface(v)\n\t}\n}", "func (r *GetProvisionedConcurrencyConfigRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"FunctionName\")\n\tdelete(f, \"Namespace\")\n\tdelete(f, \"Qualifier\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"GetProvisionedConcurrencyConfigRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *PutTotalConcurrencyConfigRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"TotalConcurrencyMem\")\n\tdelete(f, \"Namespace\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"PutTotalConcurrencyConfigRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *PutReservedConcurrencyConfigRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"FunctionName\")\n\tdelete(f, \"ReservedConcurrencyMem\")\n\tdelete(f, \"Namespace\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"PutReservedConcurrencyConfigRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *DescribeInstanceOperationsRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"InstanceId\")\n\tdelete(f, \"StartTime\")\n\tdelete(f, \"EndTime\")\n\tdelete(f, \"Offset\")\n\tdelete(f, \"Limit\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"DescribeInstanceOperationsRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *PutProvisionedConcurrencyConfigResponse) FromJsonString(s string) error {\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *StartPublishCdnStreamResponse) FromJsonString(s string) error {\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *CreateClusterResponse) FromJsonString(s string) error {\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *DeleteProvisionedConcurrencyConfigRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"FunctionName\")\n\tdelete(f, \"Qualifier\")\n\tdelete(f, \"Namespace\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"DeleteProvisionedConcurrencyConfigRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *CopyFunctionResponse) FromJsonString(s string) error {\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *CreateAuditRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"IsEnableCmqNotify\")\n\tdelete(f, \"ReadWriteAttribute\")\n\tdelete(f, \"AuditName\")\n\tdelete(f, \"CosRegion\")\n\tdelete(f, \"IsCreateNewBucket\")\n\tdelete(f, \"CosBucketName\")\n\tdelete(f, \"KeyId\")\n\tdelete(f, \"CmqQueueName\")\n\tdelete(f, \"KmsRegion\")\n\tdelete(f, \"IsEnableKmsEncry\")\n\tdelete(f, \"CmqRegion\")\n\tdelete(f, \"LogFilePrefix\")\n\tdelete(f, \"IsCreateNewQueue\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"CreateAuditRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func newPutCommandDataWithJSON(id string, changeVector *string, document map[string]interface{}) *PutCommandDataWithJSON {\n\tpanicIf(document == nil, \"Document cannot be nil\")\n\n\tres := &PutCommandDataWithJSON{\n\t\tCommandData: &CommandData{\n\t\t\tType: CommandPut,\n\t\t\tID: id,\n\t\t\tChangeVector: changeVector,\n\t\t},\n\t\tdocument: document,\n\t}\n\treturn res\n}", "func (r *ModifyResourceScheduleConfigRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"InstanceId\")\n\tdelete(f, \"Key\")\n\tdelete(f, \"Value\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"ModifyResourceScheduleConfigRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *AllocateCustomerCreditRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"AddedCredit\")\n\tdelete(f, \"ClientUin\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"AllocateCustomerCreditRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *DescribeResourceScheduleRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"InstanceId\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"DescribeResourceScheduleRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *CreateTriggerRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"FunctionName\")\n\tdelete(f, \"TriggerName\")\n\tdelete(f, \"Type\")\n\tdelete(f, \"TriggerDesc\")\n\tdelete(f, \"Namespace\")\n\tdelete(f, \"Qualifier\")\n\tdelete(f, \"Enable\")\n\tdelete(f, \"CustomArgument\")\n\tdelete(f, \"Description\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"CreateTriggerRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *ScaleOutClusterRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"InstanceChargeType\")\n\tdelete(f, \"InstanceId\")\n\tdelete(f, \"ScaleOutNodeConfig\")\n\tdelete(f, \"ClientToken\")\n\tdelete(f, \"InstanceChargePrepaid\")\n\tdelete(f, \"ScriptBootstrapActionConfig\")\n\tdelete(f, \"SoftDeployInfo\")\n\tdelete(f, \"ServiceNodeInfo\")\n\tdelete(f, \"DisasterRecoverGroupIds\")\n\tdelete(f, \"Tags\")\n\tdelete(f, \"HardwareSourceType\")\n\tdelete(f, \"PodSpecInfo\")\n\tdelete(f, \"ClickHouseClusterName\")\n\tdelete(f, \"ClickHouseClusterType\")\n\tdelete(f, \"YarnNodeLabel\")\n\tdelete(f, \"EnableStartServiceFlag\")\n\tdelete(f, \"ResourceSpec\")\n\tdelete(f, \"Zone\")\n\tdelete(f, \"SubnetId\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"ScaleOutClusterRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *PublishVersionRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"FunctionName\")\n\tdelete(f, \"Description\")\n\tdelete(f, \"Namespace\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"PublishVersionRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *TerminateTasksRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"InstanceId\")\n\tdelete(f, \"ResourceIds\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"TerminateTasksRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func NewMoneyTransferCommandJSONClient(addr string, client HTTPClient) MoneyTransferCommand {\n\tprefix := urlBase(addr) + MoneyTransferCommandPathPrefix\n\turls := [1]string{\n\t\tprefix + \"Send\",\n\t}\n\tif httpClient, ok := client.(*http.Client); ok {\n\t\treturn &moneyTransferCommandJSONClient{\n\t\t\tclient: withoutRedirects(httpClient),\n\t\t\turls: urls,\n\t\t}\n\t}\n\treturn &moneyTransferCommandJSONClient{\n\t\tclient: client,\n\t\turls: urls,\n\t}\n}", "func (r *QueryCreditQuotaRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\t\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"QueryCreditQuotaRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func NewFromJSON(j []byte) (Event, error) {\n\tprotocol := gjson.GetBytes(j, \"protocol\")\n\tif !protocol.Exists() {\n\t\treturn nil, fmt.Errorf(\"no protocol field present\")\n\t}\n\n\tproto, err := protoStringToTypeString(protocol.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tetype, ok := eventTypes[proto]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unknown protocol '%s' received\", protocol.String())\n\t}\n\n\tfactory, ok := eventJSONParsers[etype]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"cannot create %s event type from JSON\", proto)\n\t}\n\n\treturn factory(j)\n}", "func NewTransferFromJson(jsonDecoder *json.Decoder, token string) (*Transfer, error) {\n\n\tvar transfer Transfer\n\n\t// tenta decodificar o json da requsiição no objeto Transfer\n\tif err := jsonDecoder.Decode(&transfer); err != nil {\n\n\t\treturn &Transfer{}, fmt.Errorf(\"error to decode the json to the Transfer object: %s\", err.Error())\n\t}\n\n\t// verifica se a conta de destino realmente existe, se nao retorna erro\n\tif !(transfer.CheckIfAccountDestinationExists()) {\n\n\t\treturn &Transfer{}, fmt.Errorf(\"Account destination does not exists\")\n\t}\n\n\t// verifica se o ammount desejado é maior que zero, afinal, quem realiza transf TIRA dinheiro da sua conta para outra, se nao retorna erro\n\tif !(transfer.CheckIfAmmountIsValid()) {\n\n\t\treturn &Transfer{}, fmt.Errorf(\"ammount desired to transfer is invalid. Provide an ammount greater than zero\")\n\t}\n\n\t// recupera a conta de origem, se nao retorna erro\n\tif err := transfer.FillAccountOriginId(token); err != nil {\n\n\t\treturn &Transfer{}, fmt.Errorf(\"cannot get the account origin from token: %s\", err.Error())\n\t}\n\n\t// como a transferência se inicia sempre por quem vai debitar, seta, então, o ammount como negativo\n\ttransfer.Ammount = -transfer.Ammount\n\n\treturn &transfer, nil\n}", "func NewStringFromJSON(json jsoniter.Any) (*String, error) {\n\tif json.Get(\"type\").ToUint() != TypeString {\n\t\treturn nil, ErrInvalidJSON\n\t}\n\n\tvalue := json.Get(\"value\").ToString()\n\treturn &String{Value: value}, nil\n}", "func FromJSON(from string) (*Config, error) {\n\tc := New()\n\tif err := json.Unmarshal([]byte(from), c); err != nil {\n\t\treturn nil, err\n\t}\n\tc.sync()\n\treturn c, nil\n}", "func fromJSONPb(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\tvar ctor starlark.Value\n\tvar text starlark.String\n\tif err := starlark.UnpackArgs(\"from_jsonpb\", args, kwargs, \"ctor\", &ctor, \"text\", &text); err != nil {\n\t\treturn nil, err\n\t}\n\n\tc, ok := ctor.(*messageCtor)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"from_jsonpb: got %s, expecting a proto message constructor\", ctor.Type())\n\t}\n\ttyp := c.typ\n\n\tprotoMsg := typ.NewProtoMessage().Interface().(proto.Message)\n\tu := jsonpb.Unmarshaler{AllowUnknownFields: true}\n\tif err := u.Unmarshal(strings.NewReader(text.GoString()), protoMsg); err != nil {\n\t\treturn nil, fmt.Errorf(\"from_jsonpb: %s\", err)\n\t}\n\n\tmsg := NewMessage(typ)\n\tif err := msg.FromProto(protoMsg); err != nil {\n\t\treturn nil, fmt.Errorf(\"from_jsonpb: %s\", err)\n\t}\n\treturn msg, nil\n}", "func FromJSON(x interface{}, data []byte) Template {\n\tif err := json.Unmarshal(data, &x); err != nil {\n\t\tFatalf(\"prototype: can't apply JSON: %s\", err)\n\t}\n\treturn New(x)\n}", "func (r *StartStopServiceOrMonitorRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"InstanceId\")\n\tdelete(f, \"OpType\")\n\tdelete(f, \"OpScope\")\n\tdelete(f, \"StrategyConfig\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"StartStopServiceOrMonitorRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *ProjectsLocationsSshKeysService) Create(parent string, sshkey *SSHKey) *ProjectsLocationsSshKeysCreateCall {\n\tc := &ProjectsLocationsSshKeysCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.parent = parent\n\tc.sshkey = sshkey\n\treturn c\n}", "func (r *DescribeMixTranscodingUsageRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"StartTime\")\n\tdelete(f, \"EndTime\")\n\tdelete(f, \"SdkAppId\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"DescribeMixTranscodingUsageRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (s *Server) FromJSON(bytes []byte) error {\n\terr := json.Unmarshal(bytes, s)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (r *UpdatePluginsRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"InstanceId\")\n\tdelete(f, \"InstallPluginList\")\n\tdelete(f, \"RemovePluginList\")\n\tdelete(f, \"ForceRestart\")\n\tdelete(f, \"ForceUpdate\")\n\tdelete(f, \"PluginType\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"UpdatePluginsRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *CreateNamespaceRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"Namespace\")\n\tdelete(f, \"Description\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"CreateNamespaceRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func newOrderFromJSON(ojson *orderJSON) interface{} {\n\t// type conversions from JSON file, arguments must align\n\treturn newOrder(ojson.Type, ojson.Client, ojson.Amount, ojson.Price)\n}", "func (r *UpdatePublishCdnStreamResponse) FromJsonString(s string) error {\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *DescribeClusterNodesRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"InstanceId\")\n\tdelete(f, \"NodeFlag\")\n\tdelete(f, \"Offset\")\n\tdelete(f, \"Limit\")\n\tdelete(f, \"HardwareResourceType\")\n\tdelete(f, \"SearchFields\")\n\tdelete(f, \"OrderField\")\n\tdelete(f, \"Asc\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"DescribeClusterNodesRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *InquiryPriceCreateInstanceRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"TimeUnit\")\n\tdelete(f, \"TimeSpan\")\n\tdelete(f, \"Currency\")\n\tdelete(f, \"PayMode\")\n\tdelete(f, \"SupportHA\")\n\tdelete(f, \"Software\")\n\tdelete(f, \"ResourceSpec\")\n\tdelete(f, \"Placement\")\n\tdelete(f, \"VPCSettings\")\n\tdelete(f, \"MetaType\")\n\tdelete(f, \"UnifyMetaInstanceId\")\n\tdelete(f, \"MetaDBInfo\")\n\tdelete(f, \"ProductId\")\n\tdelete(f, \"SceneName\")\n\tdelete(f, \"ExternalService\")\n\tdelete(f, \"VersionID\")\n\tdelete(f, \"MultiZoneSettings\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"InquiryPriceCreateInstanceRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *DescribeInstancesRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"DisplayStrategy\")\n\tdelete(f, \"InstanceIds\")\n\tdelete(f, \"Offset\")\n\tdelete(f, \"Limit\")\n\tdelete(f, \"ProjectId\")\n\tdelete(f, \"OrderField\")\n\tdelete(f, \"Asc\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"DescribeInstancesRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func NewPictureJSON(jsonBytes []byte) *Picture {\n\tpicture := new(Picture)\n\terr := json.Unmarshal(jsonBytes, picture)\n\tif err == nil {\n\t\treturn picture\n\t}\n\treturn nil\n}", "func (r *CreateAuditTrackRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"Name\")\n\tdelete(f, \"ActionType\")\n\tdelete(f, \"ResourceType\")\n\tdelete(f, \"Status\")\n\tdelete(f, \"EventNames\")\n\tdelete(f, \"Storage\")\n\tdelete(f, \"TrackForAllMembers\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"CreateAuditTrackRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *DescribeUserClbWafRegionsRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"DescribeUserClbWafRegionsRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *CreateAccountRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"AccountType\")\n\tdelete(f, \"Mail\")\n\tdelete(f, \"Password\")\n\tdelete(f, \"ConfirmPassword\")\n\tdelete(f, \"PhoneNum\")\n\tdelete(f, \"CountryCode\")\n\tdelete(f, \"Area\")\n\tdelete(f, \"Extended\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"CreateAccountRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func CreateResourceFromJSON(buf []byte) (*Resource, error) {\n\tif buf == nil {\n\t\treturn &Resource{}, fmt.Errorf(\"Json buffer is nil\")\n\t}\n\tif len(buf) == 0 {\n\t\treturn &Resource{}, fmt.Errorf(\"Json buffer is zero-length\")\n\t}\n\n\tdest := new(Resource)\n\n\terr := json.Unmarshal(buf, dest)\n\tif err != nil {\n\t\treturn &Resource{}, fmt.Errorf(\"Error unmarshalling JSON: %v\", err)\n\t}\n\n\treturn dest, nil\n}", "func (r *DescribeAccessExportsRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"TopicId\")\n\tdelete(f, \"Offset\")\n\tdelete(f, \"Limit\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"DescribeAccessExportsRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *StopPublishCdnStreamResponse) FromJsonString(s string) error {\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *InquireAuditCreditRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\t\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"InquireAuditCreditRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func newSSHProcess(client *sshRunner, info jasper.ProcessInfo) (jasper.Process, error) {\n\tif client == nil {\n\t\treturn nil, errors.New(\"SSH process needs an SSH client to run CLI commands\")\n\t}\n\treturn &sshProcess{\n\t\tclient: client,\n\t\tinfo: info,\n\t}, nil\n}", "func NewPeerFromJSON(p PeerJSON) (Peer, error) {\n\thasIncomingPort := false\n\tif p.HasIncomingPort != nil {\n\t\thasIncomingPort = *p.HasIncomingPort\n\t} else if p.HasIncomePort != nil {\n\t\thasIncomingPort = *p.HasIncomePort\n\t}\n\n\t// LastSeen could be a RFC3339Nano timestamp or an int64 unix timestamp\n\tvar lastSeen int64\n\tswitch p.LastSeen.(type) {\n\tcase string:\n\t\tlastSeenTime, err := time.Parse(time.RFC3339Nano, p.LastSeen.(string))\n\t\tif err != nil {\n\t\t\treturn Peer{}, err\n\t\t}\n\t\tlastSeen = lastSeenTime.Unix()\n\tcase json.Number:\n\t\tlastSeenNum := p.LastSeen.(json.Number)\n\t\tvar err error\n\t\tlastSeen, err = lastSeenNum.Int64()\n\t\tif err != nil {\n\t\t\treturn Peer{}, err\n\t\t}\n\tdefault:\n\t\treturn Peer{}, fmt.Errorf(\"Invalid type %T for LastSeen field\", p.LastSeen)\n\t}\n\n\treturn Peer{\n\t\tAddr: p.Addr,\n\t\tLastSeen: lastSeen,\n\t\tPrivate: p.Private,\n\t\tTrusted: p.Trusted,\n\t\tHasIncomingPort: hasIncomingPort,\n\t}, nil\n}", "func (r *CreateAccessExportResponse) FromJsonString(s string) error {\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *QueryPartnerCreditRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\t\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"QueryPartnerCreditRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *DeleteAccessExportRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"ExportId\")\n\tdelete(f, \"TopicId\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"DeleteAccessExportRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func FromJSON(js string) (Car, error) {\n\tvar c car\n\terr := json.Unmarshal([]byte(js), &c)\n\treturn c, err\n}", "func (r *GetReservedConcurrencyConfigRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"FunctionName\")\n\tdelete(f, \"Namespace\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"GetReservedConcurrencyConfigRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *RestartNodesRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"InstanceId\")\n\tdelete(f, \"NodeNames\")\n\tdelete(f, \"ForceRestart\")\n\tdelete(f, \"RestartMode\")\n\tdelete(f, \"IsOffline\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"RestartNodesRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *DescribeInstancesRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"Zone\")\n\tdelete(f, \"InstanceIds\")\n\tdelete(f, \"InstanceNames\")\n\tdelete(f, \"Offset\")\n\tdelete(f, \"Limit\")\n\tdelete(f, \"OrderByKey\")\n\tdelete(f, \"OrderByType\")\n\tdelete(f, \"TagList\")\n\tdelete(f, \"IpList\")\n\tdelete(f, \"ZoneList\")\n\tdelete(f, \"HealthStatus\")\n\tdelete(f, \"VpcIds\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"DescribeInstancesRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func New(config *model.SFTP) (*server.Client, error) {\n\tvar err error\n\tvar client = &Client{cfg: config}\n\tvar sshConf *ssh.ClientConfig\n\tvar sshAuth []ssh.AuthMethod\n\n\t// SSH Auth\n\tif config.Key != \"\" {\n\t\tif sshAuth, err = client.readPublicKey(config.Key, config.Password); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to read SFTP public key, %v\", err)\n\t\t}\n\t} else {\n\t\tsshAuth = []ssh.AuthMethod{\n\t\t\tssh.Password(config.Password),\n\t\t}\n\t}\n\tsshConf = &ssh.ClientConfig{\n\t\tUser: config.Username,\n\t\tAuth: sshAuth,\n\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t\tTimeout: config.Timeout * time.Second,\n\t}\n\n\tsshConf.SetDefaults()\n\tclient.ssh, err = ssh.Dial(\"tcp\", fmt.Sprintf(\"%s:%d\", config.Host, config.Port), sshConf)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot open ssh connection, %v\", err)\n\t}\n\n\tif client.sftp, err = sftp.NewClient(client.ssh, sftp.MaxPacket(config.MaxPacketSize)); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &server.Client{Handler: client}, err\n}", "func (r *TerminateClusterNodesRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"InstanceId\")\n\tdelete(f, \"CvmInstanceIds\")\n\tdelete(f, \"NodeFlag\")\n\tdelete(f, \"GraceDownFlag\")\n\tdelete(f, \"GraceDownTime\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"TerminateClusterNodesRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func NewJson(s string) Json {\n\tif s == \"\" {\n\t\treturn \"\"\n\t}\n\tif j := strings.TrimSpace(s); j != \"\" && len(j) > 1 {\n\t\treturn Json(j)\n\t}\n\treturn \"\"\n}", "func (r *DeleteSessionRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"Domain\")\n\tdelete(f, \"Edition\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"DeleteSessionRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (a *StartScreencastArgs) UnmarshalJSON(b []byte) error {\n\ttype Copy StartScreencastArgs\n\tc := &Copy{}\n\terr := json.Unmarshal(b, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*a = StartScreencastArgs(*c)\n\treturn nil\n}", "func (r *DescribeAuditTracksRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"PageNumber\")\n\tdelete(f, \"PageSize\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"DescribeAuditTracksRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (queue *Queue) FromJSON(data []byte) error {\n\treturn queue.heap.FromJSON(data)\n}", "func (r *PutTotalConcurrencyConfigResponse) FromJsonString(s string) error {\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func SecuritySchemeFromJSON(buf []byte, dst interface{}) error {\n\tv, ok := dst.(*SecurityScheme)\n\tif !ok {\n\t\treturn errors.Errorf(`dst needs to be a pointer to SecurityScheme, but got %T`, dst)\n\t}\n\tvar tmp securityScheme\n\tif err := json.Unmarshal(buf, &tmp); err != nil {\n\t\treturn errors.Wrap(err, `failed to unmarshal SecurityScheme`)\n\t}\n\t*v = &tmp\n\treturn nil\n}", "func (r *ListCosEnableRegionRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"WebsiteType\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"ListCosEnableRegionRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *CreateAliasRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"Name\")\n\tdelete(f, \"FunctionName\")\n\tdelete(f, \"FunctionVersion\")\n\tdelete(f, \"Namespace\")\n\tdelete(f, \"RoutingConfig\")\n\tdelete(f, \"Description\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"CreateAliasRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *ModifyResourceSchedulerRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"InstanceId\")\n\tdelete(f, \"OldValue\")\n\tdelete(f, \"NewValue\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"ModifyResourceSchedulerRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *PublishLayerVersionRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"LayerName\")\n\tdelete(f, \"CompatibleRuntimes\")\n\tdelete(f, \"Content\")\n\tdelete(f, \"Description\")\n\tdelete(f, \"LicenseInfo\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"PublishLayerVersionRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *Robot) FromJSON(jsonData string) error {\n\tif len(jsonData) == 0 {\n\t\treturn errors.New(\"empty json data to parse\")\n\t}\n\n\treturn json.Unmarshal([]byte(jsonData), r)\n}", "func (r *QueryCustomersCreditRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"FilterType\")\n\tdelete(f, \"Filter\")\n\tdelete(f, \"Page\")\n\tdelete(f, \"PageSize\")\n\tdelete(f, \"Order\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"QueryCustomersCreditRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *GetCountryCodesRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\t\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"GetCountryCodesRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func FromJSON(paramsJSON string) (backend.Backend, error) {\n\tcfg := Config{}\n\terr := json.Unmarshal([]byte(paramsJSON), &cfg)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\treturn New(cfg)\n}", "func (r *QueryDirectCustomersCreditRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\t\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"QueryDirectCustomersCreditRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *Registration) FromJSON(jsonData string) error {\n\tif len(jsonData) == 0 {\n\t\treturn errors.New(\"empty json data to parse\")\n\t}\n\n\treturn json.Unmarshal([]byte(jsonData), r)\n}", "func (c *Center) CallWithJson(b []byte) (interface{}, error) {\n\tcmd := &Command{}\n\terr := json.Unmarshal(b, cmd)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"JSON syntax error.\")\n\t}\n\treturn c.Call(cmd.Name, cmd.Args...)\n}", "func (r *RestartInstanceRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"InstanceId\")\n\tdelete(f, \"ForceRestart\")\n\tdelete(f, \"RestartMode\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"RestartInstanceRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *GetProvisionedConcurrencyConfigResponse) FromJsonString(s string) error {\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func fromJson(jsonBytes []byte) (ResumeData, error) {\n\tvar data ResumeData\n\terr := json.Unmarshal(jsonBytes, &data)\n\treturn data, err\n}", "func (r *DescribeFlowTrendRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"Domain\")\n\tdelete(f, \"StartTs\")\n\tdelete(f, \"EndTs\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"DescribeFlowTrendRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (r *DeleteReservedConcurrencyConfigRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"FunctionName\")\n\tdelete(f, \"Namespace\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"DeleteReservedConcurrencyConfigRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func ParseJSON(data []byte) (*cloudformation.Template, error) {\n\treturn ParseJSONWithOptions(data, nil)\n}", "func (r *Request) FromJSON(data string) (*Request, error) {\n\tvar req Request\n\terr := json.Unmarshal([]byte(data), &req)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not deserialise json into Create request: %w\", err)\n\t}\n\n\treturn &req, nil\n}", "func (r *AllocateCustomerCreditResponse) FromJsonString(s string) error {\n\treturn json.Unmarshal([]byte(s), &r)\n}" ]
[ "0.54791486", "0.54042786", "0.53776586", "0.53611845", "0.53110397", "0.5243469", "0.5240868", "0.51889795", "0.5179141", "0.51741886", "0.5161294", "0.5137017", "0.5074047", "0.5005854", "0.49931017", "0.4984174", "0.49608943", "0.4929296", "0.49131292", "0.48126945", "0.48105833", "0.48015362", "0.4796305", "0.47902313", "0.47524768", "0.4730518", "0.47168213", "0.47060123", "0.4690245", "0.46719992", "0.46696448", "0.4647834", "0.46420398", "0.46372104", "0.4634508", "0.4629098", "0.46251068", "0.46175584", "0.46159348", "0.45984516", "0.45892093", "0.45879847", "0.45755824", "0.4575482", "0.4570697", "0.4568128", "0.45628202", "0.4561971", "0.45475364", "0.45353064", "0.45231944", "0.45088503", "0.45085624", "0.4504633", "0.4487413", "0.44812533", "0.44810405", "0.44795978", "0.44686604", "0.44679627", "0.44646943", "0.44479197", "0.44396874", "0.44335383", "0.44312236", "0.442887", "0.44258183", "0.4425069", "0.44236654", "0.4417991", "0.44114655", "0.44053894", "0.44033822", "0.4396665", "0.43957746", "0.43940905", "0.43846646", "0.43744218", "0.436508", "0.43602234", "0.4358499", "0.43571535", "0.43460298", "0.434369", "0.43420115", "0.4339308", "0.43384194", "0.43181428", "0.43113002", "0.43034908", "0.4301471", "0.4300724", "0.42954838", "0.4293102", "0.4288889", "0.4279167", "0.42787775", "0.42735732", "0.42652383", "0.42523918" ]
0.85841995
0
Run the current command. returns: The CommandResult An error if the command execution fails
func (scp *SCP) Run(_ string) (*entities.CommandResult, derrors.Error) { conn, err := connection.NewSSHConnection( scp.TargetHost, scp.getTargetPort(), scp.Credentials.Username, scp.Credentials.Password, "", scp.Credentials.PrivateKey) if err != nil { return nil, derrors.NewInternalError(errors.SSHConnectionError, err).WithParams(scp.TargetHost) } start := time.Now() err = conn.Copy(scp.Source, scp.Destination, false) if err != nil { return nil, derrors.NewInternalError(errors.SSHConnectionError, err).WithParams(scp.TargetHost) } return entities.NewSuccessCommand([]byte(scp.String() + ": OK " + time.Since(start).String())), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Run() error {\n\treturn command.Execute()\n}", "func Run() {\n\tcmd.Execute()\n}", "func (c *Cmd) Run() error {\n\treturn c.runInnerCommand()\n}", "func (h *Handler) Run(_ *cli.Context) error {\n\tcmd, err := newCommand(h)\n\tutils.FatalOnErr(err)\n\n\tutils.FatalOnErr(cmd.Run())\n\n\treturn nil\n}", "func (l *Logger) Run(_ string) (*entities.CommandResult, derrors.Error) {\n\treturn entities.NewSuccessCommand([]byte(l.Msg)), nil\n}", "func (c *Cmd) Run() error {\n\treturn c.Cmd.Run()\n}", "func (c Command) Run(args ...string) error {\n\treturn c.builder().Run(args...)\n}", "func (t testCommand) Run() error {\n\tif t.shouldFail {\n\t\treturn errors.New(\"I AM ERROR\")\n\t}\n\treturn nil\n}", "func (c *CmdReal) Run() error {\n\treturn c.cmd.Run()\n}", "func Execute() error {\n\treturn cmd.Execute()\n}", "func (r StoreBot) Run(command *SlashCommand) (slashCommandImmediateReturn string) {\n // If you (optionally) want to do some asynchronous work (like sending API calls to slack)\n // you can put it in a go routine like this\n go r.DeferredAction(command)\n // The string returned here will be shown only to the user who executed the command\n // and will show up as a message from slackbot.\n return \"\"\n}", "func (client *Client) Run() {\n\tret, val, msg := client.executeCommand()\n\tlog.Printf(\"Execute command result: %v\", ret)\n\tlog.Printf(\"Execute command value: %v\", val)\n\tlog.Printf(\"Execute command message: %v\", msg)\n}", "func (c *Commandable) Run() (status *types.CommandStatus, err error) {\n\truncmdlist, err := NewRunCmdListFromSpec(c.Command.Spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout := runcmdlist.Run()\n\tc.setStatus(out)\n\treturn c.Status, nil\n}", "func (c *Command) Run(ctx context.Context) error {\n\t// TODO: criteria\n\terr := c.Exec(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif c.Next != nil {\n\t\treturn c.Next.Run(ctx)\n\t}\n\n\treturn nil\n}", "func Execute() error { return rootCmd.Execute() }", "func (tile38 *Tile38Adapter) RunCommand(q *Command) (interface{}, error) {\n\n\tcmd := redis.NewCmd(q.QueryParts...)\n\n\ttile38.client.Process(cmd)\n\n\tresult, err := cmd.Result()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}", "func (ac *activeClient) runCommand(c *ishell.Context) {\n\tcommand := strings.Join(c.Args, \" \")\n\tvar r string\n\targs := shared.Cmd{\n\t\tCmd: command,\n\t\tPowershell: false,\n\t}\n\n\tif err := ac.RPC.Call(\"API.RunCmd\", args, &r); err != nil {\n\t\tc.Println(yellow(\"[\"+ac.Data().Name+\"] \") + red(\"[!] Bad or unkown command:\", err))\n\t}\n\n\tc.Println(r)\n}", "func runCommand(cmd *exec.Cmd) error {\n\terr := cmd.Run()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (db Database) Run(cmd interface{}, result interface{}) os.Error {\n\tcursor, err := db.Conn.Find(db.Name+\".$cmd\", cmd, runFindOptions)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar d BSONData\n\tif err := cursor.Next(&d); err != nil {\n\t\treturn err\n\t}\n\n\tvar r CommandResponse\n\tif err := Decode(d.Data, &r); err != nil {\n\t\treturn err\n\t}\n\tif err := r.Error(); err != nil {\n\t\treturn err\n\t}\n\n\tif result != nil {\n\t\tif err := d.Decode(result); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (dc *DriverCall) Run() (*DriverStatus, error) {\n\tcmd := dc.plugin.runner.Command(dc.Execpath, dc.args...)\n\n\ttimeout := false\n\tif dc.Timeout > 0 {\n\t\ttimer := time.AfterFunc(dc.Timeout, func() {\n\t\t\ttimeout = true\n\t\t\tcmd.Stop()\n\t\t})\n\t\tdefer timer.Stop()\n\t}\n\n\toutput, execErr := cmd.CombinedOutput()\n\tif execErr != nil {\n\t\tif timeout {\n\t\t\treturn nil, ErrorTimeout\n\t\t}\n\t\t_, err := handleCmdResponse(dc.Command, output)\n\t\tif err == nil {\n\t\t\tglog.Errorf(\"FlexVolume: driver bug: %s: exec error (%s) but no error in response.\", dc.Execpath, execErr)\n\t\t\treturn nil, execErr\n\t\t}\n\n\t\tglog.Warningf(\"FlexVolume: driver call failed: executable: %s, args: %s, error: %s, output: %q\", dc.Execpath, dc.args, execErr.Error(), output)\n\t\treturn nil, err\n\t}\n\n\tstatus, err := handleCmdResponse(dc.Command, output)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn status, nil\n}", "func (r *MockRunner) Run(cmd *exec.Cmd) error {\n\targs := r.Called(cmd)\n\treturn args.Error(0)\n}", "func (client *activeClient) runCommand(c *ishell.Context) {\n\tcommand := strings.Join(c.Args, \" \")\n\tvar r string\n\targs := shared.Cmd{\n\t\tCmd: command,\n\t\tPowershell: false,\n\t}\n\n\terr := client.RPC.Call(\"API.RunCmd\", args, &r)\n\tif err != nil {\n\t\tc.Println(yellow(\"[\"+client.Client.Name+\"] \") + red(\"[!] Bad or unkown command!\"))\n\t\tc.Println(yellow(\"[\"+client.Client.Name+\"] \") + red(\"[!] \", err))\n\t}\n\n\tc.Println(r)\n}", "func (c *Command) run(cmd, path string, clearStack bool) error {\n\tif c.specialCmd(cmd, path) {\n\t\treturn nil\n\t}\n\tcmds := strings.Split(cmd, \" \")\n\tcommand := strings.ToLower(cmds[0])\n\tgvr, v, err := c.viewMetaFor(command)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch command {\n\tcase \"ctx\", \"context\", \"contexts\":\n\t\tif len(cmds) == 2 {\n\t\t\treturn useContext(c.app, cmds[1])\n\t\t}\n\t\treturn c.exec(cmd, gvr, c.componentFor(gvr, path, v), clearStack)\n\tcase \"dir\":\n\t\tif len(cmds) != 2 {\n\t\t\treturn errors.New(\"You must specify a directory\")\n\t\t}\n\t\treturn c.app.dirCmd(cmds[1])\n\tdefault:\n\t\t// checks if Command includes a namespace\n\t\tns := c.app.Config.ActiveNamespace()\n\t\tif len(cmds) == 2 {\n\t\t\tns = cmds[1]\n\t\t}\n\t\tif err := c.app.switchNS(ns); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !c.alias.Check(command) {\n\t\t\treturn fmt.Errorf(\"`%s` Command not found\", cmd)\n\t\t}\n\t\treturn c.exec(cmd, gvr, c.componentFor(gvr, path, v), clearStack)\n\t}\n}", "func (r RealCommandRunner) Run(command string, args ...string) ([]byte, error) {\n\tout, err := exec.Command(command, args...).CombinedOutput()\n\treturn out, err\n}", "func (cmd *Cmd) Run() error {\n\tif isWindows {\n\t\treturn cmd.Spawn()\n\t}\n\treturn cmd.Exec()\n}", "func (c *LocalCmd) Run() error {\n\treturn runCmd(c.cmd, c.args, c.env, ioutil.Discard, ioutil.Discard)\n}", "func (ins *EC2RemoteClient) RunCommand(cmd string) (exitStatus int, err error) {\n\texitStatus, err = ins.cmdClient.RunCommand(cmd)\n\treturn exitStatus, err\n}", "func (mikrotikAPI MikrotikAPI) RunCmd(body string, expect *regexp.Regexp) (result string, err error) {\n\treply, err := mikrotikAPI.mtClient.RunArgs(strings.Split(body, \" \"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif expect != nil {\n\t\t_, err = waitForExpected(strings.NewReader(reply.String()), expect)\n\t}\n\n\treturn fmt.Sprintf(\"%s\\n%s\", body, reply.String()), err\n}", "func Run(cmd *exec.Cmd) (*RunResult, error) {\n\trr := &RunResult{Args: cmd.Args}\n\n\tvar outb, errb bytes.Buffer\n\tcmd.Stdout, rr.Stdout = &outb, &outb\n\tcmd.Stderr, rr.Stderr = &errb, &errb\n\n\tstart := time.Now()\n\tklog.V(1).Infof(\"Running: %s\", cmd)\n\terr := cmd.Run()\n\trr.Duration = time.Since(start)\n\n\tif err != nil {\n\t\tif exitError, ok := err.(*exec.ExitError); ok {\n\t\t\trr.ExitCode = exitError.ExitCode()\n\t\t}\n\t}\n\n\tklog.V(1).Infof(\"Completed: %s (duration: %s, exit code: %d, err: %v)\", cmd, rr.Duration, rr.ExitCode, err)\n\tif len(rr.Stderr.Bytes()) > 0 {\n\t\tklog.V(1).Infof(\"stderr:\\n%s\\n\", rr.Stderr.String())\n\t}\n\n\treturn rr, err\n}", "func (self *Client) RunCommand(cmd *Command) (string, []error) {\n var (\n output string\n errs []error\n )\n\n //- Compile our \"Valid\" and \"Error\" REGEX patterns, if not done already.\n // This will allow us to reuse it with compiling it every time.\n cmd.CompileCmdRegex()\n\n\tcmd.LogCommandConfig() //- DEBUG\n\n //- \"Write\" the command to the remote SSH session.\n self.StdinPipe.Write([]byte(cmd.Exec))\n\n //- Loop until we've gotten all output from the remote SSH Session.\n done := false\n lastError := \"\"\n for done != true {\n b, _ := self.StdoutPipe.ReadByte()\n output = output + string(b)\n\n //- Check for errors, if we have any ErrorPatterns to test.\n if len(cmd.ErrorPatterns) > 0 {\n if matchedError, errDesc := testRegex(output, cmd.ErrorRegex); matchedError == true {\n if lastError != errDesc {\n errs = append(errs, fmt.Errorf(\"Matched error pattern: %s\", errDesc))\n lastError = errDesc\n }\n }\n }\n\n //- Check for Valid output. Continue retrieving bytes until we see a\n // \"valid\" pattern.\n if done, _ = testRegex(output, cmd.ValidRegex); done == true {\n //- Make sure there isn't any more left to read.\n//\t\t\ttime.Sleep(time.Second)\n if buff := self.StdoutPipe.Buffered(); buff != 0 {\n done = false\n }\n }\n }\n\n return output, errs\n}", "func Execute() {\n\tif err := cmd.Execute(); err != nil {\n\t\tlog.Printf(\"failed command execution: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}", "func Execute() {\n if err := rootCmd.Execute(); err != nil {\n fmt.Println(err)\n os.Exit(1)\n }\n}", "func Execute() {\n if err := rootCmd.Execute(); err != nil {\n fmt.Println(err)\n os.Exit(1)\n }\n}", "func Execute() {\n if err := rootCmd.Execute(); err != nil {\n fmt.Println(err)\n os.Exit(1)\n }\n}", "func (command Command) Execute() (result model.Result) {\n\tfmt.Println(command.Description)\n\tlog.Printf(\"Executing: %s in %s\", command.Command, command.Path)\n\t// Create the command\n\tcmd := exec.Command(command.Command, command.Args...)\n\tcmd.Dir = command.Path\n\n\tvar writer io.Writer\n\tvar stdBuffer bytes.Buffer\n\n\t// If it's silent we only write to the buffer\n\tif command.Silent {\n\t\twriter = io.MultiWriter(&stdBuffer)\n\t} else {\n\t\twriter = io.MultiWriter(os.Stdout, &stdBuffer)\n\t}\n\n\tcmd.Stdout = writer\n\tcmd.Stderr = writer\n\n\t// Execute the command\n\tif err := cmd.Run(); err != nil {\n\t\tlog.Print(err)\n\t\treturn model.Result{\n\t\t\tMessage: err.Error(),\n\t\t\tWasSuccessful: false,\n\t\t}\n\t}\n\n\t// Read the output of the executed command\n\t// For now we just log it. But it could be later used to determine the success of running the command.\n\tlog.Println(\"Command output:\")\n\tlog.Println(\"-----------------------------------\")\n\tscanner := bufio.NewScanner(&stdBuffer)\n\tfor scanner.Scan() {\n\t\tlog.Println(scanner.Text())\n\t}\n\tlog.Println(\"-----------------------------------\")\n\n\tresult.WasSuccessful = true\n\tresult.Message = \"The command \\\"\" + command.Command + \"\\\"\" + \" was executed successfully.\"\n\n\treturn result\n}", "func Run(cmd *exec.Cmd) (*RunResult, error) {\n\trr := &RunResult{Args: cmd.Args}\n\n\tvar outb, errb bytes.Buffer\n\tcmd.Stdout, rr.Stdout = &outb, &outb\n\tcmd.Stderr, rr.Stderr = &errb, &errb\n\n\tstart := time.Now()\n\tklog.V(1).Infof(\"Running: %s\", cmd)\n\terr := cmd.Run()\n\trr.Duration = time.Since(start)\n\n\tif err != nil {\n\t\tif exitError, ok := err.(*exec.ExitError); ok {\n\t\t\trr.ExitCode = exitError.ExitCode()\n\t\t}\n\t\tklog.Errorf(\"cmd.Run returned error: %v\", err)\n\t}\n\n\tklog.V(1).Infof(\"Completed: %s (duration: %s, exit code: %d, err: %v)\", cmd, rr.Duration, rr.ExitCode, err)\n\tif len(rr.Stderr.Bytes()) > 0 {\n\t\tklog.Warningf(\"%s\", rr.Stderr.String())\n\t}\n\n\tif err == nil {\n\t\treturn rr, err\n\t}\n\treturn rr, fmt.Errorf(\"%s: %w, stderr=%s\", cmd.Args, err, errb.String())\n}", "func runCommand() {\n\tvar commandOutput bytes.Buffer\n\tvar c *exec.Cmd\n\tif len(commandArgs) > 1 {\n\t\tc = exec.Command(commandArgs[0], commandArgs[1:]...)\n\t} else {\n\t\tc = exec.Command(commandArgs[0])\n\t}\n\tc.Stdout = &commandOutput\n\tc.Stderr = &commandOutput\n\n\terr := c.Run()\n\tif err != nil {\n\t\toutput.PrintError(commandOutput, err)\n\t} else if commandOutput.String() != \"\" {\n\t\toutput.PrintSuccess(commandOutput)\n\t} else {\n\t\toutput.NoError()\n\t}\n}", "func Run(cmd *exec.Cmd) error {\n\treturn DefaultRunner.Run(cmd)\n}", "func (cmd *Command) Run() error {\n\t// Copied from exec.Cmd#Run\n\tif err := cmd.Start(); err != nil {\n\t\treturn err\n\t}\n\treturn cmd.Wait()\n}", "func (o *Cmd) Run(rl lib.ReactorLog, msg lib.Msg) error {\n\n\tvar args []string\n\n\tif o.argsjson {\n\t\tfor _, parse := range o.args {\n\t\t\tif strings.Contains(parse, \"$.\") {\n\t\t\t\tnewParse := parse\n\t\t\t\tfor _, argValue := range strings.Split(parse, \"$.\") {\n\t\t\t\t\tif argValue == \"\" {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\top, _ := jq.Parse(\".\" + argValue) // create an Op\n\t\t\t\t\tvalue, _ := op.Apply(msg.Body())\n\t\t\t\t\tnewParse = strings.Replace(newParse, \"$.\"+argValue, strings.Trim(string(value), \"\\\"\"), -1)\n\t\t\t\t}\n\t\t\t\targs = append(args, newParse)\n\t\t\t} else {\n\t\t\t\targs = append(args, parse)\n\t\t\t}\n\t\t}\n\t} else {\n\t\targs = o.args\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), maximumCmdTimeLive)\n\tdefer cancel()\n\n\tvar c *exec.Cmd\n\tif len(args) > 0 {\n\t\tc = exec.CommandContext(ctx, o.cmd, args...)\n\t} else {\n\t\tc = exec.CommandContext(ctx, o.cmd)\n\t}\n\n\tc.Stdout = rl\n\tc.Stderr = rl\n\n\trunlog := fmt.Sprintf(\"RUN: %s %s\", o.cmd, strings.Join(args, \" \"))\n\tlog.Println(runlog)\n\trl.WriteStrings(runlog)\n\tif err := c.Run(); err != nil {\n\t\t// This will fail after timeout.\n\t\trl.WriteStrings(fmt.Sprintf(\"ERROR: %s\", err))\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Command) Run(ctx *Context) {\n\tc.initialize()\n\n\tif c.ShowHelp == nil {\n\t\tc.ShowHelp = showHelp\n\t}\n\n\t// parse cli arguments\n\tcl := &commandline{\n\t\tflags: c.Flags,\n\t\tcommands: c.Commands,\n\t}\n\tvar err error\n\tif c.SkipFlagParsing {\n\t\tcl.args = ctx.args[1:]\n\t} else {\n\t\terr = cl.parse(ctx.args[1:])\n\t}\n\n\t// build context\n\tnewCtx := &Context{\n\t\tname: ctx.name + \" \" + c.Name,\n\t\tapp: ctx.app,\n\t\tcommand: c,\n\t\tflags: c.Flags,\n\t\tcommands: c.Commands,\n\t\targs: cl.args,\n\t\tparent: ctx,\n\t}\n\n\tif err != nil {\n\t\tnewCtx.ShowError(err)\n\t}\n\n\t// show --help\n\tif newCtx.GetBool(\"help\") {\n\t\tnewCtx.ShowHelpAndExit(0)\n\t}\n\n\t// command not found\n\tif cl.command == nil && len(c.Commands) > 0 && len(cl.args) > 0 {\n\t\tcmd := cl.args[0]\n\t\tif c.OnCommandNotFound != nil {\n\t\t\tc.OnCommandNotFound(newCtx, cmd)\n\t\t} else {\n\t\t\tnewCtx.ShowError(fmt.Errorf(\"no such command: %s\", cmd))\n\t\t}\n\t\treturn\n\t}\n\n\t// run command\n\tif cl.command != nil {\n\t\tcl.command.Run(newCtx)\n\t\treturn\n\t}\n\n\tif c.Action != nil {\n\t\tdefer newCtx.handlePanic()\n\t\tc.Action(newCtx)\n\t} else {\n\t\tnewCtx.ShowHelpAndExit(0)\n\t}\n}", "func (s *replayService) Run(command string) error {\n\tif commands, ok := s.commands.Commands[command]; ok {\n\t\tif commands.Error != \"\" {\n\t\t\treturn errors.New(commands.Error)\n\t\t}\n\t}\n\ts.commands.Next(command)\n\treturn nil\n}", "func (i ios) Run(ctx context.Context, command string) (string, error) {\n\toutput, err := i.RunUntil(ctx, command, i.basePrompt())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\toutput = strings.ReplaceAll(output, \"\\r\\n\", \"\\n\")\n\tlines := strings.Split(output, \"\\n\")\n\tresult := \"\"\n\n\tfor i := 1; i < len(lines)-1; i++ {\n\t\tresult += lines[i] + \"\\n\"\n\t}\n\n\treturn result, nil\n}", "func (k *OcRunner) RunCommand(command string) (stdOut string, stdErr string, exitCode int, err error) {\n\tstdOut, stdErr, exitCode, err = runCommand(command, k.CommandPath)\n\treturn\n}", "func Run() int {\n\tflag.Parse()\n\tctx := context.Background()\n\tres := subcommands.Execute(ctx)\n\treturn int(res)\n}", "func (b *RunStep) Run(state quantum.StateBag) error {\n\trunner := state.Get(\"runner\").(quantum.Runner)\n\tconn := state.Get(\"conn\").(quantum.AgentConn)\n\toutCh := conn.Logs()\n\tsigCh := conn.Signals()\n\n\tif b.Command == \"\" {\n\t\tcommandRaw, ok := state.GetOk(\"command\")\n\t\tif ok {\n\t\t\tb.Command = commandRaw.(string)\n\t\t}\n\t}\n\n\tlog.Printf(\"Running command: %v\", b.Command)\n\n\terr := runner.Run(b.Command, outCh, sigCh)\n\tif err != nil {\n\t\treturn errors.New(\"Cmd: \" + b.Command + \" failed: \" + err.Error())\n\t}\n\treturn nil\n}", "func Run() {\n\tif len(os.Args) < 2 {\n\t\tusageExit(errors.New(\"missing command name\"))\n\t}\n\tselected := os.Args[1]\n\tif selected == \"-h\" || selected == \"--help\" || selected == \"-help\" {\n\t\tusageExit(nil)\n\t}\n\tif strings.HasPrefix(selected, \"-\") {\n\t\tusageExit(errors.New(\"command name required as first argument\"))\n\t}\n\tcmd, ok := commands[selected]\n\tif !ok {\n\t\tusageExit(errors.New(\"unknown command '\" + selected + \"'\"))\n\t}\n\n\t// flags.Parse prints help in case of -help. I'm not a fan of this.\n\tcmd.flags.SetOutput(ioutil.Discard)\n\terr := cmd.flags.Parse(os.Args[2:])\n\tcmd.flags.SetOutput(Output)\n\tif err == flag.ErrHelp {\n\t\tcmdUsageExit(cmd.flags, nil)\n\t}\n\tif err != nil {\n\t\tcmdUsageExit(cmd.flags, err)\n\t}\n\terr = cmd.f()\n\tif err != nil {\n\t\tif isArgError(err) {\n\t\t\tcmdUsageExit(cmd.flags, err)\n\t\t}\n\t\tfmt.Fprintf(Output, \"Error running %s command: %+v\", cmd.flags.Name(), err)\n\t\tos.Exit(1)\n\t}\n\tos.Exit(0)\n}", "func (cmd *Cmd) Run() error {\n\tvar stderr bytes.Buffer\n\tcmd.cmd.Stderr = &stderr\n\terr := cmd.cmd.Run()\n\tif err != nil {\n\t\tswitch err.(type) {\n\t\tcase *exec.ExitError:\n\t\t\tfmt.Fprintf(os.Stderr, \"%s\\n\", stderr.String())\n\t\t\treturn err\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (f CommanderFunc) Run(ctx context.Context, command string, args ...string) error {\n\treturn f(ctx, command, args...)\n}", "func Run(cmd *exec.Cmd) (string, error) {\n\tklog.V(4).Infof(\"Executing: %s\", cmd)\n\n\tr, w := io.Pipe()\n\tcmd.Stdout = w\n\tcmd.Stderr = w\n\tbuffer := new(bytes.Buffer)\n\tr2 := io.TeeReader(r, buffer)\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tscanner := bufio.NewScanner(r2)\n\t\tfor scanner.Scan() {\n\t\t\tklog.V(5).Infof(\"%s: %s\", cmd.Path, scanner.Text())\n\t\t}\n\t}()\n\terr := cmd.Run()\n\tw.Close()\n\twg.Wait()\n\tklog.V(4).Infof(\"%s terminated, with %d bytes of output and error %v\", cmd.Path, buffer.Len(), err)\n\n\toutput := string(buffer.Bytes())\n\tif err != nil {\n\t\terr = fmt.Errorf(\"command %q failed: %v\\nOutput: %s\", cmd, err, output)\n\t}\n\treturn output, err\n}", "func (c DefaultCommander) Run(cmd *exec.Cmd) ([]byte, error) {\n\tout, err := cmd.Output()\n\tdefer func() {\n\t\t// If this fails, there isn't much to do\n\t\t_ = cmd.Process.Kill()\n\t}()\n\n\treturn out, err\n}", "func (state *State) RunCommand(script *Script, code *Value, params []*Value) (ret *Value, err error) {\n\tscript.Host = state\n\n\terr = nil\n\tdefer state.trapErrorRuntime(script, &err, script.ClearMost)\n\t\n\tif code.Type != TypCode && code.Type != TypCommand {\n\t\tRaiseError(\"Attempt to run non-executable Value.\")\n\t}\n\tcode.call(script, nil, params)\n\tret = script.RetVal\n\treturn\n}", "func (j Jibi) RunCommand(cmd Command, resp chan string) {\n\tif cmd < cmdCPU {\n\t\tj.cpu.RunCommand(cmd, resp)\n\t} else if cmd < cmdGPU {\n\t\tj.gpu.RunCommand(cmd, resp)\n\t} else if cmd < cmdKEYPAD {\n\t\tj.kp.RunCommand(cmd, resp)\n\t} else if cmd < cmdALL {\n\t\tj.cpu.RunCommand(cmd, resp)\n\t\tj.gpu.RunCommand(cmd, resp)\n\t\tj.kp.RunCommand(cmd, resp)\n\t}\n}", "func (e *executor) Run(cmd *exec.Cmd) (string, error) {\n\treturn e.RunWithContext(context.Background(), cmd)\n}", "func (c *PushCommand) Run(args []string) int {\n\n\treturn 0\n}", "func (instance *Host) Run(ctx context.Context, cmd string, outs outputs.Enum, connectionTimeout, executionTimeout time.Duration) (_ int, _ string, _ string, ferr fail.Error) {\n\tdefer fail.OnPanic(&ferr)\n\tconst invalid = -1\n\n\tif valid.IsNil(instance) {\n\t\treturn invalid, \"\", \"\", fail.InvalidInstanceError()\n\t}\n\n\tif ctx == nil {\n\t\treturn invalid, \"\", \"\", fail.InvalidParameterCannotBeNilError(\"ctx\")\n\t}\n\tif cmd == \"\" {\n\t\treturn invalid, \"\", \"\", fail.InvalidParameterError(\"cmd\", \"cannot be empty string\")\n\t}\n\n\treturn instance.unsafeRun(ctx, cmd, outs, connectionTimeout, executionTimeout)\n}", "func Run(cmd *exec.Cmd) (string, error) {\n\treturn DefaultExecutor.Run(cmd)\n}", "func (c Command) Run(ctx *Context) (err error) {\n\tif !c.SkipFlagParsing {\n\t\tif len(c.Subcommands) > 0 {\n\t\t\treturn c.startApp(ctx)\n\t\t}\n\t}\n\n\tif !c.HideHelp && (HelpFlag != BoolFlag{}) {\n\t\t// append help to flags\n\t\tc.Flags = append(\n\t\t\tc.Flags,\n\t\t\tHelpFlag,\n\t\t)\n\t}\n\n\tif ctx.App.UseShortOptionHandling {\n\t\tc.UseShortOptionHandling = true\n\t}\n\n\tset, err := c.parseFlags(ctx.Args().Tail(), ctx.shellComplete)\n\n\tcontext := NewContext(ctx.App, set, ctx)\n\tcontext.Command = c\n\tif checkCommandCompletions(context, c.Name) {\n\t\treturn nil\n\t}\n\n\tif err != nil {\n\t\tif c.OnUsageError != nil {\n\t\t\terr := c.OnUsageError(context, err, false)\n\t\t\tcontext.App.handleExitCoder(context, err)\n\t\t\treturn err\n\t\t}\n\t\t_, _ = fmt.Fprintln(context.App.Writer, \"Incorrect Usage:\", err.Error())\n\t\t_, _ = fmt.Fprintln(context.App.Writer)\n\t\t_ = ShowCommandHelp(context, c.Name)\n\t\treturn err\n\t}\n\n\tif checkCommandHelp(context, c.Name) {\n\t\treturn nil\n\t}\n\n\tcerr := checkRequiredFlags(c.Flags, context)\n\tif cerr != nil {\n\t\t_ = ShowCommandHelp(context, c.Name)\n\t\treturn cerr\n\t}\n\n\tif c.After != nil {\n\t\tdefer func() {\n\t\t\tafterErr := c.After(context)\n\t\t\tif afterErr != nil {\n\t\t\t\tcontext.App.handleExitCoder(context, err)\n\t\t\t\tif err != nil {\n\t\t\t\t\terr = NewMultiError(err, afterErr)\n\t\t\t\t} else {\n\t\t\t\t\terr = afterErr\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\tif c.Before != nil {\n\t\terr = c.Before(context)\n\t\tif err != nil {\n\t\t\tcontext.App.handleExitCoder(context, err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif c.Action == nil {\n\t\tc.Action = helpSubcommand.Action\n\t}\n\n\terr = HandleAction(c.Action, context)\n\n\tif err != nil {\n\t\tcontext.App.handleExitCoder(context, err)\n\t}\n\treturn err\n}", "func RunCommand(t *testing.T) *Command {\n\tt.Helper()\n\n\t// prefer MustRunCluster since it sets up for using etcd using\n\t// the GenDisCoConfig(size) option.\n\treturn MustRunUnsharedCluster(t, 1).GetNode(0)\n}", "func Command(command string, args ...string) *exec.Cmd { return runner.Command(command, args...) }", "func Run() {\n\tflag.Usage = usage\n\tflag.Parse()\n\n\targs := flag.Args()\n\tif len(args) < 1 {\n\t\tusage()\n\t}\n\n\tmutex.Lock()\n\tc, ok := commands[args[0]]\n\tmutex.Unlock()\n\tif !ok || !c.Runnable() {\n\t\tfmt.Fprintf(os.Stderr, \"%s: unknown subcommand %s\\nRun '%s help' for usage.\\n\", Name, args[0], Name)\n\t\tos.Exit(1)\n\t}\n\n\tfs := flag.NewFlagSet(c.Name(), flag.ExitOnError)\n\tfs.Usage = func() { Usage(c) }\n\tc.Register(fs)\n\tfs.Parse(args[1:])\n\terr := c.Run(fs.Args())\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%s: %s: %v\\n\", Name, c.Name(), err)\n\t\tos.Exit(1)\n\t}\n}", "func Run() error {\n\tcmd := NewCommand(os.Stdin, os.Stdout, os.Stderr)\n\treturn cmd.Execute()\n}", "func (sshConfig *SSHConfig) Run(cmd string) (string, error) {\n\tb, err1 := sshConfig.rawRun(cmd)\n\treturn string(b), err1\n}", "func (ac *AgentCommand) Run(workingDir string) error {\n\tac.LogTask(slogger.INFO, \"Running script task for command \\n%v in directory %v\", ac.ScriptLine, workingDir)\n\n\tlogWriterInfo := &evergreen.LoggingWriter{Logger: ac.Task, Severity: level.Info}\n\tlogWriterErr := &evergreen.LoggingWriter{Logger: ac.Task, Severity: level.Error}\n\n\tignoreErrors := false\n\tif strings.HasPrefix(ac.ScriptLine, \"-\") {\n\t\tac.ScriptLine = ac.ScriptLine[1:]\n\t\tignoreErrors = true\n\t}\n\n\tcmd := &subprocess.LocalCommand{\n\t\tCmdString: ac.ScriptLine,\n\t\tWorkingDirectory: workingDir,\n\t\tStdout: logWriterInfo,\n\t\tStderr: logWriterErr,\n\t\tEnvironment: os.Environ(),\n\t}\n\terr := cmd.PrepToRun(ac.Expansions)\n\tif err != nil {\n\t\tac.LogTask(slogger.ERROR, \"Failed to prepare command: %v\", err)\n\t}\n\n\tac.LogTask(slogger.INFO, \"Running command (expanded): %v\", cmd.CmdString)\n\n\tctx, cancel := context.WithCancel(context.TODO())\n\tdoneStatus := make(chan error)\n\tgo func() {\n\t\tdoneStatus <- cmd.Run(ctx)\n\t}()\n\n\tselect {\n\tcase err = <-doneStatus:\n\t\tif ignoreErrors {\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\tcase <-ac.KillChan:\n\t\t// try and kill the process\n\t\tac.LogExecution(slogger.INFO, \"Got kill signal, stopping process: %v\", cmd.GetPid())\n\t\tcancel()\n\t\tif err := cmd.Stop(); err != nil {\n\t\t\tac.LogExecution(slogger.ERROR, \"Error occurred stopping process: %v\", err)\n\t\t}\n\t\treturn InterruptedCmdError\n\t}\n}", "func (o *ExecuteOptions) Run() error {\n\treturn o.Cmd.Help()\n}", "func (cmd *MoveCommand) Run() {\n\tnewSrcPwd := cmdPath(cmd.client.Pwd, cmd.Source)\n\tnewTargetPwd := cmdPath(cmd.client.Pwd, cmd.Target)\n\n\tt := cmd.client.GetType(newSrcPwd)\n\tif t != client.NODE && t != client.LEAF {\n\t\tfmt.Fprintln(cmd.stderr, \"Not a valid source path: \"+newSrcPwd)\n\t\treturn\n\t}\n\n\trunCommandWithTraverseTwoPaths(cmd.client, newSrcPwd, newTargetPwd, cmd.moveSecret)\n\treturn\n}", "func RunCommand(commandStr string) error {\n\tcommandStr = strings.TrimSuffix(commandStr, \"\\n\")\n\tarrCommandStr := strings.Fields(commandStr)\n\tif len(arrCommandStr) > 3 {\n\t\tarrCommandStr[2] = strings.Join(arrCommandStr[2:], \" \")\n\t\tarrCommandStr = arrCommandStr[:3]\n\t} else if len(arrCommandStr) == 0 {\n\t\treturn nil\n\t}\n\tswitch arrCommandStr[0] {\n\tcase \"exit\":\n\t\tos.Exit(0)\n\tcase \"help\":\n\t\tShowLegend()\n\t\treturn nil\n\tcase \"describe\":\n\t\treturn DescribeProcess(schema, arrCommandStr)\n\tcase \"table\":\n\t\tif result, err := SearchProcess(schema, arrCommandStr); err != nil {\n\t\t\treturn err\n\t\t} else {\n\t\t\tRenderTabularView(arrCommandStr[1], result)\n\t\t\treturn nil\n\t\t}\n\tcase \"search\":\n\t\tresult, err := SearchProcess(schema, arrCommandStr)\n\t\ts, _ := prettyjson.Marshal(result)\n\t\tfmt.Println(string(s))\n\t\treturn err\n\tdefault:\n\t\treturn fmt.Errorf(\"Unsupported command\")\n\t}\n\treturn nil\n}", "func (a *App) Command(stdout, stderr io.Writer, cmdArgs ...string) error {\n\treturn Provisioner.ExecuteCommand(stdout, stderr, a, cmdArgs[0], cmdArgs[1:]...)\n}", "func (c *Cmd) Run() error {\n\tif err := c.Start(); err != nil {\n\t\treturn err\n\t}\n\treturn c.Wait()\n}", "func (c *Cmd) Run() error {\n\tif err := c.Start(); err != nil {\n\t\treturn err\n\t}\n\treturn c.Wait()\n}", "func (c *Command) Run(t *testing.T) {\n\targs := strings.Split(c.Args, \" \")\n\tif output, err := exec.Command(c.Exec, args...).CombinedOutput(); err != nil {\n\t\tt.Fatalf(\"Error executing: '%s' '%s' -err: '%v'\", c.Exec, c.Args, strings.TrimSpace(string(output)))\n\t}\n}", "func main() {\n cmd.Execute ()\n}", "func Execute() {\n\tmainCmd.Execute()\n}", "func runCommand(command string, commandPath string) (stdOut string, stdErr string, exitCode int, err error) {\n\treturn runCommandWithTimeout(command, commandPath, \"1h\")\n}", "func (m *Manager) Run(command []string) error {\n\topts := buildah.RunOptions{}\n\treturn m.b.Run(command, opts)\n}", "func Run() error {\n\t/*\n\t\tlogs.InitLogs()\n\t\tdefer logs.FlushLogs()\n\t*/\n\n\tcmd := cmd.NewJXCommand(cmdutil.NewFactory(), os.Stdin, os.Stdout, os.Stderr)\n\treturn cmd.Execute()\n}", "func (r Runner) Run(commandAndArgs ...string) (string, error) {\n\tif len(commandAndArgs) == 0 {\n\t\treturn \"\", fmt.Errorf(\"No command provided.\")\n\t}\n\toutput, err := exec.Command(commandAndArgs[0], commandAndArgs[1:]...).CombinedOutput()\n\toutputString := string(output)\n\tif err != nil {\n\t\terrorString := fmt.Sprintf(\"%s\", err)\n\t\tif outputString != \"\" {\n\t\t\terrorString = fmt.Sprintf(\"%s, details: %s\", errorString, outputString)\n\t\t}\n\t\treturn \"\", fmt.Errorf(\"Failed to execute command %s: %s\", commandAndArgs, errorString)\n\t}\n\treturn outputString, nil\n}", "func Run(cmd *cobra.Command) (string, error) {\n\tctx := context.Background()\n\tdataIn, err := input(ctx)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to obtain input\")\n\t}\n\n\t// Further errors do not need a usage report.\n\tcmd.SilenceUsage = true\n\n\tdataOut, err := process(ctx, dataIn)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to process\")\n\t}\n\n\tif viper.GetBool(\"quiet\") {\n\t\treturn \"\", nil\n\t}\n\n\tresults, err := output(ctx, dataOut)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to obtain output\")\n\t}\n\n\treturn results, nil\n}", "func (cc *CopyCommand) RunCommand() error {\n\tcc.cpOption.recursive, _ = GetBool(OptionRecursion, cc.command.options)\n\tcc.cpOption.force, _ = GetBool(OptionForce, cc.command.options)\n\tcc.cpOption.update, _ = GetBool(OptionUpdate, cc.command.options)\n\tcc.cpOption.threshold, _ = GetInt(OptionBigFileThreshold, cc.command.options)\n\tcc.cpOption.cpDir, _ = GetString(OptionCheckpointDir, cc.command.options)\n\tcc.cpOption.routines, _ = GetInt(OptionRoutines, cc.command.options)\n\tcc.cpOption.ctnu = false\n\tif cc.cpOption.recursive {\n\t\tdisableIgnoreError, _ := GetBool(OptionDisableIgnoreError, cc.command.options)\n\t\tcc.cpOption.ctnu = !disableIgnoreError\n\t}\n\toutputDir, _ := GetString(OptionOutputDir, cc.command.options)\n\tcc.cpOption.snapshotPath, _ = GetString(OptionSnapshotPath, cc.command.options)\n\tcc.cpOption.vrange, _ = GetString(OptionRange, cc.command.options)\n\tcc.cpOption.encodingType, _ = GetString(OptionEncodingType, cc.command.options)\n\tcc.cpOption.meta, _ = GetString(OptionMeta, cc.command.options)\n\tcc.cpOption.tagging, _ = GetString(OptionTagging, cc.command.options)\n\tacl, _ := GetString(OptionACL, cc.command.options)\n\tpayer, _ := GetString(OptionRequestPayer, cc.command.options)\n\tcc.cpOption.partitionInfo, _ = GetString(OptionPartitionDownload, cc.command.options)\n\tcc.cpOption.versionId, _ = GetString(OptionVersionId, cc.command.options)\n\tcc.cpOption.enableSymlinkDir, _ = GetBool(OptionEnableSymlinkDir, cc.command.options)\n\tcc.cpOption.onlyCurrentDir, _ = GetBool(OptionOnlyCurrentDir, cc.command.options)\n\tcc.cpOption.disableDirObject, _ = GetBool(OptionDisableDirObject, cc.command.options)\n\tcc.cpOption.disableAllSymlink, _ = GetBool(OptionDisableAllSymlink, cc.command.options)\n\n\tif cc.cpOption.enableSymlinkDir && cc.cpOption.disableAllSymlink {\n\t\treturn fmt.Errorf(\"--enable-symlink-dir and --disable-all-symlink can't be both exist\")\n\t}\n\n\tvar res bool\n\tres, cc.cpOption.filters = getFilter(os.Args)\n\tif !res {\n\t\treturn fmt.Errorf(\"--include or --exclude does not support format containing dir info\")\n\t}\n\n\tif !cc.cpOption.recursive && len(cc.cpOption.filters) > 0 {\n\t\treturn fmt.Errorf(\"--include or --exclude only work with --recursive\")\n\t}\n\n\tfor k, v := range cc.cpOption.filters {\n\t\tLogInfo(\"filter %d,name:%s,pattern:%s\\n\", k, v.name, v.pattern)\n\t}\n\n\t//get file list\n\tsrcURLList, err := cc.getStorageURLs(cc.command.args[0 : len(cc.command.args)-1])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdestURL, err := StorageURLFromString(cc.command.args[len(cc.command.args)-1], cc.cpOption.encodingType)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\topType := cc.getCommandType(srcURLList, destURL)\n\tif err := cc.checkCopyArgs(srcURLList, destURL, opType); err != nil {\n\t\treturn err\n\t}\n\tif err := cc.checkCopyOptions(opType); err != nil {\n\t\treturn err\n\t}\n\n\tcc.cpOption.options = []oss.Option{}\n\tif cc.cpOption.meta != \"\" {\n\t\theaders, err := cc.command.parseHeaders(cc.cpOption.meta, false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttopts, err := cc.command.getOSSOptions(headerOptionMap, headers)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcc.cpOption.options = append(cc.cpOption.options, topts...)\n\t}\n\n\tif cc.cpOption.tagging != \"\" {\n\t\tif opType == operationTypeGet {\n\t\t\treturn fmt.Errorf(\"No need to set tagging for download\")\n\t\t}\n\t\ttags, err := cc.command.getOSSTagging(cc.cpOption.tagging)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttagging := oss.Tagging{Tags: tags}\n\t\tcc.cpOption.options = append(cc.cpOption.options, oss.SetTagging(tagging))\n\t}\n\n\tif acl != \"\" {\n\t\tif opType == operationTypeGet {\n\t\t\treturn fmt.Errorf(\"No need to set ACL for download\")\n\t\t}\n\n\t\tvar opAcl oss.ACLType\n\t\tif opAcl, err = cc.command.checkACL(acl, objectACL); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcc.cpOption.options = append(cc.cpOption.options, oss.ObjectACL(opAcl))\n\t}\n\n\tif cc.cpOption.versionId != \"\" {\n\t\tcc.cpOption.options = append(cc.cpOption.options, oss.VersionId(cc.cpOption.versionId))\n\t}\n\n\tif payer != \"\" {\n\t\tif payer != strings.ToLower(string(oss.Requester)) {\n\t\t\treturn fmt.Errorf(\"invalid request payer: %s, please check\", payer)\n\t\t}\n\t\tcc.cpOption.options = append(cc.cpOption.options, oss.RequestPayer(oss.PayerType(payer)))\n\t\tcc.cpOption.payerOptions = append(cc.cpOption.payerOptions, oss.RequestPayer(oss.PayerType(payer)))\n\t}\n\n\t// init reporter\n\tif cc.cpOption.reporter, err = GetReporter(cc.cpOption.recursive, outputDir, commandLine); err != nil {\n\t\treturn err\n\t}\n\n\t// create checkpoint dir\n\tif err := os.MkdirAll(cc.cpOption.cpDir, 0755); err != nil {\n\n\t\t//\n\t\t//fmt.Printf(\"%s\", cc.cpOption.cpDir)\n\t\treturn err\n\t}\n\n\t// load snapshot\n\tif cc.cpOption.snapshotPath != \"\" {\n\t\tif cc.cpOption.snapshotldb, err = leveldb.OpenFile(cc.cpOption.snapshotPath, nil); err != nil {\n\t\t\treturn fmt.Errorf(\"load snapshot error, reason: %s\", err.Error())\n\t\t}\n\t\tdefer cc.cpOption.snapshotldb.Close()\n\t}\n\n\tif cc.cpOption.partitionInfo != \"\" {\n\t\tif opType == operationTypeGet {\n\t\t\tsliceInfo := strings.Split(cc.cpOption.partitionInfo, \":\")\n\t\t\tif len(sliceInfo) == 2 {\n\t\t\t\tpartitionIndex, err1 := strconv.Atoi(sliceInfo[0])\n\t\t\t\tpartitionCount, err2 := strconv.Atoi(sliceInfo[1])\n\t\t\t\tif err1 != nil || err2 != nil {\n\t\t\t\t\treturn fmt.Errorf(\"parsar OptionPartitionDownload error,value is:%s\", cc.cpOption.partitionInfo)\n\t\t\t\t}\n\t\t\t\tif partitionIndex < 1 || partitionCount < 1 || partitionIndex > partitionCount {\n\t\t\t\t\treturn fmt.Errorf(\"parsar OptionPartitionDownload error,value is:%s\", cc.cpOption.partitionInfo)\n\t\t\t\t}\n\t\t\t\tcc.cpOption.partitionIndex = partitionIndex\n\t\t\t\tcc.cpOption.partitionCount = partitionCount\n\t\t\t} else {\n\t\t\t\treturn fmt.Errorf(\"parsar OptionPartitionDownload error,value is:%s\", cc.cpOption.partitionInfo)\n\t\t\t}\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"PutObject or CopyObject doesn't support option OptionPartitionDownload\")\n\t\t}\n\t} else {\n\t\tcc.cpOption.partitionIndex = 0\n\t\tcc.cpOption.partitionCount = 0\n\t}\n\n\tcc.monitor.init(opType)\n\tcc.cpOption.opType = opType\n\n\tchProgressSignal = make(chan chProgressSignalType, 10)\n\tgo cc.progressBar()\n\n\tstartT := time.Now().UnixNano() / 1000 / 1000\n\tswitch opType {\n\tcase operationTypePut:\n\t\tLogInfo(\"begin uploadFiles\\n\")\n\t\terr = cc.uploadFiles(srcURLList, destURL.(CloudURL))\n\tcase operationTypeGet:\n\t\tLogInfo(\"begin downloadFiles\\n\")\n\t\terr = cc.downloadFiles(srcURLList[0].(CloudURL), destURL.(FileURL))\n\tdefault:\n\t\tLogInfo(\"begin copyFiles\\n\")\n\t\terr = cc.copyFiles(srcURLList[0].(CloudURL), destURL.(CloudURL))\n\t}\n\tendT := time.Now().UnixNano() / 1000 / 1000\n\tif endT-startT > 0 {\n\t\taverSpeed := (cc.monitor.transferSize / (endT - startT)) * 1000\n\t\tfmt.Printf(\"\\naverage speed %d(byte/s)\\n\", averSpeed)\n\t\tLogInfo(\"average speed %d(byte/s)\\n\", averSpeed)\n\t}\n\n\tcc.cpOption.reporter.Clear()\n\tckFiles, _ := ioutil.ReadDir(cc.cpOption.cpDir)\n\tif err == nil && len(ckFiles) == 0 {\n\t\tLogInfo(\"begin Remove checkpointDir %s\\n\", cc.cpOption.cpDir)\n\t\tos.RemoveAll(cc.cpOption.cpDir)\n\t}\n\treturn err\n}", "func (s *Shell) Run(ctx context.Context, args []string) error {\n\tcmds := map[string]*Command{}\n\tfor _, cmd := range s.Commands {\n\t\tcmdNames := append(cmd.Aliases, cmd.Name)\n\t\tfor i := range cmdNames {\n\t\t\tcmds[cmdNames[i]] = cmd\n\t\t}\n\t}\n\n\tif len(args) == 1 && args[0] == \"\" {\n\t\ts.WriteUsage(os.Stdout)\n\t\treturn nil\n\t}\n\n\tcmd := args[0]\n\tvar cleanedArgs []string\n\tif len(args) > 1 {\n\t\tcleanedArgs = args[1:]\n\t}\n\n\tc, ok := cmds[cmd]\n\tif ok {\n\t\treturn c.Do(ctx, s, cleanedArgs)\n\t}\n\treturn s.hasNoSuchCommand(ctx, cmd)\n}", "func (g *UICommand) Run() error {\n\tlog.WithField(\"g\", g).Trace(\n\t\t\"Running cli command\",\n\t)\n\n\tuiServer := meshservice.NewUIServer(\n\t\tg.meshConfig.Agent.GRPCSocket,\n\t\tg.meshConfig.UI.HTTPBindAddr,\n\t\tg.meshConfig.UI.HTTPBindPort)\n\tuiServer.Serve()\n\n\treturn nil\n}", "func (r *RunCommand) Execute(args []string) (err error) {\n\t// If we run as a service, we need to catch panics.\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tcerberus.Logger.Fatalln(r)\n\t\t}\n\t}()\n\n\tif err := r.RootCommand.Execute(args); err != nil {\n\t\tcerberus.Logger.Fatalln(err)\n\t}\n\n\tif err := cerberus.RunService(r.Args.Name); err != nil {\n\t\tcerberus.Logger.Fatalln(err)\n\t}\n\n\treturn nil\n}", "func (sh *Shell) RunCommand(cmd string, args []string, timeout time.Duration) (result string, err error) {\n\n\t// default timeout\n\tif timeout == 0 {\n\t\ttimeout = sh.timeout\n\t}\n\n\t// Already called in LoadRemoteEnvironment, but just in case.\n\tif !sh.tokenSet {\n\t\terr = sh.setTokenIndex(sh.Log, timeout)\n\t\tif err != nil {\n\t\t\tsh.Log.Error(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tcmd = cmd + \" \" + strings.Join(args, \" \") // Concat command and args.\n\n\t// Get platform/OS for correct dispatch. Use associated host/DB, or anything.\n\t// Waiting, only Unix...\n\treturn sh.runCommandUnix(cmd, timeout)\n}", "func (c *Tool) Run() ([]byte, error) {\n\tif IsDebug() == true {\n\t\tstart := time.Now()\n\t\tcommands := c.Commands()\n\t\tout, err := c.Command().CombinedOutput()\n\t\tfmt.Println(time.Since(start), commands)\n\t\treturn out, err\n\t}\n\treturn c.Command().CombinedOutput()\n}", "func (mock *MockEnv) Run(command ggman.Command, workdir string, stdin string, argv ...string) (code uint8, stdout, stderr string) {\n\t// create buffers\n\tstdinReader := strings.NewReader(stdin)\n\tstdoutBuffer := &bytes.Buffer{}\n\tstderrBuffer := &bytes.Buffer{}\n\n\t// create a program and run Main()\n\tfakeggman := ggman.NewProgram()\n\tccommand, _ := reflectx.CopyInterface(command)\n\tfakeggman.Register(ccommand)\n\n\tstream := stream.NewIOStream(stdoutBuffer, stderrBuffer, stdinReader, 0)\n\n\t// run the code\n\terr := exit.AsError(fakeggman.Main(stream, env.Parameters{\n\t\tVariables: mock.vars,\n\t\tPlumbing: mock.plumbing,\n\t\tWorkdir: workdir,\n\t}, argv))\n\treturn uint8(err.ExitCode), stdoutBuffer.String(), stderrBuffer.String()\n}", "func (t *Test) Run() error {\n\tfor _, cmd := range t.cmds {\n\t\t// TODO(fabxc): aggregate command errors, yield diffs for result\n\t\t// comparison errors.\n\t\tif err := t.exec(cmd); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (r *Reflex) runCommand(name string, stdout chan<- OutMsg) {\n\tcommand := replaceSubSymbol(r.command, r.subSymbol, name)\n\tcmd := exec.Command(command[0], command[1:]...)\n\tr.cmd = cmd\n\n\tif flagSequential {\n\t\tseqCommands.Lock()\n\t}\n\n\ttty, err := pty.Start(cmd)\n\tif err != nil {\n\t\tinfoPrintln(r.id, err)\n\t\treturn\n\t}\n\tr.tty = tty\n\n\tgo func() {\n\t\tscanner := bufio.NewScanner(tty)\n\t\tfor scanner.Scan() {\n\t\t\tstdout <- OutMsg{r.id, scanner.Text()}\n\t\t}\n\t\t// Intentionally ignoring scanner.Err() for now.\n\t\t// Unfortunately, the pty returns a read error when the child dies naturally, so I'm just going to ignore\n\t\t// errors here unless I can find a better way to handle it.\n\t}()\n\n\tr.mu.Lock()\n\tr.running = true\n\tr.mu.Unlock()\n\tgo func() {\n\t\terr := cmd.Wait()\n\t\tif !r.Killed() && err != nil {\n\t\t\tstdout <- OutMsg{r.id, fmt.Sprintf(\"(error exit: %s)\", err)}\n\t\t}\n\t\tr.done <- struct{}{}\n\t\tif flagSequential {\n\t\t\tseqCommands.Unlock()\n\t\t}\n\t}()\n}", "func (s *service) ExecuteCommand(pluginContext *plugin.Context, commandArgs *model.CommandArgs) (resp *model.CommandResponse, err error) {\n\tparams := &commandParams{\n\t\tpluginContext: pluginContext,\n\t\tcommandArgs: commandArgs,\n\t}\n\tif pluginContext == nil || commandArgs == nil {\n\t\treturn errorOut(params, errors.New(\"invalid arguments to command.Handler. Please contact your system administrator\"))\n\t}\n\n\tconf := s.conf.MattermostConfig().Config()\n\tenableOAuthServiceProvider := conf.ServiceSettings.EnableOAuthServiceProvider\n\tif enableOAuthServiceProvider == nil || !*enableOAuthServiceProvider {\n\t\treturn errorOut(params, errors.Errorf(\"the system setting `Enable OAuth 2.0 Service Provider` needs to be enabled in order for the Apps plugin to work. Please go to %s/admin_console/integrations/integration_management and enable it.\", commandArgs.SiteURL))\n\t}\n\n\tenableBotAccounts := conf.ServiceSettings.EnableBotAccountCreation\n\tif enableBotAccounts == nil || !*enableBotAccounts {\n\t\treturn errorOut(params, errors.Errorf(\"the system setting `Enable Bot Account Creation` needs to be enabled in order for the Apps plugin to work. Please go to %s/admin_console/integrations/bot_accounts and enable it.\", commandArgs.SiteURL))\n\t}\n\n\tsplit := strings.Fields(commandArgs.Command)\n\tif len(split) < 2 {\n\t\treturn errorOut(params, errors.New(\"no subcommand specified, nothing to do\"))\n\t}\n\n\tcommand := split[0]\n\tif command != \"/\"+config.CommandTrigger {\n\t\treturn errorOut(params, errors.Errorf(\"%q is not a supported command and should not have been invoked. Please contact your system administrator\", command))\n\t}\n\n\tparams.current = split[1:]\n\n\tdefer func(log utils.Logger, developerMode bool) {\n\t\tif x := recover(); x != nil {\n\t\t\tstack := string(debug.Stack())\n\n\t\t\tlog.Errorw(\n\t\t\t\t\"Recovered from a panic in a command\",\n\t\t\t\t\"command\", commandArgs.Command,\n\t\t\t\t\"error\", x,\n\t\t\t\t\"stack\", stack,\n\t\t\t)\n\n\t\t\ttxt := utils.CodeBlock(commandArgs.Command+\"\\n\") + \"Command paniced. \"\n\n\t\t\tif developerMode {\n\t\t\t\ttxt += fmt.Sprintf(\"Error: **%v**. Stack:\\n%v\", x, utils.CodeBlock(stack))\n\t\t\t} else {\n\t\t\t\ttxt += \"Please check the server logs for more details.\"\n\t\t\t}\n\t\t\tresp = &model.CommandResponse{\n\t\t\t\tText: txt,\n\t\t\t\tResponseType: model.CommandResponseTypeEphemeral,\n\t\t\t}\n\t\t}\n\t}(s.conf.Logger(), s.conf.Get().DeveloperMode)\n\n\treturn s.handleMain(params)\n}", "func (c *Command) Run() (int, error) {\n\n\t// Ensure we always target running instances\n\tc.Targets = append(c.Targets, \"instance-state-name=running\")\n\n\ttargets, err := c.targets()\n\tif err != nil {\n\t\treturn 1, err\n\t}\n\n\t// Randomize and limit the number of instances\n\tinstanceIDs, err := randomTargets(targets, c.TargetLimit)\n\tif err != nil {\n\t\treturn 1, err\n\t}\n\n\t// Split the instanceIDs into batches of 50 items.\n\tbatch := 50\n\tfor i := 0; i < len(instanceIDs); i += batch {\n\t\tj := i + batch\n\t\tif j > len(instanceIDs) {\n\t\t\tj = len(instanceIDs)\n\t\t}\n\n\t\tif err := c.RunCommand(instanceIDs[i:j]); err != nil {\n\t\t\treturn 1, err\n\t\t}\n\n\t}\n\n\treturn exitCode, nil\n}", "func (c *Subcommand) Run(flags *flag.FlagSet) error {\n\tif c.runFn != nil {\n\t\treturn c.runFn(flags)\n\t}\n\treturn nil\n}", "func Run() error {\n\trootCmd := newRootCmd()\n\treturn rootCmd.Execute()\n}", "func (runner *SSHRunner) Run(command string) (string, error) {\n\treturn runner.runSSHCommandFromDriver(command, false)\n}", "func (client *Client) Run(command string, silent bool) (output string, err error) {\n\tkeys := ssh.Auth{\n\t\tKeys: []string{client.PrivateKeyFile},\n\t}\n\tsshterm, err := ssh.NewNativeClient(client.User, client.Host, \"SSH-2.0-MyCustomClient-1.0\", client.Port, &keys, nil)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to request shell - %s\", err)\n\t}\n\tif !silent {\n\t\tlog.Printf(\"Running: ssh -i \\\"%s\\\" %s@%s %s\", client.PrivateKeyFile, client.User, client.Host, command)\n\t}\n\tr, _, err := sshterm.Start(command)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to start command - %s\", err)\n\t}\n\tsshterm.Wait()\n\tresponse, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to read response - %s\", err)\n\t}\n\treturn string(response), nil\n}", "func (cmd *Command) Run(ctx *util.Context) {\n\tif cmd.Help == character.StartHelp {\n\t\tif db.CheckStarted(ctx.Message.Author.ID) {\n\t\t\tctx.Reply(\"you have already started your journey, run `delete` to delete your character\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tif cmd.MustStart {\n\t\tif !db.CheckStarted(ctx.Message.Author.ID) {\n\t\t\tctx.Reply(util.NoneDialog)\n\t\t\treturn\n\t\t}\n\n\t\t// Validate character\n\t\tuser, err := db.GetUser(ctx.Message.Author.ID)\n\t\tif util.CheckDB(err, ctx) {\n\t\t\treturn\n\t\t}\n\n\t\t_, ok := item.Items[user.Hat]\n\t\tif !ok && user.Hat != \"None\" {\n\t\t\tutil.InvalidChar(user.Hat, ctx)\n\t\t\treturn\n\t\t}\n\n\t\t_, ok = room.Rooms[user.Room]\n\t\tif !ok {\n\t\t\tutil.InvalidChar(user.Room, ctx)\n\t\t\treturn\n\t\t}\n\n\t\tfor _, value := range user.Inv {\n\t\t\t_, ok := item.Items[value.ID]\n\t\t\tif !ok {\n\t\t\t\tutil.InvalidChar(value.ID, ctx)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tfor _, value := range user.Arsenal {\n\t\t\t_, ok := item.Items[value]\n\t\t\tif !ok {\n\t\t\t\tutil.InvalidChar(value, ctx)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tif cmd.NoCombat {\n\t\tuser, err := db.GetUser(ctx.Message.Author.ID)\n\t\tif util.CheckDB(err, ctx) {\n\t\t\treturn\n\t\t}\n\n\t\tif user.Combat {\n\t\t\tctx.Reply(util.NoneCombat)\n\t\t\treturn\n\t\t}\n\t}\n\n\tcmd.Exec(ctx)\n}", "func Execute(ctx context.Context) error {\n\treturn rootCmd.ExecuteContext(ctx)\n}", "func Run(rootCommand *Command, version string, runEnv *cli.RunEnv) int {\n\tstart := time.Now()\n\tinternal.SetRunEnvDefaults(runEnv)\n\tvar exitCode int\n\tif err := runRootCommand(rootCommand, version, start, runEnv, &exitCode); err != nil {\n\t\tprintError(runEnv.Stderr, err)\n\t\treturn 1\n\t}\n\treturn exitCode\n}", "func (updateCommand *UpdateCommand) Run() (ExecutionStatus, error) {\n\tupdateExecution := NewUpdateExecution(updateCommand)\n\terr := updateExecution.Start()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn updateExecution, err\n}", "func (c *TestCommand) Run() error {\n\tlocalPath, err := c.build()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfile, err := os.Open(localPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tftpConn, err := c.config.DialFtp()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer ftpConn.Close()\n\n\t_, name := filepath.Split(localPath)\n\tdronePath, err := ftpConn.Upload(file, name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer ftpConn.Del(name)\n\n\ttelnetConn, err := c.config.DialTelnet()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer telnetConn.Close()\n\n\tcmd := fmt.Sprintf(\"chmod +x %s && %s\", dronePath, dronePath)\n\treturn telnetConn.Exec(cmd, os.Stdout)\n}", "func (gc *command) Run(args []string) (err error) {\n\n\tgc.commandData.Target, gc.commandData.UserCommand = common.GetTargetAndClusterCommand(args)\n\n\tif common.HasOption(gc.commandData.UserCommand.Parameters, []string{\"-v\", \"--version\"}) {\n\t\tfmt.Printf(\"Version: %d.%d.%d\\n\", domain.VersionType.Major, domain.VersionType.Minor, domain.VersionType.Build)\n\t\treturn\n\t}\n\n\t// if no user command and args contains -h or --help\n\tif gc.commandData.UserCommand.Command == \"\" {\n\t\tprintHelp()\n\t\treturn\n\t}\n\n\tgeodeConnection := &GeodeConnection{}\n\n\terr = geodeConnection.GetConnectionData(&gc.commandData)\n\tif err != nil {\n\t\tprintHelp()\n\t\treturn\n\t}\n\n\t// From this point common code can handle the processing of the command\n\terr = gc.comm.ProcessCommand(&gc.commandData)\n\n\treturn\n}", "func (ins *EC2RemoteClient) RunCommandWithOutput(cmd string) (exitStatus int, stdoutBuf bytes.Buffer, stderrBuf bytes.Buffer, err error) {\n\texitStatus, stdoutBuf, stderrBuf, err = ins.cmdClient.RunCommandWithOutput(cmd)\n\treturn exitStatus, stdoutBuf, stderrBuf, err\n}", "func (err *ErrBytesRecv) Execute() error {\n\treturn executeCommand(err.config)\n}" ]
[ "0.7561612", "0.69532496", "0.68798643", "0.68055874", "0.6770573", "0.6748194", "0.6677681", "0.66319287", "0.65913767", "0.6591189", "0.65801775", "0.6575124", "0.6574193", "0.65640867", "0.652324", "0.65216607", "0.6511455", "0.64802206", "0.6476532", "0.64580154", "0.64575607", "0.64562094", "0.64535505", "0.64373773", "0.64372593", "0.64257514", "0.6420214", "0.6395045", "0.6384289", "0.6378082", "0.63669556", "0.63440955", "0.63440955", "0.63440955", "0.633876", "0.6311657", "0.63093746", "0.6289017", "0.62861097", "0.62730485", "0.62704057", "0.62663", "0.62487376", "0.62364453", "0.62311465", "0.6230067", "0.6212727", "0.6211931", "0.62030196", "0.619311", "0.6178576", "0.61773145", "0.61740017", "0.6168472", "0.6167883", "0.6156827", "0.6151672", "0.613987", "0.6136498", "0.6135617", "0.61280686", "0.6124205", "0.61240655", "0.6123828", "0.61018157", "0.60966325", "0.6095547", "0.6094925", "0.6094826", "0.6094826", "0.60540134", "0.60536176", "0.6051628", "0.6046953", "0.6044304", "0.60243344", "0.6020284", "0.60154045", "0.60113764", "0.6010051", "0.60099375", "0.6004144", "0.6001773", "0.5997933", "0.59938914", "0.59895337", "0.5988163", "0.59844095", "0.59834063", "0.5983381", "0.5980638", "0.5977243", "0.59738237", "0.5971567", "0.5958114", "0.5954565", "0.59497374", "0.5946484", "0.59446853", "0.59354526", "0.59328187" ]
0.0
-1
String obtains a string representation
func (scp *SCP) String() string { return fmt.Sprintf("SYNC SCP %s %s:%s", scp.Source, scp.TargetHost, scp.Destination) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (enc *simpleEncoding) String() string {\n\treturn \"simpleEncoding(\" + enc.baseName + \")\"\n}", "func (s Library) String() string {\n\tres := make([]string, 5)\n\tres[0] = \"ID: \" + reform.Inspect(s.ID, true)\n\tres[1] = \"UserID: \" + reform.Inspect(s.UserID, true)\n\tres[2] = \"VolumeID: \" + reform.Inspect(s.VolumeID, true)\n\tres[3] = \"CreatedAt: \" + reform.Inspect(s.CreatedAt, true)\n\tres[4] = \"UpdatedAt: \" + reform.Inspect(s.UpdatedAt, true)\n\treturn strings.Join(res, \", \")\n}", "func (s VerbatimString) ToString() (string, error) { return _verbatimString(s).ToString() }", "func (s *S) String() string {\n\treturn fmt.Sprintf(\"%s\", s) // Sprintf will call s.String()\n}", "func (s simpleString) String() string { return string(s) }", "func String() string {\n\toutput := output{\n\t\tRerun: Rerun,\n\t\tVariables: Variables,\n\t\tItems: Items,\n\t}\n\tvar err error\n\tvar b []byte\n\tif Indent == \"\" {\n\t\tb, err = json.Marshal(output)\n\t} else {\n\t\tb, err = json.MarshalIndent(output, \"\", Indent)\n\t}\n\tif err != nil {\n\t\tmessageErr := Errorf(\"Error in parser. Please report this output to https://github.com/drgrib/alfred/issues: %v\", err)\n\t\tpanic(messageErr)\n\t}\n\ts := string(b)\n\treturn s\n}", "func (s CreateAlgorithmOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateAlgorithmOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s Sign) Str() string { return string(s[:]) }", "func (e Str) String() string {\n\treturn fmt.Sprintf(\"%v\", e)\n}", "func String(v interface{}) string {\n\treturn StringWithOptions(v, nil)\n}", "func (s String) ToString() string {\n\treturn string(s)\n}", "func (x XID) String() string {\n\tdst := make([]byte, 20)\n\tx.encode(dst)\n\treturn b2s(dst)\n}", "func (s CreateCanaryOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s *String) String() string {\n\tj, err := json.Marshal(string(s.s))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(j)\n}", "func (i NotMachine) String() string { return toString(i) }", "func (d Decomposition) String() string {\n\treturn d.string(\"*\", \"(\", \")\")\n}", "func String() string {\n\treturn fmt.Sprintf(`Version: \"%s\", BuildTime: \"%s\", Commit: \"%s\" `, Version, BuildTime, Commit)\n}", "func (c identifier) String() string {\n\treturn string(c)\n}", "func (n Name) String() string {\n\treturn string(n)\n}", "func (n Name) String() string {\n\treturn string(n)\n}", "func (s ReEncryptOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r *Registry) String() string {\n\tout := make([]string, 0, len(r.nameToObject))\n\tfor name, object := range r.nameToObject {\n\t\tout = append(out, fmt.Sprintf(\"* %s:\\n%s\", name, object.serialization))\n\t}\n\treturn strings.Join(out, \"\\n\\n\")\n}", "func (p *PN) String() string {\n\t// find the right slice length first to efficiently allot a []string\n\tsegs := make([]string, 0, p.sliceReq())\n\treturn strings.Join(p.string(\"\", segs), \"\")\n}", "func (s CreateUseCaseOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (id ID) String() string {\n\ttext := make([]byte, encodedLen)\n\tencode(text, id[:])\n\treturn *(*string)(unsafe.Pointer(&text))\n}", "func (c ComponentIdentifier) String() string {\n\tvar buf bytes.Buffer\n\n\tbuf.WriteString(c.Format)\n\tbuf.WriteString(\":\")\n\tbuf.WriteString(c.Coordinates.String())\n\n\treturn buf.String()\n}", "func (p *Parser) String() string {\n\tb, _ := json.Marshal(p)\n\treturn string(b)\n}", "func (s CreateComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func String(b []byte) (s string) {\n\treturn string(b)\n}", "func String(b []byte) string {\n\treturn string(b)\n}", "func (r Info) String() string {\n\tJSON, err := json.Marshal(r)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn string(JSON)\n}", "func (s CreateFHIRDatastoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func toString(s interface{}) string {\n\tif s != nil {\n\t\treturn s.(string)\n\t}\n\treturn \"\"\n}", "func String() string {\n\treturn fmt.Sprintf(\n\t\t\"AppVersion = %s\\n\"+\n\t\t\t\"VCSRef = %s\\n\"+\n\t\t\t\"BuildVersion = %s\\n\"+\n\t\t\t\"BuildDate = %s\",\n\t\tAppVersion, VCSRef, BuildVersion, Date,\n\t)\n}", "func (p Protocol) String() string {\n\treturn string(p)\n}", "func String() string {\n\treturn StringWithSize(IntInRange(1, 8))\n}", "func (s CreateEntityOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (g Name) String() string {\n\treturn string(g)\n}", "func (s CreateDatabaseOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (e ExternalCfps) String() string {\n\tje, _ := json.Marshal(e)\n\treturn string(je)\n}", "func (s CreateProgramOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s RenderingEngine) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r Resiliency) String() string {\n\tb, _ := json.Marshal(r)\n\treturn string(b)\n}", "func (s ResolutionTechniques) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateThingOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s GetComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s StartPipelineReprocessingOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s SourceAlgorithm) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s GetObjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateRoomOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (z *Perplex) String() string {\n\ta := make([]string, 5)\n\ta[0] = \"(\"\n\ta[1] = fmt.Sprintf(\"%v\", &z.l)\n\tif z.r.Sign() == -1 {\n\t\ta[2] = fmt.Sprintf(\"%v\", &z.r)\n\t} else {\n\t\ta[2] = fmt.Sprintf(\"+%v\", &z.r)\n\t}\n\ta[3] = \"s\"\n\ta[4] = \")\"\n\treturn strings.Join(a, \"\")\n}", "func (clp CLP) String() string {\n\treturn fmt.Sprintf(\"%v%v%v%v\", clp.Creator, clp.Ticker, clp.Name, clp.ReserveRatio)\n}", "func (book *Book) String() string {\n\treturn \tfmt.Sprintf(\"id=%d, subject=%v, title=%v, author=%v\\n\",book.id,book.subject,book.title,book.author)\n}", "func (e ExternalCfp) String() string {\n\tje, _ := json.Marshal(e)\n\treturn string(je)\n}", "func (s Scheme) String() string {\n\treturn string(s)\n}", "func (r *Rope) String() string {\n\treturn r.Substr(0, r.runes)\n}", "func (r Rooms) String() string {\n\tjr, _ := json.Marshal(r)\n\treturn string(jr)\n}", "func (sf *String) String() string {\n\treturn sf.Value\n}", "func (ps *PrjnStru) String() string {\n\tstr := \"\"\n\tif ps.Recv == nil {\n\t\tstr += \"recv=nil; \"\n\t} else {\n\t\tstr += ps.Recv.Name() + \" <- \"\n\t}\n\tif ps.Send == nil {\n\t\tstr += \"send=nil\"\n\t} else {\n\t\tstr += ps.Send.Name()\n\t}\n\tif ps.Pat == nil {\n\t\tstr += \" Pat=nil\"\n\t} else {\n\t\tstr += \" Pat=\" + ps.Pat.Name()\n\t}\n\treturn str\n}", "func (s *StringStep) String() string {\n\treturn string(*s)\n}", "func (p person) String() string {\n\treturn fmt.Sprintf(\"Object %s: %d\", p.Name, p.Age)\n}", "func (s GetCanaryOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s *Scalar) String() string {\n\tresult, _ := s.MarshalText()\n\treturn string(result)\n}", "func (s CreateBotLocaleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateTrialComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateHITTypeOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func String() string {\n\treturn fmt.Sprintf(\"OLM version: %s\\ngit commit: %s\\n\", OLMVersion, GitCommit)\n}", "func (p polynomial) String() (str string) {\n\tfor _, m := range p.monomials {\n\t\tstr = str + \" \" + m.String() + \" +\"\n\t}\n\tstr = strings.TrimRight(str, \"+\")\n\treturn \"f(x) = \" + strings.TrimSpace(str)\n}", "func (s CreateSafetyRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s ResolveRoomOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (enc ObjectEncoding) String() string {\n\tswitch enc {\n\tcase ObjectEncodingRaw:\n\t\treturn \"raw\"\n\tcase ObjectEncodingInt:\n\t\treturn \"int\"\n\tcase ObjectEncodingHT:\n\t\treturn \"hashtable\"\n\tcase ObjectEncodingZipmap:\n\t\treturn \"zipmap\"\n\tcase ObjectEncodingLinkedlist:\n\t\treturn \"linkedlist\"\n\tcase ObjectEncodingZiplist:\n\t\treturn \"ziplist\"\n\tcase ObjectEncodingIntset:\n\t\treturn \"intset\"\n\tcase ObjectEncodingSkiplist:\n\t\treturn \"skiplist\"\n\tcase ObjectEncodingEmbstr:\n\t\treturn \"embstr\"\n\tcase ObjectEncodingQuicklist:\n\t\treturn \"quicklist\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}", "func (r ReceiveAll) String() string {\n\tJSON, err := json.Marshal(r)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn string(JSON)\n}", "func (s CreateLanguageModelOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateDatastoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s TransformOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s GenerateTemplateOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s GenerateTemplateOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateSceneOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s GetEntityOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (p Packet) String() string {\n\treturn fmt.Sprintf(\"<Packet {Command: %x, Data: %v, Expect: %v}>\", p.Command, p.Data, p.Expect)\n}", "func (s CreateActivationOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (g GetObjectOutput) String() string {\n\treturn helper.Prettify(g)\n}", "func (s *Signature) String() string {\n\treturn fmt.Sprintf(\"%s %s %s\", s.Value, s.PublicKey, s.Endorsement)\n}", "func (s NetworkPathComponentDetails) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (t Type) String() string {\n\tswitch t {\n\tdefault:\n\t\treturn \"Unknown\"\n\tcase '+':\n\t\treturn \"SimpleString\"\n\tcase '-':\n\t\treturn \"Error\"\n\tcase ':':\n\t\treturn \"Integer\"\n\tcase '$':\n\t\treturn \"BulkString\"\n\tcase '*':\n\t\treturn \"Array\"\n\tcase 'R':\n\t\treturn \"RDB\"\n\t}\n}", "func (a agent) String() string {\n\treturn fmt.Sprintf(\"[id=%v, name=%v, processVersion=%v, bundleVersion=%v, features=%v, zones=%v]\",\n\t\ta.id, a.name, a.processVersion, a.bundleVersion, a.features, a.zones)\n}", "func String(v interface{}) string {\n\treturn v.(string)\n}", "func (id UUID) String() string {\n\tvar buf [StringMaxLen]byte\n\tn := id.EncodeString(buf[:])\n\treturn string(buf[n:])\n}", "func (c CourseCode) String() string {\n\tjc, _ := json.Marshal(c)\n\treturn string(jc)\n}", "func (n *Node) String() string {\n\treturn n.recString(0)\n}", "func (s SequenceInformation) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (z Zamowienium) String() string {\n\tjz, _ := json.Marshal(z)\n\treturn string(jz)\n}", "func (s DescribeAlgorithmOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r *InterRecord) String() string {\n\tbuf := r.Bytes()\n\tdefer ffjson.Pool(buf)\n\n\treturn string(buf)\n}", "func (s CreateModelCardOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (sk StringKey) String() string {\n\treturn fmt.Sprintf(\"StringKey{%s, str:%q}\", sk.Base.String(), sk.str)\n}", "func (s ParticipantDetails) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreatePipelineOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreatePipelineOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreatePipelineOutput) String() string {\n\treturn awsutil.Prettify(s)\n}" ]
[ "0.708365", "0.6992918", "0.6976505", "0.68555176", "0.6838207", "0.68321586", "0.682511", "0.682511", "0.68162453", "0.6800907", "0.6799687", "0.6795744", "0.67955774", "0.679453", "0.67803866", "0.67799884", "0.6759549", "0.67546695", "0.67431027", "0.6738842", "0.6738842", "0.6733722", "0.6720205", "0.6708044", "0.6707102", "0.6680502", "0.6678532", "0.66752034", "0.66723967", "0.6670297", "0.66598666", "0.66590625", "0.6657758", "0.66398895", "0.6638301", "0.663573", "0.6634824", "0.6629503", "0.66239226", "0.66156876", "0.6608851", "0.6601289", "0.6599591", "0.65969527", "0.65969425", "0.6588486", "0.65879613", "0.65843034", "0.6583775", "0.6581698", "0.6581044", "0.65691584", "0.656797", "0.65631664", "0.655972", "0.65569896", "0.65558875", "0.6555533", "0.65541434", "0.6553739", "0.6552796", "0.655223", "0.65515554", "0.65469897", "0.6543887", "0.6541833", "0.65417", "0.6540887", "0.65393496", "0.65383285", "0.6537675", "0.65333945", "0.65296865", "0.6527748", "0.6526145", "0.6525705", "0.65255326", "0.65255326", "0.6524499", "0.6522267", "0.65216976", "0.6519264", "0.65188193", "0.65155196", "0.6514103", "0.6509615", "0.650744", "0.65071", "0.65068436", "0.6506753", "0.6505817", "0.650384", "0.650368", "0.650364", "0.6503117", "0.6502698", "0.650103", "0.65000844", "0.64971507", "0.64971507", "0.64971507" ]
0.0
-1
PrettyPrint returns a simple space indexed string.
func (scp *SCP) PrettyPrint(indentation int) string { return strings.Repeat(" ", indentation) + scp.String() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (i ExtraLeadingSpace) String() string { return toString(i) }", "func (fr FlushResult) PrettyString() string {\n\treturn fmt.Sprintf(\"wiped %d records\\n\", fr.Count)\n}", "func (l *Logger) PrettyPrint(identation int) string {\n\treturn strings.Repeat(\" \", identation) + l.String()\n}", "func (a Authorization) PrettyPrint() string {\n\tbs, err := json.MarshalIndent(a, \"\", \" \")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(bs)\n}", "func SprettyPrint(graph *Graph) string {\n\treturn recursiveString(graph.Root, 0, false)\n}", "func (n Node) Pretty() string {\n\treturn fmt.Sprintf(\"Node : %v , Address: %v, DhtID: %v\", n.pubKey.String(), n.address, n.DhtID().Pretty())\n}", "func pretty(c ResultChunk, snap *mockstore.Snapshot) string {\n\tformatKID := func(kid uint64) string {\n\t\txid := snap.ExternalID(kid)\n\t\treturn fmt.Sprintf(\"#%d:%s\", kid, xid)\n\t}\n\ts := strings.Builder{}\n\tfor rowIdx, row := range c.Facts {\n\t\tfor _, f := range row.Facts {\n\t\t\tfmtObj := f.Object.String()\n\t\t\tif f.Object.IsType(rpc.KtKID) {\n\t\t\t\tfmtObj = formatKID(f.Object.ValKID())\n\t\t\t}\n\t\t\tfmt.Fprintf(&s, \"row:%3d subject:%-20s predicate:%-20s object:%-20s\\n\",\n\t\t\t\trowIdx, formatKID(f.Subject), formatKID(f.Predicate), fmtObj)\n\t\t}\n\t\ts.WriteByte('\\n')\n\t}\n\treturn s.String()\n}", "func PrettyPrint(rt *RTable, sub []string) string {\n\tvar buf bytes.Buffer\n\n\tif rt.Size() == 0 {\n\t\treturn \"\"\n\t}\n\ts, m := getStringTab(rt)\n\tlength := rt.Size()\n\n\tbuf.WriteString(\"+\" + strings.Repeat(\"-\",\n\t\t(m+1)*length-1) + \"+\\n\")\n\tfor row := 0; row < length; row++ {\n\t\tl := 1\n\t\tfor tok := 0; tok < l; tok++ {\n\t\t\tbuf.WriteString(strings.Repeat(\" \", (m+1)*row) + \"|\")\n\t\t\tfor col := row; col < length; col++ {\n\t\t\t\tif len((*s)[col][row]) == 0 {\n\t\t\t\t\tprintToken(\"\", m, &buf)\n\t\t\t\t} else if tok == 0 {\n\t\t\t\t\tl = max(len((*s)[col][row]), l)\n\t\t\t\t\tprintToken((*s)[col][row][0], m, &buf)\n\t\t\t\t} else if tok < len((*s)[col][row]) {\n\t\t\t\t\tprintToken((*s)[col][row][tok], m, &buf)\n\t\t\t\t} else {\n\t\t\t\t\tprintToken(\"\", m, &buf)\n\t\t\t\t}\n\t\t\t\tbuf.WriteString(\"|\")\n\t\t\t}\n\t\t\tbuf.WriteString(\"\\n\")\n\t\t}\n\t\tbuf.WriteString(strings.Repeat(\" \",\n\t\t\t(m+1)*row) + \"+\" + strings.Repeat(\"-\",\n\t\t\t(m+1)*(length-row)-1))\n\t\tif row+1 == length {\n\t\t\tbuf.WriteString(\"+\\n\")\n\t\t} else {\n\t\t\tbuf.WriteString(\"|\\n\")\n\t\t}\n\t}\n\n\tprintSub(sub, m, &buf)\n\n\treturn buf.String()\n}", "func (scope *Scope) Pretty(level int) string {\n\tpadding := \"\"\n\tfor i := 0; i < level; i++ {\n\t\tpadding += \" \"\n\t}\n\tvar buffer bytes.Buffer\n\tfor k, v := range scope.variables {\n\t\tbuffer.WriteString(fmt.Sprintf(\"%s%s %v\\n\", padding, k, v))\n\t}\n\tif scope.previous != nil {\n\t\tbuffer.WriteString(scope.previous.Pretty(level + 1))\n\t}\n\treturn buffer.String()\n}", "func (ps *Parser) PrettyPrint() string {\n\tindent, output := 0, \"\"\n\tfor _, section := range ps.Tokens.Sections {\n\t\toutput += \"<\" + section.Type + \">\" + \"\\n\"\n\t\tfor _, item := range section.Items {\n\t\t\tindent++\n\t\t\tfor i := 0; i < indent; i++ {\n\t\t\t\toutput += \"\\t\"\n\t\t\t}\n\t\t\tif len(item.Parts) == 0 {\n\t\t\t\toutput += item.TValue + \" <\" + item.TType + \">\" + \"\\n\"\n\t\t\t} else {\n\t\t\t\toutput += \"<\" + item.TType + \">\" + \"\\n\"\n\t\t\t}\n\t\t\tfor _, part := range item.Parts {\n\t\t\t\tindent++\n\t\t\t\tfor i := 0; i < indent; i++ {\n\t\t\t\t\toutput += \"\\t\"\n\t\t\t\t}\n\t\t\t\toutput += part.Token.TValue + \" <\" + part.Token.TType + \">\" + \"\\n\"\n\t\t\t\tindent--\n\t\t\t}\n\t\t\tindent--\n\t\t}\n\t}\n\treturn output\n}", "func (k *Key) String() string { return fmt.Sprintf(\"%d\", k.index) }", "func indent(s string, n int) string {\n\tif n <= 0 || s == \"\" {\n\t\treturn s\n\t}\n\tl := strings.Split(s, \"\\n\")\n\tb := strings.Builder{}\n\ti := strings.Repeat(\" \", n)\n\tfor _, v := range l {\n\t\tfmt.Fprintf(&b, \"%s%s\\n\", i, v)\n\t}\n\treturn b.String()\n}", "func indent(s string, n int) string {\n\tif n <= 0 || s == \"\" {\n\t\treturn s\n\t}\n\tl := strings.Split(s, \"\\n\")\n\tb := strings.Builder{}\n\ti := strings.Repeat(\" \", n)\n\tfor _, v := range l {\n\t\tfmt.Fprintf(&b, \"%s%s\\n\", i, v)\n\t}\n\treturn b.String()\n}", "func (mpt *MerklePatriciaTrie) PrettyPrint(w io.Writer) error {\n\tmpt.mutex.RLock()\n\tdefer mpt.mutex.RUnlock()\n\treturn mpt.pp(w, mpt.root, 0, false)\n}", "func (s CreateIndexOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateIndexOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (m *Matrix) PrettyP(s string, color Color){\n\tm.TextColor = color\n\tm.Println(s)\n}", "func (node ASTNode) PrettyPrint(indent int) string {\n\tspaces := strings.Repeat(\" \", indent)\n\toutput := fmt.Sprintf(\"%s%s {\\n\", spaces, node.nodeType)\n\tnextIndent := indent + 2\n\tif node.value != nil {\n\t\tif converted, ok := node.value.(fmt.Stringer); ok {\n\t\t\t// Account for things like comparator nodes\n\t\t\t// that are enums with a String() method.\n\t\t\toutput += fmt.Sprintf(\"%svalue: %s\\n\", strings.Repeat(\" \", nextIndent), converted.String())\n\t\t} else {\n\t\t\toutput += fmt.Sprintf(\"%svalue: %#v\\n\", strings.Repeat(\" \", nextIndent), node.value)\n\t\t}\n\t}\n\tlastIndex := len(node.children)\n\tif lastIndex > 0 {\n\t\toutput += fmt.Sprintf(\"%schildren: {\\n\", strings.Repeat(\" \", nextIndent))\n\t\tchildIndent := nextIndent + 2\n\t\tfor _, elem := range node.children {\n\t\t\toutput += elem.PrettyPrint(childIndent)\n\t\t}\n\t}\n\toutput += fmt.Sprintf(\"%s}\\n\", spaces)\n\treturn output\n}", "func PrettyPrint(i interface{}) string {\n\tswitch t := i.(type) {\n\tcase nil:\n\t\treturn \"None\"\n\tcase string:\n\t\treturn capitalizeFirst(t)\n\tdefault:\n\t\treturn capitalizeFirst(fmt.Sprintf(\"%s\", t))\n\t}\n}", "func (s GetIndexOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func prettyPrint(arrStr ...[]string) {\n\tfor fi := range arrStr {\n\t\tfinalString := \"\"\n\t\tfor item := range arrStr[fi] {\n\t\t\tfinalString = fmt.Sprint(finalString, arrStr[fi][item])\n\t\t}\n\t\tfmt.Println(finalString)\n\t}\n}", "func (s Index) String() string {\n\treturn awsutil.Prettify(s)\n}", "func DumpPrettyTable(w io.Writer, title string, data []byte) {\n\tconst ncol = 8\n\n\tfmt.Fprintf(w, \"%s\\n\", title)\n\tfmt.Fprint(w, \" | 0 1 2 3 4 5 6 7 | 01234567 | 0 1 2 3 4 5 6 7 |\\n\")\n\tfmt.Fprint(w, \" | 8 9 A B C D E F | 89ABCDEF | 8 9 A B C D E F |\\n\")\n\n\tvar (\n\t\tchunks = SplitEach(data, ncol)\n\t\tchunk []byte\n\t\tx int\n\t\ty int\n\t\tc byte\n\t)\n\tfor x, chunk = range chunks {\n\t\tfmt.Fprintf(w, `%#08x|`, x*ncol)\n\n\t\t// Print as hex.\n\t\tfor y, c = range chunk {\n\t\t\tfmt.Fprintf(w, ` %02x`, c)\n\t\t}\n\t\tfor y++; y < ncol; y++ {\n\t\t\tfmt.Fprint(w, ` `)\n\t\t}\n\n\t\t// Print as char.\n\t\tfmt.Fprint(w, ` | `)\n\t\tfor y, c = range chunk {\n\t\t\tif c >= 33 && c <= 126 {\n\t\t\t\tfmt.Fprintf(w, `%c`, c)\n\t\t\t} else {\n\t\t\t\tfmt.Fprint(w, `.`)\n\t\t\t}\n\t\t}\n\t\tfor y++; y < ncol; y++ {\n\t\t\tfmt.Fprint(w, ` `)\n\t\t}\n\n\t\t// Print as integer.\n\t\tfmt.Fprint(w, ` |`)\n\t\tfor y, c = range chunk {\n\t\t\tfmt.Fprintf(w, ` %3d`, c)\n\t\t}\n\t\tfor y++; y < ncol; y++ {\n\t\t\tfmt.Fprint(w, ` `)\n\t\t}\n\t\tfmt.Fprintf(w, \" |%d\\n\", x*ncol)\n\t}\n}", "func PrettyPrint(graph *Graph) {\n\tfmt.Println(graph.Name)\n\tfmt.Println(\"\")\n\tstr := recursiveString(graph.Root, 0, true)\n\tfmt.Printf(\"%s\", str)\n}", "func (*Term) print(cs []*Column, idx int) string {\n\tret := fmt.Sprint(\"| \")\n\tfor _, c := range cs {\n\t\tformat := fmt.Sprintf(\"%%-%dv\", c.Len)\n\t\tif idx < 0 {\n\t\t\tret += fmt.Sprintf(format, c.Name)\n\t\t} else {\n\t\t\tret += fmt.Sprintf(format, c.Values[idx])\n\t\t}\n\t\tret += fmt.Sprint(\" | \")\n\t}\n\tret += fmt.Sprintln(\"\")\n\treturn ret\n}", "func PrettyPrint(v interface{}, prefix string, indent string) (string, error) {\n\tb, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to marshal\")\n\t}\n\n\tvar out bytes.Buffer\n\tif err := json.Indent(&out, b, prefix, indent); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to indent\")\n\t}\n\n\tif _, err := out.WriteString(\"\\n\"); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to write string\")\n\t}\n\n\treturn out.String(), nil\n}", "func s(n int) string {\n\tif n < 0 {\n\t\tn = 1\n\t}\n\treturn strings.Repeat(\" \", n)\n}", "func (k *Kernel) String() string {\n\tresult := \"\"\n\tstride := k.MaxX()\n\theight := k.MaxY()\n\tfor y := 0; y < height; y++ {\n\t\tresult += fmt.Sprintf(\"\\n\")\n\t\tfor x := 0; x < stride; x++ {\n\t\t\tresult += fmt.Sprintf(\"%-8.4f\", k.At(x, y))\n\t\t}\n\t}\n\treturn result\n}", "func (cc *ChannelsCache) PrettyPrint() string {\n\tvar res []string\n\tfor _, channel := range *cc {\n\t\tres = append(res, fmt.Sprintf(\"%d - %s\", channel.Id, channel.Title))\n\t}\n\treturn strings.Join(res, \"\\n\")\n}", "func (k *Index) String() string {\n\treturn fmt.Sprintf(\"%d\", uint32(*k))\n}", "func (counts keyedCounts) String() string {\n\tvar keys []string\n\tfor k := range counts {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\n\tvar buf strings.Builder\n\tfor _, k := range keys {\n\t\tbuf.WriteString(fmt.Sprintf(\"%-65s\\t%s\\n\", k, counts[k]))\n\t}\n\treturn buf.String()\n}", "func (fz ForwardZone) PrettyString() string {\n\tbuffer := new(bytes.Buffer)\n\n\tw := tabwriter.NewWriter(buffer, minwidth, tabwidth, padding, padchar, tabwriter.TabIndent)\n\tfmt.Fprintf(w, \"zone\\tnameservers\\n\")\n\tfmt.Fprintf(w, \"----\\t-----------\\n\")\n\tfmt.Fprintf(w, \"%s\\t%s\\n\", DeCanonicalize(fz.Name), strings.Join(fz.Nameservers, \", \"))\n\tw.Flush()\n\n\treturn buffer.String()\n}", "func (g *Game) PrettyPrint() string {\n\treturn fmt.Sprintf(\"ID: %v\\n%v\", g.ID.String(), g.Board.GetCurrentState())\n}", "func (connection *EsConnection) PrettyString(callback func(args ...interface{})) {\n\tcallback(\"ElasticSearch connection details:\")\n\tcallback(fmt.Sprintf(\"\\t * Port: %s\", connection.Port))\n\tcallback(fmt.Sprintf(\"\\t * URL: %s\", connection.URL))\n\tcallback(fmt.Sprintf(\"\\t * Namespace: %s\", connection.Namespace))\n}", "func PrettyPint(v interface{}) (err error) {\n\tb, err := json.MarshalIndent(v, \"\", \" \")\n\tif err == nil {\n\t\tfmt.Println(string(b))\n\t}\n\treturn\n}", "func (fzs ForwardZones) PrettyString() string {\n\t// Sorting []forwardZone by Name\n\tsort.Slice(fzs, func(i, j int) bool {\n\t\treturn fzs[i].Name < fzs[j].Name\n\t})\n\n\tbuffer := new(bytes.Buffer)\n\n\tw := tabwriter.NewWriter(buffer, minwidth, tabwidth, padding, padchar, tabwriter.TabIndent)\n\tfmt.Fprintf(w, \"zone\\tnameservers\\n\")\n\tfmt.Fprintf(w, \"----\\t-----------\\n\")\n\tfor _, fz := range fzs {\n\t\tfmt.Fprintf(w, \"%s\\t%s\\n\", DeCanonicalize(fz.Name), strings.Join(fz.Nameservers, \", \"))\n\t}\n\tw.Flush()\n\n\treturn buffer.String()\n}", "func PrettyPrint(s string, indentLevel int, color Color) {\n\tvar tabStr string\n\tfor i := 0; i < indentLevel; i++ {\n\t\ttabStr += \"\\t\"\n\t}\n\tstr := fmt.Sprintf(\"%s%s\\n\\n\", tabStr, regexp.MustCompile(\"\\n\").ReplaceAllString(s, \"\\n\"+tabStr))\n\tif color != NoColor {\n\t\tif cfunc, ok := colorFunc[color]; !ok {\n\t\t\tfmt.Print(\"COLOR NOT SUPPORTED\")\n\t\t} else {\n\t\t\tcfunc(str)\n\t\t}\n\t} else {\n\t\tfmt.Print(str)\n\t}\n}", "func (cv ClusterVersion) PrettyPrint() string {\n\t// If we're a version greater than v20.2 and have an odd internal version,\n\t// we're a fence version. See fenceVersionFor in pkg/migration to understand\n\t// what these are.\n\tfenceVersion := !cv.Version.LessEq(roachpb.Version{Major: 20, Minor: 2}) && (cv.Internal%2) == 1\n\tif !fenceVersion {\n\t\treturn cv.String()\n\t}\n\treturn redact.Sprintf(\"%s%s\", cv.String(), \"(fence)\").StripMarkers()\n}", "func (node *IndexHints) Format(buf *TrackedBuffer) {\n\tbuf.astPrintf(node, \" %sindex \", node.Type.ToString())\n\tif len(node.Indexes) == 0 {\n\t\tbuf.astPrintf(node, \"()\")\n\t} else {\n\t\tprefix := \"(\"\n\t\tfor _, n := range node.Indexes {\n\t\t\tbuf.astPrintf(node, \"%s%v\", prefix, n)\n\t\t\tprefix = \", \"\n\t\t}\n\t\tbuf.astPrintf(node, \")\")\n\t}\n}", "func (v VersionInfo) PrettyString() string {\n\tbuffer := new(bytes.Buffer)\n\tw := tabwriter.NewWriter(buffer, minwidth, tabwidth, padding, padchar, tabwriter.TabIndent)\n\n\tfmt.Fprintf(w, \"version\\tbuild\\n\")\n\tfmt.Fprintf(w, \"------\\t-----\\n\")\n\tfmt.Fprintf(w, \"%s\\t%s\\n\", v.Version, v.Build)\n\tw.Flush()\n\n\treturn buffer.String()\n}", "func formatPrint(thePrint string, numSpaces int) string {\n\tif len(thePrint) < numSpaces {\n\t\tthePrint += strings.Repeat(\" \", (numSpaces - len(thePrint)))\n\t}\n\treturn thePrint\n}", "func indent(n int) (s string) {\n\tfor i := 0; i < n; i++ {\n\t\ts += \"\\t\"\n\t}\n\treturn\n}", "func PrettyPrint(v interface{}) {\n\tfmt.Printf(\"%# v\\n\", pretty.Formatter(v))\n}", "func (s Snowflake) HexPrettyString() string {\n\treturn \"0x\" + strconv.FormatUint(uint64(s), 16)\n}", "func (idx Index) StringDump(showMutationInfo bool) string {\n\ts := fmt.Sprintf(\"\\nLabel: %d\\n\", idx.Label)\n\tif showMutationInfo {\n\t\ts += fmt.Sprintf(\"Last Mutation ID: %d\\n\", idx.LastMutId)\n\t\ts += fmt.Sprintf(\"Last Modification Time: %s\\n\", idx.LastModTime)\n\t\ts += fmt.Sprintf(\"Last Modification User: %s\\n\", idx.LastModUser)\n\t\ts += fmt.Sprintf(\"Last Modification App: %s\\n\\n\", idx.LastModApp)\n\t}\n\n\ts += fmt.Sprintf(\"Total blocks: %d\\n\", len(idx.Blocks))\n\tfor zyx, svc := range idx.Blocks {\n\t\tizyxStr := BlockIndexToIZYXString(zyx)\n\t\ts += fmt.Sprintf(\"Block %s:\\n\", izyxStr)\n\t\tfor sv, count := range svc.Counts {\n\t\t\ts += fmt.Sprintf(\" Supervoxel %10d: %d voxels\\n\", sv, count)\n\t\t}\n\t\ts += fmt.Sprintf(\"\\n\")\n\t}\n\treturn s\n}", "func (d duration) pretty() string {\n\treturn fmt.Sprintf(\"Duration: %d\", &d) // modify *duration and *d => &d\n}", "func (id ID) Pretty() string {\n\treturn IDB58Encode(id)\n}", "func (ms Migrations) PrettyPrint(wr io.Writer, detail prettyprint.DetailLevel) error {\n\tmigrationsTpl := `\n{{ define \"migrations_sgl\" }}{{ len . }} servers{{ end }}\n\n{{ define \"migrations_medium\" -}}\n{{- range . -}}\n{{- prettysprint . \"_sgl\" }}\n{{ end -}}\n{{- end }}\n\n{{ define \"migrations_full\" }}{{ template \"migrations_medium\" . }}{{ end }}\n`\n\treturn prettyprint.Run(wr, migrationsTpl, \"migrations\"+string(detail), ms)\n}", "func PrettyToken(t token.Token) string {\n\tvar ttype string\n\tvar literal = t.Literal\n\n\tif t.Type == token.ILLEGAL {\n\t\tttype = fmt.Sprint(au.Red(t.Type))\n\t} else {\n\t\tttype = fmt.Sprint(au.Green(au.Italic(t.Type)))\n\t}\n\n\tif literal == \"\\n\" {\n\t\tliteral = \"\\\\n\"\n\t}\n\n\tttliteral := au.Bold(au.BrightYellow(literal))\n\n\treturn fmt.Sprintf(\"(Lit: '%s', Type: '%s', line=%d, startcol=%d, endcol=%d)\",\n\t\tttliteral, ttype, t.Line, t.StartCol, t.EndCol,\n\t)\n}", "func (tree *Tree23) PrettyPrint() {\n\t//fmt.Printf(\"--%d(%.0f)\\n\", tree.root, tree.max(tree.root))\n\ttree.pprint(tree.root, 0)\n\tfmt.Printf(\"\\n\")\n}", "func (t *testResult) PrettyPrint() string {\n\tout := t.PrettyPrintLines()\n\treturn strings.Join(out, \"\\n\")\n}", "func (h leadingHorizontalRule) String() string { return string(h) }", "func (qt QueryTimes) PrettyPrint() {\n\tfmt.Println(\"No of processed queries:\", len(qt))\n\tfmt.Println(\"Minimum query time: \", qt.min())\n\tfmt.Println(\"Maximum query time: \", qt.max())\n\tfmt.Println(\"Median query time: \", qt.median())\n\tfmt.Println(\"Average query time: \", qt.average())\n\tfmt.Println(\"Total processing time:\", qt.sum())\n}", "func (q *PriorityQueue) PrettyPrint() {\n\tfmt.Println(\"Priority Queue\")\n\tq.priority.PrettyPrint()\n\n\tfmt.Println(\"Normal Queue\")\n\tq.normal.PrettyPrint()\n}", "func stringify(n *Node, level int) {\n\tif n != nil {\n\t\tformat := \"\"\n\t\tfor i := 0; i < level; i++ {\n\t\t\tformat += \" \"\n\t\t}\n\t\tformat += \"---[ \"\n\t\tlevel++\n\t\tstringify(n.left, level)\n\t\tfmt.Printf(format+\"%d\\n\", n.key)\n\t\tstringify(n.right, level)\n\t}\n}", "func (bA *CompactBitArray) StringIndented(indent string) string {\n\tif bA == nil {\n\t\treturn \"nil-BitArray\"\n\t}\n\tlines := []string{}\n\tbits := \"\"\n\tsize := bA.Count()\n\tfor i := 0; i < size; i++ {\n\t\tif bA.GetIndex(i) {\n\t\t\tbits += \"x\"\n\t\t} else {\n\t\t\tbits += \"_\"\n\t\t}\n\n\t\tif i%100 == 99 {\n\t\t\tlines = append(lines, bits)\n\t\t\tbits = \"\"\n\t\t}\n\n\t\tif i%10 == 9 {\n\t\t\tbits += indent\n\t\t}\n\n\t\tif i%50 == 49 {\n\t\t\tbits += indent\n\t\t}\n\t}\n\n\tif len(bits) > 0 {\n\t\tlines = append(lines, bits)\n\t}\n\n\treturn fmt.Sprintf(\"BA{%v:%v}\", size, strings.Join(lines, indent))\n}", "func Pretty(v interface{}) (string, error) {\n\tout, err := json.MarshalIndent(v, \"\", \" \")\n\treturn string(out), err\n}", "func (i NoExplanation) String() string { return toString(i) }", "func (jArray *A) Indent() string {\n\treturn indent(jArray)\n}", "func (w *RootWalker) String() (out string) {\n\ttabs := func(n int) {\n\t\tfor i := 0; i < n; i++ {\n\t\t\tout += \"\\t\"\n\t\t}\n\t}\n\tout += fmt.Sprint(\"Root\")\n\tsize := w.Size()\n\tif size == 0 {\n\t\treturn\n\t}\n\tout += fmt.Sprintf(\".Refs[%d] ->\\n\", w.stack[0].prevInFieldIndex)\n\tfor i, obj := range w.stack {\n\t\tschName := \"\"\n\t\ts, _ := w.r.SchemaByReference(obj.s)\n\t\tif s != nil {\n\t\t\tschName = s.Name()\n\t\t}\n\n\t\ttabs(i)\n\t\tout += fmt.Sprintf(\" %s\", schName)\n\t\tout += fmt.Sprintf(` = \"%v\"`+\"\\n\", obj.p)\n\n\t\ttabs(i)\n\t\tif obj.next != nil {\n\t\t\tout += fmt.Sprintf(\" %s\", schName)\n\t\t\tout += fmt.Sprintf(\".%s\", obj.next.prevFieldName)\n\t\t\tif obj.next.prevInFieldIndex != -1 {\n\t\t\t\tout += fmt.Sprintf(\"[%d]\", obj.next.prevInFieldIndex)\n\t\t\t}\n\t\t\tout += fmt.Sprint(\" ->\\n\")\n\t\t}\n\t}\n\treturn\n}", "func (w *RootWalker) String() (out string) {\n\ttabs := func(n int) {\n\t\tfor i := 0; i < n; i++ {\n\t\t\tout += \"\\t\"\n\t\t}\n\t}\n\tout += fmt.Sprint(\"Root\")\n\tsize := w.Size()\n\tif size == 0 {\n\t\treturn\n\t}\n\tout += fmt.Sprintf(\".Refs[%d] ->\\n\", w.stack[0].prevInFieldIndex)\n\tfor i, obj := range w.stack {\n\t\tschName := \"\"\n\t\ts, _ := w.r.SchemaByReference(obj.s)\n\t\tif s != nil {\n\t\t\tschName = s.Name()\n\t\t}\n\n\t\ttabs(i)\n\t\tout += fmt.Sprintf(\" %s\", schName)\n\t\tout += fmt.Sprintf(` = \"%v\"`+\"\\n\", obj.p)\n\n\t\ttabs(i)\n\t\tif obj.next != nil {\n\t\t\tout += fmt.Sprintf(\" %s\", schName)\n\t\t\tout += fmt.Sprintf(\".%s\", obj.next.prevFieldName)\n\t\t\tif obj.next.prevInFieldIndex != -1 {\n\t\t\t\tout += fmt.Sprintf(\"[%d]\", obj.next.prevInFieldIndex)\n\t\t\t}\n\t\t\tout += fmt.Sprint(\" ->\\n\")\n\t\t}\n\t}\n\treturn\n}", "func (node *IndexHint) formatFast(buf *TrackedBuffer) {\n\tbuf.WriteByte(' ')\n\tbuf.WriteString(node.Type.ToString())\n\tbuf.WriteString(\"index \")\n\tif node.ForType != NoForType {\n\t\tbuf.WriteString(\"for \")\n\t\tbuf.WriteString(node.ForType.ToString())\n\t\tbuf.WriteByte(' ')\n\t}\n\tif len(node.Indexes) == 0 {\n\t\tbuf.WriteString(\"()\")\n\t} else {\n\t\tprefix := \"(\"\n\t\tfor _, n := range node.Indexes {\n\t\t\tbuf.WriteString(prefix)\n\t\t\tn.formatFast(buf)\n\t\t\tprefix = \", \"\n\t\t}\n\t\tbuf.WriteByte(')')\n\t}\n}", "func printToken(s string, max int, buf *bytes.Buffer) {\n\tbuf.WriteString(s)\n\tif l := len(s); l < max {\n\t\tbuf.WriteString(strings.Repeat(\" \", max-l))\n\t}\n}", "func printPair(pair Pair) {\n\tfmt.Print(\" < \")\n\tprintVector(pair.V1)\n\tfmt.Print(\" , \")\n\tprintVector(pair.V2)\n\tfmt.Print(\" > \")\n}", "func spacer(level int) string {\n\treturn strings.Repeat(\" \", level)\n}", "func prettyPhrase(phrase []string) string {\n\tvar builder strings.Builder\n\n\tfor i, p := range phrase {\n\t\tbuilder.WriteString(p)\n\t\tbreakline := (i+1)%6 == 0\n\t\tif breakline {\n\t\t\tbuilder.WriteString(\"\\n\")\n\t\t} else if i < len(phrase)-1 {\n\t\t\tbuilder.WriteString(\" \")\n\t\t}\n\t}\n\n\treturn builder.String()\n}", "func (v Vector) String() string {\n\tvar sb strings.Builder\n\tfmt.Fprint(&sb, prefix)\n\n\tdefineables := v.definables()\n\n\tfirst := true\n\tfor _, metric := range order {\n\t\tdef := defineables[metric]\n\t\tif !def.defined() {\n\t\t\tcontinue\n\t\t}\n\t\tif !first {\n\t\t\tfmt.Fprint(&sb, partSeparator)\n\t\t} else {\n\t\t\tfirst = false\n\t\t}\n\t\tfmt.Fprintf(&sb, \"%s%s%s\", metric, metricSeparator, def)\n\t}\n\n\tfmt.Fprint(&sb, suffix)\n\n\treturn sb.String()\n}", "func stringify(n *BinarySearchNode, level int, builder *strings.Builder) {\n\tif n != nil {\n\t\tformat := \"\"\n\t\tfor i := 0; i < level; i++ {\n\t\t\tformat += \" \"\n\t\t}\n\t\tformat += \"---[ \"\n\t\tlevel++\n\t\tstringify(n.left, level, builder)\n\t\tbuilder.WriteString(fmt.Sprintf(format+\"%d\\n\", n.value))\n\t\tstringify(n.right, level, builder)\n\t}\n}", "func (ii *IndexInfo) Format(buf *TrackedBuffer) {\n\tif ii.Primary {\n\t\tbuf.astPrintf(ii, \"%s\", ii.Type)\n\t} else {\n\t\tbuf.astPrintf(ii, \"%s\", ii.Type)\n\t\tif !ii.Name.IsEmpty() {\n\t\t\tbuf.astPrintf(ii, \" %v\", ii.Name)\n\t\t}\n\t}\n}", "func (g Graph) PrettyPrint(w io.Writer) {\n\tnewline := \"\"\n\tfor k, v := range g {\n\t\tfmt.Fprintf(w, \"%s%s, %s (%g, %g)\\n\", newline, k.City, k.State, k.Latitude, k.Longitude)\n\t\tnewline = \"\\n\" // redundant but this avoids if\n\t\tfor kk, vv := range v {\n\t\t\tfmt.Fprintf(w, \"\\t%-16s%3s%7.1fmi%10s\\n\", kk.City, kk.State, vv.Distance*MetersToMiles, vv.TravelTime)\n\t\t}\n\t}\n}", "func (t *strideTable[T]) treeDebugString() string {\n\tvar ret bytes.Buffer\n\tt.treeDebugStringRec(&ret, 1, 0) // index of 0/0, and 0 indent\n\treturn ret.String()\n}", "func (s subspace) String() string {\n\treturn fmt.Sprintf(\"Subspace(rawPrefix=%s)\", fdb.Printable(s.rawPrefix))\n}", "func (o *Kanban) StringifyPretty() string {\n\to.Hash()\n\treturn pjson.Stringify(o, true)\n}", "func (r *RequestListIndex) String() string {\n\treturn fmt.Sprintf(\"id: %s, type: list index, key: %s\"+\n\t\t\", index: %d\", r.ID, r.Key, r.Index)\n}", "func (t *strideTable[T]) tableDebugString() string {\n\tvar ret bytes.Buffer\n\tfor i, ent := range t.entries {\n\t\tif i == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tv := \"(nil)\"\n\t\tif ent.value != nil {\n\t\t\tv = fmt.Sprint(*ent.value)\n\t\t}\n\t\tfmt.Fprintf(&ret, \"idx=%3d (%s), parent=%3d (%s), val=%v\\n\", i, formatPrefixTable(inversePrefixIndex(i)), ent.prefixIndex, formatPrefixTable(inversePrefixIndex((ent.prefixIndex))), v)\n\t}\n\treturn ret.String()\n}", "func spaced(s ...interface{}) string {\n\tret := make([]string, 0, len(s))\n\tfor _, t := range s {\n\t\tif t != nil {\n\t\t\tr := fmt.Sprint(t)\n\t\t\tif r != \"\" {\n\t\t\t\tret = append(ret, r)\n\t\t\t}\n\t\t}\n\t}\n\treturn strings.Join(ret, \" \")\n}", "func (t Table) String() string {\n\ttotal := fmt.Sprintf(\"\\n\")\n\tfor i, stack := range t {\n\t\tvar label string\n\t\tswitch i {\n\t\tcase 0, 1, 2, 3, 5:\n\t\t\tlabel = fmt.Sprintf(\" %d\", i+1)\n\t\tcase 4:\n\t\t\tlabel = fmt.Sprintf(\"4s\")\n\t\tcase 6:\n\t\t\tlabel = fmt.Sprintf(\" %d\", 8)\n\t\tcase 7:\n\t\t\tlabel = fmt.Sprintf(\" %d\", 9)\n\t\tcase 8:\n\t\t\tlabel = fmt.Sprintf(\"%d\", 12)\n\t\tcase 9:\n\t\t\tlabel = fmt.Sprintf(\"%d\", 16)\n\t\tdefault:\n\t\t\tfmt.Println(\"default\")\n\t\t}\n\t\ttotal += fmt.Sprintf(\"[%s] --> %v\\n\", label, stack)\n\t}\n\treturn total\n}", "func Space(s string, n int) string { return At(s, ' ', n) }", "func (b Board) prettyPrint() {\n\tfmt.Printf(\"\\nWhite player: %s, Black player: %s\\n\", b.players[White], b.players[Black])\n\n\tfmt.Printf(\" a b c d e f g h\\n\")\n\tfor y := endSquare; y >= startSquare; y-- {\n\t\tfmt.Printf(\"%d \", y)\n\t\tfor x := startSquare; x <= endSquare; x++ {\n\t\t\tp := b.getPieceByCoordinates(x, y)\n\t\t\tif p != nil {\n\t\t\t\tif p.color == White {\n\t\t\t\t\tfmt.Printf(\" w%s \", string(p.pieceType))\n\t\t\t\t} else if p.color == Black {\n\t\t\t\t\tfmt.Printf(\" b%s \", string(p.pieceType))\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\" \")\n\t\t\t}\n\n\t\t}\n\t\tfmt.Printf(\"\\n\")\n\t}\n}", "func (ie *IndexExpr) String() string {\n\treturn fmt.Sprintf(\"(%s[%s])\", ie.Left.String(), ie.Index.String())\n}", "func prettyFormat(node *BTree, indent string, last bool) string {\n\tresult := indent\n\n\tif last {\n\t\tresult += \"\\\\-\"\n\t\tindent += \" \"\n\t} else {\n\t\tresult += \"|-\"\n\t\tindent += \"| \"\n\t}\n\n\tif node == nil {\n\t\tresult += \"<nada>\\n\"\n\n\t\treturn result\n\t}\n\n\tresult += fmt.Sprintf(\"%v\", node.Value) + \"\\n\"\n\n\tchildren := make([]*BTree, 0)\n\n\tif node.Left != nil {\n\t\tchildren = append(children, node.Left)\n\t} else {\n\t\tchildren = append(children, nil)\n\t}\n\n\tif node.Right != nil {\n\t\tchildren = append(children, node.Right)\n\t} else {\n\t\tchildren = append(children, nil)\n\t}\n\n\tfor i := 0; i < len(children); i++ {\n\t\tresult += prettyFormat(children[i], indent, i == len(children)-1)\n\t}\n\n\treturn result\n}", "func Space(count int) string {\n\treturn strings.Repeat(\" \", count)\n}", "func PrettyPrint(in string) string {\n\tvar out bytes.Buffer\n\terr := json.Indent(&out, []byte(in), \"\", \"\\t\")\n\tif err != nil {\n\t\treturn in\n\t}\n\treturn out.String()\n}", "func PrettyString(inObj interface{}, depthLimit int) string {\n\tvar buf bytes.Buffer\n\tformObj(&buf, reflect.ValueOf(inObj), 0, depthLimit)\n\tbuf.WriteString(\"\\n\")\n\treturn buf.String()\n}", "func (c *Counter) String() string {\n\treturn fmt.Sprintf(\"%s\\t%v\",c.key,c.count)\n}", "func Indent(s string) string {\n\tif config.Minify {\n\t\treturn s\n\t}\n\n\tin := \" \"\n\tr := strings.NewReplacer(\"\\n\", \"\\n\"+in)\n\ts = r.Replace(s)\n\treturn in + strings.TrimSuffix(s, in)\n}", "func (s MapInt) String() string { return StringSlice(\", \", \"[\", \"]\", s.Slice()...) }", "func (x Index) String() string {\n\tif str, ok := _IndexMap[x]; ok {\n\t\treturn str\n\t}\n\treturn fmt.Sprintf(\"Index(%d)\", x)\n}", "func (s *CreateIndexStatement) String() string {\n\tvar buf bytes.Buffer\n\tbuf.WriteString(\"CREATE\")\n\tif s.Unique.IsValid() {\n\t\tbuf.WriteString(\" UNIQUE\")\n\t}\n\tbuf.WriteString(\" INDEX\")\n\tif s.IfNotExists.IsValid() {\n\t\tbuf.WriteString(\" IF NOT EXISTS\")\n\t}\n\tfmt.Fprintf(&buf, \" %s ON %s \", s.Name.String(), s.Table.String())\n\n\tbuf.WriteString(\"(\")\n\tfor i, col := range s.Columns {\n\t\tif i != 0 {\n\t\t\tbuf.WriteString(\", \")\n\t\t}\n\t\tbuf.WriteString(col.String())\n\t}\n\tbuf.WriteString(\")\")\n\n\tif s.WhereExpr != nil {\n\t\tfmt.Fprintf(&buf, \" WHERE %s\", s.WhereExpr.String())\n\t}\n\n\treturn buf.String()\n}", "func Sprint(args ...interface{}) string {\n\treturn wrapString(func() string {\n\t\treturn fmt.Sprint(styleArgs(args)...)\n\t})\n}", "func prettyPrint(src []byte) (string, error) {\n\tvar dst bytes.Buffer\n\terr := json.Indent(&dst, src, \"\", \" \")\n\tif nil != err {\n\t\treturn \"\", err\n\t}\n\treturn dst.String(), nil\n}", "func (s DeleteIndexOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s ExpressionStepElementKeyIntExact) String() string {\n\treturn fmt.Sprintf(\"[%d]\", s)\n}", "func (h *Heap) String() string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"[\")\n\n\tvar nodesInLayer, newLineIdx int = 1, 0\n\tfor i, el := range h.heap {\n\t\tsb.WriteString(strconv.Itoa(el))\n\t\tif i == len(h.heap)-1 {\n\t\t\tbreak\n\t\t}\n\n\t\tif i == newLineIdx {\n\t\t\tsb.WriteRune('\\n')\n\t\t\tnodesInLayer *= 2\n\t\t\tnewLineIdx += nodesInLayer\n\t\t\tcontinue\n\t\t}\n\n\t\tsb.WriteRune(' ')\n\t}\n\n\tsb.WriteString(\"]\")\n\treturn sb.String()\n}", "func (v CachingType) PrettyString(depth uint, withHeader bool, opts ...pretty.Option) string {\n\treturn v.String()\n}", "func (s UpdateIndexTypeOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func printA(n int){\n\ta :=\"\"\n\tfor i:=0;i<n;i++{\n\t\ta+=\"A\"\n\t}\n\tfmt.Println(a)\n}", "func (c *Card) PrettyPrint() {\n\tfmt.Println(\"Card Title: \", c.CardTitle)\n\tfmt.Println(\"Card House: \", c.House)\n\tfmt.Println(\"Card Amber: \", c.Amber)\n}", "func bytesToPrettyBar(bar []byte) string {\n\twriter := new(bytes.Buffer)\n\tfor _, p := range bar {\n\t\tif p != 0 {\n\t\t\twriter.WriteRune('x')\n\t\t} else {\n\t\t\twriter.WriteRune('-')\n\t\t}\n\t}\n\treturn writer.String()\n}", "func PrettyPrintStruct(data interface{}) string {\n\tv := reflect.ValueOf(data)\n\tmethod := v.MethodByName(\"String\")\n\tif method.IsValid() && method.Type().NumIn() == 0 && method.Type().NumOut() == 1 &&\n\t\tmethod.Type().Out(0).Kind() == reflect.String {\n\t\tresult := method.Call([]reflect.Value{})\n\t\treturn result[0].String()\n\t}\n\treturn fmt.Sprintf(\"%#v\", data)\n}" ]
[ "0.6439502", "0.61760306", "0.59833777", "0.59277177", "0.5895147", "0.5875071", "0.58508503", "0.5809923", "0.5798425", "0.5776657", "0.5729011", "0.572732", "0.572732", "0.5722393", "0.56776077", "0.56776077", "0.5616657", "0.5615194", "0.5596373", "0.55866176", "0.5582632", "0.5562355", "0.55386484", "0.5518597", "0.551395", "0.550863", "0.55061704", "0.55010635", "0.54878956", "0.54775655", "0.5477022", "0.54594976", "0.54524606", "0.54518634", "0.54395205", "0.5433841", "0.54286957", "0.5417458", "0.54152", "0.53983086", "0.53965104", "0.53838235", "0.538157", "0.53765357", "0.53676265", "0.53038543", "0.52997535", "0.52950424", "0.52875066", "0.52824104", "0.5277137", "0.5272881", "0.526786", "0.5266122", "0.5265373", "0.5259872", "0.525362", "0.523619", "0.52297056", "0.5228179", "0.5228179", "0.5213063", "0.5203149", "0.520154", "0.52006257", "0.5192116", "0.51916784", "0.51900476", "0.5184233", "0.5183418", "0.51718897", "0.51714545", "0.5158195", "0.5145254", "0.51410323", "0.51343447", "0.5132711", "0.5125168", "0.51133275", "0.5112848", "0.5111481", "0.5111083", "0.51100236", "0.510671", "0.51038116", "0.5100407", "0.509194", "0.508327", "0.5079518", "0.5077099", "0.5067613", "0.504781", "0.5044348", "0.503382", "0.50275713", "0.50212014", "0.50178343", "0.5009907", "0.50062495", "0.49960336" ]
0.57190317
14
UserString returns a simple string representation of the command for the user.
func (scp *SCP) UserString() string { return fmt.Sprintf("SCP %s %s:%s", scp.Source, scp.TargetHost, scp.Destination) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s PosixUser) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s GetUserOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s MessageState) UserCommand() string {\n\treturn strings.Replace(s.MessageParts()[0], CommandPrefix, \"\", 1)\n}", "func (user *UserID) String() string {\n\treturn user.raw\n}", "func (s GetUserInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (m *User) String() string {\n\tif m == nil {\n\t\treturn \"<nil>\"\n\t}\n\torig := m.Password\n\tm.Password = \"<not shown>\"\n\n\tstr := proto.CompactTextString(m)\n\n\tm.Password = orig\n\treturn str\n}", "func (s pgUser) String() string {\n\tres := make([]string, 2)\n\tres[0] = \"UserID: \" + reform.Inspect(s.UserID, true)\n\tres[1] = \"UserName: \" + reform.Inspect(s.UserName, true)\n\treturn strings.Join(res, \", \")\n}", "func (s User) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s User) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DescribeUserOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DescribeUserOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateUserOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateUserOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateUserOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DeleteUserOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DeleteUserOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (l *Logger) UserString() string {\n\treturn \"adding log entry\"\n}", "func (s RegisterUserOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s IamUser) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (user User) String() string {\n\tif len(user.DisplayName) > 0 {\n\t\treturn user.DisplayName\n\t}\n\treturn user.ID\n}", "func (s DeleteUserInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DeleteUserInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateUserInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateUserInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateUserInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DescribeUserInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DescribeUserInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (u *User) String() string {\n\treturn fmt.Sprintf(\"ID='%s' name='%s'\", u.ID, u.Name)\n}", "func User() string {\n\treturn user\n}", "func (u *User) String() string {\n\tvar builder strings.Builder\n\tbuilder.WriteString(\"User(\")\n\tbuilder.WriteString(fmt.Sprintf(\"id=%v\", u.ID))\n\tbuilder.WriteString(\", email=\")\n\tbuilder.WriteString(u.Email)\n\tbuilder.WriteString(\", password=\")\n\tbuilder.WriteString(u.Password)\n\tbuilder.WriteString(\", images=\")\n\tbuilder.WriteString(u.Images)\n\tbuilder.WriteByte(')')\n\treturn builder.String()\n}", "func (u *User) String() string {\n\tstr := u.Host.Nick()\n\tif fh := u.Host.String(); len(fh) > 0 && str != fh {\n\t\tstr += \" \" + fh\n\t}\n\tif len(u.Realname) > 0 {\n\t\tstr += \" \" + u.Realname\n\t}\n\n\treturn str\n}", "func (u User) String() string {\n\ts := fmt.Sprintf(\"|-------------------------------------------------------------------------------|\\n\")\n\ts += fmt.Sprintf(\"| UserId | %-65s |\\n\", u.UserID)\n\ts += fmt.Sprintf(\"| Username | %-65s |\\n\", u.Username)\n\ts += fmt.Sprintf(\"| Firstname | %-65s |\\n\", u.FirstName)\n\ts += fmt.Sprintf(\"| Lastname | %-65s |\\n\", u.LastName)\n\ts += fmt.Sprintf(\"| Email | %-65s |\\n\", u.Email)\n\ts += fmt.Sprintf(\"| LastLogin | %-65s |\\n\", u.LastLogin)\n\ts += fmt.Sprintf(\"| Self | %-65s |\\n\", u.SelfLink)\n\ts += fmt.Sprintf(\"|-------------------------------------------------------------------------------|\\n\")\n\n\treturn s\n}", "func (s DescribedUser) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DisableUserOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s RegisterUserInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (u *Userinfo) String() string {\n\tif u == nil {\n\t\treturn \"\"\n\t}\n\ts := escape(u.username, encodeUserPassword)\n\tif u.passwordSet {\n\t\ts += \":\" + escape(u.password, encodeUserPassword)\n\t}\n\treturn s\n}", "func (user *User) String() string {\n\tjson, _ := json.MarshalIndent(*user, \" \", \" \")\n\treturn string(json)\n}", "func (a *userAction) String() string {\n\tvar props = &userActionProps{}\n\n\tif a.props != nil {\n\t\tprops = a.props\n\t}\n\n\treturn props.tr(a.log, nil)\n}", "func (s UserContext) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s UserData) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s UserData) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s UserData) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s UserData) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (u *User) String() string {\n\tvar builder strings.Builder\n\tbuilder.WriteString(\"User(\")\n\tbuilder.WriteString(fmt.Sprintf(\"id=%v\", u.ID))\n\tbuilder.WriteString(\", tenant=\")\n\tbuilder.WriteString(u.Tenant)\n\tbuilder.WriteString(\", uuid=\")\n\tbuilder.WriteString(u.UUID)\n\tbuilder.WriteString(\", parent_id=\")\n\tbuilder.WriteString(fmt.Sprintf(\"%v\", u.ParentID))\n\tbuilder.WriteString(\", is_super=\")\n\tbuilder.WriteString(fmt.Sprintf(\"%v\", u.IsSuper))\n\tbuilder.WriteString(\", data=\")\n\tbuilder.WriteString(fmt.Sprintf(\"%v\", u.Data))\n\tbuilder.WriteString(\", created_at=\")\n\tbuilder.WriteString(u.CreatedAt.Format(time.ANSIC))\n\tbuilder.WriteString(\", updated_at=\")\n\tbuilder.WriteString(u.UpdatedAt.Format(time.ANSIC))\n\tbuilder.WriteByte(')')\n\treturn builder.String()\n}", "func (u User) String() string {\n\tju, _ := json.Marshal(u)\n\treturn string(ju)\n}", "func (u User) String() string {\n\tju, _ := json.Marshal(u)\n\treturn string(ju)\n}", "func (u User) String() string {\n\tju, _ := json.Marshal(u)\n\treturn string(ju)\n}", "func (u User) String() string {\n\tju, _ := json.Marshal(u)\n\treturn string(ju)\n}", "func (u User) String() string {\n\tju, _ := json.Marshal(u)\n\treturn string(ju)\n}", "func (u User) String() string {\n\tju, _ := json.Marshal(u)\n\treturn string(ju)\n}", "func (u *User) String() string {\n\tvar builder strings.Builder\n\tbuilder.WriteString(\"User(\")\n\tbuilder.WriteString(fmt.Sprintf(\"id=%v, \", u.ID))\n\tbuilder.WriteString(\"name=\")\n\tbuilder.WriteString(u.Name)\n\tbuilder.WriteString(\", \")\n\tbuilder.WriteString(\"display_name=\")\n\tbuilder.WriteString(u.DisplayName)\n\tbuilder.WriteString(\", \")\n\tbuilder.WriteString(\"admin=\")\n\tbuilder.WriteString(fmt.Sprintf(\"%v\", u.Admin))\n\tbuilder.WriteString(\", \")\n\tbuilder.WriteString(\"created_at=\")\n\tbuilder.WriteString(u.CreatedAt.Format(time.ANSIC))\n\tbuilder.WriteString(\", \")\n\tbuilder.WriteString(\"updated_at=\")\n\tbuilder.WriteString(u.UpdatedAt.Format(time.ANSIC))\n\tbuilder.WriteString(\", \")\n\tif v := u.DeletedAt; v != nil {\n\t\tbuilder.WriteString(\"deleted_at=\")\n\t\tbuilder.WriteString(v.Format(time.ANSIC))\n\t}\n\tbuilder.WriteByte(')')\n\treturn builder.String()\n}", "func (u *User) String() string {\n\treturn u.Username + \"#\" + u.Discriminator\n}", "func (u *User) String() string {\n\tvar builder strings.Builder\n\tbuilder.WriteString(\"User(\")\n\tbuilder.WriteString(fmt.Sprintf(\"id=%v\", u.ID))\n\tbuilder.WriteString(\", create_time=\")\n\tbuilder.WriteString(u.CreateTime.Format(time.ANSIC))\n\tbuilder.WriteString(\", update_time=\")\n\tbuilder.WriteString(u.UpdateTime.Format(time.ANSIC))\n\tbuilder.WriteString(\", email=\")\n\tbuilder.WriteString(u.Email)\n\tbuilder.WriteString(\", firebaseUid=\")\n\tbuilder.WriteString(u.FirebaseUid)\n\tbuilder.WriteByte(')')\n\treturn builder.String()\n}", "func (s UserIdentity) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (u *User) String() string {\n\tvar builder strings.Builder\n\tbuilder.WriteString(\"User(\")\n\tbuilder.WriteString(fmt.Sprintf(\"id=%v\", u.ID))\n\tbuilder.WriteString(\", field1=\")\n\tbuilder.WriteString(u.Field1)\n\tbuilder.WriteString(\", field2=\")\n\tbuilder.WriteString(u.Field2)\n\tbuilder.WriteString(\", field3=\")\n\tbuilder.WriteString(u.Field3)\n\tbuilder.WriteString(\", first_name=\")\n\tbuilder.WriteString(u.FirstName)\n\tbuilder.WriteString(\", last_name=\")\n\tbuilder.WriteString(u.LastName)\n\tbuilder.WriteByte(')')\n\treturn builder.String()\n}", "func (d *DocumentUser) String() string {\n\n\t// Gives access to the fields in another model\n\tuadmin.Preload(d)\n\n\t// Returns the full name from the User model\n\treturn d.User.String()\n}", "func (u *User) String() string {\n\tvar builder strings.Builder\n\tbuilder.WriteString(\"User(\")\n\tbuilder.WriteString(fmt.Sprintf(\"id=%v\", u.ID))\n\tbuilder.WriteString(\", uuid=\")\n\tbuilder.WriteString(fmt.Sprintf(\"%v\", u.UUID))\n\tbuilder.WriteString(\", lastName=\")\n\tbuilder.WriteString(u.LastName)\n\tbuilder.WriteString(\", firstName=\")\n\tbuilder.WriteString(u.FirstName)\n\tbuilder.WriteString(\", age=\")\n\tbuilder.WriteString(fmt.Sprintf(\"%v\", u.Age))\n\tbuilder.WriteString(\", profile=\")\n\tbuilder.WriteString(u.Profile)\n\tbuilder.WriteString(\", email=\")\n\tbuilder.WriteString(u.Email)\n\tbuilder.WriteString(\", password=<sensitive>\")\n\tbuilder.WriteByte(')')\n\treturn builder.String()\n}", "func (s GetCurrentUserDataOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (c Command) String() string {\n\tswitch c {\n\tcase SERVER:\n\t\treturn \"server\"\n\tcase ASSETS:\n\t\treturn \"assets\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}", "func (n *CreateUser) String() string {\n\tusers := make([]string, len(n.Users))\n\tfor i, user := range n.Users {\n\t\tusers[i] = user.UserName.String(\"\")\n\t}\n\tifNotExists := \"\"\n\tif n.IfNotExists {\n\t\tifNotExists = \"IfNotExists: \"\n\t}\n\treturn fmt.Sprintf(\"CreateUser(%s%s)\", ifNotExists, strings.Join(users, \", \"))\n}", "func (s Command) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (u *User) String() string {\n\tif u.UserName != \"\" {\n\t\treturn u.UserName\n\t}\n\n\tname := u.FirstName\n\tif u.LastName != \"\" {\n\t\tname += \" \" + u.LastName\n\t}\n\n\treturn name\n}", "func (s PutUserStatusOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (inst *UserN) String() string {\n\trs, _ := json.Marshal(inst)\n\treturn string(rs)\n}", "func (s FederatedUser) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s FederatedUser) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s PutUserStatusInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s GetRelationalDatabaseMasterUserPasswordInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (cu *CompanyUser) String() string {\n\tvar builder strings.Builder\n\tbuilder.WriteString(\"CompanyUser(\")\n\tbuilder.WriteString(fmt.Sprintf(\"id=%v\", cu.ID))\n\tbuilder.WriteString(\", last_name=\")\n\tbuilder.WriteString(cu.LastName)\n\tbuilder.WriteString(\", first_name=\")\n\tbuilder.WriteString(cu.FirstName)\n\tbuilder.WriteString(\", last_name_furigana=\")\n\tbuilder.WriteString(cu.LastNameFurigana)\n\tbuilder.WriteString(\", first_name_furigana=\")\n\tbuilder.WriteString(cu.FirstNameFurigana)\n\tbuilder.WriteString(\", profile_name=\")\n\tbuilder.WriteString(cu.ProfileName)\n\tbuilder.WriteString(\", icon_url=\")\n\tbuilder.WriteString(cu.IconURL)\n\tbuilder.WriteString(\", gender=\")\n\tbuilder.WriteString(fmt.Sprintf(\"%v\", cu.Gender))\n\tbuilder.WriteByte(')')\n\treturn builder.String()\n}", "func (s GetRelationalDatabaseMasterUserPasswordOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (u *User) String() string {\n\tvar builder strings.Builder\n\tbuilder.WriteString(\"User(\")\n\tbuilder.WriteString(fmt.Sprintf(\"id=%v\", u.ID))\n\tbuilder.WriteString(\", created_at=\")\n\tbuilder.WriteString(u.CreatedAt.Format(time.ANSIC))\n\tbuilder.WriteString(\", updated_at=\")\n\tbuilder.WriteString(u.UpdatedAt.Format(time.ANSIC))\n\tbuilder.WriteString(\", username=\")\n\tbuilder.WriteString(u.Username)\n\tbuilder.WriteString(\", fullname=\")\n\tbuilder.WriteString(u.Fullname)\n\tbuilder.WriteString(\", password=\")\n\tbuilder.WriteString(u.Password)\n\tbuilder.WriteString(\", email=\")\n\tbuilder.WriteString(u.Email)\n\tbuilder.WriteString(\", phone=\")\n\tbuilder.WriteString(u.Phone)\n\tbuilder.WriteString(\", bio=\")\n\tbuilder.WriteString(u.Bio)\n\tbuilder.WriteString(\", intro=\")\n\tbuilder.WriteString(u.Intro)\n\tbuilder.WriteString(\", github_profile=\")\n\tbuilder.WriteString(u.GithubProfile)\n\tbuilder.WriteString(\", profile_picture_url=\")\n\tbuilder.WriteString(u.ProfilePictureURL)\n\tbuilder.WriteString(\", status=\")\n\tbuilder.WriteString(fmt.Sprintf(\"%v\", u.Status))\n\tbuilder.WriteByte(')')\n\treturn builder.String()\n}", "func (o PgbenchSpecPostgresOutput) User() pulumi.StringOutput {\n\treturn o.ApplyT(func(v PgbenchSpecPostgres) string { return v.User }).(pulumi.StringOutput)\n}", "func (u *User) String() string {\n\tvar builder strings.Builder\n\tbuilder.WriteString(\"User(\")\n\tbuilder.WriteString(fmt.Sprintf(\"id=%v\", u.ID))\n\tbuilder.WriteString(\", created_at=\")\n\tbuilder.WriteString(u.CreatedAt.Format(time.ANSIC))\n\tbuilder.WriteString(\", updated_at=\")\n\tbuilder.WriteString(u.UpdatedAt.Format(time.ANSIC))\n\tbuilder.WriteString(\", username=\")\n\tbuilder.WriteString(u.Username)\n\tbuilder.WriteString(\", avatar=\")\n\tbuilder.WriteString(u.Avatar)\n\tbuilder.WriteString(\", remind_me=\")\n\tbuilder.WriteString(fmt.Sprintf(\"%v\", u.RemindMe))\n\tbuilder.WriteString(\", wake_up_time=\")\n\tbuilder.WriteString(u.WakeUpTime.Format(time.ANSIC))\n\tbuilder.WriteString(\", sleep_time=\")\n\tbuilder.WriteString(u.SleepTime.Format(time.ANSIC))\n\tbuilder.WriteString(\", gender=\")\n\tbuilder.WriteString(fmt.Sprintf(\"%v\", u.Gender))\n\tbuilder.WriteString(\", weight=\")\n\tbuilder.WriteString(fmt.Sprintf(\"%v\", u.Weight))\n\tbuilder.WriteString(\", daily_intake=\")\n\tbuilder.WriteString(fmt.Sprintf(\"%v\", u.DailyIntake))\n\tbuilder.WriteString(\", container_image=\")\n\tbuilder.WriteString(u.ContainerImage)\n\tbuilder.WriteString(\", container_volume=\")\n\tbuilder.WriteString(fmt.Sprintf(\"%v\", u.ContainerVolume))\n\tbuilder.WriteString(\", drink_at_a_time=\")\n\tbuilder.WriteString(fmt.Sprintf(\"%v\", u.DrinkAtATime))\n\tbuilder.WriteString(\", password=\")\n\tbuilder.WriteString(u.Password)\n\tbuilder.WriteByte(')')\n\treturn builder.String()\n}", "func (s ExecuteCommandInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DisableUserInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (c *Command) String() string {\n\tif len(c.Params) > 0 {\n\t\treturn fmt.Sprintf(\"%s %s\", c.Name, string(bytes.Join(c.Params, byteSpace)))\n\t}\n\treturn string(c.Name)\n}", "func (s UserReference) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (c *Command) String() string {\n\treturn strings.Join(c.StringSlice(), \" \")\n}", "func (s GetCurrentUserDataInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (cmd *Cmd) String() string {\n\treturn fmt.Sprintf(\"%s %s\", cmd.Name, strings.Join(cmd.Args, \" \"))\n}", "func UserToString(id int) {\n\tvar i int\n\ti = GetIndexOfUser(id)\n\n\tfmt.Println(\"User Id: \", userList[i].uID)\n\tfmt.Println(\"User Email: \", userList[i].uEmail)\n\tfmt.Println(\"User Password: \", userList[i].uPassword)\n\tfmt.Println(\"User Bank Name: \", userList[i].uBankAccount.bankName)\n\tfmt.Println(\"User Account #: \", userList[i].uBankAccount.accountNumber)\n\tfmt.Println(\"User Routing #: \", userList[i].uBankAccount.routingNumber)\n\tfmt.Println(\"\\n\")\n}", "func (s UpdateUserHierarchyOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s ListedUser) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o UserConf) String() string {\n\tif int(o) >= len(userConfStr) || o < 0 {\n\t\treturn userConfStr[0]\n\t}\n\n\treturn userConfStr[o]\n}", "func GetUser() string {\n\tif cuser == \"\" {\n\t\tcuser = GetCmdStr(\"echo $USER\")\n\t}\n\tif cuser == \"\" {\n\t\tcuser = GetCmdStr(\"whoami\")\n\t}\n\treturn cuser\n}", "func (s AssumedRoleUser) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (cmd *Command) String() string {\n\treturn fmt.Sprintf(\"ID:%s,Op:%d,Key:%s,Value:%s,Resp:%s\", cmd.ID, cmd.Op, cmd.Key, cmd.Value, cmd.Resp)\n}", "func (s UpdateUserHierarchyInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s UserSummary) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (cmd *Command) String() string {\n\tstr := \"\"\n\tif cmd.c.Process != nil {\n\t\tstr += fmt.Sprintf(\"(PID %v) \", cmd.c.Process.Pid)\n\t}\n\tif cmd.pgid >= 0 {\n\t\tstr += fmt.Sprintf(\"(PGID %v) \", cmd.pgid)\n\t}\n\tstr += shellquote.Join(cmd.c.Args...)\n\treturn str\n}", "func (cmd *command) String() string {\n\tif len(cmd.params) == 0 {\n\t\treturn fmt.Sprintf(\"(%s)\", cmd.name)\n\t}\n\n\tparams := make([]string, len(cmd.params))\n\tfor i, param := range cmd.params {\n\t\tswitch concrete := param.(type) {\n\t\tcase int:\n\t\t\tparams[i] = fmt.Sprintf(\"%d\", concrete)\n\t\tcase float64:\n\t\t\tparams[i] = fmt.Sprintf(\"%0.2f\", concrete)\n\t\tcase string:\n\t\t\tparams[i] = concrete\n\t\tcase *command:\n\t\t\tparams[i] = concrete.String()\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"Unexpected type: %T\", concrete))\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"(%s %s)\", cmd.name, strings.Join(params, \" \"))\n}", "func (s UserTurnResult) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s UserIdentityInfo) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s UpdateUserSettingsInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s UpdateUserIdentityInfoInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (c causer) String() string {\n\treturn c.Name\n}", "func (s UpdateUserIdentityInfoOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (c Command) String() string {\n\tvar cmdStr strings.Builder\n\tcmdStr.WriteString(cmdString + c.Command)\n\n\tfirst := true\n\tfor key, val := range c.Properties {\n\t\tif first {\n\t\t\tfirst = false\n\t\t\tcmdStr.WriteString(\" \")\n\t\t} else {\n\t\t\tcmdStr.WriteString(\",\")\n\t\t}\n\n\t\tcmdStr.WriteString(fmt.Sprintf(\"%s=%s\", key, escape(val)))\n\t}\n\n\tcmdStr.WriteString(cmdString)\n\tcmdStr.WriteString(escapeData(c.Message))\n\treturn cmdStr.String()\n}", "func (inst *UserExtN) String() string {\n\trs, _ := json.Marshal(inst)\n\treturn string(rs)\n}", "func (o BuildStrategySpecBuildStepsSecurityContextSeLinuxOptionsOutput) User() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BuildStrategySpecBuildStepsSecurityContextSeLinuxOptions) *string { return v.User }).(pulumi.StringPtrOutput)\n}" ]
[ "0.7131865", "0.69964004", "0.69042116", "0.68736285", "0.68736136", "0.6841844", "0.67860997", "0.6781669", "0.6781669", "0.6776455", "0.6776455", "0.6716205", "0.6716205", "0.6716205", "0.67156404", "0.67156404", "0.6670632", "0.664154", "0.662496", "0.6622693", "0.6615488", "0.6615488", "0.65911007", "0.65911007", "0.65911007", "0.6555839", "0.6555839", "0.65518093", "0.6547822", "0.6533217", "0.65320355", "0.6520407", "0.65203905", "0.65046114", "0.6493522", "0.6486402", "0.6460744", "0.6442783", "0.64414024", "0.6437069", "0.6437069", "0.6437069", "0.6437069", "0.64336365", "0.6408966", "0.6408966", "0.6408966", "0.6408966", "0.6408966", "0.6408966", "0.63965845", "0.63964915", "0.6367758", "0.63671666", "0.6351183", "0.63482493", "0.63136", "0.63004357", "0.62983394", "0.62938046", "0.621754", "0.62151027", "0.6207024", "0.61928385", "0.6182644", "0.6182644", "0.6172581", "0.6155515", "0.6151276", "0.6145402", "0.6145195", "0.6126197", "0.61111015", "0.6092988", "0.6092335", "0.6087852", "0.60815084", "0.6058691", "0.6050349", "0.604028", "0.6040194", "0.6025095", "0.6018307", "0.5996975", "0.5990535", "0.59846026", "0.5983682", "0.5973625", "0.5969067", "0.5968055", "0.59599775", "0.59564364", "0.5946508", "0.59288573", "0.5924732", "0.59050655", "0.5902967", "0.589559", "0.58901167", "0.58869153" ]
0.686068
5
Define the CRU functions for the config path
func (b *backend) pathConfigCRUD() *framework.Path { return &framework.Path{ Pattern: fmt.Sprintf("config/?$"), HelpSynopsis: "Configure the Minio connection.", HelpDescription: "Use this endpoint to set the Minio endpoint, accessKeyId, secretAccessKey and SSL settings.", Fields: map[string]*framework.FieldSchema{ "endpoint": &framework.FieldSchema{ Type: framework.TypeString, Description: "The Minio server endpoint.", }, "accessKeyId": &framework.FieldSchema{ Type: framework.TypeString, Description: "The Minio administrative key ID.", }, "secretAccessKey": &framework.FieldSchema{ Type: framework.TypeString, Description: "The Minio administrative secret access key.", }, "useSSL": &framework.FieldSchema{ Type: framework.TypeBool, Description: "(Optional, default `false`) Use SSL to connect to the Minio server.", }, }, Callbacks: map[logical.Operation]framework.OperationFunc{ logical.ReadOperation: b.pathConfigRead, logical.UpdateOperation: b.pathConfigUpdate, }, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func commonCloudConfig(encodedData, command, path string, cf map[interface{}]interface{}, newUserDataFile *os.File) error {\n\twriteFile := map[string]string{\n\t\t\"encoding\": \"gzip+b64\",\n\t\t\"content\": fmt.Sprintf(\"%s\", encodedData),\n\t\t\"permissions\": \"0644\",\n\t\t\"path\": path,\n\t}\n\tif err := appendValueToListInCloudConfig(cf, \"write_files\", writeFile); err != nil {\n\t\treturn err\n\t}\n\n\t// Add to the runcmd directive\n\tif err := appendValueToListInCloudConfig(cf, \"runcmd\", fmt.Sprintf(\"%s %s\", command, writeFile[\"path\"])); err != nil {\n\t\treturn err\n\t}\n\n\tuserdataContent, err := yaml.Marshal(cf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tuserdataContent = append([]byte(\"#cloud-config\\n\"), userdataContent...)\n\t_, err = newUserDataFile.Write(userdataContent)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func initConfig() {\n\tif cfgFile != \"\" {\n\t\t// enable ability to specify config file via flag\n\t\tviper.SetConfigFile(cfgFile)\n\t}\n\n\tsetDefaultValues()\n\n\t// Check whether the user has specified the WUM_UC_HOME environment variable.\n\tWUMUCHome = os.Getenv(constant.WUM_UC_HOME)\n\tif WUMUCHome == \"\" {\n\t\t// User has not specified WUM_UC_HOME.\n\t\t// Get the home directory of the current user.\n\t\thomeDirPath, err := homedir.Dir()\n\t\tif err != nil {\n\t\t\tutil.HandleErrorAndExit(err, \"Cannot determine the current user's home directory.\")\n\t\t}\n\t\tWUMUCHome = filepath.Join(homeDirPath, constant.WUMUC_HOME_DIR_NAME)\n\t\tlogger.Debug(fmt.Sprintf(\"wum-uc home directory path: %s\", WUMUCHome))\n\t\tutil.SetWUMUCLocalRepo(WUMUCHome)\n\t}\n\tviper.Set(constant.WUM_UC_HOME, WUMUCHome)\n\tutil.LoadWUMUCConfig(WUMUCHome)\n\n\tviper.SetConfigName(\"config\") // name of config file (without extension)\n\tviper.AddConfigPath(\".\")\n\tviper.AddConfigPath(\"$HOME/.wum-uc\")\n\t//viper.AutomaticEnv()\n\n\t// If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tlogger.Debug(fmt.Sprintf(\"Config file found: %v\", viper.ConfigFileUsed()))\n\t} else {\n\t\tlogger.Debug(\"Config file not found.\")\n\t}\n\n\tlogger.Debug(fmt.Sprintf(\"PATH_SEPARATOR: %s\", constant.PATH_SEPARATOR))\n\tlogger.Debug(\"Config Values: ---------------------------\")\n\tlogger.Debug(fmt.Sprintf(\"%s: %s\", constant.CHECK_MD5_DISABLED, viper.GetString(constant.CHECK_MD5_DISABLED)))\n\tlogger.Debug(fmt.Sprintf(\"%s: %s\", constant.RESOURCE_FILES_MANDATORY,\n\t\tviper.GetStringSlice(constant.RESOURCE_FILES_MANDATORY)))\n\tlogger.Debug(fmt.Sprintf(\"%s: %s\", constant.RESOURCE_FILES_OPTIONAL,\n\t\tviper.GetStringSlice(constant.RESOURCE_FILES_OPTIONAL)))\n\tlogger.Debug(fmt.Sprintf(\"%s: %s\", constant.RESOURCE_FILES_SKIP,\n\t\tviper.GetStringSlice(constant.RESOURCE_FILES_SKIP)))\n\tlogger.Debug(fmt.Sprintf(\"%s: %s\", constant.PLATFORM_VERSIONS,\n\t\tviper.GetStringMapString(constant.PLATFORM_VERSIONS)))\n\tlogger.Debug(\"-----------------------------------------\")\n}", "func initConfig() {\n}", "func initConfig() {\n}", "func initConfig() {\n}", "func initConfig() {\n}", "func initConfig() {\n}", "func initConfig() {\n}", "func initConfig() {\n\tctx := cuecontext.New()\n\tval := cue.Value{}\n\text := filepath.Ext(cfgFile)\n\n\t_, err := os.Stat(cfgFile)\n\tif err != nil {\n\t\tcobra.CheckErr(err)\n\t}\n\n\tswitch ext {\n\tcase \".cue\":\n\t\tbuildInstances := load.Instances([]string{cfgFile}, nil)\n\t\tinsts := cue.Build(buildInstances)\n\t\tval = insts[0].Value()\n\tcase \".json\", \".yaml\":\n\t\tr, err := os.Open(cfgFile)\n\t\tif err != nil {\n\t\t\tcobra.CheckErr(err)\n\t\t}\n\t\tdata, err := ioutil.ReadAll(r)\n\t\tif err != nil {\n\t\t\tcobra.CheckErr(err)\n\t\t}\n\t\tval = ctx.CompileBytes(data)\n\tdefault:\n\t\tcobra.CheckErr(fmt.Errorf(\"config file must be json or yaml format\"))\n\t}\n\n\tif err := cfg.BuildConfig(val); err != nil {\n\t\tvar errs []string\n\t\tfor _, v := range errors.Errors(err) {\n\t\t\t_, args := v.Msg()\n\t\t\tpath := strings.Join(v.Path(), \".\")\n\t\t\tmsg := fmt.Sprintf(\"%s invalid value %v\", path, args[0])\n\t\t\terrs = append(errs, msg)\n\t\t}\n\n\t\tlog.Fatalf(\"errors loading config: %v\", errs[1:])\n\t}\n}", "func UserConfigDir() (string, error)", "func (ac *Config) LoadCommonFunctions(w http.ResponseWriter, req *http.Request, filename string, L *lua.LState, flushFunc func(), httpStatus *FutureStatus) {\n\t// Make basic functions, like print, available to the Lua script.\n\t// Only exports functions that can relate to HTTP responses or requests.\n\tac.LoadBasicWeb(w, req, L, filename, flushFunc, httpStatus)\n\n\t// Make other basic functions available\n\tac.LoadBasicSystemFunctions(L)\n\n\t// Functions for rendering markdown or amber\n\tac.LoadRenderFunctions(w, req, L)\n\n\t// If there is a database backend\n\tif ac.perm != nil {\n\n\t\t// Retrieve the userstate\n\t\tuserstate := ac.perm.UserState()\n\n\t\t// Set the cookie secret, if set\n\t\tif ac.cookieSecret != \"\" {\n\t\t\tuserstate.SetCookieSecret(ac.cookieSecret)\n\t\t}\n\n\t\t// Functions for serving files in the same directory as a script\n\t\tac.LoadServeFile(w, req, L, filename)\n\n\t\t// Functions mainly for adding admin prefixes and configuring permissions\n\t\tac.LoadServerConfigFunctions(L, filename)\n\n\t\t// Make the functions related to userstate available to the Lua script\n\t\tusers.Load(w, req, L, userstate)\n\n\t\tcreator := userstate.Creator()\n\n\t\t// Simpleredis data structures\n\t\tdatastruct.LoadList(L, creator)\n\t\tdatastruct.LoadSet(L, creator)\n\t\tdatastruct.LoadHash(L, creator)\n\t\tdatastruct.LoadKeyValue(L, creator)\n\n\t\t// For saving and loading Lua functions\n\t\tcodelib.Load(L, creator)\n\n\t\t// For executing PostgreSQL queries\n\t\tpquery.Load(L)\n\n\t\t// For executing MSSQL queries\n\t\tmssql.Load(L)\n\n\t}\n\n\t// For handling JSON data\n\tjnode.LoadJSONFunctions(L)\n\tac.LoadJFile(L, filepath.Dir(filename))\n\tjnode.Load(L)\n\n\t// Extras\n\tpure.Load(L)\n\n\t// pprint\n\t// exportREPL(L)\n\n\t// Plugins\n\tac.LoadPluginFunctions(L, nil)\n\n\t// Cache\n\tac.LoadCacheFunctions(L)\n\n\t// Pages and Tags\n\tonthefly.Load(L)\n\n\t// File uploads\n\tupload.Load(L, w, req, filepath.Dir(filename))\n\n\t// HTTP Client\n\thttpclient.Load(L, ac.serverHeaderName)\n}", "func returnGoConfigFuncsSection() (string, error) {\n\tdialectString := fmt.Sprintf(\"\\n// Dialect states that we are utilizing postgres\\n\") +\n\t\tfmt.Sprintf(\"func (c PostgresConfig) Dialect() string {\\n\") +\n\t\tfmt.Sprintf(\"\treturn \\\"postgres\\\"\\n}\\n\\n\")\n\n\tconnectionString := fmt.Sprintf(\"\\n// Connection makes the db connection string\\n\") +\n\t\tfmt.Sprintf(\"func (c PostgresConfig) Connection() string {\\n\") +\n\t\tfmt.Sprintf(\"\tif c.Host == \\\"localhost\\\" {\\n\") +\n\t\tfmt.Sprintf(\"\t\tif c.Password == \\\"\\\" {\\n\") +\n\t\tfmt.Sprintf(\"\t\t\treturn fmt.Sprintf(\\\"host=%%s port=%%d user=%%s dbname=%%s sslmode=disable\\\", c.Host, c.Port, c.User, c.Dbname)\\n\") +\n\t\tfmt.Sprintf(\"\t\t}\\n\") +\n\t\tfmt.Sprintf(\"\t\treturn fmt.Sprintf(\\\"user=%%s password=%%s host=%%s dbname=%%s sslmode=disable\\\", c.User, c.Password, c.Host, c.Dbname)\\n}\\n\") +\n\t\tfmt.Sprintf(\"\treturn fmt.Sprintf(\\\"user=%%s password=%%s host=%%s dbname=%%s\\\", c.User, c.Password, c.Host, c.Dbname)\\n}\\n\\n\")\n\n\tloadConfigString := fmt.Sprintf(\"// LoadConfig initializes the db based on env variables\\n\") +\n\t\tfmt.Sprintf(\"func LoadConfig() Config {\\n\") +\n\t\tfmt.Sprintf(\"\tvar c Config\\n\") +\n\t\tfmt.Sprintf(\"\tvar (\\n\") +\n\t\tfmt.Sprintf(\"\t\thost = os.Getenv(\\\"DBHOST\\\")\\n\") +\n\t\tfmt.Sprintf(\"\t\tname = os.Getenv(\\\"DBNAME\\\")\\n\") +\n\t\tfmt.Sprintf(\"\t\tuser = os.Getenv(\\\"DBUSER\\\")\\n\") +\n\t\tfmt.Sprintf(\"\t\tpass = os.Getenv(\\\"DBPASS\\\")\\n\") +\n\t\tfmt.Sprintf(\"\t\tport = os.Getenv(\\\"PORT\\\")\\n\") +\n\t\tfmt.Sprintf(\"\t\tenv = os.Getenv(\\\"ENVIRONMENT\\\")\\n\t)\\n\\n\") +\n\t\tfmt.Sprintf(\"\tc.Database.Host = host\\n\") +\n\t\tfmt.Sprintf(\"\tc.Database.Dbname = name\\n\") +\n\t\tfmt.Sprintf(\"\tc.Database.User = user\\n\") +\n\t\tfmt.Sprintf(\"\tc.Database.Password = pass\\n\") +\n\t\tfmt.Sprintf(\"\tc.Database.Port = 5432\\n\\n\") +\n\t\tfmt.Sprintf(\"\tc.Port = port\\n\") +\n\t\tfmt.Sprintf(\"\tc.Env = env\\n\\n\") +\n\t\tfmt.Sprintf(\"\treturn c\\n}\")\n\n\treturn dialectString +\n\t\tconnectionString +\n\t\tloadConfigString, nil\n}", "func CreateCouncillorAdminPath() string {\n\treturn fmt.Sprintf(\"/admin/councillor\")\n}", "func UserConfig() string {\n\thome, _ := HomeDir()\n\n\tif home != \"\" {\n\t\tfor _, n := range []string{\".choriarc\", \".mcollective\"} {\n\t\t\thomeCfg := filepath.Join(home, n)\n\n\t\t\tif FileExist(homeCfg) {\n\t\t\t\treturn homeCfg\n\t\t\t}\n\t\t}\n\t}\n\n\tif runtime.GOOS == \"windows\" {\n\t\treturn filepath.Join(\"C:\\\\\", \"ProgramData\", \"choria\", \"etc\", \"client.conf\")\n\t}\n\n\tif FileExist(\"/etc/choria/client.conf\") {\n\t\treturn \"/etc/choria/client.conf\"\n\t}\n\n\tif FileExist(\"/usr/local/etc/choria/client.conf\") {\n\t\treturn \"/usr/local/etc/choria/client.conf\"\n\t}\n\n\treturn \"/etc/puppetlabs/mcollective/client.cfg\"\n}", "func initConfig() {\n\tif viper.GetBool(\"debug\") {\n\t\tlog.SetLevel(log.DebugLevel)\n\t\tlog.Debugf(\"Debug logging enabled!\")\n\t} else {\n\t\tlog.SetLevel(log.InfoLevel)\n\t}\n\n\tlog.Debugf(\"Cago Version: %s\", Version)\n\n\t// Enable overriding of configuration values using environment variables\n\tviper.SetEnvPrefix(\"CAGO\")\n\tviper.AutomaticEnv()\n\n\t// Check for the configuration file in the following order:\n\t// 1. Local configuration file specified using a command line argument\n\t// 2. Remote configuration file specified using the CAGO_CONFIG_URL environment variable\n\t// 3. Local configuration file cached from a previous download\n\t// 4. Local configuration file manually created by user\n\n\t// Step 1: Check to see if the configuration file path is set via command line argument\n\tconfigurationFilePath := viper.GetString(configFileFlagLong)\n\tif configurationFilePath != \"\" {\n\t\tlog.Debugf(\"Configuration file command line argument '%s' is set to: %s\", configFileFlagLong, configurationFilePath)\n\t} else {\n\t\tlog.Debugf(\"Configuration file command line argument '%s' is not set\", configFileFlagLong)\n\t}\n\n\t// Step 2 and 3: Download a remote file or used a previously cached version\n\tif configurationFilePath == \"\" {\n\t\tremoteConfigurationFileURL, ok := os.LookupEnv(\"CAGO_CONFIG_URL\")\n\t\tif ok {\n\t\t\tlog.Debugf(\"Environment variable '%s' is set to: %s\", remoteConfigFileEnvVariable, remoteConfigurationFileURL)\n\t\t\tconfigurationFilePath = getRemoteConfigurationFile(remoteConfigurationFileURL)\n\t\t} else {\n\t\t\tlog.Debugf(\"Environment variable '%s' is not set\", remoteConfigFileEnvVariable)\n\t\t}\n\t}\n\n\t// Step 4: Use a manually created local file\n\tif configurationFilePath == \"\" {\n\t\t// If the didn't load, try finding the remote configuration file\n\t\tconfigurationFilePath = getLocalConfigurationFile()\n\t}\n\n\tif configurationFilePath == \"\" {\n\t\tlog.Errorf(\"Cago could not find a configuration file to use! Here's what Cago checks:\")\n\t\tlog.Errorf(\" 1. Configuration file path specified using command line argument: %s\", configFileFlagLong)\n\t\tlog.Errorf(\" 2. Remote configuration file URL specified using environment variable: %s\", remoteConfigFileEnvVariable)\n\t\tlog.Errorf(\" 3. Previously cached remote configuration file in: %s\", cachedConfigFile)\n\t\tlog.Errorf(\" 4. Manually created configuration file here: %s\", localConfigFile)\n\n\t\tos.Exit(1)\n\t}\n\n\t// Read the configuration file\n\tviper.SetConfigFile(configurationFilePath)\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tlog.Fatalf(\"Could not process configuration file (%s), bailing out: %s\", configurationFilePath, err)\n\t\tos.Exit(1)\n\t}\n}", "func init() {\n\terr := envconfig.Process(\"RPCH\", &Cfg)\n\tif err != nil {\n\t\tlog.Fatalf(\"FATAL: %v - error importing environment variables. See: %v\\n\", utils.FileLine(), err)\n\t}\n\n\tRgxFnamePrefix = regexp.MustCompile(`^[a-f0-9]+_`)\n}", "func loadConfig(funcs []func() error) error {\n\tvar err error\n\n\tfor _, f := range funcs {\n\t\terr = f()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn err\n}", "func init() {\n\tvar fnm string\n\n\t//This is the way to initialize a struct.\n\tConf = Config{}\n\n\t//Pass the variable as a pointer.\n\treadFlags(&fnm)\n\t\n\t//Call the function defined in config.\n\tConf.SetFileName(fnm)\n}", "func setupConfigHandlers(r *mux.Router) {\n\tr.HandleFunc(\"/config\", settingshttp.Server.GetFullSystemProbeConfig(getAggregatedNamespaces()...)).Methods(\"GET\")\n\tr.HandleFunc(\"/config/list-runtime\", settingshttp.Server.ListConfigurable).Methods(\"GET\")\n\tr.HandleFunc(\"/config/{setting}\", settingshttp.Server.GetValue).Methods(\"GET\")\n\tr.HandleFunc(\"/config/{setting}\", settingshttp.Server.SetValue).Methods(\"POST\")\n}", "func validateConfig() {\n\tvalidators := []*knf.Validator{\n\t\t{MAIN_RUN_USER, knfv.Empty, nil},\n\t\t{MAIN_RUN_GROUP, knfv.Empty, nil},\n\t\t{PATHS_WORKING_DIR, knfv.Empty, nil},\n\t\t{PATHS_HELPER_DIR, knfv.Empty, nil},\n\t\t{PATHS_SYSTEMD_DIR, knfv.Empty, nil},\n\t\t{PATHS_UPSTART_DIR, knfv.Empty, nil},\n\t\t{DEFAULTS_NPROC, knfv.Empty, nil},\n\t\t{DEFAULTS_NOFILE, knfv.Empty, nil},\n\t\t{DEFAULTS_RESPAWN_COUNT, knfv.Empty, nil},\n\t\t{DEFAULTS_RESPAWN_INTERVAL, knfv.Empty, nil},\n\t\t{DEFAULTS_KILL_TIMEOUT, knfv.Empty, nil},\n\n\t\t{DEFAULTS_NPROC, knfv.Less, 0},\n\t\t{DEFAULTS_NOFILE, knfv.Less, 0},\n\t\t{DEFAULTS_RESPAWN_COUNT, knfv.Less, 0},\n\t\t{DEFAULTS_RESPAWN_INTERVAL, knfv.Less, 0},\n\t\t{DEFAULTS_KILL_TIMEOUT, knfv.Less, 0},\n\n\t\t{MAIN_RUN_USER, knfs.User, nil},\n\t\t{MAIN_RUN_GROUP, knfs.Group, nil},\n\n\t\t{PATHS_WORKING_DIR, knff.Perms, \"DRWX\"},\n\t\t{PATHS_HELPER_DIR, knff.Perms, \"DRWX\"},\n\t}\n\n\tif knf.GetB(LOG_ENABLED, true) {\n\t\tvalidators = append(validators,\n\t\t\t&knf.Validator{LOG_DIR, knfv.Empty, nil},\n\t\t\t&knf.Validator{LOG_FILE, knfv.Empty, nil},\n\t\t\t&knf.Validator{LOG_DIR, knff.Perms, \"DWX\"},\n\t\t)\n\t}\n\n\terrs := knf.Validate(validators)\n\n\tif len(errs) != 0 {\n\t\tprintError(\"Errors while configuration validation:\")\n\n\t\tfor _, err := range errs {\n\t\t\tprintError(\" - %v\", err)\n\t\t}\n\n\t\tos.Exit(1)\n\t}\n}", "func getPathConversionFunction() func(string) string {\n\tif runtime.GOOS != \"windows\" || os.Getenv(\"DOCKER_MACHINE_NAME\") == \"\" {\n\t\treturn func(path string) string { return path }\n\t}\n\n\treturn func(path string) string {\n\t\treturn fmt.Sprintf(\"/%s%s\", strings.ToUpper(path[:1]), path[2:])\n\t}\n}", "func initConfig() {\n\t// Find home directory.\n\thome, err := os.UserHomeDir()\n\tzenDir := home + \"/.zen\"\n\n\tcobra.CheckErr(err)\n\n\t// load the config data\n\tcfg = config.InitConfig(zenDir)\n\n\t// set default exec and runner\n\tcfg.AppCfg.Executor = &plugins.DefaultExecutor{}\n\tcfg.AppCfg.Runner = &plugins.DefaultRunner{}\n\n\t// load plugin from path based on config default\n\tfor _, plugin := range cfg.Plugins.Runners {\n\t\tif plugin.Name == cfg.AppCfg.RunnerID {\n\t\t\tplugins.LoadPlugin(plugin.Path)\n\t\t\tcfg.AppCfg.Runner = plugins.ZenPluginRegistry.Runner\n\t\t}\n\t}\n\n\tfor _, plugin := range cfg.Plugins.Executors {\n\t\tif plugin.Name == cfg.AppCfg.ExecutorID {\n\t\t\tplugins.LoadPlugin(plugin.Path)\n\t\t\tcfg.AppCfg.Executor = plugins.ZenPluginRegistry.Executor\n\t\t}\n\t}\n\n}", "func ConfigCRDCreator() reconciling.NamedCustomResourceDefinitionCreatorGetter {\n\treturn func() (string, reconciling.CustomResourceDefinitionCreator) {\n\t\treturn resources.GatekeeperConfigCRDName, func(crd *apiextensionsv1beta1.CustomResourceDefinition) (*apiextensionsv1beta1.CustomResourceDefinition, error) {\n\t\t\tcrd.Annotations = map[string]string{\"controller-gen.kubebuilder.io/version\": \"v0.2.4\"}\n\t\t\tcrd.Labels = map[string]string{\"gatekeeper.sh/system\": \"yes\"}\n\t\t\tcrd.Spec.Group = configAPIGroup\n\t\t\tcrd.Spec.Versions = []apiextensionsv1beta1.CustomResourceDefinitionVersion{\n\t\t\t\t{Name: configAPIVersion, Served: true, Storage: true},\n\t\t\t}\n\t\t\tcrd.Spec.Scope = apiextensionsv1beta1.NamespaceScoped\n\t\t\tcrd.Spec.Names.Kind = \"Config\"\n\t\t\tcrd.Spec.Names.ListKind = \"ConfigList\"\n\t\t\tcrd.Spec.Names.Plural = \"configs\"\n\t\t\tcrd.Spec.Names.Singular = \"config\"\n\n\t\t\treturn crd, nil\n\t\t}\n\t}\n}", "func SetupFunc(config *modulebase.ModuleConfig) (*modulebase.ModuleSetupInfo, error) {\n m[\"red\"]=0xe74c3c\n m[\"orange\"]=0xe67e22\n m[\"yellow\"]=0xf1c40f\n m[\"green\"]=0x2ecc71\n m[\"blue\"]=0x3498db\n m[\"purple\"]=0x9b59b6\n events := []interface{}{\n\t\troleChangeUpdateCallback,\n\t}\n\treturn &modulebase.ModuleSetupInfo{\n Events: &events,\n\t\tCommands: &commandTree,\n Help: helpString,\n DBStart: handleDbStart,\n\t}, nil\n}", "func mkAbsolutePaths(config *ConfigurationOptions) {\n\tconfig.NodeAgentWorkloadHomeDir = filepath.Join(config.NodeAgentManagementHomeDir, config.NodeAgentWorkloadHomeDir)\n\tconfig.NodeAgentCredentialsHomeDir = filepath.Join(config.NodeAgentManagementHomeDir, config.NodeAgentCredentialsHomeDir)\n\tconfig.NodeAgentManagementAPI = filepath.Join(config.NodeAgentManagementHomeDir, config.NodeAgentManagementAPI)\n}", "func (k *kubelet) configFile() (string, error) {\n\tconfig := &kubeletconfig.KubeletConfiguration{\n\t\tTypeMeta: v1.TypeMeta{\n\t\t\tKind: \"KubeletConfiguration\",\n\t\t\tAPIVersion: kubeletconfig.SchemeGroupVersion.String(),\n\t\t},\n\t\t// Enables TLS certificate rotation, which is good from security point of view.\n\t\tRotateCertificates: true,\n\t\t// Request HTTPS server certs from API as well, so kubelet does not generate self-signed certificates.\n\t\tServerTLSBootstrap: true,\n\t\t// If Docker is configured to use systemd as a cgroup driver and Docker is used as container\n\t\t// runtime, this needs to be set to match Docker.\n\t\t// TODO pull that information dynamically based on what container runtime is configured.\n\t\tCgroupDriver: k.config.CgroupDriver,\n\t\t// Address where kubelet should listen on.\n\t\tAddress: k.config.Address,\n\t\t// Disable healht port for now, since we don't use it.\n\t\t// TODO check how to use it and re-enable it.\n\t\tHealthzPort: &[]int32{0}[0],\n\t\t// Set up cluster domain. Without this, there is no 'search' field in /etc/resolv.conf in containers, so\n\t\t// short-names resolution like mysvc.myns.svc does not work.\n\t\tClusterDomain: \"cluster.local\",\n\t\t// Authenticate clients using CA file.\n\t\tAuthentication: kubeletconfig.KubeletAuthentication{\n\t\t\tX509: kubeletconfig.KubeletX509Authentication{\n\t\t\t\tClientCAFile: \"/etc/kubernetes/pki/ca.crt\",\n\t\t\t},\n\t\t},\n\n\t\t// This defines where should pods cgroups be created, like /kubepods and /kubepods/burstable.\n\t\t// Also when specified, it suppresses a lot message about it.\n\t\tCgroupRoot: \"/\",\n\n\t\t// Used for calculating node allocatable resources.\n\t\t// If EnforceNodeAllocatable has 'system-reserved' set, those limits will be enforced on cgroup specified\n\t\t// with SystemReservedCgroup.\n\t\tSystemReserved: k.config.SystemReserved,\n\n\t\t// Used for calculating node allocatable resources.\n\t\t// If EnforceNodeAllocatable has 'kube-reserved' set, those limits will be enforced on cgroup specified\n\t\t// with KubeReservedCgroup.\n\t\tKubeReserved: k.config.KubeReserved,\n\n\t\tClusterDNS: k.config.ClusterDNSIPs,\n\n\t\tHairpinMode: k.config.HairpinMode,\n\t}\n\n\tkubelet, err := yaml.Marshal(config)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"serializing to YAML: %w\", err)\n\t}\n\n\treturn string(kubelet), nil\n}", "func init() {\n\tinitCfgDir()\n\tinitCreds()\n}", "func Config(r *mux.Router) *mux.Router {\n\troutes := accountRoutes\n\troutes = append(routes, loginRoute, transferRoutes[1], transferRoutes[0])\n\tfor _, route := range routes {\n\n\t\tif route.AuthRequired {\n\t\t\tr.HandleFunc(route.Url, middlewares.Logger(middlewares.Auth(route.Function))).Methods(route.Method)\n\t\t} else {\n\t\t\tr.HandleFunc(route.Url, route.Function).Methods(route.Method)\n\t\t}\n\t}\n\tfmt.Println(\"rotas configuradas\")\n\treturn r\n}", "func initConfig() {\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(-1)\n\t}\n\tsep := fmt.Sprintf(\"%c\", os.PathSeparator)\n\tif !strings.HasSuffix(wd, sep) {\n\t\twd += sep\n\t}\n\n\tconfFile = wd + \"gbb.json\"\n}", "func configconfigViewFunc(cmd *cobra.Command, args []string) {\n\tlog.Debugf(\"Reading configuration file %q\", configFile)\n\tcontents, err := options.ViewConfig()\n\tif err != nil {\n\t\tlog.Fatalf(\"Error reading configuration file: %s\", err)\n\t}\n\tfmt.Println(string(contents))\n}", "func (s *Rest) configCtrl(w http.ResponseWriter, r *http.Request) {\n\ttype config struct {\n\t\tVersion string `json:\"version\"`\n\t\tEditDuration int `json:\"edit_duration\"`\n\t\tMaxCommentSize int `json:\"max_comment_size\"`\n\t\tAdmins []string `json:\"admins\"`\n\t\tAuth []string `json:\"auth_providers\"`\n\t\tLowScore int `json:\"low_score\"`\n\t\tCriticalScore int `json:\"critical_score\"`\n\t\tReadOnlyAge int `json:\"readonly_age\"`\n\t}\n\n\tcnf := config{\n\t\tVersion: s.Version,\n\t\tEditDuration: int(s.DataService.EditDuration.Seconds()),\n\t\tMaxCommentSize: s.DataService.MaxCommentSize,\n\t\tAdmins: s.Authenticator.Admins,\n\t\tLowScore: s.ScoreThresholds.Low,\n\t\tCriticalScore: s.ScoreThresholds.Critical,\n\t\tReadOnlyAge: s.ReadOnlyAge,\n\t}\n\n\tcnf.Auth = []string{}\n\tfor _, ap := range s.Authenticator.Providers {\n\t\tcnf.Auth = append(cnf.Auth, ap.Name)\n\t}\n\n\tif cnf.Admins == nil { // prevent json serialization to nil\n\t\tcnf.Admins = []string{}\n\t}\n\trender.Status(r, http.StatusOK)\n\trender.JSON(w, r, cnf)\n}", "func init() {\n\tinitconf(configLocation)\n}", "func ConfPathProc(confPath string, confRoot string) string {\n\tif !strings.HasPrefix(confPath, \"/\") {\n\t // relative path to confRoot\n\t confPath = path.Join(confRoot, confPath)\n\t} \n\t\n\treturn confPath\n}", "func cobraConfig() {\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tif _, ok := err.(viper.ConfigFileNotFoundError); ok {\n\t\t\tlog.Debug().Err(err).Msg(\"unable to read config file\")\n\t\t} else {\n\t\t\tlog.Warn().Err(err).Msg(\"unable to read config file\")\n\t\t}\n\t}\n}", "func OperateOnCIOperatorConfig(path string, callback ConfigIterFunc) error {\n\tinfo, err := InfoFromPath(path)\n\tif err != nil {\n\t\tlogrus.WithField(\"source-file\", path).WithError(err).Error(\"Failed to resolve info from CI Operator configuration path\")\n\t\treturn err\n\t}\n\tjobConfig, err := readCiOperatorConfig(path, *info)\n\tif err != nil {\n\t\tlogrus.WithField(\"source-file\", path).WithError(err).Error(\"Failed to load CI Operator configuration\")\n\t\treturn err\n\t}\n\tif err = callback(jobConfig, info); err != nil {\n\t\tlogrus.WithField(\"source-file\", path).WithError(err).Error(\"Failed to execute callback\")\n\t\treturn err\n\t}\n\treturn nil\n}", "func ConfigPath(ctx *types.SystemContext) string {\n\tconfPath := systemRegistriesConfPath\n\tif ctx != nil {\n\t\tif ctx.SystemRegistriesConfPath != \"\" {\n\t\t\tconfPath = ctx.SystemRegistriesConfPath\n\t\t} else if ctx.RootForImplicitAbsolutePaths != \"\" {\n\t\t\tconfPath = filepath.Join(ctx.RootForImplicitAbsolutePaths, systemRegistriesConfPath)\n\t\t}\n\t}\n\treturn confPath\n}", "func setupContainerdConfig(ctx context.Context, cfg *config.Node) error {\n\t// TODO: Create windows config setup.\n\treturn nil\n}", "func initConfig() {\n\n\t_, hasToken := os.LookupEnv(\"PRIVATE_ACCESS_TOKEN\")\n\t_, hasURL := os.LookupEnv(\"CI_PROJECT_URL\")\n\tif !hasToken || !hasURL {\n\t\tlog.Fatal(\"You need to set 'CI_PROJECT_URL' and 'PRIVATE_ACCESS_TOKEN'\")\n\t}\n\n\tviper.Set(\"Token\", os.Getenv(\"PRIVATE_ACCESS_TOKEN\"))\n\tviper.Set(\"ProjectUrl\", os.Getenv(\"CI_PROJECT_URL\"))\n\n\tu, err := url.Parse(viper.GetString(\"ProjectUrl\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tviper.Set(\"BaseUrl\", fmt.Sprintf(\"%s://%s\", u.Scheme, u.Host))\n\tviper.Set(\"RegistryUrl\", fmt.Sprintf(\"%s/container_registry.json\", viper.GetString(\"ProjectUrl\")))\n\n}", "func (a *API) config(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"GET\":\n\t\tif cfg, err := a.GetHorizonAgbotConfig(); err != nil {\n\t\t\t// ConfigFile does not exist\n\t\t\tglog.Error(APIlogString(fmt.Sprintf(\"error with File System Config File, error: %v\", err)))\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t} else {\n\t\t\twriteResponse(w, cfg, http.StatusOK)\n\t\t}\n\tcase \"OPTIONS\":\n\t\tw.Header().Set(\"Allow\", \"GET, OPTIONS\")\n\t\tw.WriteHeader(http.StatusOK)\n\tdefault:\n\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t}\n}", "func initConfig() {\n\tif verbose {\n\t\tutils.EnableVerboseMode()\n\t\tt := time.Now()\n\t\tutils.Logf(\"Executed ImportExportCLI (%s) on %v\\n\", utils.MICmd, t.Format(time.RFC1123))\n\t}\n\n\tutils.Logln(utils.LogPrefixInfo+\"Insecure:\", insecure)\n\tif insecure {\n\t\tutils.Insecure = true\n\t}\n}", "func (config *Config) evaluateConcertoConfigFile(c *cli.Context) error {\n\tlog.Debug(\"evaluateConcertoConfigFile\")\n\tcurrUser, err := config.evaluateCurrentUser()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif configFile := c.String(\"concerto-config\"); configFile != \"\" {\n\n\t\tlog.Debug(\"Concerto configuration file location taken from env/args\")\n\t\tconfig.ConfFile = configFile\n\n\t} else {\n\n\t\tif runtime.GOOS == \"windows\" {\n\t\t\tif config.CurrentUserIsAdmin && (config.BrownfieldToken != \"\" || (config.CommandPollingToken != \"\" && config.ServerID != \"\") || FileExists(windowsServerConfigFile)) {\n\t\t\t\tlog.Debugf(\"Current user is administrator, setting config file as %s\", windowsServerConfigFile)\n\t\t\t\tconfig.ConfFile = windowsServerConfigFile\n\t\t\t} else {\n\t\t\t\t// User mode Windows\n\t\t\t\tlog.Debugf(\"Current user is regular user: %s\", currUser.Username)\n\t\t\t\tconfig.ConfFile = filepath.Join(currUser.HomeDir, \".concerto/client.xml\")\n\t\t\t}\n\t\t} else {\n\t\t\t// Server mode *nix\n\t\t\tif config.CurrentUserIsAdmin && (config.BrownfieldToken != \"\" || (config.CommandPollingToken != \"\" && config.ServerID != \"\") || FileExists(nixServerConfigFile)) {\n\t\t\t\tconfig.ConfFile = nixServerConfigFile\n\t\t\t} else {\n\t\t\t\t// User mode *nix\n\t\t\t\tconfig.ConfFile = filepath.Join(currUser.HomeDir, \".concerto/client.xml\")\n\t\t\t}\n\t\t}\n\t}\n\tconfig.ConfLocation = path.Dir(config.ConfFile)\n\treturn nil\n}", "func initConfig() {\n\tif RootConfig.clusterID == \"\" {\n\t\tlog.Fatal(\"A cluster id must be provided.\")\n\t}\n\tif RootConfig.internal {\n\t\tRootConfig.config = insideCluster()\n\t} else {\n\t\tRootConfig.config = outsideCluster()\n\t}\n}", "func (c *Config) initVariables(i *ini.File) {\n\tc.DefaultPort = getIntValue(i, \"Network\", \"port\", 8000)\n\tc.NetworkMode = getStringValue(i, \"Network\", \"mode\", \"port_opened\") //port_opened,upnp,relay\n\tc.MaxConnection = getIntValue(i, \"Network\", \"max_connection\", 100)\n\tc.Docroot = getPathValue(i, \"Path\", \"docroot\", \"./www\") //path from cwd\n\tc.RunDir = getRelativePathValue(i, \"Path\", \"run_dir\", \"../run\", c.Docroot) //path from docroot\n\tc.FileDir = getRelativePathValue(i, \"Path\", \"file_dir\", \"../file\", c.Docroot) //path from docroot\n\tc.CacheDir = getRelativePathValue(i, \"Path\", \"cache_dir\", \"../cache\", c.Docroot) //path from docroot\n\tc.TemplateDir = getRelativePathValue(i, \"Path\", \"template_dir\", \"../gou_template\", c.Docroot) //path from docroot\n\tc.SpamList = getRelativePathValue(i, \"Path\", \"spam_list\", \"../file/spam.txt\", c.Docroot)\n\tc.InitnodeList = getRelativePathValue(i, \"Path\", \"initnode_list\", \"../file/initnode.txt\", c.Docroot)\n\tc.FollowList = getRelativePathValue(i, \"Path\", \"follow_list\", \"../file/follow_list.txt\", c.Docroot)\n\tc.NodeAllowFile = getRelativePathValue(i, \"Path\", \"node_allow\", \"../file/node_allow.txt\", c.Docroot)\n\tc.NodeDenyFile = getRelativePathValue(i, \"Path\", \"node_deny\", \"../file/node_deny.txt\", c.Docroot)\n\tc.ReAdminStr = getStringValue(i, \"Gateway\", \"admin\", \"^(127|\\\\[::1\\\\])\")\n\tc.ReFriendStr = getStringValue(i, \"Gateway\", \"friend\", \"^(127|\\\\[::1\\\\])\")\n\tc.ReVisitorStr = getStringValue(i, \"Gateway\", \"visitor\", \".\")\n\tc.ServerName = getStringValue(i, \"Gateway\", \"server_name\", \"\")\n\tc.TagSize = getIntValue(i, \"Gateway\", \"tag_size\", 20)\n\tc.RSSRange = getInt64Value(i, \"Gateway\", \"rss_range\", 3*24*60*60)\n\tc.TopRecentRange = getInt64Value(i, \"Gateway\", \"top_recent_range\", 3*24*60*60)\n\tc.RecentRange = getInt64Value(i, \"Gateway\", \"recent_range\", 31*24*60*60)\n\tc.RecordLimit = getIntValue(i, \"Gateway\", \"record_limit\", 2048)\n\tc.Enable2ch = getBoolValue(i, \"Gateway\", \"enable_2ch\", false)\n\tc.EnableProf = getBoolValue(i, \"Gateway\", \"enable_prof\", false)\n\tc.HeavyMoon = getBoolValue(i, \"Gateway\", \"moonlight\", false)\n\tc.EnableEmbed = getBoolValue(i, \"Gateway\", \"enable_embed\", true)\n\tc.RelayNumber = getIntValue(i, \"Gateway\", \"relay_number\", 5)\n\tc.LogDir = getPathValue(i, \"Path\", \"log_dir\", \"./log\") //path from cwd\n\tc.ThreadPageSize = getIntValue(i, \"Application Thread\", \"page_size\", 50)\n\tc.DefaultThumbnailSize = getStringValue(i, \"Application Thread\", \"thumbnail_size\", \"\")\n\tc.ForceThumbnail = getBoolValue(i, \"Application Thread\", \"force_thumbnail\", false)\n\tctype := \"Application Thread\"\n\tc.SaveRecord = getInt64Value(i, ctype, \"save_record\", 0)\n\tc.SaveSize = getIntValue(i, ctype, \"save_size\", 1)\n\tc.GetRange = getInt64Value(i, ctype, \"get_range\", 31*24*60*60)\n\tif c.GetRange > time.Now().Unix() {\n\t\tlog.Fatal(\"get_range is too big\")\n\t}\n\tc.SyncRange = getInt64Value(i, ctype, \"sync_range\", 10*24*60*60)\n\tif c.SyncRange > time.Now().Unix() {\n\t\tlog.Fatal(\"sync_range is too big\")\n\t}\n\tc.SaveRemoved = getInt64Value(i, ctype, \"save_removed\", 50*24*60*60)\n\tif c.SaveRemoved > time.Now().Unix() {\n\t\tlog.Fatal(\"save_removed is too big\")\n\t}\n\n\tif c.SyncRange == 0 {\n\t\tc.SaveRecord = 0\n\t}\n\n\tif c.SaveRemoved != 0 && c.SaveRemoved <= c.SyncRange {\n\t\tc.SyncRange = c.SyncRange + 1\n\t}\n\n}", "func loadConfig() error {\n\tconfigMap = make(map[string]interface{})\n\tfmt.Println(\"Reading \", os.Args[1])\n\tdat, err := ioutil.ReadFile(os.Args[1])\n\tcheckError(err)\n\n\tif err := json.Unmarshal(dat, &configMap); err != nil {\n\t\tlog.Fatal(\"Error in loading config \", err)\n\t}\n\tprotocol = configMap[\"protocol\"].(string)\n\tipAdd = configMap[\"ipAddress\"].(string)\n\tport = configMap[\"port\"].(string)\n\taddr := []string{ipAdd, port}\n\tselfaddr = strings.Join(addr, \"\")\n\tif selfaddr == \"\" {\n\t\tfmt.Println(\"Could not initialize selfaddr\")\n\t}\n\tchordid = getChordId(port, ipAdd)\n\tpersiStorage :=\n\t\tconfigMap[\"persistentStorageContainer\"].(map[string]interface{})\n\tdict3File = persiStorage[\"file\"].(string)\n\tmethods = configMap[\"methods\"].([]interface{})\n\tstabilizeInterval = configMap[\"stabilizeInterval\"].(float64)\n\tcheckPredInterval = configMap[\"checkPredInterval\"].(float64)\n\tfixfingersInterval = configMap[\"fixfingersInterval\"].(float64)\n\tentrypt = configMap[\"entrypoint\"].(string)\n\tfmt.Println(\"Methods exposed by server: \", methods)\n\treturn nil\n}", "func initConfig() {\n\tappid, _ = utils.Cfg.GetString(\"wechat\", \"appid\")\n\tsecret, _ = utils.Cfg.GetString(\"wechat\", \"secret\")\n\tbaseUrl, _ := utils.Cfg.GetString(\"beego\", \"base_url\")\n\tredirectUrl = url.QueryEscape(baseUrl + \"/wechat\")\n\twechatAPIHost = \"https://api.weixin.qq.com\"\n}", "func (ac *Config) LoadLuaFunctionsForREPL(L *lua.LState, o *term.TextOutput) {\n\n\t// Server configuration functions\n\tac.LoadServerConfigFunctions(L, \"\")\n\n\t// Other basic system functions, like log()\n\tac.LoadBasicSystemFunctions(L)\n\n\t// If there is a database backend\n\tif ac.perm != nil {\n\n\t\t// Retrieve the creator struct\n\t\tcreator := ac.perm.UserState().Creator()\n\n\t\t// Simpleredis data structures\n\t\tdatastruct.LoadList(L, creator)\n\t\tdatastruct.LoadSet(L, creator)\n\t\tdatastruct.LoadHash(L, creator)\n\t\tdatastruct.LoadKeyValue(L, creator)\n\n\t\t// For saving and loading Lua functions\n\t\tcodelib.Load(L, creator)\n\t}\n\n\t// For handling JSON data\n\tjnode.LoadJSONFunctions(L)\n\tac.LoadJFile(L, ac.serverDirOrFilename)\n\tjnode.Load(L)\n\n\t// Extras\n\tpure.Load(L)\n\n\t// Export pprint and scriptdir\n\texportREPLSpecific(L)\n\n\t// Plugin functionality\n\tac.LoadPluginFunctions(L, o)\n\n\t// Cache\n\tac.LoadCacheFunctions(L)\n}", "func (t *Trinity) initViewSetCfg() {\n\tv := &ViewSetCfg{\n\t\tDb: t.db,\n\t\tHasAuthCtl: false,\n\t\tAtomicRequestMap: map[string]bool{\n\t\t\t\"RETRIEVE\": t.setting.GetAtomicRequest(),\n\t\t\t\"GET\": t.setting.GetAtomicRequest(),\n\t\t\t\"POST\": t.setting.GetAtomicRequest(),\n\t\t\t\"PATCH\": t.setting.GetAtomicRequest(),\n\t\t\t\"PUT\": t.setting.GetAtomicRequest(),\n\t\t\t\"DELETE\": t.setting.GetAtomicRequest(),\n\t\t},\n\t\tAuthenticationBackendMap: map[string]func(c *gin.Context) error{\n\t\t\t\"RETRIEVE\": JwtUnverifiedAuthBackend,\n\t\t\t\"GET\": JwtUnverifiedAuthBackend,\n\t\t\t\"POST\": JwtUnverifiedAuthBackend,\n\t\t\t\"PATCH\": JwtUnverifiedAuthBackend,\n\t\t\t\"PUT\": JwtUnverifiedAuthBackend,\n\t\t\t\"DELETE\": JwtUnverifiedAuthBackend,\n\t\t},\n\t\tGetCurrentUserAuth: func(c *gin.Context, db *gorm.DB) error {\n\t\t\tc.Set(\"UserID\", \"\") // with c.GetInt64(\"UserID\")\n\t\t\tc.Set(\"UserPermission\", []string{}) // with c.GetStringSlice(\"UserID\")\n\t\t\treturn nil\n\t\t},\n\t\tAccessBackendRequireMap: map[string][]string{},\n\t\tAccessBackendCheckMap: map[string]func(v *ViewSetRunTime) error{\n\t\t\t\"RETRIEVE\": DefaultAccessBackend,\n\t\t\t\"GET\": DefaultAccessBackend,\n\t\t\t\"POST\": DefaultAccessBackend,\n\t\t\t\"PATCH\": DefaultAccessBackend,\n\t\t\t\"PUT\": DefaultAccessBackend,\n\t\t\t\"DELETE\": DefaultAccessBackend,\n\t\t},\n\t\tPreloadListMap: map[string]map[string]func(db *gorm.DB) *gorm.DB{\n\t\t\t\"RETRIEVE\": nil, // Foreign key :Foreign table if you want to filter the foreign table\n\t\t\t\"GET\": nil,\n\t\t},\n\t\tFilterBackendMap: map[string]func(c *gin.Context, db *gorm.DB) *gorm.DB{\n\t\t\t\"RETRIEVE\": DefaultFilterBackend,\n\t\t\t\"GET\": DefaultFilterBackend,\n\t\t\t\"POST\": DefaultFilterBackend,\n\t\t\t\"PATCH\": DefaultFilterBackend,\n\t\t\t\"PUT\": DefaultFilterBackend,\n\t\t\t\"DELETE\": DefaultFilterBackend,\n\t\t},\n\t\tFilterByList: []string{},\n\t\tFilterCustomizeFunc: map[string]func(db *gorm.DB, queryValue string) *gorm.DB{},\n\t\tSearchingByList: []string{},\n\t\tOrderingByList: map[string]bool{},\n\t\tPageSize: t.setting.GetPageSize(),\n\t\tEnableOrderBy: true,\n\t\tEnableChangeLog: false,\n\t\tEnableDataVersion: true,\n\t\tEnableVersionControl: false,\n\t\tRetrieve: DefaultRetrieveCallback,\n\t\tGet: DefaultGetCallback,\n\t\tPost: DefaultPostCallback,\n\t\tPut: DefaultPutCallback,\n\t\tPatch: DefaultPatchCallback,\n\t\tDelete: DefaultDeleteCallback,\n\t}\n\tt.vCfg = v\n\n}", "func initConfig() {\n\tif debug {\n\t\tlogrus.SetLevel(logrus.DebugLevel)\n\t}\n\tif cfgFile != \"\" {\n\t\t// Use config file from the flag.\n\t\tviper.SetConfigFile(cfgFile)\n\t} else {\n\t\t// Find home directory.\n\t\thome, err := homedir.Dir()\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\t// Search config in home directory with name \".izlyctl\" (without extension).\n\t\tviper.AddConfigPath(home)\n\t\tviper.SetConfigName(\".izlyctl\")\n\t}\n\n\tviper.AutomaticEnv() // read in environment variables that match\n\n\t// If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tlogrus.Debugf(\"Using config file: %s\", viper.ConfigFileUsed())\n\t}\n\tviper.BindPFlag(\"api.auth.login\", rootCmd.PersistentFlags().Lookup(\"user\"))\n\tviper.BindPFlag(\"api.auth.password\", rootCmd.PersistentFlags().Lookup(\"password\"))\n\tviper.BindPFlag(\"api.url\", rootCmd.PersistentFlags().Lookup(\"server\"))\n\tviper.BindPFlag(\"user.rate\", rootCmd.PersistentFlags().Lookup(\"rate\"))\n\tviper.BindPFlag(\"user.dueDate\", rootCmd.PersistentFlags().Lookup(\"dueDate\"))\n}", "func init() {\n\tcurrentDir, _ = pathhelper.GetCurrentExecDir()\n\tconfigFile = path.Join(currentDir, \"config.json\")\n}", "func GetConfig(myCfg string, tolerant, allowSourcing, expand, recursive bool, expandMap map[string]string) map[string]string {\n\tif len(expandMap) > 0 {\n\t\texpand = true\n\t} else {\n\t\texpandMap = map[string]string{}\n\t}\n\tmyKeys := map[string]string{}\n\n\tif recursive {\n\t\tif !expand {\n\t\t\texpandMap = map[string]string{}\n\t\t}\n\t\tfname := \"\"\n\t\tfor _, fname = range grab.RecursiveFileList(myCfg) {\n\t\t\tnewKeys := GetConfig(fname, tolerant, allowSourcing, true, false, expandMap)\n\t\t\tfor k, v := range newKeys {\n\t\t\t\tmyKeys[k] = v\n\t\t\t}\n\t\t}\n\t\tif fname == \"\" {\n\t\t\treturn nil\n\t\t}\n\t\treturn myKeys\n\t}\n\n\tf, err := os.Open(myCfg)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tf.Close()\n\tc, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tcontent := string(c)\n\n\tif content != \"\" && !strings.HasSuffix(content, \"\\n\") {\n\t\tcontent += \"\\n\"\n\t}\n\tif strings.Contains(content, \"\\r\") {\n\t\tmsg.WriteMsg(fmt.Sprintf(\"!!! Please use dos2unix to convert line endings in config file: '%s'\\n\", myCfg), -1, nil)\n\t}\n\tlex := NewGetConfigShlex(strings.NewReader(content), myCfg, true, \"\", tolerant)\n\tlex.Wordchars = \"abcdfeghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789~!@#$%*_\\\\:;?,./-+{}\"\n\tlex.Quotes = \"\\\"'\"\n\tif allowSourcing {\n\t\tlex.allowSourcing(expandMap)\n\t}\n\tfor {\n\t\tkey, _ := lex.GetToken()\n\t\tif key == \"export\" {\n\t\t\tkey, _ = lex.GetToken()\n\t\t}\n\t\tif key == \"\" {\n\t\t\tbreak\n\t\t}\n\t\tequ, _ := lex.GetToken()\n\t\tif equ == \"\" {\n\t\t\tmsg1 := \"Unexpected EOF\" //TODO error_leader\n\t\t\tif !tolerant {\n\t\t\t\t//raise ParseError(msg)\n\t\t\t} else {\n\t\t\t\tmsg.WriteMsg(fmt.Sprintf(\"%s\\n\", msg1), -1, nil)\n\t\t\t\treturn myKeys\n\t\t\t}\n\t\t} else if equ != \"=\" {\n\t\t\tmsg1 := fmt.Sprintf(\"Invalid token '%s' (not '=')\", equ) //TODO error_leader\n\t\t\tif !tolerant {\n\t\t\t\t//raise ParseError(msg)\n\t\t\t} else {\n\t\t\t\tmsg.WriteMsg(fmt.Sprintf(\"%s\\n\", msg1), -1, nil)\n\t\t\t\treturn myKeys\n\t\t\t}\n\t\t}\n\t\tval, _ := lex.GetToken() /* TODO: fix it\n\t\tif val == \"\" {\n\t\t\tmsg := fmt.Sprintf(\"Unexpected end of config file: variable '%s'\", key) //TODO error_leader\n\t\t\tif !tolerant {\n\t\t\t\t//raise ParseError(msg)\n\t\t\t} else {\n\t\t\t\tmsg.WriteMsg(fmt.Sprintf(\"%s\\n\", msg), -1, nil)\n\t\t\t\treturn myKeys\n\t\t\t}\n\t\t}*/\n\t\tif invalidVarNameRe.MatchString(key) {\n\t\t\tmsg1 := fmt.Sprintf(\"Invalid variable name '%s'\", key) //TODO error_leader\n\t\t\tif !tolerant {\n\t\t\t\t//raise ParseError(msg)\n\t\t\t} else {\n\t\t\t\tmsg.WriteMsg(fmt.Sprintf(\"%s\\n\", msg1), -1, nil)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif expand {\n\t\t\tmyKeys[key] = VarExpand(val, expandMap, nil) //TODO lex.error_leader\n\t\t\texpandMap[key] = myKeys[key]\n\t\t} else {\n\t\t\tmyKeys[key] = val\n\t\t}\n\t}\n\treturn myKeys\n}", "func configCheck() {\n\t// TODO\n}", "func Config(fn URLGenerator) {\n\tm.Lock()\n\turlFn = fn\n\tm.Unlock()\n}", "func expFunctions(baseDir string) map[string]function.Function {\n\treturn map[string]function.Function{\n\t\t\"abs\": stdlib.AbsoluteFunc,\n\t\t\"abspath\": funcs.AbsPathFunc,\n\t\t\"basename\": funcs.BasenameFunc,\n\t\t\"base64decode\": funcs.Base64DecodeFunc,\n\t\t\"base64encode\": funcs.Base64EncodeFunc,\n\t\t\"base64gzip\": funcs.Base64GzipFunc,\n\t\t\"base64sha256\": funcs.Base64Sha256Func,\n\t\t\"base64sha512\": funcs.Base64Sha512Func,\n\t\t\"bcrypt\": funcs.BcryptFunc,\n\t\t\"can\": tryfunc.CanFunc,\n\t\t\"ceil\": stdlib.CeilFunc,\n\t\t\"chomp\": stdlib.ChompFunc,\n\t\t\"cidrhost\": funcs.CidrHostFunc,\n\t\t\"cidrnetmask\": funcs.CidrNetmaskFunc,\n\t\t\"cidrsubnet\": funcs.CidrSubnetFunc,\n\t\t\"cidrsubnets\": funcs.CidrSubnetsFunc,\n\t\t\"coalesce\": funcs.CoalesceFunc,\n\t\t\"coalescelist\": stdlib.CoalesceListFunc,\n\t\t\"compact\": stdlib.CompactFunc,\n\t\t\"concat\": stdlib.ConcatFunc,\n\t\t\"contains\": stdlib.ContainsFunc,\n\t\t\"csvdecode\": stdlib.CSVDecodeFunc,\n\t\t\"dirname\": funcs.DirnameFunc,\n\t\t\"distinct\": stdlib.DistinctFunc,\n\t\t\"element\": stdlib.ElementFunc,\n\t\t\"chunklist\": stdlib.ChunklistFunc,\n\t\t\"file\": funcs.MakeFileFunc(baseDir, false),\n\t\t\"fileexists\": funcs.MakeFileExistsFunc(baseDir),\n\t\t\"fileset\": funcs.MakeFileSetFunc(baseDir),\n\t\t\"filebase64\": funcs.MakeFileFunc(baseDir, true),\n\t\t\"filebase64sha256\": funcs.MakeFileBase64Sha256Func(baseDir),\n\t\t\"filebase64sha512\": funcs.MakeFileBase64Sha512Func(baseDir),\n\t\t\"filemd5\": funcs.MakeFileMd5Func(baseDir),\n\t\t\"filesha1\": funcs.MakeFileSha1Func(baseDir),\n\t\t\"filesha256\": funcs.MakeFileSha256Func(baseDir),\n\t\t\"filesha512\": funcs.MakeFileSha512Func(baseDir),\n\t\t\"flatten\": stdlib.FlattenFunc,\n\t\t\"floor\": stdlib.FloorFunc,\n\t\t\"format\": stdlib.FormatFunc,\n\t\t\"formatdate\": stdlib.FormatDateFunc,\n\t\t\"formatlist\": stdlib.FormatListFunc,\n\t\t\"indent\": stdlib.IndentFunc,\n\t\t\"index\": funcs.IndexFunc, // stdlib.IndexFunc is not compatible\n\t\t\"join\": stdlib.JoinFunc,\n\t\t\"jsondecode\": stdlib.JSONDecodeFunc,\n\t\t\"jsonencode\": stdlib.JSONEncodeFunc,\n\t\t\"keys\": stdlib.KeysFunc,\n\t\t\"length\": funcs.LengthFunc,\n\t\t\"list\": funcs.ListFunc,\n\t\t\"log\": stdlib.LogFunc,\n\t\t\"lookup\": funcs.LookupFunc,\n\t\t\"lower\": stdlib.LowerFunc,\n\t\t\"map\": funcs.MapFunc,\n\t\t\"matchkeys\": funcs.MatchkeysFunc,\n\t\t\"max\": stdlib.MaxFunc,\n\t\t\"md5\": funcs.Md5Func,\n\t\t\"merge\": stdlib.MergeFunc,\n\t\t\"min\": stdlib.MinFunc,\n\t\t\"parseint\": stdlib.ParseIntFunc,\n\t\t\"pathexpand\": funcs.PathExpandFunc,\n\t\t\"pow\": stdlib.PowFunc,\n\t\t\"range\": stdlib.RangeFunc,\n\t\t\"regex\": stdlib.RegexFunc,\n\t\t\"regexall\": stdlib.RegexAllFunc,\n\t\t\"replace\": funcs.ReplaceFunc,\n\t\t\"reverse\": stdlib.ReverseListFunc,\n\t\t\"rsadecrypt\": funcs.RsaDecryptFunc,\n\t\t\"setintersection\": stdlib.SetIntersectionFunc,\n\t\t\"setproduct\": stdlib.SetProductFunc,\n\t\t\"setsubtract\": stdlib.SetSubtractFunc,\n\t\t\"setunion\": stdlib.SetUnionFunc,\n\t\t\"sha1\": funcs.Sha1Func,\n\t\t\"sha256\": funcs.Sha256Func,\n\t\t\"sha512\": funcs.Sha512Func,\n\t\t\"signum\": stdlib.SignumFunc,\n\t\t\"slice\": stdlib.SliceFunc,\n\t\t\"sort\": stdlib.SortFunc,\n\t\t\"split\": stdlib.SplitFunc,\n\t\t\"strrev\": stdlib.ReverseFunc,\n\t\t\"substr\": stdlib.SubstrFunc,\n\t\t\"timestamp\": funcs.TimestampFunc,\n\t\t\"timeadd\": stdlib.TimeAddFunc,\n\t\t\"title\": stdlib.TitleFunc,\n\t\t\"tostring\": funcs.MakeToFunc(cty.String),\n\t\t\"tonumber\": funcs.MakeToFunc(cty.Number),\n\t\t\"tobool\": funcs.MakeToFunc(cty.Bool),\n\t\t\"toset\": funcs.MakeToFunc(cty.Set(cty.DynamicPseudoType)),\n\t\t\"tolist\": funcs.MakeToFunc(cty.List(cty.DynamicPseudoType)),\n\t\t\"tomap\": funcs.MakeToFunc(cty.Map(cty.DynamicPseudoType)),\n\t\t\"transpose\": funcs.TransposeFunc,\n\t\t\"trim\": stdlib.TrimFunc,\n\t\t\"trimprefix\": stdlib.TrimPrefixFunc,\n\t\t\"trimspace\": stdlib.TrimSpaceFunc,\n\t\t\"trimsuffix\": stdlib.TrimSuffixFunc,\n\t\t\"try\": tryfunc.TryFunc,\n\t\t\"upper\": stdlib.UpperFunc,\n\t\t\"urlencode\": funcs.URLEncodeFunc,\n\t\t\"uuid\": funcs.UUIDFunc,\n\t\t\"uuidv5\": funcs.UUIDV5Func,\n\t\t\"values\": stdlib.ValuesFunc,\n\t\t\"yamldecode\": yaml.YAMLDecodeFunc,\n\t\t\"yamlencode\": yaml.YAMLEncodeFunc,\n\t\t\"zipmap\": stdlib.ZipmapFunc,\n\t}\n\n}", "func PreRunEFunc(config *Config) func(*cobra.Command, []string) error {\n\treturn func(cmd *cobra.Command, args []string) error {\n\t\tformatter := cmd.Annotations[\"command\"]\n\n\t\t// root command must have an argument, otherwise we're going to show help\n\t\tif formatter == \"root\" && len(args) == 0 {\n\t\t\tcmd.Help() //nolint:errcheck\n\t\t\tos.Exit(0)\n\t\t}\n\n\t\tcmd.Flags().VisitAll(func(f *pflag.Flag) {\n\t\t\tchangedfs[f.Name] = f.Changed\n\t\t})\n\n\t\t// read config file if provided and/or available\n\t\tif config.File == \"\" {\n\t\t\treturn fmt.Errorf(\"value of '--config' can't be empty\")\n\t\t}\n\n\t\tfile := filepath.Join(args[0], config.File)\n\t\tcfgreader := &cfgreader{\n\t\t\tfile: file,\n\t\t\tconfig: config,\n\t\t}\n\n\t\tif found, err := cfgreader.exist(); !found {\n\t\t\t// config is explicitly provided and file not found, this is an error\n\t\t\tif changedfs[\"config\"] {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// config is not provided and file not found, only show an error for the root command\n\t\t\tif formatter == \"root\" {\n\t\t\t\tcmd.Help() //nolint:errcheck\n\t\t\t\tos.Exit(0)\n\t\t\t}\n\t\t} else {\n\t\t\t// config file is found, we're now going to parse it\n\t\t\tif err := cfgreader.parse(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// explicitly setting formatter to Config for non-root commands this\n\t\t// will effectively override formattter properties from config file\n\t\t// if 1) config file exists and 2) formatter is set and 3) explicitly\n\t\t// a subcommand was executed in the terminal\n\t\tif formatter != \"root\" {\n\t\t\tconfig.Formatter = formatter\n\t\t}\n\n\t\tconfig.process()\n\n\t\tif err := config.validate(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n}", "func getCfgPath(name string) string {\n\treturn configDir + \"/\" + name + \".conf\"\n}", "func config(name string, command []string) string {\n\tswitch initSystem {\n\tcase \"systemd\":\n\n\t\t// todo: in order to make this more flexible, use functional options\n\t\t// along with perhaps a template\n\t\treturn fmt.Sprintf(`[Unit]\nDescription=%s\nAfter=network.target\n\n[Service]\nType=simple\nExecStart=%s\n\n[Install]\nWantedBy=multi-user.target\n`, name, strings.Join(command, \" \"))\n\n\t// todo: double check upstart\n\tcase \"upstart\":\n\t\treturn fmt.Sprintf(`\nscript\n%s\nend script`, strings.Join(command, \" \"))\n\t}\n\n\treturn \"\"\n}", "func initConfig() {\n\tif cfgFile != \"\" {\n\t\t// Use config file from the flag.\n\t\tviper.SetConfigFile(cfgFile)\n\t} else {\n\t\t// Find home directory.\n\t\thome, err := os.UserHomeDir()\n\t\tcobra.CheckErr(err)\n\n\t\t// Search config in home directory with name \".tnt2\" (without extension).\n\t\tviper.AddConfigPath(home)\n\t\tviper.SetConfigType(\"yaml\")\n\t\tviper.SetConfigName(\".tnt2\")\n\t}\n\tviper.AutomaticEnv() // read in environment variables that match\n\t// If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tfmt.Fprintln(os.Stderr, \"Using config file:\", viper.ConfigFileUsed())\n\t}\n\t// Get the counter file name based on the current user.\n\tu, err := user.Current()\n\tcobra.CheckErr(err)\n\tcntrFileName = fmt.Sprintf(\"%s%c%s\", u.HomeDir, os.PathSeparator, tnt2CountFile)\n}", "func (c Calendars) configPath() (string, error) {\n\tconfDir, err := configDirectory()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn filepath.Join(confDir, \"calendars.txt\"), nil\n}", "func (*Module) CueConfig() string {\n\treturn `\nflamingoCommerceAdapterStandalone: {\n\tcommercesearch: {\n\t\tenableIndexing: bool | *true\n\t\trepositoryAdapter: \"bleve\" | *\"inmemory\"\n\t\tbleveAdapter: {\n\t\t\tproductsToParentCategories: bool | *true\n\t\t\tenableCategoryFacet: bool | *false\n\t\t\tfacetConfig: [...{attributeCode: string, amount: number}]\n\t\t\tsortConfig:[...{attributeCode: string, attributeType: \"numeric\"|\"bool\"|*\"text\", asc: bool, desc: bool}]\n\t\t}\n\t}\n}`\n}", "func KubeConfigFn(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\tvar path, clusterCtxName string\n\tvar provider *starlarkstruct.Struct\n\n\tif err := starlark.UnpackArgs(\n\t\tidentifiers.kubeCfg, args, kwargs,\n\t\t\"cluster_context?\", &clusterCtxName,\n\t\t\"path?\", &path,\n\t\t\"capi_provider?\", &provider,\n\t); err != nil {\n\t\treturn starlark.None, fmt.Errorf(\"%s: %s\", identifiers.kubeCfg, err)\n\t}\n\n\t// check if only one of the two options are present\n\tif (len(path) == 0 && provider == nil) || (len(path) != 0 && provider != nil) {\n\t\treturn starlark.None, errors.New(\"need either path or capi_provider\")\n\t}\n\n\tif len(path) == 0 {\n\t\tval := provider.Constructor()\n\t\tif constructor, ok := val.(starlark.String); ok {\n\t\t\tconstStr := constructor.GoString()\n\t\t\tif constStr != identifiers.capvProvider && constStr != identifiers.capaProvider {\n\t\t\t\treturn starlark.None, errors.New(\"unknown capi provider\")\n\t\t\t}\n\t\t}\n\n\t\tpathVal, err := provider.Attr(\"kube_config\")\n\t\tif err != nil {\n\t\t\treturn starlark.None, errors.Wrap(err, \"could not find the kubeconfig attribute\")\n\t\t}\n\t\tpathStr, ok := pathVal.(starlark.String)\n\t\tif !ok {\n\t\t\treturn starlark.None, errors.New(\"could not fetch kubeconfig\")\n\t\t}\n\t\tpath = pathStr.GoString()\n\t}\n\n\tpath, err := util.ExpandPath(path)\n\tif err != nil {\n\t\treturn starlark.None, err\n\t}\n\n\tstructVal := starlarkstruct.FromStringDict(starlark.String(identifiers.kubeCfg), starlark.StringDict{\n\t\t\"cluster_context\": starlark.String(clusterCtxName),\n\t\t\"path\": starlark.String(path),\n\t})\n\n\treturn structVal, nil\n}", "func initConfig() {\n\tif !debug {\n\t\tlog.AllowLevel(\"debug\")\n\t}\n\n\tconfig = &registrar.Config{}\n\tconfigPath, err := os.UserConfigDir()\n\tif err != nil {\n\t\t// TODO handle this\n\t\tpanic(\"cannot retrieve the user configuration directory\")\n\t}\n\tdefaultCfgPath := path.Join(configPath, \"cosmos\", \"registry\")\n\tafero.NewOsFs().MkdirAll(defaultCfgPath, 0700)\n\n\tviper.SetConfigType(\"yaml\")\n\n\tif cfgFile != \"\" {\n\t\t// Use config file from the flag.\n\t\tviper.SetConfigFile(cfgFile)\n\t} else {\n\t\tviper.AddConfigPath(defaultCfgPath)\n\t\tviper.SetConfigName(\"config\")\n\t}\n\n\t// set the workspace folder\n\tcfgFilePath := viper.ConfigFileUsed()\n\tif cfgFilePath == \"\" {\n\t\tcfgFilePath = path.Join(defaultCfgPath, \"config.yaml\")\n\t}\n\t//now read in the config\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tviper.Unmarshal(config)\n\t\tlogger.Debug(\"Using config file at \", \"config\", viper.ConfigFileUsed())\n\t} else {\n\t\tswitch err.(type) {\n\t\tcase viper.ConfigFileNotFoundError:\n\t\t\tif noInteraction {\n\t\t\t\tprintln(\"config file not found\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif err = interactiveSetup(); err != nil {\n\t\t\t\tprintln(\"unexpected error \", err.Error())\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tviper.Unmarshal(config)\n\t\t\tprintln(\"\\nThe configuration is:\")\n\t\t\tprompts.PrettyMap(viper.AllSettings())\n\t\t\tprintln()\n\t\t\tif ok := prompts.Confirm(false, \"save the configuration?\"); !ok {\n\t\t\t\tprintln(\"aborting, run the command again to change the configuration\")\n\t\t\t\tos.Exit(0)\n\t\t\t}\n\n\t\t\tif err = viper.WriteConfigAs(cfgFilePath); err != nil {\n\t\t\t\tprintln(\"aborting, error writing the configuration file:\", err.Error())\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tprintln(\"config file saved in \", cfgFilePath)\n\n\t\tdefault:\n\t\t\tprintln(\"the configuration file appers corrupted: \", err.Error())\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\t// set the config workspace folder\n\tconfig.Workspace = path.Dir(cfgFilePath)\n}", "func init() {\n\tconfig := domain.LoadCfg(\"manga\")\n\tif config == nil {\n\t\tlog.Info(\"用户未设置漫画相关的配置\")\n\t\treturn\n\t}\n\tmangaClockIn.config = config\n\ttaskList = append(taskList, mangaClockIn)\n}", "func (self *userRestAPI) init(r *mux.Router,configfile string) error {\n\tvar err error\n\n\tself.engine,err = model.NewEngine(configfile)\n\tif err != nil {\n\t\treturn logError(err)\n\t}\n\n\tapi := r.PathPrefix(\"/user/v1\").Subrouter()\n\n\tapi.HandleFunc(\"/flighthistory/id/{token}/b/{band}/n/{number}\", self.flightHistory).Methods(http.MethodGet)\n\tapi.HandleFunc(\"/transactions/id/{token}/b/{band}/n/{number}\", self.transactions).Methods(http.MethodGet)\n\tapi.HandleFunc(\"/promises/id/{token}/b/{band}/n/{number}\", self.promises).Methods(http.MethodGet)\n\tapi.HandleFunc(\"/account/id/{token}/b/{band}/n/{number}\", self.account).Methods(http.MethodGet)\n\tapi.HandleFunc(\"/dailystats/id/{token}\", self.dailyStats)\n\tapi.Use(middlewareIdToken)\n\n\treturn nil\n}", "func LoadConfig() {\n\n\tif build.ModuleConsole {\n\t\tsharedConsole.Log(\"Console enabled\", \"Module\")\n\t\tconsole.LoadConfig()\n\t}\n\n\tif build.ModuleLogViewer {\n\t\tsharedConsole.Log(\"LogViewer enabled\", \"Module\")\n\t\tlogviewer.LoadConfig()\n\t}\n\n\tif build.ModuleBackup {\n\t\tsharedConsole.Log(\"Backup enabled\", \"Module\")\n\t\tbackup.LoadConfig()\n\t}\n\n\tif build.ModuleOpenESPM {\n\t\tsharedConsole.Log(\"openESPM enabled\", \"Module\")\n\t\topenespm.LoadConfig()\n\t}\n\n\tif build.ModuleFileshare {\n\t\tsharedConsole.Log(\"Fileshare enabled\", \"Module\")\n\t\tfileshare.LoadConfig()\n\t}\n\n\tif build.ModuleHomepage {\n\t\tsharedConsole.Log(\"Homepage enabled\", \"Module\")\n\t\thomepage.LoadConfig()\n\t}\n\n\tif build.ModuleMesh || build.ModuleMessenger || build.ModuleMeshFS {\n\t\tsharedConsole.Log(\"Mesh enabled\", \"Module\")\n\t\tmesh.LoadConfig()\n\t}\n\n\tif build.ModuleMessenger {\n\t\tsharedConsole.Log(\"Messenger enabled\", \"Module\")\n\t\tmessenger.LoadConfig()\n\t}\n\n\tif build.ModuleMeshFS {\n\t\tsharedConsole.Log(\"MeshFileSync enabled\", \"Module\")\n\t\tmeshfilesync.LoadConfig()\n\t}\n\n\tif build.ModuleMediaDownloader {\n\t\tsharedConsole.Log(\"MediaDownloader enabled\", \"Module\")\n\t\tmediadownloader.LoadConfig()\n\t}\n\n\tif build.ModuleIPTracker {\n\t\tsharedConsole.Log(\"IPTracker enabled\", \"Module\")\n\t\tiptracker.LoadConfig()\n\t}\n\n\tif build.ModuleGasPrice {\n\t\tsharedConsole.Log(\"GasPrice enabled\", \"Module\")\n\t\tgasprice.LoadConfig()\n\t}\n\n\tif build.ModulePictureX {\n\t\tsharedConsole.Log(\"PictureX enabled\", \"Module\")\n\t\tpicturex.LoadConfig()\n\t}\n\n\tif build.ModuleS7Backup {\n\t\tsharedConsole.Log(\"S7Backup enabled\", \"Module\")\n\t\ts7backup.LoadConfig()\n\t}\n\n\tif build.ModuleInstaBackup {\n\t\tsharedConsole.Log(\"InstaBackup enabled\", \"Module\")\n\t\tinstabackup.LoadConfig()\n\t}\n\n\tif build.ModuleInstaFollowBot {\n\t\tsharedConsole.Log(\"InstaFollowBot enabled\", \"Module\")\n\t\tinstafollowbot.LoadConfig()\n\t}\n\n\tif build.ModuleMonMotion {\n\t\tsharedConsole.Log(\"MonMotion enabled\", \"Module\")\n\t\tmonmotion.LoadConfig()\n\t}\n\n\tif build.ModuleGPSNav {\n\t\tsharedConsole.Log(\"GPSNav enabled\", \"Module\")\n\t\tgpsnav.LoadConfig()\n\t}\n\n\tif build.ModuleModbusTest {\n\t\tsharedConsole.Log(\"ModbusTest enabled\", \"Module\")\n\t\tmodbustest.LoadConfig()\n\t}\n\n\tif build.ModuleHeatingMath {\n\t\tsharedConsole.Log(\"HeatingMath enabled\", \"Module\")\n\t\theatingmath.LoadConfig()\n\t}\n\n\tif build.ModuleMark {\n\t\tsharedConsole.Log(\"Mark enabled\", \"Module\")\n\t\tmark.LoadConfig()\n\t}\n\n\tif build.ModuleParaTest {\n\t\tsharedConsole.Log(\"ParaTest enabled\", \"Module\")\n\t\tparatest.LoadConfig()\n\t}\n}", "func (s *Server) initConfig() (err error) {\n\t// Home directory is current working directory by default\n\tif s.HomeDir == \"\" {\n\t\ts.HomeDir, err = os.Getwd()\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed to get server's home directory\")\n\t\t}\n\t}\n\t// Make home directory absolute, if not already\n\tabsoluteHomeDir, err := filepath.Abs(s.HomeDir)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to make server's home directory path absolute: %s\", err)\n\t}\n\ts.HomeDir = absoluteHomeDir\n\t// Create config if not set\n\tif s.Config == nil {\n\t\ts.Config = new(ServerConfig)\n\t}\n\ts.CA.server = s\n\ts.CA.HomeDir = s.HomeDir\n\terr = s.initMultiCAConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\trevoke.SetCRLFetcher(s.fetchCRL)\n\t// Make file names absolute\n\ts.makeFileNamesAbsolute()\n\n\tcompModeStr := os.Getenv(\"FABRIC_CA_SERVER_COMPATIBILITY_MODE_V1_3\")\n\tif compModeStr == \"\" {\n\t\tcompModeStr = \"true\" // TODO: Change default to false once all clients have been updated to use the new authorization header\n\t}\n\n\ts.Config.CompMode1_3, err = strconv.ParseBool(compModeStr)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"Invalid value for boolean environment variable 'FABRIC_CA_SERVER_COMPATIBILITY_MODE_V1_3'\")\n\t}\n\n\treturn nil\n}", "func initConfig() {\n\n\t// Configure logging\n\tconst logNameConsole = \"console\"\n\tlevel, _ := glog.NewLogLevel(rootFlags.logLevel)\n\tglog.ClearBackends()\n\tglog.SetBackend(logNameConsole, glog.NewWriterBackend(os.Stderr, \"\", level, \"\"))\n\n\t// Load config from file\n\tresticmanager.AppConfig.Load(rootFlags.appConfigFile)\n\tresticmanager.AppConfig.DryRun = rootFlags.dryrun\n\n\t// Add file logging if required\n\tif logConfig := resticmanager.AppConfig.LoggingConfig(); (!rootFlags.noFileLogging) && (logConfig != nil) {\n\t\tconst logNameFile = \"appfile\"\n\n\t\tglog.SetBackend(logNameFile,\n\t\t\tglog.NewFileBackend(\n\t\t\t\tlogConfig.Filename,\n\t\t\t\tlogConfig.Append,\n\t\t\t\t\"\",\n\t\t\t\tlogConfig.Level,\n\t\t\t\t\"\", // Use default logging format\n\t\t\t))\n\n\t}\n\n}", "func Init(cfgFile string, logLevel string, noClean bool) {\n\n\tNoClean = noClean\n\n\tlvl := capnslog.WARNING\n\tif logLevel != \"\" {\n\t\t// Initialize logging system\n\t\tvar err error\n\t\tlvl, err = capnslog.ParseLevel(strings.ToUpper(logLevel))\n\t\tif err != nil {\n\t\t\tlog.Warningf(\"Wrong Log level %v, defaults to [Warning]\", logLevel)\n\t\t\tlvl = capnslog.WARNING\n\t\t}\n\n\t}\n\tcapnslog.SetGlobalLogLevel(lvl)\n\tcapnslog.SetFormatter(capnslog.NewPrettyFormatter(os.Stdout, false))\n\n\tviper.SetEnvPrefix(\"clairctl\")\n\tviper.SetConfigName(\"clairctl\") // name of config file (without extension)\n\tviper.AddConfigPath(\"$HOME/.clairctl\") // adding home directory as first search path\n\tviper.AddConfigPath(\".\") // adding home directory as first search path\n\tviper.AutomaticEnv() // read in environment variables that match\n\tif cfgFile != \"\" {\n\t\tviper.SetConfigFile(cfgFile)\n\t}\n\terr := viper.ReadInConfig()\n\tif err != nil {\n\t\te, ok := err.(viper.ConfigParseError)\n\t\tif ok {\n\t\t\tlog.Fatalf(\"error parsing config file: %v\", e)\n\t\t}\n\t\tlog.Debugf(\"No config file used\")\n\t} else {\n\t\tlog.Debugf(\"Using config file: %v\", viper.ConfigFileUsed())\n\t}\n\n\tif viper.Get(\"clair.uri\") == nil {\n\t\tviper.Set(\"clair.uri\", \"http://localhost\")\n\t}\n\tif viper.Get(\"clair.port\") == nil {\n\t\tviper.Set(\"clair.port\", \"6060\")\n\t}\n\tif viper.Get(\"clair.healthPort\") == nil {\n\t\tviper.Set(\"clair.healthPort\", \"6061\")\n\t}\n\n\tif viper.Get(\"clair.report.path\") == nil {\n\t\tviper.Set(\"clair.report.path\", \"reports\")\n\t}\n\tif viper.Get(\"clair.report.format\") == nil {\n\t\tviper.Set(\"clair.report.format\", \"html\")\n\t}\n\tif viper.Get(\"auth.insecureSkipVerify\") == nil {\n\t\tviper.Set(\"auth.insecureSkipVerify\", \"true\")\n\t}\n\tif viper.Get(\"clairctl.ip\") == nil {\n\t\tviper.Set(\"clairctl.ip\", \"\")\n\t}\n\tif viper.Get(\"clairctl.port\") == nil {\n\t\tviper.Set(\"clairctl.port\", 0)\n\t}\n\tif viper.Get(\"clairctl.interface\") == nil {\n\t\tviper.Set(\"clairctl.interface\", \"\")\n\t}\n\tif viper.Get(\"clairctl.tempFolder\") == nil {\n\t\tviper.Set(\"clairctl.tempFolder\", \"/tmp/clairctl\")\n\t}\n\tif viper.Get(\"notifier.severity\") == nil {\n\t\tviper.Set(\"notifier.severity\", \"Critical\")\n\t}\n\n}", "func createConfig(apiServerURL, kubeCfgPath string, qps float32, burst int) (*rest.Config, error) {\n\tvar (\n\t\tconfig *rest.Config\n\t\terr error\n\t)\n\tcmdName := \"cilium\"\n\tif len(os.Args[0]) != 0 {\n\t\tcmdName = filepath.Base(os.Args[0])\n\t}\n\tuserAgent := fmt.Sprintf(\"%s/%s\", cmdName, version.Version)\n\n\tswitch {\n\t// If the apiServerURL and the kubeCfgPath are empty then we can try getting\n\t// the rest.Config from the InClusterConfig\n\tcase apiServerURL == \"\" && kubeCfgPath == \"\":\n\t\tif config, err = rest.InClusterConfig(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tcase kubeCfgPath != \"\":\n\t\tif config, err = clientcmd.BuildConfigFromFlags(\"\", kubeCfgPath); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tcase strings.HasPrefix(apiServerURL, \"https://\"):\n\t\tif config, err = rest.InClusterConfig(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tconfig.Host = apiServerURL\n\tdefault:\n\t\tconfig = &rest.Config{Host: apiServerURL, UserAgent: userAgent}\n\t}\n\n\tsetConfig(config, userAgent, qps, burst)\n\treturn config, nil\n}", "func initConfig() {\n\tuser := user.Current()\n\tif cfgFile != \"\" {\n\t\tuser.Config.SetConfigFile(cfgFile)\n\t}\n\t// else if home\n\t// home := pkg.GetHome()\n\t// if cfgFile != \"\" {\n\t// \t// Use config file from the flag.\n\t// \tuser.Config.SetConfigFile(cfgFile)\n\t// \t// viper.SetConfigFile(cfgFile)\n\t// } else {\n\t// \th := home.Get()\n\t// \tviper.AddConfigPath(h.Path)\n\t// \tviper.SetConfigName(home.CONFIG_FILENAME)\n\t// }\n\n\t// viper.AutomaticEnv() // read in environment variables that match\n\t// viper.SetEnvPrefix(\"wk\")\n\n\t// // If a config file is found, read it in.\n\t// if err := viper.ReadInConfig(); err == nil {\n\t// \tfmt.Println(\"Using config file:\", viper.ConfigFileUsed())\n\t// }\n}", "func CustomEnvironment(ravenURL, flowID, workerID string) OptionFunc {\n\topts := []OptionFunc{}\n\n\tif optionFn, err := WithRavenURL((fmt.Sprintf(\"capnproto://%s\", ravenURL))); err != nil {\n\t\treturn errorFunc(err)\n\t} else {\n\t\topts = append(opts, optionFn)\n\t}\n\n\tif optionFn, err := WithFlowID(flowID); err != nil {\n\t\treturn errorFunc(err)\n\t} else {\n\t\topts = append(opts, optionFn)\n\t}\n\n\tif optionFn, err := WithWorkerID(workerID); err != nil {\n\t\treturn errorFunc(err)\n\t} else {\n\t\topts = append(opts, optionFn)\n\t}\n\n\treturn func(c *Config) error {\n\t\tfor _, optionFn := range opts {\n\t\t\tif err := optionFn(c); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}\n}", "func initConfig() {\n\tvar config Configuration\n\tconfig.Databases = initAllDBConfig()\n\tconfig.Services = initAllServiceConfig()\n}", "func initConfig() {\n\tviper.BindEnv(\"CNI_CONF_NAME\")\n\tviper.BindEnv(\"CNI_ETC_DIR\")\n\tviper.BindEnv(\"CNI_BIN_DIR\")\n\tviper.BindEnv(\"COIL_PATH\")\n\tviper.BindEnv(\"CNI_NETCONF_FILE\")\n\tviper.BindEnv(\"CNI_NETCONF\")\n\tviper.BindEnv(\"COIL_BOOT_TAINT\")\n\n\tviper.SetDefault(\"CNI_CONF_NAME\", defaultCniConfName)\n\tviper.SetDefault(\"CNI_ETC_DIR\", defaultCniEtcDir)\n\tviper.SetDefault(\"CNI_BIN_DIR\", defaultCniBinDir)\n\tviper.SetDefault(\"COIL_PATH\", defaultCoilPath)\n}", "func createContrailConfig(fqNameTable *FQNameTableType, tp, name, parentType string, fqName []string) (*ContrailConfig, error) {\n\tu, err := uuid.NewUUID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tus := u.String()\n\tif (*fqNameTable)[tp] == nil {\n\t\t(*fqNameTable)[tp] = map[string]string{}\n\t}\n\tt := time.Now().String()\n\tts := strings.ReplaceAll(t, \" \", \"T\")\n\tc := ContrailConfig{\n\t\tUUID: us,\n\t\tType: tp,\n\t\tParentType: parentType,\n\t\tDisplayName: name,\n\t\tPerms2: types.PermType2{\n\t\t\tOwner: \"cloud-admin\",\n\t\t\tOwnerAccess: 7,\n\t\t\tGlobalAccess: 5,\n\t\t},\n\t\tIdPerms: types.IdPermsType{\n\t\t\tEnable: true,\n\t\t\tUuid: &types.UuidType{\n\t\t\t\tUuidMslong: binary.BigEndian.Uint64(u[:8]),\n\t\t\t\tUuidLslong: binary.BigEndian.Uint64(u[8:]),\n\t\t\t},\n\t\t\tCreated: ts,\n\t\t\tLastModified: ts,\n\t\t\tUserVisible: true,\n\t\t\tPermissions: &types.PermType{\n\t\t\t\tOwner: \"cloud-admin\",\n\t\t\t\tOwnerAccess: 7,\n\t\t\t\tOtherAccess: 7,\n\t\t\t\tGroup: \"cloud-admin-group\",\n\t\t\t\tGroupAccess: 7,\n\t\t\t},\n\t\t\tDescription: \"\",\n\t\t\tCreator: \"\",\n\t\t},\n\t\tFqName: fqName,\n\t}\n\t(*fqNameTable)[tp][fmt.Sprintf(\"%s:%s\", strings.Join(fqName, \":\"), us)] = \"null\"\n\treturn &c, nil\n}", "func SetupCRDs(crdPath, pattern string) env.Func {\n\treturn func(ctx context.Context, c *envconf.Config) (context.Context, error) {\n\t\tr, err := resources.New(c.Client().RESTConfig())\n\t\tif err != nil {\n\t\t\treturn ctx, err\n\t\t}\n\t\treturn ctx, decoder.ApplyWithManifestDir(ctx, r, crdPath, pattern, []resources.CreateOption{})\n\t}\n}", "func customizeWebConsole(k *kabanerov1alpha1.Kabanero, clientset *kubernetes.Clientset, config *restclient.Config, landingURL string) error {\n\t// Get a copy of the web-console ConfigMap.\n\tcm, err := getWebConsoleConfigMap(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Get the embedded yaml entry in the web console ConfigMap yaml.\n\twccyaml := cm.Data[\"webconsole-config.yaml\"]\n\n\tm := make(map[string]interface{})\n\terr = yaml.Unmarshal([]byte(wccyaml), &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Update the extensions section of the embedded webconsole-config.yaml entry\n\tscripts, ssheets := getCustomizationURLs(landingURL)\n\n\tfor k, v := range m {\n\t\tif k == \"extensions\" {\n\t\t\textmap := v.(map[interface{}]interface{})\n\t\t\tfor kk, vv := range extmap {\n\t\t\t\tif kk == \"scriptURLs\" {\n\t\t\t\t\teScripts := scripts\n\t\t\t\t\tsun := make([]interface{}, (len(eScripts)))\n\t\t\t\t\tvar ix = 0\n\t\t\t\t\tif vv != nil {\n\t\t\t\t\t\tsu := vv.([]interface{})\n\t\t\t\t\t\teScripts = getEffectiveCustomizationURLs(su, scripts)\n\t\t\t\t\t\tsun = make([]interface{}, (len(su) + len(eScripts)))\n\n\t\t\t\t\t\tfor i := 0; i < len(su); i++ {\n\t\t\t\t\t\t\tsun[ix] = su[ix]\n\t\t\t\t\t\t\tix++\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfor _, u := range eScripts {\n\t\t\t\t\t\tsun[ix] = u\n\t\t\t\t\t\tix++\n\t\t\t\t\t}\n\t\t\t\t\textmap[kk] = sun\n\t\t\t\t}\n\t\t\t\tif kk == \"stylesheetURLs\" {\n\t\t\t\t\teSsheets := ssheets\n\t\t\t\t\tsun := make([]interface{}, (len(eSsheets)))\n\t\t\t\t\tvar ix = 0\n\t\t\t\t\tif vv != nil {\n\t\t\t\t\t\tsu := vv.([]interface{})\n\t\t\t\t\t\teSsheets = getEffectiveCustomizationURLs(su, ssheets)\n\t\t\t\t\t\tsun = make([]interface{}, (len(su) + len(eSsheets)))\n\n\t\t\t\t\t\tfor i := 0; i < len(su); i++ {\n\t\t\t\t\t\t\tsun[ix] = su[ix]\n\t\t\t\t\t\t\tix++\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tfor _, u := range eSsheets {\n\t\t\t\t\t\tsun[ix] = u\n\t\t\t\t\t\tix++\n\t\t\t\t\t}\n\t\t\t\t\textmap[kk] = sun\n\t\t\t\t}\n\t\t\t}\n\t\t\tm[k] = extmap\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Update our copy of the web console yaml and update it.\n\tupatedCMBytes, err := yaml.Marshal(m)\n\tcm.Data[\"webconsole-config.yaml\"] = string(upatedCMBytes)\n\t_, err = yaml.Marshal(cm)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tkllog.Info(fmt.Sprintf(\"customizeWebConsole: ConfigMap for update: %v\", cm))\n\n\t_, err = clientset.CoreV1().ConfigMaps(\"openshift-web-console\").Update(cm)\n\n\treturn err\n}", "func initConfig() {\n\thome, err := homedir.Dir()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t\t//panic()\n\t}\n\n\tcreateDefaultConfigFile(path.Join(home, \".gg-cli.yaml\"))\n\tcreateLocalCacheDir(path.Join(home, \".gg\"))\n\n\tviper.AddConfigPath(home)\n\tviper.SetConfigName(\".gg-cli\")\n\n\tviper.AutomaticEnv() // read in environment variables that match\n\n\t// If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tfmt.Println(\"没有找到配置文件(.gg-cli.yaml) 请检查环境:\" + cfgFile)\n\t}\n\n}", "func generateConfigFile(context *clusterd.Context, clusterInfo *ClusterInfo, pathRoot, keyringPath string, globalConfig *CephConfig, clientSettings map[string]string) (string, error) {\n\n\t// create the config directory\n\tif err := os.MkdirAll(pathRoot, 0744); err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"failed to create config directory at %q\", pathRoot)\n\t}\n\n\tconfigFile, err := createGlobalConfigFileSection(context, clusterInfo, globalConfig)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to create global config section\")\n\t}\n\n\tif err := mergeDefaultConfigWithRookConfigOverride(context, clusterInfo, configFile); err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"failed to merge global config with %q\", k8sutil.ConfigOverrideName)\n\t}\n\n\tqualifiedUser := getQualifiedUser(clusterInfo.CephCred.Username)\n\tif err := addClientConfigFileSection(configFile, qualifiedUser, keyringPath, clientSettings); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to add admin client config section\")\n\t}\n\n\t// write the entire config to disk\n\tfilePath := getConfFilePath(pathRoot, clusterInfo.Namespace)\n\tlogger.Infof(\"writing config file %s\", filePath)\n\tif err := configFile.SaveTo(filePath); err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"failed to save config file %s\", filePath)\n\t}\n\n\treturn filePath, nil\n}", "func CgLs(s string) string {\r\n\tp := SLICES + \"/user-\" + s + \".slice\"\r\n\tout, err := exec.Command(\"systemd-cgls\", p).Output()\r\n\tcheck(err)\r\n\treturn string(out)\r\n}", "func (c *Config) Defaults() {\n\tc.Paths.Mount = \"/auth\"\n\tc.Paths.NotAuthorized = \"/\"\n\tc.Paths.AuthLoginOK = \"/\"\n\tc.Paths.ConfirmOK = \"/\"\n\tc.Paths.ConfirmNotOK = \"/\"\n\tc.Paths.LockNotOK = \"/\"\n\tc.Paths.LogoutOK = \"/\"\n\tc.Paths.OAuth2LoginOK = \"/\"\n\tc.Paths.OAuth2LoginNotOK = \"/\"\n\tc.Paths.RecoverOK = \"/\"\n\tc.Paths.RegisterOK = \"/\"\n\tc.Paths.RootURL = \"http://localhost:8080\"\n\n\tc.Modules.BCryptCost = bcrypt.DefaultCost\n\tc.Modules.ConfirmMethod = http.MethodGet\n\tc.Modules.ExpireAfter = time.Hour\n\tc.Modules.LockAfter = 3\n\tc.Modules.LockWindow = 5 * time.Minute\n\tc.Modules.LockDuration = 12 * time.Hour\n\tc.Modules.LogoutMethod = \"DELETE\"\n\tc.Modules.RecoverLoginAfterRecovery = false\n\tc.Modules.RecoverTokenDuration = 24 * time.Hour\n}", "func addConfigs() error {\n\tconst template = `apiVersion: hnc.x-k8s.io/v1alpha2\nkind: HierarchyConfiguration\nmetadata:\n name: hierarchy\n namespace: %s\n annotations:\n config.kubernetes.io/path: %s\nspec:\n parent: %s`\n\n\tfor nm, ns := range forest {\n\t\tif ns.hasConfig || ns.parent == \"\"{\n\t\t\t// Don't generate configs if one already exists or for roots\n\t\t\tcontinue\n\t\t}\n\n\t\t// Build the filepath for this new yaml object based on its hierarchical path\n\t\tpath := nm + \"/hierarchyconfiguration.yaml\"\n\t\tpnm := ns.parent\n\t\tfor pnm != \"\" {\n\t\t\tpath = pnm + \"/\" + path\n\t\t\tpnm = forest[pnm].parent\n\t\t}\n\t\tpath = \"namespaces/\" + path\n\n\t\t// Generate the config from the template\n\t\tconfig := fmt.Sprintf(template, nm, path, ns.parent)\n\t\tn, err := yaml.Parse(config)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"HC config was:\\n%s\\n\", config)\n\t\t\treturn fmt.Errorf(\"couldn't generate hierarchy config for %q: %s\\n\", nm, err)\n\t\t}\n\t\tfmt.Fprintf(os.Stderr, \"Generating %q\\n\", path)\n\t\tresourceList.Items = append(resourceList.Items, n)\n\t}\n\n\treturn nil\n}", "func MakeConfig(c *def.App) (out *nine.Config) {\n\tC := c.Cats\n\tvar configFile string\n\tvar tn, sn, rn bool\n\tout = &nine.Config{\n\t\tConfigFile: &configFile,\n\t\tAppDataDir: C.Str(\"app\", \"appdatadir\"),\n\t\tDataDir: C.Str(\"app\", \"datadir\"),\n\t\tLogDir: C.Str(\"app\", \"logdir\"),\n\t\tLogLevel: C.Str(\"log\", \"level\"),\n\t\tSubsystems: C.Map(\"log\", \"subsystem\"),\n\t\tNetwork: C.Str(\"p2p\", \"network\"),\n\t\tAddPeers: C.Tags(\"p2p\", \"addpeer\"),\n\t\tConnectPeers: C.Tags(\"p2p\", \"connect\"),\n\t\tMaxPeers: C.Int(\"p2p\", \"maxpeers\"),\n\t\tListeners: C.Tags(\"p2p\", \"listen\"),\n\t\tDisableListen: C.Bool(\"p2p\", \"nolisten\"),\n\t\tDisableBanning: C.Bool(\"p2p\", \"disableban\"),\n\t\tBanDuration: C.Duration(\"p2p\", \"banduration\"),\n\t\tBanThreshold: C.Int(\"p2p\", \"banthreshold\"),\n\t\tWhitelists: C.Tags(\"p2p\", \"whitelist\"),\n\t\tUsername: C.Str(\"rpc\", \"user\"),\n\t\tPassword: C.Str(\"rpc\", \"pass\"),\n\t\tServerUser: C.Str(\"rpc\", \"user\"),\n\t\tServerPass: C.Str(\"rpc\", \"pass\"),\n\t\tLimitUser: C.Str(\"limit\", \"user\"),\n\t\tLimitPass: C.Str(\"limit\", \"pass\"),\n\t\tRPCConnect: C.Str(\"rpc\", \"connect\"),\n\t\tRPCListeners: C.Tags(\"rpc\", \"listen\"),\n\t\tRPCCert: C.Str(\"tls\", \"cert\"),\n\t\tRPCKey: C.Str(\"tls\", \"key\"),\n\t\tRPCMaxClients: C.Int(\"rpc\", \"maxclients\"),\n\t\tRPCMaxWebsockets: C.Int(\"rpc\", \"maxwebsockets\"),\n\t\tRPCMaxConcurrentReqs: C.Int(\"rpc\", \"maxconcurrentreqs\"),\n\t\tRPCQuirks: C.Bool(\"rpc\", \"quirks\"),\n\t\tDisableRPC: C.Bool(\"rpc\", \"disable\"),\n\t\tNoTLS: C.Bool(\"tls\", \"disable\"),\n\t\tDisableDNSSeed: C.Bool(\"p2p\", \"nodns\"),\n\t\tExternalIPs: C.Tags(\"p2p\", \"externalips\"),\n\t\tProxy: C.Str(\"proxy\", \"address\"),\n\t\tProxyUser: C.Str(\"proxy\", \"user\"),\n\t\tProxyPass: C.Str(\"proxy\", \"pass\"),\n\t\tOnionProxy: C.Str(\"proxy\", \"address\"),\n\t\tOnionProxyUser: C.Str(\"proxy\", \"user\"),\n\t\tOnionProxyPass: C.Str(\"proxy\", \"pass\"),\n\t\tOnion: C.Bool(\"proxy\", \"tor\"),\n\t\tTorIsolation: C.Bool(\"proxy\", \"isolation\"),\n\t\tTestNet3: &tn,\n\t\tRegressionTest: &rn,\n\t\tSimNet: &sn,\n\t\tAddCheckpoints: C.Tags(\"chain\", \"addcheckpoints\"),\n\t\tDisableCheckpoints: C.Bool(\"chain\", \"disablecheckpoints\"),\n\t\tDbType: C.Str(\"chain\", \"dbtype\"),\n\t\tProfile: C.Int(\"app\", \"profile\"),\n\t\tCPUProfile: C.Str(\"app\", \"cpuprofile\"),\n\t\tUpnp: C.Bool(\"app\", \"upnp\"),\n\t\tMinRelayTxFee: C.Float(\"p2p\", \"minrelaytxfee\"),\n\t\tFreeTxRelayLimit: C.Float(\"p2p\", \"freetxrelaylimit\"),\n\t\tNoRelayPriority: C.Bool(\"p2p\", \"norelaypriority\"),\n\t\tTrickleInterval: C.Duration(\"p2p\", \"trickleinterval\"),\n\t\tMaxOrphanTxs: C.Int(\"p2p\", \"maxorphantxs\"),\n\t\tAlgo: C.Str(\"mining\", \"algo\"),\n\t\tGenerate: C.Bool(\"mining\", \"generate\"),\n\t\tGenThreads: C.Int(\"mining\", \"genthreads\"),\n\t\tMiningAddrs: C.Tags(\"mining\", \"addresses\"),\n\t\tMinerListener: C.Str(\"mining\", \"listener\"),\n\t\tMinerPass: C.Str(\"mining\", \"pass\"),\n\t\tBlockMinSize: C.Int(\"block\", \"minsize\"),\n\t\tBlockMaxSize: C.Int(\"block\", \"maxsize\"),\n\t\tBlockMinWeight: C.Int(\"block\", \"minweight\"),\n\t\tBlockMaxWeight: C.Int(\"block\", \"maxweight\"),\n\t\tBlockPrioritySize: C.Int(\"block\", \"prioritysize\"),\n\t\tUserAgentComments: C.Tags(\"p2p\", \"useragentcomments\"),\n\t\tNoPeerBloomFilters: C.Bool(\"p2p\", \"nobloomfilters\"),\n\t\tNoCFilters: C.Bool(\"p2p\", \"nocfilters\"),\n\t\tSigCacheMaxSize: C.Int(\"chain\", \"sigcachemaxsize\"),\n\t\tBlocksOnly: C.Bool(\"p2p\", \"blocksonly\"),\n\t\tTxIndex: C.Bool(\"chain\", \"txindex\"),\n\t\tAddrIndex: C.Bool(\"chain\", \"addrindex\"),\n\t\tRelayNonStd: C.Bool(\"chain\", \"relaynonstd\"),\n\t\tRejectNonStd: C.Bool(\"chain\", \"rejectnonstd\"),\n\t\tTLSSkipVerify: C.Bool(\"tls\", \"skipverify\"),\n\t\tWallet: C.Bool(\"wallet\", \"enable\"),\n\t\tNoInitialLoad: C.Bool(\"wallet\", \"noinitialload\"),\n\t\tWalletPass: C.Str(\"wallet\", \"pass\"),\n\t\tWalletServer: C.Str(\"wallet\", \"server\"),\n\t\tCAFile: C.Str(\"tls\", \"cafile\"),\n\t\tOneTimeTLSKey: C.Bool(\"tls\", \"onetime\"),\n\t\tServerTLS: C.Bool(\"tls\", \"server\"),\n\t\tLegacyRPCListeners: C.Tags(\"rpc\", \"listen\"),\n\t\tLegacyRPCMaxClients: C.Int(\"rpc\", \"maxclients\"),\n\t\tLegacyRPCMaxWebsockets: C.Int(\"rpc\", \"maxwebsockets\"),\n\t\tExperimentalRPCListeners: &[]string{},\n\t\tState: node.StateCfg,\n\t}\n\treturn\n}", "func getPlatformStringsAddFunction(c *config.Config, info fileInfo, cgoTags *cgoTagsAndOpts) func(sb *platformStringsBuilder, ss ...string) {\n\tisOSSpecific, isArchSpecific := isOSArchSpecific(info, cgoTags)\n\tv := getGoConfig(c).rulesGoVersion\n\tconstraintPrefix := \"@\" + getGoConfig(c).rulesGoRepoName + \"//go/platform:\"\n\n\tswitch {\n\tcase !isOSSpecific && !isArchSpecific:\n\t\tif checkConstraints(c, \"\", \"\", info.goos, info.goarch, info.tags, cgoTags) {\n\t\t\treturn func(sb *platformStringsBuilder, ss ...string) {\n\t\t\t\tfor _, s := range ss {\n\t\t\t\t\tsb.addGenericString(s)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tcase isOSSpecific && !isArchSpecific:\n\t\tvar osMatch []string\n\t\tfor _, os := range rule.KnownOSs {\n\t\t\tif rulesGoSupportsOS(v, os) &&\n\t\t\t\tcheckConstraints(c, os, \"\", info.goos, info.goarch, info.tags, cgoTags) {\n\t\t\t\tosMatch = append(osMatch, os)\n\t\t\t}\n\t\t}\n\t\tif len(osMatch) > 0 {\n\t\t\treturn func(sb *platformStringsBuilder, ss ...string) {\n\t\t\t\tfor _, s := range ss {\n\t\t\t\t\tsb.addOSString(s, osMatch, constraintPrefix)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tcase !isOSSpecific && isArchSpecific:\n\t\tvar archMatch []string\n\t\tfor _, arch := range rule.KnownArchs {\n\t\t\tif rulesGoSupportsArch(v, arch) &&\n\t\t\t\tcheckConstraints(c, \"\", arch, info.goos, info.goarch, info.tags, cgoTags) {\n\t\t\t\tarchMatch = append(archMatch, arch)\n\t\t\t}\n\t\t}\n\t\tif len(archMatch) > 0 {\n\t\t\treturn func(sb *platformStringsBuilder, ss ...string) {\n\t\t\t\tfor _, s := range ss {\n\t\t\t\t\tsb.addArchString(s, archMatch, constraintPrefix)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\tvar platformMatch []rule.Platform\n\t\tfor _, platform := range rule.KnownPlatforms {\n\t\t\tif rulesGoSupportsPlatform(v, platform) &&\n\t\t\t\tcheckConstraints(c, platform.OS, platform.Arch, info.goos, info.goarch, info.tags, cgoTags) {\n\t\t\t\tplatformMatch = append(platformMatch, platform)\n\t\t\t}\n\t\t}\n\t\tif len(platformMatch) > 0 {\n\t\t\treturn func(sb *platformStringsBuilder, ss ...string) {\n\t\t\t\tfor _, s := range ss {\n\t\t\t\t\tsb.addPlatformString(s, platformMatch, constraintPrefix)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn func(_ *platformStringsBuilder, _ ...string) {}\n}", "func (jj *Juju) fetchConfig(user, service string) (string, error) {\n //FIXME This works only for hivetest and hivelab\n // Could explore directories instead\n if ! strings.HasPrefix(service, \"hive\") {\n log.Infof(\"service not supported for custom configuration\")\n return \"\", nil\n }\n // Initialize\n configLabTree := []string{\n \"serf-ip\", \"dna-repo\", \"targets\", \"app-repo\", \"extra-packages\",\n \"openlibs\", \"editor\", \"terminal_multiplexer\", \"plugins\",\n \"shell/default\", \"shell/prompt\",\n \"dev/node_version\", \"dev/go_version\", \"dev/python_version\",\n }\n config := make(map[string]string)\n\n // Fetch and store configuration\n log.Infof(\"reading configuration for node %s\\n\", jj.id(user, service))\n for _, key := range configLabTree {\n result, err := jj.Controller.Get(filepath.Join(user, service, key))\n if err == nil && len(result) == 1 {\n log.Infof(\"[config] %s = %s\\n\", strings.Replace(key, \"/\", \".\", -1), result[0].Value)\n config[strings.Replace(key, \"/\", \"-\", -1)] = result[0].Value \n }\n }\n\n // Dump file\n charmConfig := make(map[string]interface{})\n charmConfig[jj.id(user, service)] = config\n log.Infof(\"serializing config\")\n out, err := goyaml.Marshal(charmConfig)\n if err != nil { return \"\", err }\n filePath := filepath.Join(\"/tmp\", user + \"-config.yaml\")\n log.Infof(\"dump configuration into %s\\n\", filePath)\n if err := ioutil.WriteFile(filePath, out, 0666); err != nil {\n return \"\", err\n }\n\n return filePath, nil\n}", "func confLoadInternal(path string) error {\n\t// Open configuration file\n\tini, err := OpenIniFile(path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\terr = nil\n\t\t}\n\t\treturn err\n\t}\n\n\tdefer ini.Close()\n\n\t// Extract options\n\tfor err == nil {\n\t\tvar rec *IniRecord\n\t\trec, err = ini.Next()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tswitch rec.Section {\n\t\tcase \"network\":\n\t\t\tswitch rec.Key {\n\t\t\tcase \"http-min-port\":\n\t\t\t\terr = confLoadIPPortKey(&Conf.HTTPMinPort, rec)\n\t\t\tcase \"http-max-port\":\n\t\t\t\terr = confLoadIPPortKey(&Conf.HTTPMaxPort, rec)\n\t\t\tcase \"dns-sd\":\n\t\t\t\terr = confLoadBinaryKey(&Conf.DNSSdEnable, rec, \"disable\", \"enable\")\n\t\t\tcase \"interface\":\n\t\t\t\terr = confLoadBinaryKey(&Conf.LoopbackOnly, rec, \"all\", \"loopback\")\n\t\t\tcase \"ipv6\":\n\t\t\t\terr = confLoadBinaryKey(&Conf.IPV6Enable, rec, \"disable\", \"enable\")\n\t\t\t}\n\t\tcase \"logging\":\n\t\t\tswitch rec.Key {\n\t\t\tcase \"device-log\":\n\t\t\t\terr = confLoadLogLevelKey(&Conf.LogDevice, rec)\n\t\t\tcase \"main-log\":\n\t\t\t\terr = confLoadLogLevelKey(&Conf.LogMain, rec)\n\t\t\tcase \"console-log\":\n\t\t\t\terr = confLoadLogLevelKey(&Conf.LogConsole, rec)\n\t\t\tcase \"console-color\":\n\t\t\t\terr = confLoadBinaryKey(&Conf.ColorConsole, rec, \"disable\", \"enable\")\n\t\t\tcase \"max-file-size\":\n\t\t\t\terr = confLoadSizeKey(&Conf.LogMaxFileSize, rec)\n\t\t\tcase \"max-backup-files\":\n\t\t\t\terr = confLoadUintKey(&Conf.LogMaxBackupFiles, rec)\n\t\t\t}\n\t\t}\n\t}\n\n\tif err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\t// Validate configuration\n\tif Conf.HTTPMinPort >= Conf.HTTPMaxPort {\n\t\treturn errors.New(\"http-min-port must be less that http-max-port\")\n\t}\n\n\treturn nil\n}", "func addMetaObjConfigDir(\n\tconfigFiles []CfgMeta,\n\tconfigDir string,\n\tserver *Server,\n\tlocationParams map[string]configProfileParams, // map[configFile]params; 'location' and 'URL' Parameters on serverHostName's Profile\n\turiSignedDSes []tc.DeliveryServiceName,\n\tdses map[tc.DeliveryServiceName]DeliveryService,\n\tcacheGroupArr []tc.CacheGroupNullable,\n\ttopologies []tc.Topology,\n\tatsMajorVersion uint,\n) ([]CfgMeta, []string, error) {\n\twarnings := []string{}\n\n\tif server.Cachegroup == nil {\n\t\treturn nil, warnings, errors.New(\"server missing Cachegroup\")\n\t}\n\n\tcacheGroups, err := makeCGMap(cacheGroupArr)\n\tif err != nil {\n\t\treturn nil, warnings, errors.New(\"making CG map: \" + err.Error())\n\t}\n\n\t// Note there may be multiple files with the same name in different directories.\n\tconfigFilesM := map[string][]CfgMeta{} // map[fileShortName]CfgMeta\n\tfor _, fi := range configFiles {\n\t\tconfigFilesM[fi.Name] = append(configFilesM[fi.Path], fi)\n\t}\n\n\t// add all strictly required files, all of which should be in the base config directory.\n\t// If they don't exist, create them.\n\t// If they exist with a relative path, prepend configDir.\n\t// If any exist with a relative path, or don't exist, and configDir is empty, return an error.\n\tfor _, fileName := range requiredFiles(atsMajorVersion) {\n\t\tif _, ok := configFilesM[fileName]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tif configDir == \"\" {\n\t\t\treturn nil, warnings, errors.New(\"required file '\" + fileName + \"' has no location Parameter, and ATS config directory not found.\")\n\t\t}\n\t\tconfigFilesM[fileName] = []CfgMeta{{\n\t\t\tName: fileName,\n\t\t\tPath: configDir,\n\t\t}}\n\t}\n\n\tfor fileName, fis := range configFilesM {\n\t\tnewFis := []CfgMeta{}\n\t\tfor _, fi := range fis {\n\t\t\tif !filepath.IsAbs(fi.Path) {\n\t\t\t\tif configDir == \"\" {\n\t\t\t\t\treturn nil, warnings, errors.New(\"file '\" + fileName + \"' has location Parameter with relative path '\" + fi.Path + \"', but ATS config directory was not found.\")\n\t\t\t\t}\n\t\t\t\tabsPath := filepath.Join(configDir, fi.Path)\n\t\t\t\tfi.Path = absPath\n\t\t\t}\n\t\t\tnewFis = append(newFis, fi)\n\t\t}\n\t\tconfigFilesM[fileName] = newFis\n\t}\n\n\tnameTopologies := makeTopologyNameMap(topologies)\n\n\tfor _, ds := range dses {\n\t\tif ds.XMLID == nil {\n\t\t\twarnings = append(warnings, \"got Delivery Service with nil XMLID - not considering!\")\n\t\t\tcontinue\n\t\t}\n\n\t\terr := error(nil)\n\t\t// Note we log errors, but don't return them.\n\t\t// If an individual DS has an error, we don't want to break the rest of the CDN.\n\t\tif ds.Topology != nil && *ds.Topology != \"\" {\n\t\t\ttopology := nameTopologies[TopologyName(*ds.Topology)]\n\n\t\t\tplacement, err := getTopologyPlacement(tc.CacheGroupName(*server.Cachegroup), topology, cacheGroups, &ds)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, warnings, errors.New(\"getting topology placement: \" + err.Error())\n\t\t\t}\n\t\t\tif placement.IsFirstCacheTier {\n\t\t\t\tif (ds.FirstHeaderRewrite != nil && *ds.FirstHeaderRewrite != \"\") || ds.MaxOriginConnections != nil || ds.ServiceCategory != nil {\n\t\t\t\t\tfileName := FirstHeaderRewriteConfigFileName(*ds.XMLID)\n\t\t\t\t\tif configFilesM, err = ensureConfigFile(configFilesM, fileName, configDir); err != nil {\n\t\t\t\t\t\twarnings = append(warnings, \"ensuring config file '\"+fileName+\"': \"+err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif placement.IsInnerCacheTier {\n\t\t\t\tif (ds.InnerHeaderRewrite != nil && *ds.InnerHeaderRewrite != \"\") || ds.MaxOriginConnections != nil || ds.ServiceCategory != nil {\n\t\t\t\t\tfileName := InnerHeaderRewriteConfigFileName(*ds.XMLID)\n\t\t\t\t\tif configFilesM, err = ensureConfigFile(configFilesM, fileName, configDir); err != nil {\n\t\t\t\t\t\twarnings = append(warnings, \"ensuring config file '\"+fileName+\"': \"+err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif placement.IsLastCacheTier {\n\t\t\t\tif (ds.LastHeaderRewrite != nil && *ds.LastHeaderRewrite != \"\") || ds.MaxOriginConnections != nil || ds.ServiceCategory != nil {\n\t\t\t\t\tfileName := LastHeaderRewriteConfigFileName(*ds.XMLID)\n\t\t\t\t\tif configFilesM, err = ensureConfigFile(configFilesM, fileName, configDir); err != nil {\n\t\t\t\t\t\twarnings = append(warnings, \"ensuring config file '\"+fileName+\"': \"+err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if strings.HasPrefix(server.Type, tc.EdgeTypePrefix) {\n\t\t\tif (ds.EdgeHeaderRewrite != nil || ds.MaxOriginConnections != nil || ds.ServiceCategory != nil) &&\n\t\t\t\tstrings.HasPrefix(server.Type, tc.EdgeTypePrefix) {\n\t\t\t\tfileName := \"hdr_rw_\" + *ds.XMLID + \".config\"\n\t\t\t\tif configFilesM, err = ensureConfigFile(configFilesM, fileName, configDir); err != nil {\n\t\t\t\t\twarnings = append(warnings, \"ensuring config file '\"+fileName+\"': \"+err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t} else if strings.HasPrefix(server.Type, tc.MidTypePrefix) {\n\t\t\tif (ds.MidHeaderRewrite != nil || ds.MaxOriginConnections != nil || ds.ServiceCategory != nil) &&\n\t\t\t\tds.Type != nil && ds.Type.UsesMidCache() &&\n\t\t\t\tstrings.HasPrefix(server.Type, tc.MidTypePrefix) {\n\t\t\t\tfileName := \"hdr_rw_mid_\" + *ds.XMLID + \".config\"\n\t\t\t\tif configFilesM, err = ensureConfigFile(configFilesM, fileName, configDir); err != nil {\n\t\t\t\t\twarnings = append(warnings, \"ensuring config file '\"+fileName+\"': \"+err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ds.RegexRemap != nil {\n\t\t\tconfigFile := \"regex_remap_\" + *ds.XMLID + \".config\"\n\t\t\tif configFilesM, err = ensureConfigFile(configFilesM, configFile, configDir); err != nil {\n\t\t\t\twarnings = append(warnings, \"ensuring config file '\"+configFile+\"': \"+err.Error())\n\t\t\t}\n\t\t}\n\t\tif ds.SigningAlgorithm != nil && *ds.SigningAlgorithm == tc.SigningAlgorithmURLSig {\n\t\t\tconfigFile := \"url_sig_\" + *ds.XMLID + \".config\"\n\t\t\tif configFilesM, err = ensureConfigFile(configFilesM, configFile, configDir); err != nil {\n\t\t\t\twarnings = append(warnings, \"ensuring config file '\"+configFile+\"': \"+err.Error())\n\t\t\t}\n\t\t}\n\t\tif ds.SigningAlgorithm != nil && *ds.SigningAlgorithm == tc.SigningAlgorithmURISigning {\n\t\t\tconfigFile := \"uri_signing_\" + *ds.XMLID + \".config\"\n\t\t\tif configFilesM, err = ensureConfigFile(configFilesM, configFile, configDir); err != nil {\n\t\t\t\twarnings = append(warnings, \"ensuring config file '\"+configFile+\"': \"+err.Error())\n\t\t\t}\n\t\t}\n\t}\n\n\tnewFiles := []CfgMeta{}\n\tfor _, fis := range configFilesM {\n\t\tfor _, fi := range fis {\n\t\t\tnewFiles = append(newFiles, fi)\n\t\t}\n\t}\n\treturn newFiles, warnings, nil\n}", "func getConfFilePath(root, clusterName string) string {\n\treturn fmt.Sprintf(\"%s/%s.config\", root, clusterName)\n}", "func Cfg() []byte {\n\treturn []byte(`# Pattern matching mode\n# auto = matches automatically a pattern\n# container-number = matches a container number\n# owner = matches a three letter owner code\n# owner-equipment-category = matches a three letter owner code with equipment category ID\n# size-type = matches length, width+height and type code\n` + Pattern + `: ` + PatternDefVal + `\n\n# Output mode\n# auto = for a single line 'fancy' and for multiple lines 'csv' output \n# csv = machine readable CSV output\n# fancy = human readable fancy output\n` + Output + `: ` + OutputDefVal + `\n\n# No header for CSV output\n` + NoHeader + `: ` + fmt.Sprintf(\"%t\", NoHeaderDefVal) + `\n\n# Separators\n#\n# ABC U 123456 0 20 G1\n# ↑ ↑ ↑ ↑ ↑\n# │ │ │ │ └─ ` + SepST + `\n# │ │ │ │\n# │ │ │ └─ ` + SepCS + `\n# │ │ │\n# │ │ └─ ` + SepSC + `\n# │ │\n# │ └─ ` + SepES + `\n# │\n# └─ ` + SepOE + `\n#\n` + SepOE + `: '` + SepOEDefVal + `'\n` + SepES + `: '` + SepESDefVal + `'\n` + SepSC + `: '` + SepSCDefVal + `'\n` + SepCS + `: '` + SepCSDefVal + ` '\n` + SepST + `: '` + SepSTDefVal + `'\n`)\n}", "func logConfig(logLevel string) (string, error) {\n\tlogConfigTemplate := `\nLOG {\n\tdefault_log_level = {{.LogLevel}};\n\tComponents {\n\t\tALL = {{.LogLevel}};\n\t}\n}`\n\tlogConfigData := nfsLogConfig{\n\t\tLogLevel: logLevel,\n\t}\n\treturn renderConfig(\"logConfig\", logConfigTemplate, logConfigData)\n}", "func init() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\":: \")\n\n\tif XDG_CONFIG_HOME == \"\" {\n\t\tXDG_CONFIG_HOME = filepath.Join(os.Getenv(\"HOME\"), \".config\")\n\t}\n\n\tif XDG_DATA_DIRS == \"\" {\n\t\tXDG_DATA_DIRS = \"/usr/local/share/:/usr/share\"\n\t}\n\n\tcache.actions = make(map[string]string)\n\tcache.actionFiles = make(map[string]string)\n\tcache.scriptFiles = make(map[string]string)\n\n\tconfig = os.Getenv(\"DEMLORC\")\n\tif config == \"\" {\n\t\tconfig = filepath.Join(XDG_CONFIG_HOME, application, application+\"rc\")\n\t}\n}", "func preConfigureCallback(vars resource.PropertyMap, c shim.ResourceConfig) error {\n\treturn nil\n}", "func setFSMultipartsConfigPath(configPath string) {\n\tcustomMultipartsConfigPath = configPath\n}", "func init() {\n\ttypes.AllowUserExec = append(types.AllowUserExec, []byte(Zksync))\n\t//注册合约启用高度\n\ttypes.RegFork(Zksync, InitFork)\n\ttypes.RegExec(Zksync, InitExecutor)\n}", "func initBaseConf() {\n\tssLEnable := false\n\tif viper.GetBool(defaultEnvHttpsEnable) {\n\t\tssLEnable = true\n\t} else {\n\t\tssLEnable = viper.GetBool(\"sslEnable\")\n\t}\n\trunMode := viper.GetString(\"runmode\")\n\tvar apiBase string\n\tif \"debug\" == runMode {\n\t\tapiBase = viper.GetString(\"dev_url\")\n\t} else if \"test\" == runMode {\n\t\tapiBase = viper.GetString(\"test_url\")\n\t} else {\n\t\tapiBase = viper.GetString(\"prod_url\")\n\t}\n\n\turi, err := url.Parse(apiBase)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tbaseHOSTByEnv := viper.GetString(defaultEnvHost)\n\tif baseHOSTByEnv != \"\" {\n\t\turi.Host = baseHOSTByEnv\n\t\tapiBase = uri.String()\n\t} else {\n\t\tisAutoHost := viper.GetBool(defaultEnvAutoGetHost)\n\t\tSugar().Debugf(\"isAutoHost %v\", isAutoHost)\n\t\tif isAutoHost {\n\t\t\tipv4, err := sys.NetworkLocalIP()\n\t\t\tif err == nil {\n\t\t\t\taddrStr := viper.GetString(\"addr\")\n\t\t\t\tvar proc string\n\t\t\t\tif ssLEnable {\n\t\t\t\t\tproc = \"https\"\n\t\t\t\t} else {\n\t\t\t\t\tproc = \"http\"\n\t\t\t\t}\n\t\t\t\tapiBase = fmt.Sprintf(\"%v://%v%v\", proc, ipv4, addrStr)\n\t\t\t}\n\t\t}\n\t}\n\n\tif ssLEnable {\n\t\tapiBase = strings.Replace(apiBase, \"http://\", \"https://\", 1)\n\t}\n\tSugar().Debugf(\"config file uri.Host %v\", uri.Host)\n\tSugar().Debugf(\"apiBase %v\", apiBase)\n\tbaseConf = BaseConf{\n\t\tBaseURL: apiBase,\n\t\tSSLEnable: ssLEnable,\n\t}\n}", "func TestConfig(t *testing.T) {\n\t// Register gomega fail handler\n\tRegisterFailHandler(Fail)\n\n\t// Have go's testing package run package specs\n\tRunSpecs(t, \"go-utils suite\")\n}", "func LoadConfig() {\n\n\terr := envconfig.Process(\"cosr\", &Config)\n\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n}", "func addRonDirConfigs(wd string, configs *[]*RawConfig, withHomeDirectory bool) {\n\tdirs := findConfigDirs(wd, withHomeDirectory)\n\tfiles := findConfigDirFiles(dirs)\n\tfor _, file := range files {\n\t\tconf, err := LoadConfigFile(file)\n\t\tif err != nil {\n\t\t\tfmt.Println(color.Red(err.Error()))\n\t\t\tcontinue\n\t\t}\n\t\t*configs = append(*configs, conf)\n\t}\n}", "func renderMultusConfig(manifestDir, defaultNetworkType string, useDHCP bool, useWhereabouts bool, apihost, apiport string, infra bootstrap.InfraStatus) ([]*uns.Unstructured, error) {\n\tobjs := []*uns.Unstructured{}\n\n\t// render the manifests on disk\n\tdata := render.MakeRenderData()\n\tdata.Data[\"ReleaseVersion\"] = os.Getenv(\"RELEASE_VERSION\")\n\tdata.Data[\"MultusImage\"] = os.Getenv(\"MULTUS_IMAGE\")\n\tdata.Data[\"CNIPluginsImage\"] = os.Getenv(\"CNI_PLUGINS_IMAGE\")\n\tdata.Data[\"BondCNIPluginImage\"] = os.Getenv(\"BOND_CNI_PLUGIN_IMAGE\")\n\tdata.Data[\"WhereaboutsImage\"] = os.Getenv(\"WHEREABOUTS_CNI_IMAGE\")\n\tdata.Data[\"EgressRouterImage\"] = os.Getenv(\"EGRESS_ROUTER_CNI_IMAGE\")\n\tdata.Data[\"RouteOverrideImage\"] = os.Getenv(\"ROUTE_OVERRRIDE_CNI_IMAGE\")\n\tdata.Data[\"KUBERNETES_SERVICE_HOST\"] = apihost\n\tdata.Data[\"KUBERNETES_SERVICE_PORT\"] = apiport\n\tdata.Data[\"RenderDHCP\"] = useDHCP\n\tdata.Data[\"RenderIpReconciler\"] = useWhereabouts\n\tdata.Data[\"MultusCNIConfDir\"] = MultusCNIConfDir\n\tdata.Data[\"SystemCNIConfDir\"] = SystemCNIConfDir\n\tdata.Data[\"DefaultNetworkType\"] = defaultNetworkType\n\tdata.Data[\"MultusSocketParentDir\"] = MultusSocketParentDir\n\tdata.Data[\"CNIBinDir\"] = CNIBinDir\n\tdata.Data[\"CniSysctlAllowlist\"] = \"default-cni-sysctl-allowlist\"\n\tdata.Data[\"HTTP_PROXY\"] = \"\"\n\tdata.Data[\"HTTPS_PROXY\"] = \"\"\n\tdata.Data[\"NO_PROXY\"] = \"\"\n\tif infra.ControlPlaneTopology == configv1.ExternalTopologyMode {\n\t\tdata.Data[\"HTTP_PROXY\"] = infra.Proxy.HTTPProxy\n\t\tdata.Data[\"HTTPS_PROXY\"] = infra.Proxy.HTTPSProxy\n\t\tdata.Data[\"NO_PROXY\"] = infra.Proxy.NoProxy\n\t}\n\n\tmanifests, err := render.RenderDir(filepath.Join(manifestDir, \"network/multus\"), &data)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to render multus manifests\")\n\t}\n\tobjs = append(objs, manifests...)\n\treturn objs, nil\n}", "func getUrl(config map[string]string, path string) (string) {\n url := fmt.Sprint(\"https://\", config[\"CONTROL_SERVICE\"], \":\", config[\"CONTROL_PORT\"], path)\n return url\n}", "func RelativizeAuthInfoLocalPaths(authInfo *clientcmdapi.AuthInfo) error {\n\tif len(authInfo.LocationOfOrigin) == 0 {\n\t\treturn fmt.Errorf(\"no location of origin for %v\", authInfo)\n\t}\n\tbase, err := filepath.Abs(filepath.Dir(authInfo.LocationOfOrigin))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not determine the absolute path of config file %s: %v\", authInfo.LocationOfOrigin, err)\n\t}\n\n\tif err := ResolvePaths(GetAuthInfoFileReferences(authInfo), base); err != nil {\n\t\treturn err\n\t}\n\tif err := RelativizePathWithNoBacksteps(GetAuthInfoFileReferences(authInfo), base); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (mod *Module)configValidate()error{\n\tif mod.config.Unique != \"\"{\n\t\tif mod.parent.uniqueExists(mod.config.Unique){//at this stage the Module hasnt been added to the parent, so it is safe to check that none exist\n\t\t\treturn errors.New(\"There is a Module already loaded with that unique identifier!\")\n\t\t}\n\t}\n\treturn nil\n}" ]
[ "0.53505033", "0.5261206", "0.5253118", "0.5253118", "0.5253118", "0.5253118", "0.5253118", "0.5253118", "0.5251652", "0.5201222", "0.5197413", "0.51820076", "0.51452744", "0.514169", "0.51257426", "0.5091423", "0.5078814", "0.49299353", "0.49148425", "0.4893956", "0.4883172", "0.4855111", "0.48101267", "0.4805985", "0.4770058", "0.4769603", "0.4760696", "0.4759699", "0.47562703", "0.47545946", "0.4753978", "0.47515437", "0.47496822", "0.47387588", "0.47371647", "0.47331223", "0.47288936", "0.472287", "0.4697795", "0.46849924", "0.46827412", "0.46745017", "0.46670946", "0.46575043", "0.46500763", "0.46482158", "0.46392405", "0.46316162", "0.462181", "0.46196172", "0.46194795", "0.46155697", "0.46119973", "0.46088699", "0.4603652", "0.46035606", "0.4602231", "0.45998192", "0.45966", "0.45940563", "0.45887533", "0.4586039", "0.45829386", "0.45737913", "0.45700657", "0.4565349", "0.45576316", "0.45544246", "0.45423025", "0.4541541", "0.45384222", "0.4536586", "0.45331267", "0.4532939", "0.4528229", "0.45250264", "0.4520841", "0.4520659", "0.45197383", "0.45192388", "0.4518468", "0.451372", "0.45072803", "0.4504613", "0.44989756", "0.44956183", "0.4491548", "0.4488266", "0.44871533", "0.44871247", "0.44856957", "0.44836032", "0.44813323", "0.44805545", "0.4476567", "0.44690982", "0.4467931", "0.44614622", "0.44614387", "0.4461363" ]
0.57287395
0
Read the current configuration
func (b *backend) pathConfigRead(ctx context.Context, req *logical.Request, _ *framework.FieldData) (*logical.Response, error) { c, err := b.GetConfig(ctx, req.Storage) if err != nil { return nil, err } return &logical.Response{ Data: map[string]interface{}{ "endpoint": c.Endpoint, "accessKeyId": c.AccessKeyId, "secretAccessKey": c.SecretAccessKey, "useSSL": c.UseSSL, }, }, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func readConf() error {\n\tbuf := new(bytes.Buffer)\n\tif _, err := os.Stat(ConfigFile); os.IsNotExist(err) {\n\t\terr := ioutil.WriteFile(ConfigFile, []byte(ConfigFileTemplate), 0644)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tbuf.Reset()\n\ttomlData, err := os.Open(ConfigFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = io.Copy(buf, tomlData)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttomlData.Close()\n\tif _, err := toml.Decode(buf.String(), &pubConf); err != nil {\n\t\treturn err\n\t}\n\tif err := json.Unmarshal([]byte(pubConf.Sample.Storage), &sampleJobs); err != nil {\n\t\treturn err\n\t}\n\tparseConf()\n\treturn nil\n}", "func readConfig() {\n\t// Is a configuration file set?\n\tif config == \"\" {\n\t\treturn\n\t}\n\n\t// Select it\n\tsetConfigFile(config)\n\n\t// Read the configuration\n\tif err := readInConfig(); err == nil {\n\t\tfmt.Fprintf(stdout, \"Using configuration file %s\\n\", configFileUsed())\n\t}\n}", "func readConfiguration() (configuration, error) {\n\thomeDir, err := homedir.Dir()\n\tif err != nil {\n\t\treturn configuration{}, err\n\t}\n\n\tconfigFilePath := filepath.Join(homeDir, \".telelog.conf\")\n\n\t// https://stackoverflow.com/questions/12518876/how-to-check-if-a-file-exists-in-go\n\tif _, err := os.Stat(configFilePath); os.IsNotExist(err) {\n\t\tif *verbose {\n\t\t\tfmt.Printf(\"config [%s] does not exist\\n\", configFilePath)\n\t\t}\n\t\treturn configuration{}, nil\n\t}\n\n\t// https://stackoverflow.com/questions/16465705/how-to-handle-configuration-in-go\n\tfile, err := os.Open(configFilePath)\n\tif err != nil {\n\t\tif *verbose {\n\t\t\tfmt.Printf(\"could not open config [%s]\\n\", configFilePath)\n\t\t}\n\t\treturn configuration{}, err\n\t}\n\tdefer file.Close()\n\n\tdecoder := json.NewDecoder(file)\n\tconf := configuration{}\n\terr = decoder.Decode(&conf)\n\tif err != nil {\n\t\tif *verbose {\n\t\t\tfmt.Printf(\"could not decode config [%s]\\n\", configFilePath)\n\t\t}\n\t\treturn configuration{}, err\n\t}\n\n\treturn conf, nil\n}", "func readConfig() {\n\tconfigPath := io.FixPrefixPath(viper.GetString(\"datadir\"), viper.GetString(\"config\"))\n\n\tif io.FileExists(configPath) {\n\t\tmergeLocalConfig(configPath)\n\t} else {\n\t\tfmt.Println(\"config file not exist \", configPath)\n\t\tmergeOnlineConfig(viper.GetString(\"config\"))\n\t}\n\n\t// load injected config from ogbootstrap if any\n\tinjectedPath := io.FixPrefixPath(viper.GetString(\"datadir\"), \"injected.toml\")\n\tif io.FileExists(injectedPath) {\n\t\tmergeLocalConfig(injectedPath)\n\t}\n\n\tmergeEnvConfig()\n\tb, err := common.PrettyJson(viper.AllSettings())\n\tpanicIfError(err, \"dump json\")\n\tfmt.Println(b)\n}", "func readConfig() (*whatphone.API, error) {\n\tconfigFile, err := getConfigFile()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tf, err := os.Open(configFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\treturn loadConfig(f)\n}", "func ReadConfig() Info {\n\treturn databases\n}", "func ReadCurrent() *AppConfig {\n\tconfigPath := os.Getenv(\"OAUTH_CONFIG_PATH\")\n\tif configPath == \"\" {\n\t\tconfigPath = \"../../../config/default.json\"\n\t}\n\n\treturn Read(configPath)\n}", "func configRead() (string, error) {\n\n\tfhndl, err := ioutil.ReadFile(\"/etc/testpool/testpool.yml\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\troot, err := simpleyaml.NewYaml(fhndl)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvalue := root.GetPath(\"tpldaemon\", \"profile\", \"log\")\n\treturn value.String()\n\n}", "func ReadConfig() AdminInfo {\n\treturn c\n}", "func ReadConfig() View {\n\treturn viewInfo\n}", "func ReadConfing() (config.Configuration, error) {\n\tvar config config.Configuration\n\n\tjsonFile, err := os.Open(\"./config/config.json\")\n\tdefer jsonFile.Close()\n\n\tif err != nil {\n\t\terr = errors.New(\"error opening config.json file, \" + err.Error())\n\t\tlog.Println(err)\n\t\treturn config, err\n\t}\n\n\tbytes, err := ioutil.ReadAll(jsonFile)\n\n\tif err != nil {\n\t\terr = errors.New(\"error reading config.json file data, \" + err.Error())\n\t\tlog.Println(err)\n\t\treturn config, err\n\t}\n\n\tjson.Unmarshal(bytes, &config)\n\treturn config, nil\n}", "func (s *store) Read() (*Config, error) {\n\tbody, err := ioutil.ReadFile(fmt.Sprintf(\"%s/%s\", s.path, configName))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar conf Config\n\tif err := json.Unmarshal(body, &conf); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &conf, nil\n}", "func readConfiguration(path string) (configuration, error) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\tlog.Printf(\"Error configuration file %s\\n\", path)\n\t\treturn configuration{}, err\n\t}\n\n\trawConfiguration := make(map[string]string)\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\tt := scanner.Text()\n\t\tlog.Print(t)\n\t\tif !strings.HasPrefix(t, \"#\") {\n\t\t\tl := strings.Split(t, \":\")\n\t\t\trawConfiguration[strings.TrimSpace(l[0])] = strings.TrimSpace(l[1])\n\t\t}\n\n\t}\n\tlog.Print(rawConfiguration)\n\tlog.Printf(\"Connecting to %s\", os.Getenv(rawConfiguration[dbEnvKey]))\n\n\twebport, err := strconv.Atoi(rawConfiguration[webPortKey])\n\tdbport := 0\n\tdbportString, ok := rawConfiguration[dbPortKey]\n\tif ok {\n\t\tdbport, err = strconv.Atoi(dbportString)\n\t}\n\n\treturn configuration{\n\t\tdbConfiguration{\n\t\t\thost: rawConfiguration[dbHostKey],\n\t\t\tport: dbport,\n\t\t\tdb: rawConfiguration[dbNameKey],\n\t\t\tuser: rawConfiguration[dbUserKey],\n\t\t\tpassword: rawConfiguration[dbPasswordKey],\n\t\t},\n\t\trawConfiguration[dbEnvKey],\n\t\twebport,\n\t}, err\n}", "func RRReadConfig() {\n\tfolderPath, err := osext.ExecutableFolder()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t// fmt.Printf(\"Executable folder = %s\\n\", folderPath)\n\tfname := folderPath + \"/conf.json\"\n\t_, err = os.Stat(fname)\n\tif nil != err {\n\t\tfmt.Printf(\"RRReadConfig: error reading %s: %v\\n\", fname, err)\n\t\tos.Exit(1)\n\t}\n\tcontent, err := ioutil.ReadFile(fname)\n\tErrcheck(err)\n\tErrcheck(json.Unmarshal(content, &AppConfig))\n\t// fmt.Printf(\"RRReadConfig: AppConfig = %#v\\n\", AppConfig)\n}", "func read(fileName string) (*Configuration, error) {\n\tif fileName == \"\" {\n\t\treturn Config, fmt.Errorf(\"Empty file name\")\n\t}\n\tfile, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn Config, err\n\t}\n\tdecoder := json.NewDecoder(file)\n\terr = decoder.Decode(Config)\n\tif err == nil {\n\t\tlog.Infof(\"Read config: %s\", fileName)\n\t} else {\n\t\tlog.Fatal(\"Cannot read config file:\", fileName, err)\n\t}\n\tif err := Config.postReadAdjustments(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn Config, err\n}", "func readConfig() Configuration {\n\tfmt.Println(\"Reading configuration file\")\n\n\tdir, _ := filepath.Abs(filepath.Dir(os.Args[0]))\n\tfilepath := []string{dir, \"config.json\"}\n\n\tfile, _ := os.Open(strings.Join(filepath, \"\\\\\"))\n\tdecoder := json.NewDecoder(file)\n\tconfiguration := Configuration{}\n\terr := decoder.Decode(&configuration)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn configuration\n}", "func readConfig() error {\n\tviper.SetConfigName(defaultConfigName)\n\tviper.SetConfigType(defaultConfigType)\n\tviper.AddConfigPath(defaultConfigPath)\n\n\tviper.WatchConfig()\n\n\t// Read the config file.\n\treturn viper.ReadInConfig()\n}", "func ReadConfig() CheckoutInfo {\n\treturn z\n}", "func readConfig(confFile, confPath, confType string) {\n\tviper.SetConfigName(confFile)\n\tviper.AddConfigPath(confPath)\n\terr := viper.ReadInConfig()\n\tif err != nil {\n\t\tfmt.Println(\"Error in reading config file. Exiting \", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\t//get all config data into a conf struct\n\tConf = map[string]string{\n\t\t\"scan_success\": viper.GetString(\"common.scan_success\"),\n\t\t\"scan_failure\": viper.GetString(\"common.scan_failure\"),\n\t\t\"sort_success\": viper.GetString(\"common.sort_success\"),\n\t\t\"sort_failure\": viper.GetString(\"common.sort_failure\"),\n\t\t\"inst_name\": viper.GetString(confType + \".inst_name\"),\n\t\t\"cont\": viper.GetString(confType + \".cont\"),\n\t\t\"scan_url\": viper.GetString(confType + \".scan_url\"),\n\t\t\"sort_url\": viper.GetString(confType + \".sort_url\"),\n\t\t\"feedback_url\": viper.GetString(confType + \".feedback_url\"),\n\t\t\"wgh_url\": viper.GetString(confType + \".wgh_url\"),\n\t\t\"event_url\": viper.GetString(confType + \".event_url\"),\n\t\t\"fault_code_url\": viper.GetString(confType + \".fault_code_url\"),\n\t\t\"image_url\": viper.GetString(confType + \".image_url\"),\n\t\t\"initConfig_url\": viper.GetString(confType + \".initConfig_url\"),\n\t}\n\tfor k, v := range Conf {\n\t\tfmt.Printf(\"%s : %s\\n\", k, v)\n\t}\n}", "func(c*Config) Read( ){\n\tif _, err := toml.DecodeFile(\"config.toml\", &c); err != nil{\n\t\tlog.Fatal(err)\n\t}\n}", "func Read() (*Config, error) {\n\tcfg := &Config{}\n\n\tif err := env.Parse(cfg); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cfg, nil\n}", "func readConfig(configPath string) (ConfigurationParameters, error) {\n\tvar config ConfigurationParameters\n\n\tlog.Print(\"Reading config file...\")\n\n\tfile, err := ioutil.ReadFile(configPath)\n\n\tif err != nil {\n\t\tlog.Print(err.Error())\n\t\treturn config, err\n\t}\n\n\tlog.Print(string(file))\n\n\terr = json.Unmarshal(file, &config)\n\tif err != nil {\n\t\tlog.Print(err.Error())\n\t\treturn config, err\n\t}\n\n\treturn config, nil\n}", "func (c *Config) Read() {\n\tif _, err := toml.DecodeFile(\"config.toml\", &c); err != nil { // decode file config.toml\n\t\tlog.Fatal(err)\n\t}\n}", "func readConfig() (config Config) {\n\tconfigJson, _ := Asset(\"config.json\")\n\terr := json.Unmarshal(configJson, &config)\n\tif err != nil {\n\t\tprintError(CONFIG_READ_ERROR + err.Error())\n\t}\n\treturn config\n}", "func Read() *Config {\n\tvar cfg Config\n\tvar cfgPath string\n\n\tcfgPath = os.Getenv(\"TOKEN_SVC_CONF\")\n\n\tif len(cfgPath) <= 0 {\n\t\tlog.Println(\"TOKEN_SVC_CONF env variable not set\")\n\t\tlog.Println(\"using default config value...\")\n\t\tcfg = defConfig()\n\t} else {\n\t\t_, err := toml.DecodeFile(cfgPath, &cfg)\n\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"unable to parse config: %v\", err.Error())\n\t\t}\n\t}\n\treturn &cfg\n}", "func get_conf() Configuration {\n\tfile, _ := os.Open(\"conf.json\")\n\tdecoder := json.NewDecoder(file)\n\t//configuration := make(Configuration)\n\tvar configuration Configuration\n\terr := decoder.Decode(&configuration)\n\tif err != nil {\n\t\tfmt.Println(\"get_conf: Decode error\", err)\n\t}\n\treturn configuration\n}", "func (m *settings) readConfig() {\n\tlog.Printf(\"Reading configuration...\")\n\tjsonBlob, err := ioutil.ReadFile(m.filename)\n\tif err != nil {\n\t\tlog.Printf(\"No config file found. Using new config file.\")\n\t\treturn\n\t}\n\tif err := json.Unmarshal(jsonBlob, &m.redirects); err != nil {\n\t\tlog.Printf(\"Error unmarshalling %s\", err)\n\t}\n}", "func ConfigRead() error {\n\n\t// As a convenience to all tools, generate a new random seed for each iteration\n\trand.Seed(time.Now().UnixNano())\n\trand.Seed(rand.Int63() ^ time.Now().UnixNano())\n\n\t// Read the config file\n\tcontents, err := ioutil.ReadFile(configSettingsPath())\n\tif os.IsNotExist(err) {\n\t\tConfigReset()\n\t\terr = nil\n\t} else if err == nil {\n\t\terr = json.Unmarshal(contents, &Config)\n\t\tif err != nil || Config.When == \"\" {\n\t\t\tConfigReset()\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"can't read configuration: %s\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn err\n\n}", "func ReadFromFile() (*Config, error) {\n\t// usr, err := user.Current()\n\t// if err != nil {\n\t// \tlog.Fatal(err)\n\t// }\n\n\t// configPath := path.Join(usr.HomeDir, `.matic-jagar/config/`)\n\t// log.Printf(\"Config Path : %s\", configPath)\n\n\tv := viper.New()\n\tv.AddConfigPath(\".\")\n\t// v.AddConfigPath(configPath)\n\tv.SetConfigName(\"config\")\n\tif err := v.ReadInConfig(); err != nil {\n\t\tlog.Fatalf(\"error while reading config.toml: %v\", err)\n\t}\n\n\tvar cfg Config\n\tif err := v.Unmarshal(&cfg); err != nil {\n\t\tlog.Fatalf(\"error unmarshaling config.toml to application config: %v\", err)\n\t}\n\n\tif err := cfg.Validate(); err != nil {\n\t\tlog.Fatalf(\"error occurred in config validation: %v\", err)\n\t}\n\n\treturn &cfg, nil\n}", "func (a *App) readConfig() {\n\tvar configLocation string\n\tif _, err := os.Stat(\"./configs\"); err == nil {\n\t\tconfigLocation = \"./configs\"\n\t}\n\n\ta.Config = config.NewEnvFile(configLocation)\n}", "func Read(filename string) error {\n\treturn cfg.Read(filename)\n}", "func readConfig() config {\n\tfile, err := ioutil.ReadFile(\"config.json\")\n\tif err != nil {\n\t\tlog.Fatalln(\"Error Opening Config File: \", err)\n\t}\n\tconfigData := config{}\n\n\terr = json.Unmarshal([]byte(file), &configData)\n\tif err != nil {\n\t\tlog.Fatalln(\"Error Parsing Config File: \", err)\n\t}\n\treturn configData\n}", "func readConfig(c *cli.Context) (service.Config, error) {\n\typath := c.GlobalString(\"config\")\n\tconfig := service.Config{}\n\tif _, err := os.Stat(ypath); err != nil {\n\t\treturn config, errors.New(\"config file path is not valid\")\n\t}\n\tydata, err := ioutil.ReadFile(ypath)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\terr = yaml.Unmarshal([]byte(ydata), &config)\n\treturn config, err\n}", "func Read(conf *Config, queue *task.Queue) []error {\n\tr := &configReader{queue: queue}\n\tr.read(conf)\n\treturn r.errors\n}", "func (s *GlobConfig) Read(id string) error {\n\tkey := globalConfigPath\n\treturn s.StateDriver.ReadState(key, s, json.Unmarshal)\n}", "func readConfigFile() {\n\n\tusr, err := user.Current()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlogger.Println(\"Reading config file...\")\n\n\tfileContents, err := ioutil.ReadFile(usr.HomeDir + \"/.autoq\")\n\n\tif err != nil {\n\t\tlogger.Fatalf(fmt.Sprintf(\"autoqctl: %v\\n\", err))\n\t}\n\n\tif err := json.Unmarshal(fileContents, &config); err != nil {\n\t\tlogger.Fatalf(\"Problem reading config: %s\", err)\n\t}\n\n\tlogger.Println(\"Using Autoq host: \" + config.Host)\n\n}", "func ReadConfigFile() {\n\tVarsConfig = Configuration{\n\t\tServer: ServerConfiguration{\n\t\t\tPort: os.Getenv(\"SERVER_PORT\"),\n\t\t},\n\t\tRedis: RedisConfiguration{\n\t\t\tHost: os.Getenv(\"REDIS_HOST\"),\n\t\t\tPoolSize: os.Getenv(\"REDIS_POOL_SIZE\"),\n\t\t},\n\t}\n\treturn\n}", "func ReadConfig(project string, opts ...option.ClientOption) (map[string]string, error) {\n\tctx := context.Background()\n\tclient, err := storage.NewClient(ctx, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbkt := client.Bucket(project + \"-cloud-robotics-config\")\n\treader, err := bkt.Object(\"config.sh\").NewReader(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer reader.Close()\n\n\tvars, err := getConfigFromReader(reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsetDefaultVars(vars)\n\treturn vars, nil\n}", "func Read() (Config, error) {\n\tviper.SetConfigName(\"config\")\n\tviper.SetConfigFile(File())\n\n\terr := viper.ReadInConfig()\n\tif err != nil {\n\t\treturn Config{\n\t\t\tAuths: []Auth{DefaultAuth},\n\t\t}, nil\n\t}\n\n\tconf := &Config{\n\t\tAuths: []Auth{},\n\t}\n\n\terr = mapstructure.Decode(viper.AllSettings(), conf)\n\tif err != nil {\n\t\tlog.Fatalf(\"%v\", err)\n\t}\n\n\tif len(conf.Auths) == 0 {\n\t\treturn Config{\n\t\t\tAuths: []Auth{DefaultAuth},\n\t\t}, nil\n\t}\n\n\treturn *conf, nil\n}", "func ReadConf() (*Conf, error) {\n\tviper.SetConfigName(\"config\")\n\tviper.SetConfigType(\"toml\")\n\tviper.AddConfigPath(\"$HOME/.smgmg\")\n\tviper.AddConfigPath(\".\")\n\n\t// defaults\n\tviper.SetDefault(\"store.file_names\", \"{{.FileName}}\")\n\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tif _, ok := err.(viper.ConfigFileNotFoundError); ok {\n\t\t\treturn nil, errors.New(\"Configuration file not found in ./config.toml or $HOME/.smgmg/config.toml\")\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif viper.GetString(\"authentication.username\") != \"\" {\n\t\tlog.Warnf(\"[DEPRECATION] Username configuration value is ignored. It is now retrieved automatically from SmugMug based on the authentication credentials.\")\n\t}\n\n\tcfg := &Conf{\n\t\tApiKey: viper.GetString(\"authentication.api_key\"),\n\t\tApiSecret: viper.GetString(\"authentication.api_secret\"),\n\t\tUserToken: viper.GetString(\"authentication.user_token\"),\n\t\tUserSecret: viper.GetString(\"authentication.user_secret\"),\n\t\tDestination: viper.GetString(\"store.destination\"),\n\t\tFilenames: viper.GetString(\"store.file_names\"),\n\t\tUseMetadataTimes: viper.GetBool(\"store.use_metadata_times\"),\n\t\tForceMetadataTimes: viper.GetBool(\"store.force_metadata_times\"),\n\t}\n\n\tcfg.overrideEnvConf()\n\n\tif !cfg.UseMetadataTimes && cfg.ForceMetadataTimes {\n\t\treturn nil, errors.New(\"Cannot use store.force_metadata_times without store.use_metadata_times\")\n\t}\n\n\treturn cfg, nil\n}", "func Get() Cfg {\n\treturn conf\n}", "func ReadConfiguration() (*models.Configuration) {\n\tpathToFile := os.Getenv(\"LOGGER_CONFIGURATION_FILE\")\n\tif _, err := os.Stat(\"/home/pi/go/src/go-goole-home-requests/configuration.yaml\"); !os.IsNotExist(err) {\n\t\tpathToFile = \"/home/pi/go/src/go-goole-home-requests/configuration.yaml\"\n\t} else {\n\t\tpathToFile = \"./configuration.yaml\"\n\t}\n\tyamlFile, err := ioutil.ReadFile(pathToFile)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar config *models.Configuration\n\n\terr = yaml.Unmarshal(yamlFile, &config)\n\tif err != nil {\n\t\tpanic(err)\n\t} else {\n\t\texecuteGoogleAssistantConfiguration(config)\n\t\tfmt.Printf(\"Configuration Loaded : %+v \\n\", config)\n\t}\n\n\treturn config\n}", "func configReader(conf string) {\n\tviper.AddConfigPath(\".\")\n\tviper.SetConfigFile(conf)\n\n\terr := viper.ReadInConfig()\n\tif err != nil {\n\t\tlog.Fatal(\"Fatal error, can't read the config file: \", err)\n\t}\n\n\t// Get basic settings\n\tregion = viper.GetString(\"region\")\n\tstackname = viper.GetString(\"stackname\")\n\n\t// Get all the values of variables under CF\n\t// and put them into a map\n\tcfvars = make(map[string]interface{})\n\tfor _, confvar := range viper.Sub(\"CF\").AllKeys() {\n\t\tif confvar != \"\" {\n\t\t\tconfval := viper.Get(\"CF.\" + confvar)\n\t\t\tcfvars[confvar] = confval\n\t\t}\n\t}\n}", "func (s *Service) readConfig() (*Config, error) {\n\tif _, err := os.Stat(s.Config); os.IsNotExist(err) {\n\t\treturn nil, err\n\t}\n\n\traw, err := ioutil.ReadFile(s.Config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcfg := &Config{}\n\terr = json.Unmarshal(raw, cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cfg, nil\n}", "func (conf *BuildConfig) Read(path string) error {\n\tf, err := os.Open(filepath.Clean(path))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tcloseErr := f.Close()\n\t\tif closeErr != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}()\n\tval, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(val, &conf.Config)\n\treturn err\n}", "func GetConfig() Configuration{\n\tcurrentPath := files.GetCurrentDirectory()\n\tjsonFile, err := os.Open(currentPath + \"/config.json\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Println(currentPath)\n\tdefer jsonFile.Close()\n\tbyteValue, _ := ioutil.ReadAll(jsonFile)\n\tvar configuration Configuration\n\tjson.Unmarshal(byteValue, &configuration)\n\treturn configuration\n}", "func readConfig(configFilePath string) *Config {\n\t// fmt.Println(\"doing readConfig\")\n\tfile, err := os.Open(configFilePath)\n\tdefer file.Close()\n\tdecoder := json.NewDecoder(file)\n\tconfig := new(Config)\n\terr = decoder.Decode(config)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn config\n}", "func Read(v *viper.Viper) error {\n\tif err := v.ReadInConfig(); err != nil {\n\t\tif errors.As(err, &viper.ConfigFileNotFoundError{}) {\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"read config file: %w\", err)\n\t}\n\treturn nil\n}", "func Read() Config {\n\tfile, err := os.Open(\"config.json\")\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not read config: %v\", err)\n\t}\n\tdefer file.Close()\n\tdecoder := json.NewDecoder(file)\n\tconfig := Config{}\n\terr = decoder.Decode(&config)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not read config: %v\", err)\n\t}\n\treturn config\n}", "func getConfig() Conf {\n\tfile, _ := os.Open(\"config/config.json\")\n\tdefer file.Close()\n\tdecoder := json.NewDecoder(file)\n\tConfig := defaultConfig()\n\terr := decoder.Decode(&Config)\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t}\n\treturn Config\n}", "func getCurrentConfiguration() (*Config, error) {\n\n\t_, err := os.Stat(configFileName)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\t_, err = initConfiguration()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\tbuffer, err := ioutil.ReadFile(configFileName)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tconfig := Config{}\n\terr = yaml.Unmarshal(buffer, &config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &config, nil\n}", "func ReadConfig() {\n\tconfigFile := \"config.json\"\n\tlog.Printf(\"ReadConfig: reading 'Configuration' from '%s'\", configFile)\n\tvar err error\n\tconf, err = loadConfig(configFile)\n\tif err == nil {\n\t\t//log.Printf(\"%+v\\n\", conf)\n\t\tlog.Printf(\"Configuration: \\n%v\", prettyPrintConf())\n\n\t} else {\n\t\tlog.Println(err)\n\t}\n}", "func ReadConfig() Database {\n\treturn databases\n}", "func Read() (*Config, error) {\n\tvar c *Config\n\n\t// Read json file\n\tif raw, err := ioutil.ReadFile(configPath); err == nil {\n\t\terr = json.Unmarshal(raw, &c)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\t// File doesn't exist, so create a new config\n\t\tfmt.Println(\"No config detected. Generating new config...\")\n\t\tc = &Config{}\n\t}\n\tif c.UserID == \"\" {\n\t\tfmt.Printf(\"No UserID present in config. Generating new UserID and \"+\n\t\t\t\"updating config at %s\\n\", configPath)\n\t\tuuid, err := uuid.NewV4()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tc.UserID = uuid.String()\n\t\tif err := c.Write(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn c, nil\n}", "func readConfig(name string, data interface{}) error {\n\tfile, err := os.Open(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\t_ = file.Close()\n\t}()\n\n\treturn json.NewDecoder(file).Decode(data)\n}", "func (c *Client) ReadConfiguration(freeswitchConfPath string) error {\n\tfile, err := os.Open(freeswitchConfPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\tdecoder := xml.NewDecoder(file)\n\tvar (\n\t\tvalues = make(map[string]string)\n\t\tkey string\n\t)\n\tfor {\n\t\ttoken, err := decoder.Token()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch token := token.(type) {\n\t\tcase xml.StartElement:\n\t\t\tkey = token.Name.Local\n\t\t\tif !(key == \"listen-port\" || key == \"listen-ip\" || key == \"password\") {\n\t\t\t\tkey = \"\"\n\t\t\t}\n\t\tcase xml.CharData:\n\t\t\tif key != \"\" {\n\t\t\t\tvalues[key] = strings.TrimSpace(string(token))\n\t\t\t}\n\t\tdefault:\n\t\t\tkey = \"\"\n\t\t}\n\t\tif len(values) == 3 {\n\t\t\tbreak\n\t\t}\n\t}\n\tfor k, v := range values {\n\t\tswitch k {\n\t\tcase \"listen-port\":\n\t\t\tif v, err := strconv.Atoi(v); err == nil {\n\t\t\t\tc.Port = uint16(v)\n\t\t\t} else {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase \"listen-ip\":\n\t\t\tc.Hostname = v\n\t\tcase \"password\":\n\t\t\tc.Password = v\n\t\t}\n\t}\n\treturn nil\n}", "func ReadConfig(data []byte) (Config, error) {\n\tconfig := NewConfig()\n\tif err := json.Unmarshal(data, &config); err != nil {\n\t\tlog.Printf(\"unable to unmarshal application configuration file data, error: %s\\n\", err.Error())\n\t\treturn config, err\n\t}\n\n\tif err := config.Validate(); err != nil {\n\t\treturn config, err\n\t}\n\n\tlog.Printf(\"Configuration loaded. Source type: %s, Destination type: %s\\n\", config.Source.Type, config.Destination.Type)\n\tlog.Printf(\"%v Sync sets found:\\n\", len(config.SyncSets))\n\n\tfor i, syncSet := range config.SyncSets {\n\t\tlog.Printf(\" %v) %s\\n\", i+1, syncSet.Name)\n\t}\n\n\treturn config, nil\n}", "func ReadConfig() *error {\n\tvar env = os.Getenv(\"ENV\")\n\n\tgame.Appartement.Bots = Config.Bots\n\tfile, err := os.Open(\"/env/config.\" + env + \".json\")\n\tif err != nil {\n\t\tlog.Println(prefixWarn, \"ENV must be of: 'localhost', 'dev' or 'prod'. starting with default configuration\")\n\t\treturn &err\n\t}\n\n\tdecoder := json.NewDecoder(file)\n\terr = decoder.Decode(&Config)\n\tif err != nil {\n\t\treturn &err\n\t}\n\n\treturn nil\n}", "func Read(path string) (*api.Config, error) {\n\tconfig, err := clientcmd.LoadFromFile(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not load kubeconfig from %s: %s\", path, err)\n\t}\n\treturn config, nil\n}", "func (b *Bot) ReadConfig(fn configCallback) {\n\tfn(b.conf)\n}", "func (m *Manager) readConfig() (readConfigCh chan *configEntry, doneCh chan bool) {\n\treadConfigCh, doneCh = make(chan *configEntry), make(chan bool)\n\tgo func() {\n\t\tresponse, err := m.etcdClient.Get(m.configPath, true, true)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Initial config not present. Monitoring changes on it from now on..\")\n\t\t} else {\n\t\t\taction := \"readingConfig\"\n\t\t\tm.processNode(response.Node, action, readConfigCh)\n\t\t\tdoneCh <- true\n\t\t}\n\t}()\n\treturn\n}", "func Read() {\n\tlog.Info(InProgress, \"Reading Settings...\")\n\tjsonstring, err := ioutil.ReadFile(DataPath + \"/settings.json\")\n\tif err == nil {\n\t\tdata := make(map[string]interface{})\n\t\terr := json.Unmarshal(jsonstring, &data)\n\t\tif err == nil {\n\t\t\tRemoteAddress, _ = data[\"RemoteAddress\"].(string)\n\n\t\t\tLocalAddress, _ = data[\"LocalAddress\"].(string)\n\n\t\t\ttmp, ok := data[\"DiskSpace\"].(float64)\n\t\t\tif ok {\n\t\t\t\tDiskSpace = int(tmp)\n\t\t\t}\n\n\t\t\ttmp, ok = data[\"MaxWorkers\"].(float64)\n\t\t\tif ok {\n\t\t\t\tMaxWorkers = int(tmp)\n\t\t\t}\n\n\t\t\ttmp, ok = data[\"QueueMaxLength\"].(float64)\n\t\t\tif ok {\n\t\t\t\tQueueMaxLength = int(tmp)\n\t\t\t}\n\n\t\t\ttmp, ok = data[\"MessageMaxSize\"].(float64)\n\t\t\tif ok {\n\t\t\t\tMessageMaxSize = int(tmp)\n\t\t\t}\n\n\t\t\ttmp, ok = data[\"MessageMinCheckDelay\"].(float64)\n\t\t\tif ok {\n\t\t\t\tMessageMinCheckDelay = int(tmp)\n\t\t\t}\n\n\t\t\ttmp, ok = data[\"MessageMaxStoreTime\"].(float64)\n\t\t\tif ok {\n\t\t\t\tMessageMaxStoreTime = int(tmp)\n\t\t\t}\n\n\t\t\tColorizedLogs, _ = data[\"ColorizedLogs\"].(bool)\n\t\t} else {\n\t\t\tlog.Warn(SettingsReadError, \"Failed to read settings from file (\"+err.Error()+\"). Falling back to defaults or using command line arguments...\")\n\t\t}\n\t}\n\n\tparseCommandLineArgs()\n\tlogger.ColorizedLogs = ColorizedLogs\n\tlog.Info(OK, \"Successfully read Settings.\")\n\tWrite()\n}", "func (c *Config) Read(path string) error {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn errors.New(\"reading config \" + path + \", \" + err.Error())\n\t}\n\n\terr = json.Unmarshal(data, c)\n\tif err != nil {\n\t\treturn errors.New(\"parsing config \" + path + \", \" + err.Error())\n\t}\n\n\tabsolutePath, err := filepath.Abs(path)\n\tif err != nil {\n\t\treturn errors.New(\"error in get absolute path\")\n\t}\n\n\tparentDir := filepath.Dir(absolutePath)\n\tc.DeploymentTemplatePath = parentDir + \"/\" + c.DeploymentTemplatePath\n\n\tdata, err = ioutil.ReadFile(c.DeploymentTemplatePath)\n\tif err != nil {\n\t\treturn errors.New(\"reading deployment template \" + c.DeploymentTemplatePath + \", \" + err.Error())\n\t}\n\tc.DeploymentTemplate = string(data)\n\t//TODO validate\n\tlogger.Infof(\"config listing\")\n\tlogger.Infof(\"deployment template path: %s\", c.DeploymentTemplatePath)\n\tlogger.Infof(\"wait for creating timeout: %d\", c.WaitForCreatingTimeout)\n\tlogger.Infof(\"pod lifetime %d\", c.PodLifetime)\n\tlogger.Infof(\"listen: %s\", c.Listen)\n\tlogger.Infof(\"namespace: %s\", c.Namespace)\n\treturn nil\n}", "func (d *driver) ReadConfig(unmarshal func(interface{}) error) error {\n\treturn nil\n}", "func (conf *Configuration) Read(path string) error {\n\tif _, err := toml.DecodeFile(path, conf); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Load() Configuration {\n\tif cfg.APIAiToken != \"\" {\n\t\treturn cfg\n\t}\n\tconf, err := os.Open(\"config/config.json\")\n\n\tif err != nil {\n\t\tlog.Fatal(\"config:Load error : \", err)\n\t}\n\n\tdecoder := json.NewDecoder(conf)\n\terr = decoder.Decode(&cfg)\n\tif err != nil {\n\t\tlog.Fatal(\"config:Load error : \", err)\n\t}\n\n\treturn cfg\n}", "func readConfiguration(filename string) (*RawConfiguration, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\treader := NewErrorReader(bufio.NewReader(f)) // HL_error_in_struct\n\theader := reader.ReadLine() // HL_error_in_struct\n\tbody := reader.ReadLine() // HL_error_in_struct\n\tif err = reader.Err(); err != nil { // HL_error_in_struct\n\t\treturn nil, err // HL_error_in_struct\n\t} // HL_error_in_struct\n\n\treturn &RawConfiguration{\n\t\theader: header,\n\t\tbody: body,\n\t}, nil\n}", "func getConf(configFile string) (configuration, error) {\n\tfile, _ := os.Open(configFile)\n\tdefer file.Close()\n\n\tdecoder := json.NewDecoder(file)\n\tConf := configuration{}\n\terr := decoder.Decode(&Conf)\n\n\t// in case of err Conf will be empty struct\n\treturn Conf, err\n\n}", "func ReadConfig() *Config {\n\tc := new(Config)\n\n\t// The listening port\n\tc.port = getPort(\"VTSB_PORT\", 8080)\n\n\t// Logging\n\tc.logLevel = getLogLevel(\"VTSB_LOGLEVEL\")\n\n\t// defaults to stdout in logrus\n\tc.logLoc = os.Getenv(\"VTSB_LOGLOCATION\")\n\n\t// Database\n\tc.admin_db_host = getHostName(\"VTSB_ADMIN_DB_HOST\")\n\tc.admin_db_port = getPort(\"VTSB_ADMIN_DB_PORT\", 3306)\n\tc.admin_db_user = os.Getenv(\"VTSB_ADMIN_DB_USER\")\n\tc.admin_db_pass = os.Getenv(\"VTSB_ADMIN_DB_PASS\")\n\tc.admin_db_name = os.Getenv(\"VTSB_ADMIN_DB_NAME\")\n\n\treturn c\n}", "func readConfig(file string) wConfig {\n\tvar c = wConfig{}\n\t_, err := os.Stat(file)\n\tif err == nil {\n\t\tf, _ := os.Open(file)\n\t\tdefer f.Close()\n\t\tdecoder := json.NewDecoder(f)\n\t\terr := decoder.Decode(&c)\n\t\tcheck(err)\n\t} else {\n\t\tif !os.IsNotExist(err) {\n\t\t\tlog.Fatalf(\"Unable to read %s: %s\\n\", file, err)\n\t\t}\n\t}\n\treturn c\n}", "func readConfig(settingFile string) ConfigJSON {\n\traw, err := ioutil.ReadFile(settingFile)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tos.Exit(1)\n\t}\n\n\tvar s ConfigJSON\n\tjson.Unmarshal(raw, &s)\n\treturn s\n}", "func ReadConfig() error {\n\t//Singleton\n\tif isLoaded {\n\t\treturn nil\n\t}\n\tif _, err := toml.DecodeFile(\"config.toml\", &Conf); err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\t//Workaround to set the database connection timeout in the mysql.Config type because the TOML parser doesn't implicitly parse Duration.\n\t//We use a wrapper and then set the value back.\n\t//Conf.DB.Timeout = Conf.Server.DB_timeout.Duration\n\tisLoaded = true\n\treturn nil\n}", "func getconf() (map[string]string, error) {\n\tif _, err := os.Stat(config.Conf()); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\tf, err := os.Open(config.Conf())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tret := make(map[string]string)\n\tscanner := bufio.NewScanner(f)\n\tfor scanner.Scan() {\n\t\tkv := strings.SplitN(scanner.Text(), \":\", 2)\n\t\tif len(kv) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tret[kv[0]] = kv[1]\n\t}\n\treturn ret, nil\n}", "func loadConfiguration() Config {\n\tvar conf Config\n\t_, b, _, _ := runtime.Caller(0)\n\tbasepath := filepath.Dir(b)\n\tfilename := fmt.Sprintf(\"%s/config.json\", basepath)\n\tconfigFile, err := os.Open(filename)\n\tdefer configFile.Close()\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t}\n\tjsonParser := json.NewDecoder(configFile)\n\tjsonParser.Decode(&conf)\n\t// Use ENV var if it's set\n\tconf.Port = getEnvIntValue(\"Port\", conf.Port)\n\tconf.ReqPerSec = getEnvIntValue(\"ReqPerSec\", conf.ReqPerSec)\n\tconf.ReqPerMin = getEnvIntValue(\"ReqPerMin\", conf.ReqPerMin)\n\tconf.ReqPerHour = getEnvIntValue(\"ReqPerHour\", conf.ReqPerHour)\n\tconf.RedisHost = getEnvStrValue(\"RedisHost\", conf.RedisHost)\n\tconf.RedisPort = getEnvIntValue(\"RedisPort\", conf.RedisPort)\n\n\treturn conf\n}", "func (turingMachine *TuringMachine) GetConfiguration() string {\n return turingMachine.tape.GetConfiguration(turingMachine.currentState.name)\n}", "func Read(filename string) ([]Config, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\treturn nil, nil\n}", "func getConfig(fpath string) {\n\traw, err := ioutil.ReadFile(fpath)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to read config %q, err: %v\", fpath, err)\n\t\tos.Exit(1)\n\t}\n\terr = json.Unmarshal(raw, &ctx.config)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to json-unmarshal config %q, err: %v\", fpath, err)\n\t\tos.Exit(1)\n\t}\n}", "func readConfig(fileName string) (*gabs.Container, error) {\n\t// Read file\n\tfileBytes, readErr := ioutil.ReadFile(fileName)\n\n\tif readErr != nil {\n\t\treturn nil, readErr\n\t}\n\n\t// Convert to usable map\n\tparsedJson, parsedJsonErr := gabs.ParseJSON(fileBytes)\n\n\tif parsedJsonErr != nil {\n\t\treturn nil, parsedJsonErr\n\t}\n\n\treturn parsedJson, nil\n}", "func (c *Configr) Read(key string) (interface{}, error) {\n\treturn c.Get(key)\n}", "func GetAppConfiguration() map[string] interface{} {\r\n\tif (appConfig != nil) {\r\n\t\treturn appConfig;\r\n\t}\r\n\r\n\tdir, _ := os.Getwd();\r\n\tplan, _ := ioutil.ReadFile(dir + \"/conf/config.json\") // filename is the JSON file to read\r\n\tvar data map[string] interface{}\r\n\terr := json.Unmarshal(plan, &data)\r\n\tif (err != nil) {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\tappConfig = data;\r\n\tprintConfig();\r\n\treturn data;\r\n}", "func loadConfig() error {\n\tconfigMap = make(map[string]interface{})\n\tfmt.Println(\"Reading \", os.Args[1])\n\tdat, err := ioutil.ReadFile(os.Args[1])\n\tcheckError(err)\n\n\tif err := json.Unmarshal(dat, &configMap); err != nil {\n\t\tlog.Fatal(\"Error in loading config \", err)\n\t}\n\tprotocol = configMap[\"protocol\"].(string)\n\tipAdd = configMap[\"ipAddress\"].(string)\n\tport = configMap[\"port\"].(string)\n\taddr := []string{ipAdd, port}\n\tselfaddr = strings.Join(addr, \"\")\n\tif selfaddr == \"\" {\n\t\tfmt.Println(\"Could not initialize selfaddr\")\n\t}\n\tchordid = getChordId(port, ipAdd)\n\tpersiStorage :=\n\t\tconfigMap[\"persistentStorageContainer\"].(map[string]interface{})\n\tdict3File = persiStorage[\"file\"].(string)\n\tmethods = configMap[\"methods\"].([]interface{})\n\tstabilizeInterval = configMap[\"stabilizeInterval\"].(float64)\n\tcheckPredInterval = configMap[\"checkPredInterval\"].(float64)\n\tfixfingersInterval = configMap[\"fixfingersInterval\"].(float64)\n\tentrypt = configMap[\"entrypoint\"].(string)\n\tfmt.Println(\"Methods exposed by server: \", methods)\n\treturn nil\n}", "func ReadConfig(configFile *string) *config.Config {\n\tconfig := config.FromFile(*configFile)\n\tlog.Printf(\"Read config file ==> OK\")\n\treturn config\n}", "func (rm *resourceManager) readConfig() error {\n\n\tresources := &types.ResourceConfList{}\n\trawBytes, err := ioutil.ReadFile(rm.configFile)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reading file %s, %v\", rm.configFile, err)\n\n\t}\n\n\tif err = json.Unmarshal(rawBytes, resources); err != nil {\n\t\treturn fmt.Errorf(\"error unmarshalling raw bytes %v\", err)\n\t}\n\n\tglog.Infof(\"ResourceList: %+v\", resources.ResourceList)\n\tfor i := range resources.ResourceList {\n\t\trm.configList = append(rm.configList, &resources.ResourceList[i])\n\t}\n\n\treturn nil\n}", "func Get() (*Configuration, error) {\n\tif cfg != nil {\n\t\treturn cfg, nil\n\t}\n\n\tcfg = &Configuration{\n\t\tBindAddr: \":8082\",\n\t}\n\n\treturn cfg, envconfig.Process(\"\", cfg)\n}", "func Get() Config {\n\treturn _conf\n}", "func readConfig(configPath string ) (DBconfig, error) {\n\n\tjsonFile, err := os.Open(configPath); if err != nil {\n\t\tlog.Printf(\"Error openning file for config path : %v, error : %v\", configPath, err.Error())\n\t\treturn DBconfig{}, err\n\t}\n\tdefer jsonFile.Close()\n\tbyteValue, _ := ioutil.ReadAll(jsonFile)\n\tvar DBconfig = DBconfig{}\n\tjson.Unmarshal(byteValue, &DBconfig)\n\n\treturn DBconfig, nil\n}", "func loadConfig() {\n\tr, err := os.Open(configPath)\n\tif err != nil {\n\t\tlog.Fatalf(\"Can't open config file!\")\n\t}\n\tdefer r.Close()\n\tdec := json.NewDecoder(r)\n\tdec.Decode(&config)\n\n\tlog.Printf(\"Config.DBAddress: %s\\n\", config.DBAddress)\n\tlog.Printf(\"Config.WorkersNo: %d\\n\", config.WorkersNo)\n\tlog.Printf(\"Config.ClearDb: %t\\n\", config.ClearDb)\n\tlog.Printf(\"Config.From: %s\\n\", config.From)\n\tlog.Printf(\"Config.To: %s\\n\", config.To)\n\tlog.Printf(\"Config.Currency: %s\\n\", config.Currency)\n\tlog.Printf(\"Config.SupportedCurrencies: %v\\n\", config.Currencies)\n}", "func Get() Config {\n\treturn conf\n}", "func ReadConfig(ctx context.Context) (*Config, error) {\n\tloader := confita.NewLoader(\n\t\tfile.NewOptionalBackend(\"/etc/mpproxy/mpproxy.json\"),\n\t\tfile.NewOptionalBackend(\"/etc/mpproxy/mpproxy.yaml\"),\n\t\tfile.NewOptionalBackend(\"./mpproxy.json\"),\n\t\tfile.NewOptionalBackend(\"./mpproxy.yaml\"),\n\t)\n\n\tcfg := &Config{}\n\n\tif err := loader.Load(ctx, cfg); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to laod config: %w\", err)\n\t}\n\n\treturn cfg, nil\n}", "func Get() *Config {\n\treturn configuration\n}", "func Get() (*Configuration, error) {\n\tif cfg != nil {\n\t\treturn cfg, nil\n\t}\n\n\tcfg = &Configuration{\n\t\tBindAddr: \":10100\",\n\t\tDefaultMaxResults: 1000,\n\t\tGracefulShutdownTimeout: 5 * time.Second,\n\t\tHost: \"http://localhost\",\n\t\tElasticSearchConfig: &ElasticSearchConfig{\n\t\t\tDestURL: \"http://localhost:9200\",\n\t\t\tDestIndex: \"courses\",\n\t\t\tShowScore: false,\n\t\t\tSignedRequests: true,\n\t\t},\n\t}\n\n\treturn cfg, envconfig.Process(\"\", cfg)\n}", "func ReadConfiguration(dir string) (Configuration, string, error) {\n\tconf := Configuration{}\n\tconf.ResourcesDir = \"resources\"\n\tconfigFilePath := path.Join(dir, \"flekszible.yaml\")\n\tloaded, err := readFromFile(configFilePath, &conf)\n\tif err != nil {\n\t\treturn conf, \"\", err\n\t}\n\tif loaded {\n\t\tconf.ResourcesDir = \"\"\n\t\treturn conf, configFilePath, nil\n\t}\n\n\tconfigFilePath = path.Join(dir, \"Flekszible\")\n\tloaded, err = readFromFile(configFilePath, &conf)\n\tif err != nil {\n\t\treturn conf, \"\", err\n\t}\n\tif loaded {\n\t\treturn conf, configFilePath, nil\n\t}\n\tconf.ResourcesDir = \"\"\n\treturn conf, \"\", nil\n\n}", "func ReadConfig() Config {\n\n\tdir, pathError := filepath.Abs(filepath.Dir(os.Args[0]))\n\tif pathError != nil {\n\t\tlog.Fatal(\"Unable to determine path of application\")\n\t}\n\n\tconfigPath := path.Join(dir, \"config.toml\")\n\n\t_, err := os.Stat(configPath)\n\n\tif err != nil {\n\t\tlog.Fatal(\"Config file is missing: \", configPath)\n\t}\n\n\tvar config Config\n\tif _, err := toml.DecodeFile(configPath, &config); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn config\n}", "func ReadConfiguration(fileName string) *Configuration {\n\tfile, err := os.Open(fileName)\n\tif err != nil {\n\t\tlog.Fatal(\"Could not open configuration file:\", err)\n\t}\n\tdefer file.Close()\n\n\tconfig := &Configuration{}\n\tdecoder := json.NewDecoder(file)\n\terr = decoder.Decode(config)\n\tif err != nil {\n\t\tlog.Fatal(\"Could not json decode the config file:\", err)\n\t}\n\n\treturn config\n}", "func Get() Configuration {\n\tvar cfg Configuration\n\n\t// Parse any arguments that may have been passed\n\tconfigPath, verbose, debug, checkonly := parseArguments()\n\n\t// Read the config file\n\tconfigFile, err := ioutil.ReadFile(configPath)\n\tif err != nil {\n\t\tfmt.Println(\"Unable to read configuration file: \", err)\n\t\tos.Exit(1)\n\t}\n\n\t// Parse the config into a struct\n\terr = yaml.Unmarshal(configFile, &cfg)\n\tif err != nil {\n\t\tfmt.Println(\"Unable to parse yaml configuration: \", err)\n\t\tos.Exit(1)\n\t}\n\n\t// If Manifest wasnt provided, exit\n\tif cfg.Manifest == \"\" {\n\t\tfmt.Println(\"Invalid configuration - Manifest: \", err)\n\t\tos.Exit(1)\n\t}\n\n\t// If URL wasnt provided, exit\n\tif cfg.URL == \"\" {\n\t\tfmt.Println(\"Invalid configuration - URL: \", err)\n\t\tos.Exit(1)\n\t}\n\n\t// If URLPackages wasn't provided, use the repo URL\n\tif cfg.URLPackages == \"\" {\n\t\tcfg.URLPackages = cfg.URL\n\t}\n\n\t// If AppDataPath wasn't provided, configure a default\n\tif cfg.AppDataPath == \"\" {\n\t\tcfg.AppDataPath = filepath.Join(os.Getenv(\"ProgramData\"), \"gorilla/\")\n\t} else {\n\t\tcfg.AppDataPath = filepath.Clean(cfg.AppDataPath)\n\t}\n\n\t// Set the verbosity\n\tif verbose && !cfg.Verbose {\n\t\tcfg.Verbose = true\n\t}\n\n\t// Set the debug and verbose\n\tif debug && !cfg.Debug {\n\t\tcfg.Debug = true\n\t\tcfg.Verbose = true\n\t}\n\n\tif checkonly && !cfg.CheckOnly {\n\t\tcfg.CheckOnly = true\n\t}\n\n\t// Set the cache path\n\tcfg.CachePath = filepath.Join(cfg.AppDataPath, \"cache\")\n\n\t// Add to GorillaReport\n\treport.Items[\"Manifest\"] = cfg.Manifest\n\treport.Items[\"Catalog\"] = cfg.Catalogs\n\n\treturn cfg\n}", "func readConfig(yamlStr []byte) Conf {\n\n\t// First unmarshall into generic structure\n\tvar data map[string]interface{}\n\terr := yaml.Unmarshal(yamlStr, &data)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unmarshal: %v\\n\", err)\n\t}\n\n\t// A config can hold multiple keyed sections\n\tc := Conf{}\n\n\t// Load generation settings\n\tif item, ok := data[\"generate\"]; ok {\n\t\tc.Rendering = loadRendering(item)\n\t}\n\treturn c\n}", "func (ec *ExecutionContext) readConfig() error {\n\tvar op errors.Op = \"cli.ExecutionContext.readConfig\"\n\t// need to get existing viper because https://github.com/spf13/viper/issues/233\n\tv := ec.Viper\n\tv.SetEnvPrefix(util.ViperEnvPrefix)\n\tv.SetEnvKeyReplacer(util.ViperEnvReplacer)\n\tv.AutomaticEnv()\n\tv.SetConfigName(\"config\")\n\tv.SetDefault(\"version\", \"1\")\n\tv.SetDefault(\"endpoint\", \"http://localhost:8080\")\n\tv.SetDefault(\"admin_secret\", \"\")\n\tv.SetDefault(\"access_key\", \"\")\n\tv.SetDefault(\"api_paths.query\", \"v1/query\")\n\tv.SetDefault(\"api_paths.v2_query\", \"v2/query\")\n\tv.SetDefault(\"api_paths.v1_metadata\", \"v1/metadata\")\n\tv.SetDefault(\"api_paths.graphql\", \"v1/graphql\")\n\tv.SetDefault(\"api_paths.config\", \"v1alpha1/config\")\n\tv.SetDefault(\"api_paths.pg_dump\", \"v1alpha1/pg_dump\")\n\tv.SetDefault(\"api_paths.version\", \"v1/version\")\n\tv.SetDefault(\"metadata_directory\", DefaultMetadataDirectory)\n\tv.SetDefault(\"migrations_directory\", DefaultMigrationsDirectory)\n\tv.SetDefault(\"seeds_directory\", DefaultSeedsDirectory)\n\tv.SetDefault(\"actions.kind\", \"synchronous\")\n\tv.SetDefault(\"actions.handler_webhook_baseurl\", \"http://localhost:3000\")\n\tv.SetDefault(\"actions.codegen.framework\", \"\")\n\tv.SetDefault(\"actions.codegen.output_dir\", \"\")\n\tv.SetDefault(\"actions.codegen.uri\", \"\")\n\tv.AddConfigPath(ec.ExecutionDirectory)\n\terr := v.ReadInConfig()\n\tif err != nil {\n\t\treturn errors.E(op, fmt.Errorf(\"cannot read config from file/env: %w\", err))\n\t}\n\tadminSecret := v.GetString(\"admin_secret\")\n\tif adminSecret == \"\" {\n\t\tadminSecret = v.GetString(\"access_key\")\n\t}\n\n\t// Admin secrets can be specified as a string value of format\n\t// [\"secret1\", \"secret2\"], similar to how the corresponding environment variable\n\t// HASURA_GRAPHQL_ADMIN_SECRETS is configured with the server\n\tadminSecretsList := v.GetString(\"admin_secrets\")\n\tadminSecrets := []string{}\n\tif len(adminSecretsList) > 0 {\n\t\tif err = json.Unmarshal([]byte(adminSecretsList), &adminSecrets); err != nil {\n\t\t\treturn errors.E(op, fmt.Errorf(\"parsing 'admin_secrets' from config.yaml / environment variable HASURA_GRAPHQL_ADMIN_SECRETS failed: expected value of format [\\\"secret1\\\", \\\"secret2\\\"]: %w\", err))\n\t\t}\n\t}\n\n\tec.Config = &Config{\n\t\tVersion: ConfigVersion(v.GetInt(\"version\")),\n\t\tDisableInteractive: v.GetBool(\"disable_interactive\"),\n\t\tServerConfig: ServerConfig{\n\t\t\tEndpoint: v.GetString(\"endpoint\"),\n\t\t\tAdminSecret: adminSecret,\n\t\t\tAdminSecrets: adminSecrets,\n\t\t\tAPIPaths: &ServerAPIPaths{\n\t\t\t\tV1Query: v.GetString(\"api_paths.query\"),\n\t\t\t\tV2Query: v.GetString(\"api_paths.v2_query\"),\n\t\t\t\tV1Metadata: v.GetString(\"api_paths.v1_metadata\"),\n\t\t\t\tGraphQL: v.GetString(\"api_paths.graphql\"),\n\t\t\t\tConfig: v.GetString(\"api_paths.config\"),\n\t\t\t\tPGDump: v.GetString(\"api_paths.pg_dump\"),\n\t\t\t\tVersion: v.GetString(\"api_paths.version\"),\n\t\t\t},\n\t\t\tInsecureSkipTLSVerify: v.GetBool(\"insecure_skip_tls_verify\"),\n\t\t\tCAPath: v.GetString(\"certificate_authority\"),\n\t\t},\n\t\tMetadataDirectory: v.GetString(\"metadata_directory\"),\n\t\tMetadataFile: v.GetString(\"metadata_file\"),\n\t\tMigrationsDirectory: v.GetString(\"migrations_directory\"),\n\t\tSeedsDirectory: v.GetString(\"seeds_directory\"),\n\t\tActionConfig: &types.ActionExecutionConfig{\n\t\t\tKind: v.GetString(\"actions.kind\"),\n\t\t\tHandlerWebhookBaseURL: v.GetString(\"actions.handler_webhook_baseurl\"),\n\t\t\tCodegen: &types.CodegenExecutionConfig{\n\t\t\t\tFramework: v.GetString(\"actions.codegen.framework\"),\n\t\t\t\tOutputDir: v.GetString(\"actions.codegen.output_dir\"),\n\t\t\t\tURI: v.GetString(\"actions.codegen.uri\"),\n\t\t\t},\n\t\t},\n\t}\n\tif !ec.Config.Version.IsValid() {\n\t\treturn errors.E(op, ErrInvalidConfigVersion)\n\t}\n\terr = ec.Config.ServerConfig.ParseEndpoint()\n\tif err != nil {\n\t\treturn errors.E(op, fmt.Errorf(\"unable to parse server endpoint: %w\", err))\n\t}\n\treturn nil\n}", "func loadConfiguration() {\n configFilePath := \"src/config/main.conf\"\n\n log.Printf(\"starting %s load\\n\", configFilePath)\n configFile, err := os.Open(configFilePath)\n if err != nil {\n log.Println(\"[ERROR] \", err)\n log.Println(\"For your happiness an example config file is provided in the 'conf' directory in the repository.\")\n os.Exit(1)\n }\n\n configDecoder := json.NewDecoder(configFile)\n err = configDecoder.Decode(&globalConfiguration)\n if err != nil {\n log.Println(\"[ERROR] \", err)\n log.Println(\"Please ensure that your config file is in valid JSON format.\")\n os.Exit(1)\n }\n\n log.Printf(\"finished %s load\\n\", configFilePath)\n}", "func ReadConfiguration() (*Config, error) {\n\ttemplatesConfigFile, err := getConfigDetails()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfile, err := os.Open(templatesConfigFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\n\tconfig := &Config{}\n\terr = jsoniter.NewDecoder(file).Decode(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn config, nil\n}", "func (c *ConfigDB) Read() {\n\tif _, err := toml.DecodeFile(\"config.toml\", &c); err != nil {\n\t\tlog.Fatal(\"[ERROR CONNECTION]\", err)\n\t}\n}" ]
[ "0.7231661", "0.7211487", "0.7201041", "0.7148904", "0.7126202", "0.7055725", "0.70521224", "0.7000314", "0.6915163", "0.6891623", "0.68754286", "0.68418735", "0.6838525", "0.68295383", "0.68170327", "0.6798976", "0.67895806", "0.67681026", "0.67338103", "0.66949594", "0.6687729", "0.66871744", "0.6677868", "0.66472906", "0.6634054", "0.66250813", "0.6610554", "0.6599958", "0.65953857", "0.6591854", "0.65850556", "0.65813375", "0.65792507", "0.657839", "0.6563446", "0.6516466", "0.6514235", "0.6511873", "0.6505224", "0.65020955", "0.64992964", "0.64860314", "0.64851785", "0.6474065", "0.6471237", "0.64623773", "0.6462205", "0.6449472", "0.64489394", "0.64487123", "0.64397687", "0.6438929", "0.64313215", "0.6430135", "0.6419817", "0.6404402", "0.6392594", "0.63884634", "0.63768345", "0.6366011", "0.63639325", "0.6357798", "0.6334588", "0.6329349", "0.63202256", "0.63166994", "0.6291988", "0.6284058", "0.62824893", "0.62763405", "0.62687534", "0.6259193", "0.62576276", "0.625425", "0.6247941", "0.6245546", "0.62429076", "0.6239582", "0.623816", "0.6223677", "0.6218655", "0.62182486", "0.6214548", "0.62141806", "0.6212594", "0.62117976", "0.6200117", "0.62000257", "0.61904204", "0.6190088", "0.618402", "0.61749303", "0.6174335", "0.6173899", "0.6171785", "0.61699605", "0.61626107", "0.6162281", "0.6156941", "0.61522985" ]
0.6158175
98
initialize an array of documents for simulation test. If a template is available read the sample json and replace them with random values. Otherwise, use the demo example.
func (rn *Runner) initSimDocs() { var err error var sdoc bson.M if rn.verbose { log.Println("initSimDocs") } rand.Seed(time.Now().Unix()) total := 512 if rn.filename == "" { for len(simDocs) < total { simDocs = append(simDocs, util.GetDemoDoc()) } return } if sdoc, err = util.GetDocByTemplate(rn.filename, true); err != nil { return } bytes, _ := json.Marshal(sdoc) if rn.verbose { log.Println(string(bytes)) } doc := make(map[string]interface{}) json.Unmarshal(bytes, &doc) for len(simDocs) < total { ndoc := make(map[string]interface{}) util.RandomizeDocument(&ndoc, doc, false) delete(ndoc, "_id") ndoc["_search"] = strconv.FormatInt(rand.Int63(), 16) simDocs = append(simDocs, ndoc) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func setupData(file string) {\n\trand.Seed(time.Now().UTC().UnixNano())\n\tdata, err := readLines(file)\n\tif err != nil {\n\t\tfmt.Println(\"Cannot read file\", err)\n\t\tos.Exit(1)\n\t}\n\tfor _, line := range data {\n\t\ts := strings.Split(line, \"|\")\n\t\tdoc, sentiment := s[0], s[1]\n\n\t\tif rand.Float64() > testPercentage {\n\t\t\ttrain = append(train, document{sentiment, doc})\n\t\t} else {\n\t\t\ttest = append(test, document{sentiment, doc})\n\t\t}\n\t}\n}", "func InitDemo(s interf.Service) error {\n\n\t// first, update file index\n\terr := s.Update()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// create over 1000 small test files for Files() tests (if not exist)\n\tfor i := 1; i < 1011; i++ {\n\t\tname := fmt.Sprintf(\"small-test-file-%d.dat\", i)\n\t\t_, err := s.Files().ByName(name)\n\t\tif err != nil {\n\t\t\t_, err := s.Save(name, strings.NewReader(name), 0)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// create big random test files\n\trnd := rand.New(rand.NewSource(1337))\n\n\tname := \"big-test-file-150.dat\"\n\tsize := 150*1024*1024 + 1\n\t_, err = s.Files().ByName(name)\n\tif err != nil {\n\t\t_, err := s.Save(name, rnd, int64(size))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// create type test files (like text, image, ...)\n\tconst fuse = 128 * 1024 // 128 kB\n\tconst buffer = 16 * 1024 * 1024 // 16 MB\n\tconst comp = 1 * 1024 * 1024 // 1 MB\n\tconst bundle = 12 * 1024 * 1024 // 12 MB\n\n\tfor _, size := range []int{0, fuse, fuse - 1, fuse + 1, buffer, buffer - 1, buffer + 1, comp, comp - 1, comp + 1, bundle, bundle - 1, bundle + 1} {\n\t\tfor _, rate := range []float32{0.99, 0.66, 0.33, 0} {\n\t\t\t// data\n\t\t\tdata := make([]byte, size)\n\t\t\trnd.Read(data)\n\t\t\tfor i := 0; i < int(float32(size)*rate); i++ {\n\t\t\t\tdata[i] = 'B'\n\t\t\t}\n\t\t\tif len(data) > 0 {\n\t\t\t\tdata[0] = 'A'\n\t\t\t}\n\n\t\t\t// save\n\t\t\tname := fmt.Sprintf(\"special-file-%d-%f.dat\", size, rate)\n\t\t\t_, err = s.Files().ByName(name)\n\t\t\tif err != nil {\n\t\t\t\t_, err := s.Save(name, bytes.NewReader(data), 0)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// final update\n\terr = s.Update()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn nil\n}", "func Read(files []string) (documents []Document) {\n\n\tfor _, fp := range files {\n\t\tf, err := ioutil.ReadFile(fp)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(\"There was an error reading the file\", err)\n\t\t\tos.Exit(-1)\n\t\t}\n\n\t\tyamlDocumentsInFile := bytes.SplitN(f, []byte(\"---\\n\"), -1)\n\t\t//fmt.Printf(\"%q\\n\", yamlDocumentsInFile)\n\n\t\tif (len(yamlDocumentsInFile) % 2) != 0 {\n\t\t\tfmt.Println(\"File \", fp, \" has an odd number of documents. File must consist of pairs of preamble and template documents, in order.\")\n\t\t\tos.Exit(-1)\n\t\t}\n\n\t\tfor i := 0; i < len(yamlDocumentsInFile); i += 2 {\n\n\t\t\tdoc := Document{}\n\t\t\terr = yaml.Unmarshal(yamlDocumentsInFile[i], &doc.Preamble)\n\t\t\tdoc.Template = string(yamlDocumentsInFile[i+1])\n\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"There was an error unmarshaling yaml\", err)\n\t\t\t\tos.Exit(-1)\n\t\t\t}\n\n\t\t\t//fmt.Printf(\"%+v\\n\", doc)\n\n\t\t\t// Perform type conversions to handle lists of maps or single map\n\t\t\tswitch p := doc.Preamble.ReadParams.(type) {\n\t\t\tcase []interface{}:\n\t\t\t\tfor _, params := range p {\n\n\t\t\t\t\t// We cannot derive a map[string]inteface{} from interface{} directly\n\t\t\t\t\tparamsMap, _ := params.(map[interface{}]interface{})\n\n\t\t\t\t\ttParams := typeCastMap(paramsMap)\n\n\t\t\t\t\tdocument := Document{}\n\t\t\t\t\tdocument.Preamble.Params = tParams\n\t\t\t\t\tdocument.Template = doc.Template\n\n\t\t\t\t\tdocuments = append(documents, document)\n\t\t\t\t}\n\t\t\tcase interface{}:\n\t\t\t\t// We cannot derive a map[string]inteface{} from interface{} directly\n\t\t\t\ttParams := p.(map[interface{}]interface{})\n\n\t\t\t\tdoc.Preamble.Params = typeCastMap(tParams)\n\n\t\t\t\tdocuments = append(documents, doc)\n\t\t\tdefault:\n\t\t\t\tfmt.Printf(\"I don't know how to deal with type %T %+v!\\n\", p, p)\n\t\t\t\tos.Exit(-1)\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\treturn\n}", "func initMockData() {\n\n\t// Generate Mock Data\n\tbooks = append(books, models.GenerateSampleBookRecord())\n\tbooks = append(books, models.GenerateSampleBookRecord())\n\tbooks = append(books, models.GenerateSampleBookRecord())\n\tbooks = append(books, models.GenerateSampleBookRecord())\n}", "func init() {\n\tf := GeneralMatrices\n\tfor level := 0; level < 2; level++ {\n\t\tmf := MutateFixtures(f, f)\n\t\tf = append(f, mf...)\n\t}\n\tTestFixtures = f\n\n}", "func main() {\n\tl := []yamlFile{\n\t\t{\"configurations.yml\", false, cfgTemplate},\n\t\t{\"configurationsResponse.yml\", true, responseTemplate},\n\t}\n\tfor _, file := range l {\n\t\tf, err := os.Create(file.Name)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tdoc := document{\n\t\t\tItems: userCfgItems(file.IsResponse),\n\t\t}\n\t\ttmpl, err := template.New(\"test\").Parse(file.TempName)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\terr = tmpl.Execute(f, doc)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tf.Close()\n\t}\n}", "func generateGoSampleFile(schema map[string]interface{}, config Config) {\r\n var obj map[string]interface{}\r\n var samples = make(map[string]interface{})\r\n var outString = \"package main\\n\\nvar samples = `\\n\"\r\n\r\n var filename = config.Samples.GoSampleFilename\r\n var elementNames = config.Samples.GoSampleElements\r\n\r\n fmt.Printf(\"Generate Go SAMPLE file %s for: \\n %s\\n\", filename, elementNames)\r\n\r\n for i := range elementNames {\r\n elementName := elementNames[i]\r\n if elementName == \"schema\" {\r\n // sample of the entire schema, can it even work?\r\n obj = schema\r\n } else {\r\n // use the schema subset\r\n obj = getObject(schema, elementName)\r\n if obj == nil {\r\n fmt.Printf(\"** WARN ** %s returned nil from getObject\\n\", elementName)\r\n return\r\n }\r\n }\r\n samples[elementName] = sampleType(obj, elementName) \r\n }\r\n samplesOut, err := json.MarshalIndent(&samples, \"\", \" \")\r\n if err != nil {\r\n fmt.Println(\"** ERR ** cannot marshal sample file output for writing\")\r\n return\r\n }\r\n outString += string(samplesOut) + \"`\"\r\n ioutil.WriteFile(filename, []byte(outString), 0644)\r\n}", "func initExamples(obj exampler, attr *expr.AttributeExpr, r *expr.ExampleGenerator) {\n\texamples := attr.ExtractUserExamples()\n\tswitch {\n\tcase len(examples) > 1:\n\t\trefs := make(map[string]*ExampleRef, len(examples))\n\t\tfor _, ex := range examples {\n\t\t\texample := &Example{\n\t\t\t\tSummary: ex.Summary,\n\t\t\t\tDescription: ex.Description,\n\t\t\t\tValue: ex.Value,\n\t\t\t}\n\t\t\trefs[ex.Summary] = &ExampleRef{Value: example}\n\t\t}\n\t\tobj.setExamples(refs)\n\t\treturn\n\tcase len(examples) > 0:\n\t\tobj.setExample(examples[0].Value)\n\tdefault:\n\t\tobj.setExample(attr.Example(r))\n\t}\n}", "func TestConcurrentCreateSmallDocuments(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"Skip on short tests\")\n\t}\n\n\t// Disable those tests for active failover\n\tif getTestMode() == testModeResilientSingle {\n\t\tt.Skip(\"Disabled in active failover mode\")\n\t}\n\n\t// don't use disallowUnknownFields in this test - we have here custom structs defined\n\tc := createClient(t, &testsClientConfig{skipDisallowUnknownFields: true})\n\n\tversion, err := c.Version(nil)\n\tif err != nil {\n\t\tt.Fatalf(\"Version failed: %s\", describe(err))\n\t}\n\tisv33p := version.Version.CompareTo(\"3.3\") >= 0\n\tif !isv33p && os.Getenv(\"TEST_CONNECTION\") == \"vst\" {\n\t\tt.Skip(\"Skipping VST load test on 3.2\")\n\t} else {\n\t\tdb := ensureDatabase(nil, c, \"document_test\", nil, t)\n\t\tcol := ensureCollection(nil, db, \"TestConcurrentCreateSmallDocuments\", nil, t)\n\n\t\tdocChan := make(chan driver.DocumentMeta, 128*1024)\n\n\t\tcreator := func(limit, interval int) {\n\t\t\tfor i := 0; i < limit; i++ {\n\t\t\t\tctx := context.Background()\n\t\t\t\tdoc := UserDoc{\n\t\t\t\t\t\"Jan\",\n\t\t\t\t\ti * interval,\n\t\t\t\t}\n\t\t\t\tmeta, err := col.CreateDocument(ctx, doc)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatalf(\"Failed to create new document: %s\", describe(err))\n\t\t\t\t}\n\t\t\t\tdocChan <- meta\n\t\t\t}\n\t\t}\n\n\t\treader := func() {\n\t\t\tfor {\n\t\t\t\tmeta, ok := <-docChan\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// Document must exists now\n\t\t\t\tif found, err := col.DocumentExists(nil, meta.Key); err != nil {\n\t\t\t\t\tt.Fatalf(\"DocumentExists failed for '%s': %s\", meta.Key, describe(err))\n\t\t\t\t} else if !found {\n\t\t\t\t\tt.Errorf(\"DocumentExists returned false for '%s', expected true\", meta.Key)\n\t\t\t\t}\n\t\t\t\t// Read document\n\t\t\t\tvar readDoc UserDoc\n\t\t\t\tif _, err := col.ReadDocument(nil, meta.Key, &readDoc); err != nil {\n\t\t\t\t\tt.Fatalf(\"Failed to read document '%s': %s\", meta.Key, describe(err))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tnoCreators := getIntFromEnv(\"NOCREATORS\", 25)\n\t\tnoReaders := getIntFromEnv(\"NOREADERS\", 50)\n\t\tnoDocuments := getIntFromEnv(\"NODOCUMENTS\", 1000) // per creator\n\n\t\twgCreators := sync.WaitGroup{}\n\t\t// Run N concurrent creators\n\t\tfor i := 0; i < noCreators; i++ {\n\t\t\twgCreators.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wgCreators.Done()\n\t\t\t\tcreator(noDocuments, noCreators)\n\t\t\t}()\n\t\t}\n\t\twgReaders := sync.WaitGroup{}\n\t\t// Run M readers\n\t\tfor i := 0; i < noReaders; i++ {\n\t\t\twgReaders.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wgReaders.Done()\n\t\t\t\treader()\n\t\t\t}()\n\t\t}\n\t\twgCreators.Wait()\n\t\tclose(docChan)\n\t\twgReaders.Wait()\n\t}\n}", "func setSampleData(ctx context.Context, client *entity.Client) error {\n\t_, err := client.Todo.Create().\n\t\tSetID(sampleID).\n\t\tSetContent(\"Sample todo data for unit test.\").\n\t\tSetCompleted(true).\n\t\tSave(ctx)\n\treturn err\n}", "func loadInitialFiles(t *testing.T, data dataSection) int32 {\n\tfilesDocs := make([]interface{}, 0, len(data.Files))\n\tchunksDocs := make([]interface{}, 0, len(data.Chunks))\n\tvar chunkSize int32\n\n\tfor _, v := range data.Files {\n\t\tdocBytes, err := v.MarshalJSON()\n\t\ttesthelpers.RequireNil(t, err, \"error converting raw message to bytes: %s\", err)\n\t\tdoc := bsonx.Doc{}\n\t\terr = bson.UnmarshalExtJSON(docBytes, false, &doc)\n\t\ttesthelpers.RequireNil(t, err, \"error creating file document: %s\", err)\n\n\t\t// convert length from int32 to int64\n\t\tif length, err := doc.LookupErr(\"length\"); err == nil {\n\t\t\tdoc = doc.Delete(\"length\")\n\t\t\tdoc = doc.Append(\"length\", bsonx.Int64(int64(length.Int32())))\n\t\t}\n\t\tif cs, err := doc.LookupErr(\"chunkSize\"); err == nil {\n\t\t\tchunkSize = cs.Int32()\n\t\t}\n\n\t\tfilesDocs = append(filesDocs, doc)\n\t}\n\n\tfor _, v := range data.Chunks {\n\t\tdocBytes, err := v.MarshalJSON()\n\t\ttesthelpers.RequireNil(t, err, \"error converting raw message to bytes: %s\", err)\n\t\tdoc := bsonx.Doc{}\n\t\terr = bson.UnmarshalExtJSON(docBytes, false, &doc)\n\t\ttesthelpers.RequireNil(t, err, \"error creating file document: %s\", err)\n\n\t\t// convert data $hex to binary value\n\t\tif hexStr, err := doc.LookupErr(\"data\", \"$hex\"); err == nil {\n\t\t\thexBytes := convertHexToBytes(t, hexStr.StringValue())\n\t\t\tdoc = doc.Delete(\"data\")\n\t\t\tdoc = append(doc, bsonx.Elem{\"data\", bsonx.Binary(0x00, hexBytes)})\n\t\t}\n\n\t\t// convert n from int64 to int32\n\t\tif n, err := doc.LookupErr(\"n\"); err == nil {\n\t\t\tdoc = doc.Delete(\"n\")\n\t\t\tdoc = append(doc, bsonx.Elem{\"n\", bsonx.Int32(n.Int32())})\n\t\t}\n\n\t\tchunksDocs = append(chunksDocs, doc)\n\t}\n\n\tif len(filesDocs) > 0 {\n\t\t_, err := files.InsertMany(ctx, filesDocs)\n\t\ttesthelpers.RequireNil(t, err, \"error inserting into files: %s\", err)\n\t\t_, err = expectedFiles.InsertMany(ctx, filesDocs)\n\t\ttesthelpers.RequireNil(t, err, \"error inserting into expected files: %s\", err)\n\t}\n\n\tif len(chunksDocs) > 0 {\n\t\t_, err := chunks.InsertMany(ctx, chunksDocs)\n\t\ttesthelpers.RequireNil(t, err, \"error inserting into chunks: %s\", err)\n\t\t_, err = expectedChunks.InsertMany(ctx, chunksDocs)\n\t\ttesthelpers.RequireNil(t, err, \"error inserting into expected chunks: %s\", err)\n\t}\n\n\treturn chunkSize\n}", "func (g *Generator) RandomNotesForResult() []string {\n\tswitch r := rand.Intn(10); {\n\tcase r < 4:\n\t\treturn nil\n\tcase r < 9:\n\t\treturn g.textGenerator.Sentences(1)\n\tdefault:\n\t\treturn g.textGenerator.Sentences(2)\n\t}\n}", "func init() {\n\tif !fileExists(toolData) || !fileExists(userData) || !fileExists(rentalData) {\n\t\terr := createFiles(toolData, userData, rentalData)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tfmt.Println(\"Populating Database\")\n\n\t\tgofakeit.Seed(0)\n\t\tgenerateTool := func(i int) *Tool {\n\t\t\treturn &Tool{\n\t\t\t\tID: i + 1,\n\t\t\t\tName: gofakeit.BuzzWord() + \" \" + gofakeit.HackerNoun(),\n\t\t\t\tDesc: gofakeit.HipsterSentence(5),\n\t\t\t\tPrice: gofakeit.Price(1, 2000),\n\t\t\t\tQuantity: gofakeit.Number(1, 30),\n\t\t\t}\n\t\t}\n\n\t\tgenerateUser := func(i int) *User {\n\t\t\treturn &User{\n\t\t\t\tID: i + 1,\n\t\t\t\tName: gofakeit.Name(),\n\t\t\t\tEmail: gofakeit.Email(),\n\t\t\t}\n\t\t}\n\n\t\tgenerateRental := func(i int) *Rental {\n\t\t\trand.Seed(rand.Int63n(1000))\n\t\t\treturn &Rental{\n\t\t\t\tID: i + 1,\n\t\t\t\tActive: true,\n\t\t\t\tToolID: rand.Intn(10) + 1,\n\t\t\t\tUserID: rand.Intn(10) + 1,\n\t\t\t}\n\t\t}\n\n\t\ttools := []Tool{}\n\t\tusers := []User{}\n\t\trentals := []Rental{}\n\n\t\tfor i := 0; i <= 10; i++ {\n\t\t\ttools = append(tools, *generateTool(i))\n\t\t\tusers = append(users, *generateUser(i))\n\t\t\trentals = append(rentals, *generateRental(i))\n\t\t}\n\n\t\tSave(toolData, tools)\n\t\tSave(userData, users)\n\t\tSave(rentalData, rentals)\n\t}\n}", "func TestNewTemplateMap(t *testing.T) {\n\tconst title = \"Translation Portal\"\n\tconst query = \"謹\"\n\tconst simplified = \"謹\"\n\tconst pinyin = \"jǐn\"\n\tconst english = \"to be cautious\"\n\tws := dicttypes.WordSense{\n\t\tId: 42,\n\t\tHeadwordId: 42,\n\t\tSimplified: simplified,\n\t\tTraditional: query,\n\t\tPinyin: pinyin,\n\t\tEnglish: english,\n\t\tGrammar: \"verb\",\n\t\tConcept: \"\\\\N\",\n\t\tConceptCN: \"\\\\N\",\n\t\tDomain: \"Literary Chinese\",\n\t\tDomainCN: \"\\\\N\",\n\t\tSubdomain: \"\\\\N\",\n\t\tSubdomainCN: \"\\\\N\",\n\t\tImage: \"\\\\N\",\n\t\tMP3: \"\\\\N\",\n\t\tNotes: \"\\\\N\",\n\t}\n\tw := dicttypes.Word{\n\t\tSimplified: simplified,\n\t\tTraditional: \"謹\",\n\t\tPinyin: pinyin,\n\t\tHeadwordId: 42,\n\t\tSenses: []dicttypes.WordSense{ws},\n\t}\n\tterm := find.TextSegment{\n\t\tQueryText: query,\n\t\tDictEntry: w,\n\t}\n\tresults := find.QueryResults{\n\t\tQuery: query,\n\t\tCollectionFile: \"\",\n\t\tNumCollections: 0,\n\t\tNumDocuments: 0,\n\t\tCollections: []find.Collection{},\n\t\tDocuments: []find.Document{},\n\t\tTerms: []find.TextSegment{term},\n\t}\n\ttype test struct {\n\t\tname string\n\t\ttemplateName string\n\t\tcontent interface{}\n\t\twant string\n\t}\n\ttests := []test{\n\t\t{\n\t\t\tname: \"Home page\",\n\t\t\ttemplateName: \"index.html\",\n\t\t\tcontent: map[string]string{\"Title\": title},\n\t\t\twant: \"<title>\" + title + \"</title>\",\n\t\t},\n\t\t{\n\t\t\tname: \"Find results\",\n\t\t\ttemplateName: \"find_results.html\",\n\t\t\tcontent: htmlContent{\n\t\t\t\tTitle: title,\n\t\t\t\tResults: results,\n\t\t\t},\n\t\t\twant: english,\n\t\t},\n\t}\n\tfor _, tc := range tests {\n\t\ttemplates := NewTemplateMap(config.WebAppConfig{})\n\t\ttmpl, ok := templates[tc.templateName]\n\t\tif !ok {\n\t\t\tt.Errorf(\"%s, template not found: %s\", tc.name, tc.templateName)\n\t\t}\n\t\tvar buf bytes.Buffer\n\t\terr := tmpl.Execute(&buf, tc.content)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%s, error rendering template %v\", tc.name, err)\n\t\t}\n\t\tgot := buf.String()\n\t\tif !strings.Contains(got, tc.want) {\n\t\t\tt.Errorf(\"%s, got %s\\n bug want %s\", tc.name, got, tc.want)\n\t\t}\n\t}\n}", "func (Docs) Generate() error {\n\treturn sh.RunWith(ENV, \"go\", \"run\", \"-tags=mage_docs\", \"./magefiles\")\n}", "func CreateSampleBooks() {\n\t\n\tws, _ := time.Parse(\"2006-01-02\", \"1623-01-01\")\n\tsk, _ := time.Parse(\"2006-01-02\", \"1986-09-05\")\n\t\n\tbooks = append(books, \n\t\tBook{\n\t\t\tISBN: \"0451527127\", \n\t\t\tAuthor: \"William Shakespeare\", \n\t\t\tTitle: \"Tempest, The\", \n\t\t\tPubDate: ws, \n\t\t\tRating: 1, \n\t\t\tCheckedOut: true})\n books = append(books, \n \tBook{\n \t\tISBN: \"1444707868\", \n \t\tAuthor: \"Stephen King\", \n \t\tTitle: \"It\", \n \t\tPubDate: sk, \n\t\t\tRating: 2, \n \t\tCheckedOut: false})\n\n}", "func generateIndex(path string, templatePath string) (lo string) {\n homeDir, hmErr := user.Current()\n checkErr(hmErr)\n var lines []string\n var layout string\n if templatePath == \"\" {\n layout = randFromFile(homeDir.HomeDir + \"/go/src/git.praetorianlabs.com/mars/sphinx/bslayouts\")\n imgOne := randFile(path + \"/img\")\n imgOneStr := \"imgOne: .\" + imgOne.Name()\n imgTwo := randFile(path + \"/img\")\n imgTwoStr := \"imgTwo: .\" + imgTwo.Name()\n imgThree := randFile(path + \"/img\")\n imgThreeStr := \"imgThree: .\" + imgThree.Name()\n imgFour := randFile(path + \"/img\")\n imgFourStr := \"imgFour: .\" + imgFour.Name()\n imgsStr := imgOneStr + \"\\n\" + imgTwoStr + \"\\n\" + imgThreeStr + \"\\n\" + imgFourStr\n\n lines = append(lines, \"---\")\n lines = append(lines, \"layout: \" + layout)\n lines = append(lines, imgsStr)\n lines = append(lines, \"title: \" + randFromFile(path + \"/titles\"))\n title := randFromFile(path + \"/titles\")\n lines = append(lines, \"navTitle: \" + title)\n lines = append(lines, \"heading: \" + title)\n lines = append(lines, \"subheading: \" + randFromFile(path + \"/subheading\"))\n lines = append(lines, \"aboutHeading: About Us\")\n lines = append(lines, generateServices(path + \"/services\"))\n lines = append(lines, generateCategories(path + \"/categories\"))\n lines = append(lines, \"servicesHeading: Our offerings\")\n lines = append(lines, \"contactDesc: Contact Us Today!\")\n lines = append(lines, \"phoneNumber: \" + randFromFile(homeDir.HomeDir + \"/go/src/git.praetorianlabs.com/mars/sphinx/phone-num\"))\n lines = append(lines, \"email: \" + randFromFile(homeDir.HomeDir + \"/go/src/git.praetorianlabs.com/mars/sphinx/emails\"))\n lines = append(lines, \"---\")\n lines = append(lines, \"\\n\")\n lines = append(lines, randFromFile(path + \"/content\"))\n } else {\n template, err := os.Open(templatePath)\n checkErr(err)\n scanner := bufio.NewScanner(template)\n for scanner.Scan() {\n lines = append(lines, scanner.Text())\n }\n }\n\n writeTemplate(homeDir.HomeDir + \"/go/src/git.praetorianlabs.com/mars/sphinx/index.md\", lines)\n\n return layout\n}", "func (d *galleryDocument) LoadTemplates(t *template.Template) error {\n\treturn nil\n}", "func main() {\n\tinputPtr := flag.String(\"i\", \"\", \"[required] Input Folder Path\")\n\toutputPtr := flag.String(\"o\", \"\", \"[required] Output Folder Path\")\n\tatomPtr := flag.Bool(\"a\", false, \"Generate Atom file\")\n\trssPtr := flag.Bool(\"r\", false, \"Generate RSS file\")\n\tsitemapPtr := flag.Bool(\"s\", true, \"Generate Sitemap.xml file\")\n\tdatePtr := flag.Bool(\"d\", true, \"Order content by date\")\n\n\tflag.Parse()\n\n\tif *inputPtr == \"\" || *outputPtr == \"\" {\n\t\tfmt.Fprintf(os.Stderr, \"Input folder (-i) and output folder (-o) must be specified with a non-empty argument.\\n\")\n\t\treturn\n\t}\n\n\tfmt.Println(\"Input:\", *inputPtr)\n\tfmt.Println(\"Output:\", *outputPtr)\n\tfmt.Println(\"Generate Atom:\", *atomPtr)\n\tfmt.Println(\"Generate RSS:\", *rssPtr)\n\tfmt.Println(\"Generate Sitemap:\", *sitemapPtr)\n\tfmt.Println(\"Content ordered by date:\", *datePtr)\n\n\tfmt.Println(\"\\nFound JSON Files in input path:\")\n\n\tcontainsIndex := false\n\tjsonFiles := getJsonFilesFromPath(*inputPtr)\n\tfor _, file := range jsonFiles {\n\t\tif strings.Contains(file, \"index.json\") {\n\t\t\tif containsIndex {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Only one 'index.json' file can exist.\")\n\t\t\t}\n\t\t\tcontainsIndex = true\n\t\t}\n\t\tfmt.Println(file)\n\t}\n\n\tif !containsIndex {\n\t\tfmt.Fprintf(os.Stderr, \"You must have one 'index.json' file.\")\n\t}\n\n\t// Get articles\n\tarticles := getArticlesFromJson(jsonFiles, *datePtr)\n\tfor _, art := range articles {\n\t\tfmt.Println(art)\n\t}\n\n\t//Template all articles\n\n\t// Create Index JSON\n\n\t// Template index JSON\n}", "func CreateRandomScene() HittableList {\n\tn := 500\n\tscene := make(HittableList, 0, n)\n\n\tfloor := Sphere{\n\t\tCenter: mgl64.Vec3{0.0, -1000.0, 0},\n\t\tRadius: 1000,\n\t\tMat: Lambertian{Albedo: mgl64.Vec3{0.5, 0.5, 0.5}}}\n\tscene = append(scene, floor)\n\n\tfor a := -11; a < 11; a++ {\n\t\tfor b := -11; b < 11; b++ {\n\t\t\tcenter := mgl64.Vec3{float64(a) + 0.9*rand.Float64(), 0.2, float64(b) + rand.Float64()}\n\t\t\tif center.Sub(mgl64.Vec3{4, 0.2, 0}).Len() <= 0.9 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsphere := Sphere{Center: center, Radius: 0.2}\n\t\t\tmaterialChoice := rand.Float64()\n\t\t\tif materialChoice < 0.8 { // Choose diffuse material for 80% of spheres.\n\t\t\t\tr := rand.Float64() * rand.Float64()\n\t\t\t\tg := rand.Float64() * rand.Float64()\n\t\t\t\tb := rand.Float64() * rand.Float64()\n\t\t\t\tsphere.Mat = Lambertian{Albedo: mgl64.Vec3{r, g, b}}\n\t\t\t} else if materialChoice < 0.95 { // Let 15% of spheres be metallic:\n\t\t\t\tr := 0.5 * (1.0 + rand.Float64())\n\t\t\t\tg := 0.5 * (1.0 + rand.Float64())\n\t\t\t\tb := 0.5 * (1.0 + rand.Float64())\n\t\t\t\tfuzz := rand.Float64()\n\t\t\t\tsphere.Mat = Metallic{Albedo: mgl64.Vec3{r, g, b}, Fuzziness: fuzz}\n\t\t\t} else { // Let the rest be dielectric:\n\t\t\t\tsphere.Mat = Dielectric{Refractance: 1.5}\n\t\t\t}\n\t\t\tscene = append(scene, sphere)\n\t\t}\n\t}\n\n\tdielectricSphere := Sphere{\n\t\tCenter: mgl64.Vec3{0, 1, 0},\n\t\tRadius: 1.0,\n\t\tMat: Dielectric{Refractance: 1.5}}\n\tdiffuseSphere := Sphere{\n\t\tCenter: mgl64.Vec3{-4, 1, 0},\n\t\tRadius: 1.0,\n\t\tMat: Lambertian{Albedo: mgl64.Vec3{0.4, 0.2, 0.1}}}\n\tmetalSphere := Sphere{\n\t\tCenter: mgl64.Vec3{4, 1, 0},\n\t\tRadius: 1.0,\n\t\tMat: Metallic{Albedo: mgl64.Vec3{0.4, 0.2, 0.1}, Fuzziness: 0.0}}\n\n\tscene = append(scene, dielectricSphere)\n\tscene = append(scene, diffuseSphere)\n\tscene = append(scene, metalSphere)\n\n\treturn scene\n}", "func initialize() string {\n\trand.Seed(time.Now().UTC().UnixNano())\n\tdictionary := openFile()\n\treturn genWord(dictionary)\n}", "func TestConcurrentCreateBigDocuments(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"Skip on short tests\")\n\t}\n\n\t// Disable those tests for active failover\n\tif getTestMode() == testModeResilientSingle {\n\t\tt.Skip(\"Disabled in active failover mode\")\n\t}\n\n\t// don't use disallowUnknownFields in this test - we have here custom structs defined\n\tc := createClient(t, &testsClientConfig{skipDisallowUnknownFields: true})\n\n\tversion, err := c.Version(nil)\n\tif err != nil {\n\t\tt.Fatalf(\"Version failed: %s\", describe(err))\n\t}\n\tisv33p := version.Version.CompareTo(\"3.3\") >= 0\n\tif !isv33p && os.Getenv(\"TEST_CONNECTION\") == \"vst\" {\n\t\tt.Skip(\"Skipping VST load test on 3.2\")\n\t} else {\n\t\tdb := ensureDatabase(nil, c, \"document_test\", nil, t)\n\t\tcol := ensureCollection(nil, db, \"TestConcurrentCreateBigDocuments\", nil, t)\n\n\t\tdocChan := make(chan driver.DocumentMeta, 16*1024)\n\n\t\tcreator := func(limit, interval int) {\n\t\t\tdata := make([]byte, 1024)\n\t\t\tfor i := 0; i < limit; i++ {\n\t\t\t\trand.Read(data)\n\t\t\t\tctx := context.Background()\n\t\t\t\tdoc := UserDoc{\n\t\t\t\t\t\"Jan\" + strconv.Itoa(i) + hex.EncodeToString(data),\n\t\t\t\t\ti * interval,\n\t\t\t\t}\n\t\t\t\tmeta, err := col.CreateDocument(ctx, doc)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatalf(\"Failed to create new document: %s\", describe(err))\n\t\t\t\t}\n\t\t\t\tdocChan <- meta\n\t\t\t}\n\t\t}\n\n\t\treader := func() {\n\t\t\tfor {\n\t\t\t\tmeta, ok := <-docChan\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// Document must exists now\n\t\t\t\tif found, err := col.DocumentExists(nil, meta.Key); err != nil {\n\t\t\t\t\tt.Fatalf(\"DocumentExists failed for '%s': %s\", meta.Key, describe(err))\n\t\t\t\t} else if !found {\n\t\t\t\t\tt.Errorf(\"DocumentExists returned false for '%s', expected true\", meta.Key)\n\t\t\t\t}\n\t\t\t\t// Read document\n\t\t\t\tvar readDoc UserDoc\n\t\t\t\tif _, err := col.ReadDocument(nil, meta.Key, &readDoc); err != nil {\n\t\t\t\t\tt.Fatalf(\"Failed to read document '%s': %s\", meta.Key, describe(err))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tnoCreators := getIntFromEnv(\"NOCREATORS\", 25)\n\t\tnoReaders := getIntFromEnv(\"NOREADERS\", 50)\n\t\tnoDocuments := getIntFromEnv(\"NODOCUMENTS\", 100) // per creator\n\n\t\twgCreators := sync.WaitGroup{}\n\t\t// Run N concurrent creators\n\t\tfor i := 0; i < noCreators; i++ {\n\t\t\twgCreators.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wgCreators.Done()\n\t\t\t\tcreator(noDocuments, noCreators)\n\t\t\t}()\n\t\t}\n\t\twgReaders := sync.WaitGroup{}\n\t\t// Run M readers\n\t\tfor i := 0; i < noReaders; i++ {\n\t\t\twgReaders.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wgReaders.Done()\n\t\t\t\treader()\n\t\t\t}()\n\t\t}\n\t\twgCreators.Wait()\n\t\tclose(docChan)\n\t\twgReaders.Wait()\n\t}\n}", "func (t *simpleTest) createImportDocument() ([]byte, []UserDocument) {\n\tbuf := &bytes.Buffer{}\n\tdocs := make([]UserDocument, 0, 10000)\n\tfmt.Fprintf(buf, `[ \"_key\", \"value\", \"name\", \"odd\" ]`)\n\tfmt.Fprintln(buf)\n\tfor i := 0; i < 10000; i++ {\n\t\tkey := fmt.Sprintf(\"docimp%05d\", i)\n\t\tuserDoc := UserDocument{\n\t\t\tKey: key,\n\t\t\tValue: i,\n\t\t\tName: fmt.Sprintf(\"Imported %d\", i),\n\t\t\tOdd: i%2 == 0,\n\t\t}\n\t\tdocs = append(docs, userDoc)\n\t\tfmt.Fprintf(buf, `[ \"%s\", %d, \"%s\", %v ]`, userDoc.Key, userDoc.Value, userDoc.Name, userDoc.Odd)\n\t\tfmt.Fprintln(buf)\n\t}\n\treturn buf.Bytes(), docs\n}", "func loadDocuments(paths []string) (map[string]string, error) {\n\tignoreFileExtensions := func(abspath string, info os.FileInfo, depth int) bool {\n\t\treturn !contains([]string{\".yaml\", \".yml\", \".json\"}, filepath.Ext(info.Name()))\n\t}\n\n\tdocumentPaths, err := loader.FilteredPaths(paths, ignoreFileExtensions)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"filter data paths: %w\", err)\n\t}\n\n\tdocuments := make(map[string]string)\n\tfor _, documentPath := range documentPaths {\n\t\tcontents, err := ioutil.ReadFile(documentPath)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read file: %w\", err)\n\t\t}\n\n\t\tdocuments[documentPath] = string(contents)\n\t}\n\n\treturn documents, nil\n}", "func (m *MockDriver) Templates() (map[string]string, error) {\n\treturn nil, nil\n}", "func Run() {\n\t//TestWriteFile()\n\t//a, _ := AppFs.Open(\"report.bat\")\n\t//fs:= new(afero.OsFs)\n\t//err := fs.Mkdir(\"temp1\", 777)\n\t//g, err:=fs.IsEmpty(\"temp/ioutil-test\")\n\t//fmt.Println(fs)\n\t//fmt.Println(afero.DirExists(fs, \"temp1\"))\n\n\t//return\n\tdoc := New(\"book\")\n\t//doc1 := New(\"article\")\n\t//Example(doc)\n\ttoday := today()\n\tdoc.DateLastRevised = today\n\n\tRender(doc)\n\t//Render(doc1)\n\t// initialize the paths for sections directories\n\tpaths := paths{\"./sections\", \"main.tex\", \"C:/Projects/Go/src/gotex/\"}\n\n\tPartialLatexFiles(paths.defaultSectionsDir + paths.defaultMainFile)\n\n\t// latex the files\n\tcmd := exec.Command(\"lualatex.exe\", \"output.tex\", \"--interaction=nonstopmode\")\n\t// sets the directory we are operating in\n\t//\n\tcmd.Dir = \"c:/Projects/Go/src/gotex/templates\"\n\tout, err := cmd.CombinedOutput()\n\tfmt.Printf(\"OUT = %v\\n\", string(out))\n\tcheckError(err)\n\tfmt.Println(today)\n}", "func TestPostSlidesDocumentInvalidtemplateStorage(t *testing.T) {\n request := createPostSlidesDocumentRequest()\n request.templateStorage = invalidizeTestParamValue(request.templateStorage, \"templateStorage\", \"string\").(string)\n e := initializeTest(\"PostSlidesDocument\", \"templateStorage\", request.templateStorage)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().DocumentApi.PostSlidesDocument(request)\n assertError(t, \"PostSlidesDocument\", \"templateStorage\", r.Code, e)\n}", "func FormatDocuments(w io.Writer, docs []Document, templateFormat string, shortSha bool, db *ParaphraseDb) {\n\tif templateFormat == \"\" {\n\t\tWriteDocuments(w, docs, shortSha)\n\t\treturn\n\t}\n\n\tfor _, doc := range docs {\n\t\terr := RenderDocument(templateFormat, &doc, db, nil)\n\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tbreak\n\t\t}\n\n\t}\n}", "func init() {\n\tfor _, path := range AssetNames() {\n\t\tbytes, err := Asset(path)\n\t\tif err != nil {\n\t\t\tlog.Panicf(\"Unable to parse: path=%s, err=%s\", path, err)\n\t\t}\n\t\ttemplates.New(path).Parse(string(bytes))\n\t}\n}", "func init() {\n\tfor _, path := range AssetNames() {\n\t\tbytes, err := Asset(path)\n\t\tif err != nil {\n\t\t\tlog.Panicf(\"Unable to parse: path=%s, err=%s\", path, err)\n\t\t}\n\t\ttemplates.New(path).Parse(string(bytes))\n\t}\n}", "func SetUp(t *assert.Assertions, store SimpleStore) {\n\tfor i := 0; i < 100; i++ {\n\t\tif i < 100/2 {\n\t\t\tt.NoError(store.Write([]index.Field{{\n\t\t\t\tKey: serviceName,\n\t\t\t\tTerm: []byte(\"gateway\"),\n\t\t\t}}, common.ItemID(i)))\n\t\t} else {\n\t\t\tt.NoError(store.Write([]index.Field{{\n\t\t\t\tKey: serviceName,\n\t\t\t\tTerm: []byte(\"webpage\"),\n\t\t\t}}, common.ItemID(i)))\n\t\t}\n\t}\n}", "func initializeDocument(document_url string) (goquery.Document, error) {\n\treturn goquery.NewDocument(document_url)\n}", "func NewSamples(dir, scsynthAddr string) (*Samples, error) {\n\tsamp, err := sampler.New(scsynthAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts := &Samples{\n\t\tSampler: samp,\n\t}\n\tif err := s.loadSamples(dir); err != nil {\n\t\treturn nil, errors.Wrap(err, \"loading samples\")\n\t}\n\tlog.Println(\"loaded samples\")\n\n\treturn s, nil\n}", "func TestUpdateDocuments1(t *testing.T) {\n\tctx := context.Background()\n\t// don't use disallowUnknownFields in this test - we have here custom structs defined\n\tc := createClient(t, &testsClientConfig{skipDisallowUnknownFields: true})\n\tdb := ensureDatabase(ctx, c, \"document_test\", nil, t)\n\tcol := ensureCollection(ctx, db, \"documents_test\", nil, t)\n\tdocs := []UserDoc{\n\t\t{\n\t\t\t\"Piere\",\n\t\t\t23,\n\t\t},\n\t\t{\n\t\t\t\"Otto\",\n\t\t\t43,\n\t\t},\n\t}\n\tmetas, errs, err := col.CreateDocuments(ctx, docs)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create new documents: %s\", describe(err))\n\t} else if err := errs.FirstNonNil(); err != nil {\n\t\tt.Fatalf(\"Expected no errors, got first: %s\", describe(err))\n\t}\n\t// Update documents\n\tupdates := []map[string]interface{}{\n\t\t{\n\t\t\t\"name\": \"Updated1\",\n\t\t},\n\t\t{\n\t\t\t\"name\": \"Updated2\",\n\t\t},\n\t}\n\tif _, _, err := col.UpdateDocuments(ctx, metas.Keys(), updates); err != nil {\n\t\tt.Fatalf(\"Failed to update documents: %s\", describe(err))\n\t}\n\t// Read updated documents\n\tfor i, meta := range metas {\n\t\tvar readDoc UserDoc\n\t\tif _, err := col.ReadDocument(ctx, meta.Key, &readDoc); err != nil {\n\t\t\tt.Fatalf(\"Failed to read document '%s': %s\", meta.Key, describe(err))\n\t\t}\n\t\tdoc := docs[i]\n\t\tdoc.Name = fmt.Sprintf(\"Updated%d\", i+1)\n\t\tif !reflect.DeepEqual(doc, readDoc) {\n\t\t\tt.Errorf(\"Got wrong document %d. Expected %+v, got %+v\", i, doc, readDoc)\n\t\t}\n\t}\n}", "func makeData() {\n\tfile, err := os.Create(\"testdata/data.txt\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer file.Close()\n\n\trand.Seed(1)\n\tfor i := 0; i < 10000; i++ {\n\t\tdata := makeWord(rand.Intn(10) + 1)\n\t\tfile.Write(data)\n\t}\n}", "func init() {\n\t// var err error\n\t// tmpl, err = template.ParseFiles(\"templates/hello.gohtml\")\n\t// if err != nil {\n\t// \tpanic(err)\n\t// }\n\ttmpl = template.Must(template.ParseGlob(\"templates/*.gohtml\"))\n\n}", "func RandomScene() World {\n\tw := World{\n\t\tSphere{\n\t\t\tCenter: Vec3{0, -1000, 0},\n\t\t\tRadius: 1000,\n\t\t\tMaterial: Lambertian{\n\t\t\t\tAlbedo: Vec3{0.5, 0.5, 0.5},\n\t\t\t},\n\t\t},\n\t\tSphere{\n\t\t\tCenter: Vec3{0, 1, 0},\n\t\t\tRadius: 1,\n\t\t\tMaterial: Dielectric{RefIndex: 1.5},\n\t\t},\n\t\tSphere{\n\t\t\tCenter: Vec3{-4, 1, 0},\n\t\t\tRadius: 1,\n\t\t\tMaterial: Lambertian{\n\t\t\t\tAlbedo: Vec3{0.4, 0.2, 0.1},\n\t\t\t},\n\t\t},\n\t\tSphere{\n\t\t\tCenter: Vec3{0.7, 0.6, 0.5},\n\t\t\tRadius: 1,\n\t\t\tMaterial: Metal{\n\t\t\t\tFuzz: 0,\n\t\t\t\tAlbedo: Vec3{0.7, 0.6, 0.5},\n\t\t\t},\n\t\t},\n\t}\n\tfor a := -11; a < 11; a++ {\n\t\tfor b := -11; b < 11; b++ {\n\t\t\tcenter := Vec3{float64(a) + 0.9 + rand.Float64(), 0.2, float64(b) + 0.9 + rand.Float64()}\n\t\t\tif center.Sub(Vec3{4, 0.2, 0}).Len() > 0.9 {\n\t\t\t\tw = append(w, Sphere{\n\t\t\t\t\tCenter: center,\n\t\t\t\t\tRadius: 0.2,\n\t\t\t\t\tMaterial: RandomMaterial(),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\treturn w\n}", "func setup() {\r\n\tvar err error\r\n\tclient, err = mongo.NewClient(options.Client().ApplyURI(\"mongodb://127.0.0.1:27017\"))\r\n\tif err != nil {\r\n\t\tlog.Fatalf(\"init test failed... %s\", err)\r\n\t}\r\n\tctx, _ := context.WithTimeout(context.Background(), 10*time.Second) //time out for connection attempts.\r\n\terr = client.Connect(ctx)\r\n\tif err != nil {\r\n\t\tlog.Fatalf(\"init test failed... %s\", err)\r\n\t}\r\n\r\n\tlen := 5\r\n\tb := make([]byte, len)\r\n\tif _, err := rand.Read(b); err != nil {\r\n\t\tlog.Fatalf(\"init test failed... %s\", err)\r\n\t}\r\n\r\n\tfirstname = fmt.Sprintf(\"%X\", b)\r\n\tlastname = fmt.Sprintf(\"%X\", b)\r\n}", "func getTagDocuments(p config.Config, swagger *openapi3.Swagger, allDocuments docs.Index) docs.Index {\n\tio.WriteString(os.Stdout, fmt.Sprintf(\"\\033[1m %s\\033[0m (%v tags)\\n\", \"Tags\", len(swagger.Tags)))\n\tfor _, tag := range swagger.Tags {\n\n\t\tvar document docs.Document\n\n\t\t// Basics.\n\t\tdocument.Site = p.Name\n\t\tdocument.Title = tag.Name\n\t\tdocument.Section = \"\"\n\t\tdocument.Subsection = \"\"\n\n\t\t// URLs.\n\t\trel_url := fmt.Sprintf(\"#tag/%s\", strings.Replace(tag.Name, \" \", \"-\", -1))\n\t\tfull_url := fmt.Sprintf(\"%s%s\", p.URL, rel_url)\n\t\tdocument.URL = full_url\n\t\tdocument.RelativeURL = fmt.Sprintf(\"/%s\", rel_url)\n\n\t\t// DocumentID hash.\n\t\th := sha1.New()\n\t\th.Write([]byte(full_url))\n\t\tdocument.DocumentID = fmt.Sprintf(\"%x\", h.Sum(nil))\n\n\t\t// Match `config.yaml` rank, and use React primary/secondary designation.\n\t\tdocument.Rank = p.Rank\n\t\tif p.Rank == 1 {\n\t\t\tdocument.Source = \"primary\"\n\t\t} else {\n\t\t\tdocument.Source = \"secondary\"\n\t\t}\n\n\t\t// Document body text.\n\t\tdocument.Text = strings.Replace(tag.Description, \"\\n\", \" \", -1)\n\n\t\t// Document description.\n\t\tdocument.Description = strings.Replace(tag.Description, \"\\n\", \" \", -1)\n\n\t\t// Append the document.\n\t\tallDocuments.Documents = append(allDocuments.Documents, document)\n\t}\n\n\treturn allDocuments\n}", "func init() {\n\tSample = map[string]Personas{\n\t\t\"1\": Personas{Id: \"1\", Nombre: \"Luis\", Apellido: \"Perez\"},\n\t\t\"2\": Personas{Id: \"2\", Nombre: \"Maria\", Apellido: \"Romano\"},\n\t\t\"3\": Personas{Id: \"3\", Nombre: \"Nestor\", Apellido: \"Sanchez\"},\n\t}\n}", "func Test_DocumentJsonRoundTrip(t *testing.T) {\n\tjsonified, err := json.Marshal(example_doc)\n\tif err != nil {\n\t\tt.Fatalf(\"Error marshaling json: %s\", err.Error())\n\t}\n\n\tvar doc_copy *Document\n\terr = json.Unmarshal(jsonified, &doc_copy)\n\tif err != nil {\n\t\tt.Fatalf(\"Error unmarshaling json: %s\", err.Error())\n\t}\n\n\tif doc_copy == nil || example_doc != *doc_copy {\n\t\tt.Error(\"JSON roundtrip produced unlike values\")\n\t}\n}", "func init() {\n\ttopLevelTemplates = template.Must(template.ParseGlob(\"./views/*.go.html\"))\n\tpageTemplates = template.Must(template.ParseGlob(\"./views/pages/*.go.html\"))\n}", "func init() {\r\n\ttpl = template.Must(template.ParseGlob(\"templates/*\"))\r\n}", "func main() {\n\tenv, err := plugins.NewEnvironment()\n\tenv.RespondAndExitIfError(err)\n\n\tvar stats *statistics.DocumentStatistics\n\n\tfor _, model := range env.Request.Models {\n\t\tswitch model.TypeUrl {\n\t\tcase \"openapi.v2.Document\":\n\t\t\tdocumentv2 := &openapiv2.Document{}\n\t\t\terr = proto.Unmarshal(model.Value, documentv2)\n\t\t\tif err == nil {\n\t\t\t\t// Analyze the API document.\n\t\t\t\tstats = statistics.NewDocumentStatistics(env.Request.SourceName, documentv2)\n\t\t\t}\n\t\tcase \"openapi.v3.Document\":\n\t\t\tdocumentv3 := &openapiv3.Document{}\n\t\t\terr = proto.Unmarshal(model.Value, documentv3)\n\t\t\tif err == nil {\n\t\t\t\t// Analyze the API document.\n\t\t\t\tstats = statistics.NewDocumentStatisticsV3(env.Request.SourceName, documentv3)\n\t\t\t}\n\t\t}\n\t}\n\n\tif stats != nil {\n\t\t// Return the analysis results with an appropriate filename.\n\t\t// Results are in files named \"summary.json\" in the same relative\n\t\t// locations as the description source files.\n\t\tfile := &plugins.File{}\n\t\tfile.Name = strings.Replace(stats.Name, path.Base(stats.Name), \"summary.json\", -1)\n\t\tfile.Data, err = json.MarshalIndent(stats, \"\", \" \")\n\t\tfile.Data = append(file.Data, []byte(\"\\n\")...)\n\t\tenv.RespondAndExitIfError(err)\n\t\tenv.Response.Files = append(env.Response.Files, file)\n\t}\n\n\tenv.RespondAndExit()\n}", "func generateResponsesDB(poll *Poll) {\n\ts1 := rand.NewSource(time.Now().UnixNano())\n\tr1 := rand.New(s1)\n\n\tnumber := 4 + r1.Intn(7)\n\tresponses := make([]Response, number)\n\toptions := len(poll.Options)\n\n\tfor i := 0; i < number; i++ {\n\t\tresponses[i].Ratings = make([]float64, options)\n\n\t\tfor j := 0; j < options; j++ {\n\t\t\trating := -2 + r1.Intn(5)\n\t\t\tresponses[i].Ratings[j] = float64(rating)\n\t\t}\n\n\t\tresponse := responses[i]\n\n\t\tif err := submitResponseDB(poll.ID, &response); err != nil {\n\t\t\tlog.Println(\"generate responses error\", err)\n\t\t}\n\t}\n}", "func (w *InstallationSuite) PopulateSampleData(ctx context.Context) error {\n\t// Do not generate guest user as by default guest accounts are disabled,\n\t// which results in guest users being deactivated when Mattermost restarts.\n\t_, err := w.client.ExecClusterInstallationCLI(w.Meta.ClusterInstallationID, \"mmctl\", []string{\"--local\", \"sampledata\", \"--teams\", \"4\", \"--channels-per-team\", \"15\", \"--guests\", \"0\"})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"while populating sample data for CI\")\n\t}\n\tw.logger.Info(\"Sample data generated\")\n\n\treturn nil\n}", "func runGenerator(cmd *cobra.Command, args []string) error {\n\tif filename == \"\" {\n\t\tfilename = \"example.json\"\n\t}\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tvar m *MatrixGenerator\n\n\tif interactive {\n\t\tvar err error\n\t\tm, err = NewInteractiveMatrixGenerator()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tt := Random\n\t\tif constness == \"constant\" {\n\t\t\tt = Constant\n\t\t}\n\n\t\tm = NewManualMatrixGenerator(size, t)\n\t}\n\tm.Run()\n\treturn m.Save(f)\n}", "func init() {\n\ttpl = template.Must(template.ParseGlob(\"templates/*\"))\n}", "func init() {\n\ttpl = template.Must(template.ParseGlob(\"./*txt\"))\n}", "func (g *Generator) RandomDocumentForClinicalNote(ctx context.Context, np *pathway.ClinicalNote, note *ir.ClinicalNote, eventTime time.Time) (*ir.ClinicalNote, error) {\n\tif note == nil {\n\t\tnote = &ir.ClinicalNote{\n\t\t\tDocumentID: g.id(np.DocumentID),\n\t\t\tDateTime: ir.NewValidTime(eventTime),\n\t\t}\n\t}\n\n\tif note.DocumentType == \"\" || np.DocumentType != \"\" {\n\t\tnote.DocumentType = g.documentType(np.DocumentType)\n\t}\n\tif np.DocumentTitle != \"\" {\n\t\tnote.DocumentTitle = np.DocumentTitle\n\t}\n\n\tdocumentContent, encoding, err := g.contentAndEncoding(ctx, np.ContentType, np.DocumentContent)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnote.Contents = append(note.Contents, &ir.ClinicalNoteContent{\n\t\tContentType: np.ContentType,\n\t\tDocumentContent: documentContent,\n\t\tDocumentEncoding: encoding,\n\t\tObservationDateTime: ir.NewValidTime(eventTime),\n\t})\n\treturn note, nil\n}", "func init() {\n\ttmpl = template.Must(template.ParseGlob(\"templates/*\"))\n}", "func Test1(t *testing.T) {\n\tlog.Print(\"\\n\\n========== SOLUTION 1 =========\\n\\n\\n\")\n\tfor i, example := range examples {\n\t\tresult, err := parse(example)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\n\t\tx, err := json.MarshalIndent(result, \" \", \" \")\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tlog.Printf(\"Example %d: %s - %s\", i, example, string(x))\n\t}\n}", "func (m *CFDocument) Init(uriPrefix string, baseName string) {\n\trandomSuffix, _ := random()\n\tname := \"http://frameworks.act.org/CFDocuments/\" + baseName + \"/\" + randomSuffix\n\n\tid := uuid.NewV5(uuid.NamespaceDNS, name)\n\n\tm.URI = uriPrefix + \"/CFDocuments/\" + id.String()\n\tm.CFPackageURI = uriPrefix + \"/CFPackages/\" + id.String()\n\tm.Identifier = id.String()\n\tm.Creator = \"subjectsToCase\"\n\tm.Title = baseName\n\tm.Description = baseName\n\tt := time.Now()\n\tm.LastChangeDateTime = fmt.Sprintf(\"%d-%02d-%02dT%02d:%02d:%02d+00:00\",\n\t\tt.Year(), t.Month(), t.Day(),\n\t\tt.Hour(), t.Minute(), t.Second())\n}", "func QueryArrayEmbeddedDocumentsExamples(t *testing.T, db *mongo.Database) {\n\tcoll := db.Collection(\"inventory_query_array_embedded\")\n\n\terr := coll.Drop(context.Background())\n\trequire.NoError(t, err)\n\n\t{\n\t\t// Start Example 29\n\n\t\tdocs := []interface{}{\n\t\t\tbson.D{\n\t\t\t\t{\"item\", \"journal\"},\n\t\t\t\t{\"instock\", bson.A{\n\t\t\t\t\tbson.D{\n\t\t\t\t\t\t{\"warehouse\", \"A\"},\n\t\t\t\t\t\t{\"qty\", 5},\n\t\t\t\t\t},\n\t\t\t\t\tbson.D{\n\t\t\t\t\t\t{\"warehouse\", \"C\"},\n\t\t\t\t\t\t{\"qty\", 15},\n\t\t\t\t\t},\n\t\t\t\t}},\n\t\t\t},\n\t\t\tbson.D{\n\t\t\t\t{\"item\", \"notebook\"},\n\t\t\t\t{\"instock\", bson.A{\n\t\t\t\t\tbson.D{\n\t\t\t\t\t\t{\"warehouse\", \"C\"},\n\t\t\t\t\t\t{\"qty\", 5},\n\t\t\t\t\t},\n\t\t\t\t}},\n\t\t\t},\n\t\t\tbson.D{\n\t\t\t\t{\"item\", \"paper\"},\n\t\t\t\t{\"instock\", bson.A{\n\t\t\t\t\tbson.D{\n\t\t\t\t\t\t{\"warehouse\", \"A\"},\n\t\t\t\t\t\t{\"qty\", 60},\n\t\t\t\t\t},\n\t\t\t\t\tbson.D{\n\t\t\t\t\t\t{\"warehouse\", \"B\"},\n\t\t\t\t\t\t{\"qty\", 15},\n\t\t\t\t\t},\n\t\t\t\t}},\n\t\t\t},\n\t\t\tbson.D{\n\t\t\t\t{\"item\", \"planner\"},\n\t\t\t\t{\"instock\", bson.A{\n\t\t\t\t\tbson.D{\n\t\t\t\t\t\t{\"warehouse\", \"A\"},\n\t\t\t\t\t\t{\"qty\", 40},\n\t\t\t\t\t},\n\t\t\t\t\tbson.D{\n\t\t\t\t\t\t{\"warehouse\", \"B\"},\n\t\t\t\t\t\t{\"qty\", 5},\n\t\t\t\t\t},\n\t\t\t\t}},\n\t\t\t},\n\t\t\tbson.D{\n\t\t\t\t{\"item\", \"postcard\"},\n\t\t\t\t{\"instock\", bson.A{\n\t\t\t\t\tbson.D{\n\t\t\t\t\t\t{\"warehouse\", \"B\"},\n\t\t\t\t\t\t{\"qty\", 15},\n\t\t\t\t\t},\n\t\t\t\t\tbson.D{\n\t\t\t\t\t\t{\"warehouse\", \"C\"},\n\t\t\t\t\t\t{\"qty\", 35},\n\t\t\t\t\t},\n\t\t\t\t}},\n\t\t\t},\n\t\t}\n\n\t\tresult, err := coll.InsertMany(context.Background(), docs)\n\n\t\t// End Example 29\n\n\t\trequire.NoError(t, err)\n\t\trequire.Len(t, result.InsertedIDs, 5)\n\t}\n\n\t{\n\t\t// Start Example 30\n\n\t\tcursor, err := coll.Find(\n\t\t\tcontext.Background(),\n\t\t\tbson.D{\n\t\t\t\t{\"instock\", bson.D{\n\t\t\t\t\t{\"warehouse\", \"A\"},\n\t\t\t\t\t{\"qty\", 5},\n\t\t\t\t}},\n\t\t\t})\n\n\t\t// End Example 30\n\n\t\trequire.NoError(t, err)\n\t\trequireCursorLength(t, cursor, 1)\n\t}\n\n\t{\n\t\t// Start Example 31\n\n\t\tcursor, err := coll.Find(\n\t\t\tcontext.Background(),\n\t\t\tbson.D{\n\t\t\t\t{\"instock\", bson.D{\n\t\t\t\t\t{\"qty\", 5},\n\t\t\t\t\t{\"warehouse\", \"A\"},\n\t\t\t\t}},\n\t\t\t})\n\n\t\t// End Example 31\n\n\t\trequire.NoError(t, err)\n\t\trequireCursorLength(t, cursor, 0)\n\t}\n\n\t{\n\t\t// Start Example 32\n\n\t\tcursor, err := coll.Find(\n\t\t\tcontext.Background(),\n\t\t\tbson.D{\n\t\t\t\t{\"instock.0.qty\", bson.D{\n\t\t\t\t\t{\"$lte\", 20},\n\t\t\t\t}},\n\t\t\t})\n\n\t\t// End Example 32\n\n\t\trequire.NoError(t, err)\n\t\trequireCursorLength(t, cursor, 3)\n\t}\n\n\t{\n\t\t// Start Example 33\n\n\t\tcursor, err := coll.Find(\n\t\t\tcontext.Background(),\n\t\t\tbson.D{\n\t\t\t\t{\"instock.qty\", bson.D{\n\t\t\t\t\t{\"$lte\", 20},\n\t\t\t\t}},\n\t\t\t})\n\n\t\t// End Example 33\n\n\t\trequire.NoError(t, err)\n\t\trequireCursorLength(t, cursor, 5)\n\t}\n\n\t{\n\t\t// Start Example 34\n\n\t\tcursor, err := coll.Find(\n\t\t\tcontext.Background(),\n\t\t\tbson.D{\n\t\t\t\t{\"instock\", bson.D{\n\t\t\t\t\t{\"$elemMatch\", bson.D{\n\t\t\t\t\t\t{\"qty\", 5},\n\t\t\t\t\t\t{\"warehouse\", \"A\"},\n\t\t\t\t\t}},\n\t\t\t\t}},\n\t\t\t})\n\n\t\t// End Example 34\n\n\t\trequire.NoError(t, err)\n\t\trequireCursorLength(t, cursor, 1)\n\t}\n\n\t{\n\t\t// Start Example 35\n\n\t\tcursor, err := coll.Find(\n\t\t\tcontext.Background(),\n\t\t\tbson.D{\n\t\t\t\t{\"instock\", bson.D{\n\t\t\t\t\t{\"$elemMatch\", bson.D{\n\t\t\t\t\t\t{\"qty\", bson.D{\n\t\t\t\t\t\t\t{\"$gt\", 10},\n\t\t\t\t\t\t\t{\"$lte\", 20},\n\t\t\t\t\t\t}},\n\t\t\t\t\t}},\n\t\t\t\t}},\n\t\t\t})\n\n\t\t// End Example 35\n\n\t\trequire.NoError(t, err)\n\t\trequireCursorLength(t, cursor, 3)\n\t}\n\n\t{\n\t\t// Start Example 36\n\n\t\tcursor, err := coll.Find(\n\t\t\tcontext.Background(),\n\t\t\tbson.D{\n\t\t\t\t{\"instock.qty\", bson.D{\n\t\t\t\t\t{\"$gt\", 10},\n\t\t\t\t\t{\"$lte\", 20},\n\t\t\t\t}},\n\t\t\t})\n\n\t\t// End Example 36\n\n\t\trequire.NoError(t, err)\n\t\trequireCursorLength(t, cursor, 4)\n\t}\n\n\t{\n\t\t// Start Example 37\n\n\t\tcursor, err := coll.Find(\n\t\t\tcontext.Background(),\n\t\t\tbson.D{\n\t\t\t\t{\"instock.qty\", 5},\n\t\t\t\t{\"instock.warehouse\", \"A\"},\n\t\t\t})\n\n\t\t// End Example 37\n\n\t\trequire.NoError(t, err)\n\t\trequireCursorLength(t, cursor, 2)\n\t}\n}", "func (w *Wheel) InitializePopulation() error {\n\titems := make([]interface{}, 0, len(w.Slices))\n\tweights := make([]int64, 0, len(w.Slices))\n\tfor _, slice := range w.Slices {\n\t\titems = append(items, slice.Value)\n\t\tweights = append(weights, slice.Weight)\n\t}\n\tvar err error\n\tw.Population, err = sampling.NewPopulation(items, weights)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to create population\")\n\t}\n\treturn nil\n}", "func (m *Storage) AddSampleRecipes() {\n\n\tfor _, recipe := range SampleMeals {\n\t\tm.recipes = append(m.recipes, recipe)\n\t}\n\n}", "func (i *Index) Create() error {\n\n\tdoc := mapping{Properties: map[string]mappingProperty{}}\n\tfor _, f := range i.md.Fields {\n\t\tdoc.Properties[f.Name] = mappingProperty{}\n\t\tfs, err := fieldTypeString(f.Type)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdoc.Properties[f.Name][\"type\"] = fs\n\t}\n\n // Added for apple to apple benchmark\n doc.Properties[\"body\"][\"type\"] = \"text\"\n doc.Properties[\"body\"][\"analyzer\"] = \"my_english_analyzer\"\n doc.Properties[\"body\"][\"search_analyzer\"] = \"whitespace\"\n doc.Properties[\"body\"][\"index_options\"] = \"offsets\"\n //doc.Properties[\"body\"][\"test\"] = \"test\"\n index_map := map[string]int{\n \"number_of_shards\" : 1,\n \"number_of_replicas\" : 0,\n }\n analyzer_map := map[string]interface{}{\n \"my_english_analyzer\": map[string]interface{}{\n \"tokenizer\": \"standard\",\n \"char_filter\": []string{ \"html_strip\" } ,\n \"filter\" : []string{\"english_possessive_stemmer\", \n \"lowercase\", \"english_stop\", \n \"english_stemmer\", \n \"asciifolding\", \"icu_folding\"},\n },\n }\n filter_map := map[string]interface{}{\n \"english_stop\": map[string]interface{}{\n \"type\": \"stop\",\n \"stopwords\": \"_english_\",\n },\n \"english_possessive_stemmer\": map[string]interface{}{\n \"type\": \"stemmer\",\n \"language\": \"possessive_english\",\n },\n \"english_stemmer\" : map[string]interface{}{\n \"type\" : \"stemmer\",\n \"name\" : \"english\",\n },\n \"my_folding\": map[string]interface{}{\n \"type\": \"asciifolding\",\n \"preserve_original\": \"false\",\n },\n }\n analysis_map := map[string]interface{}{\n \"analyzer\": analyzer_map,\n \"filter\" : filter_map,\n }\n settings := map[string]interface{}{\n \"index\": index_map,\n \"analysis\": analysis_map,\n }\n\n // TODO delete?\n\t// we currently manually create the autocomplete mapping\n\t/*ac := mapping{\n\t\tProperties: map[string]mappingProperty{\n\t\t\t\"sugg\": mappingProperty{\n\t\t\t\t\"type\": \"completion\",\n\t\t\t\t\"payloads\": true,\n\t\t\t},\n\t\t},\n\t}*/\n\n\tmappings := map[string]mapping{\n\t\ti.typ: doc,\n //\t\"autocomplete\": ac,\n\t}\n\n fmt.Println(mappings)\n\n\t//_, err := i.conn.CreateIndex(i.name).BodyJson(map[string]interface{}{\"mappings\": mappings}).Do()\n\t_, err := i.conn.CreateIndex(i.name).BodyJson(map[string]interface{}{\"mappings\": mappings, \"settings\": settings}).Do()\n\n if err != nil {\n fmt.Println(\"Error \", err)\n\t\tfmt.Println(\"!!!!Get Error when using client to create index\")\n\t}\n\n\treturn err\n}", "func (tr *TestRecorder) init() {}", "func Test_NewResources(t *testing.T) {\n\ttype args struct {\n\t\tbody []byte\n\t\theader map[string][]string\n\t\tbinding ResolvedTrigger\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twant []json.RawMessage\n\t}{{\n\t\tname: \"empty\",\n\t\targs: args{\n\t\t\tbody: json.RawMessage{},\n\t\t\theader: map[string][]string{},\n\t\t\tbinding: ResolvedTrigger{\n\t\t\t\tTriggerTemplate: bldr.TriggerTemplate(\"tt\", \"namespace\"),\n\t\t\t\tTriggerBindings: []*triggersv1.TriggerBinding{bldr.TriggerBinding(\"tb\", \"namespace\")},\n\t\t\t},\n\t\t},\n\t\twant: []json.RawMessage{},\n\t}, {\n\t\tname: \"one resource template\",\n\t\targs: args{\n\t\t\tbody: json.RawMessage(`{\"foo\": \"bar\"}`),\n\t\t\theader: map[string][]string{\"one\": {\"1\"}},\n\t\t\tbinding: ResolvedTrigger{\n\t\t\t\tTriggerTemplate: bldr.TriggerTemplate(\"tt\", \"namespace\",\n\t\t\t\t\tbldr.TriggerTemplateSpec(\n\t\t\t\t\t\tbldr.TriggerTemplateParam(\"param1\", \"description\", \"\"),\n\t\t\t\t\t\tbldr.TriggerTemplateParam(\"param2\", \"description\", \"\"),\n\t\t\t\t\t\tbldr.TriggerResourceTemplate(json.RawMessage(`{\"rt1\": \"$(params.param1)-$(params.param2)\"}`)),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\tTriggerBindings: []*triggersv1.TriggerBinding{\n\t\t\t\t\tbldr.TriggerBinding(\"tb\", \"namespace\",\n\t\t\t\t\t\tbldr.TriggerBindingSpec(\n\t\t\t\t\t\t\tbldr.TriggerBindingParam(\"param1\", \"$(body.foo)\"),\n\t\t\t\t\t\t\tbldr.TriggerBindingParam(\"param2\", \"$(header.one)\"),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\twant: []json.RawMessage{\n\t\t\tjson.RawMessage(`{\"rt1\": \"bar-1\"}`),\n\t\t},\n\t}, {\n\t\tname: \"multiple resource templates\",\n\t\targs: args{\n\t\t\tbody: json.RawMessage(`{\"foo\": \"bar\"}`),\n\t\t\theader: map[string][]string{\"one\": {\"1\"}},\n\t\t\tbinding: ResolvedTrigger{\n\t\t\t\tTriggerTemplate: bldr.TriggerTemplate(\"tt\", \"namespace\",\n\t\t\t\t\tbldr.TriggerTemplateSpec(\n\t\t\t\t\t\tbldr.TriggerTemplateParam(\"param1\", \"description\", \"\"),\n\t\t\t\t\t\tbldr.TriggerTemplateParam(\"param2\", \"description\", \"\"),\n\t\t\t\t\t\tbldr.TriggerTemplateParam(\"param3\", \"description\", \"default2\"),\n\t\t\t\t\t\tbldr.TriggerResourceTemplate(json.RawMessage(`{\"rt1\": \"$(params.param1)-$(params.param2)\"}`)),\n\t\t\t\t\t\tbldr.TriggerResourceTemplate(json.RawMessage(`{\"rt2\": \"$(params.param3)\"}`)),\n\t\t\t\t\t\tbldr.TriggerResourceTemplate(json.RawMessage(`{\"rt3\": \"rt3\"}`)),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\tTriggerBindings: []*triggersv1.TriggerBinding{\n\t\t\t\t\tbldr.TriggerBinding(\"tb\", \"namespace\",\n\t\t\t\t\t\tbldr.TriggerBindingSpec(\n\t\t\t\t\t\t\tbldr.TriggerBindingParam(\"param1\", \"$(body.foo)\"),\n\t\t\t\t\t\t\tbldr.TriggerBindingParam(\"param2\", \"$(header.one)\"),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\twant: []json.RawMessage{\n\t\t\tjson.RawMessage(`{\"rt1\": \"bar-1\"}`),\n\t\t\tjson.RawMessage(`{\"rt2\": \"default2\"}`),\n\t\t\tjson.RawMessage(`{\"rt3\": \"rt3\"}`),\n\t\t},\n\t}, {\n\t\tname: \"one resource template with one uid\",\n\t\targs: args{\n\t\t\tbody: json.RawMessage(`{\"foo\": \"bar\"}`),\n\t\t\tbinding: ResolvedTrigger{\n\t\t\t\tTriggerTemplate: bldr.TriggerTemplate(\"tt\", \"namespace\",\n\t\t\t\t\tbldr.TriggerTemplateSpec(\n\t\t\t\t\t\tbldr.TriggerTemplateParam(\"param1\", \"description\", \"\"),\n\t\t\t\t\t\tbldr.TriggerResourceTemplate(json.RawMessage(`{\"rt1\": \"$(params.param1)-$(uid)\"}`)),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\tTriggerBindings: []*triggersv1.TriggerBinding{\n\t\t\t\t\tbldr.TriggerBinding(\"tb\", \"namespace\",\n\t\t\t\t\t\tbldr.TriggerBindingSpec(\n\t\t\t\t\t\t\tbldr.TriggerBindingParam(\"param1\", \"$(body.foo)\"),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\twant: []json.RawMessage{\n\t\t\tjson.RawMessage(`{\"rt1\": \"bar-cbhtc\"}`),\n\t\t},\n\t}, {\n\t\tname: \"one resource template with three uid\",\n\t\targs: args{\n\t\t\tbody: json.RawMessage(`{\"foo\": \"bar\"}`),\n\t\t\tbinding: ResolvedTrigger{\n\t\t\t\tTriggerTemplate: bldr.TriggerTemplate(\"tt\", \"namespace\",\n\t\t\t\t\tbldr.TriggerTemplateSpec(\n\t\t\t\t\t\tbldr.TriggerTemplateParam(\"param1\", \"description\", \"\"),\n\t\t\t\t\t\tbldr.TriggerResourceTemplate(json.RawMessage(`{\"rt1\": \"$(params.param1)-$(uid)-$(uid)\", \"rt2\": \"$(uid)\"}`)),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\tTriggerBindings: []*triggersv1.TriggerBinding{\n\t\t\t\t\tbldr.TriggerBinding(\"tb\", \"namespace\",\n\t\t\t\t\t\tbldr.TriggerBindingSpec(\n\t\t\t\t\t\t\tbldr.TriggerBindingParam(\"param1\", \"$(body.foo)\"),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\twant: []json.RawMessage{\n\t\t\tjson.RawMessage(`{\"rt1\": \"bar-cbhtc-cbhtc\", \"rt2\": \"cbhtc\"}`),\n\t\t},\n\t}, {\n\t\tname: \"multiple resource templates with multiple uid\",\n\t\targs: args{\n\t\t\tbody: json.RawMessage(`{\"foo\": \"bar\"}`),\n\t\t\tbinding: ResolvedTrigger{\n\t\t\t\tTriggerTemplate: bldr.TriggerTemplate(\"tt\", \"namespace\",\n\t\t\t\t\tbldr.TriggerTemplateSpec(\n\t\t\t\t\t\tbldr.TriggerTemplateParam(\"param1\", \"description\", \"\"),\n\t\t\t\t\t\tbldr.TriggerTemplateParam(\"param2\", \"description\", \"default2\"),\n\t\t\t\t\t\tbldr.TriggerResourceTemplate(json.RawMessage(`{\"rt1\": \"$(params.param1)-$(uid)\", \"$(uid)\": \"$(uid)\"}`)),\n\t\t\t\t\t\tbldr.TriggerResourceTemplate(json.RawMessage(`{\"rt2\": \"$(params.param2)-$(uid)\"}`)),\n\t\t\t\t\t\tbldr.TriggerResourceTemplate(json.RawMessage(`{\"rt3\": \"rt3\"}`)),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\tTriggerBindings: []*triggersv1.TriggerBinding{\n\t\t\t\t\tbldr.TriggerBinding(\"tb\", \"namespace\",\n\t\t\t\t\t\tbldr.TriggerBindingSpec(\n\t\t\t\t\t\t\tbldr.TriggerBindingParam(\"param1\", \"$(body.foo)\"),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\twant: []json.RawMessage{\n\t\t\tjson.RawMessage(`{\"rt1\": \"bar-cbhtc\", \"cbhtc\": \"cbhtc\"}`),\n\t\t\tjson.RawMessage(`{\"rt2\": \"default2-cbhtc\"}`),\n\t\t\tjson.RawMessage(`{\"rt3\": \"rt3\"}`),\n\t\t},\n\t}, {\n\t\tname: \"one resource template multiple bindings\",\n\t\targs: args{\n\t\t\tbody: json.RawMessage(`{\"foo\": \"bar\"}`),\n\t\t\theader: map[string][]string{\"one\": {\"1\"}},\n\t\t\tbinding: ResolvedTrigger{\n\t\t\t\tTriggerTemplate: bldr.TriggerTemplate(\"tt\", \"namespace\",\n\t\t\t\t\tbldr.TriggerTemplateSpec(\n\t\t\t\t\t\tbldr.TriggerTemplateParam(\"param1\", \"description\", \"\"),\n\t\t\t\t\t\tbldr.TriggerTemplateParam(\"param2\", \"description\", \"\"),\n\t\t\t\t\t\tbldr.TriggerResourceTemplate(json.RawMessage(`{\"rt1\": \"$(params.param1)-$(params.param2)\"}`)),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\tTriggerBindings: []*triggersv1.TriggerBinding{\n\t\t\t\t\tbldr.TriggerBinding(\"tb\", \"namespace\",\n\t\t\t\t\t\tbldr.TriggerBindingSpec(\n\t\t\t\t\t\t\tbldr.TriggerBindingParam(\"param1\", \"$(body.foo)\"),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t\tbldr.TriggerBinding(\"tb2\", \"namespace\",\n\t\t\t\t\t\tbldr.TriggerBindingSpec(\n\t\t\t\t\t\t\tbldr.TriggerBindingParam(\"param2\", \"$(header.one)\"),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\twant: []json.RawMessage{\n\t\t\tjson.RawMessage(`{\"rt1\": \"bar-1\"}`),\n\t\t},\n\t}, {\n\t\tname: \"bindings with static values\",\n\t\targs: args{\n\t\t\tbody: json.RawMessage(`{\"foo\": \"bar\"}`),\n\t\t\tbinding: ResolvedTrigger{\n\t\t\t\tTriggerTemplate: bldr.TriggerTemplate(\"tt\", \"ns\", bldr.TriggerTemplateSpec(\n\t\t\t\t\tbldr.TriggerTemplateParam(\"p1\", \"\", \"\"),\n\t\t\t\t\tbldr.TriggerTemplateParam(\"p2\", \"\", \"\"),\n\t\t\t\t\tbldr.TriggerResourceTemplate(json.RawMessage(`{\"p1\": \"$(params.p1)\", \"p2\": \"$(params.p2)\"}`)),\n\t\t\t\t),\n\t\t\t\t),\n\t\t\t\tTriggerBindings: []*triggersv1.TriggerBinding{\n\t\t\t\t\tbldr.TriggerBinding(\"tb\", \"ns\", bldr.TriggerBindingSpec(\n\t\t\t\t\t\tbldr.TriggerBindingParam(\"p1\", \"static_value\"),\n\t\t\t\t\t\tbldr.TriggerBindingParam(\"p2\", \"$(body.foo)\"),\n\t\t\t\t\t)),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\twant: []json.RawMessage{\n\t\t\tjson.RawMessage(`{\"p1\": \"static_value\", \"p2\": \"bar\"}`),\n\t\t},\n\t}, {\n\t\tname: \"bindings with combination of static values \",\n\t\targs: args{\n\t\t\tbody: json.RawMessage(`{\"foo\": \"fooValue\", \"bar\": \"barValue\"}`),\n\t\t\tbinding: ResolvedTrigger{\n\t\t\t\tTriggerTemplate: bldr.TriggerTemplate(\"tt\", \"ns\", bldr.TriggerTemplateSpec(\n\t\t\t\t\tbldr.TriggerTemplateParam(\"p1\", \"\", \"\"),\n\t\t\t\t\tbldr.TriggerResourceTemplate(json.RawMessage(`{\"p1\": \"$(params.p1)\"`)),\n\t\t\t\t),\n\t\t\t\t),\n\t\t\t\tTriggerBindings: []*triggersv1.TriggerBinding{\n\t\t\t\t\tbldr.TriggerBinding(\"tb\", \"ns\", bldr.TriggerBindingSpec(\n\t\t\t\t\t\tbldr.TriggerBindingParam(\"p1\", \"Event values are - foo: $(body.foo); bar: $(body.bar)\"),\n\t\t\t\t\t)),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\twant: []json.RawMessage{\n\t\t\tjson.RawMessage(`{\"p1\": \"Event values are - foo: fooValue; bar: barValue\"`),\n\t\t},\n\t}, {\n\t\tname: \"event value is JSON string\",\n\t\targs: args{\n\t\t\tbody: json.RawMessage(`{\"a\": \"b\"}`),\n\t\t\tbinding: ResolvedTrigger{\n\t\t\t\tTriggerTemplate: bldr.TriggerTemplate(\"tt\", \"ns\", bldr.TriggerTemplateSpec(\n\t\t\t\t\tbldr.TriggerTemplateParam(\"p1\", \"\", \"\"),\n\t\t\t\t\tbldr.TriggerResourceTemplate(json.RawMessage(`{\"p1\": \"$(params.p1)\"}`)),\n\t\t\t\t),\n\t\t\t\t),\n\t\t\t\tTriggerBindings: []*triggersv1.TriggerBinding{\n\t\t\t\t\tbldr.TriggerBinding(\"tb\", \"ns\", bldr.TriggerBindingSpec(\n\t\t\t\t\t\tbldr.TriggerBindingParam(\"p1\", \"$(body)\"),\n\t\t\t\t\t)),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\twant: []json.RawMessage{\n\t\t\tjson.RawMessage(`{\"p1\": \"{\\\"a\\\":\\\"b\\\"}\"}`),\n\t\t},\n\t}, {\n\t\tname: \"header event values\",\n\t\targs: args{\n\t\t\theader: map[string][]string{\n\t\t\t\t\"a\": {\"singlevalue\"},\n\t\t\t\t\"b\": {\"multiple\", \"values\"},\n\t\t\t},\n\t\t\tbinding: ResolvedTrigger{\n\t\t\t\tTriggerTemplate: bldr.TriggerTemplate(\"tt\", \"ns\", bldr.TriggerTemplateSpec(\n\t\t\t\t\tbldr.TriggerTemplateParam(\"p1\", \"\", \"\"),\n\t\t\t\t\tbldr.TriggerTemplateParam(\"p2\", \"\", \"\"),\n\t\t\t\t\tbldr.TriggerResourceTemplate(json.RawMessage(`{\"p1\": \"$(params.p1)\",\"p2\": \"$(params.p2)\"}`)),\n\t\t\t\t),\n\t\t\t\t),\n\t\t\t\tTriggerBindings: []*triggersv1.TriggerBinding{\n\t\t\t\t\tbldr.TriggerBinding(\"tb\", \"ns\", bldr.TriggerBindingSpec(\n\t\t\t\t\t\tbldr.TriggerBindingParam(\"p1\", \"$(header.a)\"),\n\t\t\t\t\t\tbldr.TriggerBindingParam(\"p2\", \"$(header.b)\"),\n\t\t\t\t\t)),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\twant: []json.RawMessage{\n\t\t\tjson.RawMessage(`{\"p1\": \"singlevalue\",\"p2\": \"multiple,values\"}`),\n\t\t},\n\t}}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t// This seeds Uid() to return 'cbhtc'\n\t\t\trand.Seed(0)\n\t\t\tparams, err := ResolveParams(tt.args.binding.TriggerBindings, tt.args.body, tt.args.header, tt.args.binding.TriggerTemplate.Spec.Params)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"ResolveParams() returned unexpected error: %s\", err)\n\t\t\t}\n\t\t\tgot := ResolveResources(tt.args.binding.TriggerTemplate, params)\n\t\t\tif diff := cmp.Diff(tt.want, got); diff != \"\" {\n\t\t\t\tstringDiff := cmp.Diff(convertJSONRawMessagesToString(tt.want), convertJSONRawMessagesToString(got))\n\t\t\t\tt.Errorf(\"ResolveResources(): -want +got: %s\", stringDiff)\n\t\t\t}\n\t\t})\n\t}\n}", "func TestGetSlidesDocumentWithFormat(t *testing.T) {\n request := createGetSlidesDocumentWithFormatRequest()\n e := initializeTest(\"GetSlidesDocumentWithFormat\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.DocumentApi.GetSlidesDocumentWithFormat(request)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n assertBinaryResponse(r, t)\n}", "func loadRawExamples() {\n\t// load chef_run's for reuse\n\trawruns = make(map[string][]byte)\n\truns := []string{\n\t\t\"../../ingest-service/examples/chef_client_run.json\",\n\t\t\"../../ingest-service/examples/converge-bad-report.json\",\n\t\t\"../../ingest-service/examples/converge-failure-report.json\",\n\t\t\"../../ingest-service/examples/converge-success-report.json\",\n\t}\n\tfor _, r := range runs {\n\t\t// load chef_run json into memory, so that we do not count the json generation\n\t\tcontent, err := ioutil.ReadFile(r)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\trawruns[r] = content\n\t}\n\n\t// load chef_action's for reuse\n\trawactions = make(map[string][]byte)\n\tactions := []string{\n\t\t\"bag_create\",\n\t\t\"bag_create\",\n\t\t\"bag_delete\",\n\t\t\"client_create\",\n\t\t\"cookbookartifactversion_update\",\n\t\t\"environment_create\",\n\t\t\"environment_delete\",\n\t\t\"environment_update\",\n\t\t\"group_create\",\n\t\t\"group_update\",\n\t\t\"item_bag_create\",\n\t\t\"item_bag_update\",\n\t\t\"node_create\",\n\t\t\"node_delete\",\n\t\t\"org_create\",\n\t\t\"permission_update_container\",\n\t\t\"permission_update_cookbook\",\n\t\t\"permission_update_environment\",\n\t\t\"policy_update\",\n\t\t\"user_associate\",\n\t\t\"user_create\",\n\t\t\"user_invite\",\n\t\t\"user_update\",\n\t\t\"version_cookbook_create\",\n\t\t\"version_cookbook_update\",\n\t}\n\tfor _, a := range actions {\n\t\tcontent, err := ioutil.ReadFile(fmt.Sprintf(\"../../ingest-service/examples/actions/%s.json\", a))\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\trawactions[a] = content\n\t}\n\n\t// load liveness's for reuse\n\trawliveness = make(map[string][]byte)\n\tliveness := []string{\n\t\t\"liveness_ping\",\n\t}\n\tfor _, l := range liveness {\n\t\tcontent, err := ioutil.ReadFile(fmt.Sprintf(\"../../ingest-service/examples/%s.json\", l))\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\trawliveness[l] = content\n\t}\n\n\t// load report's for reuse\n\trawreports = make(map[string][]byte)\n\treports := []string{\n\t\t\"compliance-failure-big-report\",\n\t\t\"compliance-success-tiny-report\",\n\t}\n\tfor _, r := range reports {\n\t\tcontent, err := ioutil.ReadFile(fmt.Sprintf(\"../../compliance-service/ingest/examples/%s.json\", r))\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\trawreports[r] = content\n\t}\n}", "func TestPostSlidesDocumentInvalidtemplatePath(t *testing.T) {\n request := createPostSlidesDocumentRequest()\n request.templatePath = invalidizeTestParamValue(request.templatePath, \"templatePath\", \"string\").(string)\n e := initializeTest(\"PostSlidesDocument\", \"templatePath\", request.templatePath)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().DocumentApi.PostSlidesDocument(request)\n assertError(t, \"PostSlidesDocument\", \"templatePath\", r.Code, e)\n}", "func init() {\n\t// name must be set when using Execute, can be empty when using ExecuteTemplate, because there naem must be given\n\ttpl = template.Must(template.New(\"\").Funcs(fm).ParseGlob(\"tpl/*.gohtml\"))\n}", "func makeCorpus(numSeries, numValuesPerSeries int, fn func(*rand.Rand) interface{}) corpus {\n\trng := rand.New(rand.NewSource(int64(numSeries) * int64(numValuesPerSeries)))\n\tvar unixNano int64\n\tcorpus := make(corpus, numSeries)\n\tfor i := 0; i < numSeries; i++ {\n\t\tvals := make([]tsm1.Value, numValuesPerSeries)\n\t\tfor j := 0; j < numValuesPerSeries; j++ {\n\t\t\tvals[j] = tsm1.NewValue(unixNano, fn(rng))\n\t\t\tunixNano++\n\t\t}\n\n\t\tk := fmt.Sprintf(\"m,t=%d\", i)\n\t\tcorpus[tsm1.SeriesFieldKey(k, \"x\")] = vals\n\t}\n\n\treturn corpus\n}", "func BuildTestDocument() *did.Document {\n\tdoc := &did.Document{}\n\n\tmainDID, _ := didlib.Parse(testDID)\n\n\tdoc.ID = *mainDID\n\tdoc.Context = did.DefaultDIDContextV1\n\tdoc.Controller = mainDID\n\n\t// Public Keys\n\tpk1 := did.DocPublicKey{}\n\tpk1ID := fmt.Sprintf(\"%v#keys-1\", testDID)\n\td1, _ := didlib.Parse(pk1ID)\n\tpk1.ID = d1\n\tpk1.Type = linkeddata.SuiteTypeSecp256k1Verification\n\tpk1.Controller = mainDID\n\thexKey := \"04f3df3cea421eac2a7f5dbd8e8d505470d42150334f512bd6383c7dc91bf8fa4d5458d498b4dcd05574c902fb4c233005b3f5f3ff3904b41be186ddbda600580b\"\n\tpk1.PublicKeyHex = utils.StrToPtr(hexKey)\n\n\tdoc.PublicKeys = []did.DocPublicKey{pk1}\n\n\t// Service endpoints\n\tep1 := did.DocService{}\n\tep1ID := fmt.Sprintf(\"%v#vcr\", testDID)\n\td2, _ := didlib.Parse(ep1ID)\n\tep1.ID = *d2\n\tep1.Type = \"CredentialRepositoryService\"\n\tep1.ServiceEndpoint = \"https://repository.example.com/service/8377464\"\n\tep1.ServiceEndpointURI = utils.StrToPtr(\"https://repository.example.com/service/8377464\")\n\n\tdoc.Services = []did.DocService{ep1}\n\n\t// Authentication\n\taw1 := did.DocAuthenicationWrapper{}\n\taw1ID := fmt.Sprintf(\"%v#keys-1\", testDID)\n\td3, _ := didlib.Parse(aw1ID)\n\taw1.ID = d3\n\taw1.IDOnly = true\n\n\taw2 := did.DocAuthenicationWrapper{}\n\taw2ID := fmt.Sprintf(\"%v#keys-2\", testDID)\n\td4, _ := didlib.Parse(aw2ID)\n\taw2.ID = d4\n\taw2.IDOnly = false\n\taw2.Type = linkeddata.SuiteTypeSecp256k1Verification\n\taw2.Controller = mainDID\n\thexKey2 := \"04debef3fcbef3f5659f9169bad80044b287139a401b5da2979e50b032560ed33927eab43338e9991f31185b3152735e98e0471b76f18897d764b4e4f8a7e8f61b\"\n\taw2.PublicKeyHex = utils.StrToPtr(hexKey2)\n\n\tdoc.Authentications = []did.DocAuthenicationWrapper{aw1, aw2}\n\n\treturn doc\n}", "func (s *SampleManager) Initialize(app string) error {\n\tif app == \"\" {\n\t\treturn errors.New(\"Sample name is empty\")\n\t}\n\n\tappPath, err := s.appCacheFolder(app)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// We still set the repo path here. There are some failure cases\n\t// that we can still work with (like no updates or repo already exists)\n\ts.repoPath = appPath\n\n\tlist, err := s.SampleLister.ListSamples(\"create\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := s.Fs.Stat(appPath); os.IsNotExist(err) {\n\t\tsampleData, ok := list[app]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Sample %s does not exist\", app)\n\t\t}\n\t\terr = s.Git.Clone(appPath, sampleData.GitRepo())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\terr := s.Git.Pull(appPath)\n\t\tif err != nil {\n\t\t\tif err != nil {\n\t\t\t\tswitch e := err.Error(); e {\n\t\t\t\tcase git.NoErrAlreadyUpToDate.Error():\n\t\t\t\t\t// Repo is already up to date. This isn't a program\n\t\t\t\t\t// error to continue as normal\n\t\t\t\t\tbreak\n\t\t\t\tdefault:\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tconfigFile, err := afero.ReadFile(s.Fs, filepath.Join(appPath, \".cli.json\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(configFile, &s.SampleConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (a *Array) Example(r *ExampleGenerator) any {\n\tcount := NewLength(a.ElemType, r)\n\tres := make([]any, count)\n\tfor i := 0; i < count; i++ {\n\t\tres[i] = a.ElemType.Example(r)\n\t\tif res[i] == nil {\n\t\t\t// Handle the case of recursive data structures\n\t\t\tres[i] = make(map[string]any)\n\t\t}\n\t}\n\treturn a.MakeSlice(res)\n}", "func test(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\t//title := \"edit\"\n\ttype data struct {\n\t\tTitle string\n\t\tBody string\n\t}\n\t//dataVal := data{\"hello\",\"test\"}\n\tt, _ := template.ParseFiles(\"edit.html\")\n\tt.Execute(w, nil)\n}", "func TestGenerator(t *testing.T) {\n\trand.Seed(1)\n\tfmt.Println(\"-------\")\n\tfmt.Println(\"Dataset with 10 examples, 4 features, 3 classes\")\n\tfmt.Println()\n\tdata, res := generator.CreateDataset(10, 4, 3)\n\tfor i, d := range data {\n\t\tfmt.Printf(\"[%.3f %.3f %.3f %.3f] => %d\\n\", d[0], d[1], d[2], d[3], res[i])\n\t}\n\n\tfmt.Println()\n\tfmt.Println(\"-------\")\n\tfmt.Println(\"Dataset with 20 examples, 6 features, 2 classes\")\n\tfmt.Println()\n\tdata, res = generator.CreateDataset(20, 6, 2)\n\tfor i, d := range data {\n\t\tfmt.Printf(\"[%.3f %.3f %.3f %.3f %.3f %.3f] => %d\\n\", d[0], d[1], d[2], d[3], d[4], d[5], res[i])\n\t}\n\n}", "func (n *OpenBazaarNode) SetUpRepublisher(interval time.Duration) {\n\tif interval == 0 {\n\t\treturn\n\t}\n\tticker := time.NewTicker(interval)\n\tgo func() {\n\t\tfor range ticker.C {\n\t\t\tn.UpdateFollow()\n\t\t\tn.SeedNode()\n\t\t}\n\t}()\n}", "func initializeTestDatabaseTemplate(ctx context.Context, t *testing.T) {\n\n\tt.Helper()\n\n\tinitTestDatabaseHash(t)\n\n\tinitIntegresClient(t)\n\n\tif err := client.SetupTemplateWithDBClient(ctx, hash, func(db *sql.DB) error {\n\n\t\tt.Helper()\n\n\t\terr := applyMigrations(t, db)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = insertFixtures(ctx, t, db)\n\n\t\treturn err\n\t}); err != nil {\n\n\t\t// This error is exceptionally fatal as it hinders ANY future other\n\t\t// test execution with this hash as the template was *never* properly\n\t\t// setuped successfully. All GetTestDatabase will wait unti timeout\n\t\t// unless we interrupt them by discarding the base template...\n\t\tdiscardError := client.DiscardTemplate(ctx, hash)\n\n\t\tif discardError != nil {\n\t\t\tt.Fatalf(\"Failed to setup template database, also discarding failed for hash %q: %v, %v\", hash, err, discardError)\n\t\t}\n\n\t\tt.Fatalf(\"Failed to setup template database (discarded) for hash %q: %v\", hash, err)\n\n\t}\n}", "func (sfs *SuiteFS) SampleFiles(tb testing.TB, testDir string) []*File {\n\ttb.Helper()\n\n\tvfs := sfs.vfsSetup\n\n\tfiles := GetSampleFiles()\n\tfor _, file := range files {\n\t\tpath := vfs.Join(testDir, file.Path)\n\n\t\terr := vfs.WriteFile(path, file.Content, file.Mode)\n\t\tif err != nil {\n\t\t\ttb.Fatalf(\"WriteFile %s : want error to be nil, got %v\", path, err)\n\t\t}\n\t}\n\n\treturn files\n}", "func loadExamples(path string) []*Example {\n\tfp, err := os.Open(path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer fp.Close()\n\n\tvar examples []*Example\n\tif err := json.NewDecoder(fp).Decode(&examples); err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn examples\n}", "func testTemplate(w http.ResponseWriter, r *http.Request) {\n\ttestpage := Page{\n\t\tID: \"urn:cts:tests:test1.test1:1\",\n\t\tText: template.HTML(\"This is a testing of the template\")}\n\n\trenderTemplate(w, \"view\", testpage)\n}", "func New() *Sample {\n\treturn &Sample{\n\t\tStartTime: time.Now(),\n\t}\n}", "func TestTool(t *testing.T) {\n\ttests := []struct {\n\t\tit string\n\t\tmode Mode\n\t\tjob string\n\t\tsetValues yamlx.Values\n\t\tglobalValues string\n\t\ttemplates map[string]string\n\t\tvault getter\n\t\twant *fakeDoer\n\t}{\n\t\t{\n\t\t\tit: \"should_apply_one_doc_with_tmplt_scoped_values\",\n\t\t\tmode: ModeGenerate,\n\t\t\tjob: `\nsteps:\n- tmplt: tpl/example.txt\n values:\n audience: all\n team:\n lead: pipo`,\n\t\t\ttemplates: map[string]string{\n\t\t\t\t\"tpl/example.txt\": `\n{{ .Values.team.lead }} says hello {{ .Values.audience }}!`,\n\t\t\t},\n\t\t\twant: &fakeDoer{\n\t\t\t\tapply: []string{\"\\npipo says hello all!\"},\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tit: \"should_apply_one_doc_with_global_and_tmplt_scoped_values\",\n\t\t\tmode: ModeGenerate,\n\t\t\tjob: `\nsteps:\n- tmplt: tpl/example.txt\n values:\n team:\n lead: pipo\ndefaults:\n audience: all\n team:\n lead: klukkluk`,\n\t\t\tglobalValues: `\naudience: world\n`,\n\t\t\ttemplates: map[string]string{\n\t\t\t\t\"tpl/example.txt\": `\n{{ .Values.team.lead }} says hello {{ .Values.audience }}!`,\n\t\t\t},\n\t\t\twant: &fakeDoer{\n\t\t\t\tapply: []string{\"\\npipo says hello world!\"},\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tit: \"should_apply_one_doc_with_setvalue_overriding_all_others\",\n\t\t\tmode: ModeGenerate,\n\t\t\tjob: `\nsteps:\n- tmplt: tpl/example.txt\n values:\n name: pipo\ndefaults:\n name: klukkluk`,\n\t\t\tsetValues: yamlx.Values{\"name\": \"dikkedeur\"},\n\t\t\tglobalValues: `\nname: mamaloe\n`,\n\t\t\ttemplates: map[string]string{\n\t\t\t\t\"tpl/example.txt\": `\n{{ .Values.name }}`,\n\t\t\t},\n\t\t\twant: &fakeDoer{\n\t\t\t\tapply: []string{\"\\ndikkedeur\"},\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tit: \"should_wait\",\n\t\t\tjob: `\nsteps:\n- wait: --one 1 --two 2`,\n\t\t\twant: &fakeDoer{\n\t\t\t\twait: []string{\"--one 1 --two 2\"},\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tit: \"should_handle_action_with_portforward_arg\",\n\t\t\tmode: ModeGenerateWithActions,\n\t\t\tjob: `\nsteps:\n- action: action/get.txt\n portForward: --forward-flags\n values:\n type: getSecret`,\n\t\t\ttemplates: map[string]string{\n\t\t\t\t\"action/get.txt\": `\ntype: {{ .Values.type }}`,\n\t\t\t},\n\n\t\t\twant: &fakeDoer{\n\t\t\t\taction: []string{\"\\ntype: getSecret\"},\n\t\t\t\tportForward: []string{\"--forward-flags\"},\n\t\t\t\tpassedValues: yamlx.Values{},\n\t\t\t\tactionTally: 1,\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tit: \"should_handle_action_with_passed_values\",\n\t\t\tmode: ModeGenerateWithActions,\n\t\t\tjob: `\nsteps:\n- action: action/nop.txt\n- action: action/value.txt`,\n\t\t\ttemplates: map[string]string{\n\t\t\t\t\"action/nop.txt\": `\nno operation`,\n\t\t\t\t\"action/value.txt\": `\ntally: {{ .Get.tally }}`,\n\t\t\t},\n\t\t\twant: &fakeDoer{\n\t\t\t\taction: []string{\"\\nno operation\", \"\\ntally: 1\"},\n\t\t\t\tportForward: []string{\"\", \"\"},\n\t\t\t\tpassedValues: yamlx.Values{\"tally\": 1},\n\t\t\t\tactionTally: 2,\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tit: \"should_handle_reads_from_vault\",\n\t\t\tmode: ModeGenerateWithActions,\n\t\t\tjob: `\nsteps:\n- tmplt: tpl/vault.txt`,\n\t\t\ttemplates: map[string]string{\n\t\t\t\t\"tpl/vault.txt\": `\nsecret: {{ vault \"object\" \"field\" }}`,\n\t\t\t},\n\t\t\tvault: &fakeVault{\n\t\t\t\t\"object/field\": \"value\",\n\t\t\t},\n\t\t\twant: &fakeDoer{\n\t\t\t\tapply: []string{\"\\nsecret: value\"},\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tit: \"should_expand_variables_in_job\",\n\t\t\tmode: ModeGenerate,\n\t\t\tjob: `\nsteps:\n- tmplt: tpl/example.txt\n values:\n text: \"{{ .Values.first }}\" # note the quotes to make this valid yaml (arguably)\ndefaults:\n first: \"hello\"\n`,\n\t\t\ttemplates: map[string]string{\n\t\t\t\t\"tpl/example.txt\": `text={{ .Values.text }}`,\n\t\t\t},\n\t\t\twant: &fakeDoer{\n\t\t\t\tapply: []string{\"text=hello\"},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tst := range tests {\n\t\tt.Run(tst.it, func(t *testing.T) {\n\t\t\t// create function to read template file content.\n\t\t\treadFile := func(path string) (string, []byte, error) {\n\t\t\t\ts, ok := tst.templates[path]\n\t\t\t\tif !ok {\n\t\t\t\t\treturn \"\", nil, fmt.Errorf(\"not found: %s\", path)\n\t\t\t\t}\n\t\t\t\treturn path, []byte(s), nil\n\t\t\t}\n\n\t\t\tm := &fakeDoer{}\n\n\t\t\ttl := Tool{\n\t\t\t\tMode: tst.mode,\n\t\t\t\tEnviron: []string{},\n\t\t\t\tExecute: m,\n\t\t\t\treadFileFn: readFile,\n\t\t\t\tvault: tst.vault,\n\t\t\t}\n\n\t\t\terr := tl.run(tst.setValues, []byte(tst.globalValues), []byte(tst.job))\n\t\t\tif assert.NoError(t, err) {\n\t\t\t\tassert.Equal(t, tst.want, m)\n\t\t\t}\n\t\t})\n\t}\n}", "func InsertExamples(t *testing.T, db *mongo.Database) {\n\tcoll := db.Collection(\"inventory_insert\")\n\n\terr := coll.Drop(context.Background())\n\trequire.NoError(t, err)\n\n\t{\n\t\t// Start Example 1\n\n\t\tresult, err := coll.InsertOne(\n\t\t\tcontext.Background(),\n\t\t\tbson.D{\n\t\t\t\t{\"item\", \"canvas\"},\n\t\t\t\t{\"qty\", 100},\n\t\t\t\t{\"tags\", bson.A{\"cotton\"}},\n\t\t\t\t{\"size\", bson.D{\n\t\t\t\t\t{\"h\", 28},\n\t\t\t\t\t{\"w\", 35.5},\n\t\t\t\t\t{\"uom\", \"cm\"},\n\t\t\t\t}},\n\t\t\t})\n\n\t\t// End Example 1\n\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, result.InsertedID)\n\t}\n\n\t{\n\t\t// Start Example 2\n\n\t\tcursor, err := coll.Find(\n\t\t\tcontext.Background(),\n\t\t\tbson.D{{\"item\", \"canvas\"}},\n\t\t)\n\n\t\t// End Example 2\n\n\t\trequire.NoError(t, err)\n\t\trequireCursorLength(t, cursor, 1)\n\n\t}\n\n\t{\n\t\t// Start Example 3\n\n\t\tresult, err := coll.InsertMany(\n\t\t\tcontext.Background(),\n\t\t\t[]interface{}{\n\t\t\t\tbson.D{\n\t\t\t\t\t{\"item\", \"journal\"},\n\t\t\t\t\t{\"qty\", int32(25)},\n\t\t\t\t\t{\"tags\", bson.A{\"blank\", \"red\"}},\n\t\t\t\t\t{\"size\", bson.D{\n\t\t\t\t\t\t{\"h\", 14},\n\t\t\t\t\t\t{\"w\", 21},\n\t\t\t\t\t\t{\"uom\", \"cm\"},\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t\tbson.D{\n\t\t\t\t\t{\"item\", \"mat\"},\n\t\t\t\t\t{\"qty\", int32(25)},\n\t\t\t\t\t{\"tags\", bson.A{\"gray\"}},\n\t\t\t\t\t{\"size\", bson.D{\n\t\t\t\t\t\t{\"h\", 27.9},\n\t\t\t\t\t\t{\"w\", 35.5},\n\t\t\t\t\t\t{\"uom\", \"cm\"},\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t\tbson.D{\n\t\t\t\t\t{\"item\", \"mousepad\"},\n\t\t\t\t\t{\"qty\", 25},\n\t\t\t\t\t{\"tags\", bson.A{\"gel\", \"blue\"}},\n\t\t\t\t\t{\"size\", bson.D{\n\t\t\t\t\t\t{\"h\", 19},\n\t\t\t\t\t\t{\"w\", 22.85},\n\t\t\t\t\t\t{\"uom\", \"cm\"},\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t})\n\n\t\t// End Example 3\n\n\t\trequire.NoError(t, err)\n\t\trequire.Len(t, result.InsertedIDs, 3)\n\t}\n}", "func newDemos(c *DemocontrollerV1alpha1Client, namespace string) *demos {\n\treturn &demos{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}", "func (t *SimpleChaincode) UploadDocuments(stub shim.ChaincodeStubInterface, args []string) (pb.Response) {\n\tvar err error\n\n\t\n\tif len(args) != 4 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 4\")\n\t}\n\n\t//input sanitation\n\tfmt.Println(\"- start registration\")\n\tif len(args[0]) <= 0 {\n\t\treturn shim.Error(\"1st argument must be a non-empty string\")\n\t}\n\tif len(args[1]) <= 0 {\n\t\treturn shim.Error(\"2nd argument must be a non-empty string\")\n\t}\n\tif len(args[2]) <= 0 {\n\t\treturn shim.Error(\"3rd argument must be a non-empty string\")\n\t}\n\tif len(args[3]) <= 0 {\n\t\treturn shim.Error(\"4th argument must be a non-empty string\")\n\t}\n\n\t\n\tdocument:=Document{}\n\t\n\tdocument.ClaimId,err = strconv.Atoi(args[0])\n\tif err != nil {\n\t\treturn shim.Error(\"Failed to get ClaimId as cannot convert it to int\")\n\t}\n\tdocument.FIRCopy = args[1]\n\t\n document.Photos=args[2]\n\tdocument.Certificates=args[3]\n\n\t\n\tfmt.Println(\"document\",document)\n\n UserAsBytes, err := stub.GetState(\"getclaims\")\n\tif err != nil {\n\t\treturn shim.Error(\"Failed to get claims\")\n\t}\n\t\n\tvar claimlist ClaimList\n\tjson.Unmarshal(UserAsBytes, &claimlist)\t//un stringify it aka JSON.parse()\n\t\n\t\n\t\tfor i:=0;i<len(claimlist.Claimlist);i++{\n\t\t\n\t\t\n\tif(claimlist.Claimlist[i].ClaimNo==document.ClaimId){\n\nclaimlist.Claimlist[i].Documents = append(claimlist.Claimlist[i].Documents,document);\n\n}\n\t\n\t\n\tjsonAsBytes, _ := json.Marshal(claimlist)\n\tfmt.Println(\"json\",jsonAsBytes)\n\terr = stub.PutState(\"getclaims\", jsonAsBytes)\t\t\t\t\t\t\t\t\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\t}\n\t\t\nfmt.Println(\"- end uploaddocumen\")\nreturn shim.Success(nil)\n\t}", "func (s *Server) Generate(w http.ResponseWriter, r *http.Request) {\n\tsentence, err := s.Corpus.Generate(100)\n\tif err != nil {\n\t\tlog.Println(err)\n\n\t\t// Must populate corpus before generating\n\t\tw.WriteHeader(400)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(&GenerateResp{\n\t\tSentence: strings.Join(sentence, \" \"),\n\t})\n}", "func DocumentHandller(res http.ResponseWriter, req *http.Request) {\n\n\tview.RenderTemplate(\"document.html\", pongo2.Context{}, res)\n}", "func loadTemplates() {\n\n\tfmt.Println(\"About to load templates\")\n\n\t// get layouts\n\tlayouts, err := filepath.Glob(\"templates/layouts/*.layout\")\n\tpanicOnError(err)\n\n\t// get list of main pages\n\tpages, err := filepath.Glob(\"templates/pages/*.html\")\n\tpanicOnError(err)\n\n\tfor _, page := range pages {\n\t\tfiles := append(layouts, page)\n\t\ttemplateName := filepath.Base(page)\n\n\t\tnewTemplate := template.Must(template.ParseFiles(files...))\n\t\tnewTemplate.Option(\"missingkey=default\")\n\n\t\tappTemplates[templateName] = newTemplate\n\t}\n\n\t// loaded templates\n\tfor file, _ := range appTemplates {\n\t\tfmt.Printf(\"Loaded Template: %s\\n\", file)\n\t\tfmt.Printf(\"loaded: %s\\n\", file)\n\t}\n\n}", "func Test_handlerStudent_getAllStudents_empty(t *testing.T) {\n\tts := httptest.NewServer(http.HandlerFunc(HandlerStudent))\n\tdefer ts.Close()\n\tGlobal_db = &StudentsDB{}\n\tGlobal_db.Init()\n\n\tresp, err := http.Get(ts.URL + \"/student/\")\n\tif err != nil {\n\t\tt.Errorf(\"Error making the GET request, %s\", err)\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tt.Errorf(\"Expected StatusCode %d, received %d\", http.StatusOK, resp.StatusCode)\n\t\treturn\n\t}\n\n\tvar a []interface{}\n\terr = json.NewDecoder(resp.Body).Decode(&a)\n\tif err != nil {\n\t\tt.Errorf(\"Error parsing the expected JSON body. Got error: %s\", err)\n\t}\n\n\tif len(a) != 0 {\n\t\tt.Errorf(\"Excpected empty array, got %s\", a)\n\t}\n}", "func NewTemplateData(p *sql.DB, v string) {\n\tdbModel = &clientdb.DBModel{DB: p}\n\tversion = v\n}", "func init() {\n\ttpl = template.Must(template.New(\"\").Funcs(fn).ParseFiles(\"index.gohtml\"))\n}", "func InitDocument(r io.Reader) *Document {\n\tdoc := new(Document)\n\tdoc.r = r\n\n\treturn doc\n}", "func RandomScene() HittableList {\n\tworld := NewHittableList()\n\n\tgroundMaterial := NewLambertian(NewVec3(0.5, 0.5, 0.5))\n\tworld.Add(NewSphere(NewVec3(0, -1000, 0), 1000, groundMaterial))\n\n\tfor a := -11; a < 11; a++ {\n\t\tfor b := -11; b < 11; b++ {\n\t\t\tchooseMat := rand.Float64()\n\t\t\tcenter := NewVec3(float64(a)+0.9*rand.Float64(), 0.2, float64(b)+0.9*rand.Float64())\n\n\t\t\tif Sub(center, NewVec3(4, 0.2, 0)).Length() > 0.9 {\n\t\t\t\tvar sphereMaterial Material\n\n\t\t\t\tif chooseMat < 0.8 {\n\t\t\t\t\t// diffuse\n\t\t\t\t\talbedo := Mul(NewVec3Random(), NewVec3Random())\n\t\t\t\t\tsphereMaterial = NewLambertian(albedo)\n\t\t\t\t} else if chooseMat < 0.95 {\n\t\t\t\t\t// Metal\n\t\t\t\t\talbedo := NewVec3Rand(0.5, 1)\n\t\t\t\t\tfuzz := RandomFloat(0, 0.5)\n\t\t\t\t\tsphereMaterial = NewMetal(albedo, fuzz)\n\t\t\t\t} else {\n\t\t\t\t\t// glass\n\t\t\t\t\tsphereMaterial = NewDielectric(1.50)\n\t\t\t\t}\n\t\t\t\tworld.Add(NewSphere(center, 0.2, sphereMaterial))\n\n\t\t\t}\n\t\t}\n\t}\n\n\tmaterial1 := NewDielectric(1.5)\n\tworld.Add(NewSphere(NewVec3(0, 1, 0), 1, material1))\n\n\tmaterial2 := NewLambertian(NewVec3(0.4, 0.2, 0.1))\n\tworld.Add(NewSphere(NewVec3(-4, 1, 0), 1, material2))\n\n\tmaterial3 := NewMetal(NewVec3(0.7, 0.6, 0.5), 0)\n\tworld.Add(NewSphere(NewVec3(4, 1, 0), 1, material3))\n\n\treturn world\n}", "func NewContents (rawContents []map[string]interface{}) []Content {\n newContents := make ([]Content, len (rawContents))\n\n for i, rawContent := range rawContents {\n newContents[i] = NewContent (rawContent)\n }\n\n return newContents\n}", "func (rn *Runner) Simulate(duration int, transactions []Transaction, thread int) error {\n\tvar err error\n\tvar client *mongo.Client\n\tvar ctx = context.Background()\n\tvar isTeardown = false\n\tvar totalTPS int\n\n\tif client, err = mdb.NewMongoClient(rn.uri, rn.sslCAFile, rn.sslPEMKeyFile); err != nil {\n\t\treturn err\n\t}\n\tdefer client.Disconnect(ctx)\n\tc := client.Database(SimDBName).Collection(CollectionName)\n\n\tfor run := 0; run < duration; run++ {\n\t\t// be a minute transactions\n\t\tstage := \"setup\"\n\t\tif run == (duration - 1) {\n\t\t\tstage = \"teardown\"\n\t\t\tisTeardown = true\n\t\t\ttotalTPS = rn.tps\n\t\t} else if run > 0 && run < (duration-1) {\n\t\t\tstage = \"thrashing\"\n\t\t\ttotalTPS = rn.tps\n\t\t} else {\n\t\t\ttotalTPS = rn.tps / 2\n\t\t}\n\n\t\tbatchCount := 0\n\t\ttotalCount := 0\n\t\tbeginTime := time.Now()\n\t\tcounter := 0\n\t\tresults := []bson.M{}\n\t\tfor time.Now().Sub(beginTime) < time.Minute {\n\t\t\tinnerTime := time.Now()\n\t\t\ttxCount := 0\n\t\t\tfor time.Now().Sub(innerTime) < time.Second && txCount < totalTPS {\n\t\t\t\tdoc := simDocs[batchCount%len(simDocs)]\n\t\t\t\tbatchCount++\n\t\t\t\tif isTeardown {\n\t\t\t\t\tc.DeleteMany(ctx, bson.M{\"_search\": doc[\"_search\"]})\n\t\t\t\t} else if len(transactions) > 0 { // --file and --tx\n\t\t\t\t\ttxCount += execTXByTemplateAndTX(c, util.CloneDoc(doc), transactions)\n\t\t\t\t} else {\n\t\t\t\t\tvar res bson.M\n\t\t\t\t\tif res, err = execTx(c, doc); err != nil {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tif thread == 0 {\n\t\t\t\t\t\tresults = append(results, res)\n\t\t\t\t\t}\n\t\t\t\t\ttxCount += len(res)\n\t\t\t\t}\n\t\t\t} // for time.Now().Sub(innerTime) < time.Second && txCount < totalTPS\n\t\t\ttotalCount += txCount\n\t\t\tcounter++\n\t\t\tseconds := 1 - time.Now().Sub(innerTime).Seconds()\n\t\t\tif seconds > 0 {\n\t\t\t\ttime.Sleep(time.Duration(seconds) * time.Second)\n\t\t\t}\n\t\t} // for time.Now().Sub(beginTime) < time.Minute\n\n\t\tif thread == 0 && len(results) > 0 {\n\t\t\tdurations := map[string]time.Duration{}\n\t\t\tfor _, res := range results {\n\t\t\t\tfor k, v := range res {\n\t\t\t\t\tif durations[k] == 0 {\n\t\t\t\t\t\tdurations[k] = time.Duration(0)\n\t\t\t\t\t}\n\t\t\t\t\tdurations[k] += v.(time.Duration)\n\t\t\t\t}\n\t\t\t}\n\t\t\ttm := time.Now()\n\t\t\tclient.Ping(ctx, nil)\n\t\t\tlog.Println(\"Average Executions Time (including network latency):\")\n\t\t\tlog.Printf(\"\\t[%12s] %v\\n\", \"Ping\", time.Now().Sub(tm))\n\t\t\tfor k, v := range durations {\n\t\t\t\tlog.Printf(\"\\t[%12s] %v\\n\", k, v/time.Duration(len(results)))\n\t\t\t}\n\t\t}\n\n\t\tif rn.verbose {\n\t\t\tlog.Println(\"=>\", time.Now().Sub(beginTime), time.Now().Sub(beginTime) > time.Minute,\n\t\t\t\ttotalCount, totalCount/counter < totalTPS, counter)\n\t\t}\n\t\ttenPctOff := float64(totalTPS) * .95\n\t\tif rn.verbose && totalCount/counter < int(tenPctOff) {\n\t\t\tlog.Printf(\"%s average TPS was %d, lower than original %d\\n\", stage, totalCount/counter, totalTPS)\n\t\t}\n\n\t\tseconds := 60 - time.Now().Sub(beginTime).Seconds()\n\t\tif seconds > 0 {\n\t\t\ttime.Sleep(time.Duration(seconds) * time.Second)\n\t\t}\n\t\tif rn.verbose {\n\t\t\tlog.Println(\"=>\", time.Now().Sub(beginTime))\n\t\t}\n\t} //for run := 0; run < duration; run++\n\n\tc.Drop(ctx)\n\treturn nil\n}", "func NewTemplates(openapiDoc *openapi3.T, basePath string) (Templates, error) {\n\tvar unsortedTemplates []*Template\n\tfor path, info := range openapiDoc.Paths {\n\t\tpathTemplates, err := pathTemplates(openapiDoc, basePath, path, info)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tunsortedTemplates = append(unsortedTemplates, pathTemplates...)\n\t}\n\n\ttemplates := make(Templates)\n\n\tfor _, template := range unsortedTemplates {\n\t\tfor placeholder, _ := range template.Placeholders {\n\t\t\tif templates[placeholder] == nil {\n\t\t\t\ttemplates[placeholder] = make([]*Template, 0)\n\t\t\t}\n\t\t\ttemplates[placeholder] = append(templates[placeholder], template)\n\t\t}\n\t}\n\n\treturn templates, nil\n}", "func init() { //nolint\n\ttestSample := TestCase{\n\t\tName: \"should load libraries from the provided path [E2E-CLI-049]\",\n\t\tArgs: args{\n\t\t\tArgs: []cmdArgs{\n\t\t\t\t[]string{\"scan\", \"--silent\", \"-q\", \"../assets/queries\", \"-p\", \"fixtures/samples/terraform-single.tf\",\n\t\t\t\t\t\"--libraries-path\", \"fixtures/samples/libraries\"},\n\n\t\t\t\t[]string{\"scan\", \"--silent\", \"-q\", \"../assets/queries\", \"-p\", \"fixtures/samples/positive.yaml\",\n\t\t\t\t\t\"--libraries-path\", \"fixtures/samples/libraries\"},\n\n\t\t\t\t[]string{\"scan\", \"--silent\", \"-q\", \"../assets/queries\", \"-p\", \"fixtures/samples/positive.yaml\",\n\t\t\t\t\t\"--libraries-path\", \"fixtures/samples/not-exists-folder\"},\n\t\t\t},\n\t\t},\n\t\tWantStatus: []int{0, 50, 126},\n\t}\n\n\tTests = append(Tests, testSample)\n}", "func templateInit(w http.ResponseWriter, templateFile string, templateData page) {\n\tif err := tmpls.ExecuteTemplate(w, templateFile, templateData); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}", "func CreateDocuments(db *gorm.DB, w http.ResponseWriter, r *http.Request) {\n\tdocument := models.DocumentType{}\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&document); err != nil {\n\t\trespondError(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\tdefer r.Body.Close()\n\n\tif err := db.Save(&document).Error; err != nil {\n\t\trespondError(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\trespondJSON(w, http.StatusCreated, document)\n}", "func Constructor() RandomizedCollection {\n \n}", "func main() {\n\tinputPdf := \"sample_form.pdf\"\n\tfillJSONFile := \"formdata.json\"\n\toutputFile := \"output.pdf\"\n\n\terr := fillFields(inputPdf, fillJSONFile, outputFile)\n\tif err != nil {\n\t\tfmt.Printf(\"Error: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tfmt.Printf(\"Success, output written to %s\\n\", outputFile)\n}", "func (s *Solver) Populate(corpuspath string) error {\n\tfile, err := os.Open(corpuspath)\n\tif err != nil {\n\t\treturn errors.New(fmt.Sprintf(\"Unable to open corpus '%s': %s\", corpuspath, err))\n\t}\n\n\tdefer file.Close()\n\tscanner := bufio.NewScanner(file)\n\n\tfor scanner.Scan() {\n\t\tword := scanner.Text()\n\t\tkey := sortStringByChar(word)\n\t\ts.words[key] = append(s.words[key], word)\n\t}\n\n\tif scanner.Err() != nil {\n\t\treturn errors.New(fmt.Sprintf(\"Unable to tokenize corpus: %s\", scanner.Err()))\n\t}\n\n\treturn nil\n}", "func InitApp(now time.Time) AppData {\n year := now.Year()\n month := int(now.Month())\n day := now.Day()\n\n date := fmt.Sprintf(\"%d-%d-%d\", year, month, day)\n\n app_data := AppData{\n TimeZone: -4,\n Date: date,\n Template: \"index.thtml\",\n Markdown: true,\n Verbose: false,\n Limit: 3,\n }\n return app_data\n}", "func NewDocForTesting(html string) js.Value {\n\tdom := jsdom.New(html, map[string]interface{}{\n\t\t\"runScripts\": \"dangerously\",\n\t\t\"resources\": \"usable\",\n\t})\n\n\t// Create doc, but then wait until loading is complete and constructed\n\t// doc is returned. By default, jsdom loads doc asynchronously:\n\t// https://oliverjam.es/blog/frontend-testing-node-jsdom/#waiting-for-external-resources\n\tc := make(chan js.Value)\n\tdom.Get(\"window\").Call(\n\t\t\"addEventListener\", \"load\",\n\t\tjsutil.OneTimeFuncOf(func(this js.Value, args []js.Value) interface{} {\n\t\t\tc <- dom.Get(\"window\").Get(\"document\")\n\t\t\treturn nil\n\t\t}))\n\treturn <-c\n}", "func setUp() {\n\tdefaultData := map[string]string{\n\t\t\"key1\": \"value1\",\n\t\t\"key2\": \"value2\",\n\t\t\"key3\": \"value3\",\n\t}\n\tjsonData, _ := json.Marshal(defaultData)\n\terr := ioutil.WriteFile(JsonTestPath, jsonData, 0644)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n}", "func init() {\n\tpageTemplate = template.Must(template.ParseFiles(\"templates/index.html\"))\n\tvar err error\n\tdb, err = sql.Open(\"mysql\", \"anychart_user:anychart_pass@/anychart_db\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}" ]
[ "0.5542034", "0.5516457", "0.5424189", "0.5281057", "0.52729017", "0.5037482", "0.5023981", "0.4994785", "0.4969272", "0.49097607", "0.49019474", "0.4812467", "0.47356394", "0.47146592", "0.46989432", "0.46973065", "0.46631458", "0.46360233", "0.46299058", "0.46009892", "0.4592998", "0.458722", "0.4561835", "0.45535865", "0.4550279", "0.45436755", "0.45370662", "0.45359033", "0.45330656", "0.45330656", "0.44922245", "0.4479103", "0.44760203", "0.446848", "0.4455935", "0.44485468", "0.44430932", "0.4437305", "0.44324106", "0.44317326", "0.4424736", "0.44201562", "0.4417401", "0.44002402", "0.43736216", "0.4372652", "0.43605128", "0.43600327", "0.435652", "0.43559042", "0.43555555", "0.43529528", "0.43446568", "0.43342695", "0.4332851", "0.43242294", "0.4319697", "0.43166932", "0.43103004", "0.4309467", "0.43088788", "0.4307531", "0.43022412", "0.42981806", "0.42885625", "0.4288188", "0.42805853", "0.42795798", "0.4277305", "0.4273613", "0.4272942", "0.42726654", "0.42637998", "0.4259029", "0.42575672", "0.42559472", "0.42546552", "0.42525816", "0.42471313", "0.42456797", "0.42456132", "0.42382818", "0.4236047", "0.4229416", "0.42276874", "0.42240623", "0.4219466", "0.42189726", "0.4215378", "0.42047694", "0.41985458", "0.41969705", "0.41963318", "0.41957554", "0.41947356", "0.41895473", "0.41837823", "0.41753116", "0.41704395", "0.41654217" ]
0.71689487
0
Simulate simulates CRUD for load tests
func (rn *Runner) Simulate(duration int, transactions []Transaction, thread int) error { var err error var client *mongo.Client var ctx = context.Background() var isTeardown = false var totalTPS int if client, err = mdb.NewMongoClient(rn.uri, rn.sslCAFile, rn.sslPEMKeyFile); err != nil { return err } defer client.Disconnect(ctx) c := client.Database(SimDBName).Collection(CollectionName) for run := 0; run < duration; run++ { // be a minute transactions stage := "setup" if run == (duration - 1) { stage = "teardown" isTeardown = true totalTPS = rn.tps } else if run > 0 && run < (duration-1) { stage = "thrashing" totalTPS = rn.tps } else { totalTPS = rn.tps / 2 } batchCount := 0 totalCount := 0 beginTime := time.Now() counter := 0 results := []bson.M{} for time.Now().Sub(beginTime) < time.Minute { innerTime := time.Now() txCount := 0 for time.Now().Sub(innerTime) < time.Second && txCount < totalTPS { doc := simDocs[batchCount%len(simDocs)] batchCount++ if isTeardown { c.DeleteMany(ctx, bson.M{"_search": doc["_search"]}) } else if len(transactions) > 0 { // --file and --tx txCount += execTXByTemplateAndTX(c, util.CloneDoc(doc), transactions) } else { var res bson.M if res, err = execTx(c, doc); err != nil { break } if thread == 0 { results = append(results, res) } txCount += len(res) } } // for time.Now().Sub(innerTime) < time.Second && txCount < totalTPS totalCount += txCount counter++ seconds := 1 - time.Now().Sub(innerTime).Seconds() if seconds > 0 { time.Sleep(time.Duration(seconds) * time.Second) } } // for time.Now().Sub(beginTime) < time.Minute if thread == 0 && len(results) > 0 { durations := map[string]time.Duration{} for _, res := range results { for k, v := range res { if durations[k] == 0 { durations[k] = time.Duration(0) } durations[k] += v.(time.Duration) } } tm := time.Now() client.Ping(ctx, nil) log.Println("Average Executions Time (including network latency):") log.Printf("\t[%12s] %v\n", "Ping", time.Now().Sub(tm)) for k, v := range durations { log.Printf("\t[%12s] %v\n", k, v/time.Duration(len(results))) } } if rn.verbose { log.Println("=>", time.Now().Sub(beginTime), time.Now().Sub(beginTime) > time.Minute, totalCount, totalCount/counter < totalTPS, counter) } tenPctOff := float64(totalTPS) * .95 if rn.verbose && totalCount/counter < int(tenPctOff) { log.Printf("%s average TPS was %d, lower than original %d\n", stage, totalCount/counter, totalTPS) } seconds := 60 - time.Now().Sub(beginTime).Seconds() if seconds > 0 { time.Sleep(time.Duration(seconds) * time.Second) } if rn.verbose { log.Println("=>", time.Now().Sub(beginTime)) } } //for run := 0; run < duration; run++ c.Drop(ctx) return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TestIntCreatePersonStoreFetchBackAndCheckContents(t *testing.T) {\n\tlog.SetPrefix(\"TestIntegrationCreatePersonAndCheckContents\")\n\t// Create a dao containing a session\n\tdbsession, err := dbsession.MakeGorpMysqlDBSession()\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tdefer dbsession.Close()\n\n\tdao := MakeRepo(dbsession)\n\n\tclearDown(dao, t)\n\n\tp := personModel.MakeInitialisedPerson(0, expectedForename1, expectedSurname1)\n\n\t// Store the person in the DB\n\tperson, err := dao.Create(p)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tlog.Printf(\"created person %s\\n\", person.String())\n\n\tretrievedPerson, err := dao.FindByID(person.ID())\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tlog.Printf(\"retrieved person %s\\n\", retrievedPerson.String())\n\n\tif retrievedPerson.ID() != person.ID() {\n\t\tt.Errorf(\"expected ID to be %d actually %d\", person.ID(),\n\t\t\tretrievedPerson.ID())\n\t}\n\tif retrievedPerson.Forename() != expectedForename1 {\n\t\tt.Errorf(\"expected forename to be %s actually %s\", expectedForename1,\n\t\t\tretrievedPerson.Forename())\n\t}\n\tif retrievedPerson.Surname() != expectedSurname1 {\n\t\tt.Errorf(\"expected surname to be %s actually %s\", expectedSurname1,\n\t\t\tretrievedPerson.Surname())\n\t}\n\n\t// Delete person and check response\n\tid := person.ID()\n\trows, err := dao.DeleteByID(person.ID())\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tif rows != 1 {\n\t\tt.Errorf(\"expected delete to return 1, actual %d\", rows)\n\t}\n\tlog.Printf(\"deleted person with ID %d\\n\", id)\n\tclearDown(dao, t)\n}", "func TestHandler_CreateTable(t *testing.T) {\n\tdb := OpenDatabase()\n\tdefer db.Close()\n\th := pie.NewHandler(db.Database)\n\ts := httptest.NewServer(h)\n\tdefer s.Close()\n\n\t// Generate multipart form body.\n\tvar buf bytes.Buffer\n\tw := multipart.NewWriter(&buf)\n\tpart, _ := w.CreateFormFile(\"file\", \"names.csv\")\n\tfmt.Fprint(part, \"fname,lname!!\\n\")\n\tfmt.Fprint(part, \"bob,smith\\n\")\n\tfmt.Fprint(part, \"susy,que\\n\")\n\tif err := w.Close(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Upload a file.\n\tresp, _ := http.Post(s.URL+\"/tables\", w.FormDataContentType(), &buf)\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tif resp.StatusCode != http.StatusOK {\n\t\tt.Fatalf(\"unexpected status: %d\", resp.StatusCode)\n\t} else if string(body) != \"\" {\n\t\tt.Fatalf(\"unexpected body: %s\", body)\n\t}\n\n\t// Verify table is created.\n\tif tbl := db.Table(\"names\"); tbl == nil {\n\t\tt.Fatal(\"expected table\")\n\t} else if len(tbl.Columns) != 2 {\n\t\tt.Fatalf(\"expected column count: %d\", len(tbl.Columns))\n\t} else if rows, _ := db.TableRows(\"names\"); len(rows) != 2 {\n\t\tt.Fatalf(\"expected row count: %d\", len(rows))\n\t}\n}", "func TestCreate(t *testing.T) {\n\n}", "func Test_RNIS_load_scenarios(t *testing.T) {\n\n\t// no override if the name is already in the DB.. security not to override something important\n\terr := createScenario(\"rnis-system-test\", \"rnis-system-test.yaml\")\n\tif err != nil {\n\t\tt.Fatal(\"Cannot create scenario, keeping the one already there and continuing testing with it :\", err)\n\t}\n}", "func Test_before(t *testing.T) {\n db.Connect()\n RegisterAllHandlers()\n TEST = true\n}", "func TestCreateTodo(t *testing.T) {\n\t_client := setupDatabase(t)\n\t_handler := setupTodoHandler(_client)\n\tdefer _client.Close()\n\n\tapp := fiber.New()\n\n\tapp.Post(\"/todos\", _handler.CreateTodo)\n\n\tbody := []byte(`{\"content\":\"Example content\"}`)\n\tr := httptest.NewRequest(\"POST\", \"/todos\", bytes.NewReader(body))\n\tr.Header.Set(\"Content-Type\", \"application/json\")\n\n\tresp, err := app.Test(r)\n\tif err != nil {\n\t\tassert.Fail(t, err.Error())\n\t}\n\n\tassert.Equal(t, fiber.StatusCreated, resp.StatusCode)\n\n\tvar data entity.Todo\n\tif err := json.NewDecoder(resp.Body).Decode(&data); err != nil {\n\t\tassert.Fail(t, err.Error())\n\t}\n\n\tassert.Equal(t, \"Example content\", data.Content)\n\tassert.Equal(t, false, data.Completed)\n\n\tfmt.Println(\"Todo ID:\", data.ID)\n\tfmt.Println(\"Status Code:\", resp.StatusCode)\n}", "func (s *ServerSuite) TestServerCRUD(c *C) {\n\te := testutils.NewResponder(\"Hi, I'm endpoint\")\n\tdefer e.Close()\n\n\tb := MakeBatch(Batch{Addr: \"localhost:11300\", Route: `Path(\"/\")`, URL: e.URL})\n\n\tc.Assert(s.mux.UpsertServer(b.BK, b.S), IsNil)\n\tc.Assert(s.mux.UpsertFrontend(b.F), IsNil)\n\tc.Assert(s.mux.UpsertListener(b.L), IsNil)\n\n\tc.Assert(s.mux.Start(), IsNil)\n\n\tc.Assert(GETResponse(c, b.FrontendURL(\"/\")), Equals, \"Hi, I'm endpoint\")\n\n\tc.Assert(s.mux.DeleteListener(b.LK), IsNil)\n\n\t_, _, err := testutils.Get(b.FrontendURL(\"/\"))\n\tc.Assert(err, NotNil)\n}", "func TestDeleteHandler(t *testing.T) {\n\n // ...\n\n}", "func TestCRUDObject(t *testing.T) {\n\tobj := testSQL{1, \"tatatoto\", \"yoyo\", 25, 42, nil}\n\n\terr := db.Save(&obj)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tID := obj.Id\n\n\t// Retrieve from Cache\n\tvar objA *testSQL\n\terr = db.Retrieve(ID, &objA)\n\n\tif objA.Name != \"tatatoto\" {\n\t\tt.Error(\"Error in Cache\", err)\n\t}\n\n\t// Remove from Cache\n\tdb.EjectFromCache(objA)\n\n\t// Retrieve from DB\n\tvar objC *testSQL\n\terr = db.Retrieve(ID, &objC)\n\n\tif objC.Name != \"tatatoto\" {\n\t\tt.Error(\"Error in DB\", err)\n\t}\n\n\t// Update object\n\tobjC.Name = \"totoro\"\n\n\terr = db.Update(objC)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tdb.EjectFromCache(objC)\n\n\tvar objD *testSQL\n\terr = db.Retrieve(ID, &objD)\n\n\tif objD.Name != \"totoro\" {\n\t\tt.Error(\"Error in Update\", err)\n\t}\n\n\t// Remove from DB\n\terr = db.Delete(&obj)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\t// Try to get from anywhere\n\tvar objB *testSQL\n\terr = db.Retrieve(ID, &objB)\n\n\tif err == nil || err != sql.ErrNoRows {\n\t\tt.Error(\"Error in Deletion\")\n\t}\n\n}", "func (h *HandlersApp01sqVendor) TableLoadTestData(w http.ResponseWriter, r *http.Request) {\n\tvar err error\n\tvar rcd App01sqVendor.App01sqVendor\n\n\tlog.Printf(\"hndlrVendor.TableLoadTestData(%s)\\n\", r.Method)\n\n\tif r.Method != \"GET\" {\n\t\thttp.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\t// Create the table.\n\terr = h.db.TableCreate()\n\tif err == nil {\n\t\tw.Write([]byte(\"Table was created\\n\"))\n\t} else {\n\t\tw.Write([]byte(\"Table creation had an error of:\" + util.ErrorString(err)))\n\t}\n\n\t// Load the test rows.\n\t// Now add some records.\n\tfor i := 0; i < 26; i++ {\n\t\tchr := 'A' + i\n\t\trcd.TestData(i)\n\t\terr = h.db.RowInsert(&rcd)\n\t\tif err == nil {\n\t\t\tstr := fmt.Sprintf(\"Added row: %c\\n\", chr)\n\t\t\tw.Write([]byte(str))\n\t\t} else {\n\t\t\tstr := fmt.Sprintf(\"Table creation had an error of: %c\\n\", chr)\n\t\t\tw.Write([]byte(str))\n\t\t}\n\t}\n\n\tlog.Printf(\"...end hndlrVendor.TableLoadTestData(%s)\\n\", util.ErrorString(err))\n\n}", "func Test_SLock(t *testing.T) {\n\tr, _ := initRepo(user, password, database, ip, port)\n\n\ttx, err := r.db.Begin()\n\tif err != nil {\n\t\treturn\n\t}\n\n\trows, err := tx.Query(querySql, \"aa\", \"bb\", \"cc\")\n\tif err != nil {\n\t\t_ = tx.Rollback()\n\t\treturn\n\t}\n\n\t// sleep 10s\n\t// then exec \"select * from xxx for update\" for testing\n\ttime.Sleep(10 * time.Second)\n\tfmt.Println(rows.Next())\n\n\tdefer tx.Commit()\n\n\treturn\n}", "func runTest(m *testing.M) int {\n\t// In order to get a Mongo session we need the name of the database we\n\t// are using. The web framework middleware is using this by convention.\n\tdbName, err := cfg.String(\"MONGO_DB\")\n\tif err != nil {\n\t\tfmt.Println(\"MongoDB is not configured\")\n\t\treturn 1\n\t}\n\n\tdb, err := db.NewMGO(\"context\", dbName)\n\tif err != nil {\n\t\tfmt.Println(\"Unable to get Mongo session\")\n\t\treturn 1\n\t}\n\n\tdefer db.CloseMGO(\"context\")\n\n\ttstdata.Generate(db)\n\tdefer tstdata.Drop(db)\n\n\tloadQuery(db, \"basic.json\")\n\tloadQuery(db, \"basic_var.json\")\n\tdefer qfix.Remove(db, \"QTEST_O\")\n\n\tloadScript(db, \"basic_script_pre.json\")\n\tloadScript(db, \"basic_script_pst.json\")\n\tdefer sfix.Remove(db, \"STEST_O\")\n\n\tloadMasks(db, \"basic.json\")\n\tdefer mfix.Remove(db, \"test_xenia_data\")\n\n\treturn m.Run()\n}", "func TestStore(t *testing.T) {\r\n\tsetup()\r\n\tp := Person{\r\n\t\tFirstname: firstname,\r\n\t\tLastname: lastname,\r\n\t}\r\n\tresult, err := p.Store(client)\r\n\t_id = result.InsertedID.(primitive.ObjectID)\r\n\r\n\tif err != nil {\r\n\t\tt.Fatalf(\"Failed store test %s\", err)\r\n\t}\r\n\r\n\tif p.Firstname != firstname {\r\n\t\tt.Fatalf(\"Failed store test %s\", err)\r\n\t}\r\n\r\n\tt.Log(\"Person was successfully stored : \"+p.Firstname+\" \"+p.Lastname+\" inserted id: \", _id)\r\n\r\n\tif err != nil {\r\n\t\tt.Fatalf(\"Failed store test %s\", err)\r\n\t}\r\n\r\n}", "func Test_WAIS_load_scenarios(t *testing.T) {\n\n\t// no override if the name is already in the DB.. security not to override something important\n\terr := createScenario(\"wais-system-test\", \"wais-system-test.yaml\")\n\tif err != nil {\n\t\tt.Fatal(\"Cannot create scenario, keeping the one already there and continuing testing with it :\", err)\n\t}\n}", "func (et *emulatorTest) create(instructions map[string][]string) {\n\tc := http.DefaultClient\n\tdata := struct {\n\t\tInstructions map[string][]string `json:\"instructions\"`\n\t}{\n\t\tInstructions: instructions,\n\t}\n\n\tbuf := new(bytes.Buffer)\n\tif err := json.NewEncoder(buf).Encode(data); err != nil {\n\t\tet.Fatalf(\"encoding request: %v\", err)\n\t}\n\n\tet.host.Path = \"retry_test\"\n\tresp, err := c.Post(et.host.String(), \"application/json\", buf)\n\tif err != nil || resp.StatusCode != 200 {\n\t\tet.Fatalf(\"creating retry test: err: %v, resp: %+v\", err, resp)\n\t}\n\tdefer func() {\n\t\tcloseErr := resp.Body.Close()\n\t\tif err == nil {\n\t\t\terr = closeErr\n\t\t}\n\t}()\n\ttestRes := struct {\n\t\tTestID string `json:\"id\"`\n\t}{}\n\tif err := json.NewDecoder(resp.Body).Decode(&testRes); err != nil {\n\t\tet.Fatalf(\"decoding test ID: %v\", err)\n\t}\n\n\tet.id = testRes.TestID\n\n\t// Create wrapped client which will send emulator instructions\n\tet.host.Path = \"\"\n\tclient, err := wrappedClient(et.T, et.id)\n\tif err != nil {\n\t\tet.Fatalf(\"creating wrapped client: %v\", err)\n\t}\n\tet.wrappedClient = client\n}", "func (p *Proxy) Create(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\tlogger := mPkg.GetLogger(ctx)\n\n\t// Making valid LoadTestSpec based on HTTP request\n\tltSpec, err := fromHTTPRequestToLoadTestSpec(r, logger, p.allowedCustomImages)\n\tif err != nil {\n\t\trender.Render(w, r, cHttp.ErrResponse(http.StatusBadRequest, err.Error()))\n\t\treturn\n\t}\n\n\t// Building LoadTest based on specs\n\tloadTest, err := apisLoadTestV1.BuildLoadTestObject(ltSpec)\n\tif err != nil {\n\t\trender.Render(w, r, cHttp.ErrResponse(http.StatusBadRequest, err.Error()))\n\t\treturn\n\t}\n\n\t// Find the old load test with the same data\n\tlabeledLoadTests, err := p.kubeClient.GetLoadTestsByLabel(ctx, loadTest)\n\tif err != nil {\n\t\tlogger.Error(\"Could not count active load tests with given hash\", zap.Error(err))\n\t\trender.Render(w, r, cHttp.ErrResponse(http.StatusInternalServerError, \"Could not count active load tests with given hash\"))\n\t\treturn\n\t}\n\n\tif len(labeledLoadTests.Items) > 0 {\n\t\tif !loadTest.Spec.Overwrite {\n\t\t\trender.Render(w, r, cHttp.ErrResponse(http.StatusBadRequest,\n\t\t\t\t\"Load test with given testfile already exists, aborting. Please delete existing load test and try again.\"))\n\t\t\treturn\n\t\t}\n\n\t\t// If users wants to overwrite\n\t\tfor _, item := range labeledLoadTests.Items {\n\t\t\t// Remove the old tests\n\t\t\terr := p.kubeClient.DeleteLoadTest(ctx, item.Name)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Error(\"Could not delete load test with error\", zap.Error(err))\n\t\t\t\trender.Render(w, r, cHttp.ErrResponse(http.StatusConflict, err.Error()))\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t// check the number of active loadtests currently running on the cluster\n\tactiveLoadTests, err := p.kubeClient.CountActiveLoadTests(ctx)\n\tif err != nil {\n\t\tlogger.Error(\"Could not count active load tests\", zap.Error(err))\n\t\trender.Render(w, r, cHttp.ErrResponse(http.StatusInternalServerError, \"Could not count active load tests\"))\n\t\treturn\n\t}\n\n\tif activeLoadTests >= p.maxLoadTestsRun {\n\t\tlogger.Warn(\"number of active load tests reached limit\", zap.Int(\"current\", activeLoadTests), zap.Int(\"limit\", p.maxLoadTestsRun))\n\t\trender.Render(w, r, cHttp.ErrResponse(http.StatusTooManyRequests, \"Number of active load tests reached limit\"))\n\t\treturn\n\t}\n\n\tbackend, err := p.registry.GetBackend(ltSpec.Type)\n\tif err != nil {\n\t\tlogger.Error(\"could not get backend\", zap.Error(err))\n\t\trender.Render(w, r, cHttp.ErrResponse(http.StatusBadRequest, err.Error()))\n\t\treturn\n\t}\n\n\terr = backend.TransformLoadTestSpec(&ltSpec)\n\tif err != nil {\n\t\tlogger.Error(\"could not transform LoadTest spec\", zap.Error(err))\n\t\trender.Render(w, r, cHttp.ErrResponse(http.StatusBadRequest, err.Error()))\n\t\treturn\n\t}\n\n\t// Pushing LoadTest to Kubernetes\n\tloadTestName, err := p.kubeClient.CreateLoadTest(ctx, loadTest)\n\tif err != nil {\n\t\tlogger.Error(\"Could not create load test\", zap.Error(err))\n\t\trender.Render(w, r, cHttp.ErrResponse(http.StatusConflict, err.Error()))\n\t\treturn\n\t}\n\n\trender.Status(r, http.StatusCreated)\n\trender.JSON(w, r, &LoadTestStatus{\n\t\tType: loadTest.Spec.Type.String(),\n\t\tDistributedPods: *loadTest.Spec.DistributedPods,\n\t\tNamespace: loadTestName,\n\t\tPhase: string(apisLoadTestV1.LoadTestCreating),\n\t\tTags: loadTest.Spec.Tags,\n\t\tHasEnvVars: len(loadTest.Spec.EnvVars) != 0,\n\t\tHasTestData: loadTest.Spec.TestData != \"\",\n\t})\n}", "func TestClient_AddDatabase(t *testing.T) {\n\tteardown := setup()\n\tdefer teardown()\n\tmux.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\taddDbRequest := models.AddDatabaseRequest{}\n\t\terr := json.NewDecoder(r.Body).Decode(&addDbRequest)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"failed to parse json\", http.StatusBadRequest)\n\t\t}\n\t\tnewDatabase := models.InstanceData{\n\t\t\tInstanceName: addDbRequest.InstanceName,\n\t\t\tReadHostGroup: 10,\n\t\t\tWriteHostGroup: 5,\n\t\t\tUsername: addDbRequest.Username,\n\t\t\tPassword: addDbRequest.Password,\n\t\t\tQueryRules: addDbRequest.QueryRules,\n\t\t\tMasterInstance: addDbRequest.MasterInstance,\n\t\t\tReadReplicas: addDbRequest.ReadReplicas,\n\t\t\tUseSSL: 0,\n\t\t\tChesterMetaData: addDbRequest.ChesterMetaData,\n\t\t}\n\t\tdatabases = append(databases, newDatabase)\n\t\taddDataBaseResponse := models.AddDatabaseResponse{\n\t\t\tAction: \"add\",\n\t\t\tQueryRules: addDbRequest.QueryRules,\n\t\t\tInstanceName: addDbRequest.InstanceName,\n\t\t\tUsername: addDbRequest.Username,\n\t\t\tPassword: addDbRequest.Password,\n\t\t\tWriteHostGroup: 5,\n\t\t\tReadHostGroup: 10,\n\t\t\tSSLEnabled: 0,\n\t\t\tChesterMetaData: addDbRequest.ChesterMetaData,\n\t\t}\n\t\trespBytes, err := json.Marshal(&addDataBaseResponse)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"failed to marshal response\", http.StatusInternalServerError)\n\t\t}\n\t\tw.WriteHeader(200)\n\t\tw.Write(respBytes)\n\t})\n\tmux.HandleFunc(\"/databases/temp\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tdbCheck := false\n\t\tfor _, db := range databases {\n\t\t\tif db.InstanceName == \"temp\" {\n\t\t\t\tdbCheck = true\n\t\t\t\tb, err := json.Marshal(db)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatalf(\"failed to marshal response from mock server %s\", err.Error())\n\t\t\t\t}\n\t\t\t\tw.Write(b)\n\t\t\t}\n\t\t}\n\t\tif !dbCheck {\n\t\t\thttp.Error(w, \"instance not found\", http.StatusNotFound)\n\t\t}\n\t})\n\tmux.HandleFunc(\"/databases\", http.HandlerFunc(getDatabasesHandler))\n\n\taddDbReadReplicaOne := models.AddDatabaseRequestDatabaseInformation{\n\t\tName: \"foo-read-1\",\n\t\tIPAddress: \"2.3.4.6\",\n\t}\n\taddDbReadReplicaTwo := models.AddDatabaseRequestDatabaseInformation{\n\t\tName: \"foo-read-2\",\n\t\tIPAddress: \"2.3.4.7\",\n\t}\n\taddDbReadReplicas := []models.AddDatabaseRequestDatabaseInformation{\n\t\taddDbReadReplicaOne, addDbReadReplicaTwo,\n\t}\n\taddDbQueryRuleOne := models.ProxySqlMySqlQueryRule{\n\t\tRuleID: 1,\n\t\tUsername: \"foo\",\n\t\tActive: 1,\n\t\tMatchDigest: \"bar\",\n\t\tDestinationHostgroup: 5,\n\t\tApply: 1,\n\t\tComment: \"baz\",\n\t}\n\taddDbQueryRuleTwo := models.ProxySqlMySqlQueryRule{\n\t\tRuleID: 2,\n\t\tUsername: \"foo\",\n\t\tActive: 1,\n\t\tMatchDigest: \"barzoople\",\n\t\tDestinationHostgroup: 10,\n\t\tApply: 1,\n\t\tComment: \"baz\",\n\t}\n\taddDbQueryRules := []models.ProxySqlMySqlQueryRule{\n\t\taddDbQueryRuleOne, addDbQueryRuleTwo,\n\t}\n\taddDbRequest := models.AddDatabaseRequest{\n\t\tAction: \"add\",\n\t\tInstanceName: \"temp\",\n\t\tUsername: \"foo\",\n\t\tPassword: \"bar\",\n\t\tMasterInstance: models.AddDatabaseRequestDatabaseInformation{\n\t\t\tName: \"foo\",\n\t\t\tIPAddress: \"2.3.4.5\",\n\t\t},\n\t\tReadReplicas: addDbReadReplicas,\n\t\tQueryRules: addDbQueryRules,\n\t\tChesterMetaData: models.ChesterMetaData{\n\t\t\tInstanceGroup: \"temp\",\n\t\t\tMaxChesterInstances: 3,\n\t\t},\n\t\tKeyData: \"\",\n\t\tCertData: \"\",\n\t\tCAData: \"\",\n\t\tEnableSSL: 0,\n\t}\n\t_, err := client.AddDatabase(addDbRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t\tt.FailNow()\n\t}\n\tdbs, err := client.GetDatabases()\n\tif err != nil {\n\t\tt.Error(err)\n\t\tt.FailNow()\n\t}\n\tif len(dbs) != 3 {\n\t\tt.Errorf(\"wtf %v\", len(dbs))\n\t\tt.FailNow()\n\t}\n\tdb, err := client.GetDatabase(\"temp\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\tt.FailNow()\n\t}\n\tif db.InstanceName != \"temp\" {\n\t\tt.Errorf(\"wrong instance %s\", db.InstanceName)\n\t\tt.FailNow()\n\t}\n}", "func Test_handlerStudent_getAllStudents_Tom(t *testing.T) {\n\tGlobal_db = &StudentsDB{}\n\tGlobal_db.Init()\n\ttestStudent := Student{\"Tom\", 21, \"id0\"}\n\tGlobal_db.Add(testStudent)\n\n\tts := httptest.NewServer(http.HandlerFunc(HandlerStudent))\n\tdefer ts.Close()\n\n\tresp, err := http.Get(ts.URL + \"/student/\")\n\tif err != nil {\n\t\tt.Errorf(\"Error making the GET request, %s\", err)\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tt.Errorf(\"Expected StatusCode %d, received %d\", http.StatusOK, resp.StatusCode)\n\t\treturn\n\t}\n\n\tvar a []Student\n\terr = json.NewDecoder(resp.Body).Decode(&a)\n\tif err != nil {\n\t\tt.Errorf(\"Error parsing the expected JSON body. Got error: %s\", err)\n\t}\n\n\tif len(a) != 1 {\n\t\tt.Errorf(\"Excpected array with one element, got %v\", a)\n\t}\n\n\tif a[0].Name != testStudent.Name || a[0].Age != testStudent.Age || a[0].StudentID != testStudent.StudentID {\n\t\tt.Errorf(\"Students do not match! Got: %v, Expected: %v\\n\", a[0], testStudent)\n\t}\n}", "func TestGetAllOrdersForTableID(t *testing.T) {\n\n // ...\n\n}", "func TestAllOps(t *testing.T) {\n\tdb, stop := testserver.NewDBForTestWithDatabase(t, \"photos\")\n\tdefer stop()\n\n\tctx := context.Background()\n\n\tif err := initSchema(ctx, db); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcfg := Config{\n\t\tDB: db,\n\t\tNumUsers: 1,\n\t}\n\n\tfor _, op := range ops {\n\t\tt.Logf(\"running %s\", op.name)\n\t\tif err := runUserOp(ctx, cfg, 1, op.typ); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}\n}", "func (suite *RepoCreateTestSuite) Run(t *testing.T) bool {\n\tif len(suite.MethodName) == 0 {\n\t\tsuite.MethodName = \"Create\"\n\t}\n\n\treturn t.Run(suite.Name, func(t *testing.T) {\n\t\ttestErr := errors.New(\"test error\")\n\n\t\tt.Run(\"success\", func(t *testing.T) {\n\t\t\tsqlxDB, sqlMock := MockDatabase(t)\n\t\t\tctx := persistence.SaveToContext(context.TODO(), sqlxDB)\n\n\t\t\tconfigureValidSQLQueries(sqlMock, suite.SQLQueryDetails)\n\n\t\t\tconvMock := suite.ConverterMockProvider()\n\t\t\tconvMock.On(\"ToEntity\", suite.ModelEntity).Return(suite.DBEntity, nil).Once()\n\t\t\tpgRepository := createRepo(suite.RepoConstructorFunc, convMock)\n\n\t\t\t// WHEN\n\t\t\terr := callCreate(pgRepository, suite.MethodName, ctx, suite.TenantID, suite.ModelEntity)\n\n\t\t\t// THEN\n\t\t\trequire.NoError(t, err)\n\t\t\tsqlMock.AssertExpectations(t)\n\t\t\tconvMock.AssertExpectations(t)\n\t\t})\n\n\t\tif !suite.IsTopLevelEntity && !suite.IsGlobal {\n\t\t\tt.Run(\"error when parent access is missing\", func(t *testing.T) {\n\t\t\t\tsqlxDB, sqlMock := MockDatabase(t)\n\t\t\t\tctx := persistence.SaveToContext(context.TODO(), sqlxDB)\n\n\t\t\t\tconfigureInvalidSelect(sqlMock, suite.SQLQueryDetails)\n\n\t\t\t\tconvMock := suite.ConverterMockProvider()\n\t\t\t\tconvMock.On(\"ToEntity\", suite.ModelEntity).Return(suite.DBEntity, nil).Once()\n\t\t\t\tpgRepository := createRepo(suite.RepoConstructorFunc, convMock)\n\t\t\t\t// WHEN\n\t\t\t\terr := callCreate(pgRepository, suite.MethodName, ctx, suite.TenantID, suite.ModelEntity)\n\t\t\t\t// THEN\n\t\t\t\trequire.Error(t, err)\n\t\t\t\trequire.Equal(t, apperrors.Unauthorized, apperrors.ErrorCode(err))\n\t\t\t\trequire.Contains(t, err.Error(), fmt.Sprintf(\"Tenant %s does not have access to the parent\", suite.TenantID))\n\n\t\t\t\tsqlMock.AssertExpectations(t)\n\t\t\t\tconvMock.AssertExpectations(t)\n\t\t\t})\n\t\t}\n\n\t\tfor i := range suite.SQLQueryDetails {\n\t\t\tt.Run(fmt.Sprintf(\"error if SQL query %d fail\", i), func(t *testing.T) {\n\t\t\t\tsqlxDB, sqlMock := MockDatabase(t)\n\t\t\t\tctx := persistence.SaveToContext(context.TODO(), sqlxDB)\n\n\t\t\t\tconfigureFailureForSQLQueryOnIndex(sqlMock, suite.SQLQueryDetails, i, testErr)\n\n\t\t\t\tconvMock := suite.ConverterMockProvider()\n\t\t\t\tconvMock.On(\"ToEntity\", suite.ModelEntity).Return(suite.DBEntity, nil).Once()\n\t\t\t\tpgRepository := createRepo(suite.RepoConstructorFunc, convMock)\n\t\t\t\t// WHEN\n\t\t\t\terr := callCreate(pgRepository, suite.MethodName, ctx, suite.TenantID, suite.ModelEntity)\n\t\t\t\t// THEN\n\t\t\t\trequire.Error(t, err)\n\t\t\t\tif suite.SQLQueryDetails[i].IsSelect {\n\t\t\t\t\trequire.Equal(t, apperrors.Unauthorized, apperrors.ErrorCode(err))\n\t\t\t\t\trequire.Contains(t, err.Error(), fmt.Sprintf(\"Tenant %s does not have access to the parent\", suite.TenantID))\n\t\t\t\t} else {\n\t\t\t\t\trequire.Equal(t, apperrors.InternalError, apperrors.ErrorCode(err))\n\t\t\t\t\trequire.Contains(t, err.Error(), \"Internal Server Error: Unexpected error while executing SQL query\")\n\t\t\t\t}\n\t\t\t\tsqlMock.AssertExpectations(t)\n\t\t\t\tconvMock.AssertExpectations(t)\n\t\t\t})\n\t\t}\n\n\t\tif !suite.DisableConverterErrorTest {\n\t\t\tt.Run(\"error when conversion fail\", func(t *testing.T) {\n\t\t\t\tsqlxDB, sqlMock := MockDatabase(t)\n\t\t\t\tctx := persistence.SaveToContext(context.TODO(), sqlxDB)\n\n\t\t\t\tconvMock := suite.ConverterMockProvider()\n\t\t\t\tconvMock.On(\"ToEntity\", suite.ModelEntity).Return(nil, testErr).Once()\n\t\t\t\tpgRepository := createRepo(suite.RepoConstructorFunc, convMock)\n\t\t\t\t// WHEN\n\t\t\t\terr := callCreate(pgRepository, suite.MethodName, ctx, suite.TenantID, suite.ModelEntity)\n\t\t\t\t// THEN\n\t\t\t\trequire.Error(t, err)\n\t\t\t\trequire.Contains(t, err.Error(), testErr.Error())\n\n\t\t\t\tsqlMock.AssertExpectations(t)\n\t\t\t\tconvMock.AssertExpectations(t)\n\t\t\t})\n\t\t}\n\n\t\tt.Run(\"returns error when item is nil\", func(t *testing.T) {\n\t\t\tctx := context.TODO()\n\t\t\tconvMock := suite.ConverterMockProvider()\n\t\t\tpgRepository := createRepo(suite.RepoConstructorFunc, convMock)\n\t\t\t// WHEN\n\t\t\terr := callCreate(pgRepository, suite.MethodName, ctx, suite.TenantID, suite.NilModelEntity)\n\t\t\t// THEN\n\t\t\trequire.Error(t, err)\n\t\t\tassert.Contains(t, err.Error(), \"Internal Server Error\")\n\t\t\tconvMock.AssertExpectations(t)\n\t\t})\n\t})\n}", "func TestController_E2E(t *testing.T) {\n\tapi := NewController(*NewInMemoryStorage())\n\ts := &testServer{Server: httptest.NewServer(api.Router)}\n\tdefer s.Close()\n\n\tt.Run(\"empty list\", s.list(0))\n\tt.Run(\"create 1\", s.create([]Note{{Title: \"\", Content: \"\"}}))\n\tt.Run(\"check 1 item\", s.list(1))\n\n\tif len(s.listNotes) == 0 {\n\t\tt.Fatalf(\"missing list nodes. stopping\")\n\t}\n\tif s.listNotes[0].ID.UUID != s.createdIDs[0] {\n\t\tt.Errorf(\"created ID not found in the list\")\n\t}\n\n\tt.Run(\"delete the item\", s.delete(s.listNotes[0].ID, true))\n\tt.Run(\"list should be empty\", s.list(0))\n\tt.Run(\"create 1 more\", s.create([]Note{{Title: \"nothing\", Content: \"\"}}))\n\tt.Run(\"delete it using body\", s.delete(NoteID{UUID: s.createdIDs[0]}, false))\n\n\tt.Run(\"list is empty again\", s.list(0))\n}", "func TestMain(m *testing.M) {\n\tcode := test.TestMain(m, func(svc *dynamodb.Client) error { // this function setups the database\n\t\t// create testing table\n\t\tcreateRequest := svc.CreateTableRequest(&dynamodb.CreateTableInput{\n\t\t\tAttributeDefinitions: []dynamodb.AttributeDefinition{\n\t\t\t\t{\n\t\t\t\t\tAttributeName: aws.String(\"PK\"),\n\t\t\t\t\tAttributeType: \"S\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tKeySchema: []dynamodb.KeySchemaElement{\n\t\t\t\t{\n\t\t\t\t\tAttributeName: aws.String(\"PK\"),\n\t\t\t\t\tKeyType: dynamodb.KeyTypeHash,\n\t\t\t\t},\n\t\t\t},\n\t\t\tProvisionedThroughput: &dynamodb.ProvisionedThroughput{\n\t\t\t\tReadCapacityUnits: aws.Int64(1),\n\t\t\t\tWriteCapacityUnits: aws.Int64(1),\n\t\t\t},\n\t\t\tTableName: aws.String(table),\n\t\t})\n\t\t_, err := createRequest.Send(context.Background())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// add testing data\n\t\trequest := svc.PutItemRequest(&dynamodb.PutItemInput{\n\t\t\tItem: map[string]dynamodb.AttributeValue{\n\t\t\t\t\"PK\": {S: aws.String(\"abc123\")},\n\t\t\t\t\"name\": {S: aws.String(\"John\")},\n\t\t\t},\n\t\t\tTableName: aws.String(table),\n\t\t})\n\t\t_, err = request.Send(context.Background())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\tos.Exit(code)\n}", "func TestToManyAdd(t *testing.T) {}", "func TestToManyAdd(t *testing.T) {}", "func TestToManyAdd(t *testing.T) {}", "func TestHandler_URLMappingPostRecapSalesSuccess(t *testing.T) {\n\to := orm.NewOrm()\n\to.Raw(\"DELETE FROM recap_sales\").Exec()\n\t// buat dummy partner\n\tpartnr := model.DummyPartnership()\n\tpartnr.IsDeleted = int8(0)\n\tpartnr.PartnershipType = \"customer\"\n\tpartnr.Save()\n\t// buat dummy so\n\tso1 := model.DummySalesOrder()\n\tso1.IsDeleted = int8(0)\n\tso1.DocumentStatus = \"finished\"\n\tso1.TotalCharge = float64(20000)\n\tso1.Customer = partnr\n\tso1.Save()\n\tso2 := model.DummySalesOrder()\n\tso2.IsDeleted = int8(0)\n\tso2.DocumentStatus = \"finished\"\n\tso2.TotalCharge = float64(30000)\n\tso2.Customer = partnr\n\tso2.Save()\n\n\t// melakukan proses login\n\tuser := model.DummyUserPriviledgeWithUsergroup(1)\n\tsd, _ := auth.Login(user)\n\ttoken := \"Bearer \" + sd.Token\n\n\t// setting body\n\tscenario := tester.D{\n\t\t\"partnership\": common.Encrypt(partnr.ID),\n\t\t\"recap_sales_items\": []tester.D{\n\t\t\t{\n\t\t\t\t\"sales_order\": common.Encrypt(so1.ID),\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"sales_order\": common.Encrypt(so2.ID),\n\t\t\t},\n\t\t},\n\t}\n\t// test\n\tng := tester.New()\n\tng.SetHeader(tester.H{\"Authorization\": token})\n\tng.POST(\"/v1/recap-sales\").SetJSON(scenario).Run(test.Router(), func(res tester.HTTPResponse, req tester.HTTPRequest) {\n\t\tassert.Equal(t, int(200), res.Code, fmt.Sprintf(\"\\nreason: Validation Not Matched,\\ndata: %v , \\nresponse: %v\", scenario, res.Body.String()))\n\t})\n\trec := &model.RecapSales{Partnership: &model.Partnership{ID: partnr.ID}}\n\te := rec.Read(\"Partnership\")\n\tassert.NoError(t, e)\n\tassert.Equal(t, float64(50000), rec.TotalAmount)\n\tassert.Equal(t, sd.User.ID, rec.CreatedBy.ID)\n\t// recap sale item\n\trecItm1 := &model.RecapSalesItem{RecapSales: &model.RecapSales{ID: rec.ID}, SalesOrder: &model.SalesOrder{ID: so1.ID}}\n\terr1 := recItm1.Read(\"RecapSales\", \"SalesOrder\")\n\tassert.NoError(t, err1)\n\trecItm2 := &model.RecapSalesItem{RecapSales: &model.RecapSales{ID: rec.ID}, SalesOrder: &model.SalesOrder{ID: so2.ID}}\n\terr2 := recItm2.Read(\"RecapSales\", \"SalesOrder\")\n\tassert.NoError(t, err2)\n}", "func TestReadUser(t *testing.T) {\r\n/////////////////////////////////// MOCKING ////////////////////////////////////////////\r\n\tvar batches = []string{\r\n\t\t`CREATE TABLE Users (Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, Name TEXT NOT NULL UNIQUE);`,\r\n\t\t`INSERT INTO Users (Id,Name) VALUES (1,'anonymous');`,\r\n\t}\r\n\t//open pseudo database for function\r\n\tdb, err := sql.Open(\"ramsql\", \"TestReadUser\")\r\n\tif err != nil {\r\n\t\tt.Fatalf(\"Error creating mock sql : %s\\n\", err)\r\n\t}\r\n\tdefer db.Close()\r\n\r\n\t// Exec every line of batch and create database\r\n\tfor _, b := range batches {\r\n\t\t_, err = db.Exec(b)\r\n\t\tif err != nil {\r\n\t\t\tt.Fatalf(\"Error exec query in query: %s\\n Error:%s\", b, err)\r\n\t\t}\r\n\t}\r\n/////////////////////////////////// MOCKING ////////////////////////////////////////////\r\n\r\n\t// Specify test variables and expected results.\r\n\ttests := []struct {\r\n\t\tid int\r\n\t\t// we need to use models.User for passing to object.This is different with \"database.User\".\r\n\t\tresult models.User\r\n\t\terr error\r\n\t}{\r\n\t\t// When give to first parameter(id) 1 , We expect result :1 error nil\r\n\t\t{id: 1, result: models.User{Id: 1, Name: \"anonymous\"}, err: nil},\r\n\t\t// When give to first parameter(id) 1 , We expect result :1 error nil\r\n\t\t//{id: 2, result: models.User{Id: 2, Name: \"test\"}, err: nil},\r\n\t}\r\n\r\n\t// test all of the variables.\r\n\tfor _, test := range tests {\r\n\t\t//get result after test.\r\n\t\ts, err := u.ReadUser(db, test.id)\r\n\t\t// if expected error type nil we need to compare with actual error different way.\r\n\t\tif test.err == nil {\r\n\t\t\t// If test fails give error.It checks expected result and expected error\r\n\t\t\tif err != test.err || s != test.result {\r\n\t\t\t\t// Compare expected error and actual error\r\n\t\t\t\tt.Errorf(\"Error is: %v . Expected: %v\", err, test.err)\r\n\t\t\t\t// Compare expected result and actual result\r\n\t\t\t\tt.Errorf(\"Result is: %v . Expected: %v\", s, test.result)\r\n\t\t\t}\r\n\t\t\t// if expected error type is not nil we need to compare with actual error different way.\r\n\t\t} else {\r\n\t\t\tif err.Error() != test.err.Error() || s != test.result {\r\n\t\t\t\t// Compare expected error and actual error\r\n\t\t\t\tt.Errorf(\"Error is: %v . Expected: %v\", err, test.err)\r\n\t\t\t\t// Compare expected result and actual result\r\n\t\t\t\tt.Errorf(\"Result is: %v . Expected: %v\", s, test.result)\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "func Test_handlerStudent_getStudent_Tom(t *testing.T) {\n\tGlobal_db = &StudentsDB{}\n\tGlobal_db.Init()\n\ttestStudent := Student{\"Tom\", 21, \"id0\"}\n\tGlobal_db.Add(testStudent)\n\n\tts := httptest.NewServer(http.HandlerFunc(HandlerStudent))\n\tdefer ts.Close()\n\n\t// --------------\n\tresp, err := http.Get(ts.URL + \"/student/id1\")\n\tif err != nil {\n\t\tt.Errorf(\"Error making the GET request, %s\", err)\n\t}\n\n\tif resp.StatusCode != http.StatusNotFound {\n\t\tt.Errorf(\"Expected StatusCode %d, received %d\", http.StatusNotFound, resp.StatusCode)\n\t\treturn\n\t}\n\n\t// --------------\n\tresp, err = http.Get(ts.URL + \"/student/id0\")\n\tif err != nil {\n\t\tt.Errorf(\"Error making the GET request, %s\", err)\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tt.Errorf(\"Expected StatusCode %d, received %d\", http.StatusOK, resp.StatusCode)\n\t\treturn\n\t}\n\n\tvar a Student\n\terr = json.NewDecoder(resp.Body).Decode(&a)\n\tif err != nil {\n\t\tt.Errorf(\"Error parsing the expected JSON body. Got error: %s\", err)\n\t}\n\n\tif a.Name != testStudent.Name || a.Age != testStudent.Age || a.StudentID != testStudent.StudentID {\n\t\tt.Errorf(\"Students do not match! Got: %v, Expected: %v\\n\", a, testStudent)\n\t}\n}", "func TestDeleteOrder(t *testing.T) {\n\n // ...\n\n}", "func testOnTiDB(cliconn *rpc.Client, method []string) {\n\ttidbreq := nodeServer.TiDBTestRequest{Echostr: \"hello, TiDB server\"}\n\tvar tidbres nodeServer.TiDBTestResponse\n\tvar remoteMethod string\n\tswitch method[0] {\n\tcase \"kill\":\n\t\tremoteMethod = \"KillTiDBServer\"\n\tcase \"cpu\":\n\t\tfmt.Printf(\"Stress TiDB Cpu for %s seconds\\n\", method[1])\n\t\tremoteMethod = \"StressCPU\"\n\t\ttidbreq.Cpubusytime, _ = strconv.ParseInt(method[1], 10, 64)\n\tdefault:\n\t\tremoteMethod = \"GetCurrentIP\"\n\t}\n\terr := cliconn.Call(\"TiDBNodeServer.\"+remoteMethod, tidbreq, &tidbres)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Printf(\"respone is %s\\n\", tidbres.Respstr)\n}", "func simulate(c echo.Context) error {\n\tsetInterval(func() {\n\n\t\ts1 := rand.NewSource(time.Now().UnixNano())\n\t\tr1 := rand.New(s1)\n\n\t\tnewVisitsData := visitsData{\n\t\t\tPages: r1.Intn(100),\n\t\t\tCount: r1.Intn(100),\n\t\t}\n\n\t\tclient.Trigger(\"visitorsCount\", \"addNumber\", newVisitsData)\n\n\t}, 2500, true)\n\n\treturn c.String(http.StatusOK, \"Simulation begun\")\n}", "func TestIntCreateTwoPeopleAndDeleteOneByIDStr(t *testing.T) {\n\tlog.SetPrefix(\"TestIntegrationCreateTwoPeopleAndDeleteOneByIDStr\")\n\t// Create a dao containing a session\n\tdbsession, err := dbsession.MakeGorpMysqlDBSession()\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tdefer dbsession.Close()\n\n\tdao := MakeRepo(dbsession)\n\n\tclearDown(dao, t)\n\n\t// Create two people\n\tp1 := personModel.MakeInitialisedPerson(0, expectedForename1, expectedSurname1)\n\tperson1, err := dao.Create(p1)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\tp2 := personModel.MakeInitialisedPerson(0, expectedForename2, expectedSurname2)\n\tperson2, err := dao.Create(p2)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\tvar IDStr = fmt.Sprintf(\"%d\", person1.ID())\n\trows, err := dao.DeleteByIDStr(IDStr)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tif rows != 1 {\n\t\tt.Errorf(\"expected one record to be deleted, actually %d\", rows)\n\t}\n\n\t// We should have one record in the DB and it should match person2\n\tpeople, err := dao.FindAll()\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\tif len(people) != 1 {\n\t\tt.Errorf(\"expected one record, actual %d\", len(people))\n\t}\n\n\tfor _, person := range people {\n\t\tif person.ID() != person2.ID() {\n\t\t\tt.Errorf(\"expected id to be %d actually %d\",\n\t\t\t\tperson2.ID(), person.ID())\n\t\t}\n\t\tif person.Forename() != expectedForename2 {\n\t\t\tt.Errorf(\"expected forename to be %s actually %s\",\n\t\t\t\texpectedForename2, person.Forename())\n\t\t}\n\t\tif person.Surname() != expectedSurname2 {\n\t\t\tt.Errorf(\"TestCreateTwoPeopleAndDeleteOneByIDStr(): expected surname to be %s actually %s\",\n\t\t\t\texpectedSurname2, person.Surname())\n\t\t}\n\t}\n\n\tclearDown(dao, t)\n}", "func TestInsertNewUserService (t *testing.T){\n\terr := PostNewUserService(user_01)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\terr = PostNewUserService(user_02)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\terr = PostNewUserService(user_03)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\terr = PostNewUserService(user_04)\n\tassert.Equal(t, 200, err.HTTPStatus)\n}", "func TestSimple(t *testing.T) {\n\tt.Logf(\"Running simple table tests\")\n\tdb, err = DialUnix(TEST_SOCK, TEST_USER, TEST_PASSWD, TEST_DBNAME)\n\tif err != nil {\n\t\tt.Logf(\"Error %s\", err)\n\t\tt.Fail()\n\t}\n\t\n\tt.Logf(\"Create table\")\n\terr = db.Query(CREATE_SIMPLE)\n\tif err != nil {\n\t\tt.Logf(\"Error %s\", err)\n\t\tt.Fail()\n\t}\n\t\n\tt.Logf(\"Insert 1000 records\")\n\trowMap := make(map[uint64][]string)\n\tfor i := 0; i < 1000; i++ {\n\t\tnum, str1, str2 := rand.Int(), randString(32), randString(128)\n\t\terr = db.Query(fmt.Sprintf(INSERT_SIMPLE, num, str1, str2))\n\t\tif err != nil {\n\t\t\tt.Logf(\"Error %s\", err)\n\t\t\tt.Fail()\n\t\t}\n\t\trow := []string{fmt.Sprintf(\"%d\", num), str1, str2}\n\t\trowMap[db.LastInsertId] = row\n\t}\n\t\n\tt.Logf(\"Select inserted data\")\n\terr = db.Query(SELECT_SIMPLE)\n\tif err != nil {\n\t\tt.Logf(\"Error %s\", err)\n\t\tt.Fail()\n\t}\n\t\n\tt.Logf(\"Use result\")\n\tres, err := db.UseResult()\n\tif err != nil {\n\t\tt.Logf(\"Error %s\", err)\n\t\tt.Fail()\n\t}\n\t\n\tt.Logf(\"Validate inserted data\")\n\tfor {\n\t\trow := res.FetchRow()\n\t\tif row == nil {\n\t\t\tbreak\n\t\t}\n\t\tid := row[0].(uint64)\n\t\tnum, str1, str2 := strconv.Itoa64(row[1].(int64)), row[2].(string), string(row[3].([]byte))\n\t\tif rowMap[id][0] != num || rowMap[id][1] != str1 || rowMap[id][2] != str2 {\n\t\t\tt.Logf(\"String from database doesn't match local string\")\n\t\t\tt.Fail()\n\t\t}\n\t}\n\t\n\tt.Logf(\"Free result\")\n\terr = res.Free()\n\tif err != nil {\n\t\tt.Logf(\"Error %s\", err)\n\t\tt.Fail()\n\t}\n\t\n\tt.Logf(\"Update some records\")\n\tfor i := uint64(0); i < 1000; i += 5 {\n\t\trowMap[i+1][2] = randString(256)\n\t\terr = db.Query(fmt.Sprintf(UPDATE_SIMPLE, rowMap[i+1][2], i+1))\n\t\tif err != nil {\n\t\t\tt.Logf(\"Error %s\", err)\n\t\t\tt.Fail()\n\t\t}\n\t\tif db.AffectedRows != 1 {\n\t\t\tt.Logf(\"Expected 1 effected row but got %d\", db.AffectedRows)\n\t\t\tt.Fail()\n\t\t}\n\t}\n\t\n\tt.Logf(\"Select updated data\")\n\terr = db.Query(SELECT_SIMPLE)\n\tif err != nil {\n\t\tt.Logf(\"Error %s\", err)\n\t\tt.Fail()\n\t}\n\t\n\tt.Logf(\"Store result\")\n\tres, err = db.StoreResult()\n\tif err != nil {\n\t\tt.Logf(\"Error %s\", err)\n\t\tt.Fail()\n\t}\n\t\n\tt.Logf(\"Validate updated data\")\n\tfor {\n\t\trow := res.FetchRow()\n\t\tif row == nil {\n\t\t\tbreak\n\t\t}\n\t\tid := row[0].(uint64)\n\t\tnum, str1, str2 := strconv.Itoa64(row[1].(int64)), row[2].(string), string(row[3].([]byte))\n\t\tif rowMap[id][0] != num || rowMap[id][1] != str1 || rowMap[id][2] != str2 {\n\t\t\tt.Logf(\"%#v %#v\", rowMap[id], row)\n\t\t\tt.Logf(\"String from database doesn't match local string\")\n\t\t\tt.Fail()\n\t\t}\n\t}\n\t\n\tt.Logf(\"Free result\")\n\terr = res.Free()\n\tif err != nil {\n\t\tt.Logf(\"Error %s\", err)\n\t\tt.Fail()\n\t}\n\n\tt.Logf(\"Drop table\")\n\terr = db.Query(DROP_SIMPLE)\n\tif err != nil {\n\t\tt.Logf(\"Error %s\", err)\n\t\tt.Fail()\n\t}\n\t\n\tt.Logf(\"Close connection\")\n\terr = db.Close()\n\tif err != nil {\n\t\tt.Logf(\"Error %s\", err)\n\t\tt.Fail()\n\t}\n}", "func (f Factory) SimulateAndExecute() bool { return f.simulateAndExecute }", "func TestAPIGetAll() error {\n\ttestRead := testCase{\n\t\tinput: \"\",\n\t\texpected: `[{\"FirstName\":\"Alec\", \"LastName\":\"Perro\", \"Age\":5}]`,\n\t}\n\n query, err := dm.Read(1)\n if err != nil {\n log.Fatal(err)\n }\n\n\tjsonify, err := json.Marshal(query)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif testRead.expected != string(jsonify) {\n\t\treturn errors.New(\"testDB failed\")\n\t}\n\n\tfmt.Println(\"Tests passed\")\n\treturn nil\n}", "func Example_crudOperations() {\n\tdb, _ := dbx.Open(\"mysql\", \"user:pass@/example\")\n\n\tvar customer Customer\n\n\t// read a customer: SELECT * FROM customer WHERE id=100\n\tdb.Select().Model(100, &customer)\n\n\t// create a customer: INSERT INTO customer (name) VALUES ('test')\n\tdb.Model(&customer).Insert()\n\n\t// update a customer: UPDATE customer SET name='test' WHERE id=100\n\tdb.Model(&customer).Update()\n\n\t// delete a customer: DELETE FROM customer WHERE id=100\n\tdb.Model(&customer).Delete()\n}", "func setupDatabase(t *testing.T) (client *entity.Client) {\n\tclient = enttest.Open(t, \"sqlite3\", \"file:ent?mode=memory&_fk=1\")\n\tctx := context.Background()\n\tif err := client.Schema.Create(ctx); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := setSampleData(ctx, client); err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}", "func (f *Factory) SimulateAndExecute() bool { return f.simulateAndExecute }", "func TestBasicAPI(t *testing.T) {\n\tr := NewRegistrar()\n\tr.Add(session)\n\tr.Remove(name)\n}", "func TestCreateSuccess(t *testing.T) {\n\tisTesting = true\n\tvar request = Request{\n\t\tPath: \"/api/devices\",\n\t\tHTTPMethod: \"POST\",\n\t\tBody: `{\n\t\t\t\"id\": \"valid-id\",\n\t\t\t\"deviceModel\": \"valid-device-model\",\n\t\t\t\"model\": \"valid-model\",\n\t\t\t\"name\": \"valid-name\",\n\t\t\t\"serial\": \"valid-serial\"\n\t\t}`,\n\t}\n\tvar response, _ = Handler(request)\n\tif response.StatusCode != 201 {\n\t\tt.Errorf(\"response status code has to be 201\")\n\t}\n}", "func BasicExample() {\n\tconfig, log, statsd := infra()\n\n\t// TODO: Define schema\n\t// TODO: Build database connector - MySQL, Mongo\n\t// TODO: Pre/post hooks and override actions\n\t// TODO: Flexibility with rendering templates (custom head/foot/style)\n\n\tusers := &crud.Entity{\n\t\tID: \"users\",\n\t\tLabel: \"User\",\n\t\tLabels: \"Users\",\n\t\tElements: crud.Elements{\n\t\t\t{\n\t\t\t\tID: \"id\",\n\t\t\t\tLabel: \"ID\",\n\t\t\t\tPrimaryKey: true,\n\t\t\t\tFormType: crud.ELEMENT_FORM_TYPE_HIDDEN,\n\t\t\t\tDataType: crud.ELEMENT_DATA_TYPE_STRING,\n\t\t\t},\n\t\t\t{\n\t\t\t\tID: \"name\",\n\t\t\t\tLabel: \"Name\",\n\t\t\t\tFormType: crud.ELEMENT_FORM_TYPE_TEXT,\n\t\t\t\tDataType: crud.ELEMENT_DATA_TYPE_STRING,\n\t\t\t},\n\t\t\t{\n\t\t\t\tID: \"age\",\n\t\t\t\tLabel: \"Age\",\n\t\t\t\tFormType: crud.ELEMENT_FORM_TYPE_TEXT,\n\t\t\t\tDataType: crud.ELEMENT_DATA_TYPE_NUMBER,\n\t\t\t\tDefaultValue: 22,\n\t\t\t},\n\t\t},\n\t}\n\n\t// Todo: should do NewEntity and not newing up Entity manually.\n\terr := users.CheckConfiguration()\n\tif err != nil {\n\t\tlog.Error(fmt.Sprintf(`Error with \"users\" entity: %v`, err))\n\t\tos.Exit(1)\n\t}\n\n\tmyConfig := &crud.Config{}\n\n\tmyCrud := crud.NewCrud(myConfig, log, statsd)\n\n\t// Add store (database)\n\tmyStore, err := crud.NewMongoStore(os.Getenv(\"MONGO_DB_CONNECTION\"), \"\", os.Getenv(\"MONGO_DB_NAME\"), statsd, log)\n\tif err != nil {\n\t\tlog.Error(fmt.Sprintf(\"Error with store: %v\", err))\n\t\tos.Exit(1)\n\t}\n\tmyCrud.AddStore(myStore)\n\n\t// Register Entity\n\tmyCrud.AddEntity(users)\n\n\t// Basic mutator added\n\tmyCrud.AddMutator(&basicMutator{})\n\n\t// Basic validator added\n\t//myCrud.AddElementsValidator(&basicElementsValidator{}) // TODO add a non-destructive validator for illustrative purposes (this one fails on all requests)\n\n\t// Mount Route\n\trouter := chi.NewRouter()\n\t// TODO remove this warning when Chi is fixed\n\trouter.Get(\"/gocrud\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(\"Bug in chi. Add / to end\"))\n\t})\n\trouter.Mount(\"/gocrud/\", myCrud.Handler())\n\n\t// Serve HTTP endpoint\n\terr = http.ListenAndServe(fmt.Sprintf(\":%d\", config.Port), router)\n\tif err != nil {\n\t\tlog.Error(\"Problem starting server\", err.Error())\n\t\tos.Exit(1)\n\t}\n}", "func TestAllRest(t *testing.T) {\n\tConfigure()\n\tvar table = [][]RequestTestPair{\n\t\ttestAddEvent(t),\n\t\ttestDuplicateEvent(t),\n\t\ttestGetAllConfig(t),\n\t\ttestAddTracer(t),\n\t\ttestSwitchProject(t),\n\t\ttestDeleteProject(t),\n\t}\n\n\tserverTestHelperBulk(table, t)\n}", "func (s *Store) fixture() {\n\ts.db.Exec(`INSERT INTO unicode_data VALUES ('1F60E', 'SMILING FACE WITH SUNGLASSES', 'So', '', '', '', '', '', '', '', '', '', '', '', '')`)\n\ts.db.Exec(`INSERT INTO unicode_data VALUES ('1F602', 'FACE WITH TEARS OF JOY', 'So', '', '', '', '', '', '', '', '', '', '', '', '')`)\n\ts.db.Exec(`INSERT INTO unicode_data VALUES ('1F4D7', 'GREEN BOOK', 'So', '', '', '', '', '', '', '', '', '', '', '', '')`)\n}", "func TestLoad(t *testing.T){\n\t\n\tLoadData()\n\n\t// Simple test if the lists contain anything\n\tif len(sightings) == 0{\n\t\tt.Errorf(\"Loading sightings failed\")\n\t}\n\tif len(species) == 0{\n\t\tt.Errorf(\"Loading species failed\")\n\t}\n}", "func Load(db *gorm.DB) ([]models.User, []models.Post) {\n\tvar insertedUsers []models.User\n\tvar insertedPosts []models.Post\n\t// drop tables if they exist\n\tdb.Debug().Migrator().DropTable(&models.User{})\n\tdb.Debug().Migrator().DropTable(&models.Post{})\n\t// migrate tables\n\tdb.Debug().AutoMigrate(&models.User{}, &models.Post{})\n\n\t// insert MockUsers\n\tfor _, user := range MockUsers {\n\t\t// encrypt user's password\n\t\tuser.BeforeSave()\n\t\t// insert user\n\t\terr := db.Debug().Create(&user).Error\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"cannot seed user: %v - user: %v\\n\", err, user)\n\t\t}\n\n\t\tinsertedUsers = append(insertedUsers, user)\n\t}\n\n\t// get total # of MockUsers\n\tvar numUsers int64\n\tdb.Model(&MockUsers).Count(&numUsers)\n\n\t// insert MockPosts when we have MockUsers\n\tif numUsers > 0 {\n\t\tfor _, post := range MockPosts {\n\t\t\t// fetch random user ID\n\t\t\ts1 := rand.NewSource(time.Now().UnixNano())\n\t\t\tr1 := rand.New(s1)\n\t\t\tvar userId []uint32\n\t\t\terr := db.Select(\"id\").Model(&models.User{}).Offset(r1.Intn(int(numUsers))).Limit(1).Take(&userId).Error\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"failed to fetch user ID: %v\\n\", err)\n\t\t\t}\n\n\t\t\t// set author ID\n\t\t\tpost.AuthorID = userId[0]\n\t\t\t// insert post with author ID link\n\t\t\terr = db.Debug().Create(&post).Error\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"cannot seed post: %v - post %v\\n\", err, post)\n\t\t\t}\n\n\t\t\tinsertedPosts = append(insertedPosts, post)\n\t\t}\n\t}\n\n\treturn insertedUsers, insertedPosts\n}", "func TestTableCreation(t *testing.T) {\n\tcommon.InitConfig()\n\n\tdb := GetInstance()\n\n\t// A map of table name to creation function,\n\t// as in database.go\n\tvar tableMap = map[string]func() error{\n\t\tpaymentsTable: db.createPaymentsTable,\n\t}\n\n\t// Loop through our creation funcs, execute and test\n\tfor _, createFunc := range tableMap {\n\t\terr := createFunc()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n}", "func TestUpdateOrder(t *testing.T) {\n\n // ...\n\n}", "func (l *LoadTester) test() {\n\tvar body []byte\n\n\tstart := time.Now()\n\tresp, err := l.client.Do(l.request)\n\tif err != nil {\n\t\tl.stats.update(0, 0, err)\n\t}\n\trd := time.Since(start)\n\n\tif resp != nil {\n\t\tdefer resp.Body.Close()\n\t\tbody, err = ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\tl.stats.update(0, 0, err)\n\t\t}\n\t}\n\n\trs := len(body)\n\n\t// update stats\n\tl.stats.update(rs, rd, nil)\n\n}", "func TestCreateModelAndListModels(t *testing.T) {\n\tsrv := testingServer()\n\tmodelRequests := make([]api.CreateModelRequest, 5)\n\tfor i := range modelRequests {\n\t\tmodelID := fmt.Sprintf(\"test-model-%d\", i)\n\t\tdescription := fmt.Sprintf(\"This is test model %d\", i)\n\t\tmodel := api.CreateModelRequest{\n\t\t\tModel: &api.Model{\n\t\t\t\tModelId: modelID,\n\t\t\t\tDescription: description,\n\t\t\t},\n\t\t}\n\t\tmodelRequests[i] = model\n\t}\n\n\tctx := context.Background()\n\n\t// TODO: Instead of doing ListModels on the server, we should inspect server.storage directly\n\tlistModelsRequest := api.ListModelsRequest{\n\t\tMaxItems: 20,\n\t}\n\tfor i, req := range modelRequests {\n\t\tlistModelsResponse, err := srv.ListModels(ctx, &listModelsRequest)\n\t\tassert.NoError(t, err)\n\t\tmodels := listModelsResponse.ModelIds\n\t\tif len(models) != i {\n\t\t\tt.Errorf(\"Incorrect number of models in storage; expected: %d, actual: %d\", i, len(models))\n\t\t}\n\t\tcreateModelResponse, err := srv.CreateModel(ctx, &req)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\texpectedResourcePath := fmt.Sprintf(\"/models/%s\", req.Model.ModelId)\n\t\tif createModelResponse.ResourcePath != expectedResourcePath {\n\t\t\tt.Errorf(\"Incorrect resource path for created model; expected: %s, actual: %s\", expectedResourcePath, createModelResponse.ResourcePath)\n\t\t}\n\t}\n\n\t// Creation with a duplicated request should fail\n\t_, err := srv.CreateModel(ctx, &modelRequests[0])\n\tif err == nil {\n\t\tt.Error(\"Server did not error out on creation of duplicate model\")\n\t}\n}", "func TestDaoAddPrivilege(t *testing.T) {\n\ttx := d.BeginGormTran(context.Background())\n\tp := &model.Privilege{\n\t\tName: \"超高清\",\n\t\tTitle: \"超高清标题\",\n\t\tExplain: \"超高清描述描述超多字超多字超多字超多字超多字超多字超多字超多字超多字超多字超多字超多字超多字\",\n\t\tType: 1,\n\t\tOperator: \"admin\",\n\t\tState: 0,\n\t\tDeleted: 0,\n\t\tIconURL: \"https://activity.hdslb.com/blackboard/activity9757/static/img/title_screen.c529058.jpg\",\n\t\tIconGrayURL: \"https://activity.hdslb.com/blackboard/activity9757/static/img/title_screen.c529058.jpg\",\n\t\tOrder: 1,\n\t\tLangType: 1,\n\t}\n\tconvey.Convey(\"get max id\", t, func() {\n\t\tep := new(model.Privilege)\n\t\tdb := d.vip.Table(_vipPrivileges).Order(\"order_num DESC\").First(&ep)\n\t\tconvey.So(db.Error, convey.ShouldBeNil)\n\t\td.vip.Table(_vipPrivilegesResources).Where(\"pid > ?\", ep.ID).Delete(model.PrivilegeResources{})\n\t\tp.ID = ep.ID + 1\n\t})\n\tconvey.Convey(\"AddPrivilege\", t, func() {\n\t\tid, err := d.AddPrivilege(tx, p)\n\t\tconvey.So(err, convey.ShouldBeNil)\n\t\tconvey.So(id, convey.ShouldNotBeNil)\n\t})\n\tconvey.Convey(\"AddPrivilegeResources\", t, func() {\n\t\ta, err := d.AddPrivilegeResources(tx, &model.PrivilegeResources{\n\t\t\tPID: p.ID,\n\t\t\tLink: \"web\",\n\t\t\tType: model.WebResources,\n\t\t})\n\t\tconvey.So(err, convey.ShouldBeNil)\n\t\tconvey.So(a, convey.ShouldNotBeNil)\n\t\ta, err = d.AddPrivilegeResources(tx, &model.PrivilegeResources{\n\t\t\tPID: p.ID,\n\t\t\tLink: \"app\",\n\t\t\tType: model.AppResources,\n\t\t})\n\t\tconvey.So(err, convey.ShouldBeNil)\n\t\tconvey.So(a, convey.ShouldNotBeNil)\n\t})\n\tconvey.Convey(\"AddPrivilege Commit\", t, func() {\n\t\terr := tx.Commit().Error\n\t\tconvey.So(err, convey.ShouldBeNil)\n\t})\n\tconvey.Convey(\"PrivilegeList\", t, func() {\n\t\tres, err := d.PrivilegeList(context.TODO(), 1)\n\t\tconvey.So(err, convey.ShouldBeNil)\n\t\tconvey.So(res, convey.ShouldNotBeNil)\n\t})\n\tconvey.Convey(\"clean data\", t, func() {\n\t\td.vip.Delete(p)\n\t\td.vip.Table(_vipPrivilegesResources).Where(\"pid >= ?\", p.ID).Delete(model.PrivilegeResources{})\n\t})\n}", "func (suite *NoteRepoTestSuite) TestNoteRepoList() {\n\tvar p = helper.Pagination{\n\t\tPage: 1,\n\t\tLimit: 2,\n\t}\n\tsuite.Run(\"find with having found id\", func() {\n\t\t// Mock du lieu tra ve\n\t\trows := sqlmock.NewRows([]string{\"id\", \"created_at\", \"updated_at\", \"deleted_at\", \"title\", \"completed\"}).\n\t\t\tAddRow(1, time.Now(), time.Now(), nil, \"Todo 123\", true).\n\t\t\tAddRow(2, time.Now(), time.Now(), nil, \"Todo 124\", false)\n\n\t\t// Trong truong ho query\n\t\tsuite.mock.ExpectQuery(\"SELECT \\\\* FROM `notes`\").\n\t\t\tWillReturnRows(rows)\n\n\t\tactual, err := suite.noteRepo.List(p)\n\t\tif err != nil {\n\t\t\tsuite.Fail(\"Error should be nil\")\n\t\t}\n\t\tif len(actual) != 2 {\n\t\t\tsuite.Fail(\"Len of result should equal to 2\")\n\t\t}\n\t})\n\n\tsuite.Run(\"find with not found id\", func() {\n\t\t// Trong turong hop khong co cai id\n\t\trows := sqlmock.NewRows([]string{\"id\", \"created_at\", \"updated_at\", \"deleted_at\", \"title\", \"completed\"})\n\t\t// Trong truong ho query\n\t\tsuite.mock.ExpectQuery(\"SELECT \\\\* FROM `notes`\").\n\t\t\tWillReturnRows(rows)\n\t\tactual, err := suite.noteRepo.List(p)\n\t\tif err != nil {\n\t\t\tsuite.Fail(\"Error should be nil\")\n\t\t}\n\t\tif len(actual) != 0 {\n\t\t\tsuite.Fail(\"Len of result should equal to 0\")\n\t\t}\n\t})\n}", "func TestGetAllTodos(t *testing.T) {\n\t_client := setupDatabase(t)\n\t_handler := setupTodoHandler(_client)\n\tdefer _client.Close()\n\n\tapp := fiber.New()\n\n\tapp.Get(\"/todos\", _handler.GetAllTodos)\n\n\tr := httptest.NewRequest(\"GET\", \"/todos\", nil)\n\n\tresp, err := app.Test(r)\n\tif err != nil {\n\t\tassert.Fail(t, err.Error())\n\t}\n\n\tassert.Equal(t, fiber.StatusOK, resp.StatusCode)\n\n\tvar data []*entity.Todo\n\tif err := json.NewDecoder(resp.Body).Decode(&data); err != nil {\n\t\tassert.Fail(t, err.Error())\n\t}\n\n\tfmt.Println(\"All Todos:\", data)\n\tfmt.Println(\"Status Code:\", resp.StatusCode)\n}", "func TestShardBasic(t *testing.T) {\n\tfmt.Println (\"TestShardBasic begin +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n\tlogger.GetLogger().Log(logger.Debug, \"TestShardBasic begin +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\\n\")\n\ttime.Sleep(8 * time.Second);\n\t\n\thostname := testutil.GetHostname()\n fmt.Println (\"Hostname: \", hostname);\n db, err := sql.Open(\"hera\", hostname + \":31002\")\n if err != nil {\n t.Fatal(\"Error starting Mux:\", err)\n return\n }\n\n\tdb.SetMaxIdleConns(0)\n\tdefer db.Close()\n\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\t// cleanup and insert one row in the table\n\tconn, err := db.Conn(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"Error getting connection %s\\n\", err.Error())\n\t}\n\ttx, _ := conn.BeginTx(ctx, nil)\n\tstmt, _ := tx.PrepareContext(ctx, \"/*cmd*/insert into test_simple_table_2 (accountID, Name, Status) VALUES(:accountID, :Name, :Status)\")\n\t_, err = stmt.Exec(sql.Named(\"accountID\", \"12346\"), sql.Named(\"Name\", \"Steve\"), sql.Named(\"Status\", \"done\"))\n\tif err != nil {\n\t\tt.Fatalf(\"Error preparing test (create row in table) %s\\n\", err.Error())\n\t}\n\terr = tx.Commit()\n\tif err != nil {\n\t\tt.Fatalf(\"Error commit %s\\n\", err.Error())\n\t}\n\t\n\tfmt.Println (\"Send an update request without shard key\")\n\tstmt, _ = conn.PrepareContext(ctx, \"/*cmd*/Update test_simple_table_2 set Status = 'progess' where Name=?\")\n\tstmt.Exec(\"Steve\")\n\n\tstmt.Close()\n\n\tcancel()\n\tconn.Close() \n\n \tfmt.Println (\"Verify insert request is sent to shard 3\")\t\n count := testutil.RegexCount (\"WORKER shd3.*Preparing.*insert into test_simple_table_2\")\n\tif (count < 1) {\n t.Fatalf (\"Error: Insert Query does NOT go to shd3\");\n }\n\n \tfmt.Println (\"Verify no shard key error is thrown for fetch request\")\t\n count = testutil.RegexCount (\"Error preprocessing sharding, hangup: HERA-373: no shard key or more than one or bad logical\")\n\tif (count < 1) {\n t.Fatalf (\"Error: No Shard key error should be thrown for fetch request\");\n }\n cal_count := testutil.RegexCountFile (\"SHARDING.*shard_key_not_found.*0.*sql=1093137600\", \"cal.log\")\n\tif (cal_count < 1) {\n t.Fatalf (\"Error: No Shard key event for fetch request in CAL\");\n }\n\t\n \tfmt.Println (\"Check CAL log for correct events\");\n cal_count = testutil.RegexCountFile (\"SHARDING.*shard_key_auto_discovery.*0.*shardkey=accountid|12346&shardid=3&scuttleid=\", \"cal.log\")\n\tif (cal_count < 1) {\n t.Fatalf (\"Error: No shard_key_auto_discovery event seen in CAL\");\n }\n cal_count = testutil.RegexCountFile (\"T.*API.*CLIENT_SESSION_3\", \"cal.log\")\n\tif (cal_count < 1) {\n t.Fatalf (\"Error: Request is not executed by shard 3 as expected\");\n }\n\n\tfmt.Println (\"Open new connection as previous connection is already closed\");\n\tctx1, cancel1 := context.WithTimeout(context.Background(), 10*time.Second)\n\tconn1, err := db.Conn(ctx1)\n if err != nil {\n t.Fatalf(\"Error getting connection %s\\n\", err.Error())\n }\n tx1, _ := conn1.BeginTx(ctx1, nil)\n\tfmt.Println (\"Update table with shard key passed\");\n stmt1, _ := tx1.PrepareContext(ctx1, \"/*cmd*/ update test_simple_table_2 set Status = 'In Progress' where accountID in (:accountID)\")\n _, err = stmt1.Exec(sql.Named(\"accountID\", \"12346\"))\n if err != nil {\n t.Fatalf(\"Error updating row in table %s\\n\", err.Error())\n }\n err = tx1.Commit()\n if err != nil {\n t.Fatalf(\"Error commit %s\\n\", err.Error())\n }\n\tstmt1, _ = conn1.PrepareContext(ctx1, \"/*TestShardingBasic*/Select name, status from test_simple_table_2 where accountID=:accountID\")\n\trows1, _ := stmt1.Query(sql.Named(\"accountID\", \"12346\"))\n if !rows1.Next() {\n\t\tt.Fatalf(\"Expected 1 row\")\n\t}\n\tvar name, status string\n\terr = rows1.Scan(&name, &status)\n\tif err != nil {\n\t\tt.Fatalf(\"Expected values %s\", err.Error())\n\t}\n\tif (name != \"Steve\" || status != \"In Progress\") {\n\t\tt.Fatalf(\"***Error: name= %s, status=%s\", name, status)\n\t}\n\trows1.Close()\n\tstmt1.Close()\n\n\tcancel1()\n\tconn1.Close()\n\n\tfmt.Println (\"Verify update request is sent to shard 3\")\n count1 := testutil.RegexCount (\"WORKER shd3.*Preparing.*update test_simple_table_2\")\n\tif (count1 < 1) {\n t.Fatalf (\"Error: Update Query does NOT go to shd3\");\n }\n\n\tfmt.Println (\"Verify select request is sent to shard 3\")\n count1 = testutil.RegexCount (\"WORKER shd3.*Preparing.*TestShardingBasic.*Select name, status from test_simple_table_2\")\n\tif (count1 < 1) {\n t.Fatalf (\"Error: Select Query does NOT go to shd3\");\n }\n\ttestutil.DoDefaultValidation(t)\n\ttime.Sleep (time.Duration(2 * time.Second))\n\tlogger.GetLogger().Log(logger.Debug, \"TestShardBasic done -------------------------------------------------------------\")\n}", "func TestDatabasesCRUD(t *testing.T) {\n\tctx := context.Background()\n\n\tbackend, err := memory.New(memory.Config{\n\t\tContext: ctx,\n\t\tClock: clockwork.NewFakeClock(),\n\t})\n\trequire.NoError(t, err)\n\n\tservice := NewDatabasesService(backend)\n\n\t// Create a couple databases.\n\tdb1, err := types.NewDatabaseV3(types.Metadata{\n\t\tName: \"db1\",\n\t}, types.DatabaseSpecV3{\n\t\tProtocol: defaults.ProtocolPostgres,\n\t\tURI: \"localhost:5432\",\n\t})\n\trequire.NoError(t, err)\n\tdb2, err := types.NewDatabaseV3(types.Metadata{\n\t\tName: \"db2\",\n\t}, types.DatabaseSpecV3{\n\t\tProtocol: defaults.ProtocolMySQL,\n\t\tURI: \"localhost:3306\",\n\t})\n\trequire.NoError(t, err)\n\n\t// Initially we expect no databases.\n\tout, err := service.GetDatabases(ctx)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 0, len(out))\n\n\t// Create both databases.\n\terr = service.CreateDatabase(ctx, db1)\n\trequire.NoError(t, err)\n\terr = service.CreateDatabase(ctx, db2)\n\trequire.NoError(t, err)\n\n\t// Try to create an invalid database.\n\tdbBadURI, err := types.NewDatabaseV3(types.Metadata{\n\t\tName: \"db-missing-port\",\n\t}, types.DatabaseSpecV3{\n\t\tProtocol: defaults.ProtocolMySQL,\n\t\tURI: \"localhost\",\n\t})\n\trequire.NoError(t, err)\n\trequire.NoError(t, service.CreateDatabase(ctx, dbBadURI))\n\n\t// Fetch all databases.\n\tout, err = service.GetDatabases(ctx)\n\trequire.NoError(t, err)\n\trequire.Empty(t, cmp.Diff([]types.Database{dbBadURI, db1, db2}, out,\n\t\tcmpopts.IgnoreFields(types.Metadata{}, \"ID\"),\n\t))\n\n\t// Fetch a specific database.\n\tdb, err := service.GetDatabase(ctx, db2.GetName())\n\trequire.NoError(t, err)\n\trequire.Empty(t, cmp.Diff(db2, db,\n\t\tcmpopts.IgnoreFields(types.Metadata{}, \"ID\"),\n\t))\n\n\t// Try to fetch a database that doesn't exist.\n\t_, err = service.GetDatabase(ctx, \"doesnotexist\")\n\trequire.IsType(t, trace.NotFound(\"\"), err)\n\n\t// Try to create the same database.\n\terr = service.CreateDatabase(ctx, db1)\n\trequire.IsType(t, trace.AlreadyExists(\"\"), err)\n\n\t// Update a database.\n\tdb1.Metadata.Description = \"description\"\n\terr = service.UpdateDatabase(ctx, db1)\n\trequire.NoError(t, err)\n\tdb, err = service.GetDatabase(ctx, db1.GetName())\n\trequire.NoError(t, err)\n\trequire.Empty(t, cmp.Diff(db1, db,\n\t\tcmpopts.IgnoreFields(types.Metadata{}, \"ID\"),\n\t))\n\n\t// Delete a database.\n\terr = service.DeleteDatabase(ctx, db1.GetName())\n\trequire.NoError(t, err)\n\tout, err = service.GetDatabases(ctx)\n\trequire.NoError(t, err)\n\trequire.Empty(t, cmp.Diff([]types.Database{dbBadURI, db2}, out,\n\t\tcmpopts.IgnoreFields(types.Metadata{}, \"ID\"),\n\t))\n\n\t// Try to delete a database that doesn't exist.\n\terr = service.DeleteDatabase(ctx, \"doesnotexist\")\n\trequire.IsType(t, trace.NotFound(\"\"), err)\n\n\t// Delete all databases.\n\terr = service.DeleteAllDatabases(ctx)\n\trequire.NoError(t, err)\n\tout, err = service.GetDatabases(ctx)\n\trequire.NoError(t, err)\n\trequire.Len(t, out, 0)\n}", "func (n *mockAgent) load(s persistapi.AgentState) {}", "func TestGetAllOrdersForRestaurantID(t *testing.T) {\n\n // ...\n\n}", "func TestUserstorage(t *testing.T) {\n t.Log(\"*** User data storage and retrieval test ***\")\n\n // initialize user\n u, err := InitUser(\"alice\",\"fubar\")\n if err != nil {\n t.Error(\"Failed to initialize user (\", err, \")\")\n } else {\n t.Log(\"Successfully stored user\", u)\n }\n\n // retrieve user \n v, err := GetUser(\"alice\", \"fubar\")\n if err != nil {\n t.Error(\"Failed to reload user\", err)\n } else {\n t.Log(\"Correctly retrieved user\", v)\n }\n}", "func Test_Basic(t *testing.T) {\n\ttt := TT{t}\n\n\ttt.ForeachDB(\"+nothing\", func(db *sql.DB) {\n\t\ttt.MustResult(db.Exec(`INSERT INTO knowledge VALUES (5, 'chaos')`)).RowsAffected()\n\n\t\taffected, err := tt.MustResult(db.Exec(`UPDATE knowledge SET thing = $1 WHERE number = $2`, \"douglas\", \"42\")).RowsAffected()\n\t\ttt.Must(err)\n\t\tif affected != 1 {\n\t\t\ttt.Unexpected(\"affected\", 1, affected)\n\t\t}\n\n\t\ttt.MustResult(db.Exec(`DELETE FROM knowledge WHERE thing = 'conspiracy'`))\n\n\t\trows := tt.MustRows(db.Query(`SELECT * FROM knowledge ORDER BY number`))\n\t\ttt.ExpectRow(rows, 5, \"chaos\")\n\t\ttt.ExpectRow(rows, 42, \"douglas\")\n\t\tif rows.Next() {\n\t\t\tt.Fatalf(\"unexpected continuation of result set\")\n\t\t}\n\t\ttt.Must(rows.Close())\n\t})\n\n\ttt.CleanupDB()\n}", "func (suite *HandlerTestSuite) TestGetSingleRecipe() {\n\n\trecipe := recipeForTest()\n\tsuite.repo.Recipes[recipe.Id] = recipe\n\n\trequest := apiGatewayRequestForTest(http.MethodGet, nil, &recipe.Id)\n\tresponse, err := suite.handler.handle(context.Background(), request)\n\tsuite.Nil(err)\n\tsuite.assertSuccessfulResponse(response)\n\n\tresponseRecipe, err := getRecipeFromResponse(response)\n\tsuite.Nil(err)\n\tsuite.Equal(recipe.Id, responseRecipe.Id)\n\n\tnotExistingId := utils.NewId()\n\trequest2 := apiGatewayRequestForTest(http.MethodGet, nil, &notExistingId)\n\tresponse2, err := suite.handler.handle(context.Background(), request2)\n\tsuite.NotNil(err)\n\tsuite.assertResponseStatusCode(response2, http.StatusInternalServerError)\n\n\trequest3 := apiGatewayRequestForTest(http.MethodGet, nil, nil)\n\tresponse3, err := suite.handler.handle(context.Background(), request3)\n\tsuite.NotNil(err)\n\tsuite.assertResponseStatusCode(response3, http.StatusBadRequest)\n}", "func (test *RestTest) Execute(testcase *TestCase, ctx *TestContext) error {\n\ttestData := testcase.Data\n\n\tswitch testcase.Method {\n\tcase METHOD_CREATE_SERVICE, METHOD_CREATE_POLICY, METHOD_CREATE_ROLEPOLICY,\n\t\tMETHOD_IS_ALLOWED, METHOD_GET_GRANTED_ROLES, METHOD_GET_GRANTED_PERMISSIONS:\n\t\treturn test.Client.Post(testData)\n\tcase METHOD_GET_SERVICE, METHOD_QUERY_SERVICE, METHOD_GET_POLICY, METHOD_QUERY_POLICY,\n\t\tMETHOD_GET_ROLEPOLICY, METHOD_QUERY_ROLEPOLICY:\n\t\treturn test.Client.Get(testData)\n\tcase METHOD_DELETE_SERVICE, METHOD_DELETE_POLICY, METHOD_DELETE_ROLEPOLICY:\n\t\treturn test.Client.Delete(testData)\n\tdefault:\n\t\treturn errors.New(ERROR_SPEEDLE_NOT_SUPPORTED)\n\t}\n}", "func StorageListTest(app *Server, t *testing.T, testData string) {\n\tapp.Storage.Clear()\n\tmodData := testData + testData\n\tkey, err := app.Storage.Set(\"test/123\", testData)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"123\", key)\n\tkey, err = app.Storage.Set(\"test/456\", modData)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"456\", key)\n\tdata, err := app.Storage.Get(\"test/*\")\n\trequire.NoError(t, err)\n\tvar testObjects []objects.Object\n\terr = json.Unmarshal(data, &testObjects)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 2, len(testObjects))\n\tfor i := range testObjects {\n\t\tif testObjects[i].Index == \"123\" {\n\t\t\trequire.Equal(t, testData, testObjects[i].Data)\n\t\t}\n\n\t\tif testObjects[i].Index == \"456\" {\n\t\t\trequire.Equal(t, modData, testObjects[i].Data)\n\t\t}\n\t}\n\tdata1, err := app.Storage.Get(\"test/123\")\n\trequire.NoError(t, err)\n\tdata2, err := app.Storage.Get(\"test/456\")\n\trequire.NoError(t, err)\n\tobj1, err := objects.DecodeRaw(data1)\n\trequire.NoError(t, err)\n\tobj2, err := objects.DecodeRaw(data2)\n\trequire.NoError(t, err)\n\trequire.Equal(t, testData, obj1.Data)\n\trequire.Equal(t, modData, obj2.Data)\n\tkeys, err := app.Storage.Keys()\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"{\\\"keys\\\":[\\\"test/123\\\",\\\"test/456\\\"]}\", string(keys))\n\n\treq := httptest.NewRequest(\n\t\t\"POST\", \"/test/*\",\n\t\tbytes.NewBuffer(\n\t\t\t[]byte(`{\"data\":\"testpost\"}`),\n\t\t),\n\t)\n\tw := httptest.NewRecorder()\n\tapp.Router.ServeHTTP(w, req)\n\tresp := w.Result()\n\trequire.Equal(t, http.StatusOK, resp.StatusCode)\n\tbody, err := io.ReadAll(resp.Body)\n\trequire.NoError(t, err)\n\tdat, err := objects.DecodeRaw(body)\n\trequire.NoError(t, err)\n\tdata, err = app.Storage.Get(\"test/*\")\n\tapp.Console.Log(string(data))\n\trequire.NoError(t, err)\n\terr = json.Unmarshal(data, &testObjects)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 3, len(testObjects))\n\terr = app.Storage.Del(\"test/\" + dat.Index)\n\trequire.NoError(t, err)\n\tdata, err = app.Storage.Get(\"test/*\")\n\trequire.NoError(t, err)\n\terr = json.Unmarshal(data, &testObjects)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 2, len(testObjects))\n\tkey, err = app.Storage.Set(\"test/glob1/glob123\", testData)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"glob123\", key)\n\tkey, err = app.Storage.Set(\"test/glob2/glob456\", modData)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"glob456\", key)\n\tdata, err = app.Storage.Get(\"test/*/*\")\n\trequire.NoError(t, err)\n\terr = json.Unmarshal(data, &testObjects)\n\tapp.Console.Log(testObjects)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 2, len(testObjects))\n\tkey, err = app.Storage.Set(\"test/1/glob/g123\", testData)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"g123\", key)\n\tkey, err = app.Storage.Set(\"test/2/glob/g456\", modData)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"g456\", key)\n\tdata, err = app.Storage.Get(\"test/*/glob/*\")\n\trequire.NoError(t, err)\n\terr = json.Unmarshal(data, &testObjects)\n\tapp.Console.Log(testObjects)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 2, len(testObjects))\n\tkey, err = app.Storage.Set(\"test1\", testData)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"test1\", key)\n\tkey, err = app.Storage.Set(\"test2\", modData)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"test2\", key)\n\tdata, err = app.Storage.Get(\"*\")\n\trequire.NoError(t, err)\n\terr = json.Unmarshal(data, &testObjects)\n\tapp.Console.Log(testObjects)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 2, len(testObjects))\n\terr = app.Storage.Del(\"*\")\n\trequire.NoError(t, err)\n\tdata, err = app.Storage.Get(\"*\")\n\trequire.NoError(t, err)\n\terr = json.Unmarshal(data, &testObjects)\n\tapp.Console.Log(testObjects)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 0, len(testObjects))\n}", "func TestDeleteLoot(t *testing.T) {\n\tdbsql, err := sql.Open(\"postgres\", \"user=postgres dbname=gorm password=simsim sslmode=disable\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdb, err := InitDB(dbsql)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = db.DeleteLoot(\"RFkfurk0gmexqmgpdx9N\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func TestController(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(utils.MakeUUID())\n}", "func (a *api) setUpTestData() {\n\tInit(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr)\n\n\ta.c = nil\n\ta.resp = nil\n\ta.err = nil\n\ta.c = client.New(goaclient.HTTPClientDoer(http.DefaultClient))\n\ta.c.Host = \"localhost:8080\"\n\n\tresp, err := a.c.ShowStatus(context.Background(), \"api/login/generate\")\n\ta.resp = resp\n\ta.err = err\n\n\t/* Retrieve the authentication token needed to create/delete workitems\n\t Example of a token is:\n\t \"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJmdWxsTmFtZSI6IlRlc3QgRGV2ZWxvcGVyIiwiaW1hZ2VVUkwiOiIiLCJ1dWlkIjoiNGI4Zjk0YjUtYWQ4OS00NzI1LWI1ZTUtNDFkNmJiNzdkZjFiIn0.ML2N_P2qm-CMBliUA1Mqzn0KKAvb9oVMbyynVkcyQq3myumGeCMUI2jy56KPuwIHySv7i-aCUl4cfIjG-8NCuS4EbFSp3ja0zpsv1UDyW6tr-T7jgAGk-9ALWxcUUEhLYSnxJoEwZPQUFNTWLYGWJiIOgM86__OBQV6qhuVwjuMlikYaHIKPnetCXqLTMe05YGrbxp7xgnWMlk9tfaxgxAJF5W6WmOlGaRg01zgvoxkRV-2C6blimddiaOlK0VIsbOiLQ04t9QA8bm9raLWX4xOkXN4ubpdsobEzcJaTD7XW0pOeWPWZY2cXCQulcAxfIy6UmCXA14C07gyuRs86Rw\" */\n\n\t// Option 1 - Extarct the 1st token from the html Data in the reponse\n\tdefer a.resp.Body.Close()\n\thtmlData, err := ioutil.ReadAll(a.resp.Body)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\t//fmt.Println(\"[[[\", string(htmlData), \"]]]\")\n\tlastBin := strings.LastIndex(string(htmlData), \"\\\"},{\\\"token\\\":\\\"\")\n\tInfo.Println(\"The token to be used is:\", string(htmlData)[11:lastBin])\n\n\t// Option 2 - Extract the 1st token from JSON in the response\n\tlastBin = strings.LastIndex(string(htmlData), \",\")\n\t//Info.Println(\"The token to be used is:\", string(htmlData)[11:lastBin])\n\n\t// TODO - Extract the token from the JSON map read from the html Data in the response\n\tbyt := []byte(string(htmlData)[1:lastBin])\n\tvar keys map[string]interface{}\n\tjson.Unmarshal(byt, &keys)\n\tsavedToken = fmt.Sprint(keys[\"token\"])\n\n\ta.c.SetJWTSigner(&goaclient.APIKeySigner{\n\t\tSignQuery: false,\n\t\tKeyName: \"Authorization\",\n\t\tKeyValue: savedToken,\n\t\tFormat: \"Bearer %s\",\n\t})\n\n\tresp, err = a.c.CreateWorkitem(context.Background(), \"/api/workitems\", createPayload())\n\t//fmt.Println(\"body = \", resp.Body)\n\t//fmt.Println(\"error = \", resp.Status)\n\ta.resp = resp\n\ta.err = err\n\n\tdefer a.resp.Body.Close()\n\thtmlData, err = ioutil.ReadAll(a.resp.Body)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\t//fmt.Println(os.Stdout, string(htmlData))\n\tInfo.Println(\"The newly created workitem is:\", string(htmlData))\n\n\tidStart := strings.LastIndex(string(htmlData), \"\\\"id\\\":\\\"\")\n\ttmpString := string(htmlData)[idStart+6:]\n\tidEnd := strings.Index(tmpString, \"\\\"\")\n\tidString = tmpString[:idEnd]\n\tInfo.Println(\"The ID of the newly created workitem is:\", idString)\n}", "func TestIntegrations(t *testing.T) {\n\t// test malformed urls\n\n\tconfig.ConfigureApp(&config.AppConfig{\n\t\tEnvName: \"test\",\n\t\tDir: \"../config\",\n\t})\n\n\tstakesSrv := &mux.StakesServer{\n\t\tTable: data.InitRecordTable(&data.TableConfig{\n\t\t\tUsername: viper.GetString(\"psql.username\"),\n\t\t\tPassword: viper.GetString(\"psql.password\"),\n\t\t\tHost: viper.GetString(\"psql.host\"),\n\t\t\tDBName: viper.GetString(\"psql.dbName\"),\n\t\t}),\n\t\tRouter: http.NewServeMux(),\n\t}\n\tstakesSrv.MapRoutes()\n\n\ttests := []struct {\n\t\tScenario string\n\t\tMethod string\n\t\tURL string\n\t\t// Want... or golden file?(against golden file since I want to use the actual uuid)\n\t}{}\n\n\t// TODO:: Create test binary and place that in an image from scratch in a docker network.\n\t// It depends on the postgres test instance, which will be prepopulated programatically before this.\n\tfor _, test := range tests {\n\t\tt.Run(test.Scenario, func(t *testing.T) {\n\t\t\treq, err := http.NewRequest(test.Method, test.URL, nil)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(\"test request could not be created\")\n\t\t\t}\n\t\t\treq.Header.Set(\"Authorization\", \"JWT token\")\n\t\t\tw := httptest.NewRecorder()\n\t\t\tstakesSrv.Router.ServeHTTP(w, req)\n\t\t})\n\t}\n}", "func TestModelRouteRepository(t *testing.T) {\n\tg := NewGomegaWithT(t)\n\n\turlPrefixValue := \"/test\"\n\tnewURLPrefixValue := \"/new/test\"\n\tcreated := &deployment.ModelRoute{\n\t\tID: mrName,\n\t\tSpec: v1alpha1.ModelRouteSpec{\n\t\t\tURLPrefix: urlPrefixValue,\n\t\t\tModelDeploymentTargets: []v1alpha1.ModelDeploymentTarget{\n\t\t\t\t{\n\t\t\t\t\tName: mdID,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tg.Expect(c.CreateModelRoute(created)).NotTo(HaveOccurred())\n\n\tfetched, err := c.GetModelRoute(mrName)\n\tg.Expect(err).NotTo(HaveOccurred())\n\tg.Expect(fetched.ID).To(Equal(created.ID))\n\tg.Expect(fetched.Spec).To(Equal(created.Spec))\n\n\tupdated := &deployment.ModelRoute{\n\t\tID: mrName,\n\t\tSpec: v1alpha1.ModelRouteSpec{\n\t\t\tURLPrefix: urlPrefixValue,\n\t\t\tModelDeploymentTargets: []v1alpha1.ModelDeploymentTarget{\n\t\t\t\t{\n\t\t\t\t\tName: mdID,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tupdated.Spec.URLPrefix = newURLPrefixValue\n\tg.Expect(c.UpdateModelRoute(updated)).NotTo(HaveOccurred())\n\n\tfetched, err = c.GetModelRoute(mrName)\n\tg.Expect(err).NotTo(HaveOccurred())\n\tg.Expect(fetched.ID).To(Equal(updated.ID))\n\tg.Expect(fetched.Spec).To(Equal(updated.Spec))\n\tg.Expect(fetched.Spec.URLPrefix).To(Equal(newURLPrefixValue))\n\n\tg.Expect(c.DeleteModelRoute(mrName)).NotTo(HaveOccurred())\n\t_, err = c.GetModelRoute(mrName)\n\tg.Expect(err).To(HaveOccurred())\n}", "func runTests(t *testing.T, tests []test) {\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresp := executeRequest(tt.method, tt.url, serialize(tt.req), tt.asAdmin)\n\t\t\tif resp.StatusCode != tt.want {\n\t\t\t\tt.Errorf(\"Unexpected status code %d\", resp.StatusCode)\n\t\t\t}\n\n\t\t\tif tt.body != \"\" {\n\t\t\t\tbodyBytes, err := ioutil.ReadAll(resp.Body)\n\t\t\t\tdefer resp.Body.Close()\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Errorf(\"Error loading body\")\n\t\t\t\t}\n\t\t\t\tif tt.body != string(bodyBytes) {\n\t\t\t\t\tt.Errorf(\"Unexpected body '%s', expected '%s'\", bodyBytes, tt.body)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}", "func TestIntCreateTwoPersonsAndReadBack(t *testing.T) {\n\tlog.SetPrefix(\"TestCreatePersonAndReadBack\")\n\t// Create a dao containing a session\n\tdbsession, err := dbsession.MakeGorpMysqlDBSession()\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tdefer dbsession.Close()\n\n\tdao := MakeRepo(dbsession)\n\n\tclearDown(dao, t)\n\n\t//Create two people\n\tp1 := personModel.MakeInitialisedPerson(0, expectedForename1, expectedSurname1)\n\tperson1, err := dao.Create(p1)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tlog.Printf(\"person1 %s\", person1.String())\n\tp2 := personModel.MakeInitialisedPerson(0, expectedForename2, expectedSurname2)\n\tperson2, err := dao.Create(p2)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\t// read all the people in the DB - expect just the two we created\n\tpeople, err := dao.FindAll()\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\tif len(people) != 2 {\n\t\tt.Errorf(\"expected 2 rows, actual %d\", len(people))\n\t}\n\n\tmatches := 0\n\tfor _, person := range people {\n\t\tswitch person.Forename() {\n\t\tcase expectedForename1:\n\t\t\tif person.Surname() == expectedSurname1 {\n\t\t\t\tmatches++\n\t\t\t} else {\n\t\t\t\tt.Errorf(\"expected surname to be %s actually %s\", expectedSurname1, person.Surname())\n\t\t\t}\n\t\tcase expectedForename2:\n\t\t\tif person.Surname() == expectedSurname2 {\n\t\t\t\tmatches++\n\t\t\t} else {\n\t\t\t\tt.Errorf(\"expected forename to be %s actually %s\", expectedForename2, person.Forename())\n\t\t\t}\n\t\tdefault:\n\t\t\tt.Errorf(\"unexpected forename - %s\", person.Forename())\n\t\t}\n\t}\n\n\t// We should have just the records we created\n\tif matches != 2 {\n\t\tt.Errorf(\"expected two matches, actual %d\", matches)\n\t}\n\n\t// Find each of the records by ID and check the fields\n\tlog.Printf(\"finding person %d\", person1.ID())\n\tperson1Returned, err := dao.FindByID(person1.ID())\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tif person1Returned.Forename() != expectedForename1 {\n\t\tt.Errorf(\"expected forename to be %s actually %s\",\n\t\t\texpectedForename1, person1Returned.Forename())\n\t}\n\tif person1Returned.Surname() != expectedSurname1 {\n\t\tt.Errorf(\"expected surname to be %s actually %s\",\n\t\t\texpectedSurname1, person1Returned.Surname())\n\t}\n\n\tvar IDStr = strconv.FormatUint(person2.ID(), 10)\n\tperson2Returned, err := dao.FindByIDStr(IDStr)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\tlog.Printf(\"found person %s\", person2Returned.String())\n\n\tif person2Returned.Forename() != expectedForename2 {\n\t\tt.Errorf(\"expected forename to be %s actually %s\",\n\t\t\texpectedForename2, person2Returned.Forename())\n\t}\n\tif person2Returned.Surname() != expectedSurname2 {\n\t\tt.Errorf(\"expected surname to be %s actually %s\",\n\t\t\texpectedSurname2, person2Returned.Surname())\n\t}\n\n\tclearDown(dao, t)\n}", "func Test_Insert(t *testing.T) {\n\n\tt.Parallel()\n\tdailwslice := create_dailyweather()\n\tinserted := dailywdao.Insert(dailwslice)\n\tif inserted == false {\n\t\tt.Error(\"insert failed!!! oops!!\")\n\t}\n\n}", "func handlerTestRunner(m *testing.M) int {\n\tdbConfig, err := config.NewTestDBConfig()\n\tif err != nil {\n\t\tpanic(errors.Wrap(err, \"initialize db config failed\"))\n\t}\n\tmg, err := migrate.New(\"file://../migrations/\", config.NewDsn(dbConfig))\n\tif err != nil {\n\t\tpanic(errors.Wrap(err, \"initialize migrate instance failed\"))\n\t}\n\tif err := mg.Drop(); err != nil && err != migrate.ErrNoChange {\n\t\tpanic(errors.Wrap(err, \"drop database failed\"))\n\t}\n\t// need to be renewed to create schema_migrations\n\tmg, _ = migrate.New(\"file://../migrations/\", config.NewDsn(dbConfig))\n\tif err := mg.Up(); err != nil {\n\t\tpanic(errors.Wrap(err, \"run migrations failed\"))\n\t}\n\n\treturn m.Run()\n}", "func TestModify4(t *testing.T) {\n\n\trequest, _ := http.NewRequest(\"GET\", \"/modify/fakeowl.png?mode=2&n=df\", nil)\n\tresponse := httptest.NewRecorder()\n\tMymux.ServeHTTP(response, request)\n}", "func TestCreateOrder(t *testing.T) {\n\n // ...\n\n}", "func Test_Read(t *testing.T) {\n\tctx := context.Background()\n\tdatabase, err := db.ConnectDB(\"\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tProjectService := NewProjectServiceServer(database)\n\treq := &v1.ReadRequest{\n\t\tApi: apiVersion,\n\t\tId: 2,\n\t}\n\tres, _ := ProjectService.Read(ctx, req)\n\tfmt.Println(res)\n\tt.Log(\"Done\")\n\n}", "func (suite *SuiteTester) SetupTest() {\n r.Table(\"users\").Delete().RunWrite(session)\n user_fixtures := make([]User, 4)\n user_fixtures[0] = User{\n FirstName: \"Tyrion\",\n LastName: \"Lannister\",\n Email: \"[email protected]\",\n Bio: \"Younger brother to Cersei and Jaime.\",\n FacebookId: \"0b8a2b98-f2c5-457a-adc0-34d10a6f3b5c\",\n CreatedAt: time.Date(2008, time.June, 13, 18, 30, 10, 0, time.UTC),\n UpdatedAt: time.Date(2014, time.October, 5, 18, 30, 10, 0, time.UTC),\n }\n user_fixtures[1] = User{\n FirstName: \"Tywin\",\n LastName: \"Lannister\",\n Email: \"[email protected]\",\n Bio: \"Lord of Casterly Rock, Shield of Lannisport and Warden of the West.\",\n FacebookId: \"bb2d8a7b-92e6-4baf-b4f7-b664bdeee25b\",\n CreatedAt: time.Date(1980, time.July, 14, 18, 30, 10, 0, time.UTC),\n UpdatedAt: time.Date(2014, time.October, 6, 18, 30, 10, 0, time.UTC),\n }\n user_fixtures[2] = User{\n FirstName: \"Jaime\",\n LastName: \"Lannister\",\n Email: \"[email protected]\",\n Bio: \"Nicknamed 'Kingslayer' for killing the previous King, Aerys II.\",\n FacebookId: \"d4c19866-eaff-4417-a1c1-93882162606d\",\n CreatedAt: time.Date(2000, time.September, 15, 18, 30, 10, 0, time.UTC),\n UpdatedAt: time.Date(2014, time.October, 7, 18, 30, 10, 0, time.UTC),\n }\n user_fixtures[3] = User{\n FirstName: \"Cersei\",\n LastName: \"Lannister\",\n Email: \"[email protected]\",\n Bio: \"Queen of the Seven Kingdoms of Westeros, is the wife of King Robert Baratheon.\",\n FacebookId: \"251d74d8-7462-4f2a-b132-6f7e429507e5\",\n CreatedAt: time.Date(2002, time.May, 12, 18, 30, 10, 0, time.UTC),\n UpdatedAt: time.Date(2014, time.October, 8, 18, 30, 10, 0, time.UTC),\n }\n\n r.Table(\"users\").Insert(user_fixtures).RunWrite(session)\n}", "func TestHandler_URLMappingGetRecapSalesSuccess(t *testing.T) {\n\to := orm.NewOrm()\n\to.Raw(\"DELETE FROM recap_sales\").Exec()\n\n\t// buat dummy recap\n\tmodel.DummyRecapSales()\n\n\t// melakukan proses login\n\tuser := model.DummyUserPriviledgeWithUsergroup(1)\n\tsd, _ := auth.Login(user)\n\ttoken := \"Bearer \" + sd.Token\n\tng := tester.New()\n\tng.SetHeader(tester.H{\"Authorization\": token})\n\tng.Method = \"GET\"\n\tng.Path = \"/v1/recap-sales\"\n\tng.Run(test.Router(), func(res tester.HTTPResponse, req tester.HTTPRequest) {\n\t\tassert.Equal(t, int(200), res.Code, fmt.Sprintf(\"Should has 'endpoint %s' with method '%s'\", \"/v1/recap-sales\", \"GET\"))\n\t})\n}", "func TestOperationBasic(t *testing.T) {\n\tlogger := logrus.New()\n\tlogger.SetLevel(logrus.DebugLevel)\n\tcfg := &urlLookup.Config{\n\t\tUpdater: urlLookup.Updater{\n\t\t\tTimeInterval: 10,\n\t\t\tDirPath: \"../blacklist\",\n\t\t}}\n\n\tupdtr := NewUpdater(UseUpdaterDeps(func(d *Deps) {\n\t\td.Logger = logger\n\t\td.DbClient = &MockRedisClient{Log: logger, CommitDelay: time.Second * 2}\n\t\td.Config = cfg\n\t}))\n\n\tif err := updtr.Init(); err != nil {\n\t\tt.Errorf(\"%s\", err)\n\t}\n\n\tif err := updtr.Close(); err != nil {\n\t\tt.Errorf(\"%s\", err)\n\t}\n\n}", "func (WebApp) TestLoad() error {\n\treturn sh.RunV(\"go-wrk\", \"-i\", \"-t=8\", \"-n=10000\", site)\n}", "func (suite *HandlerTestSuite) TestDeleteRecipe() {\n\n\trecipe1 := recipeForTest()\n\tsuite.repo.Recipes[recipe1.Id] = recipe1\n\trecipe2 := recipeForTest()\n\tsuite.repo.Recipes[recipe2.Id] = recipe2\n\n\trequest := apiGatewayRequestForTest(http.MethodDelete, nil, &recipe2.Id)\n\tresponse, err := suite.handler.handle(context.Background(), request)\n\tsuite.Nil(err)\n\tsuite.assertSuccessfulResponse(response)\n\n\t_, recipe1Exists := suite.repo.Recipes[recipe1.Id]\n\tsuite.True(recipe1Exists)\n\t_, recipe2Exists := suite.repo.Recipes[recipe2.Id]\n\tsuite.False(recipe2Exists)\n\n\tnotExistingId := utils.NewId()\n\trequest2 := apiGatewayRequestForTest(http.MethodDelete, nil, &notExistingId)\n\tresponse2, err := suite.handler.handle(context.Background(), request2)\n\tsuite.NotNil(err)\n\tsuite.assertResponseStatusCode(response2, http.StatusInternalServerError)\n\n\trequest3 := apiGatewayRequestForTest(http.MethodDelete, nil, nil)\n\tresponse3, err := suite.handler.handle(context.Background(), request3)\n\tsuite.NotNil(err)\n\tsuite.assertResponseStatusCode(response3, http.StatusBadRequest)\n}", "func TestGetPartnersWorking(t *testing.T) {\n\tclearTable()\n\tinsertGame()\n\tapitest.New().\n\t\tDebug().\n\t\tHandler(newApp().Router).\n\t\tGet(\"/api/assoc_partners\").\n\t\tExpect(t).\n\t\tStatus(http.StatusOK).\n\t\tEnd()\n}", "func xTestRealBackend(t *testing.T) {\n\tins, err := bq.NewInserter(etl.SW, time.Now())\n\tvar parser etl.Parser = parser.NewDiscoParser(ins)\n\n\tmeta := map[string]bigquery.Value{\"filename\": \"filename\", \"parse_time\": time.Now()}\n\tfor i := 0; i < 3; i++ {\n\t\t// Iterations:\n\t\t// Add two rows, no upload.\n\t\t// Add two more rows, triggering an upload of 3 rows.\n\t\t// Add two more rows, triggering an upload of 3 rows.\n\t\terr = parser.ParseAndInsert(meta, \"testName\", test_data)\n\t\tif ins.Accepted() != 2 {\n\t\t\tt.Error(\"Accepted = \", ins.Accepted())\n\t\t\tt.Fail()\n\t\t}\n\t}\n\n\tif ins.Accepted() != 6 {\n\t\tt.Error(\"Accepted = \", ins.Accepted())\n\t}\n\tif ins.RowsInBuffer() != 0 {\n\t\tt.Error(\"RowsInBuffer = \", ins.RowsInBuffer())\n\t}\n\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}", "func OpenTestConnection() (db *gorm.DB, err error) {\n\tswitch os.Getenv(\"GORM_DIALECT\") {\n\tcase \"mysql\":\n\t\t// CREATE USER 'gorm'@'localhost' IDENTIFIED BY 'gorm';\n\t\t// CREATE DATABASE gorm;\n\t\t// GRANT ALL ON gorm.* TO 'gorm'@'localhost';\n\t\tfmt.Println(\"testing mysql...\")\n\t\tdbhost := os.Getenv(\"GORM_DBADDRESS\")\n\t\tif dbhost != \"\" {\n\t\t\tdbhost = fmt.Sprintf(\"tcp(%v)\", dbhost)\n\t\t}\n\t\tdb, err = gorm.Open(\"mysql\", fmt.Sprintf(\"gorm:gorm@%v/gorm?charset=utf8&parseTime=True\", dbhost))\n\tcase \"postgres\":\n\t\tfmt.Println(\"testing postgres...\")\n\t\tdbhost := os.Getenv(\"GORM_DBHOST\")\n\t\tif dbhost != \"\" {\n\t\t\tdbhost = fmt.Sprintf(\"host=%v \", dbhost)\n\t\t}\n\t\tdb, err = gorm.Open(\"postgres\", fmt.Sprintf(\"%v user=gorm password=gorm DB.name=gorm sslmode=disable\", dbhost))\n\tcase \"foundation\":\n\t\tfmt.Println(\"testing foundation...\")\n\t\tdb, err = gorm.Open(\"foundation\", \"dbname=gorm port=15432 sslmode=disable\")\n\tcase \"mssql\":\n\t\t// CREATE LOGIN gorm WITH PASSWORD = 'LoremIpsum86';\n\t\t// CREATE DATABASE gorm;\n\t\t// USE gorm;\n\t\t// CREATE USER gorm FROM LOGIN gorm;\n\t\t// sp_changedbowner 'gorm';\n\t\tfmt.Println(\"testing mssql...\")\n\t\tdb, err = gorm.Open(\"mssql\", \"sqlserver://gorm:LoremIpsum86@localhost:1433?database=gorm\")\n\tdefault:\n\t\tfmt.Println(\"testing sqlite3...\")\n\t\tdb, err = gorm.Open(\"sqlite3\", filepath.Join(os.TempDir(), \"gorm.db\"))\n\t}\n\n\t// db.SetLogger(Logger{log.New(os.Stdout, \"\\r\\n\", 0)})\n\t// db.SetLogger(log.New(os.Stdout, \"\\r\\n\", 0))\n\tif os.Getenv(\"DEBUG\") == \"true\" {\n\t\tdb.LogMode(true)\n\t}\n\n\tif err == nil {\n\t\tdb.DB().SetMaxIdleConns(10)\n\t}\n\n\treturn\n}", "func TestGetTodoByID(t *testing.T) {\n\t_client := setupDatabase(t)\n\t_handler := setupTodoHandler(_client)\n\tdefer _client.Close()\n\n\tapp := fiber.New()\n\n\tapp.Get(\"/todos/:id\", _handler.GetTodoByID)\n\n\tr := httptest.NewRequest(\"GET\", \"/todos/\"+sampleID.String(), nil)\n\n\tresp, err := app.Test(r)\n\tif err != nil {\n\t\tassert.Fail(t, err.Error())\n\t}\n\n\tassert.Equal(t, fiber.StatusOK, resp.StatusCode)\n\n\tvar data entity.Todo\n\tif err := json.NewDecoder(resp.Body).Decode(&data); err != nil {\n\t\tassert.Fail(t, err.Error())\n\t}\n\tassert.Equal(t, sampleID, data.ID)\n\tassert.Equal(t, \"Sample todo data for unit test.\", data.Content)\n\tassert.Equal(t, true, data.Completed)\n\n\tfmt.Println(\"Todo:\", data.String())\n\tfmt.Println(\"Status Code:\", resp.StatusCode)\n}", "func (t *Test) Run(tc *TestSuite) error {\n\n\tmqutil.Logger.Print(\"\\n--- \" + t.Name)\n\tfmt.Printf(\"\\nRunning test case: %s\\n\", t.Name)\n\terr := t.ResolveParameters(tc)\n\tif err != nil {\n\t\tfmt.Printf(\"... Fail\\n... %s\\n\", err.Error())\n\t\treturn err\n\t}\n\n\treq := resty.R()\n\tif len(tc.ApiToken) > 0 {\n\t\treq.SetAuthToken(tc.ApiToken)\n\t} else if len(tc.Username) > 0 {\n\t\treq.SetBasicAuth(tc.Username, tc.Password)\n\t}\n\n\tpath := GetBaseURL(t.db.Swagger) + t.SetRequestParameters(req)\n\tvar resp *resty.Response\n\n\tt.startTime = time.Now()\n\tswitch t.Method {\n\tcase mqswag.MethodGet:\n\t\tresp, err = req.Get(path)\n\tcase mqswag.MethodPost:\n\t\tresp, err = req.Post(path)\n\tcase mqswag.MethodPut:\n\t\tresp, err = req.Put(path)\n\tcase mqswag.MethodDelete:\n\t\tresp, err = req.Delete(path)\n\tcase mqswag.MethodPatch:\n\t\tresp, err = req.Patch(path)\n\tcase mqswag.MethodHead:\n\t\tresp, err = req.Head(path)\n\tcase mqswag.MethodOptions:\n\t\tresp, err = req.Options(path)\n\tdefault:\n\t\treturn mqutil.NewError(mqutil.ErrInvalid, fmt.Sprintf(\"Unknown method in test %s: %v\", t.Name, t.Method))\n\t}\n\tt.stopTime = time.Now()\n\tfmt.Printf(\"... call completed: %f seconds\\n\", t.stopTime.Sub(t.startTime).Seconds())\n\n\tif err != nil {\n\t\tt.err = mqutil.NewError(mqutil.ErrHttp, err.Error())\n\t} else {\n\t\tmqutil.Logger.Print(resp.Status())\n\t\tmqutil.Logger.Println(string(resp.Body()))\n\t}\n\terr = t.ProcessResult(resp)\n\treturn err\n}", "func mockInsertFile() error {\n\n\tconnString := mysql.ConstructConnString(dbUserName, dbPassword, dbName)\n\n\tseqDatabase := mysql.ConnectDatabase(connString)\n\n\t//seq Repository\n\tseq := mysql.NewSeq(seqDatabase)\n\n\t//Generate ID for New File\n\tfileID, err := seq.Find(\"FILENAME\")\n\tif err != nil {\n\t\treturn errors.New(\"Error on IDGenerator for Filename \" + err.Error())\n\t}\n\n\tfmt.Println(\"New FILE ID: \", fileID)\n\n\tvar timeStart = time.Now().Format(dateOnly)\n\tvar timeAfter = time.Now().Add(150 * time.Hour).Format(dateOnly)\n\tvar fgName = strconv.Itoa(fileID) + fileExt\n\tvar destPath = storageFolder + fgName\n\n\tnodeID, err := seq.Find(\"NODE\") //Generate a new ID for Node\n\tif err != nil {\n\t\treturn errors.New(\"Error on IDGenerator for Node \" + err.Error())\n\t}\n\n\tfmt.Println(\"New Node ID: \", nodeID)\n\n\t//create a test file\n\t_, err = CreateFile(fileName, fileSize)\n\tif err != nil {\n\t\treturn errors.New(\"Error on Create File \" + err.Error())\n\t}\n\n\t//populate the struct with data\n\tnewNode, err := CreateNewNode(nodeID, fileName, timeStart, graphID, fileType, userID)\n\tif err != nil {\n\t\treturn errors.New(\"Error on populating Node struct \" + err.Error())\n\t}\n\tnewFmedia, err := CreateNewFm(nodeID, fileName, fileExt, storageFolder, fgName, fileName, fileRemarks, fileSize, 1, 1)\n\tif err != nil {\n\t\treturn errors.New(\"Error on populating Fmedia struct\" + err.Error())\n\t}\n\tnewNL, err := CreateNewNL(parentID, nodeID, linkType)\n\tif err != nil {\n\t\treturn errors.New(\"Error on populating Nodelink struct\" + err.Error())\n\t}\n\tnewFv, err := CreateNewFv(nodeID, timeAfter, fileRemarks, timeStart, \"1\", verState)\n\tif err != nil {\n\t\treturn errors.New(\"Error on populating Fversion struct\" + err.Error())\n\t}\n\tnewConv, err := CreateNewConv(nodeID, fileExt, destPath)\n\tif err != nil {\n\t\treturn errors.New(\"Error on populating Convqueue struct\" + err.Error())\n\t}\n\t//Copy the file to destination\n\terr = CopyFile(fileName, destPath)\n\tif err != nil {\n\t\treturn errors.New(\"Error on Copy File \" + err.Error())\n\t}\n\n\t//Prepare statement for insert\n\tstmt := new(PreparedStmt)\n\terr = stmt.PrepareStatement(seqDatabase)\n\tif err != nil {\n\t\treturn errors.New(\"Error on Prepare Statment \" + err.Error())\n\t}\n\n\t//Insert data into database\n\terr = CommitIntoDatabase(seqDatabase, *stmt, newNode, newFmedia, newNL, newFv, newConv)\n\tif err != nil {\n\t\treturn errors.New(\"Error on CommitIntoDatabase \" + err.Error())\n\t}\n\n\t//now update the seq table's value after the file has been successfully inserted\n\terr = seq.Update(\"FILE\", fileID)\n\tif err != nil {\n\t\treturn errors.New(\"Error on Update File Value \" + err.Error())\n\t}\n\terr = seq.Update(\"NODE\", nodeID)\n\tif err != nil {\n\t\treturn errors.New(\"Error on Update Node Value \" + err.Error())\n\t}\n\n\tseqDatabase.Close()\n\n\treturn nil\n}", "func (suite *ControllersTestSuite) SetupTest() {\n\titer := suite.DB.Conn.NewIterator(nil, nil)\n\tfor iter.Next() {\n\t\tkey := iter.Key()\n\t\tsuite.DB.Conn.Delete(key, nil)\n\t}\n}", "func TestCreateUserAndLogin(t *testing.T) {\n\tgo createServer()\n\tcreateUser()\n\tlog.Println(\"*********************************************\")\n\tloginClient()\n}", "func (programRepo *mockProgramRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func setupSingleTableDatabase(f *testhelpers.TestFerry, sourceDB, targetDB *sql.DB) {\n\tmaxId := 20\n\ttesthelpers.SeedInitialData(sourceDB, \"gftest\", \"table1\", maxId)\n\n\tfor i := 0; i < 4; i++ {\n\t\tquery := \"DELETE FROM gftest.table1 WHERE id = ?\"\n\t\t_, err := sourceDB.Exec(query, rand.Intn(maxId-1)+1)\n\t\ttesthelpers.PanicIfError(err)\n\t}\n\n\ttesthelpers.SeedInitialData(targetDB, \"gftest\", \"table1\", 0)\n}", "func TestUpdateTodoByID(t *testing.T) {\n\t_client := setupDatabase(t)\n\t_handler := setupTodoHandler(_client)\n\tdefer _client.Close()\n\n\tapp := fiber.New()\n\n\tapp.Put(\"/todos/:id\", _handler.UpdateTodoByID)\n\n\tbody := []byte(`{\"content\":\"Updated content\"}`)\n\tr := httptest.NewRequest(\"PUT\", \"/todos/\"+sampleID.String(), bytes.NewReader(body))\n\tr.Header.Set(\"Content-Type\", \"application/json\")\n\n\tresp, err := app.Test(r)\n\tif err != nil {\n\t\tassert.Fail(t, err.Error())\n\t}\n\n\tassert.Equal(t, fiber.StatusOK, resp.StatusCode)\n\n\tvar data entity.Todo\n\tif err := json.NewDecoder(resp.Body).Decode(&data); err != nil {\n\t\tassert.Fail(t, err.Error())\n\t}\n\tassert.Equal(t, \"Updated content\", data.Content)\n\n\tfmt.Println(\"Updated content:\", data.Content)\n\tfmt.Println(\"Status Code:\", resp.StatusCode)\n}", "func TestServiceUpdateToJSON_TwoConfig_UpdateActions(t *testing.T) {\n}", "func (transactionRepo *mockTransactionRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func TestDatabase(t *testing.T) {\n\tt.Log(\"Testing database connection...\")\n\tinitDb()\n\n\tt.Log(\"Testing database insertion...\")\n\n\tcollection := db.C(\"testUsers\")\n\n\ttestUsers := []interface{}{\n\t\t&User{\n\t\t\tId: bson.NewObjectId(),\n\t\t\tCreatedAt: bson.Now(),\n\t\t\tUsername: \"Bobble\",\n\t\t\tPassword: \"Suepass\",\n\t\t\tFullname: \"Bob Sue\",\n\t\t\tStories: []string{},\n\t\t},\n\t\t&User{\n\t\t\tId: bson.NewObjectId(),\n\t\t\tCreatedAt: bson.Now(),\n\t\t\tUsername: \"AliceRex\",\n\t\t\tPassword: \"Suepassaroo\",\n\t\t\tFullname: \"Alice Dino\",\n\t\t\tStories: []string{},\n\t\t},\n\t}\n\terr := collection.Insert(testUsers...)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to insert test users into the database\\n%v\\n\", err)\n\t}\n\n\tt.Log(\"Testing database retrieval...\")\n\n\tresult := []User{}\n\terr = collection.Find(bson.M{\"username\": \"AliceRex\"}).All(&result)\n\tif err != nil || len(result) == 0 {\n\t\tt.Errorf(\"Failed to find test user in the database\\n%v\\n\", err)\n\t}\n\n\terr = collection.Find(nil).All(&result)\n\tif err != nil || len(result) == 0 {\n\t\tt.Errorf(\"Failed to find test users in the database\\n%v\\n\", err)\n\t}\n\n\tinfo, err := collection.RemoveAll(nil)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to remove test users from the database\\n%v\\n\", err)\n\t}\n\n\tif info.Removed < 2 {\n\t\tt.Error(\"Failed to either add or remove test users from the database\")\n\t}\n}", "func TestSimpleSingle(t *testing.T) {\n\tc := client.MustNewClient()\n\tkubecli := mustNewKubeClient(t)\n\tns := getNamespace(t)\n\n\t// Prepare deployment config\n\tdepl := newDeployment(\"test-sng-\" + uniuri.NewLen(4))\n\tdepl.Spec.Mode = api.NewMode(api.DeploymentModeSingle)\n\n\t// Create deployment\n\t_, err := c.DatabaseV1().ArangoDeployments(ns).Create(depl)\n\tif err != nil {\n\t\tt.Fatalf(\"Create deployment failed: %v\", err)\n\t}\n\t// Prepare cleanup\n\tdefer removeDeployment(c, depl.GetName(), ns)\n\n\t// Wait for deployment to be ready\n\tapiObject, err := waitUntilDeployment(c, depl.GetName(), ns, deploymentIsReady())\n\tif err != nil {\n\t\tt.Fatalf(\"Deployment not running in time: %v\", err)\n\t}\n\n\t// Create a database client\n\tctx := context.Background()\n\tclient := mustNewArangodDatabaseClient(ctx, kubecli, apiObject, t, nil)\n\n\t// Wait for single server available\n\tif err := waitUntilVersionUp(client, nil); err != nil {\n\t\tt.Fatalf(\"Single server not running returning version in time: %v\", err)\n\t}\n\n\t// Check server role\n\tassert.NoError(t, testServerRole(ctx, client, driver.ServerRoleSingle))\n}", "func populateTestDatabaseTasks(t *testing.T, db *store.Database) {\n\ttaskBiology := model.Task{Name: \"biology\", ProjectID: uint(2)}\n\terr := db.PostTask(taskBiology)\n\n\tif err != nil {\n\t\tt.Fatalf(\"Error populating test database with tasks: %v\", err)\n\t\treturn\n\t}\n\n\ttaskPhysics := model.Task{Name: \"physics\", ProjectID: uint(2)}\n\terr = db.PostTask(taskPhysics)\n\n\tif err != nil {\n\t\tt.Fatalf(\"Error populating test database with tasks: %v\", err)\n\t}\n}", "func Loadtest(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"In loadtest handler....\")\n\tvars := mux.Vars(r)\n\titerationsStr := vars[\"iterations\"]\n\titerations, err := strconv.ParseInt(iterationsStr, 10, 64)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\t//TODO: Attempt doing primitive / basic integer multiplication!!!\n\n\tfactValue := new(big.Int)\n\tfactValue.SetInt64(1)\n\tstart := time.Now()\n\tfor i := int64(0); i < iterations; i++ {\n\t\tfactValue.Mul(factValue, big.NewInt(i))\n\n\t}\n\n\tend := time.Now()\n\telapsed := end.Sub(start)\n\tlog.Println(\"Loadtest took \", elapsed, \" to perform \", iterations)\n\tfmt.Fprintln(w, \"Loadtest took \", elapsed, \" to perform \", iterations)\n\n}", "func TestDeleteTaskAPI(t *testing.T) {\n\n\ttask, err := NewTask(\"test delete task api\")\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error : %v\", err)\n\t}\n\tif err := task.Save(); err != nil {\n\t\tt.Fatalf(\"unexpected error : %v\", err)\n\t}\n\n\tm := mux.NewRouter()\n\tm.HandleFunc(\"/task/{sid}\", DeleteTaskAPI)\n\n\trr := httptest.NewRecorder()\n\treq, _ := http.NewRequest(http.MethodGet, \"/task/\"+task.SID, strings.NewReader(\"\"))\n\n\tm.ServeHTTP(rr, req)\n\n\t// Test status code.\n\tif rr.Code != http.StatusNoContent {\n\t\tt.Errorf(\"Code : %v, Error : %v\", rr.Code, rr.Body.String())\n\t}\n}", "func TestSmokeTfSingleRecordReader(t *testing.T) {\n\tconst path = \"data/tf-train-single.record\"\n\n\tf, err := os.Open(path)\n\ttassert.CheckFatal(t, err)\n\tdefer f.Close()\n\n\treadTfExamples, err := readExamples(f)\n\ttassert.CheckError(t, err)\n\n\tif len(readTfExamples) != 1 {\n\t\tt.Errorf(\"expected to read one tf.Examples, got %d\", len(readTfExamples))\n\t}\n}", "func TestTest_Sample(t *testing.T) {\n\tt.Parallel()\n\n\t// get DynamoDB client and do something\n\tsvc, err := test.GetClient()\n\trequire.Nil(t, err)\n\trequest := svc.GetItemRequest(&dynamodb.GetItemInput{\n\t\tKey: map[string]dynamodb.AttributeValue{\n\t\t\t\"PK\": {S: aws.String(\"abc123\")},\n\t\t},\n\t\tTableName: aws.String(table),\n\t})\n\tresponse, err := request.Send(context.Background())\n\trequire.Nil(t, err)\n\tassert.Equal(t, \"abc123\", *(response.Item[\"PK\"].S))\n\tassert.Equal(t, \"John\", *(response.Item[\"name\"].S))\n}" ]
[ "0.5576088", "0.55627745", "0.55369925", "0.55351794", "0.5529553", "0.5417228", "0.53943944", "0.53907675", "0.5383706", "0.5376304", "0.5351497", "0.5331802", "0.5329244", "0.530411", "0.5297993", "0.52658594", "0.5262189", "0.5261754", "0.52447003", "0.52349526", "0.52309126", "0.5224325", "0.5223106", "0.5216944", "0.5216944", "0.5216944", "0.5210408", "0.51749337", "0.51697", "0.5158666", "0.51442546", "0.5138586", "0.5129626", "0.51139295", "0.5101977", "0.51017374", "0.50960845", "0.50834584", "0.50672805", "0.5065156", "0.5061039", "0.5057928", "0.50574505", "0.505644", "0.50452244", "0.50375634", "0.50367916", "0.5025915", "0.502268", "0.501351", "0.5012825", "0.50109273", "0.5009267", "0.50002086", "0.4997106", "0.49899256", "0.49774584", "0.49730095", "0.49709624", "0.49706995", "0.49609336", "0.4959979", "0.49595392", "0.49591625", "0.49560952", "0.49527556", "0.49479458", "0.4945385", "0.49453595", "0.4942368", "0.4941839", "0.49358794", "0.49248135", "0.4915954", "0.4907536", "0.490449", "0.48991102", "0.4897414", "0.48959252", "0.488468", "0.488415", "0.48818153", "0.48796698", "0.4879164", "0.48770255", "0.4871306", "0.48701185", "0.48636973", "0.4862421", "0.48606858", "0.48580673", "0.4857295", "0.48405647", "0.48356014", "0.48328507", "0.48262984", "0.4822173", "0.48191506", "0.48164037", "0.48045787" ]
0.5023307
48
SupportSelectors registers a label selector flag in flagSet, storing the value provided in p. It will replace the flag lookup for "selector" and the shorthand lookup for "l".
func SupportSelectors(flagSet *pflag.FlagSet, p *[]string) { flagSet.StringArrayVarP(p, "selector", "l", []string{}, "filter results by a set of comma-separated label selectors") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func WithSelector(s metav1.LabelSelector) Option {\n\treturn func(r *Reconciler) error {\n\t\tp, err := ctrlpredicate.LabelSelectorPredicate(s)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tr.selectorPredicate = p\n\t\treturn nil\n\t}\n}", "func getLabelSelectors() string {\n\treturn \"!ephemeral-enforcer\"\n}", "func extendSelector(selector labels.Selector, requirements ...func() (*labels.Requirement, error)) (labels.Selector, error) {\n\tif selector == nil {\n\t\tselector = labels.Everything()\n\t}\n\n\tfor _, fn := range requirements {\n\t\tr, err := fn()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tselector = selector.Add(*r)\n\t}\n\n\treturn selector, nil\n}", "func (l *labelInfo) genSelector() clusterservice.Selector {\n\treturn clusterservice.NewSelector().SelectByLabel(\n\t\tl.allLabels(), clusterservice.EQ,\n\t)\n}", "func getLabelSelectorListOpts(m *v1alpha1.PerconaServerMongoDB, replset *v1alpha1.ReplsetSpec) *metav1.ListOptions {\n\tlabelSelector := labels.SelectorFromSet(labelsForPerconaServerMongoDB(m, replset)).String()\n\treturn &metav1.ListOptions{LabelSelector: labelSelector}\n}", "func DaemonSetNodeSelectorLabels(operation *operatorv1.Operation) (map[string]string, error) {\n\tif operation.Spec.RenewCertificates != nil {\n\t\treturn setupRenewCertificates(), nil\n\t}\n\n\tif operation.Spec.Upgrade != nil {\n\t\treturn setupUpgrade(), nil\n\t}\n\n\tif operation.Spec.CustomOperation != nil {\n\t\treturn setupCustom(), nil\n\t}\n\n\treturn nil, errors.New(\"Invalid Operation.Spec.OperatorDescriptor. There are no operation implementation matching this spec\")\n}", "func (t *OpenconfigSystem_System_Logging_RemoteServers_RemoteServer_Selectors) NewSelector(Facility E_OpenconfigSystemLogging_SYSLOG_FACILITY, Severity E_OpenconfigSystemLogging_SyslogSeverity) (*OpenconfigSystem_System_Logging_RemoteServers_RemoteServer_Selectors_Selector, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Selector == nil {\n\t\tt.Selector = make(map[OpenconfigSystem_System_Logging_RemoteServers_RemoteServer_Selectors_Selector_Key]*OpenconfigSystem_System_Logging_RemoteServers_RemoteServer_Selectors_Selector)\n\t}\n\n\tkey := OpenconfigSystem_System_Logging_RemoteServers_RemoteServer_Selectors_Selector_Key{\n\t\tFacility: Facility,\n\t\tSeverity: Severity,\n\t}\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Selector[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Selector\", key)\n\t}\n\n\tt.Selector[key] = &OpenconfigSystem_System_Logging_RemoteServers_RemoteServer_Selectors_Selector{\n\t\tFacility: Facility,\n\t\tSeverity: Severity,\n\t}\n\n\treturn t.Selector[key], nil\n}", "func createSelector(values map[string]string) labels.Selector {\n\tselector := labels.NewSelector()\n\tfor k, v := range values {\n\t\treq, err := labels.NewRequirement(k, \"=\", []string{v})\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tselector = selector.Add(*req)\n\t}\n\n\treturn selector\n}", "func LabelMapFromNodeSelectorString(selector string) (map[string]set.Set, error) {\n\tlabelsMap := make(map[string]set.Set)\n\n\tif len(selector) == 0 {\n\t\treturn labelsMap, nil\n\t}\n\n\tlabels := strings.Split(selector, \",\")\n\tfor _, label := range labels {\n\t\tl := strings.Split(label, \"=\")\n\t\tif len(l) != 2 {\n\t\t\treturn labelsMap, fmt.Errorf(\"invalid selector: %v\", l)\n\t\t}\n\t\tkey := strings.TrimSpace(l[0])\n\t\tvalue := strings.TrimSpace(l[1])\n\t\tif _, exist := labelsMap[key]; !exist {\n\t\t\tlabelsMap[key] = set.NewSet()\n\t\t}\n\t\tlabelsMap[key].Add(value)\n\t}\n\treturn labelsMap, nil\n}", "func (t *OpenconfigOfficeAp_System_Logging_RemoteServers_RemoteServer_Selectors) NewSelector(Facility E_OpenconfigSystemLogging_SYSLOG_FACILITY, Severity E_OpenconfigSystemLogging_SyslogSeverity) (*OpenconfigOfficeAp_System_Logging_RemoteServers_RemoteServer_Selectors_Selector, error) {\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Selector == nil {\n\t\tt.Selector = make(map[OpenconfigOfficeAp_System_Logging_RemoteServers_RemoteServer_Selectors_Selector_Key]*OpenconfigOfficeAp_System_Logging_RemoteServers_RemoteServer_Selectors_Selector)\n\t}\n\n\tkey := OpenconfigOfficeAp_System_Logging_RemoteServers_RemoteServer_Selectors_Selector_Key{\n\t\tFacility: Facility,\n\t\tSeverity: Severity,\n\t}\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Selector[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Selector\", key)\n\t}\n\n\tt.Selector[key] = &OpenconfigOfficeAp_System_Logging_RemoteServers_RemoteServer_Selectors_Selector{\n\t\tFacility: Facility,\n\t\tSeverity: Severity,\n\t}\n\n\treturn t.Selector[key], nil\n}", "func (pr *PolicyReflector) labelSelectorToProto(selector *clientapi_metav1.LabelSelector) *proto.Policy_LabelSelector {\n\tselectorProto := &proto.Policy_LabelSelector{}\n\t// MatchLabels\n\tif selector.MatchLabels != nil {\n\t\tfor key, val := range selector.MatchLabels {\n\t\t\tselectorProto.MatchLabel = append(selectorProto.MatchLabel, &proto.Policy_Label{Key: key, Value: val})\n\t\t}\n\t}\n\t// MatchExpressions\n\tif selector.MatchExpressions != nil {\n\t\tfor _, expression := range selector.MatchExpressions {\n\t\t\texpressionProto := &proto.Policy_LabelSelector_LabelExpression{}\n\t\t\t// Key\n\t\t\texpressionProto.Key = expression.Key\n\t\t\t// Operator\n\t\t\tswitch expression.Operator {\n\t\t\tcase clientapi_metav1.LabelSelectorOpIn:\n\t\t\t\texpressionProto.Operator = proto.Policy_LabelSelector_LabelExpression_IN\n\t\t\tcase clientapi_metav1.LabelSelectorOpNotIn:\n\t\t\t\texpressionProto.Operator = proto.Policy_LabelSelector_LabelExpression_NOT_IN\n\t\t\tcase clientapi_metav1.LabelSelectorOpExists:\n\t\t\t\texpressionProto.Operator = proto.Policy_LabelSelector_LabelExpression_EXISTS\n\t\t\tcase clientapi_metav1.LabelSelectorOpDoesNotExist:\n\t\t\t\texpressionProto.Operator = proto.Policy_LabelSelector_LabelExpression_DOES_NOT_EXIST\n\n\t\t\t}\n\t\t\t// Values\n\t\t\tif expression.Values != nil {\n\t\t\t\tfor _, val := range expression.Values {\n\t\t\t\t\texpressionProto.Value = append(expressionProto.Value, val)\n\t\t\t\t}\n\t\t\t}\n\t\t\t// append expression\n\t\t\tselectorProto.MatchExpression = append(selectorProto.MatchExpression, expressionProto)\n\t\t}\n\t}\n\treturn selectorProto\n}", "func GetSelector() *Selector {}", "func LabelSelectorAsSelector(ps *model.LabelSelector) (labels.Selector, error) {\n\tif ps == nil {\n\t\treturn labels.Nothing(), nil\n\t}\n\tif len(ps.MatchLabels)+len(ps.MatchExpressions) == 0 {\n\t\treturn labels.Everything(), nil\n\t}\n\tselector := labels.NewSelector()\n\tfor k, v := range ps.MatchLabels {\n\t\tr, err := labels.NewRequirement(k, labels.Equals, []string{v})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tselector = selector.Add(*r)\n\t}\n\tfor _, expr := range ps.MatchExpressions {\n\t\tvar op labels.Operator\n\t\tswitch expr.Operator {\n\t\tcase model.LabelSelectorOpIn:\n\t\t\top = labels.In\n\t\tcase model.LabelSelectorOpNotIn:\n\t\t\top = labels.NotIn\n\t\tcase model.LabelSelectorOpExists:\n\t\t\top = labels.Exists\n\t\tcase model.LabelSelectorOpDoesNotExist:\n\t\t\top = labels.DoesNotExist\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"%q is not a valid pod selector operator\", expr.Operator)\n\t\t}\n\t\tr, err := labels.NewRequirement(expr.Key, op, append([]string(nil), expr.Values...))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tselector = selector.Add(*r)\n\t}\n\treturn selector, nil\n}", "func makeSelector(revision *v1alpha1.Revision) *metav1.LabelSelector {\n\treturn &metav1.LabelSelector{MatchLabels: makeLabels(revision)}\n}", "func DefaultSelector(\n\tpod *v1.Pod,\n\tsl corelisters.ServiceLister,\n\tcl corelisters.ReplicationControllerLister,\n\trsl appslisters.ReplicaSetLister,\n\tssl appslisters.StatefulSetLister,\n) labels.Selector {\n\tlabelSet := make(labels.Set)\n\t// Since services, RCs, RSs and SSs match the pod, they won't have conflicting\n\t// labels. Merging is safe.\n\n\tif services, err := GetPodServices(sl, pod); err == nil {\n\t\tfor _, service := range services {\n\t\t\tlabelSet = labels.Merge(labelSet, service.Spec.Selector)\n\t\t}\n\t}\n\tselector := labelSet.AsSelector()\n\n\towner := metav1.GetControllerOfNoCopy(pod)\n\tif owner == nil {\n\t\treturn selector\n\t}\n\n\tgv, err := schema.ParseGroupVersion(owner.APIVersion)\n\tif err != nil {\n\t\treturn selector\n\t}\n\n\tgvk := gv.WithKind(owner.Kind)\n\tswitch gvk {\n\tcase rcKind:\n\t\tif rc, err := cl.ReplicationControllers(pod.Namespace).Get(owner.Name); err == nil {\n\t\t\tlabelSet = labels.Merge(labelSet, rc.Spec.Selector)\n\t\t\tselector = labelSet.AsSelector()\n\t\t}\n\tcase rsKind:\n\t\tif rs, err := rsl.ReplicaSets(pod.Namespace).Get(owner.Name); err == nil {\n\t\t\tif other, err := metav1.LabelSelectorAsSelector(rs.Spec.Selector); err == nil {\n\t\t\t\tif r, ok := other.Requirements(); ok {\n\t\t\t\t\tselector = selector.Add(r...)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase ssKind:\n\t\tif ss, err := ssl.StatefulSets(pod.Namespace).Get(owner.Name); err == nil {\n\t\t\tif other, err := metav1.LabelSelectorAsSelector(ss.Spec.Selector); err == nil {\n\t\t\t\tif r, ok := other.Requirements(); ok {\n\t\t\t\t\tselector = selector.Add(r...)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tdefault:\n\t\t// Not owned by a supported controller.\n\t}\n\n\treturn selector\n}", "func getSelectorLabels(component string) map[string]string {\n\tlabels := map[string]string{}\n\tswitch component {\n\tcase \"imc-controller\":\n\t\tlabels[\"messaging.knative.dev/channel\"] = \"in-memory-channel\"\n\t\tlabels[\"messaging.knative.dev/role\"] = \"controller\"\n\tcase \"imc-dispatcher\":\n\t\tlabels[\"messaging.knative.dev/channel\"] = \"in-memory-channel\"\n\t\tlabels[\"messaging.knative.dev/role\"] = \"dispatcher\"\n\tcase \"mt-broker-filter\":\n\t\tlabels[\"eventing.knative.dev/brokerRole\"] = \"filter\"\n\tcase \"mt-broker-ingress\":\n\t\tlabels[\"eventing.knative.dev/brokerRole\"] = \"ingress\"\n\tcase \"kafka-controller-manager\":\n\t\tlabels[\"control-plane\"] = \"kafka-controller-manager\"\n\tdefault:\n\t\tlabels[\"app\"] = component\n\t}\n\treturn labels\n}", "func NewSelector() Selector {\n\treturn internalSelector(nil)\n}", "func newSelector() map[string]string {\n\treturn map[string]string{selectorKey: string(uuid.NewUUID())}\n}", "func (c *OneClient) SetSelector(servicePath string, s Selector) {\n\tc.mu.Lock()\n\tc.selectors[servicePath] = s\n\tif xclient, ok := c.xclients[servicePath]; ok {\n\t\txclient.SetSelector(s)\n\t}\n\tc.mu.Unlock()\n}", "func (t *OpenconfigSystem_System_Logging_Console_Selectors) NewSelector(Facility E_OpenconfigSystemLogging_SYSLOG_FACILITY, Severity E_OpenconfigSystemLogging_SyslogSeverity) (*OpenconfigSystem_System_Logging_Console_Selectors_Selector, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Selector == nil {\n\t\tt.Selector = make(map[OpenconfigSystem_System_Logging_Console_Selectors_Selector_Key]*OpenconfigSystem_System_Logging_Console_Selectors_Selector)\n\t}\n\n\tkey := OpenconfigSystem_System_Logging_Console_Selectors_Selector_Key{\n\t\tFacility: Facility,\n\t\tSeverity: Severity,\n\t}\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Selector[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Selector\", key)\n\t}\n\n\tt.Selector[key] = &OpenconfigSystem_System_Logging_Console_Selectors_Selector{\n\t\tFacility: Facility,\n\t\tSeverity: Severity,\n\t}\n\n\treturn t.Selector[key], nil\n}", "func New(opts ...Option) selector.Selector {\n\treturn NewBuilder(opts...).Build()\n}", "func MakeSelector(in map[string]string) labels.Selector {\n\tset := make(labels.Set)\n\tfor key, val := range in {\n\t\tset[key] = val\n\t}\n\treturn set.AsSelector()\n}", "func getNodesWithSelector(f *framework.Framework, labelselector map[string]string) []corev1.Node {\n\tvar nodes corev1.NodeList\n\tlo := &client.ListOptions{\n\t\tLabelSelector: labels.SelectorFromSet(labelselector),\n\t}\n\tf.Client.List(goctx.TODO(), &nodes, lo)\n\treturn nodes.Items\n}", "func (f *Filter) SetSelector(s ...string) *Filter {\n\tf.selector = s\n\tf.selectorHash = buildSelectorHash(s)\n\treturn f\n}", "func addNodeSel(clientset *kubernetes.Clientset, name string, labelkey string, labelvalue string) {\n // Getting deployments\n deploymentsClient := clientset.AppsV1beta1().Deployments(apiv1.NamespaceDefault)\n\n // Updating deployment\n retryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error {\n // Retrieve the latest version of Deployment before attempting update\n // RetryOnConflict uses exponential backoff to avoid exhausting the apiserver\n result, getErr := deploymentsClient.Get(name, metav1.GetOptions{})\n if getErr != nil {\n panic(fmt.Errorf(\"Failed to get latest version of Deployment: %v\", getErr))\n }\n\n fmt.Printf(\"Updating nodeSelector of deployment %v\\n\", name)\n\n // Modifying nodeSelectors\n if result.Spec.Template.Spec.NodeSelector == nil {\n result.Spec.Template.Spec.NodeSelector = make(map[string]string)\n }\n result.Spec.Template.Spec.NodeSelector[labelkey] = labelvalue\n\n _, updateErr := deploymentsClient.Update(result)\n return updateErr\n })\n if retryErr != nil {\n panic(fmt.Errorf(\"Update failed: %v\", retryErr))\n }\n fmt.Printf(\"Updated labels of deployment %v\\n\", name)\n}", "func TransformLabelsToSelector(labels map[string]string) string {\n\tlabelList := make([]string, 0)\n\tfor key, value := range labels {\n\t\tlabelList = append(labelList, fmt.Sprintf(\"%s=%s\", key, value))\n\t}\n\treturn strings.Join(labelList, \",\")\n}", "func (p *parser) parsePseudoclassSelector() (Selector, error) {\n\tif p.i >= len(p.s) {\n\t\treturn nil, fmt.Errorf(\"expected pseudoclass selector (:pseudoclass), found EOF instead\")\n\t}\n\tif p.s[p.i] != ':' {\n\t\treturn nil, fmt.Errorf(\"expected attribute selector (:pseudoclass), found '%c' instead\", p.s[p.i])\n\t}\n\n\tp.i++\n\tname, err := p.parseIdentifier()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname = toLowerASCII(name)\n\n\tswitch name {\n\tcase \"not\", \"has\", \"haschild\":\n\t\tif !p.consumeParenthesis() {\n\t\t\treturn nil, errExpectedParenthesis\n\t\t}\n\t\tsel, parseErr := p.parseSelectorGroup()\n\t\tif parseErr != nil {\n\t\t\treturn nil, parseErr\n\t\t}\n\t\tif !p.consumeClosingParenthesis() {\n\t\t\treturn nil, errExpectedClosingParenthesis\n\t\t}\n\n\t\tswitch name {\n\t\tcase \"not\":\n\t\t\treturn negatedSelector(sel), nil\n\t\tcase \"has\":\n\t\t\treturn hasDescendantSelector(sel), nil\n\t\tcase \"haschild\":\n\t\t\treturn hasChildSelector(sel), nil\n\t\t}\n\n\tcase \"contains\", \"containsown\":\n\t\tif !p.consumeParenthesis() {\n\t\t\treturn nil, errExpectedParenthesis\n\t\t}\n\t\tif p.i == len(p.s) {\n\t\t\treturn nil, errUnmatchedParenthesis\n\t\t}\n\t\tvar val string\n\t\tswitch p.s[p.i] {\n\t\tcase '\\'', '\"':\n\t\t\tval, err = p.parseString()\n\t\tdefault:\n\t\t\tval, err = p.parseIdentifier()\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tval = strings.ToLower(val)\n\t\tp.skipWhitespace()\n\t\tif p.i >= len(p.s) {\n\t\t\treturn nil, errors.New(\"unexpected EOF in pseudo selector\")\n\t\t}\n\t\tif !p.consumeClosingParenthesis() {\n\t\t\treturn nil, errExpectedClosingParenthesis\n\t\t}\n\n\t\tswitch name {\n\t\tcase \"contains\":\n\t\t\treturn textSubstrSelector(val), nil\n\t\tcase \"containsown\":\n\t\t\treturn ownTextSubstrSelector(val), nil\n\t\t}\n\n\tcase \"matches\", \"matchesown\":\n\t\tif !p.consumeParenthesis() {\n\t\t\treturn nil, errExpectedParenthesis\n\t\t}\n\t\trx, err := p.parseRegex()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif p.i >= len(p.s) {\n\t\t\treturn nil, errors.New(\"unexpected EOF in pseudo selector\")\n\t\t}\n\t\tif !p.consumeClosingParenthesis() {\n\t\t\treturn nil, errExpectedClosingParenthesis\n\t\t}\n\n\t\tswitch name {\n\t\tcase \"matches\":\n\t\t\treturn textRegexSelector(rx), nil\n\t\tcase \"matchesown\":\n\t\t\treturn ownTextRegexSelector(rx), nil\n\t\t}\n\n\tcase \"nth-child\", \"nth-last-child\", \"nth-of-type\", \"nth-last-of-type\":\n\t\tif !p.consumeParenthesis() {\n\t\t\treturn nil, errExpectedParenthesis\n\t\t}\n\t\ta, b, err := p.parseNth()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !p.consumeClosingParenthesis() {\n\t\t\treturn nil, errExpectedClosingParenthesis\n\t\t}\n\t\tif a == 0 {\n\t\t\tswitch name {\n\t\t\tcase \"nth-child\":\n\t\t\t\treturn simpleNthChildSelector(b, false), nil\n\t\t\tcase \"nth-of-type\":\n\t\t\t\treturn simpleNthChildSelector(b, true), nil\n\t\t\tcase \"nth-last-child\":\n\t\t\t\treturn simpleNthLastChildSelector(b, false), nil\n\t\t\tcase \"nth-last-of-type\":\n\t\t\t\treturn simpleNthLastChildSelector(b, true), nil\n\t\t\t}\n\t\t}\n\t\treturn nthChildSelector(a, b,\n\t\t\t\tname == \"nth-last-child\" || name == \"nth-last-of-type\",\n\t\t\t\tname == \"nth-of-type\" || name == \"nth-last-of-type\"),\n\t\t\tnil\n\n\tcase \"first-child\":\n\t\treturn simpleNthChildSelector(1, false), nil\n\tcase \"last-child\":\n\t\treturn simpleNthLastChildSelector(1, false), nil\n\tcase \"first-of-type\":\n\t\treturn simpleNthChildSelector(1, true), nil\n\tcase \"last-of-type\":\n\t\treturn simpleNthLastChildSelector(1, true), nil\n\tcase \"only-child\":\n\t\treturn onlyChildSelector(false), nil\n\tcase \"only-of-type\":\n\t\treturn onlyChildSelector(true), nil\n\tcase \"input\":\n\t\treturn inputSelector, nil\n\tcase \"empty\":\n\t\treturn emptyElementSelector, nil\n\tcase \"root\":\n\t\treturn rootSelector, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"unknown pseudoclass :%s\", name)\n}", "func (p *parser) parsePseudoclassSelector() (Selector, error) {\n\tif p.i >= len(p.s) {\n\t\treturn nil, fmt.Errorf(\"expected pseudoclass selector (:pseudoclass), found EOF instead\")\n\t}\n\tif p.s[p.i] != ':' {\n\t\treturn nil, fmt.Errorf(\"expected attribute selector (:pseudoclass), found '%c' instead\", p.s[p.i])\n\t}\n\n\tp.i++\n\tname, err := p.parseIdentifier()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname = toLowerASCII(name)\n\n\tswitch name {\n\tcase \"not\", \"has\", \"haschild\":\n\t\tif !p.consumeParenthesis() {\n\t\t\treturn nil, errExpectedParenthesis\n\t\t}\n\t\tsel, parseErr := p.parseSelectorGroup()\n\t\tif parseErr != nil {\n\t\t\treturn nil, parseErr\n\t\t}\n\t\tif !p.consumeClosingParenthesis() {\n\t\t\treturn nil, errExpectedClosingParenthesis\n\t\t}\n\n\t\tswitch name {\n\t\tcase \"not\":\n\t\t\treturn negatedSelector(sel), nil\n\t\tcase \"has\":\n\t\t\treturn hasDescendantSelector(sel), nil\n\t\tcase \"haschild\":\n\t\t\treturn hasChildSelector(sel), nil\n\t\t}\n\n\tcase \"contains\", \"containsown\":\n\t\tif !p.consumeParenthesis() {\n\t\t\treturn nil, errExpectedParenthesis\n\t\t}\n\t\tif p.i == len(p.s) {\n\t\t\treturn nil, errUnmatchedParenthesis\n\t\t}\n\t\tvar val string\n\t\tswitch p.s[p.i] {\n\t\tcase '\\'', '\"':\n\t\t\tval, err = p.parseString()\n\t\tdefault:\n\t\t\tval, err = p.parseIdentifier()\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tval = strings.ToLower(val)\n\t\tp.skipWhitespace()\n\t\tif p.i >= len(p.s) {\n\t\t\treturn nil, errors.New(\"unexpected EOF in pseudo selector\")\n\t\t}\n\t\tif !p.consumeClosingParenthesis() {\n\t\t\treturn nil, errExpectedClosingParenthesis\n\t\t}\n\n\t\tswitch name {\n\t\tcase \"contains\":\n\t\t\treturn textSubstrSelector(val), nil\n\t\tcase \"containsown\":\n\t\t\treturn ownTextSubstrSelector(val), nil\n\t\t}\n\n\tcase \"matches\", \"matchesown\":\n\t\tif !p.consumeParenthesis() {\n\t\t\treturn nil, errExpectedParenthesis\n\t\t}\n\t\trx, err := p.parseRegex()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif p.i >= len(p.s) {\n\t\t\treturn nil, errors.New(\"unexpected EOF in pseudo selector\")\n\t\t}\n\t\tif !p.consumeClosingParenthesis() {\n\t\t\treturn nil, errExpectedClosingParenthesis\n\t\t}\n\n\t\tswitch name {\n\t\tcase \"matches\":\n\t\t\treturn textRegexSelector(rx), nil\n\t\tcase \"matchesown\":\n\t\t\treturn ownTextRegexSelector(rx), nil\n\t\t}\n\n\tcase \"nth-child\", \"nth-last-child\", \"nth-of-type\", \"nth-last-of-type\":\n\t\tif !p.consumeParenthesis() {\n\t\t\treturn nil, errExpectedParenthesis\n\t\t}\n\t\ta, b, err := p.parseNth()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !p.consumeClosingParenthesis() {\n\t\t\treturn nil, errExpectedClosingParenthesis\n\t\t}\n\t\tif a == 0 {\n\t\t\tswitch name {\n\t\t\tcase \"nth-child\":\n\t\t\t\treturn simpleNthChildSelector(b, false), nil\n\t\t\tcase \"nth-of-type\":\n\t\t\t\treturn simpleNthChildSelector(b, true), nil\n\t\t\tcase \"nth-last-child\":\n\t\t\t\treturn simpleNthLastChildSelector(b, false), nil\n\t\t\tcase \"nth-last-of-type\":\n\t\t\t\treturn simpleNthLastChildSelector(b, true), nil\n\t\t\t}\n\t\t}\n\t\treturn nthChildSelector(a, b,\n\t\t\t\tname == \"nth-last-child\" || name == \"nth-last-of-type\",\n\t\t\t\tname == \"nth-of-type\" || name == \"nth-last-of-type\"),\n\t\t\tnil\n\n\tcase \"first-child\":\n\t\treturn simpleNthChildSelector(1, false), nil\n\tcase \"last-child\":\n\t\treturn simpleNthLastChildSelector(1, false), nil\n\tcase \"first-of-type\":\n\t\treturn simpleNthChildSelector(1, true), nil\n\tcase \"last-of-type\":\n\t\treturn simpleNthLastChildSelector(1, true), nil\n\tcase \"only-child\":\n\t\treturn onlyChildSelector(false), nil\n\tcase \"only-of-type\":\n\t\treturn onlyChildSelector(true), nil\n\tcase \"input\":\n\t\treturn inputSelector, nil\n\tcase \"empty\":\n\t\treturn emptyElementSelector, nil\n\tcase \"root\":\n\t\treturn rootSelector, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"unknown pseudoclass :%s\", name)\n}", "func SelectorFromSet(ls Set) Selector {\n\tif ls == nil {\n\t\treturn Everything()\n\t}\n\titems := make([]Selector, 0, len(ls))\n\tfor label, value := range ls {\n\t\titems = append(items, &hasTerm{label: label, value: value})\n\t}\n\tif len(items) == 1 {\n\t\treturn items[0]\n\t}\n\treturn andTerm(items)\n}", "func (t *OpenconfigOfficeAp_System_Logging_Console_Selectors) NewSelector(Facility E_OpenconfigSystemLogging_SYSLOG_FACILITY, Severity E_OpenconfigSystemLogging_SyslogSeverity) (*OpenconfigOfficeAp_System_Logging_Console_Selectors_Selector, error) {\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Selector == nil {\n\t\tt.Selector = make(map[OpenconfigOfficeAp_System_Logging_Console_Selectors_Selector_Key]*OpenconfigOfficeAp_System_Logging_Console_Selectors_Selector)\n\t}\n\n\tkey := OpenconfigOfficeAp_System_Logging_Console_Selectors_Selector_Key{\n\t\tFacility: Facility,\n\t\tSeverity: Severity,\n\t}\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Selector[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Selector\", key)\n\t}\n\n\tt.Selector[key] = &OpenconfigOfficeAp_System_Logging_Console_Selectors_Selector{\n\t\tFacility: Facility,\n\t\tSeverity: Severity,\n\t}\n\n\treturn t.Selector[key], nil\n}", "func SelectorLabels(name, instance string) map[string]string {\n\treturn map[string]string{\n\t\tApplicationNameLabelKey: name,\n\t\tApplicationInstanceLabelKey: instance,\n\t}\n}", "func (l Labels) Set(value string) error {\n\tlabelsStrs := strings.Split(value, \",\")\n\tfor _, labelStr := range labelsStrs {\n\t\tkv := strings.Split(labelStr, \"=\")\n\t\tif len(kv) < 1 || len(kv) > 2 {\n\t\t\treturn fmt.Errorf(\"invalid pod selector format\")\n\t\t}\n\n\t\tval := \"\"\n\t\tif len(kv) == 2 {\n\t\t\tval = kv[1]\n\t\t}\n\n\t\tl[kv[0]] = val\n\t}\n\n\treturn nil\n}", "func Parse(selector string) (*Selector, error) {\n\tp := &Parser{l: &Lexer{s: selector, pos: 0}}\n\trequirements, err := p.parse()\n\tif err != nil {\n\t\treturn &Selector{}, err\n\t}\n\tsort.Sort(ByKey(requirements)) // sort to grant determistic parsing\n\treturn &Selector{\n\t\tRequirements: requirements,\n\t}, nil\n}", "func Selector(sel string) (NodeFunc, error) {\n\tSel, err := cascadia.Parse(sel)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NodeFunc(func(node *html.Node) bool {\n\t\treturn Sel.Match(node)\n\t}), nil\n}", "func SelectorLabelsWithComponent(name, instance, component string) map[string]string {\n\tlabels := SelectorLabels(name, instance)\n\tlabels[ApplicationComponentLabelKey] = component\n\n\treturn labels\n}", "func matchesSelector(blockMeta *metadata.Meta, selectorLabels labels.Labels) bool {\n\tfor _, l := range selectorLabels {\n\t\tif v, ok := blockMeta.Thanos.Labels[l.Name]; !ok || (l.Value != \"*\" && v != l.Value) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func SelectorFromSet(ls Set) *Selector {\n\tif ls == nil || len(ls) == 0 {\n\t\treturn &Selector{}\n\t}\n\trequirements := make([]*Requirement, 0)\n\tfor label, value := range ls {\n\t\tr, err := NewRequirement(label, Operator_equals, []string{value})\n\t\tif err == nil {\n\t\t\trequirements = append(requirements, r)\n\t\t}\n\t}\n\t// sort to have deterministic string representation\n\tsort.Sort(ByKey(requirements))\n\treturn &Selector{\n\t\tRequirements: requirements,\n\t}\n}", "func (p *parser) parseSelector() (result Selector, err error) {\n\tp.skipWhitespace()\n\tresult, err = p.parseSimpleSelectorSequence()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor {\n\t\tvar combinator byte\n\t\tif p.skipWhitespace() {\n\t\t\tcombinator = ' '\n\t\t}\n\t\tif p.i >= len(p.s) {\n\t\t\treturn\n\t\t}\n\n\t\tswitch p.s[p.i] {\n\t\tcase '+', '>', '~':\n\t\t\tcombinator = p.s[p.i]\n\t\t\tp.i++\n\t\t\tp.skipWhitespace()\n\t\tcase ',', ')':\n\t\t\t// These characters can't begin a selector, but they can legally occur after one.\n\t\t\treturn\n\t\t}\n\n\t\tif combinator == 0 {\n\t\t\treturn\n\t\t}\n\n\t\tc, err := p.parseSimpleSelectorSequence()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tswitch combinator {\n\t\tcase ' ':\n\t\t\tresult = descendantSelector(result, c)\n\t\tcase '>':\n\t\t\tresult = childSelector(result, c)\n\t\tcase '+':\n\t\t\tresult = siblingSelector(result, c, true)\n\t\tcase '~':\n\t\t\tresult = siblingSelector(result, c, false)\n\t\t}\n\t}\n\n\tpanic(\"unreachable\")\n}", "func (p *parser) parseSelector() (result Selector, err error) {\n\tp.skipWhitespace()\n\tresult, err = p.parseSimpleSelectorSequence()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor {\n\t\tvar combinator byte\n\t\tif p.skipWhitespace() {\n\t\t\tcombinator = ' '\n\t\t}\n\t\tif p.i >= len(p.s) {\n\t\t\treturn\n\t\t}\n\n\t\tswitch p.s[p.i] {\n\t\tcase '+', '>', '~':\n\t\t\tcombinator = p.s[p.i]\n\t\t\tp.i++\n\t\t\tp.skipWhitespace()\n\t\tcase ',', ')':\n\t\t\t// These characters can't begin a selector, but they can legally occur after one.\n\t\t\treturn\n\t\t}\n\n\t\tif combinator == 0 {\n\t\t\treturn\n\t\t}\n\n\t\tc, err := p.parseSimpleSelectorSequence()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tswitch combinator {\n\t\tcase ' ':\n\t\t\tresult = descendantSelector(result, c)\n\t\tcase '>':\n\t\t\tresult = childSelector(result, c)\n\t\tcase '+':\n\t\t\tresult = siblingSelector(result, c, true)\n\t\tcase '~':\n\t\t\tresult = siblingSelector(result, c, false)\n\t\t}\n\t}\n\n\tpanic(\"unreachable\")\n}", "func (s internalSelector) Add(reqs ...Requirement) Selector {\n\tret := make(internalSelector, 0, len(s)+len(reqs))\n\tret = append(ret, s...)\n\tret = append(ret, reqs...)\n\tsort.Sort(ByKey(ret))\n\treturn ret\n}", "func LabelSelectorToPromLabels(selector *metav1.LabelSelector) []*promlabels.Matcher {\n\tif selector == nil {\n\t\treturn []*promlabels.Matcher{}\n\t}\n\n\tvar result []*promlabels.Matcher\n\n\tif selector.MatchLabels != nil {\n\t\tfor name, value := range selector.MatchLabels {\n\t\t\tresult = append(result, &promlabels.Matcher{\n\t\t\t\tType: promlabels.MatchEqual,\n\t\t\t\tName: name,\n\t\t\t\tValue: value,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn result\n}", "func makeSelector(ts *prompb.TimeSeries) string {\n\ts := []string{}\n\tfor _, label := range ts.Labels[1:] {\n\t\ts = append(s, fmt.Sprintf(\"%s=%s\", label.Name, label.Value))\n\t}\n\treturn strings.Join(s, \":\")\n}", "func parseSelector(str string) (*types.Selector, error) {\n\tparts := strings.SplitAfterN(str, \":\", 2)\n\tif len(parts) < 2 {\n\t\treturn nil, fmt.Errorf(\"selector \\\"%s\\\" must be formatted as type:value\", str)\n\t}\n\n\ts := &types.Selector{\n\t\t// Strip the trailing delimiter\n\t\tType: strings.TrimSuffix(parts[0], \":\"),\n\t\tValue: parts[1],\n\t}\n\treturn s, nil\n}", "func NewSelector(ctx Context) Selector {\n\tstate := getState(ctx)\n\tstate.dispatcher.selectorSequence++\n\treturn NewNamedSelector(ctx, fmt.Sprintf(\"selector-%v\", state.dispatcher.selectorSequence))\n}", "func (e *LiteralExpr) Selector() LogSelectorExpr { return e }", "func Parse(selector string, opts ...field.PathOption) (Selector, error) {\n\tparsedSelector, err := parse(selector, field.ToPath(opts...))\n\tif err == nil {\n\t\treturn parsedSelector, nil\n\t}\n\treturn nil, err\n}", "func ParseSelector(selector string) (Selector, error) {\n\tparts := strings.Split(selector, \",\")\n\tsort.Strings(parts)\n\tvar items []Selector\n\tfor _, part := range parts {\n\t\tif part == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif lhs, rhs, ok := try(part, \"!=\"); ok {\n\t\t\titems = append(items, &notHasTerm{label: lhs, value: rhs})\n\t\t} else if lhs, rhs, ok := try(part, \"==\"); ok {\n\t\t\titems = append(items, &hasTerm{label: lhs, value: rhs})\n\t\t} else if lhs, rhs, ok := try(part, \"=\"); ok {\n\t\t\titems = append(items, &hasTerm{label: lhs, value: rhs})\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"invalid selector: '%s'; can't understand '%s'\", selector, part)\n\t\t}\n\t}\n\tif len(items) == 1 {\n\t\treturn items[0], nil\n\t}\n\treturn andTerm(items), nil\n}", "func SelectorFromSet(ls Set) Selector {\n\tif ls == nil {\n\t\treturn Everything()\n\t}\n\titems := make([]Selector, 0, len(ls))\n\tfor field, value := range ls {\n\t\titems = append(items, &hasTerm{field: field, value: value})\n\t}\n\tif len(items) == 1 {\n\t\treturn items[0]\n\t}\n\treturn andTerm(items)\n}", "func TestPodAnnotationFitsSelector(t *testing.T) {\n\tutilfeature.DefaultFeatureGate.Set(\"AffinityInAnnotations=true\")\n\ttests := []struct {\n\t\tpod *v1.Pod\n\t\tlabels map[string]string\n\t\tfits bool\n\t\ttest string\n\t}{\n\t\t{\n\t\t\tpod: &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\tv1.AffinityAnnotationKey: `\n\t\t\t\t\t\t{\"nodeAffinity\": { \"requiredDuringSchedulingIgnoredDuringExecution\": {\n\t\t\t\t\t\t\t\"nodeSelectorTerms\": [{\n\t\t\t\t\t\t\t\t\"matchExpressions\": [{\n\t\t\t\t\t\t\t\t\t\"key\": \"foo\",\n\t\t\t\t\t\t\t\t\t\"operator\": \"In\",\n\t\t\t\t\t\t\t\t\t\"values\": [\"bar\", \"value2\"]\n\t\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t}}}`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tlabels: map[string]string{\n\t\t\t\t\"foo\": \"bar\",\n\t\t\t},\n\t\t\tfits: true,\n\t\t\ttest: \"Pod with matchExpressions using In operator that matches the existing node\",\n\t\t},\n\t\t{\n\t\t\tpod: &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\tv1.AffinityAnnotationKey: `\n\t\t\t\t\t\t{\"nodeAffinity\": { \"requiredDuringSchedulingIgnoredDuringExecution\": {\n\t\t\t\t\t\t\t\"nodeSelectorTerms\": [{\n\t\t\t\t\t\t\t\t\"matchExpressions\": [{\n\t\t\t\t\t\t\t\t\t\"key\": \"kernel-version\",\n\t\t\t\t\t\t\t\t\t\"operator\": \"Gt\",\n\t\t\t\t\t\t\t\t\t\"values\": [\"0204\"]\n\t\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t}}}`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tlabels: map[string]string{\n\t\t\t\t// We use two digit to denote major version and two digit for minor version.\n\t\t\t\t\"kernel-version\": \"0206\",\n\t\t\t},\n\t\t\tfits: true,\n\t\t\ttest: \"Pod with matchExpressions using Gt operator that matches the existing node\",\n\t\t},\n\t\t{\n\t\t\tpod: &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\tv1.AffinityAnnotationKey: `\n\t\t\t\t\t\t{\"nodeAffinity\": { \"requiredDuringSchedulingIgnoredDuringExecution\": {\n\t\t\t\t\t\t\t\"nodeSelectorTerms\": [{\n\t\t\t\t\t\t\t\t\"matchExpressions\": [{\n\t\t\t\t\t\t\t\t\t\"key\": \"mem-type\",\n\t\t\t\t\t\t\t\t\t\"operator\": \"NotIn\",\n\t\t\t\t\t\t\t\t\t\"values\": [\"DDR\", \"DDR2\"]\n\t\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t}}}`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tlabels: map[string]string{\n\t\t\t\t\"mem-type\": \"DDR3\",\n\t\t\t},\n\t\t\tfits: true,\n\t\t\ttest: \"Pod with matchExpressions using NotIn operator that matches the existing node\",\n\t\t},\n\t\t{\n\t\t\tpod: &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\tv1.AffinityAnnotationKey: `\n\t\t\t\t\t\t{\"nodeAffinity\": { \"requiredDuringSchedulingIgnoredDuringExecution\": {\n\t\t\t\t\t\t\t\"nodeSelectorTerms\": [{\n\t\t\t\t\t\t\t\t\"matchExpressions\": [{\n\t\t\t\t\t\t\t\t\t\"key\": \"GPU\",\n\t\t\t\t\t\t\t\t\t\"operator\": \"Exists\"\n\t\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t}}}`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tlabels: map[string]string{\n\t\t\t\t\"GPU\": \"NVIDIA-GRID-K1\",\n\t\t\t},\n\t\t\tfits: true,\n\t\t\ttest: \"Pod with matchExpressions using Exists operator that matches the existing node\",\n\t\t},\n\t\t{\n\t\t\tpod: &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\tv1.AffinityAnnotationKey: `\n\t\t\t\t\t\t{\"nodeAffinity\": { \"requiredDuringSchedulingIgnoredDuringExecution\": {\n\t\t\t\t\t\t\t\"nodeSelectorTerms\": [{\n\t\t\t\t\t\t\t\t\"matchExpressions\": [{\n\t\t\t\t\t\t\t\t\t\"key\": \"foo\",\n\t\t\t\t\t\t\t\t\t\"operator\": \"In\",\n\t\t\t\t\t\t\t\t\t\"values\": [\"value1\", \"value2\"]\n\t\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t}}}`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tlabels: map[string]string{\n\t\t\t\t\"foo\": \"bar\",\n\t\t\t},\n\t\t\tfits: false,\n\t\t\ttest: \"Pod with affinity that don't match node's labels won't schedule onto the node\",\n\t\t},\n\t\t{\n\t\t\tpod: &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\tv1.AffinityAnnotationKey: `\n\t\t\t\t\t\t{\"nodeAffinity\": { \"requiredDuringSchedulingIgnoredDuringExecution\": {\n\t\t\t\t\t\t\t\"nodeSelectorTerms\": null\n\t\t\t\t\t\t}}}`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tlabels: map[string]string{\n\t\t\t\t\"foo\": \"bar\",\n\t\t\t},\n\t\t\tfits: false,\n\t\t\ttest: \"Pod with a nil []NodeSelectorTerm in affinity, can't match the node's labels and won't schedule onto the node\",\n\t\t},\n\t\t{\n\t\t\tpod: &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\tv1.AffinityAnnotationKey: `\n\t\t\t\t\t\t{\"nodeAffinity\": { \"requiredDuringSchedulingIgnoredDuringExecution\": {\n\t\t\t\t\t\t\t\"nodeSelectorTerms\": []\n\t\t\t\t\t\t}}}`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tlabels: map[string]string{\n\t\t\t\t\"foo\": \"bar\",\n\t\t\t},\n\t\t\tfits: false,\n\t\t\ttest: \"Pod with an empty []NodeSelectorTerm in affinity, can't match the node's labels and won't schedule onto the node\",\n\t\t},\n\t\t{\n\t\t\tpod: &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\tv1.AffinityAnnotationKey: `\n\t\t\t\t\t\t{\"nodeAffinity\": { \"requiredDuringSchedulingIgnoredDuringExecution\": {\n\t\t\t\t\t\t\t\"nodeSelectorTerms\": [{}, {}]\n\t\t\t\t\t\t}}}`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tlabels: map[string]string{\n\t\t\t\t\"foo\": \"bar\",\n\t\t\t},\n\t\t\tfits: false,\n\t\t\ttest: \"Pod with invalid NodeSelectTerms in affinity will match no objects and won't schedule onto the node\",\n\t\t},\n\t\t{\n\t\t\tpod: &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\tv1.AffinityAnnotationKey: `\n\t\t\t\t\t\t{\"nodeAffinity\": { \"requiredDuringSchedulingIgnoredDuringExecution\": {\n\t\t\t\t\t\t\t\"nodeSelectorTerms\": [{\"matchExpressions\": [{}]}]\n\t\t\t\t\t\t}}}`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tlabels: map[string]string{\n\t\t\t\t\"foo\": \"bar\",\n\t\t\t},\n\t\t\tfits: false,\n\t\t\ttest: \"Pod with empty MatchExpressions is not a valid value will match no objects and won't schedule onto the node\",\n\t\t},\n\t\t{\n\t\t\tpod: &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\t\"some-key\": \"some-value\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tlabels: map[string]string{\n\t\t\t\t\"foo\": \"bar\",\n\t\t\t},\n\t\t\tfits: true,\n\t\t\ttest: \"Pod with no Affinity will schedule onto a node\",\n\t\t},\n\t\t{\n\t\t\tpod: &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\tv1.AffinityAnnotationKey: `\n\t\t\t\t\t\t{\"nodeAffinity\": { \"requiredDuringSchedulingIgnoredDuringExecution\": null\n\t\t\t\t\t\t}}`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tlabels: map[string]string{\n\t\t\t\t\"foo\": \"bar\",\n\t\t\t},\n\t\t\tfits: true,\n\t\t\ttest: \"Pod with Affinity but nil NodeSelector will schedule onto a node\",\n\t\t},\n\t\t{\n\t\t\tpod: &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\tv1.AffinityAnnotationKey: `\n\t\t\t\t\t\t{\"nodeAffinity\": { \"requiredDuringSchedulingIgnoredDuringExecution\": {\n\t\t\t\t\t\t\t\"nodeSelectorTerms\": [{\n\t\t\t\t\t\t\t\t\"matchExpressions\": [{\n\t\t\t\t\t\t\t\t\t\"key\": \"GPU\",\n\t\t\t\t\t\t\t\t\t\"operator\": \"Exists\"\n\t\t\t\t\t\t\t\t}, {\n\t\t\t\t\t\t\t\t\t\"key\": \"GPU\",\n\t\t\t\t\t\t\t\t\t\"operator\": \"NotIn\",\n\t\t\t\t\t\t\t\t\t\"values\": [\"AMD\", \"INTER\"]\n\t\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t}}}`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tlabels: map[string]string{\n\t\t\t\t\"GPU\": \"NVIDIA-GRID-K1\",\n\t\t\t},\n\t\t\tfits: true,\n\t\t\ttest: \"Pod with multiple matchExpressions ANDed that matches the existing node\",\n\t\t},\n\t\t{\n\t\t\tpod: &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\tv1.AffinityAnnotationKey: `\n\t\t\t\t\t\t{\"nodeAffinity\": { \"requiredDuringSchedulingIgnoredDuringExecution\": {\n\t\t\t\t\t\t\t\"nodeSelectorTerms\": [{\n\t\t\t\t\t\t\t\t\"matchExpressions\": [{\n\t\t\t\t\t\t\t\t\t\"key\": \"GPU\",\n\t\t\t\t\t\t\t\t\t\"operator\": \"Exists\"\n\t\t\t\t\t\t\t\t}, {\n\t\t\t\t\t\t\t\t\t\"key\": \"GPU\",\n\t\t\t\t\t\t\t\t\t\"operator\": \"In\",\n\t\t\t\t\t\t\t\t\t\"values\": [\"AMD\", \"INTER\"]\n\t\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t}}}`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tlabels: map[string]string{\n\t\t\t\t\"GPU\": \"NVIDIA-GRID-K1\",\n\t\t\t},\n\t\t\tfits: false,\n\t\t\ttest: \"Pod with multiple matchExpressions ANDed that doesn't match the existing node\",\n\t\t},\n\t\t{\n\t\t\tpod: &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\tv1.AffinityAnnotationKey: `\n\t\t\t\t\t\t{\"nodeAffinity\": { \"requiredDuringSchedulingIgnoredDuringExecution\": {\n\t\t\t\t\t\t\t\"nodeSelectorTerms\": [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\"matchExpressions\": [{\n\t\t\t\t\t\t\t\t\t\t\"key\": \"foo\",\n\t\t\t\t\t\t\t\t\t\t\"operator\": \"In\",\n\t\t\t\t\t\t\t\t\t\t\"values\": [\"bar\", \"value2\"]\n\t\t\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\"matchExpressions\": [{\n\t\t\t\t\t\t\t\t\t\t\"key\": \"diffkey\",\n\t\t\t\t\t\t\t\t\t\t\"operator\": \"In\",\n\t\t\t\t\t\t\t\t\t\t\"values\": [\"wrong\", \"value2\"]\n\t\t\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t}}}`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tlabels: map[string]string{\n\t\t\t\t\"foo\": \"bar\",\n\t\t\t},\n\t\t\tfits: true,\n\t\t\ttest: \"Pod with multiple NodeSelectorTerms ORed in affinity, matches the node's labels and will schedule onto the node\",\n\t\t},\n\t\t// TODO: Uncomment this test when implement RequiredDuringSchedulingRequiredDuringExecution\n\t\t//\t\t{\n\t\t//\t\t\tpod: &v1.Pod{\n\t\t//\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t//\t\t\t\t\tAnnotations: map[string]string{\n\t\t//\t\t\t\t\t\tv1.AffinityAnnotationKey: `\n\t\t//\t\t\t\t\t\t{\"nodeAffinity\": {\n\t\t//\t\t\t\t\t\t\t\"requiredDuringSchedulingRequiredDuringExecution\": {\n\t\t//\t\t\t\t\t\t\t\t\"nodeSelectorTerms\": [{\n\t\t//\t\t\t\t\t\t\t\t\t\"matchExpressions\": [{\n\t\t//\t\t\t\t\t\t\t\t\t\t\"key\": \"foo\",\n\t\t//\t\t\t\t\t\t\t\t\t\t\"operator\": \"In\",\n\t\t//\t\t\t\t\t\t\t\t\t\t\"values\": [\"bar\", \"value2\"]\n\t\t//\t\t\t\t\t\t\t\t\t}]\n\t\t//\t\t\t\t\t\t\t\t}]\n\t\t//\t\t\t\t\t\t\t},\n\t\t//\t\t\t\t\t\t\t\"requiredDuringSchedulingIgnoredDuringExecution\": {\n\t\t//\t\t\t\t\t\t\t\t\"nodeSelectorTerms\": [{\n\t\t//\t\t\t\t\t\t\t\t\t\"matchExpressions\": [{\n\t\t//\t\t\t\t\t\t\t\t\t\t\"key\": \"foo\",\n\t\t//\t\t\t\t\t\t\t\t\t\t\"operator\": \"NotIn\",\n\t\t//\t\t\t\t\t\t\t\t\t\t\"values\": [\"bar\", \"value2\"]\n\t\t//\t\t\t\t\t\t\t\t\t}]\n\t\t//\t\t\t\t\t\t\t\t}]\n\t\t//\t\t\t\t\t\t\t}\n\t\t//\t\t\t\t\t\t}}`,\n\t\t//\t\t\t\t\t},\n\t\t//\t\t\t\t},\n\t\t//\t\t\t},\n\t\t//\t\t\tlabels: map[string]string{\n\t\t//\t\t\t\t\"foo\": \"bar\",\n\t\t//\t\t\t},\n\t\t//\t\t\tfits: false,\n\t\t//\t\t\ttest: \"Pod with an Affinity both requiredDuringSchedulingRequiredDuringExecution and \" +\n\t\t//\t\t\t\t\"requiredDuringSchedulingIgnoredDuringExecution indicated that don't match node's labels and won't schedule onto the node\",\n\t\t//\t\t},\n\t\t{\n\t\t\tpod: &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\tv1.AffinityAnnotationKey: `\n\t\t\t\t\t\t{\"nodeAffinity\": { \"requiredDuringSchedulingIgnoredDuringExecution\": {\n\t\t\t\t\t\t\t\"nodeSelectorTerms\": [{\n\t\t\t\t\t\t\t\t\"matchExpressions\": [{\n\t\t\t\t\t\t\t\t\t\"key\": \"foo\",\n\t\t\t\t\t\t\t\t\t\"operator\": \"Exists\"\n\t\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t}}}`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSpec: v1.PodSpec{\n\t\t\t\t\tNodeSelector: map[string]string{\n\t\t\t\t\t\t\"foo\": \"bar\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tlabels: map[string]string{\n\t\t\t\t\"foo\": \"bar\",\n\t\t\t},\n\t\t\tfits: true,\n\t\t\ttest: \"Pod with an Affinity and a PodSpec.NodeSelector(the old thing that we are deprecating) \" +\n\t\t\t\t\"both are satisfied, will schedule onto the node\",\n\t\t},\n\t\t{\n\t\t\tpod: &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\tv1.AffinityAnnotationKey: `\n\t\t\t\t\t\t{\"nodeAffinity\": { \"requiredDuringSchedulingIgnoredDuringExecution\": {\n\t\t\t\t\t\t\t\"nodeSelectorTerms\": [{\n\t\t\t\t\t\t\t\t\"matchExpressions\": [{\n\t\t\t\t\t\t\t\t\t\"key\": \"foo\",\n\t\t\t\t\t\t\t\t\t\"operator\": \"Exists\"\n\t\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t}}}`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSpec: v1.PodSpec{\n\t\t\t\t\tNodeSelector: map[string]string{\n\t\t\t\t\t\t\"foo\": \"bar\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tlabels: map[string]string{\n\t\t\t\t\"foo\": \"barrrrrr\",\n\t\t\t},\n\t\t\tfits: false,\n\t\t\ttest: \"Pod with an Affinity matches node's labels but the PodSpec.NodeSelector(the old thing that we are deprecating) \" +\n\t\t\t\t\"is not satisfied, won't schedule onto the node\",\n\t\t},\n\t}\n\texpectedFailureReasons := []algorithm.PredicateFailureReason{ErrNodeSelectorNotMatch}\n\n\tfor _, test := range tests {\n\t\tnode := v1.Node{ObjectMeta: metav1.ObjectMeta{Labels: test.labels}}\n\t\tnodeInfo := schedulercache.NewNodeInfo()\n\t\tnodeInfo.SetNode(&node)\n\n\t\tfits, reasons, err := PodMatchNodeSelector(test.pod, PredicateMetadata(test.pod, nil), nodeInfo)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%s: unexpected error: %v\", test.test, err)\n\t\t}\n\t\tif !fits && !reflect.DeepEqual(reasons, expectedFailureReasons) {\n\t\t\tt.Errorf(\"%s: unexpected failure reasons: %v, want: %v\", test.test, reasons, expectedFailureReasons)\n\t\t}\n\t\tif fits != test.fits {\n\t\t\tt.Errorf(\"%s: expected: %v got %v\", test.test, test.fits, fits)\n\t\t}\n\t}\n}", "func setLabelOpts(s *specgen.SpecGenerator, runtime *libpod.Runtime, pidConfig specgen.Namespace, ipcConfig specgen.Namespace) error {\n\treturn nil\n}", "func createNodeSelector(nodeName string) *v1.NodeSelector {\n\treturn &v1.NodeSelector{\n\t\tNodeSelectorTerms: []v1.NodeSelectorTerm{\n\t\t\tv1.NodeSelectorTerm{\n\t\t\t\tMatchExpressions: []v1.NodeSelectorRequirement{\n\t\t\t\t\tv1.NodeSelectorRequirement{\n\t\t\t\t\t\tKey: \"kubernetes.io/hostname\",\n\t\t\t\t\t\tOperator: v1.NodeSelectorOpIn,\n\t\t\t\t\t\tValues: []string{nodeName},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func Selector(s selector.Selector) Option {\n\treturn func(o *Options) {\n\t\to.Selector = s\n\t}\n}", "func Selector(s selector.Selector) Option {\n\treturn func(o *Options) {\n\t\to.Selector = s\n\t}\n}", "func getSelectorFromString(str string) (labels.Selector, error) {\n\tlabelSelector, err := v1.ParseToLabelSelector(str)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tselector, err := v1.LabelSelectorAsSelector(labelSelector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn selector, nil\n}", "func (e *EvaluateJobArgsBuilder) setNodeSelectors() error {\n\te.args.NodeSelectors = map[string]string{}\n\targKey := \"selector\"\n\tvar nodeSelectors *[]string\n\tvalue, ok := e.argValues[argKey]\n\tif !ok {\n\t\treturn nil\n\t}\n\tnodeSelectors = value.(*[]string)\n\tlog.Debugf(\"node selectors: %v\", *nodeSelectors)\n\te.args.NodeSelectors = transformSliceToMap(*nodeSelectors, \"=\")\n\treturn nil\n}", "func SetGlobalSelector(builder Builder) {\n\tglobalSelector = builder\n}", "func TestPoolSelectorBasic(t *testing.T) {\n\tpoolA := mkPool(poolAUID, \"pool-a\", []string{\"10.0.10.0/24\"})\n\tselector := slim_meta_v1.LabelSelector{\n\t\tMatchLabels: map[string]string{\n\t\t\t\"color\": \"red\",\n\t\t},\n\t}\n\tpoolA.Spec.ServiceSelector = &selector\n\n\tfixture := mkTestFixture([]*cilium_api_v2alpha1.CiliumLoadBalancerIPPool{\n\t\tpoolA,\n\t}, true, true, nil)\n\n\tgo fixture.hive.Start(context.Background())\n\tdefer fixture.hive.Stop(context.Background())\n\n\tawait := fixture.AwaitService(func(action k8s_testing.Action) bool {\n\t\tif action.GetResource() != servicesResource || action.GetVerb() != \"patch\" {\n\t\t\treturn false\n\t\t}\n\n\t\tsvc := fixture.PatchedSvc(action)\n\n\t\tif svc.Name != \"red-service\" {\n\t\t\tt.Error(\"Expected update from 'red-service'\")\n\t\t\treturn true\n\t\t}\n\n\t\tif len(svc.Status.LoadBalancer.Ingress) != 1 {\n\t\t\tt.Error(\"Expected service to receive exactly one ingress IP\")\n\t\t\treturn true\n\t\t}\n\n\t\tif net.ParseIP(svc.Status.LoadBalancer.Ingress[0].IP).To4() == nil {\n\t\t\tt.Error(\"Expected service to receive a IPv4 address\")\n\t\t\treturn true\n\t\t}\n\n\t\tif len(svc.Status.Conditions) != 1 {\n\t\t\tt.Error(\"Expected service to receive exactly one condition\")\n\t\t\treturn true\n\t\t}\n\n\t\tif svc.Status.Conditions[0].Type != ciliumSvcRequestSatisfiedCondition {\n\t\t\tt.Error(\"Expected condition to be svc-satisfied:true\")\n\t\t\treturn true\n\t\t}\n\n\t\tif svc.Status.Conditions[0].Status != slim_meta_v1.ConditionTrue {\n\t\t\tt.Error(\"Expected condition to be svc-satisfied:true\")\n\t\t\treturn true\n\t\t}\n\n\t\treturn true\n\t}, time.Second)\n\n\tpolicy := slim_core_v1.IPFamilyPolicySingleStack\n\tmatchingService := &slim_core_v1.Service{\n\t\tObjectMeta: slim_meta_v1.ObjectMeta{\n\t\t\tName: \"red-service\",\n\t\t\tUID: serviceAUID,\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"color\": \"red\",\n\t\t\t},\n\t\t},\n\t\tSpec: slim_core_v1.ServiceSpec{\n\t\t\tType: slim_core_v1.ServiceTypeLoadBalancer,\n\t\t\tIPFamilyPolicy: &policy,\n\t\t},\n\t}\n\n\t_, err := fixture.svcClient.Services(\"default\").Create(context.Background(), matchingService, meta_v1.CreateOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif await.Block() {\n\t\tt.Fatal(\"Expected service status update\")\n\t}\n\n\t// If t.Error was called within the await\n\tif t.Failed() {\n\t\treturn\n\t}\n\n\tawait = fixture.AwaitService(func(action k8s_testing.Action) bool {\n\t\tif action.GetResource() != servicesResource || action.GetVerb() != \"patch\" {\n\t\t\treturn false\n\t\t}\n\n\t\tsvc := fixture.PatchedSvc(action)\n\n\t\tif svc.Name != \"blue-service\" {\n\t\t\treturn false\n\t\t}\n\n\t\tif len(svc.Status.LoadBalancer.Ingress) != 0 {\n\t\t\tt.Error(\"Expected service to not receive any ingress IPs\")\n\t\t\treturn true\n\t\t}\n\n\t\tif len(svc.Status.Conditions) != 1 {\n\t\t\tt.Error(\"Expected service to receive exactly one condition\")\n\t\t\treturn true\n\t\t}\n\n\t\tif svc.Status.Conditions[0].Type != ciliumSvcRequestSatisfiedCondition {\n\t\t\tt.Error(\"Expected condition to be svc-satisfied:false\")\n\t\t\treturn true\n\t\t}\n\n\t\tif svc.Status.Conditions[0].Status != slim_meta_v1.ConditionFalse {\n\t\t\tt.Error(\"Expected condition to be svc-satisfied:false\")\n\t\t\treturn true\n\t\t}\n\n\t\treturn true\n\t}, time.Second)\n\n\tnonMatchingService := &slim_core_v1.Service{\n\t\tObjectMeta: slim_meta_v1.ObjectMeta{\n\t\t\tName: \"blue-service\",\n\t\t\tUID: serviceBUID,\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"color\": \"blue\",\n\t\t\t},\n\t\t},\n\t\tSpec: slim_core_v1.ServiceSpec{\n\t\t\tType: slim_core_v1.ServiceTypeLoadBalancer,\n\t\t\tIPFamilyPolicy: &policy,\n\t\t},\n\t}\n\n\t_, err = fixture.svcClient.Services(\"default\").Create(context.Background(), nonMatchingService, meta_v1.CreateOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif await.Block() {\n\t\tt.Fatal(\"Expected service status update\")\n\t}\n}", "func (o PodsMetricSourcePatchOutput) Selector() metav1.LabelSelectorPatchPtrOutput {\n\treturn o.ApplyT(func(v PodsMetricSourcePatch) *metav1.LabelSelectorPatch { return v.Selector }).(metav1.LabelSelectorPatchPtrOutput)\n}", "func makeSvcSelectorLabels(vdb *vapi.VerticaDB, sc *vapi.Subcluster) map[string]string {\n\t// The selector will simply use the common labels for all objects.\n\treturn makeCommonLabels(vdb, sc)\n}", "func Compile(sel string) (Selector, error) {\n\tcompiled, err := ParseGroup(sel)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn Selector(compiled.Match), nil\n}", "func ProjectSelector(project string) string {\n\treturn LabelProject + \"=\" + project\n}", "func MatchesSelector(installable interfaces.IInstallable, selector string) (bool, error) {\n\n\tlog.Logger.Tracef(\"Testing whether installable '%s' matches the selector '%s'\",\n\t\tinstallable.FullyQualifiedId(), selector)\n\n\tselectorParts := strings.Split(selector, constants.NamespaceSeparator)\n\tif len(selectorParts) != 2 {\n\t\treturn false, errors.New(fmt.Sprintf(\"Fully-qualified IDs must \"+\n\t\t\t\"be given, i.e. formatted 'manifest-id%skapp-id' or 'manifest-id%s%s' \"+\n\t\t\t\"for all kapps in a manifest\", constants.NamespaceSeparator,\n\t\t\tconstants.NamespaceSeparator, constants.WildcardCharacter))\n\t}\n\n\tselectorManifestId := selectorParts[0]\n\tselectorId := selectorParts[1]\n\n\tidParts := strings.Split(installable.FullyQualifiedId(), constants.NamespaceSeparator)\n\tif len(idParts) != 2 {\n\t\treturn false, errors.New(fmt.Sprintf(\"Fully-qualified kapp ID \"+\n\t\t\t\"has an unexpected format: %s\", installable.FullyQualifiedId()))\n\t}\n\n\tkappManifestId := idParts[0]\n\tkappId := idParts[1]\n\n\tif selectorManifestId == kappManifestId {\n\t\tif selectorId == constants.WildcardCharacter || selectorId == kappId {\n\t\t\tlog.Logger.Tracef(\"Installable '%s' did match the selector '%s'\", installable.FullyQualifiedId(), selector)\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\tlog.Logger.Tracef(\"Installable '%s' didn't match the selector '%s'\", installable.FullyQualifiedId(), selector)\n\treturn false, nil\n}", "func (r ApiGetIqnpoolPoolListRequest) Select_(select_ string) ApiGetIqnpoolPoolListRequest {\n\tr.select_ = &select_\n\treturn r\n}", "func getSelectorMap(s string) map[string]string {\n\tselector := map[string]string{}\n\tif name := nameRegex.FindString(s); name != \"\" {\n\t\tselector[\"elementName\"] = name\n\t}\n\tif id := idRegex.FindString(s); id != \"\" {\n\t\tselector[\"id\"] = id[1:]\n\t}\n\tif class := classRegex.FindString(s); class != \"\" {\n\t\tselector[\"class\"] = class[1:]\n\t}\n\treturn selector\n}", "func NodeSelectorRequirementsAsSelector(nsm []corev1.NodeSelectorRequirement) (labels.Selector, error) {\n\tif len(nsm) == 0 {\n\t\treturn labels.Nothing(), nil\n\t}\n\tselector := labels.NewSelector()\n\tfor _, expr := range nsm {\n\t\tvar op selection.Operator\n\t\tswitch expr.Operator {\n\t\tcase corev1.NodeSelectorOpIn:\n\t\t\top = selection.In\n\t\tcase corev1.NodeSelectorOpNotIn:\n\t\t\top = selection.NotIn\n\t\tcase corev1.NodeSelectorOpExists:\n\t\t\top = selection.Exists\n\t\tcase corev1.NodeSelectorOpDoesNotExist:\n\t\t\top = selection.DoesNotExist\n\t\tcase corev1.NodeSelectorOpGt:\n\t\t\top = selection.GreaterThan\n\t\tcase corev1.NodeSelectorOpLt:\n\t\t\top = selection.LessThan\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"%q is not a valid node selector operator\", expr.Operator)\n\t\t}\n\t\tr, err := labels.NewRequirement(expr.Key, op, expr.Values)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tselector = selector.Add(*r)\n\t}\n\treturn selector, nil\n}", "func (o PodsMetricSourcePatchPtrOutput) Selector() metav1.LabelSelectorPatchPtrOutput {\n\treturn o.ApplyT(func(v *PodsMetricSourcePatch) *metav1.LabelSelectorPatch {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Selector\n\t}).(metav1.LabelSelectorPatchPtrOutput)\n}", "func WithSelectors(selectors ...string) Option {\n\treturn func(cfg *Config) {\n\t\tcfg.Selectors = append(cfg.Selectors, selectors...)\n\t}\n}", "func (p *Pod) Selector() labels.Selector {\n\treturn labels.SelectorFromSet(p.Labels)\n}", "func Selector(selector, fieldName string) string {\n\tif selector != \"\" {\n\t\tfieldName = selector + \".\" + fieldName\n\t}\n\treturn fieldName\n}", "func (o SystemParameterRuleOutput) Selector() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v SystemParameterRule) *string { return v.Selector }).(pulumi.StringPtrOutput)\n}", "func selectorDefPath(filePath string, s selector) string {\n\treturn fmt.Sprintf(\"%s%s\", filepath.ToSlash(filePath), string(s))\n}", "func SelectorFromValidatedSet(ls Set) Selector {\n\tif ls == nil || len(ls) == 0 {\n\t\treturn internalSelector{}\n\t}\n\trequirements := make([]Requirement, 0, len(ls))\n\tfor label, value := range ls {\n\t\trequirements = append(requirements, Requirement{key: label, operator: selection.Equals, strValues: []string{value}})\n\t}\n\t// sort to have deterministic string representation\n\tsort.Sort(ByKey(requirements))\n\treturn internalSelector(requirements)\n}", "func (b *Balancer) GetSelector() pool { return b.selector }", "func (o Iperf3SpecServerConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionOutput) LabelSelector() Iperf3SpecServerConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorPtrOutput {\n\treturn o.ApplyT(func(v Iperf3SpecServerConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecution) *Iperf3SpecServerConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelector {\n\t\treturn v.LabelSelector\n\t}).(Iperf3SpecServerConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorPtrOutput)\n}", "func SelectorFromValidatedSet(ls Set) *Selector {\n\tif ls == nil || len(ls) == 0 {\n\t\treturn &Selector{}\n\t}\n\trequirements := make([]*Requirement, 0)\n\tfor label, value := range ls {\n\t\trequirements = append(requirements, &Requirement{Key: label, Operator: Operator_name[int32(Operator_equals)], Values: []string{value}})\n\t}\n\t// sort to have deterministic string representation\n\tsort.Sort(ByKey(requirements))\n\treturn &Selector{\n\t\tRequirements: requirements,\n\t}\n}", "func (o PodsMetricSourcePtrOutput) Selector() metav1.LabelSelectorPtrOutput {\n\treturn o.ApplyT(func(v *PodsMetricSource) *metav1.LabelSelector {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Selector\n\t}).(metav1.LabelSelectorPtrOutput)\n}", "func (o Iperf3SpecServerConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionOutput) LabelSelector() Iperf3SpecServerConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorPtrOutput {\n\treturn o.ApplyT(func(v Iperf3SpecServerConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecution) *Iperf3SpecServerConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelector {\n\t\treturn v.LabelSelector\n\t}).(Iperf3SpecServerConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorPtrOutput)\n}", "func (o Iperf3SpecServerConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermOutput) LabelSelector() Iperf3SpecServerConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorPtrOutput {\n\treturn o.ApplyT(func(v Iperf3SpecServerConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTerm) *Iperf3SpecServerConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelector {\n\t\treturn v.LabelSelector\n\t}).(Iperf3SpecServerConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorPtrOutput)\n}", "func (o QperfSpecServerConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionOutput) LabelSelector() QperfSpecServerConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorPtrOutput {\n\treturn o.ApplyT(func(v QperfSpecServerConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecution) *QperfSpecServerConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelector {\n\t\treturn v.LabelSelector\n\t}).(QperfSpecServerConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorPtrOutput)\n}", "func parseSelectorOrDie(s string) labels.Selector {\n\tsel, err := labels.Parse(s)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn sel\n}", "func SetSelector(selector string) Option {\n\treturn func(s *Scraper) Option {\n\t\tprev := s.selector\n\t\ts.selector = selector\n\t\treturn SetSelector(prev)\n\t}\n}", "func (o PodsMetricStatusPatchOutput) Selector() metav1.LabelSelectorPatchPtrOutput {\n\treturn o.ApplyT(func(v PodsMetricStatusPatch) *metav1.LabelSelectorPatch { return v.Selector }).(metav1.LabelSelectorPatchPtrOutput)\n}", "func Query(sel string) (Selector, error) {\n\tp := &parser{s: sel}\n\tcompiled, err := p.parseSelectorGroup()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif p.i < len(sel) {\n\t\treturn nil, fmt.Errorf(\"parsing %q: %d bytes left over\", sel, len(sel)-p.i)\n\t}\n\n\treturn compiled, nil\n}", "func (o QperfSpecServerConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionOutput) LabelSelector() QperfSpecServerConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorPtrOutput {\n\treturn o.ApplyT(func(v QperfSpecServerConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecution) *QperfSpecServerConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelector {\n\t\treturn v.LabelSelector\n\t}).(QperfSpecServerConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorPtrOutput)\n}", "func NodeSelectorRequirementsAsSelector(nsm []v1.NodeSelectorRequirement) (labels.Selector, error) {\n\tif len(nsm) == 0 {\n\t\treturn labels.Nothing(), nil\n\t}\n\tselector := labels.NewSelector()\n\tfor _, expr := range nsm {\n\t\tvar op selection.Operator\n\t\tswitch expr.Operator {\n\t\tcase v1.NodeSelectorOpIn:\n\t\t\top = selection.In\n\t\tcase v1.NodeSelectorOpNotIn:\n\t\t\top = selection.NotIn\n\t\tcase v1.NodeSelectorOpExists:\n\t\t\top = selection.Exists\n\t\tcase v1.NodeSelectorOpDoesNotExist:\n\t\t\top = selection.DoesNotExist\n\t\tcase v1.NodeSelectorOpGt:\n\t\t\top = selection.GreaterThan\n\t\tcase v1.NodeSelectorOpLt:\n\t\t\top = selection.LessThan\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"%q is not a valid node selector operator\", expr.Operator)\n\t\t}\n\t\tr, err := labels.NewRequirement(expr.Key, op, expr.Values)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tselector = selector.Add(*r)\n\t}\n\treturn selector, nil\n}", "func (o Iperf3SpecClientConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermOutput) LabelSelector() Iperf3SpecClientConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorPtrOutput {\n\treturn o.ApplyT(func(v Iperf3SpecClientConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTerm) *Iperf3SpecClientConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelector {\n\t\treturn v.LabelSelector\n\t}).(Iperf3SpecClientConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorPtrOutput)\n}", "func (o Iperf3SpecClientConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionOutput) LabelSelector() Iperf3SpecClientConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorPtrOutput {\n\treturn o.ApplyT(func(v Iperf3SpecClientConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecution) *Iperf3SpecClientConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelector {\n\t\treturn v.LabelSelector\n\t}).(Iperf3SpecClientConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorPtrOutput)\n}", "func (fr *fakeRequest) Selector() datamodel.Node {\n\treturn fr.selector\n}", "func (r ApiGetHyperflexAutoSupportPolicyListRequest) Select_(select_ string) ApiGetHyperflexAutoSupportPolicyListRequest {\n\tr.select_ = &select_\n\treturn r\n}", "func (o Iperf3SpecClientConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionOutput) LabelSelector() Iperf3SpecClientConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorPtrOutput {\n\treturn o.ApplyT(func(v Iperf3SpecClientConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecution) *Iperf3SpecClientConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelector {\n\t\treturn v.LabelSelector\n\t}).(Iperf3SpecClientConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorPtrOutput)\n}", "func Parse(sel string) (Sel, error) {\n\tp := &parser{s: sel}\n\tcompiled, err := p.parseSelector()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif p.i < len(sel) {\n\t\treturn nil, fmt.Errorf(\"parsing %q: %d bytes left over\", sel, len(sel)-p.i)\n\t}\n\n\treturn compiled, nil\n}", "func (o MetricIdentifierPatchOutput) Selector() metav1.LabelSelectorPatchPtrOutput {\n\treturn o.ApplyT(func(v MetricIdentifierPatch) *metav1.LabelSelectorPatch { return v.Selector }).(metav1.LabelSelectorPatchPtrOutput)\n}", "func (o Iperf3SpecServerConfigurationPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermOutput) LabelSelector() Iperf3SpecServerConfigurationPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorPtrOutput {\n\treturn o.ApplyT(func(v Iperf3SpecServerConfigurationPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTerm) *Iperf3SpecServerConfigurationPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelector {\n\t\treturn v.LabelSelector\n\t}).(Iperf3SpecServerConfigurationPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorPtrOutput)\n}", "func (o PodsMetricSourceOutput) Selector() metav1.LabelSelectorPtrOutput {\n\treturn o.ApplyT(func(v PodsMetricSource) *metav1.LabelSelector { return v.Selector }).(metav1.LabelSelectorPtrOutput)\n}", "func MatchLabels(selector map[string]string, target map[string]string) bool {\n\t// empty selector matches nothing\n\tif len(selector) == 0 {\n\t\treturn false\n\t}\n\t// *: * matches everything even empty target set\n\tif selector[Wildcard] == Wildcard {\n\t\treturn true\n\t}\n\tfor key, val := range selector {\n\t\tif targetVal, ok := target[key]; !ok || (val != targetVal && val != Wildcard) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func TestUpdatePodSelector(t *testing.T) {\n\tcluster := NewClusterState()\n\tvpa := addTestVpa(cluster)\n\tpod := addTestPod(cluster)\n\n\t// Update the VPA selector such that it still matches the Pod.\n\tassert.NoError(t, cluster.AddOrUpdateVpa(testVpaID, \"label-1 in (value-1,value-2)\"))\n\tvpa = cluster.Vpas[testVpaID]\n\tassert.Equal(t, pod, vpa.Pods[testPodID])\n\tassert.Equal(t, vpa, pod.Vpa)\n\n\t// Update the VPA selector to no longer match the Pod.\n\tassert.NoError(t, cluster.AddOrUpdateVpa(testVpaID, \"label-1 = value-2\"))\n\tvpa = cluster.Vpas[testVpaID]\n\tassert.Empty(t, vpa.Pods)\n\tassert.Nil(t, pod.Vpa)\n\n\t// Update the VPA selector to match the Pod again.\n\tassert.NoError(t, cluster.AddOrUpdateVpa(testVpaID, \"label-1 = value-1\"))\n\tvpa = cluster.Vpas[testVpaID]\n\tassert.Equal(t, pod, vpa.Pods[testPodID])\n\tassert.Equal(t, vpa, pod.Vpa)\n}", "func (o QperfSpecServerConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermOutput) LabelSelector() QperfSpecServerConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorPtrOutput {\n\treturn o.ApplyT(func(v QperfSpecServerConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTerm) *QperfSpecServerConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelector {\n\t\treturn v.LabelSelector\n\t}).(QperfSpecServerConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorPtrOutput)\n}", "func SelectorFromSet(ls Set) Selector {\n\treturn SelectorFromValidatedSet(ls)\n}", "func (o QperfSpecClientConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionOutput) LabelSelector() QperfSpecClientConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorPtrOutput {\n\treturn o.ApplyT(func(v QperfSpecClientConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecution) *QperfSpecClientConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelector {\n\t\treturn v.LabelSelector\n\t}).(QperfSpecClientConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorPtrOutput)\n}", "func unionSelector(a, b Selector) Selector {\n\treturn func(n *Node) bool {\n\t\treturn a(n) || b(n)\n\t}\n}" ]
[ "0.55560446", "0.55550456", "0.5418782", "0.5232401", "0.516599", "0.51499623", "0.51457506", "0.50850743", "0.5066663", "0.50539064", "0.50173676", "0.5006262", "0.4976947", "0.4937381", "0.49275225", "0.4902265", "0.48829624", "0.48598814", "0.4855713", "0.48544148", "0.48372066", "0.48215005", "0.48024172", "0.47968346", "0.47936878", "0.47577813", "0.4753775", "0.4753775", "0.47466975", "0.4730676", "0.47275406", "0.4726525", "0.4704904", "0.47026923", "0.469297", "0.46729922", "0.46625102", "0.4662102", "0.4662102", "0.46546888", "0.46487656", "0.46442538", "0.46302068", "0.46290714", "0.46163353", "0.46081942", "0.4597833", "0.45947385", "0.45822936", "0.45433423", "0.45375666", "0.45277503", "0.45277503", "0.45272678", "0.45221284", "0.45183486", "0.44985548", "0.44978473", "0.44737914", "0.4467201", "0.44617817", "0.4461108", "0.44593117", "0.44574144", "0.4448311", "0.44433576", "0.4438826", "0.44333026", "0.44316313", "0.44200343", "0.44116256", "0.4400409", "0.43989184", "0.43961635", "0.43872714", "0.4386149", "0.43807283", "0.4373839", "0.43732092", "0.43730596", "0.4372654", "0.43718868", "0.43612388", "0.43605718", "0.43597206", "0.43573833", "0.43563017", "0.4349891", "0.43484604", "0.4348276", "0.43471542", "0.43439007", "0.43432158", "0.43413112", "0.43375373", "0.43364325", "0.43351242", "0.4333098", "0.43324894", "0.4326722" ]
0.7420431
0
SupportCAS registers a version constrained compareandset flag in flagSet, storing the value provided in p. This enables commands using API methods that operate on existing resources to take a version string to be used as an update constraint. The returned closure indicates whether the flag was given a value. It will replace the flag lookup for "cas".
func SupportCAS(flagSet *pflag.FlagSet, p *string) func() bool { const casName = "cas" flagSet.StringVar(p, casName, "", "make changes to a resource conditional upon matching the provided version") return func() bool { return flagSet.Changed(casName) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func SupportCASWithRestrictions(flagSet *pflag.FlagSet, p *string, restrictions map[string]string) func() bool {\n\tconst casName = \"cas\"\n\n\tdescription := \"make changes to a resource conditional upon matching the provided version\"\n\n\tif len(restrictions) > 0 {\n\t\tdescription += \". Valid only if \"\n\t\tfor k, v := range restrictions {\n\t\t\tdescription += fmt.Sprintf(\"%s=%s \", k, v)\n\t\t}\n\t}\n\n\tflagSet.StringVar(p, casName, \"\", description)\n\n\treturn func() bool {\n\t\treturn flagSet.Changed(casName)\n\t}\n}", "func (k *KV) CAS(p *KVPair, q *WriteOptions) (bool, *WriteMeta, error) {\n\tparams := make(map[string]string, 2)\n\tif p.Flags != 0 {\n\t\tparams[\"flags\"] = strconv.FormatUint(p.Flags, 10)\n\t}\n\tparams[\"cas\"] = strconv.FormatUint(p.ModifyIndex, 10)\n\treturn k.put(p.Key, params, p.Value, q)\n}", "func (client *Client) CAS(vb uint16, k string, f CasFunc,\n\tinitexp int) (rv *gomemcached.MCResponse, err error) {\n\n\tflags := 0\n\texp := 0\n\n\tfor {\n\t\torig, err := client.Get(vb, k)\n\t\tif err != nil && orig != nil && orig.Status != gomemcached.KEY_ENOENT {\n\t\t\treturn rv, err\n\t\t}\n\n\t\tif orig.Status == gomemcached.KEY_ENOENT {\n\t\t\tinit := f([]byte{})\n\t\t\t// If it doesn't exist, add it\n\t\t\tresp, err := client.Add(vb, k, 0, initexp, init)\n\t\t\tif err == nil && resp.Status != gomemcached.KEY_EEXISTS {\n\t\t\t\treturn rv, err\n\t\t\t}\n\t\t\t// Copy the body into this response.\n\t\t\tresp.Body = init\n\t\t\treturn resp, err\n\t\t} else {\n\t\t\treq := &gomemcached.MCRequest{\n\t\t\t\tOpcode: gomemcached.SET,\n\t\t\t\tVBucket: vb,\n\t\t\t\tKey: []byte(k),\n\t\t\t\tCas: orig.Cas,\n\t\t\t\tOpaque: 0,\n\t\t\t\tExtras: []byte{0, 0, 0, 0, 0, 0, 0, 0},\n\t\t\t\tBody: f(orig.Body)}\n\n\t\t\tbinary.BigEndian.PutUint64(req.Extras, uint64(flags)<<32|uint64(exp))\n\t\t\tresp, err := client.Send(req)\n\t\t\tif err == nil {\n\t\t\t\treturn resp, nil\n\t\t\t}\n\t\t}\n\t}\n\tpanic(\"Unreachable\")\n}", "func (f *Flag) Set() { atomic.CompareAndSwapUint32((*uint32)(unsafe.Pointer(f)), 0, 1) }", "func (db *DBDriver) CAS(ctx context.Context, member, key string, nonce, origValue, value []byte) ([]byte, error) {\n\tctx, tx, err := dbtx.BeginTx(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer db.reapTx(tx)\n\n\tbuf, err := randomBuf()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcount, err := models.Kvstores(\n\t\tmodels.KvstoreWhere.Member.EQ(member),\n\t\tmodels.KvstoreWhere.Key.EQ(key),\n\t\tmodels.KvstoreWhere.Value.EQ(origValue),\n\t\tmodels.KvstoreWhere.Nonce.EQ(nonce),\n\t).UpdateAll(ctx, tx, models.M{\"value\": value, \"nonce\": buf})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif count == 0 {\n\t\tif _, _, err := db.get(ctx, tx, member, key); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, ErrNotEqual\n\t}\n\n\treturn buf, tx.Commit()\n}", "func (*bzlLibraryLang) RegisterFlags(fs *flag.FlagSet, cmd string, c *config.Config) {}", "func CClosureMarshalBooleanFlags(closure *Closure, returnValue *Value, nParamValues uint32, paramValues *Value, invocationHint uintptr, marshalData uintptr) {\n\tc_closure := (*C.GClosure)(C.NULL)\n\tif closure != nil {\n\t\tc_closure = (*C.GClosure)(closure.ToC())\n\t}\n\n\tc_return_value := (*C.GValue)(C.NULL)\n\tif returnValue != nil {\n\t\tc_return_value = (*C.GValue)(returnValue.ToC())\n\t}\n\n\tc_n_param_values := (C.guint)(nParamValues)\n\n\tc_param_values := (*C.GValue)(C.NULL)\n\tif paramValues != nil {\n\t\tc_param_values = (*C.GValue)(paramValues.ToC())\n\t}\n\n\tc_invocation_hint := (C.gpointer)(invocationHint)\n\n\tc_marshal_data := (C.gpointer)(marshalData)\n\n\tC.g_cclosure_marshal_BOOLEAN__FLAGS(c_closure, c_return_value, c_n_param_values, c_param_values, c_invocation_hint, c_marshal_data)\n\n\treturn\n}", "func (m *mCryptographyServiceMockVerify) Set(f func(p crypto.PublicKey, p1 insolar.Signature, p2 []byte) (r bool)) *CryptographyServiceMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.VerifyFunc = f\n\treturn m.mock\n}", "func Set(name, value string) bool {\n\tf, ok := flags.formal[name];\n\tif !ok {\n\t\treturn false\n\t}\n\tok = f.Value.set(value);\n\tif !ok {\n\t\treturn false\n\t}\n\tflags.actual[name] = f;\n\treturn true;\n}", "func (r *Registers) setFlagC(bit bool) {\n\tif bit {\n\t\t// 1110 | 0001 => 1111\n\t\t// 1111 | 0001 => 1111\n\t\tr.F |= carryFlag\n\t} else {\n\t\t// 1010 & 1110 => 1010\n\t\t// 1011 & 1110 => 1010\n\t\tr.F = r.F &^ carryFlag\n\t}\n}", "func (c *consulClient) CAS(ctx context.Context, key string, out interface{}, f CASCallback) error {\n\tspan, ctx := opentracing.StartSpanFromContext(ctx, \"Consul CAS\", opentracing.Tag{Key: \"key\", Value: key})\n\tdefer span.Finish()\n\tvar (\n\t\tindex = uint64(0)\n\t\tretries = 10\n\t\tretry = true\n\t\tintermediate interface{}\n\t)\n\tfor i := 0; i < retries; i++ {\n\t\tkvp, _, err := c.kv.Get(key, queryOptions)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error getting %s: %v\", key, err)\n\t\t\tcontinue\n\t\t}\n\t\tif kvp != nil {\n\t\t\tif err := json.NewDecoder(bytes.NewReader(kvp.Value)).Decode(out); err != nil {\n\t\t\t\tlog.Errorf(\"Error deserialising %s: %v\", key, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tindex = kvp.ModifyIndex // if key doesn't exist, index will be 0\n\t\t\tintermediate = out\n\t\t}\n\n\t\tintermediate, retry, err = f(intermediate)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error CASing %s: %v\", key, err)\n\t\t\tif !retry {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif intermediate == nil {\n\t\t\tpanic(\"Callback must instantiate value!\")\n\t\t}\n\n\t\tvalue := bytes.Buffer{}\n\t\tif err := json.NewEncoder(&value).Encode(intermediate); err != nil {\n\t\t\tlog.Errorf(\"Error serialising value for %s: %v\", key, err)\n\t\t\tcontinue\n\t\t}\n\t\tok, _, err := c.kv.CAS(&consul.KVPair{\n\t\t\tKey: key,\n\t\t\tValue: value.Bytes(),\n\t\t\tModifyIndex: index,\n\t\t}, writeOptions)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error CASing %s: %v\", key, err)\n\t\t\tcontinue\n\t\t}\n\t\tif !ok {\n\t\t\tlog.Errorf(\"Error CASing %s, trying again %d\", key, index)\n\t\t\tcontinue\n\t\t}\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"Failed to CAS %s\", key)\n}", "func (ab *ABool) Set(b bool) {\n\tvar val int32\n\tif b {\n\t\tval = 1\n\t}\n\tatomic.StoreInt32(&ab.flag, val)\n}", "func registerFlags() {\n\tcfsslFlagSet.StringVar(&Config.hostname, \"hostname\", \"\", \"Hostname for the cert\")\n\tcfsslFlagSet.StringVar(&Config.certFile, \"cert\", \"\", \"Client certificate that contains the public key\")\n\tcfsslFlagSet.StringVar(&Config.csrFile, \"csr\", \"\", \"Certificate signature request file for new public key\")\n\tcfsslFlagSet.StringVar(&Config.caFile, \"ca\", \"ca.pem\", \"CA used to sign the new certificate\")\n\tcfsslFlagSet.StringVar(&Config.caKeyFile, \"ca-key\", \"ca-key.pem\", \"CA private key\")\n\tcfsslFlagSet.StringVar(&Config.keyFile, \"key\", \"\", \"private key for the certificate\")\n\tcfsslFlagSet.StringVar(&Config.intermediatesFile, \"intermediates\", \"\", \"intermediate certs\")\n\tcfsslFlagSet.StringVar(&Config.caBundleFile, \"ca-bundle\", \"/etc/cfssl/ca-bundle.crt\", \"Bundle to be used for root certificates pool\")\n\tcfsslFlagSet.StringVar(&Config.intBundleFile, \"int-bundle\", \"/etc/cfssl/int-bundle.crt\", \"Bundle to be used for intermediate certificates pool\")\n\tcfsslFlagSet.StringVar(&Config.address, \"address\", \"127.0.0.1\", \"Address to bind\")\n\tcfsslFlagSet.IntVar(&Config.port, \"port\", 8888, \"Port to bind\")\n\tcfsslFlagSet.StringVar(&Config.configFile, \"f\", \"\", \"path to configuration file\")\n\tcfsslFlagSet.StringVar(&Config.profile, \"profile\", \"\", \"signing profile to use\")\n\tcfsslFlagSet.BoolVar(&Config.isCA, \"initca\", false, \"initialise new CA\")\n\tcfsslFlagSet.StringVar(&Config.intDir, \"int-dir\", \"/etc/cfssl/intermediates\", \"specify intermediates directory\")\n\tcfsslFlagSet.StringVar(&Config.flavor, \"flavor\", \"ubiquitous\", \"Bundle Flavor: ubiquitous, optimal and force.\")\n\tcfsslFlagSet.StringVar(&Config.metadata, \"metadata\", \"/etc/cfssl/ca-bundle.crt.metadata\", \"Metadata file for root certificate presence. The content of the file is a json dictionary (k,v): each key k is SHA-1 digest of a root certificate while value v is a list of key store filenames.\")\n\tcfsslFlagSet.StringVar(&Config.domain, \"domain\", \"\", \"remote server domain name\")\n\tcfsslFlagSet.StringVar(&Config.ip, \"ip\", \"\", \"remote server ip\")\n\tcfsslFlagSet.StringVar(&Config.remote, \"remote\", \"\", \"remote CFSSL server\")\n}", "func flagSet(name string, cfg *CmdConfig) *flag.FlagSet {\n\tflags := flag.NewFlagSet(name, flag.ExitOnError)\n\tflags.StringVar(\n\t\t&cfg.ConfigPath,\n\t\t\"config-path\",\n\t\tsetFromEnvStr(\"CONFIG_PATH\", \"/repo\"),\n\t\t\"Configuration root directory. Should include the '.porter' or 'environment' directory. \"+\n\t\t\t\"Kubernetes object yaml files may be in the directory or in a subdirectory named 'k8s'.\",\n\t)\n\tflags.StringVar(&cfg.ConfigType, \"config-type\", setFromEnvStr(\"CONFIG_TYPE\", \"porter\"), \"Configuration type, \"+\n\t\t\"simple or porter.\")\n\tflags.StringVar(&cfg.Environment, \"environment\", setFromEnvStr(\"ENVIRONMENT\", \"\"), \"Environment of deployment.\")\n\tflags.IntVar(&cfg.MaxConfigMaps, \"max-cm\", setFromEnvInt(\"MAX_CM\", 5), \"Maximum number of configmaps and secret \"+\n\t\t\"objects to keep per app.\")\n\tflags.StringVar(&cfg.Namespace, \"namespace\", setFromEnvStr(\"NAMESPACE\", \"default\"), \"Kubernetes namespace.\")\n\tflags.StringVar(&cfg.Regions, \"regions\", setFromEnvStr(\"REGIONS\", \"\"), \"Regions\"+\n\t\t\"of deployment. (Multiple Space delimited regions allowed)\")\n\tflags.StringVar(&cfg.SHA, \"sha\", setFromEnvStr(\"sha\", \"\"), \"Deployment sha.\")\n\tflags.StringVar(&cfg.VaultAddress, \"vault-addr\", setFromEnvStr(\"VAULT_ADDR\", \"https://vault.loc.adobe.net\"),\n\t\t\"Vault server.\")\n\tflags.StringVar(&cfg.VaultBasePath, \"vault-path\", setFromEnvStr(\"VAULT_PATH\", \"/\"), \"Path in Vault.\")\n\tflags.StringVar(&cfg.VaultToken, \"vault-token\", setFromEnvStr(\"VAULT_TOKEN\", \"\"), \"Vault token.\")\n\tflags.StringVar(&cfg.SecretPathWhiteList, \"secret-path-whitelist\", setFromEnvStr(\"SECRET_PATH_WHITELIST\", \"\"), \"\"+\n\t\t\"Multiple Space delimited secret path whitelist allowed\")\n\tflags.BoolVar(&cfg.Verbose, \"v\", setFromEnvBool(\"VERBOSE\"), \"Verbose log output.\")\n\tflags.IntVar(&cfg.Wait, \"wait\", setFromEnvInt(\"WAIT\", 180), \"Extra time to wait for deployment to complete in \"+\n\t\t\"seconds.\")\n\tflags.StringVar(&cfg.LogMode, \"log-mode\", setFromEnvStr(\"LOG_MODE\", \"inline\"), \"Pod log streaming mode. \"+\n\t\t\"One of 'inline' (print to porter2k8s log), 'file' (write to filesystem, see log-dir option), \"+\n\t\t\"'none' (disable log streaming)\")\n\tflags.StringVar(&cfg.LogDir, \"log-dir\", setFromEnvStr(\"LOG_DIR\", \"logs\"),\n\t\t\"Directory to write pod logs into. (must already exist)\")\n\n\treturn flags\n}", "func isFlagSet(cflags uint32, c cflag) (bool) {\n if (cflags & uint32(c)) != 0 {\n return true\n }\n return false\n}", "func (x *fastReflection_FlagOptions) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif x.Name != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.Name)\n\t\tif !f(fd_FlagOptions_name, value) {\n\t\t\treturn\n\t\t}\n\t}\n\tif x.Shorthand != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.Shorthand)\n\t\tif !f(fd_FlagOptions_shorthand, value) {\n\t\t\treturn\n\t\t}\n\t}\n\tif x.Usage != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.Usage)\n\t\tif !f(fd_FlagOptions_usage, value) {\n\t\t\treturn\n\t\t}\n\t}\n\tif x.DefaultValue != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.DefaultValue)\n\t\tif !f(fd_FlagOptions_default_value, value) {\n\t\t\treturn\n\t\t}\n\t}\n\tif x.Deprecated != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.Deprecated)\n\t\tif !f(fd_FlagOptions_deprecated, value) {\n\t\t\treturn\n\t\t}\n\t}\n\tif x.ShorthandDeprecated != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.ShorthandDeprecated)\n\t\tif !f(fd_FlagOptions_shorthand_deprecated, value) {\n\t\t\treturn\n\t\t}\n\t}\n\tif x.Hidden != false {\n\t\tvalue := protoreflect.ValueOfBool(x.Hidden)\n\t\tif !f(fd_FlagOptions_hidden, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func NewSetFlag(base ParserProvider) ParserProvider {\n\treturn &setFlagProvider{\n\t\tbase: base,\n\t}\n}", "func (at *Time) CAS(old, new time.Time) bool {\n\treturn at.v.CAS(old.UnixNano(), new.UnixNano())\n}", "func GRPCSupport() bool {\n\tverString := os.Getenv(PluginVaultVersionEnv)\n\n\t// If the env var is empty, we fall back to netrpc for backward compatibility.\n\tif verString == \"\" {\n\t\treturn false\n\t}\n\n\tif verString != \"unknown\" {\n\t\tver, err := version.NewVersion(verString)\n\t\tif err != nil {\n\t\t\treturn true\n\t\t}\n\n\t\t// Due to some regressions on 0.9.2 & 0.9.3 we now require version 0.9.4\n\t\t// to allow the plugin framework to default to gRPC.\n\t\tconstraint, err := version.NewConstraint(\">= 0.9.4\")\n\t\tif err != nil {\n\t\t\treturn true\n\t\t}\n\n\t\treturn constraint.Check(ver)\n\t}\n\n\treturn true\n}", "func initializePFlagMap() {\n\tpflagValueFuncMap = map[FlagType]newPFlagValueFunc{\n\t\tuuidFlag: func() pflag.Value {\n\t\t\t// this corresponds to the merkle leaf hash of entries, which is represented by a 64 character hexadecimal string\n\t\t\treturn valueFactory(uuidFlag, validateString(\"required,len=64,hexadecimal\"), \"\")\n\t\t},\n\t\tshaFlag: func() pflag.Value {\n\t\t\t// this validates a valid sha256 checksum which is optionally prefixed with 'sha256:'\n\t\t\treturn valueFactory(shaFlag, validateSHA256Value, \"\")\n\t\t},\n\t\temailFlag: func() pflag.Value {\n\t\t\t// this validates an email address\n\t\t\treturn valueFactory(emailFlag, validateString(\"required,email\"), \"\")\n\t\t},\n\t\tlogIndexFlag: func() pflag.Value {\n\t\t\t// this checks for a valid integer >= 0\n\t\t\treturn valueFactory(logIndexFlag, validateLogIndex, \"\")\n\t\t},\n\t\tpkiFormatFlag: func() pflag.Value {\n\t\t\t// this ensures a PKI implementation exists for the requested format\n\t\t\treturn valueFactory(pkiFormatFlag, validateString(fmt.Sprintf(\"required,oneof=%v\", strings.Join(pki.SupportedFormats(), \" \"))), \"pgp\")\n\t\t},\n\t\ttypeFlag: func() pflag.Value {\n\t\t\t// this ensures the type of the log entry matches a type supported in the CLI\n\t\t\treturn valueFactory(typeFlag, validateTypeFlag, \"rekord\")\n\t\t},\n\t\tfileFlag: func() pflag.Value {\n\t\t\t// this validates that the file exists and can be opened by the current uid\n\t\t\treturn valueFactory(fileFlag, validateString(\"required,file\"), \"\")\n\t\t},\n\t\turlFlag: func() pflag.Value {\n\t\t\t// this validates that the string is a valid http/https URL\n\t\t\treturn valueFactory(urlFlag, validateString(\"required,url,startswith=http|startswith=https\"), \"\")\n\t\t},\n\t\tfileOrURLFlag: func() pflag.Value {\n\t\t\t// applies logic of fileFlag OR urlFlag validators from above\n\t\t\treturn valueFactory(fileOrURLFlag, validateFileOrURL, \"\")\n\t\t},\n\t\toidFlag: func() pflag.Value {\n\t\t\t// this validates for an OID, which is a sequence of positive integers separated by periods\n\t\t\treturn valueFactory(oidFlag, validateOID, \"\")\n\t\t},\n\t\tformatFlag: func() pflag.Value {\n\t\t\t// this validates the output format requested\n\t\t\treturn valueFactory(formatFlag, validateString(\"required,oneof=json default\"), \"\")\n\t\t},\n\t\ttimeoutFlag: func() pflag.Value {\n\t\t\t// this validates the timeout is >= 0\n\t\t\treturn valueFactory(formatFlag, validateTimeout, \"\")\n\t\t},\n\t}\n}", "func checkStringFlagReplaceWithUtilVersion(name string, arg string, compulsory bool) (exists bool) {\n\tvar hasArg bool\n\n\tif arg != \"\" {\n\t\texists = true\n\t}\n\n\t// Try to detect missing flag argument.\n\t// If an argument is another flag, argument has not been provided.\n\tif exists && !strings.HasPrefix(arg, \"-\") {\n\t\t// Option expecting an argument but has been followed by another flag.\n\t\thasArg = true\n\t}\n\t/*\n\t\twhere(fmt.Sprintf(\"-%s compulsory = %t\", name, compulsory))\n\t\twhere(fmt.Sprintf(\"-%s exists = %t\", name, exists))\n\t\twhere(fmt.Sprintf(\"-%s hasArg = %t\", name, hasArg))\n\t\twhere(fmt.Sprintf(\"-%s value = %s\", name, arg))\n\t*/\n\n\tif compulsory && !exists {\n\t\tfmt.Fprintf(os.Stderr, \"compulsory flag: -%s\\n\", name)\n\t\tprintUsage()\n\t\tos.Exit(2)\n\t}\n\n\tif exists && !hasArg {\n\t\tfmt.Fprintf(os.Stderr, \"flag -%s needs a valid argument (not: %s)\\n\", name, arg)\n\t\tprintUsage()\n\t\tos.Exit(3)\n\t}\n\n\treturn\n}", "func (f futexChecker) Op(addr uintptr, opIn uint32) (bool, error) {\n\top := (opIn >> 28) & 0xf\n\tcmp := (opIn >> 24) & 0xf\n\topArg := (opIn >> 12) & 0xfff\n\tcmpArg := opIn & 0xfff\n\n\tif op&linux.FUTEX_OP_OPARG_SHIFT != 0 {\n\t\topArg = 1 << opArg\n\t\top &^= linux.FUTEX_OP_OPARG_SHIFT // clear flag\n\t}\n\n\tvar oldVal uint32\n\tvar err error\n\tswitch op {\n\tcase linux.FUTEX_OP_SET:\n\t\toldVal, err = f.t.MemoryManager().SwapUint32(f.t, usermem.Addr(addr), opArg, usermem.IOOpts{\n\t\t\tAddressSpaceActive: true,\n\t\t})\n\tcase linux.FUTEX_OP_ADD:\n\t\toldVal, err = f.atomicOp(addr, func(a uint32) uint32 {\n\t\t\treturn a + opArg\n\t\t})\n\tcase linux.FUTEX_OP_OR:\n\t\toldVal, err = f.atomicOp(addr, func(a uint32) uint32 {\n\t\t\treturn a | opArg\n\t\t})\n\tcase linux.FUTEX_OP_ANDN:\n\t\toldVal, err = f.atomicOp(addr, func(a uint32) uint32 {\n\t\t\treturn a &^ opArg\n\t\t})\n\tcase linux.FUTEX_OP_XOR:\n\t\toldVal, err = f.atomicOp(addr, func(a uint32) uint32 {\n\t\t\treturn a ^ opArg\n\t\t})\n\tdefault:\n\t\treturn false, syserror.ENOSYS\n\t}\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tswitch cmp {\n\tcase linux.FUTEX_OP_CMP_EQ:\n\t\treturn oldVal == cmpArg, nil\n\tcase linux.FUTEX_OP_CMP_NE:\n\t\treturn oldVal != cmpArg, nil\n\tcase linux.FUTEX_OP_CMP_LT:\n\t\treturn oldVal < cmpArg, nil\n\tcase linux.FUTEX_OP_CMP_LE:\n\t\treturn oldVal <= cmpArg, nil\n\tcase linux.FUTEX_OP_CMP_GT:\n\t\treturn oldVal > cmpArg, nil\n\tcase linux.FUTEX_OP_CMP_GE:\n\t\treturn oldVal >= cmpArg, nil\n\tdefault:\n\t\treturn false, syserror.ENOSYS\n\t}\n}", "func (cfg *Config) RegisterFlags(f *flag.FlagSet) {\n\tcfg.ShardingRing.RegisterFlags(f)\n\n\tcfg.BlockRanges = cortex_tsdb.DurationList{2 * time.Hour, 12 * time.Hour, 24 * time.Hour}\n\tcfg.retryMinBackoff = 10 * time.Second\n\tcfg.retryMaxBackoff = time.Minute\n\n\tf.Var(&cfg.BlockRanges, \"compactor.block-ranges\", \"List of compaction time ranges.\")\n\tf.DurationVar(&cfg.ConsistencyDelay, \"compactor.consistency-delay\", 0, fmt.Sprintf(\"Minimum age of fresh (non-compacted) blocks before they are being processed. Malformed blocks older than the maximum of consistency-delay and %s will be removed.\", compact.PartialUploadThresholdAge))\n\tf.IntVar(&cfg.BlockSyncConcurrency, \"compactor.block-sync-concurrency\", 20, \"Number of Go routines to use when syncing block index and chunks files from the long term storage.\")\n\tf.IntVar(&cfg.MetaSyncConcurrency, \"compactor.meta-sync-concurrency\", 20, \"Number of Go routines to use when syncing block meta files from the long term storage.\")\n\tf.StringVar(&cfg.DataDir, \"compactor.data-dir\", \"./data\", \"Data directory in which to cache blocks and process compactions\")\n\tf.DurationVar(&cfg.CompactionInterval, \"compactor.compaction-interval\", time.Hour, \"The frequency at which the compaction runs\")\n\tf.IntVar(&cfg.CompactionRetries, \"compactor.compaction-retries\", 3, \"How many times to retry a failed compaction within a single compaction run.\")\n\tf.IntVar(&cfg.CompactionConcurrency, \"compactor.compaction-concurrency\", 1, \"Max number of concurrent compactions running.\")\n\tf.DurationVar(&cfg.CleanupInterval, \"compactor.cleanup-interval\", 15*time.Minute, \"How frequently compactor should run blocks cleanup and maintenance, as well as update the bucket index.\")\n\tf.IntVar(&cfg.CleanupConcurrency, \"compactor.cleanup-concurrency\", 20, \"Max number of tenants for which blocks cleanup and maintenance should run concurrently.\")\n\tf.BoolVar(&cfg.ShardingEnabled, \"compactor.sharding-enabled\", false, \"Shard tenants across multiple compactor instances. Sharding is required if you run multiple compactor instances, in order to coordinate compactions and avoid race conditions leading to the same tenant blocks simultaneously compacted by different instances.\")\n\tf.StringVar(&cfg.ShardingStrategy, \"compactor.sharding-strategy\", util.ShardingStrategyDefault, fmt.Sprintf(\"The sharding strategy to use. Supported values are: %s.\", strings.Join(supportedShardingStrategies, \", \")))\n\tf.DurationVar(&cfg.DeletionDelay, \"compactor.deletion-delay\", 12*time.Hour, \"Time before a block marked for deletion is deleted from bucket. \"+\n\t\t\"If not 0, blocks will be marked for deletion and compactor component will permanently delete blocks marked for deletion from the bucket. \"+\n\t\t\"If 0, blocks will be deleted straight away. Note that deleting blocks immediately can cause query failures.\")\n\tf.DurationVar(&cfg.TenantCleanupDelay, \"compactor.tenant-cleanup-delay\", 6*time.Hour, \"For tenants marked for deletion, this is time between deleting of last block, and doing final cleanup (marker files, debug files) of the tenant.\")\n\tf.BoolVar(&cfg.BlockDeletionMarksMigrationEnabled, \"compactor.block-deletion-marks-migration-enabled\", false, \"When enabled, at compactor startup the bucket will be scanned and all found deletion marks inside the block location will be copied to the markers global location too. This option can (and should) be safely disabled as soon as the compactor has successfully run at least once.\")\n\tf.BoolVar(&cfg.SkipBlocksWithOutOfOrderChunksEnabled, \"compactor.skip-blocks-with-out-of-order-chunks-enabled\", false, \"When enabled, mark blocks containing index with out-of-order chunks for no compact instead of halting the compaction.\")\n\tf.IntVar(&cfg.BlockFilesConcurrency, \"compactor.block-files-concurrency\", 10, \"Number of goroutines to use when fetching/uploading block files from object storage.\")\n\tf.IntVar(&cfg.BlocksFetchConcurrency, \"compactor.blocks-fetch-concurrency\", 3, \"Number of goroutines to use when fetching blocks from object storage when compacting.\")\n\n\tf.Var(&cfg.EnabledTenants, \"compactor.enabled-tenants\", \"Comma separated list of tenants that can be compacted. If specified, only these tenants will be compacted by compactor, otherwise all tenants can be compacted. Subject to sharding.\")\n\tf.Var(&cfg.DisabledTenants, \"compactor.disabled-tenants\", \"Comma separated list of tenants that cannot be compacted by this compactor. If specified, and compactor would normally pick given tenant for compaction (via -compactor.enabled-tenants or sharding), it will be ignored instead.\")\n\n\tf.DurationVar(&cfg.BlockVisitMarkerTimeout, \"compactor.block-visit-marker-timeout\", 5*time.Minute, \"How long block visit marker file should be considered as expired and able to be picked up by compactor again.\")\n\tf.DurationVar(&cfg.BlockVisitMarkerFileUpdateInterval, \"compactor.block-visit-marker-file-update-interval\", 1*time.Minute, \"How frequently block visit marker file should be updated duration compaction.\")\n\n\tf.BoolVar(&cfg.AcceptMalformedIndex, \"compactor.accept-malformed-index\", false, \"When enabled, index verification will ignore out of order label names.\")\n}", "func ResourceApplyAddSignUseLocking(value bool) ResourceApplyAddSignAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"use_locking\"] = value\n\t}\n}", "func (m *UpdateAllowedCombinationsResult) SetConditionalAccessReferences(value []string)() {\n err := m.GetBackingStore().Set(\"conditionalAccessReferences\", value)\n if err != nil {\n panic(err)\n }\n}", "func (f *PluginAPIClientMeta) FlagSet() *flag.FlagSet {\n\tfs := flag.NewFlagSet(\"vault plugin settings\", flag.ContinueOnError)\n\n\tfs.StringVar(&f.flagCACert, \"ca-cert\", \"\", \"\")\n\tfs.StringVar(&f.flagCAPath, \"ca-path\", \"\", \"\")\n\tfs.StringVar(&f.flagClientCert, \"client-cert\", \"\", \"\")\n\tfs.StringVar(&f.flagClientKey, \"client-key\", \"\", \"\")\n\tfs.BoolVar(&f.flagInsecure, \"tls-skip-verify\", false, \"\")\n\n\treturn fs\n}", "func AtomicSet(v *Var, val interface{}) {\n\t// since we're only doing one operation, we don't need a full transaction\n\tglobalLock.Lock()\n\tv.mu.Lock()\n\tv.val = val\n\tv.version++\n\tv.mu.Unlock()\n\tglobalCond.Broadcast()\n\tglobalLock.Unlock()\n}", "func pflagRegister(global, local *pflag.FlagSet, globalName string) {\n\tif f := global.Lookup(globalName); f != nil {\n\t\tf.Name = normalize(f.Name)\n\t\tlocal.AddFlag(f)\n\t} else {\n\t\tpanic(fmt.Sprintf(\"failed to find flag in global flagset (pflag): %s\", globalName))\n\t}\n}", "func (e Enum) FlagSet(v any, key string) error {\n\treturn e.setValue(v, key)\n}", "func (t tagSet) cas(i, j int) {\n\tif t[i].key > t[j].key {\n\t\tt.Swap(i, j)\n\t}\n}", "func (f *Flag) Set() {\n\tatomic.StoreInt32(&f.flag, 1)\n}", "func cx(v *vm.State, o vm.Opcode) error {\n\tif cond, err := v.Flags.Condition(o.X()); err != nil {\n\t\treturn err\n\t} else if cond {\n\t\tcall(v, vm.Pointer(o.HHLL()))\n\t}\n\treturn nil\n}", "func addCredentialProviderFlags(fs *pflag.FlagSet) {\n\t// lookup flags in global flag set and re-register the values with our flagset\n\tglobal := pflag.CommandLine\n\tlocal := pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)\n\n\taddLegacyCloudProviderCredentialProviderFlags(global, local)\n\n\tfs.AddFlagSet(local)\n}", "func (r *FeatureGateVersionRange) Contains(version string) (bool, error) {\n\tvar constraint string\n\tswitch {\n\tcase r.AddedInVersion != \"\" && r.RemovedInVersion == \"\":\n\t\tconstraint = fmt.Sprintf(\">= %s\", r.AddedInVersion)\n\tcase r.AddedInVersion == \"\" && r.RemovedInVersion != \"\":\n\t\tconstraint = fmt.Sprintf(\"< %s\", r.RemovedInVersion)\n\tcase r.AddedInVersion != \"\" && r.RemovedInVersion != \"\":\n\t\tconstraint = fmt.Sprintf(\">= %s, < %s\", r.AddedInVersion, r.RemovedInVersion)\n\tdefault:\n\t\tconstraint = \"*\"\n\t}\n\treturn utilsversion.CheckVersionMeetsConstraint(version, constraint)\n}", "func CASTemplateFeatureGate() (bool, error) {\n\treturn strconv.ParseBool(lookEnv(CASTemplateFeatureGateENVK))\n}", "func (i *Int64) CAS(old, new int64) bool {\n\treturn atomic.CompareAndSwapInt64((*int64)(i), old, new)\n}", "func InitFeatureFlags(flag *pflag.FlagSet) {\n\tflag.Bool(FeatureFlagAccessCode, false, \"Flag (bool) to enable requires-access-code\")\n\tflag.Bool(FeatureFlagRoleBasedAuth, false, \"Flag (bool) to enable role-based-auth\")\n\tflag.Bool(FeatureFlagConvertPPMsToGHC, false, \"Flag (bool) to enable convert-ppms-to-ghc\")\n}", "func (k *KV) Acquire(p *KVPair, q *WriteOptions) (bool, *WriteMeta, error) {\n\tparams := make(map[string]string, 2)\n\tif p.Flags != 0 {\n\t\tparams[\"flags\"] = strconv.FormatUint(p.Flags, 10)\n\t}\n\tparams[\"acquire\"] = p.Session\n\treturn k.put(p.Key, params, p.Value, q)\n}", "func (mmDone *mFlagMockDone) Set(f func(ctx context.Context, isDone func() bool)) *FlagMock {\n\tif mmDone.defaultExpectation != nil {\n\t\tmmDone.mock.t.Fatalf(\"Default expectation is already set for the Flag.Done method\")\n\t}\n\n\tif len(mmDone.expectations) > 0 {\n\t\tmmDone.mock.t.Fatalf(\"Some expectations are already set for the Flag.Done method\")\n\t}\n\n\tmmDone.mock.funcDone = f\n\treturn mmDone.mock\n}", "func (b *bitVec) set(n uint) bool {\n\tpos, slot := b.calculateBitLocation(n)\n\tif b.get(n) { // bit was set\n\t\treturn true\n\t} else { // set the bit\n\t\tb.bits[pos] = b.bits[pos] | 1<<slot\n\t\treturn false\n\t}\n}", "func checkCompilerFlag(flag string, languages []string, tc toolchain) string {\n\tfor _, lang := range languages {\n\t\tif tc.checkFlagIsSupported(lang, flag) {\n\t\t\treturn flag\n\t\t}\n\t}\n\treturn \"\"\n}", "func (c *Config) RegisterFlagsWithPrefix(prefix string, f *pflag.FlagSet) {\n}", "func getFlag(query bool, authority bool) uint16 {\n\tvar out uint16\n\tif !query {\n\t\tout |= 1\n\t}\n\tif authority {\n\t\tout |= 1 << 5\n\t}\n\treturn out\n}", "func getFlag(query bool, authority bool) uint16 {\n\tvar out uint16\n\tif !query {\n\t\tout |= 1\n\t}\n\tif authority {\n\t\tout |= 1 << 5\n\t}\n\treturn out\n}", "func (f *Factory) SetFlags() {\n}", "func AddFlagSetProvider(f FlagSetProvider) {\n\te.AddFlagSetProvider(f)\n}", "func WithCASValue(cas uint64) MutationOpt {\n\treturn func(req *internal.Request) {\n\t\treq.CAS = cas\n\t}\n}", "func CfnIPSet_IsConstruct(x interface{}) *bool {\n\t_init_.Initialize()\n\n\tvar returns *bool\n\n\t_jsii_.StaticInvoke(\n\t\t\"monocdk.aws_guardduty.CfnIPSet\",\n\t\t\"isConstruct\",\n\t\t[]interface{}{x},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (llrb *LLRB) SetCAS(\n\tkey, value, oldvalue []byte, cas uint64) ([]byte, uint64, error) {\n\n\tif !llrb.lock() {\n\t\treturn nil, 0, fmt.Errorf(\"closed\")\n\t}\n\toldvalue, cas, err := llrb.setcas(key, value, oldvalue, cas)\n\tllrb.unlock()\n\n\treturn oldvalue, cas, err\n}", "func (msf *ModuleSetFlag) RegisterFlag(set *pflag.FlagSet, helpCommand string) {\n\tdescription := \"define the enabled modules (available modules: \" +\n\t\tmsf.availableModules.String() + \")\"\n\tif helpCommand != \"\" {\n\t\tdescription += \" use '\" + helpCommand + \"' for more information\"\n\t}\n\tif msf.shortFlag != \"\" {\n\t\tset.VarP(msf, msf.longFlag, msf.shortFlag, description)\n\t\treturn\n\t}\n\tset.Var(msf, msf.longFlag, description)\n}", "func (ctl *CRSpecBuilderFromCobraFlags) SetCRSpecFieldByFlag(f *pflag.Flag) {\n\tif f.Changed {\n\t\tlog.Debugf(\"flag '%s': CHANGED\", f.Name)\n\t\tswitch f.Name {\n\t\t// case \"enable-binary-analysis\", \"enable-source-code-upload\", \"environs\": - these are handled in addEnvironsFlagValues()\n\t\tcase \"size\":\n\t\t\tctl.blackDuckSpec.Size = ctl.Size\n\t\tcase \"version\":\n\t\t\tctl.blackDuckSpec.Version = ctl.Version\n\t\tcase \"expose-ui\":\n\t\t\tctl.blackDuckSpec.ExposeService = ctl.ExposeService\n\t\tcase \"db-prototype\":\n\t\t\tctl.blackDuckSpec.DbPrototype = ctl.DbPrototype\n\t\tcase \"external-postgres-host\":\n\t\t\tif ctl.blackDuckSpec.ExternalPostgres == nil {\n\t\t\t\tctl.blackDuckSpec.ExternalPostgres = &blackduckv1.PostgresExternalDBConfig{}\n\t\t\t}\n\t\t\tctl.blackDuckSpec.ExternalPostgres.PostgresHost = ctl.ExternalPostgresHost\n\t\tcase \"external-postgres-port\":\n\t\t\tif ctl.blackDuckSpec.ExternalPostgres == nil {\n\t\t\t\tctl.blackDuckSpec.ExternalPostgres = &blackduckv1.PostgresExternalDBConfig{}\n\t\t\t}\n\t\t\tctl.blackDuckSpec.ExternalPostgres.PostgresPort = ctl.ExternalPostgresPort\n\t\tcase \"external-postgres-admin\":\n\t\t\tif ctl.blackDuckSpec.ExternalPostgres == nil {\n\t\t\t\tctl.blackDuckSpec.ExternalPostgres = &blackduckv1.PostgresExternalDBConfig{}\n\t\t\t}\n\t\t\tctl.blackDuckSpec.ExternalPostgres.PostgresAdmin = ctl.ExternalPostgresAdmin\n\t\tcase \"external-postgres-user\":\n\t\t\tif ctl.blackDuckSpec.ExternalPostgres == nil {\n\t\t\t\tctl.blackDuckSpec.ExternalPostgres = &blackduckv1.PostgresExternalDBConfig{}\n\t\t\t}\n\t\t\tctl.blackDuckSpec.ExternalPostgres.PostgresUser = ctl.ExternalPostgresUser\n\t\tcase \"external-postgres-ssl\":\n\t\t\tif ctl.blackDuckSpec.ExternalPostgres == nil {\n\t\t\t\tctl.blackDuckSpec.ExternalPostgres = &blackduckv1.PostgresExternalDBConfig{}\n\t\t\t}\n\t\t\tctl.blackDuckSpec.ExternalPostgres.PostgresSsl = strings.ToUpper(ctl.ExternalPostgresSsl) == \"TRUE\"\n\t\tcase \"external-postgres-admin-password\":\n\t\t\tif ctl.blackDuckSpec.ExternalPostgres == nil {\n\t\t\t\tctl.blackDuckSpec.ExternalPostgres = &blackduckv1.PostgresExternalDBConfig{}\n\t\t\t}\n\t\t\tctl.blackDuckSpec.ExternalPostgres.PostgresAdminPassword = util.Base64Encode([]byte(ctl.ExternalPostgresAdminPassword))\n\t\tcase \"external-postgres-user-password\":\n\t\t\tif ctl.blackDuckSpec.ExternalPostgres == nil {\n\t\t\t\tctl.blackDuckSpec.ExternalPostgres = &blackduckv1.PostgresExternalDBConfig{}\n\t\t\t}\n\t\t\tctl.blackDuckSpec.ExternalPostgres.PostgresUserPassword = util.Base64Encode([]byte(ctl.ExternalPostgresUserPassword))\n\t\tcase \"pvc-storage-class\":\n\t\t\tctl.blackDuckSpec.PVCStorageClass = ctl.PvcStorageClass\n\t\tcase \"liveness-probes\":\n\t\t\tctl.blackDuckSpec.LivenessProbes = strings.ToUpper(ctl.LivenessProbes) == \"TRUE\"\n\t\tcase \"persistent-storage\":\n\t\t\tctl.blackDuckSpec.PersistentStorage = strings.ToUpper(ctl.PersistentStorage) == \"TRUE\"\n\t\tcase \"pvc-file-path\":\n\t\t\tdata, err := util.ReadFileData(ctl.PVCFilePath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"failed to read pvc file: %+v\", err)\n\t\t\t}\n\t\t\tpvcs := []blackduckv1.PVC{}\n\t\t\terr = json.Unmarshal([]byte(data), &pvcs)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"failed to unmarshal pvc structs: %+v\", err)\n\t\t\t}\n\t\t\tfor _, newPVC := range pvcs {\n\t\t\t\tfound := false\n\t\t\t\tfor i, currPVC := range ctl.blackDuckSpec.PVC {\n\t\t\t\t\tif newPVC.Name == currPVC.Name {\n\t\t\t\t\t\tctl.blackDuckSpec.PVC[i] = newPVC\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !found {\n\t\t\t\t\tctl.blackDuckSpec.PVC = append(ctl.blackDuckSpec.PVC, newPVC)\n\t\t\t\t}\n\t\t\t}\n\t\tcase \"node-affinity-file-path\":\n\t\t\tdata, err := util.ReadFileData(ctl.NodeAffinityFilePath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"failed to read node affinity file: %+v\", err)\n\t\t\t}\n\t\t\tnodeAffinities := map[string][]blackduckv1.NodeAffinity{}\n\t\t\terr = json.Unmarshal([]byte(data), &nodeAffinities)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"failed to unmarshal node affinities: %+v\", err)\n\t\t\t}\n\t\t\tctl.blackDuckSpec.NodeAffinities = nodeAffinities\n\t\tcase \"security-context-file-path\":\n\t\t\tdata, err := util.ReadFileData(ctl.SecurityContextFilePath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"failed to read security context file: %+v\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tSecurityContexts := map[string]api.SecurityContext{}\n\t\t\terr = json.Unmarshal([]byte(data), &SecurityContexts)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"failed to unmarshal security contexts: %+v\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctl.blackDuckSpec.SecurityContexts = SecurityContexts\n\t\tcase \"postgres-claim-size\":\n\t\t\tfor i := range ctl.blackDuckSpec.PVC {\n\t\t\t\tif ctl.blackDuckSpec.PVC[i].Name == \"blackduck-postgres\" { // update claim size and return\n\t\t\t\t\tctl.blackDuckSpec.PVC[i].Size = ctl.PostgresClaimSize\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tctl.blackDuckSpec.PVC = append(ctl.blackDuckSpec.PVC, blackduckv1.PVC{Name: \"blackduck-postgres\", Size: ctl.PostgresClaimSize}) // add postgres PVC if doesn't exist\n\t\tcase \"certificate-name\":\n\t\t\tctl.blackDuckSpec.CertificateName = ctl.CertificateName\n\t\tcase \"certificate-file-path\":\n\t\t\tdata, err := util.ReadFileData(ctl.CertificateFilePath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"failed to read certificate file: %+v\", err)\n\t\t\t}\n\t\t\tctl.blackDuckSpec.Certificate = data\n\t\tcase \"certificate-key-file-path\":\n\t\t\tdata, err := util.ReadFileData(ctl.CertificateKeyFilePath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"failed to read certificate file: %+v\", err)\n\t\t\t}\n\t\t\tctl.blackDuckSpec.CertificateKey = data\n\t\tcase \"proxy-certificate-file-path\":\n\t\t\tdata, err := util.ReadFileData(ctl.ProxyCertificateFilePath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"failed to read certificate file: %+v\", err)\n\t\t\t}\n\t\t\tctl.blackDuckSpec.ProxyCertificate = data\n\t\tcase \"auth-custom-ca-file-path\":\n\t\t\tdata, err := util.ReadFileData(ctl.AuthCustomCAFilePath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"failed to read authCustomCA file: %+v\", err)\n\t\t\t}\n\t\t\tctl.blackDuckSpec.AuthCustomCA = data\n\t\tcase \"type\":\n\t\t\tctl.blackDuckSpec.Type = ctl.Type\n\t\tcase \"desired-state\":\n\t\t\tctl.blackDuckSpec.DesiredState = ctl.DesiredState\n\t\tcase \"migration-mode\":\n\t\t\tif ctl.MigrationMode {\n\t\t\t\tctl.blackDuckSpec.DesiredState = \"DbMigrate\"\n\t\t\t}\n\t\tcase \"image-registries\":\n\t\t\tctl.blackDuckSpec.ImageRegistries = ctl.ImageRegistries\n\t\tcase \"license-key\":\n\t\t\tctl.blackDuckSpec.LicenseKey = ctl.LicenseKey\n\t\tcase \"admin-password\":\n\t\t\tctl.blackDuckSpec.AdminPassword = util.Base64Encode([]byte(ctl.AdminPassword))\n\t\tcase \"postgres-password\":\n\t\t\tctl.blackDuckSpec.PostgresPassword = util.Base64Encode([]byte(ctl.PostgresPassword))\n\t\tcase \"user-password\":\n\t\t\tctl.blackDuckSpec.UserPassword = util.Base64Encode([]byte(ctl.UserPassword))\n\t\tcase \"registry\":\n\t\t\tif ctl.blackDuckSpec.RegistryConfiguration == nil {\n\t\t\t\tctl.blackDuckSpec.RegistryConfiguration = &api.RegistryConfiguration{}\n\t\t\t}\n\t\t\tctl.blackDuckSpec.RegistryConfiguration.Registry = ctl.Registry\n\t\tcase \"pull-secret-name\":\n\t\t\tif ctl.blackDuckSpec.RegistryConfiguration == nil {\n\t\t\t\tctl.blackDuckSpec.RegistryConfiguration = &api.RegistryConfiguration{}\n\t\t\t}\n\t\t\tctl.blackDuckSpec.RegistryConfiguration.PullSecrets = ctl.PullSecrets\n\t\tcase \"seal-key\":\n\t\t\tctl.blackDuckSpec.SealKey = util.Base64Encode([]byte(ctl.SealKey))\n\t\tdefault:\n\t\t\tlog.Debugf(\"flag '%s': NOT FOUND\", f.Name)\n\t\t}\n\t} else {\n\t\tlog.Debugf(\"flag '%s': UNCHANGED\", f.Name)\n\t}\n}", "func (o *PtNaturalBcs) Set(key string, nod *Node, fcn fun.Func, extra string) (setisok bool) {\n\td := nod.GetDof(key)\n\tif d == nil { // handle LBB nodes\n\t\treturn\n\t}\n\tif idx, ok := o.Eq2idx[d.Eq]; ok {\n\t\to.Bcs[idx].Key = \"f\" + key\n\t\to.Bcs[idx].Eq = d.Eq\n\t\to.Bcs[idx].X = nod.Vert.C\n\t\to.Bcs[idx].Fcn = fcn\n\t\to.Bcs[idx].Extra = extra\n\t} else {\n\t\to.Eq2idx[d.Eq] = len(o.Bcs)\n\t\to.Bcs = append(o.Bcs, &PtNaturalBc{\"f\" + key, d.Eq, nod.Vert.C, fcn, extra})\n\t}\n\treturn true\n}", "func (m *MetricsProvider) CASIncrementCacheHitCount() {\n}", "func (cb callBacker) cautionCallBoolArgInt(fn_name string, arg int64) (bool, error) {\n\tif check, err := cb.checkCallBoolArgInt(fn_name, arg); check.Called {\n\t\treturn check.Return, err\n\t}\n\treturn false, cb.printCaution(fn_name)\n}", "func (o *GstObj) FlagSet(flag uint32) {\n\tC.CALL_MACRO_GST_OBJECT_FLAG_SET(o.g(), C.guint32(flag))\n}", "func (BooleanLiteral) paramValueNode() {}", "func Verifier(I, p []byte, bits int) (Ih, salt, v []byte, err error) {\n\tpf, ok := pflist[bits]\n\tif 0 == big.NewInt(0).Cmp(pf.N) || !ok {\n\t\terr = fmt.Errorf(\"Invalid bits: %d\", bits)\n\t\treturn\n\t}\n\n\ti := hashbyte(I)\n\ts := randbytes((bits / 2) / 8)\n\tx := hmacint(p, s, i)\n\n\tr := big.NewInt(0).Exp(pf.g, x, pf.N)\n\n\tsalt = s\n\tIh = i\n\tv = r.Bytes()\n\n\treturn\n}", "func checkFlag(fs *pflag.FlagSet, name string) (wasSet bool) {\n\tfs.Visit(func(f *pflag.Flag) {\n\t\tif f.Name == name {\n\t\t\twasSet = true\n\t\t}\n\t})\n\n\treturn\n}", "func SetFlag(f *asn1.BitString, i int) {\n\tfor l := len(f.Bytes); l < 4; l++ {\n\t\t(*f).Bytes = append((*f).Bytes, byte(0))\n\t\t(*f).BitLength = len((*f).Bytes) * 8\n\t}\n\t//Which byte?\n\tb := i / 8\n\t//Which bit in byte\n\tp := uint(7 - (i - 8*b))\n\t(*f).Bytes[b] = (*f).Bytes[b] | (1 << p)\n}", "func (cct pipConstraint) match(v Version) bool {\n\treturn cct.compare(v, cct)\n}", "func CfnResourceVersion_IsConstruct(x interface{}) *bool {\n\t_init_.Initialize()\n\n\tvar returns *bool\n\n\t_jsii_.StaticInvoke(\n\t\t\"aws-cdk-lib.aws_cloudformation.CfnResourceVersion\",\n\t\t\"isConstruct\",\n\t\t[]interface{}{x},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (r *Registers) getFlagC() bool {\n\treturn r.F&carryFlag != 0\n}", "func (s *BasePCREListener) EnterOption_flag(ctx *Option_flagContext) {}", "func (s *Store) KVSSetCAS(idx uint64, entry *structs.DirEntry) (bool, error) {\n\ttx := s.db.Txn(true)\n\tdefer tx.Abort()\n\n\tset, err := s.kvsSetCASTxn(tx, idx, entry)\n\tif !set || err != nil {\n\t\treturn false, err\n\t}\n\n\ttx.Commit()\n\treturn true, nil\n}", "func ContainFlag(sourceFlag, flag int) bool {\n\treturn sourceFlag&flag != 0\n}", "func github_com_jtolds_gls_markS(tag uint, cb func()) { _m(tag, cb) }", "func (f *FeatureGateClient) setActivated(ctx context.Context, gate *corev1alpha2.FeatureGate, featureName string) error {\n\tfor i := range gate.Spec.Features {\n\t\tif gate.Spec.Features[i].Name == featureName {\n\t\t\tgate.Spec.Features[i].Activate = true\n\t\t\treturn f.crClient.Update(ctx, gate)\n\t\t}\n\t}\n\treturn fmt.Errorf(\"could not activate Feature %s as it was not found in FeatureGate %s: %w\", featureName, gate.Name, ErrTypeNotFound)\n}", "func (f PktFlags) Has(v PktFlags) bool {\n\treturn (f & v) == v\n}", "func (m *Vulnerability) SetHasChatter(value *bool)() {\n err := m.GetBackingStore().Set(\"hasChatter\", value)\n if err != nil {\n panic(err)\n }\n}", "func IsFlagSet(f *asn1.BitString, i int) bool {\n\t//Which byte?\n\tb := i / 8\n\t//Which bit in byte\n\tp := uint(7 - (i - 8*b))\n\tif (*f).Bytes[b]&(1<<p) != 0 {\n\t\treturn true\n\t}\n\treturn false\n}", "func (ab *ABool) Get() bool {\n\treturn atomic.LoadInt32(&ab.flag) == 1\n}", "func (sw *Swizzle) Verify(p Proof) (bool, error) {\n\tproof, ok := p.(*SwizzleProof)\n\tif !ok {\n\t\treturn false, errors.New(\"use SwizzleProof instance for proof\")\n\t}\n\tvar rhs big.Int\n\tvar dummy big.Int\n\tch := sw.lastChallenge\n\tfor i := 0; i < sw.chunks; i++ {\n\t\tf, err := keyedPRFBig(sw.fKey, sw.prime, i)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tv, err := keyedPRFBig(ch.Key, ch.Vmax, i)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\trhs.Add(&rhs, dummy.Mul(v, f))\n\t}\n\tfor j := 0; j < ch.Sectors; j++ {\n\t\talpha, err := keyedPRFBig(sw.alphaKey, sw.prime, j)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\trhs.Add(&rhs, dummy.Mul(alpha, &proof.Mu[j]))\n\t}\n\tdummy.DivMod(&rhs, sw.prime, &rhs)\n\tif proof.Sigma.Cmp(&rhs) == 0 {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}", "func (f *fragment) setBit(rowID, columnID uint64) (changed bool, err error) {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\tmustClose, err := f.reopen()\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"reopening\")\n\t}\n\tif mustClose {\n\t\tdefer f.safeClose()\n\t}\n\n\t// handle mutux field type\n\tif f.mutexVector != nil {\n\t\tif err := f.handleMutex(rowID, columnID); err != nil {\n\t\t\treturn changed, errors.Wrap(err, \"handling mutex\")\n\t\t}\n\t}\n\n\treturn f.unprotectedSetBit(rowID, columnID)\n}", "func (c *Tag) setCarrier(names []string, cc *bin.Arg) bool {\n\tif c.carrierKey == \"\" {\n\t\treturn false\n\t}\n\tif c.carrier.IsNil() || c.carrier.IsZero() || !c.carrier.IsValid() {\n\t\treturn false\n\t}\n\t// set the field named `Arg`\n\tc.setArgsCarrier(cc)\n\tvalid := c.carrier\n\tif valid.Kind() == reflect.Ptr {\n\t\tvalid = valid.Elem()\n\t}\n\n\tif valid.Kind() != reflect.Struct {\n\t\treturn false\n\t}\n\n\tfield := valid.FieldByName(c.carrierKey)\n\tif !field.IsValid() {\n\t\treturn false\n\t}\n\n\t//@todo Currently, string types are supported temporarily. Later, generic types are used to support more types\n\t// set value\n\tisSet := false\n\trawValue := cc.ArgRaw(names...)\n\tswitch field.Kind() {\n\tcase reflect.String:\n\t\tval := reflect.ValueOf(rawValue)\n\t\tfield.Set(val)\n\t\tisSet = true\n\tcase reflect.Bool:\n\t\tvBool := false\n\t\tif rawValue != \"\" {\n\t\t\tvBool = parser.ConvBool(rawValue)\n\t\t} else {\n\t\t\tvBool = cc.CheckSetting(names...)\n\t\t}\n\t\tval := reflect.ValueOf(vBool)\n\t\tfield.Set(val)\n\t\tisSet = true\n\tcase reflect.Int:\n\t\tval := reflect.ValueOf(parser.ConvInt(rawValue))\n\t\tfield.Set(val)\n\t\tisSet = true\n\tcase reflect.Int64:\n\t\tval := reflect.ValueOf(parser.ConvI64(rawValue))\n\t\tfield.Set(val)\n\t\tisSet = true\n\tcase reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint, reflect.Uint8,\n\t\treflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\tval := reflect.ValueOf(parser.ConvInt(rawValue))\n\t\tfield.Set(val.Convert(field.Type()))\n\t\tisSet = true\n\tcase reflect.Float64, reflect.Float32:\n\t\tval := reflect.ValueOf(parser.ConvF64(rawValue))\n\t\tfield.Set(val.Convert(field.Type()))\n\t\tisSet = true\n\t}\n\treturn isSet\n}", "func matchCombo(i int, param []int) bool {\n\tc := 0\n\n\tfor _, v := range param {\n\t\tif bitExist(i, v-1) {\n\t\t\tc++\n\t\t}\n\t}\n\n\treturn c >= 3\n}", "func (b *taskBuilder) cas(casSpec string) {\n\tb.Spec.CasSpec = casSpec\n}", "func (s *CacheServer) Cas(ctx context.Context, in *pb.CacheRequest) (*pb.CacheResponse, error) {\n\tin.Operation = pb.CacheRequest_CAS\n\treturn s.Call(ctx, in)\n}", "func (p RProc) FlagSet(flag uint32) {\n\tflags := C._mrb_rproc_flags(p.p) & C.uint32_t(flag)\n\tC._mrb_rproc_set_flags(p.p, C.uint32_t(flags))\n}", "func (m *modelDao) checkFeature(key string) error {\n\tif m.flags == nil {\n\t\treturn fmt.Errorf(\"flag provider not set\")\n\t}\n\n\treturn m.flags.CheckFeature(key)\n}", "func (s *lockState) cas(key, old, new string) (string, bool) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tif s.locks[key] == old {\n\t\ts.locks[key] = new\n\t\treturn new, true\n\t}\n\treturn s.locks[key], false\n}", "func PTestRPC_ConcurrentCas(t *testing.T) {\n\tnclients := 3\n\tniters := 3\n\n\tclients := make([]*Client, nclients)\n\tfor i := 0; i < nclients; i++ {\n\t\tcl := mkClientUrl(t, leaderUrl)\n\t\tif cl == nil {\n\t\t\tt.Fatalf(\"Unable to create client #%d\", i)\n\t\t}\n\t\tdefer cl.close()\n\t\tclients[i] = cl\n\t}\n\n\tvar sem sync.WaitGroup // Used as a semaphore to coordinate goroutines to *begin* concurrently\n\tsem.Add(1)\n\n\tm, _ := clients[0].write(\"concCas\", \"first\", 0)\n\tver := m.Version\n\tif m.Kind != 'O' || ver == 0 {\n\t\tt.Fatalf(\"Expected write to succeed and return version\")\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(nclients)\n\n\terrorCh := make(chan error, nclients)\n\n\tfor i := 0; i < nclients; i++ {\n\t\tgo func(i int, ver int, cl *Client) {\n\t\t\tsem.Wait()\n\t\t\tdefer wg.Done()\n\t\t\tfor j := 0; j < niters; j++ {\n\t\t\t\tstr := fmt.Sprintf(\"cl %d %d\", i, j)\n\t\t\t\tfor {\n\t\t\t\t\tm, err := cl.cas(\"concCas\", ver, str, 0)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\terrorCh <- err\n\t\t\t\t\t\treturn\n\t\t\t\t\t} else if m.Kind == 'O' {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t} else if m.Kind != 'V' {\n\t\t\t\t\t\terrorCh <- errors.New(fmt.Sprintf(\"Expected 'V' msg, got %c\", m.Kind))\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tver = m.Version // retry with latest version\n\t\t\t\t}\n\t\t\t}\n\t\t}(i, ver, clients[i])\n\t}\n\n\tsem.Done() // Start goroutines\n\ttime.Sleep(1000 * time.Millisecond) // give goroutines a chance\n\twg.Wait() // Wait for them to finish\n\ttime.Sleep(10 * time.Second)\n\n\tselect {\n\tcase e := <-errorCh:\n\t\tt.Fatalf(\"Error received while doing cas: %v\", e)\n\tdefault: // no errors\n\t}\n\tm, _ = clients[0].read(\"concCas\")\n\tif !(m.Kind == 'C' && strings.HasSuffix(string(m.Contents), \" 2\")) {\n\t\tt.Fatalf(\"Expected to be able to read after 1000 writes. Got msg.Kind = %d, msg.Contents=%s\", m.Kind, m.Contents)\n\t}\n}", "func (_Onesplitaudit *OnesplitauditCaller) FLAGENABLEKYBERBANCORRESERVE(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Onesplitaudit.contract.Call(opts, &out, \"FLAG_ENABLE_KYBER_BANCOR_RESERVE\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (ctx *verifierContext) AddAgentSpecificCLIFlags(flagSet *flag.FlagSet) {\n\tctx.versionPtr = flagSet.Bool(\"v\", false, \"Version\")\n}", "func ResourceApplyPowerSignUseLocking(value bool) ResourceApplyPowerSignAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"use_locking\"] = value\n\t}\n}", "func contains(flags []flag, param string) bool {\n\tfor _, f := range flags {\n\t\tif f.name == strings.ReplaceAll(param, \"_\", \"-\") {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func TestAcceptFCAndConflictingRevision(t *testing.T) {\n\tif testing.Short() {\n\t\tt.SkipNow()\n\t}\n\ttpt, err := createTpoolTester(t.Name())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer tpt.Close()\n\n\t// Create and fund a valid file contract.\n\tbuilder, err := tpt.wallet.StartTransaction()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tpayout := types.NewCurrency64(1e9)\n\t_, err = builder.FundContract(payout)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tbuilder.AddFileContract(types.FileContract{\n\t\tWindowStart: tpt.cs.Height() + 2,\n\t\tWindowEnd: tpt.cs.Height() + 5,\n\t\tPayout: payout,\n\t\tValidProofOutputs: []types.SiacoinOutput{{Value: payout}},\n\t\tMissedProofOutputs: []types.SiacoinOutput{{Value: payout}},\n\t\tUnlockHash: types.UnlockConditions{}.UnlockHash(),\n\t})\n\ttSet, err := builder.Sign(true)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = tpt.tpool.AcceptTransactionSet(tSet)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfcid := tSet[len(tSet)-1].FileContractID(0)\n\n\t// Create a file contract revision and submit it.\n\trSet := []types.Transaction{{\n\t\tFileContractRevisions: []types.FileContractRevision{{\n\t\t\tParentID: fcid,\n\t\t\tNewRevisionNumber: 2,\n\n\t\t\tNewWindowStart: tpt.cs.Height() + 2,\n\t\t\tNewWindowEnd: tpt.cs.Height() + 5,\n\t\t\tNewValidProofOutputs: []types.SiacoinOutput{{Value: payout}},\n\t\t\tNewMissedProofOutputs: []types.SiacoinOutput{{Value: payout}},\n\t\t}},\n\t}}\n\terr = tpt.tpool.AcceptTransactionSet(rSet)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func (f *DBStoreRefreshCommitResolvabilityFunc) PushHook(hook func(context.Context, int, string, bool, time.Time) (int, int, error)) {\n\tf.mutex.Lock()\n\tf.hooks = append(f.hooks, hook)\n\tf.mutex.Unlock()\n}", "func (cmd *CompanyListHyCompanyCommand) RegisterFlags(cc *cobra.Command, c *client.Client) {\n}", "func (*AnalyzerOrgPolicyConstraint_Constraint_BooleanConstraint) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_asset_v1_asset_service_proto_rawDescGZIP(), []int{53, 0, 1}\n}", "func (_Onesplitaudit *OnesplitauditCallerSession) FLAGENABLEKYBERBANCORRESERVE() (*big.Int, error) {\n\treturn _Onesplitaudit.Contract.FLAGENABLEKYBERBANCORRESERVE(&_Onesplitaudit.CallOpts)\n}", "func (mmInjectCodeDescriptor *mClientMockInjectCodeDescriptor) Set(f func(r1 insolar.Reference, c1 CodeDescriptor)) *ClientMock {\n\tif mmInjectCodeDescriptor.defaultExpectation != nil {\n\t\tmmInjectCodeDescriptor.mock.t.Fatalf(\"Default expectation is already set for the Client.InjectCodeDescriptor method\")\n\t}\n\n\tif len(mmInjectCodeDescriptor.expectations) > 0 {\n\t\tmmInjectCodeDescriptor.mock.t.Fatalf(\"Some expectations are already set for the Client.InjectCodeDescriptor method\")\n\t}\n\n\tmmInjectCodeDescriptor.mock.funcInjectCodeDescriptor = f\n\treturn mmInjectCodeDescriptor.mock\n}", "func CClosureMarshalBooleanBoxedBoxed(closure *Closure, returnValue *Value, nParamValues uint32, paramValues *Value, invocationHint uintptr, marshalData uintptr) {\n\tc_closure := (*C.GClosure)(C.NULL)\n\tif closure != nil {\n\t\tc_closure = (*C.GClosure)(closure.ToC())\n\t}\n\n\tc_return_value := (*C.GValue)(C.NULL)\n\tif returnValue != nil {\n\t\tc_return_value = (*C.GValue)(returnValue.ToC())\n\t}\n\n\tc_n_param_values := (C.guint)(nParamValues)\n\n\tc_param_values := (*C.GValue)(C.NULL)\n\tif paramValues != nil {\n\t\tc_param_values = (*C.GValue)(paramValues.ToC())\n\t}\n\n\tc_invocation_hint := (C.gpointer)(invocationHint)\n\n\tc_marshal_data := (C.gpointer)(marshalData)\n\n\tC.g_cclosure_marshal_BOOLEAN__BOXED_BOXED(c_closure, c_return_value, c_n_param_values, c_param_values, c_invocation_hint, c_marshal_data)\n\n\treturn\n}", "func (f Flags) Set(v Flags) {\n\tf = f | v\n}", "func (ctl *Ctl) SetFlag(f *pflag.Flag) {\n\tif f.Changed {\n\t\tlog.Debugf(\"Flag %s: CHANGED\", f.Name)\n\t\tswitch f.Name {\n\t\tcase \"version\":\n\t\t\tctl.Spec.Version = ctl.Version\n\t\tcase \"alert-image\":\n\t\t\tctl.Spec.AlertImage = ctl.AlertImage\n\t\tcase \"cfssl-image\":\n\t\t\tctl.Spec.CfsslImage = ctl.CfsslImage\n\t\tcase \"stand-alone\":\n\t\t\tctl.Spec.StandAlone = &ctl.StandAlone\n\t\tcase \"expose-service\":\n\t\t\tctl.Spec.ExposeService = ctl.ExposeService\n\t\tcase \"port\":\n\t\t\tctl.Spec.Port = &ctl.Port\n\t\tcase \"encryption-password\":\n\t\t\tctl.Spec.EncryptionPassword = ctl.EncryptionPassword\n\t\tcase \"encryption-global-salt\":\n\t\t\tctl.Spec.EncryptionGlobalSalt = ctl.EncryptionGlobalSalt\n\t\tcase \"persistent-storage\":\n\t\t\tctl.Spec.PersistentStorage = ctl.PersistentStorage\n\t\tcase \"pvc-name\":\n\t\t\tctl.Spec.PVCName = ctl.PVCName\n\t\tcase \"pvc-storage-class\":\n\t\t\tctl.Spec.PVCStorageClass = ctl.PVCStorageClass\n\t\tcase \"pvc-size\":\n\t\t\tctl.Spec.PVCSize = ctl.PVCSize\n\t\tcase \"alert-memory\":\n\t\t\tctl.Spec.AlertMemory = ctl.AlertMemory\n\t\tcase \"cfssl-memory\":\n\t\t\tctl.Spec.CfsslMemory = ctl.CfsslMemory\n\t\tcase \"environs\":\n\t\t\tctl.Spec.Environs = ctl.Environs\n\t\tcase \"alert-desired-state\":\n\t\t\tctl.Spec.DesiredState = ctl.DesiredState\n\t\tdefault:\n\t\t\tlog.Debugf(\"Flag %s: Not Found\", f.Name)\n\t\t}\n\t} else {\n\t\tlog.Debugf(\"Flag %s: UNCHANGED\", f.Name)\n\t}\n}", "func (c *ConsensusRequest) check() bool {\n\t// Can we start?\n\ttemplate := c.Template()\n\tif template == nil {\n\t\tlog.Printf(\"Template %s not found for request %s\", c.TemplateId, c.Id)\n\t\treturn false\n\t}\n\n\t// Did we meet the auth?\n\tminAuth := template.Acl.MinAuth\n\tvoteCount := 1 // Initial vote by the requester\n\tfor _ = range c.ApproveUserIds {\n\t\tvoteCount++\n\t}\n\tif uint(voteCount) < minAuth {\n\t\t// Did not meet\n\t\tlog.Printf(\"Vote count %d does not yet meet required %d for request %s\", voteCount, minAuth, c.Id)\n\t\treturn false\n\t}\n\n\t// Start\n\treturn c.start()\n}", "func interpretWaitFlag(cmd cobra.Command) map[string]bool {\n\tif !cmd.Flags().Changed(waitComponents) {\n\t\tklog.Infof(\"Wait components to verify : %+v\", kverify.DefaultComponents)\n\t\treturn kverify.DefaultComponents\n\t}\n\n\twaitFlags, err := cmd.Flags().GetStringSlice(waitComponents)\n\tif err != nil {\n\t\tklog.Warningf(\"Failed to read --wait from flags: %v.\\n Moving on will use the default wait components: %+v\", err, kverify.DefaultComponents)\n\t\treturn kverify.DefaultComponents\n\t}\n\n\tif len(waitFlags) == 1 {\n\t\t// respecting legacy flag before minikube 1.9.0, wait flag was boolean\n\t\tif waitFlags[0] == \"false\" || waitFlags[0] == \"none\" {\n\t\t\tklog.Infof(\"Waiting for no components: %+v\", kverify.NoComponents)\n\t\t\treturn kverify.NoComponents\n\t\t}\n\t\t// respecting legacy flag before minikube 1.9.0, wait flag was boolean\n\t\tif waitFlags[0] == \"true\" || waitFlags[0] == \"all\" {\n\t\t\tklog.Infof(\"Waiting for all components: %+v\", kverify.AllComponents)\n\t\t\treturn kverify.AllComponents\n\t\t}\n\t}\n\n\twaitComponents := kverify.NoComponents\n\tfor _, wc := range waitFlags {\n\t\tseen := false\n\t\tfor _, valid := range kverify.AllComponentsList {\n\t\t\tif wc == valid {\n\t\t\t\twaitComponents[wc] = true\n\t\t\t\tseen = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif !seen {\n\t\t\tklog.Warningf(\"The value %q is invalid for --wait flag. valid options are %q\", wc, strings.Join(kverify.AllComponentsList, \",\"))\n\t\t}\n\t}\n\tklog.Infof(\"Waiting for components: %+v\", waitComponents)\n\treturn waitComponents\n}", "func (f *SubRepoPermissionCheckerEnabledFunc) PushHook(hook func() bool) {\n\tf.mutex.Lock()\n\tf.hooks = append(f.hooks, hook)\n\tf.mutex.Unlock()\n}", "func (_Rootchain *RootchainCaller) Flagged(opts *bind.CallOpts, _value *big.Int) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _Rootchain.contract.Call(opts, out, \"flagged\", _value)\n\treturn *ret0, err\n}", "func (h *atomicHeadTailIndex) cas(old, new headTailIndex) bool {\n\treturn h.u.CompareAndSwap(uint64(old), uint64(new))\n}", "func (b *AtomicFlag) TrySet(bVal bool) bool {\n\tvar v int32\n\tif bVal {\n\t\tv = 1\n\t}\n\tprev := atomic.SwapInt32(&b.val, v)\n\t// already set. unsuccessful\n\tif prev == v {\n\t\treturn false\n\t}\n\treturn true\n}" ]
[ "0.713732", "0.5748753", "0.51435745", "0.49321052", "0.48497313", "0.4782158", "0.45628622", "0.4547487", "0.45408538", "0.453088", "0.45060343", "0.44663414", "0.44497126", "0.44328275", "0.43742675", "0.4353449", "0.4303753", "0.4245013", "0.41860422", "0.41646722", "0.41443455", "0.4141565", "0.41235363", "0.4109537", "0.40814993", "0.4073868", "0.40731978", "0.40692878", "0.40566322", "0.4046255", "0.40458265", "0.4033987", "0.4033369", "0.4027738", "0.40271163", "0.40146536", "0.40125573", "0.40066427", "0.4003776", "0.4001718", "0.39905074", "0.3985706", "0.3983781", "0.3983781", "0.39818826", "0.39794543", "0.39758408", "0.39715523", "0.39625874", "0.39484018", "0.39458376", "0.39419428", "0.3935146", "0.39348906", "0.39293802", "0.391962", "0.39190465", "0.39159778", "0.39107683", "0.3908146", "0.3907768", "0.38927948", "0.38852954", "0.38750264", "0.387495", "0.387246", "0.38712206", "0.38696867", "0.38671982", "0.38664898", "0.386386", "0.3857154", "0.3857125", "0.38522586", "0.3850162", "0.38497698", "0.38497567", "0.38481253", "0.38462794", "0.38440308", "0.38390917", "0.38365743", "0.38350418", "0.38317516", "0.38294867", "0.38240895", "0.38219106", "0.38156837", "0.38154125", "0.3814432", "0.38121915", "0.38100868", "0.38086033", "0.38068613", "0.38042456", "0.38003427", "0.37927374", "0.37897402", "0.37893656", "0.37875712" ]
0.80135137
0
SupportCASWithRestrictions has the same behaviour of SupportCAS but specifies restriction on the helper description.
func SupportCASWithRestrictions(flagSet *pflag.FlagSet, p *string, restrictions map[string]string) func() bool { const casName = "cas" description := "make changes to a resource conditional upon matching the provided version" if len(restrictions) > 0 { description += ". Valid only if " for k, v := range restrictions { description += fmt.Sprintf("%s=%s ", k, v) } } flagSet.StringVar(p, casName, "", description) return func() bool { return flagSet.Changed(casName) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func SupportCAS(flagSet *pflag.FlagSet, p *string) func() bool {\n\tconst casName = \"cas\"\n\n\tflagSet.StringVar(p, casName, \"\", \"make changes to a resource conditional upon matching the provided version\")\n\n\treturn func() bool {\n\t\treturn flagSet.Changed(casName)\n\t}\n}", "func addRestrictions(parent *Block, ft *factsTable, t domain, v, w *Value, r relation) {\n\tif t == 0 {\n\t\t// Trivial case: nothing to do.\n\t\t// Shoult not happen, but just in case.\n\t\treturn\n\t}\n\tfor i := domain(1); i <= t; i <<= 1 {\n\t\tif t&i == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tft.update(parent, v, w, i, r)\n\t}\n}", "func (m *mockServer) Restrictions(ctx context.Context, swapType swap.Type,\n\tinitiator string) (\n\t*Restrictions, error) {\n\n\targs := m.Called(ctx, swapType)\n\n\treturn args.Get(0).(*Restrictions), args.Error(1)\n}", "func (c Config) RestrictionsOrDefault() string {\n\tif c.Restrictions != \"\" {\n\t\treturn c.Restrictions\n\t}\n\treturn DefaultRestrictionsInternal\n}", "func (c Config) RestrictionsOrDefault() string {\n\tif c.Restrictions != \"\" {\n\t\treturn c.Restrictions\n\t}\n\treturn DefaultRestrictionsInternal\n}", "func (s *ServicesTestSuite) NetworkRestrictions(t *testing.T, opts ...Option) {\n\tctx := context.Background()\n\n\t// blank slate, should be get/delete should fail\n\t_, err := s.RestrictionsS.GetNetworkRestrictions(ctx)\n\trequire.True(t, trace.IsNotFound(err))\n\n\terr = s.RestrictionsS.DeleteNetworkRestrictions(ctx)\n\trequire.True(t, trace.IsNotFound(err))\n\n\tallow := []types.AddressCondition{\n\t\t{CIDR: \"10.0.1.0/24\"},\n\t\t{CIDR: \"10.0.2.2\"},\n\t}\n\tdeny := []types.AddressCondition{\n\t\t{CIDR: \"10.1.0.0/16\"},\n\t\t{CIDR: \"8.8.8.8\"},\n\t}\n\n\texpected := types.NewNetworkRestrictions()\n\texpected.SetAllow(allow)\n\texpected.SetDeny(deny)\n\n\t// set and make sure we get it back\n\terr = s.RestrictionsS.SetNetworkRestrictions(ctx, expected)\n\trequire.NoError(t, err)\n\n\tactual, err := s.RestrictionsS.GetNetworkRestrictions(ctx)\n\trequire.NoError(t, err)\n\n\trequire.Empty(t, cmp.Diff(expected.GetAllow(), actual.GetAllow()))\n\trequire.Empty(t, cmp.Diff(expected.GetDeny(), actual.GetDeny()))\n\n\t// now delete should work ok and get should fail again\n\terr = s.RestrictionsS.DeleteNetworkRestrictions(ctx)\n\trequire.NoError(t, err)\n\n\terr = s.RestrictionsS.DeleteNetworkRestrictions(ctx)\n\trequire.True(t, trace.IsNotFound(err))\n}", "func (o LienOutput) Restrictions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *Lien) pulumi.StringArrayOutput { return v.Restrictions }).(pulumi.StringArrayOutput)\n}", "func (c Config) allowsLicense(name string) bool {\n\tfor _, l := range c.Licenses {\n\t\tif l == name {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func DefaultEndpointAuthorizationsForHelpDeskRole(volumeBrowsingAuthorizations bool) portainer.Authorizations {\n\tauthorizations := map[portainer.Authorization]bool{\n\t\tportainer.OperationDockerContainerArchiveInfo: true,\n\t\tportainer.OperationDockerContainerList: true,\n\t\tportainer.OperationDockerContainerChanges: true,\n\t\tportainer.OperationDockerContainerInspect: true,\n\t\tportainer.OperationDockerContainerTop: true,\n\t\tportainer.OperationDockerContainerLogs: true,\n\t\tportainer.OperationDockerContainerStats: true,\n\t\tportainer.OperationDockerImageList: true,\n\t\tportainer.OperationDockerImageSearch: true,\n\t\tportainer.OperationDockerImageGetAll: true,\n\t\tportainer.OperationDockerImageGet: true,\n\t\tportainer.OperationDockerImageHistory: true,\n\t\tportainer.OperationDockerImageInspect: true,\n\t\tportainer.OperationDockerNetworkList: true,\n\t\tportainer.OperationDockerNetworkInspect: true,\n\t\tportainer.OperationDockerVolumeList: true,\n\t\tportainer.OperationDockerVolumeInspect: true,\n\t\tportainer.OperationDockerSwarmInspect: true,\n\t\tportainer.OperationDockerNodeList: true,\n\t\tportainer.OperationDockerNodeInspect: true,\n\t\tportainer.OperationDockerServiceList: true,\n\t\tportainer.OperationDockerServiceInspect: true,\n\t\tportainer.OperationDockerServiceLogs: true,\n\t\tportainer.OperationDockerSecretList: true,\n\t\tportainer.OperationDockerSecretInspect: true,\n\t\tportainer.OperationDockerConfigList: true,\n\t\tportainer.OperationDockerConfigInspect: true,\n\t\tportainer.OperationDockerTaskList: true,\n\t\tportainer.OperationDockerTaskInspect: true,\n\t\tportainer.OperationDockerTaskLogs: true,\n\t\tportainer.OperationDockerPluginList: true,\n\t\tportainer.OperationDockerDistributionInspect: true,\n\t\tportainer.OperationDockerPing: true,\n\t\tportainer.OperationDockerInfo: true,\n\t\tportainer.OperationDockerVersion: true,\n\t\tportainer.OperationDockerEvents: true,\n\t\tportainer.OperationDockerSystem: true,\n\t\tportainer.OperationDockerAgentPing: true,\n\t\tportainer.OperationDockerAgentList: true,\n\t\tportainer.OperationDockerAgentHostInfo: true,\n\t\tportainer.OperationPortainerStackList: true,\n\t\tportainer.OperationPortainerStackInspect: true,\n\t\tportainer.OperationPortainerStackFile: true,\n\t\tportainer.OperationPortainerWebhookList: true,\n\t\tportainer.EndpointResourcesAccess: true,\n\t}\n\n\tif volumeBrowsingAuthorizations {\n\t\tauthorizations[portainer.OperationDockerAgentBrowseGet] = true\n\t\tauthorizations[portainer.OperationDockerAgentBrowseList] = true\n\t}\n\n\treturn authorizations\n}", "func (a *HyperflexApiService) CreateHyperflexFeatureLimitInternal(ctx context.Context) ApiCreateHyperflexFeatureLimitInternalRequest {\n\treturn ApiCreateHyperflexFeatureLimitInternalRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (a authorizer) Authorize(ctx context.Context, id bakery.Identity, ops []bakery.Op) (allowed []bool, caveats []checkers.Caveat, err error) {\n\tallowed = make([]bool, len(ops))\n\tfor i := range allowed {\n\t\tallowed[i] = true\n\t}\n\tcaveats = []checkers.Caveat{{\n\t\tLocation: a.thirdPartyLocation,\n\t\tCondition: \"access-allowed\",\n\t}}\n\treturn\n}", "func (o *ClientConfiguration) GetCategoryRestrictionsOk() (*[]Category, bool) {\n\tif o == nil || o.CategoryRestrictions == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.CategoryRestrictions, true\n}", "func init() {\n\taddCheck(CheckCapabilitiesRestricted)\n}", "func (*TargetRestrictionOperation) Descriptor() ([]byte, []int) {\n\treturn file_google_ads_googleads_v14_common_targeting_setting_proto_rawDescGZIP(), []int{2}\n}", "func checkAnnotationOnSvcPvc(svcPVC *v1.PersistentVolumeClaim,\n\tallowedTopologies map[string][]string, categories []string) error {\n\tannotationsMap := svcPVC.Annotations\n\tif accessibleTopoString, x := annotationsMap[tkgHAccessibleAnnotationKey]; x {\n\t\taccessibleTopology := strings.Split(accessibleTopoString, \":\")\n\t\ttopoKey := strings.Split(accessibleTopology[0], \"{\")[1]\n\t\ttopoVal := strings.Split(accessibleTopology[1], \"}\")[0]\n\t\tcategory := strings.SplitAfter(topoKey, \"/\")[1]\n\t\tcategoryKey := strings.Split(category, `\"`)[0]\n\t\tif isValuePresentInTheList(categories, categoryKey) {\n\t\t\tif isValuePresentInTheList(allowedTopologies[topoKey], topoVal) {\n\t\t\t\treturn fmt.Errorf(\"couldn't find allowed accessible topology: %v on svc pvc: %s\"+\n\t\t\t\t\t\"instead found: %v\", allowedTopologies[topoKey], svcPVC.Name, topoVal)\n\t\t\t}\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"couldn't find key: %s on allowed categories %v\",\n\t\t\t\tcategory, categories)\n\t\t}\n\t} else {\n\t\treturn fmt.Errorf(\"couldn't find annotation key: %s on svc pvc: %s\",\n\t\t\ttkgHAccessibleAnnotationKey, svcPVC.Name)\n\t}\n\n\tif requestedTopoString, y := annotationsMap[tkgHARequestedAnnotationKey]; y {\n\t\tavailabilityTopo := strings.Split(requestedTopoString, \",\")\n\t\tfor _, avlTopo := range availabilityTopo {\n\t\t\trequestedTopology := strings.Split(avlTopo, \":\")\n\t\t\ttopoKey := strings.Split(requestedTopology[0], \"{\")[1]\n\t\t\ttopoVal := strings.Split(requestedTopology[1], \"}\")[0]\n\t\t\tcategory := strings.SplitAfter(topoKey, \"/\")[1]\n\t\t\tcategoryKey := strings.Split(category, `\"`)[0]\n\t\t\tif isValuePresentInTheList(categories, categoryKey) {\n\t\t\t\tif isValuePresentInTheList(allowedTopologies[topoKey], topoVal) {\n\t\t\t\t\treturn fmt.Errorf(\"couldn't find allowed accessible topology: %v on svc pvc: %s\"+\n\t\t\t\t\t\t\"instead found: %v\", allowedTopologies[topoKey], svcPVC.Name, topoVal)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn fmt.Errorf(\"couldn't find key: %s on allowed categories %v\",\n\t\t\t\t\tcategory, categories)\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn fmt.Errorf(\"couldn't find annotation key: %s on svc pvc: %s\",\n\t\t\ttkgHARequestedAnnotationKey, svcPVC.Name)\n\t}\n\treturn nil\n}", "func (m *baggageRestrictionManager) AddBaggageRestrictions(service string, restrictions []*baggage.BaggageRestriction) {\n\tm.Lock()\n\tdefer m.Unlock()\n\tm.restrictions[service] = restrictions\n}", "func (m *Machine) checkRestrictions() error {\n\tif err := m.timedOut(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := m.tooManyCells(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := m.tooWide(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := m.tooTall(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (t *osCinderCSITranslator) CanSupport(pv *v1.PersistentVolume) bool {\n\treturn pv != nil && pv.Spec.Cinder != nil\n}", "func NewRestriction(keyAllowed bool, maxValueLength int) *Restriction {\n\treturn &Restriction{\n\t\tkeyAllowed: keyAllowed,\n\t\tmaxValueLength: maxValueLength,\n\t}\n}", "func TestCASPriorityExpanderCustom(t *testing.T) {\n\ttest := newIntegrationTest(\"cas-priority-expander-custom.example.com\", \"cluster-autoscaler-priority-expander-custom\").\n\t\twithAddons(\n\t\t\tawsCCMAddon,\n\t\t\tawsEBSCSIAddon,\n\t\t\tdnsControllerAddon,\n\t\t\t\"cluster-autoscaler.addons.k8s.io-k8s-1.15\",\n\t\t)\n\ttest.expectTerraformFilenames = append(test.expectTerraformFilenames,\n\t\t\"aws_launch_template_nodes-high-priority.cas-priority-expander-custom.example.com_user_data\",\n\t\t\"aws_launch_template_nodes-low-priority.cas-priority-expander-custom.example.com_user_data\",\n\t\t\"aws_s3_object_nodeupconfig-nodes-high-priority_content\",\n\t\t\"aws_s3_object_nodeupconfig-nodes-low-priority_content\",\n\t)\n\ttest.runTestTerraformAWS(t)\n}", "func (m *ScheduleLayer) SetRestrictions(val []Restriction) {\n\tm.restrictionsField = val\n}", "func (rc *ResourceCommand) createNetworkRestrictions(ctx context.Context, client auth.ClientI, raw services.UnknownResource) error {\n\tnewNetRestricts, err := services.UnmarshalNetworkRestrictions(raw.Raw)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\tif err := client.SetNetworkRestrictions(ctx, newNetRestricts); err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\tfmt.Printf(\"network restrictions have been updated\\n\")\n\treturn nil\n}", "func (m *ConditionalAccessPolicy) SetDescription(value *string)() {\n err := m.GetBackingStore().Set(\"description\", value)\n if err != nil {\n panic(err)\n }\n}", "func buildColumnToPossibleRestrictions(tickets []Ticket, restrictions []FieldDef) [][]int {\n\tnumberOfColumns := len(restrictions)\n\trowToRestrictions := make([][]int, numberOfColumns)\n\tfor i := 0; i < numberOfColumns; i++ {\n\t\trowToRestrictions[i] = buildPossibleRestrictionsForColumn(getColumn(tickets, i), restrictions)\n\t}\n\treturn rowToRestrictions\n}", "func (*TargetRestriction) Descriptor() ([]byte, []int) {\n\treturn file_google_ads_googleads_v14_common_targeting_setting_proto_rawDescGZIP(), []int{1}\n}", "func (r requiresReplaceIfModifier) Description(ctx context.Context) string {\n\treturn r.description\n}", "func TestRestrictedSuggestions(t *testing.T) {\n\tvar (\n\t\tfailedWithinTimeout = &loopdb.LoopEvent{\n\t\t\tSwapStateData: loopdb.SwapStateData{\n\t\t\t\tState: loopdb.StateFailOffchainPayments,\n\t\t\t},\n\t\t\tTime: testTime,\n\t\t}\n\n\t\tfailedBeforeBackoff = &loopdb.LoopEvent{\n\t\t\tSwapStateData: loopdb.SwapStateData{\n\t\t\t\tState: loopdb.StateFailOffchainPayments,\n\t\t\t},\n\t\t\tTime: testTime.Add(\n\t\t\t\tdefaultFailureBackoff * -1,\n\t\t\t),\n\t\t}\n\n\t\t// failedTemporary is a swap that failed outside of our backoff\n\t\t// period, but we still want to back off because the swap is\n\t\t// considered pending.\n\t\tfailedTemporary = &loopdb.LoopEvent{\n\t\t\tSwapStateData: loopdb.SwapStateData{\n\t\t\t\tState: loopdb.StateFailTemporary,\n\t\t\t},\n\t\t\tTime: testTime.Add(\n\t\t\t\tdefaultFailureBackoff * -3,\n\t\t\t),\n\t\t}\n\n\t\tchanRules = map[lnwire.ShortChannelID]*SwapRule{\n\t\t\tchanID1: chanRule,\n\t\t\tchanID2: chanRule,\n\t\t}\n\t)\n\n\ttests := []struct {\n\t\tname string\n\t\tchannels []lndclient.ChannelInfo\n\t\tloopOut []*loopdb.LoopOut\n\t\tloopIn []*loopdb.LoopIn\n\t\tchanRules map[lnwire.ShortChannelID]*SwapRule\n\t\tpeerRules map[route.Vertex]*SwapRule\n\t\texpected *Suggestions\n\t}{\n\t\t{\n\t\t\tname: \"no existing swaps\",\n\t\t\tchannels: []lndclient.ChannelInfo{\n\t\t\t\tchannel1,\n\t\t\t},\n\t\t\tloopOut: nil,\n\t\t\tloopIn: nil,\n\t\t\tchanRules: chanRules,\n\t\t\texpected: &Suggestions{\n\t\t\t\tOutSwaps: []loop.OutRequest{\n\t\t\t\t\tchan1Rec,\n\t\t\t\t},\n\t\t\t\tDisqualifiedChans: noneDisqualified,\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"unrestricted loop out\",\n\t\t\tchannels: []lndclient.ChannelInfo{\n\t\t\t\tchannel1,\n\t\t\t},\n\t\t\tloopOut: []*loopdb.LoopOut{\n\t\t\t\t{\n\t\t\t\t\tContract: &loopdb.LoopOutContract{\n\t\t\t\t\t\tOutgoingChanSet: nil,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tchanRules: chanRules,\n\t\t\texpected: &Suggestions{\n\t\t\t\tOutSwaps: []loop.OutRequest{\n\t\t\t\t\tchan1Rec,\n\t\t\t\t},\n\t\t\t\tDisqualifiedChans: noneDisqualified,\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"unrestricted loop in\",\n\t\t\tchannels: []lndclient.ChannelInfo{\n\t\t\t\tchannel1,\n\t\t\t},\n\t\t\tloopIn: []*loopdb.LoopIn{\n\t\t\t\t{\n\t\t\t\t\tContract: &loopdb.LoopInContract{\n\t\t\t\t\t\tLastHop: nil,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tchanRules: chanRules,\n\t\t\texpected: &Suggestions{\n\t\t\t\tOutSwaps: []loop.OutRequest{\n\t\t\t\t\tchan1Rec,\n\t\t\t\t},\n\t\t\t\tDisqualifiedChans: noneDisqualified,\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"restricted loop out\",\n\t\t\tchannels: []lndclient.ChannelInfo{\n\t\t\t\tchannel1, channel2,\n\t\t\t},\n\t\t\tloopOut: []*loopdb.LoopOut{\n\t\t\t\t{\n\t\t\t\t\tContract: chan1Out,\n\t\t\t\t},\n\t\t\t},\n\t\t\tchanRules: chanRules,\n\t\t\texpected: &Suggestions{\n\t\t\t\tOutSwaps: []loop.OutRequest{\n\t\t\t\t\tchan2Rec,\n\t\t\t\t},\n\t\t\t\tDisqualifiedChans: map[lnwire.ShortChannelID]Reason{\n\t\t\t\t\tchanID1: ReasonLoopOut,\n\t\t\t\t},\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"restricted loop in\",\n\t\t\tchannels: []lndclient.ChannelInfo{\n\t\t\t\tchannel1, channel2,\n\t\t\t},\n\t\t\tloopIn: []*loopdb.LoopIn{\n\t\t\t\t{\n\t\t\t\t\tContract: &loopdb.LoopInContract{\n\t\t\t\t\t\tLastHop: &peer2,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tchanRules: chanRules,\n\t\t\texpected: &Suggestions{\n\t\t\t\tOutSwaps: []loop.OutRequest{\n\t\t\t\t\tchan1Rec,\n\t\t\t\t},\n\t\t\t\tDisqualifiedChans: map[lnwire.ShortChannelID]Reason{\n\t\t\t\t\tchanID2: ReasonLoopIn,\n\t\t\t\t},\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"swap failed recently\",\n\t\t\tchannels: []lndclient.ChannelInfo{\n\t\t\t\tchannel1,\n\t\t\t},\n\t\t\tloopOut: []*loopdb.LoopOut{\n\t\t\t\t{\n\t\t\t\t\tContract: chan1Out,\n\t\t\t\t\tLoop: loopdb.Loop{\n\t\t\t\t\t\tEvents: []*loopdb.LoopEvent{\n\t\t\t\t\t\t\tfailedWithinTimeout,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tchanRules: chanRules,\n\t\t\texpected: &Suggestions{\n\t\t\t\tDisqualifiedChans: map[lnwire.ShortChannelID]Reason{\n\t\t\t\t\tchanID1: ReasonFailureBackoff,\n\t\t\t\t},\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"swap failed before cutoff\",\n\t\t\tchannels: []lndclient.ChannelInfo{\n\t\t\t\tchannel1,\n\t\t\t},\n\t\t\tloopOut: []*loopdb.LoopOut{\n\t\t\t\t{\n\t\t\t\t\tContract: chan1Out,\n\t\t\t\t\tLoop: loopdb.Loop{\n\t\t\t\t\t\tEvents: []*loopdb.LoopEvent{\n\t\t\t\t\t\t\tfailedBeforeBackoff,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tchanRules: chanRules,\n\t\t\texpected: &Suggestions{\n\t\t\t\tOutSwaps: []loop.OutRequest{\n\t\t\t\t\tchan1Rec,\n\t\t\t\t},\n\t\t\t\tDisqualifiedChans: noneDisqualified,\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"temporary failure\",\n\t\t\tchannels: []lndclient.ChannelInfo{\n\t\t\t\tchannel1,\n\t\t\t},\n\t\t\tloopOut: []*loopdb.LoopOut{\n\t\t\t\t{\n\t\t\t\t\tContract: chan1Out,\n\t\t\t\t\tLoop: loopdb.Loop{\n\t\t\t\t\t\tEvents: []*loopdb.LoopEvent{\n\t\t\t\t\t\t\tfailedTemporary,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tchanRules: chanRules,\n\t\t\texpected: &Suggestions{\n\t\t\t\tDisqualifiedChans: map[lnwire.ShortChannelID]Reason{\n\t\t\t\t\tchanID1: ReasonLoopOut,\n\t\t\t\t},\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"existing on peer's channel\",\n\t\t\tchannels: []lndclient.ChannelInfo{\n\t\t\t\tchannel1,\n\t\t\t\t{\n\t\t\t\t\tChannelID: chanID3.ToUint64(),\n\t\t\t\t\tPubKeyBytes: peer1,\n\t\t\t\t},\n\t\t\t},\n\t\t\tloopOut: []*loopdb.LoopOut{\n\t\t\t\t{\n\t\t\t\t\tContract: chan1Out,\n\t\t\t\t},\n\t\t\t},\n\t\t\tpeerRules: map[route.Vertex]*SwapRule{\n\t\t\t\tpeer1: {\n\t\t\t\t\tThresholdRule: NewThresholdRule(0, 50),\n\t\t\t\t\tType: swap.TypeOut,\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: &Suggestions{\n\t\t\t\tDisqualifiedChans: noneDisqualified,\n\t\t\t\tDisqualifiedPeers: map[route.Vertex]Reason{\n\t\t\t\t\tpeer1: ReasonLoopOut,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, testCase := range tests {\n\t\ttestCase := testCase\n\n\t\tt.Run(testCase.name, func(t *testing.T) {\n\t\t\t// Create a manager config which will return the test\n\t\t\t// case's set of existing swaps.\n\t\t\tcfg, lnd := newTestConfig()\n\t\t\tcfg.ListLoopOut = func(context.Context) ([]*loopdb.LoopOut, error) {\n\t\t\t\treturn testCase.loopOut, nil\n\t\t\t}\n\t\t\tcfg.ListLoopIn = func(context.Context) ([]*loopdb.LoopIn, error) {\n\t\t\t\treturn testCase.loopIn, nil\n\t\t\t}\n\n\t\t\tlnd.Channels = testCase.channels\n\n\t\t\tparams := defaultParameters\n\t\t\tparams.AutoloopBudgetLastRefresh = testBudgetStart\n\t\t\tif testCase.chanRules != nil {\n\t\t\t\tparams.ChannelRules = testCase.chanRules\n\t\t\t}\n\n\t\t\tif testCase.peerRules != nil {\n\t\t\t\tparams.PeerRules = testCase.peerRules\n\t\t\t}\n\n\t\t\ttestSuggestSwaps(\n\t\t\t\tt, newSuggestSwapsSetup(cfg, lnd, params),\n\t\t\t\ttestCase.expected, nil,\n\t\t\t)\n\t\t})\n\t}\n}", "func cacheControlOpts(o ObjectInfo) *cacheControl {\n\tc := cacheControl{}\n\tm := o.UserDefined\n\tif !o.Expires.Equal(timeSentinel) {\n\t\tc.expiry = o.Expires\n\t}\n\n\tvar headerVal string\n\tfor k, v := range m {\n\t\tif strings.ToLower(k) == \"cache-control\" {\n\t\t\theaderVal = v\n\t\t}\n\n\t}\n\tif headerVal == \"\" {\n\t\treturn nil\n\t}\n\theaderVal = strings.ToLower(headerVal)\n\theaderVal = strings.TrimSpace(headerVal)\n\n\tvals := strings.Split(headerVal, \",\")\n\tfor _, val := range vals {\n\t\tval = strings.TrimSpace(val)\n\n\t\tif val == \"no-store\" {\n\t\t\tc.noStore = true\n\t\t\tcontinue\n\t\t}\n\t\tif val == \"only-if-cached\" {\n\t\t\tc.onlyIfCached = true\n\t\t\tcontinue\n\t\t}\n\t\tif val == \"no-cache\" {\n\t\t\tc.noCache = true\n\t\t\tcontinue\n\t\t}\n\t\tp := strings.Split(val, \"=\")\n\n\t\tif len(p) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tif p[0] == \"max-age\" ||\n\t\t\tp[0] == \"s-maxage\" ||\n\t\t\tp[0] == \"min-fresh\" ||\n\t\t\tp[0] == \"max-stale\" {\n\t\t\ti, err := strconv.Atoi(p[1])\n\t\t\tif err != nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif p[0] == \"max-age\" {\n\t\t\t\tc.maxAge = i\n\t\t\t}\n\t\t\tif p[0] == \"s-maxage\" {\n\t\t\t\tc.sMaxAge = i\n\t\t\t}\n\t\t\tif p[0] == \"min-fresh\" {\n\t\t\t\tc.minFresh = i\n\t\t\t}\n\t\t\tif p[0] == \"max-stale\" {\n\t\t\t\tc.maxStale = i\n\t\t\t}\n\t\t}\n\t}\n\treturn &c\n}", "func addIndVarRestrictions(ft *factsTable, b *Block, iv indVar) {\n\td := signed\n\tif ft.isNonNegative(iv.min) && ft.isNonNegative(iv.max) {\n\t\td |= unsigned\n\t}\n\n\tif iv.flags&indVarMinExc == 0 {\n\t\taddRestrictions(b, ft, d, iv.min, iv.ind, lt|eq)\n\t} else {\n\t\taddRestrictions(b, ft, d, iv.min, iv.ind, lt)\n\t}\n\n\tif iv.flags&indVarMaxInc == 0 {\n\t\taddRestrictions(b, ft, d, iv.ind, iv.max, lt)\n\t} else {\n\t\taddRestrictions(b, ft, d, iv.ind, iv.max, lt|eq)\n\t}\n}", "func configureFlags(api *operations.ControlAsistenciaAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func (p *serviceEvaluator) Constraints(required []api.ResourceName, item runtime.Object) error {\n\tservice, ok := item.(*api.Service)\n\tif !ok {\n\t\treturn fmt.Errorf(\"unexpected input object %v\", item)\n\t}\n\n\trequiredSet := quota.ToSet(required)\n\tmissingSet := sets.NewString()\n\tserviceUsage, err := p.Usage(service)\n\tif err != nil {\n\t\treturn err\n\t}\n\tserviceSet := quota.ToSet(quota.ResourceNames(serviceUsage))\n\tif diff := requiredSet.Difference(serviceSet); len(diff) > 0 {\n\t\tmissingSet.Insert(diff.List()...)\n\t}\n\n\tif len(missingSet) == 0 {\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"must specify %s\", strings.Join(missingSet.List(), \",\"))\n}", "func requirementsOf(requirementType string) {\n\n}", "func (r WebRestrictions) ScopeDescription() string {\n\tif r.getScopeClass() {\n\t\treturn \"This token has restrictions for scopes.\"\n\t}\n\treturn \"This token can use all configured scopes.\"\n}", "func (r WebRestrictions) Text() string {\n\tdata, _ := json.Marshal(r.Restrictions)\n\treturn string(data)\n}", "func (me TAttlistAbstractTextNlmCategory) IsConclusions() bool { return me.String() == \"CONCLUSIONS\" }", "func (Ca) Definition() sophos.Definition { return *defCa }", "func (s serverImpl) isCreatorAllowListed(ctx types.Context, allowlist []string, designer sdk.Address) bool {\n\tfor _, addr := range allowlist {\n\t\tctx.GasMeter().ConsumeGas(gasCostPerIteration, \"credit class creators allowlist\")\n\t\tallowListedAddr, _ := sdk.AccAddressFromBech32(addr)\n\t\tif designer.Equals(allowListedAddr) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func middlewareRegistrationRestrictionTests(t *testing.T,\n\tnode *lntest.HarnessNode) {\n\n\ttestCases := []struct {\n\t\tregistration *lnrpc.MiddlewareRegistration\n\t\texpectedErr string\n\t}{{\n\t\tregistration: &lnrpc.MiddlewareRegistration{\n\t\t\tMiddlewareName: \"foo\",\n\t\t},\n\t\texpectedErr: \"invalid middleware name\",\n\t}, {\n\t\tregistration: &lnrpc.MiddlewareRegistration{\n\t\t\tMiddlewareName: \"itest-interceptor\",\n\t\t\tCustomMacaroonCaveatName: \"foo\",\n\t\t},\n\t\texpectedErr: \"custom caveat name of at least\",\n\t}, {\n\t\tregistration: &lnrpc.MiddlewareRegistration{\n\t\t\tMiddlewareName: \"itest-interceptor\",\n\t\t\tCustomMacaroonCaveatName: \"itest-caveat\",\n\t\t\tReadOnlyMode: true,\n\t\t},\n\t\texpectedErr: \"cannot set read-only and custom caveat name\",\n\t}}\n\n\tfor idx, tc := range testCases {\n\t\ttc := tc\n\n\t\tt.Run(fmt.Sprintf(\"%d\", idx), func(tt *testing.T) {\n\t\t\tinvalidName := registerMiddleware(\n\t\t\t\ttt, node, tc.registration,\n\t\t\t)\n\t\t\t_, err := invalidName.stream.Recv()\n\t\t\trequire.Error(tt, err)\n\t\t\trequire.Contains(tt, err.Error(), tc.expectedErr)\n\n\t\t\tinvalidName.cancel()\n\t\t})\n\t}\n}", "func (l *License) GetLimitations() []string {\n\tif l == nil || l.Limitations == nil {\n\t\treturn nil\n\t}\n\treturn *l.Limitations\n}", "func (m *ScheduleLayer) Restrictions() []Restriction {\n\treturn m.restrictionsField\n}", "func (me TrestrictionType) IsNeedToKnow() bool { return me.String() == \"need-to-know\" }", "func TestCASPriorityExpander(t *testing.T) {\n\ttest := newIntegrationTest(\"cas-priority-expander.example.com\", \"cluster-autoscaler-priority-expander\").\n\t\twithAddons(\n\t\t\tawsCCMAddon,\n\t\t\tawsEBSCSIAddon,\n\t\t\tdnsControllerAddon,\n\t\t\t\"cluster-autoscaler.addons.k8s.io-k8s-1.15\",\n\t\t)\n\ttest.expectTerraformFilenames = append(test.expectTerraformFilenames,\n\t\t\"aws_launch_template_nodes-high-priority.cas-priority-expander.example.com_user_data\",\n\t\t\"aws_launch_template_nodes-low-priority.cas-priority-expander.example.com_user_data\",\n\t\t\"aws_s3_object_nodeupconfig-nodes-high-priority_content\",\n\t\t\"aws_s3_object_nodeupconfig-nodes-low-priority_content\",\n\t)\n\ttest.runTestTerraformAWS(t)\n}", "func (o SkuOutput) Restrictions() RestrictionArrayOutput {\n\treturn o.ApplyT(func(v Sku) []Restriction { return v.Restrictions }).(RestrictionArrayOutput)\n}", "func NeedsLicense(kind string) bool {\n\treturn kind == \"car\" || kind == \"truck\"\n}", "func DescriptionContains(v string) predicate.AllocationStrategy {\n\treturn predicate.AllocationStrategy(func(s *sql.Selector) {\n\t\ts.Where(sql.Contains(s.C(FieldDescription), v))\n\t})\n}", "func limitedByDefault(usage corev1.ResourceList, limitedResources []resourcequotaapi.LimitedResource) []corev1.ResourceName {\n\tresult := []corev1.ResourceName{}\n\tfor _, limitedResource := range limitedResources {\n\t\tfor k, v := range usage {\n\t\t\t// if a resource is consumed, we need to check if it matches on the limited resource list.\n\t\t\tif v.Sign() == 1 {\n\t\t\t\t// if we get a match, we add it to limited set\n\t\t\t\tfor _, matchContain := range limitedResource.MatchContains {\n\t\t\t\t\tif strings.Contains(string(k), matchContain) {\n\t\t\t\t\t\tresult = append(result, k)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}", "func combineRestrictions(fieldsMap map[string]string, rests string) (string, error) {\n\tif rests == \"\" {\n\t\treturn \"\", nil\n\t}\n\trestsArray := strings.Split(rests, \",\")\n\trestsBlock := \"\"\n\n\t// field\n\tfield := restsArray[0]\n\tif field != \"\" {\n\t\tf := fieldsMap[field]\n\t\tif f == \"\" {\n\t\t\treturn \"\", newError(\"Unexpected selection order field - \" + field)\n\t\t}\n\t\trestsBlock = \"order by q.\" + f + \" \"\n\t}\n\n\t// order\n\torder := restsArray[1]\n\tif order != \"\" {\n\t\tif order != \"asc\" && order != \"desc\" {\n\t\t\treturn \"\", newError(\"Unexpected selection order - \" + order)\n\t\t}\n\n\t\tif restsBlock == \"\" {\n\t\t\trestsBlock = \"order by q.ID \" + order\n\t\t} else {\n\t\t\trestsBlock = restsBlock + order\n\t\t}\n\t}\n\n\t// limit\n\tlimit := restsArray[2]\n\tif limit != \"\" {\n\t\t_, err := strconv.Atoi(limit)\n\t\tif err != nil {\n\t\t\treturn \"\", newError(\"Unexpected selection limit - \" + limit)\n\t\t}\n\n\t\tif restsBlock == \"\" {\n\t\t\trestsBlock = \"limit \" + limit\n\t\t} else {\n\t\t\trestsBlock = restsBlock + \" limit \" + limit\n\t\t}\n\t}\n\n\t// offset\n\toffset := restsArray[3]\n\tif offset != \"\" {\n\t\t_, err := strconv.Atoi(offset)\n\t\tif err != nil {\n\t\t\treturn \"\", newError(\"Unexpected selection offset - \" + offset)\n\t\t}\n\n\t\tif restsBlock == \"\" {\n\t\t\trestsBlock = \"offset \" + offset\n\t\t} else {\n\t\t\trestsBlock = restsBlock + \" offset \" + offset\n\t\t}\n\t}\n\n\treturn restsBlock, nil\n}", "func resolveFlags(rqProtocol *v2.Request, rqInternal *msg.Request) error {\n\tswitch rqInternal.Section {\n\tcase msg.SectionConfiguration:\n\t\tswitch rqInternal.Action {\n\t\tcase msg.ActionRemove:\n\t\t\tif val, err := strconv.ParseBool(rqProtocol.Flags.AlarmClearing); err != nil {\n\t\t\t\t// disable by default\n\t\t\t\trqInternal.Flags.AlarmClearing = false\n\t\t\t} else if val {\n\t\t\t\t// explicit enable\n\t\t\t\trqInternal.Flags.AlarmClearing = true\n\t\t\t} else {\n\t\t\t\trqInternal.Flags.AlarmClearing = false\n\t\t\t}\n\t\t\tfallthrough\n\n\t\tcase msg.ActionAdd, msg.ActionUpdate:\n\t\t\tif val, err := strconv.ParseBool(rqProtocol.Flags.ResetActivation); err != nil {\n\t\t\t\t// disable by default\n\t\t\t\trqInternal.Flags.ResetActivation = false\n\n\t\t\t\t// ...but enable by default if AlarmClearing is enabled\n\t\t\t\tif rqInternal.Flags.AlarmClearing {\n\t\t\t\t\trqInternal.Flags.ResetActivation = true\n\t\t\t\t}\n\t\t\t} else if val {\n\t\t\t\t// explicit enable\n\t\t\t\trqInternal.Flags.ResetActivation = true\n\t\t\t} else {\n\t\t\t\trqInternal.Flags.ResetActivation = false\n\t\t\t}\n\n\t\t\tif val, err := strconv.ParseBool(rqProtocol.Flags.CacheInvalidation); err != nil {\n\t\t\t\t// enable by default\n\t\t\t\trqInternal.Flags.CacheInvalidation = true\n\t\t\t} else if !val {\n\t\t\t\t// explicit disable\n\t\t\t\trqInternal.Flags.CacheInvalidation = false\n\t\t\t} else {\n\t\t\t\trqInternal.Flags.CacheInvalidation = true\n\t\t\t}\n\n\t\t\tif val, err := strconv.ParseBool(rqProtocol.Flags.SendDeploymentFeedback); err != nil {\n\t\t\t\t// disable by default\n\t\t\t\trqInternal.Flags.SendDeploymentFeedback = false\n\t\t\t} else if val {\n\t\t\t\t// explicit enable\n\t\t\t\trqInternal.Flags.SendDeploymentFeedback = true\n\t\t\t} else {\n\t\t\t\trqInternal.Flags.SendDeploymentFeedback = false\n\t\t\t}\n\t\t}\n\n\tcase msg.SectionDeployment:\n\t\tswitch rqInternal.ConfigurationTask {\n\t\tcase msg.TaskRollout:\n\t\t\trqInternal.Flags.AlarmClearing = false\n\t\t\trqInternal.Flags.CacheInvalidation = true\n\t\t\trqInternal.Flags.ResetActivation = false\n\t\t\trqInternal.Flags.SendDeploymentFeedback = true\n\t\tcase msg.TaskDeprovision:\n\t\t\trqInternal.Flags.AlarmClearing = false\n\t\t\trqInternal.Flags.CacheInvalidation = false\n\t\t\trqInternal.Flags.ResetActivation = false\n\t\t\trqInternal.Flags.SendDeploymentFeedback = true\n\t\tcase msg.TaskDelete:\n\t\t\trqInternal.Flags.AlarmClearing = true\n\t\t\trqInternal.Flags.CacheInvalidation = true\n\t\t\trqInternal.Flags.ResetActivation = true\n\t\t\trqInternal.Flags.SendDeploymentFeedback = true\n\t\t}\n\t}\n\tif rqInternal.Flags.AlarmClearing && !rqInternal.Flags.CacheInvalidation {\n\t\treturn fmt.Errorf(`Invalid flag combination: alarm.clearing requires cache.invalidation`)\n\t}\n\treturn nil\n}", "func (a *HyperflexApiService) CreateHyperflexAutoSupportPolicy(ctx context.Context) ApiCreateHyperflexAutoSupportPolicyRequest {\n\treturn ApiCreateHyperflexAutoSupportPolicyRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (b *taskBuilder) cas(casSpec string) {\n\tb.Spec.CasSpec = casSpec\n}", "func (fvc FirmwareVersionCriterion) AsAnnouncementFeedbackCriterion() (*AnnouncementFeedbackCriterion, bool) {\n\treturn nil, false\n}", "func (*AnalyzerOrgPolicyConstraint_Constraint_BooleanConstraint) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_asset_v1_asset_service_proto_rawDescGZIP(), []int{53, 0, 1}\n}", "func channelRestrictionsValue(maxChannelCount uint64) *standardConfigValue {\n\treturn &standardConfigValue{\n\t\tkey: ChannelRestrictionsKey,\n\t\tvalue: &ob.ChannelRestrictions{\n\t\t\tMaxCount: maxChannelCount,\n\t\t},\n\t}\n}", "func (c *CseListCall) Safe(safe string) *CseListCall {\n\tc.urlParams_.Set(\"safe\", safe)\n\treturn c\n}", "func (o ServicePerimetersServicePerimeterSpecOutput) RestrictedServices() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ServicePerimetersServicePerimeterSpec) []string { return v.RestrictedServices }).(pulumi.StringArrayOutput)\n}", "func (r *Distribution) Restrictions() pulumi.Output {\n\treturn r.s.State[\"restrictions\"]\n}", "func (o ServicePerimeterSpecVpcAccessibleServicesOutput) EnableRestriction() pulumi.BoolPtrOutput {\n\treturn o.ApplyT(func(v ServicePerimeterSpecVpcAccessibleServices) *bool { return v.EnableRestriction }).(pulumi.BoolPtrOutput)\n}", "func (m *SecuritySchemeMutator) Description(v string) *SecuritySchemeMutator {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\tm.proxy.description = v\n\treturn m\n}", "func (cnc CarrierNameCriterion) AsAnnouncementFeedbackCriterion() (*AnnouncementFeedbackCriterion, bool) {\n\treturn nil, false\n}", "func (ace *ActiveContainerError) Forbidden() {}", "func (o GoogleCloudRetailV2alphaModelPageOptimizationConfigResponseOutput) Restriction() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaModelPageOptimizationConfigResponse) string { return v.Restriction }).(pulumi.StringOutput)\n}", "func (g *Generator) UseWordlistEFFShort() {\n\tg.wordlist = wordlists[\"en_eff_short\"]\n}", "func (c *CseSiterestrictListCall) Safe(safe string) *CseSiterestrictListCall {\n\tc.urlParams_.Set(\"safe\", safe)\n\treturn c\n}", "func (o ServicePerimeterSpecOutput) RestrictedServices() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ServicePerimeterSpec) []string { return v.RestrictedServices }).(pulumi.StringArrayOutput)\n}", "func DefaultEndpointAuthorizationsForReadOnlyUserRole(volumeBrowsingAuthorizations bool) portainer.Authorizations {\n\tauthorizations := map[portainer.Authorization]bool{\n\t\tportainer.OperationDockerContainerArchiveInfo: true,\n\t\tportainer.OperationDockerContainerList: true,\n\t\tportainer.OperationDockerContainerChanges: true,\n\t\tportainer.OperationDockerContainerInspect: true,\n\t\tportainer.OperationDockerContainerTop: true,\n\t\tportainer.OperationDockerContainerLogs: true,\n\t\tportainer.OperationDockerContainerStats: true,\n\t\tportainer.OperationDockerImageList: true,\n\t\tportainer.OperationDockerImageSearch: true,\n\t\tportainer.OperationDockerImageGetAll: true,\n\t\tportainer.OperationDockerImageGet: true,\n\t\tportainer.OperationDockerImageHistory: true,\n\t\tportainer.OperationDockerImageInspect: true,\n\t\tportainer.OperationDockerNetworkList: true,\n\t\tportainer.OperationDockerNetworkInspect: true,\n\t\tportainer.OperationDockerVolumeList: true,\n\t\tportainer.OperationDockerVolumeInspect: true,\n\t\tportainer.OperationDockerSwarmInspect: true,\n\t\tportainer.OperationDockerNodeList: true,\n\t\tportainer.OperationDockerNodeInspect: true,\n\t\tportainer.OperationDockerServiceList: true,\n\t\tportainer.OperationDockerServiceInspect: true,\n\t\tportainer.OperationDockerServiceLogs: true,\n\t\tportainer.OperationDockerSecretList: true,\n\t\tportainer.OperationDockerSecretInspect: true,\n\t\tportainer.OperationDockerConfigList: true,\n\t\tportainer.OperationDockerConfigInspect: true,\n\t\tportainer.OperationDockerTaskList: true,\n\t\tportainer.OperationDockerTaskInspect: true,\n\t\tportainer.OperationDockerTaskLogs: true,\n\t\tportainer.OperationDockerPluginList: true,\n\t\tportainer.OperationDockerDistributionInspect: true,\n\t\tportainer.OperationDockerPing: true,\n\t\tportainer.OperationDockerInfo: true,\n\t\tportainer.OperationDockerVersion: true,\n\t\tportainer.OperationDockerEvents: true,\n\t\tportainer.OperationDockerSystem: true,\n\t\tportainer.OperationDockerAgentPing: true,\n\t\tportainer.OperationDockerAgentList: true,\n\t\tportainer.OperationDockerAgentHostInfo: true,\n\t\tportainer.OperationPortainerStackList: true,\n\t\tportainer.OperationPortainerStackInspect: true,\n\t\tportainer.OperationPortainerStackFile: true,\n\t\tportainer.OperationPortainerWebhookList: true,\n\t}\n\n\tif volumeBrowsingAuthorizations {\n\t\tauthorizations[portainer.OperationDockerAgentBrowseGet] = true\n\t\tauthorizations[portainer.OperationDockerAgentBrowseList] = true\n\t}\n\n\treturn authorizations\n}", "func StridedSliceEllipsisMask(value int64) StridedSliceAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"ellipsis_mask\"] = value\n\t}\n}", "func configureFlags(api *operations.ReservoirAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func (fm FeatureMap) SetSimple(name string, unknownsAllowed bool, f func() bool) {\n\tif f() {\n\t\tfm[name] = &providers.DocumentationNote{HasFeature: true}\n\t} else if !unknownsAllowed {\n\t\tfm[name] = &providers.DocumentationNote{HasFeature: false}\n\t}\n}", "func (flags SEFlags) AuthorityMeasure() bool {\n\treturn flags&0x04 != 0\n}", "func usageCSRFlags(w io.Writer, line int) {\n\tfmt.Fprintln(w, \"CSR field options:\")\n\tlistOpts(w, []string{\n\t\tcommonNameFlag,\n\t\tserialNumberFlag,\n\t\torganizationalUnitFlag,\n\t\torganizationFlag,\n\t\tstreetAddressFlag,\n\t\tlocalityFlag,\n\t\tprovinceFlag,\n\t\tpostalCodeFlag,\n\t\tcountryFlag,\n\t\tdnsNamesFlag,\n\t\temailsFlag,\n\t\tipsFlag,\n\t\turisFlag,\n\t})\n\tfmt.Fprintln(w)\n\n\toutputPara(w, line, 0, usageCSRMultiPara)\n}", "func (s ServiceSpecs) SupportService(serviceUrl string, serviceOrg string) bool {\n\tif serviceUrl == \"\" {\n\t\treturn true\n\t} else {\n\t\tif len(s) == 0 {\n\t\t\treturn true\n\t\t} else {\n\t\t\tfor _, sp := range s {\n\t\t\t\tif sp.Url == serviceUrl && (sp.Org == \"\" || sp.Org == serviceOrg) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func (o ServicePerimetersServicePerimeterSpecVpcAccessibleServicesOutput) EnableRestriction() pulumi.BoolPtrOutput {\n\treturn o.ApplyT(func(v ServicePerimetersServicePerimeterSpecVpcAccessibleServices) *bool { return v.EnableRestriction }).(pulumi.BoolPtrOutput)\n}", "func addJoinConfigFlags(flagSet *flag.FlagSet, cfg *kubeadmapiv1.JoinConfiguration) {\n\tflagSet.StringVar(\n\t\t&cfg.NodeRegistration.Name, options.NodeName, cfg.NodeRegistration.Name,\n\t\t`Specify the node name.`,\n\t)\n\tflagSet.StringVar(\n\t\t&cfg.ControlPlane.CertificateKey, options.CertificateKey, cfg.ControlPlane.CertificateKey,\n\t\t\"Use this key to decrypt the certificate secrets uploaded by init.\",\n\t)\n\t// add control plane endpoint flags to the specified flagset\n\tflagSet.StringVar(\n\t\t&cfg.ControlPlane.LocalAPIEndpoint.AdvertiseAddress, options.APIServerAdvertiseAddress, cfg.ControlPlane.LocalAPIEndpoint.AdvertiseAddress,\n\t\t\"If the node should host a new control plane instance, the IP address the API Server will advertise it's listening on. If not set the default network interface will be used.\",\n\t)\n\tflagSet.Int32Var(\n\t\t&cfg.ControlPlane.LocalAPIEndpoint.BindPort, options.APIServerBindPort, cfg.ControlPlane.LocalAPIEndpoint.BindPort,\n\t\t\"If the node should host a new control plane instance, the port for the API Server to bind to.\",\n\t)\n\t// adds bootstrap token specific discovery flags to the specified flagset\n\tflagSet.StringVar(\n\t\t&cfg.Discovery.BootstrapToken.Token, options.TokenDiscovery, \"\",\n\t\t\"For token-based discovery, the token used to validate cluster information fetched from the API server.\",\n\t)\n\tflagSet.StringSliceVar(\n\t\t&cfg.Discovery.BootstrapToken.CACertHashes, options.TokenDiscoveryCAHash, []string{},\n\t\t\"For token-based discovery, validate that the root CA public key matches this hash (format: \\\"<type>:<value>\\\").\",\n\t)\n\tflagSet.BoolVar(\n\t\t&cfg.Discovery.BootstrapToken.UnsafeSkipCAVerification, options.TokenDiscoverySkipCAHash, false,\n\t\t\"For token-based discovery, allow joining without --discovery-token-ca-cert-hash pinning.\",\n\t)\n\t//\tdiscovery via kube config file flag\n\tflagSet.StringVar(\n\t\t&cfg.Discovery.File.KubeConfigPath, options.FileDiscovery, \"\",\n\t\t\"For file-based discovery, a file or URL from which to load cluster information.\",\n\t)\n\tflagSet.StringVar(\n\t\t&cfg.Discovery.TLSBootstrapToken, options.TLSBootstrapToken, cfg.Discovery.TLSBootstrapToken,\n\t\t`Specify the token used to temporarily authenticate with the Kubernetes Control Plane while joining the node.`,\n\t)\n\tcmdutil.AddCRISocketFlag(flagSet, &cfg.NodeRegistration.CRISocket)\n}", "func SupportFlags(cmd *cobra.Command) {\n\tcmd.Flags().StringVarP(&URL, \"url\", \"u\", \"\", \"Recipe URL\")\n\tcmd.Flags().StringVarP(&FilePath, \"filepath\", \"f\", \"\", \"Recipe file path\")\n}", "func configureFlags(api *operations.KubernikusAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func permitOps(includeOperations []string) []string {\n\tif includeOperations == nil {\n\t\treturn nil\n\t}\n\tvar filterOps []string\n\tfor _, ops := range includeOperations {\n\t\tops := strings.ToLower(ops)\n\t\tif _, exist := allowedMaps[ops]; exist {\n\t\t\tfilterOps = append(filterOps, ops)\n\t\t}\n\t}\n\treturn filterOps\n}", "func (_BaseContentSpace *BaseContentSpaceCaller) CanContribute(opts *bind.CallOpts, _candidate common.Address) (bool, error) {\n\tvar out []interface{}\n\terr := _BaseContentSpace.contract.Call(opts, &out, \"canContribute\", _candidate)\n\n\tif err != nil {\n\t\treturn *new(bool), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(bool)).(*bool)\n\n\treturn out0, err\n\n}", "func (me XsdGoPkgHasAttr_Restriction_TrestrictionType_Private) RestrictionDefault() TrestrictionType {\n\treturn TrestrictionType(\"private\")\n}", "func createSupportBundleSpecSecret(app apptypes.AppType, sequence int64, kotsKinds *kotsutil.KotsKinds, secretName string, builtBundle *troubleshootv1beta2.SupportBundle, opts types.TroubleshootOptions, clientset kubernetes.Interface) error {\n\ts := serializer.NewYAMLSerializer(serializer.DefaultMetaFactory, scheme.Scheme, scheme.Scheme)\n\tvar b bytes.Buffer\n\tif err := s.Encode(builtBundle, &b); err != nil {\n\t\treturn errors.Wrap(err, \"failed to encode support bundle\")\n\t}\n\n\ttemplatedSpec := b.Bytes()\n\n\trenderedSpec, err := helper.RenderAppFile(app, &sequence, templatedSpec, kotsKinds, util.PodNamespace)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed render support bundle spec\")\n\t}\n\n\t// unmarshal the spec, look for image replacements in collectors and then remarshal\n\t// we do this after template rendering to support templating and then replacement\n\tsupportBundle, err := kotsutil.LoadSupportBundleFromContents(renderedSpec)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to unmarshal rendered support bundle spec\")\n\t}\n\n\tvar registrySettings registrytypes.RegistrySettings\n\tif !util.IsHelmManaged() {\n\t\ts, err := store.GetStore().GetRegistryDetailsForApp(app.GetID())\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to get registry settings for app\")\n\t\t}\n\t\tregistrySettings = s\n\t}\n\n\tcollectors, err := registry.UpdateCollectorSpecsWithRegistryData(supportBundle.Spec.Collectors, registrySettings, kotsKinds.Installation, kotsKinds.License, &kotsKinds.KotsApplication)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to update collectors\")\n\t}\n\tsupportBundle.Spec.Collectors = collectors\n\tb.Reset()\n\tif err := s.Encode(supportBundle, &b); err != nil {\n\t\treturn errors.Wrap(err, \"failed to encode support bundle\")\n\t}\n\trenderedSpec = b.Bytes()\n\n\texistingSecret, err := clientset.CoreV1().Secrets(util.PodNamespace).Get(context.TODO(), secretName, metav1.GetOptions{})\n\tlabels := kotstypes.MergeLabels(kotstypes.GetKotsadmLabels(), kotstypes.GetTroubleshootLabels())\n\tif err != nil {\n\t\tif kuberneteserrors.IsNotFound(err) {\n\t\t\tsecret := &corev1.Secret{\n\t\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t\tKind: \"Secret\",\n\t\t\t\t},\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: secretName,\n\t\t\t\t\tNamespace: util.PodNamespace,\n\t\t\t\t\tLabels: labels,\n\t\t\t\t},\n\t\t\t\tData: map[string][]byte{\n\t\t\t\t\tSpecDataKey: renderedSpec,\n\t\t\t\t},\n\t\t\t}\n\n\t\t\t_, err = clientset.CoreV1().Secrets(util.PodNamespace).Create(context.TODO(), secret, metav1.CreateOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"failed to create support bundle secret\")\n\t\t\t}\n\n\t\t\tlogger.Debugf(\"created %q support bundle spec secret\", secretName)\n\t\t} else {\n\t\t\treturn errors.Wrap(err, \"failed to read support bundle secret\")\n\t\t}\n\t} else {\n\t\tif existingSecret.Data == nil {\n\t\t\texistingSecret.Data = map[string][]byte{}\n\t\t}\n\t\texistingSecret.Data[SpecDataKey] = renderedSpec\n\t\texistingSecret.ObjectMeta.Labels = labels\n\n\t\t_, err = clientset.CoreV1().Secrets(util.PodNamespace).Update(context.TODO(), existingSecret, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to update support bundle secret\")\n\t\t}\n\t}\n\treturn nil\n}", "func configureFlags(api *operations.EsiAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func (me TrestrictionType) IsPrivate() bool { return me.String() == \"private\" }", "func (*AnalyzerOrgPolicyConstraint_CustomConstraint) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_asset_v1_asset_service_proto_rawDescGZIP(), []int{53, 1}\n}", "func TestIsAllowed(t *testing.T) {\n\tdummyProxy := &proxy{\n\t\tvalidHostsSupplier: func() []string {\n\t\t\treturn []string{\"test1.com\", \"test2.io\", \"test3.org\"}\n\t\t},\n\t}\n\n\tassert.Equal(t, false, dummyProxy.isAllowed(\"\"))\n\tassert.Equal(t, false, dummyProxy.isAllowed(\"test1.org\"))\n\tassert.Equal(t, false, dummyProxy.isAllowed(\"test4.com\"))\n\tassert.Equal(t, true, dummyProxy.isAllowed(\"test2.io\"))\n\n\tdummyProxy = &proxy{\n\t\tvalidHostsSupplier: func() []string {\n\t\t\treturn []string{\"*test1.com\", \"test2.io\", \"test3.org\"}\n\t\t},\n\t}\n\n\tassert.Equal(t, true, dummyProxy.isAllowed(\"123test1.com\"))\n\tassert.Equal(t, false, dummyProxy.isAllowed(\"123test1.io\"))\n\n\tdummyProxy = &proxy{\n\t\tvalidHostsSupplier: func() []string {\n\t\t\treturn []string{\"foo.%.alpha.com\", \"test2.io\", \"test3.org\"}\n\t\t},\n\t}\n\n\tassert.Equal(t, false, dummyProxy.isAllowed(\"123test1.com\"))\n\tassert.Equal(t, true, dummyProxy.isAllowed(\"foo.bar.alpha.com\"))\n\tassert.Equal(t, false, dummyProxy.isAllowed(\"foo.bar.baz.alpha.com\"))\n}", "func (k *KV) CAS(p *KVPair, q *WriteOptions) (bool, *WriteMeta, error) {\n\tparams := make(map[string]string, 2)\n\tif p.Flags != 0 {\n\t\tparams[\"flags\"] = strconv.FormatUint(p.Flags, 10)\n\t}\n\tparams[\"cas\"] = strconv.FormatUint(p.ModifyIndex, 10)\n\treturn k.put(p.Key, params, p.Value, q)\n}", "func NewApplicationEnforcedRestrictionsSessionControl()(*ApplicationEnforcedRestrictionsSessionControl) {\n m := &ApplicationEnforcedRestrictionsSessionControl{\n ConditionalAccessSessionControl: *NewConditionalAccessSessionControl(),\n }\n odataTypeValue := \"#microsoft.graph.applicationEnforcedRestrictionsSessionControl\";\n m.SetOdataType(&odataTypeValue);\n return m\n}", "func CollectiveGatherCommunicationHint(value string) CollectiveGatherAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"communication_hint\"] = value\n\t}\n}", "func configureFlags(api *operations.ToDoDemoAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func configureFlags(api *operations.ToDoDemoAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func (p *ParsedConsent) PurposeAllowed(pu int) bool {\n\t_, ok := p.purposesAllowed[pu]\n\treturn ok\n}", "func (a *HyperflexApiService) CreateHyperflexFeatureLimitExternal(ctx context.Context) ApiCreateHyperflexFeatureLimitExternalRequest {\n\treturn ApiCreateHyperflexFeatureLimitExternalRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func TestSizeRestrictions(t *testing.T) {\n\tvar (\n\t\tserverRestrictions = Restrictions{\n\t\t\tMinimum: 6000,\n\t\t\tMaximum: 10000,\n\t\t}\n\n\t\tprepay, routing = testPPMFees(defaultFeePPM, testQuote, 7000)\n\t\toutSwap = loop.OutRequest{\n\t\t\tAmount: 7000,\n\t\t\tOutgoingChanSet: loopdb.ChannelSet{chanID1.ToUint64()},\n\t\t\tMaxPrepayRoutingFee: prepay,\n\t\t\tMaxSwapRoutingFee: routing,\n\t\t\tMaxMinerFee: scaleMaxMinerFee(\n\t\t\t\tscaleMinerFee(testQuote.MinerFee),\n\t\t\t),\n\t\t\tMaxSwapFee: testQuote.SwapFee,\n\t\t\tMaxPrepayAmount: testQuote.PrepayAmount,\n\t\t\tSweepConfTarget: defaultConfTarget,\n\t\t\tInitiator: autoloopSwapInitiator,\n\t\t}\n\t)\n\n\ttests := []struct {\n\t\tname string\n\n\t\t// clientRestrictions holds the restrictions that the client\n\t\t// has configured.\n\t\tclientRestrictions Restrictions\n\n\t\tprepareMock func(m *mockServer)\n\n\t\t// suggestions is the set of suggestions we expect.\n\t\tsuggestions *Suggestions\n\n\t\t// expectedError is the error we expect.\n\t\texpectedError error\n\t}{\n\t\t{\n\t\t\tname: \"minimum more than server, swap happens\",\n\t\t\tclientRestrictions: Restrictions{\n\t\t\t\tMinimum: 7000,\n\t\t\t},\n\t\t\tsuggestions: &Suggestions{\n\t\t\t\tOutSwaps: []loop.OutRequest{\n\t\t\t\t\tchan1Rec,\n\t\t\t\t},\n\t\t\t\tDisqualifiedChans: noneDisqualified,\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"minimum more than server, no swap\",\n\t\t\tclientRestrictions: Restrictions{\n\t\t\t\tMinimum: 8000,\n\t\t\t},\n\t\t\tsuggestions: &Suggestions{\n\t\t\t\tDisqualifiedChans: map[lnwire.ShortChannelID]Reason{\n\t\t\t\t\tchanID1: ReasonLiquidityOk,\n\t\t\t\t},\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"maximum less than server, swap happens\",\n\t\t\tclientRestrictions: Restrictions{\n\t\t\t\tMaximum: 7000,\n\t\t\t},\n\t\t\tsuggestions: &Suggestions{\n\t\t\t\tOutSwaps: []loop.OutRequest{\n\t\t\t\t\toutSwap,\n\t\t\t\t},\n\t\t\t\tDisqualifiedChans: noneDisqualified,\n\t\t\t\tDisqualifiedPeers: noPeersDisqualified,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// Originally, our client params are ok. But then the\n\t\t\t// server increases its minimum, making the client\n\t\t\t// params stale.\n\t\t\tname: \"client params stale over time\",\n\t\t\tclientRestrictions: Restrictions{\n\t\t\t\tMinimum: 6500,\n\t\t\t\tMaximum: 9000,\n\t\t\t},\n\t\t\tprepareMock: func(m *mockServer) {\n\t\t\t\trestrictions := serverRestrictions\n\n\t\t\t\tm.On(\n\t\t\t\t\t\"Restrictions\", mock.Anything,\n\t\t\t\t\tswap.TypeOut,\n\t\t\t\t).Return(\n\t\t\t\t\t&restrictions, nil,\n\t\t\t\t).Once()\n\n\t\t\t\tm.On(\n\t\t\t\t\t\"Restrictions\", mock.Anything,\n\t\t\t\t\tswap.TypeOut,\n\t\t\t\t).Return(\n\t\t\t\t\t&Restrictions{\n\t\t\t\t\t\tMinimum: 5000,\n\t\t\t\t\t\tMaximum: 6000,\n\t\t\t\t\t}, nil,\n\t\t\t\t).Once()\n\t\t\t},\n\t\t\tsuggestions: nil,\n\t\t\texpectedError: ErrMaxExceedsServer,\n\t\t},\n\t}\n\n\tfor _, testCase := range tests {\n\t\ttestCase := testCase\n\n\t\tt.Run(testCase.name, func(t *testing.T) {\n\t\t\tcfg, lnd := newTestConfig()\n\n\t\t\tlnd.Channels = []lndclient.ChannelInfo{\n\t\t\t\tchannel1,\n\t\t\t}\n\n\t\t\tparams := defaultParameters\n\t\t\tparams.AutoloopBudgetLastRefresh = testBudgetStart\n\t\t\tparams.ClientRestrictions = testCase.clientRestrictions\n\t\t\tparams.ChannelRules = map[lnwire.ShortChannelID]*SwapRule{\n\t\t\t\tchanID1: chanRule,\n\t\t\t}\n\n\t\t\t// Use a mock that has our expected calls for the test\n\t\t\t// case set to provide server restrictions.\n\t\t\tmockServer := &mockServer{}\n\n\t\t\t// If the test wants us to prime the mock, use its\n\t\t\t// function, otherwise just return our default\n\t\t\t// restrictions.\n\t\t\tif testCase.prepareMock != nil {\n\t\t\t\ttestCase.prepareMock(mockServer)\n\t\t\t} else {\n\t\t\t\trestrictions := serverRestrictions\n\n\t\t\t\tmockServer.On(\n\t\t\t\t\t\"Restrictions\", mock.Anything,\n\t\t\t\t\tmock.Anything,\n\t\t\t\t).Return(&restrictions, nil)\n\t\t\t}\n\n\t\t\tcfg.Restrictions = mockServer.Restrictions\n\n\t\t\ttestSuggestSwaps(\n\t\t\t\tt, newSuggestSwapsSetup(cfg, lnd, params),\n\t\t\t\ttestCase.suggestions, testCase.expectedError,\n\t\t\t)\n\n\t\t\tmockServer.AssertExpectations(t)\n\t\t})\n\t}\n}", "func CollectiveReduceV2CommunicationHint(value string) CollectiveReduceV2Attr {\n\treturn func(m optionalAttr) {\n\t\tm[\"communication_hint\"] = value\n\t}\n}", "func shouldRotateEntry(rotation *rkev1.RotateCertificates, entry *planEntry) bool {\n\trelevantServices := map[string]struct{}{}\n\n\tif len(rotation.Services) == 0 {\n\t\treturn true\n\t}\n\n\tif isWorker(entry) {\n\t\trelevantServices[\"rke2-server\"] = struct{}{}\n\t\trelevantServices[\"k3s-server\"] = struct{}{}\n\t\trelevantServices[\"api-server\"] = struct{}{}\n\t\trelevantServices[\"kubelet\"] = struct{}{}\n\t\trelevantServices[\"kube-proxy\"] = struct{}{}\n\t\trelevantServices[\"auth-proxy\"] = struct{}{}\n\t}\n\n\tif isControlPlane(entry) {\n\t\trelevantServices[\"rke2-server\"] = struct{}{}\n\t\trelevantServices[\"k3s-server\"] = struct{}{}\n\t\trelevantServices[\"api-server\"] = struct{}{}\n\t\trelevantServices[\"kubelet\"] = struct{}{}\n\t\trelevantServices[\"kube-proxy\"] = struct{}{}\n\t\trelevantServices[\"auth-proxy\"] = struct{}{}\n\t\trelevantServices[\"controller-manager\"] = struct{}{}\n\t\trelevantServices[\"scheduler\"] = struct{}{}\n\t\trelevantServices[\"rke2-controller\"] = struct{}{}\n\t\trelevantServices[\"k3s-controller\"] = struct{}{}\n\t\trelevantServices[\"admin\"] = struct{}{}\n\t\trelevantServices[\"cloud-controller\"] = struct{}{}\n\t}\n\n\tif isEtcd(entry) {\n\t\trelevantServices[\"etcd\"] = struct{}{}\n\t\trelevantServices[\"kubelet\"] = struct{}{}\n\t\trelevantServices[\"k3s-server\"] = struct{}{}\n\t\trelevantServices[\"rke2-server\"] = struct{}{}\n\t}\n\n\tfor i := range rotation.Services {\n\t\tif _, ok := relevantServices[rotation.Services[i]]; ok {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (o SkuResponseOutput) Restrictions() RestrictionResponseArrayOutput {\n\treturn o.ApplyT(func(v SkuResponse) []RestrictionResponse { return v.Restrictions }).(RestrictionResponseArrayOutput)\n}", "func configureFlags(api *operations.OpenPitrixAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func LookupPolicyDecisions(datasetID string, policyCompiler pc.IPolicyCompiler, req *modules.DataInfo, input *app.M4DApplication, op pb.AccessOperation_AccessType) {\n\t// call external policy manager to get governance instructions for this operation\n\tappContext := ConstructApplicationContext(datasetID, input, op)\n\tvar flow app.ModuleFlow\n\tswitch op {\n\tcase pb.AccessOperation_READ:\n\t\tflow = app.Read\n\tcase pb.AccessOperation_COPY:\n\t\tflow = app.Copy\n\tcase pb.AccessOperation_WRITE:\n\t\tflow = app.Write\n\t}\n\tpcresponse, err := policyCompiler.GetPoliciesDecisions(appContext)\n\tif err != nil {\n\t\terrStatus, _ := status.FromError(err)\n\t\treq.Actions[flow] = modules.Transformations{\n\t\t\tAllowed: false,\n\t\t\tMessage: errStatus.Message(),\n\t\t\tReason: utils.DetermineCause(err, \"PolicyManagerService\"),\n\t\t\tEnforcementActions: make([]pb.EnforcementAction, 0),\n\t\t}\n\t} else {\n\t\tfor _, datasetDecision := range pcresponse.GetDatasetDecisions() {\n\t\t\tif datasetDecision.GetDataset().GetDatasetId() != datasetID {\n\t\t\t\tcontinue // not our data set\n\t\t\t}\n\t\t\tvar actions []pb.EnforcementAction\n\t\t\toperationDecisions := datasetDecision.GetDecisions()\n\t\t\tfor _, operationDecision := range operationDecisions {\n\t\t\t\tenforcementActions := operationDecision.GetEnforcementActions()\n\t\t\t\tfor _, action := range enforcementActions {\n\t\t\t\t\tif utils.IsDenied(action.GetName()) {\n\t\t\t\t\t\tvar msg, reason string\n\t\t\t\t\t\tif operationDecision.Operation.Type == pb.AccessOperation_READ {\n\t\t\t\t\t\t\tmsg = \"Governance policies forbid access to the data\"\n\t\t\t\t\t\t\treason = \"AccessDenied\"\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tmsg = \"Copy of the data is required but can not be done according to the governance policies.\"\n\t\t\t\t\t\t\treason = \"CopyDenied\"\n\t\t\t\t\t\t}\n\t\t\t\t\t\treq.Actions[flow] = modules.Transformations{\n\t\t\t\t\t\t\tAllowed: false,\n\t\t\t\t\t\t\tMessage: msg,\n\t\t\t\t\t\t\tReason: reason,\n\t\t\t\t\t\t\tEnforcementActions: make([]pb.EnforcementAction, 0),\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\t// Check if this is a real action (i.e. not Allow)\n\t\t\t\t\tif utils.IsAction(action.GetName()) {\n\t\t\t\t\t\tactions = append(actions, *action.DeepCopy())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treq.Actions[flow] = modules.Transformations{\n\t\t\t\tAllowed: true,\n\t\t\t\tEnforcementActions: actions,\n\t\t\t}\n\t\t}\n\t}\n}", "func (m *baggageRestrictionManager) GetBaggageRestrictions(serviceName string) ([]*baggage.BaggageRestriction, error) {\n\tm.Lock()\n\tdefer m.Unlock()\n\tif restrictions, ok := m.restrictions[serviceName]; ok {\n\t\treturn restrictions, nil\n\t}\n\treturn nil, nil\n}", "func (*AnalyzerOrgPolicyConstraint_Constraint_ListConstraint) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_asset_v1_asset_service_proto_rawDescGZIP(), []int{53, 0, 0}\n}", "func (b *Builder) attributeRestriction(cond *protocol.Condition_AttributeRestriction) elementary {\n\tif len(cond.Values) == 0 {\n\t\treturn alwaysFalse\n\t}\n\n\tattr := b.internStr(cond.Attribute)\n\tvals := b.internSet(cond.Values)\n\n\treturn func(ctx context.Context, attrs realms.Attrs) bool {\n\t\tif val, known := attrs[attr]; known {\n\t\t\t_, match := vals[val]\n\t\t\treturn match\n\t\t}\n\t\treturn false\n\t}\n}", "func Configure(api *operations.ClaAPI, service IService, sessionStore *dynastore.Store, signatureService signatures.SignatureService, eventsService events.Service) {\n\n\tapi.CompanyAddCclaWhitelistRequestHandler = company.AddCclaWhitelistRequestHandlerFunc(\n\t\tfunc(params company.AddCclaWhitelistRequestParams) middleware.Responder {\n\t\t\treqID := utils.GetRequestID(params.XREQUESTID)\n\t\t\tctx := context.WithValue(context.Background(), utils.XREQUESTID, reqID) // nolint\n\t\t\trequestID, err := service.AddCclaApprovalListRequest(ctx, params.CompanyID, params.ProjectID, params.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn company.NewAddCclaWhitelistRequestBadRequest().WithXRequestID(reqID).WithPayload(errorResponse(err))\n\t\t\t}\n\n\t\t\teventsService.LogEventWithContext(ctx, &events.LogEventArgs{\n\t\t\t\tEventType: events.CCLAApprovalListRequestCreated,\n\t\t\t\tProjectID: params.ProjectID,\n\t\t\t\tCompanyID: params.CompanyID,\n\t\t\t\tUserID: params.Body.ContributorID,\n\t\t\t\tEventData: &events.CCLAApprovalListRequestCreatedEventData{RequestID: requestID},\n\t\t\t})\n\n\t\t\treturn company.NewAddCclaWhitelistRequestOK().WithXRequestID(reqID)\n\t\t})\n\n\tapi.CompanyApproveCclaWhitelistRequestHandler = company.ApproveCclaWhitelistRequestHandlerFunc(\n\t\tfunc(params company.ApproveCclaWhitelistRequestParams, claUser *user.CLAUser) middleware.Responder {\n\t\t\treqID := utils.GetRequestID(params.XREQUESTID)\n\t\t\tctx := context.WithValue(context.Background(), utils.XREQUESTID, reqID) // nolint\n\t\t\terr := service.ApproveCclaApprovalListRequest(ctx, claUser, params.CompanyID, params.ProjectID, params.RequestID)\n\t\t\tif err != nil {\n\t\t\t\treturn company.NewApproveCclaWhitelistRequestBadRequest().WithXRequestID(reqID).WithPayload(errorResponse(err))\n\t\t\t}\n\n\t\t\teventsService.LogEventWithContext(ctx, &events.LogEventArgs{\n\t\t\t\tEventType: events.CCLAApprovalListRequestApproved,\n\t\t\t\tProjectID: params.ProjectID,\n\t\t\t\tCompanyID: params.CompanyID,\n\t\t\t\tUserID: claUser.UserID,\n\t\t\t\tEventData: &events.CCLAApprovalListRequestApprovedEventData{RequestID: params.RequestID},\n\t\t\t})\n\n\t\t\treturn company.NewApproveCclaWhitelistRequestOK().WithXRequestID(reqID)\n\t\t})\n\n\tapi.CompanyRejectCclaWhitelistRequestHandler = company.RejectCclaWhitelistRequestHandlerFunc(\n\t\tfunc(params company.RejectCclaWhitelistRequestParams, claUser *user.CLAUser) middleware.Responder {\n\t\t\treqID := utils.GetRequestID(params.XREQUESTID)\n\t\t\tctx := context.WithValue(context.Background(), utils.XREQUESTID, reqID) // nolint\n\t\t\terr := service.RejectCclaApprovalListRequest(ctx, params.CompanyID, params.ProjectID, params.RequestID)\n\t\t\tif err != nil {\n\t\t\t\treturn company.NewRejectCclaWhitelistRequestBadRequest().WithXRequestID(reqID).WithPayload(errorResponse(err))\n\t\t\t}\n\n\t\t\teventsService.LogEventWithContext(ctx, &events.LogEventArgs{\n\t\t\t\tEventType: events.CCLAApprovalListRequestRejected,\n\t\t\t\tProjectID: params.ProjectID,\n\t\t\t\tCompanyID: params.CompanyID,\n\t\t\t\tUserID: claUser.UserID,\n\t\t\t\tEventData: &events.CCLAApprovalListRequestRejectedEventData{RequestID: params.RequestID},\n\t\t\t})\n\n\t\t\treturn company.NewRejectCclaWhitelistRequestOK().WithXRequestID(reqID)\n\t\t})\n\n\tapi.CompanyListCclaWhitelistRequestsHandler = company.ListCclaWhitelistRequestsHandlerFunc(\n\t\tfunc(params company.ListCclaWhitelistRequestsParams, claUser *user.CLAUser) middleware.Responder {\n\t\t\treqID := utils.GetRequestID(params.XREQUESTID)\n\t\t\tctx := context.WithValue(context.Background(), utils.XREQUESTID, reqID) // nolint\n\t\t\tf := logrus.Fields{\n\t\t\t\t\"functionName\": \"CompanyListCclaWhitelistRequestsHandler\",\n\t\t\t\tutils.XREQUESTID: ctx.Value(utils.XREQUESTID),\n\t\t\t}\n\t\t\tlog.WithFields(f).Debugf(\"Invoking ListCclaApprovalListRequests with Company ID: %+v, Project ID: %+v, Status: %+v\",\n\t\t\t\tparams.CompanyID, params.ProjectID, params.Status)\n\t\t\tresult, err := service.ListCclaApprovalListRequest(params.CompanyID, params.ProjectID, params.Status)\n\t\t\tif err != nil {\n\t\t\t\treturn company.NewListCclaWhitelistRequestsBadRequest().WithXRequestID(reqID).WithPayload(errorResponse(err))\n\t\t\t}\n\n\t\t\treturn company.NewListCclaWhitelistRequestsOK().WithXRequestID(reqID).WithPayload(result)\n\t\t})\n\n\tapi.CompanyListCclaWhitelistRequestsByCompanyAndProjectHandler = company.ListCclaWhitelistRequestsByCompanyAndProjectHandlerFunc(\n\t\tfunc(params company.ListCclaWhitelistRequestsByCompanyAndProjectParams, claUser *user.CLAUser) middleware.Responder {\n\t\t\treqID := utils.GetRequestID(params.XREQUESTID)\n\t\t\tctx := context.WithValue(context.Background(), utils.XREQUESTID, reqID) // nolint\n\t\t\tf := logrus.Fields{\n\t\t\t\t\"functionName\": \"v1.approval_list.handlers.CompanyListCclaWhitelistRequestsByCompanyAndProjectHandler\",\n\t\t\t\tutils.XREQUESTID: ctx.Value(utils.XREQUESTID),\n\t\t\t\t\"companyID\": params.CompanyID,\n\t\t\t\t\"projectID\": params.ProjectID,\n\t\t\t\t\"status\": utils.StringValue(params.Status),\n\t\t\t\t\"claUserName\": claUser.Name,\n\t\t\t\t\"claUserUserID\": claUser.UserID,\n\t\t\t\t\"claUserLFEmail\": claUser.LFEmail,\n\t\t\t\t\"claUserLFUsername\": claUser.LFUsername,\n\t\t\t}\n\t\t\tlog.WithFields(f).Debugf(\"Invoking ListCclaApprovalListRequestByCompanyProjectUser with Company ID: %+v, Project ID: %+v, Status: %+v\",\n\t\t\t\tparams.CompanyID, params.ProjectID, params.Status)\n\t\t\tresult, err := service.ListCclaApprovalListRequestByCompanyProjectUser(params.CompanyID, &params.ProjectID, params.Status, nil)\n\t\t\tif err != nil {\n\t\t\t\treturn company.NewListCclaWhitelistRequestsByCompanyAndProjectBadRequest().WithPayload(errorResponse(err))\n\t\t\t}\n\n\t\t\treturn company.NewListCclaWhitelistRequestsByCompanyAndProjectOK().WithPayload(result)\n\t\t})\n\n\tapi.CompanyListCclaWhitelistRequestsByCompanyAndProjectAndUserHandler = company.ListCclaWhitelistRequestsByCompanyAndProjectAndUserHandlerFunc(\n\t\tfunc(params company.ListCclaWhitelistRequestsByCompanyAndProjectAndUserParams, claUser *user.CLAUser) middleware.Responder {\n\t\t\tlog.Debugf(\"Invoking ListCclaApprovalListRequestByCompanyProjectUser with Company ID: %+v, Project ID: %+v, Status: %+v, User: %+v\",\n\t\t\t\tparams.CompanyID, params.ProjectID, params.Status, claUser.LFUsername)\n\t\t\tresult, err := service.ListCclaApprovalListRequestByCompanyProjectUser(params.CompanyID, &params.ProjectID, params.Status, &claUser.LFUsername)\n\t\t\tif err != nil {\n\t\t\t\treturn company.NewListCclaWhitelistRequestsByCompanyAndProjectAndUserBadRequest().WithPayload(errorResponse(err))\n\t\t\t}\n\n\t\t\treturn company.NewListCclaWhitelistRequestsByCompanyAndProjectAndUserOK().WithPayload(result)\n\t\t})\n}" ]
[ "0.5919251", "0.50340575", "0.47609738", "0.46032247", "0.46032247", "0.4576036", "0.43962824", "0.4389457", "0.43631983", "0.43160895", "0.42956102", "0.42474902", "0.42231268", "0.42087105", "0.42079505", "0.41916513", "0.4179671", "0.4169304", "0.4164298", "0.41262516", "0.41205466", "0.41181144", "0.41167685", "0.40760985", "0.40758228", "0.4056817", "0.40451807", "0.40339392", "0.40315774", "0.40303624", "0.4027508", "0.40240332", "0.40221843", "0.40170905", "0.40159848", "0.40144855", "0.40046355", "0.39944336", "0.39918312", "0.39814836", "0.39792466", "0.39772832", "0.39764816", "0.39758465", "0.39632508", "0.3963035", "0.39602977", "0.39590487", "0.39558077", "0.39348385", "0.39331034", "0.3927346", "0.39268017", "0.39259097", "0.3924927", "0.39239684", "0.39096987", "0.39081025", "0.39062643", "0.3902907", "0.39013058", "0.38946515", "0.3893217", "0.3890012", "0.38879678", "0.38867715", "0.3884833", "0.38780463", "0.38780248", "0.3874087", "0.3872498", "0.387099", "0.38694832", "0.3869249", "0.3858295", "0.385791", "0.38544887", "0.38543046", "0.38517466", "0.38501376", "0.3846375", "0.3846242", "0.38423452", "0.3840799", "0.3840712", "0.38406813", "0.38397086", "0.38397086", "0.3838296", "0.3832842", "0.38326344", "0.38313472", "0.38299334", "0.3828718", "0.3827594", "0.38274488", "0.38257775", "0.38242722", "0.38179776", "0.38172588" ]
0.74843174
0
SupportAsync registers a boolean flag for enabling asynchronous command behaviour in flagSet, storing the value provided in p. The default for the flag is to not perform requests asynchronously. It will replace the flag lookup for "async".
func SupportAsync(flagSet *pflag.FlagSet, p *bool) { flagSet.BoolVar(p, "async", false, "perform the operation asynchronously, using the configured timeout duration") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (req *SetRequest) Async() bool {\n\treturn req.impl.Async()\n}", "func WithAsyncFunc(f func(r Result)) InvocationOption {\n\treturn func(op InvocationOp) InvocationOp { op.Func = f; op.Async = true; return op }\n}", "func Async(a bool) CollectorOption {\n\treturn func(collector *Collector) {\n\t\tcollector.async = a\n\t}\n}", "func EnableAsynchronousCloser(closer bool) {\n\tAsynchronousCloser = closer\n}", "func (impl *Impl) SetAsync() error {\n\timpl.forever = true\n\treturn impl.buffer.SetAsync()\n}", "func EagerPyFuncIsAsync(value bool) EagerPyFuncAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"is_async\"] = value\n\t}\n}", "func (e *Event) Async() {\r\n\te.async = true\r\n}", "func (defintion *IndexDefinition) SetAsync(value bool) (outDef *IndexDefinition) {\n\toutDef = defintion\n\toutDef.Async = value\n\treturn\n}", "func (req *GetRequest) Async() bool {\n\treturn req.impl.Async()\n}", "func (c CommitterProbe) SetUseAsyncCommit() {\n\tc.useAsyncCommit = 1\n}", "func Asyncrhronous() MigrationOption {\n\treturn func(m Migration) {\n\t\tm.Base().async = true\n\t}\n}", "func (this *ThreadCtl) MarkStartAsync() {\n\tgo func() {\n\t\tthis.signalChan <- \"start\"\n\t}()\n}", "func DoAsync(repos []string, fwrap Wrapper) {\n\tviper.Set(config.UseSync, false)\n\tDo(repos, fwrap)\n}", "func handleAsync(req *netm.Request) netm.Response {\n\treturn netm.Response{Status: &netm.Status{Type: netm.Status_NO_ERROR, Message: \"Success\"}}\n}", "func WithSynchronous(v bool) Option {\n\treturn synchronousOption(v)\n}", "func (o SyncCallbackOption) IsOption() {}", "func (c *Client) AnswerAsyncNotify(rsp bool, msg string) string {\n\tret := map[string]interface{}{\n\t\t\"response\": rsp,\n\t\t\"msg\": msg,\n\t}\n\tdata, err := json.Marshal(ret)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn string(data)\n}", "func (rb *RequestBuilder) AsyncOptions(url string, f func(*Response)) {\n\tgo func() {\n\t\tf(rb.Options(url))\n\t}()\n}", "func (this *ThreadCtl) MarkStopAsync() {\n\tgo func() {\n\t\tthis.signalChan <- \"stop\"\n\t}()\n}", "func asyncRequest(cmd egoscale.AsyncCommand, msg string) (interface{}, error) {\n\tresponse := cs.Response(cmd)\n\n\tfmt.Print(msg)\n\tvar errorReq error\n\tcs.AsyncRequestWithContext(gContext, cmd, func(jobResult *egoscale.AsyncJobResult, err error) bool {\n\n\t\tfmt.Print(\".\")\n\n\t\tif err != nil {\n\t\t\terrorReq = err\n\t\t\treturn false\n\t\t}\n\n\t\tif jobResult.JobStatus == egoscale.Pending {\n\t\t\treturn true\n\t\t}\n\n\t\tif errR := jobResult.Result(response); errR != nil {\n\t\t\terrorReq = errR\n\t\t\treturn false\n\t\t}\n\n\t\tfmt.Println(\" success.\")\n\t\treturn false\n\t})\n\n\tif errorReq != nil {\n\t\tfmt.Println(\" failure!\")\n\t}\n\n\treturn response, errorReq\n}", "func DemonstrateAsyncCall(wg *sync.WaitGroup) {\r\n\tvar consumer Consumer\r\n\tconsumer.Init()\r\n\tconsumer.Subscribe(waitOnResult, waitOnError, waitOnCompletion)\r\n\tconsumer.ExecuteAsyncOp(wg)\r\n\tfmt.Println(\"Caller continuing ..\")\r\n\twg.Wait()\r\n}", "func (s *Sun) StartAsync() {\n\ts.start(true)\n}", "func CheckAsync(doCheckVersion, inContainer, isDSImage bool) <-chan *CheckVersionInfo {\n\tresultCh := make(chan *CheckVersionInfo, 1)\n\n\tif doCheckVersion {\n\t\tgo func() {\n\t\t\tresultCh <- Check(inContainer, isDSImage)\n\t\t}()\n\t} else {\n\t\tclose(resultCh)\n\t}\n\n\treturn resultCh\n}", "func isPrimeAsync(number int64, channel chan PrimeResult) {\n\n\tresult:= new (PrimeResult)\n\tresult.number= number\n\tresult.prime= isPrime(number)\n\tchannel <- *result\n}", "func (pinger *PerpetualPinger) pingAsync(self phi.Task) {\n\tresponder := make(chan phi.Message, 1)\n\tok := pinger.ponger.Send(Ping{Responder: responder})\n\tif !ok {\n\t\tpanic(\"failed to send ping\")\n\t}\n\tgo func() {\n\t\tfor m := range responder {\n\t\t\tok := self.Send(m)\n\t\t\tif !ok {\n\t\t\t\tpanic(\"failed to receive pong\")\n\t\t\t}\n\t\t}\n\t}()\n}", "func WithAsync() EventConfigurator {\n\treturn func(handler EventHandler) {\n\t\th := handler.(*eventHandler)\n\t\th.async = true\n\t}\n}", "func StartAsync(ctx context.Context) {\n\tgo func() {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\terr := manager().processOnce()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t}()\n}", "func BenchmarkIncAsync(b *testing.B) {\n\tchain, reqs := initBenchmark(b)\n\tsolobench.RunBenchmarkAsync(b, chain, reqs, nil)\n}", "func IsSubscribeAsync(m Mono) bool {\n\treturn mono.IsSubscribeAsync(m.Raw())\n}", "func (o *InvestmentsTransactionsGetRequestOptions) HasAsyncUpdate() bool {\n\tif o != nil && o.AsyncUpdate != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (f *Flagger) Bool(name, shorthand string, value bool, usage string) {\n\tf.cmd.Flags().BoolP(name, shorthand, value, usage)\n\tf.cfg.BindPFlag(name, f.cmd.Flags().Lookup(name))\n}", "func (client *Client) EnableAsync(routinePoolSize, maxTaskQueueSize int) {\n\tclient.asyncTaskQueue = make(chan func(), maxTaskQueueSize)\n\tfor i := 0; i < routinePoolSize; i++ {\n\t\tgo func() {\n\t\t\tfor client.isRunning {\n\t\t\t\tselect {\n\t\t\t\tcase task, notClosed := <-client.asyncTaskQueue:\n\t\t\t\t\tif notClosed {\n\t\t\t\t\t\ttask()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n}", "func supportSyntaxToBool(instanceTypeSupport *string) *bool {\n\tif instanceTypeSupport == nil {\n\t\treturn nil\n\t}\n\tif strings.ToLower(*instanceTypeSupport) == required || strings.ToLower(*instanceTypeSupport) == supported || strings.ToLower(*instanceTypeSupport) == \"default\" {\n\t\treturn aws.Bool(true)\n\t}\n\treturn aws.Bool(false)\n}", "func Synchronous(b bool) func(e *Endpoint) {\n\treturn func(e *Endpoint) { e.synchronous = b }\n}", "func (bf NaiveBloomFilter) LookupAsync(entry string) (bool, error) {\n\thashes := hashEntry([]byte(entry), bf.hf)\n\tfor i := 0; i < bf.hf; i++ {\n\t\tlookup_idx := hashes[i] & (bf.size - 1)\n\t\tif exists, err := bf.getByteAsync(lookup_idx); !exists {\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\treturn false, nil\n\t\t}\n\t}\n\treturn true, nil\n}", "func (async *async) isPending() bool {\n\tstate := atomic.LoadUint32(&async.state)\n\treturn state == pending\n}", "func AsyncRead() MountOption {\n\treturn func(conf *mountConfig) error {\n\t\tconf.initFlags |= InitAsyncRead\n\t\treturn nil\n\t}\n}", "func (c CommitterProbe) IsAsyncCommit() bool {\n\treturn c.isAsyncCommit()\n}", "func (p *MeterProvider) registerAsyncInstrument(a *Async, m *MeterImpl, runner sdkapi.AsyncRunner) {\n\tp.lock.Lock()\n\tdefer p.lock.Unlock()\n\n\tm.asyncInstruments.Register(a, runner)\n}", "func ServeAsync(port int, closing chan bool, acceptHandler OnAccept) error {\n\tl, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", port))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tserver := new(Server)\n\tserver.Closing = closing\n\tserver.OnAccept = acceptHandler\n\tgo server.Serve(l)\n\treturn nil\n}", "func GRPCSupport() bool {\n\tverString := os.Getenv(PluginVaultVersionEnv)\n\n\t// If the env var is empty, we fall back to netrpc for backward compatibility.\n\tif verString == \"\" {\n\t\treturn false\n\t}\n\n\tif verString != \"unknown\" {\n\t\tver, err := version.NewVersion(verString)\n\t\tif err != nil {\n\t\t\treturn true\n\t\t}\n\n\t\t// Due to some regressions on 0.9.2 & 0.9.3 we now require version 0.9.4\n\t\t// to allow the plugin framework to default to gRPC.\n\t\tconstraint, err := version.NewConstraint(\">= 0.9.4\")\n\t\tif err != nil {\n\t\t\treturn true\n\t\t}\n\n\t\treturn constraint.Check(ver)\n\t}\n\n\treturn true\n}", "func (p *protocol) NonBlocking() bool {\n\treturn false\n}", "func asyncExecute(wg *sync.WaitGroup, fn func()) {\n\t(*wg).Add(1)\n\tgo func() {\n\t\tdefer (*wg).Done()\n\t\tfn()\n\t}()\n}", "func (_Onesplitaudit *OnesplitauditCaller) FLAGENABLEMULTIPATHETH(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Onesplitaudit.contract.Call(opts, &out, \"FLAG_ENABLE_MULTI_PATH_ETH\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (o *InvestmentsTransactionsGetRequestOptions) SetAsyncUpdate(v bool) {\n\to.AsyncUpdate = &v\n}", "func (w *WebServer) StartAsync() {\n\t// Crée mon channel pour le signal d'arret\n\tw.ChannelStop = make(chan os.Signal, 1)\n\n\tsignal.Notify(w.ChannelStop, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)\n\n\tgo func() {\n\t\tw.start()\n\t}()\n}", "func NewUnsupportedAsyncEnqueueAccess() EnqueueDataAccess {\n\treturn &noAsyncEnqueueAccess{}\n}", "func (bf BloomFilter) LookupAsync(entry string) (bool, error) {\n\thashes := hashEntry([]byte(entry), bf.hf)\n\tfor i := 0; i < bf.hf; i++ {\n\t\tlookup_idx := hashes[i] & (bf.size - 1)\n\t\tif exists, err := bf.getBitAsync(lookup_idx); !exists {\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\treturn false, nil\n\t\t}\n\t}\n\treturn true, nil\n}", "func RunAsync(yml load.Config, samplesToMerge *load.SamplesToMerge, originalAPINo int) {\n\tload.Logrus.WithFields(logrus.Fields{\n\t\t\"name\": yml.Name,\n\t\t\"apis\": len(yml.APIs),\n\t}).Debug(\"config: processing apis: ASYNC mode. Will skip StoreLookups VariableLookups for: \")\n\n\t// load secrets\n\t_ = loadSecrets(&yml)\n\tvar wgapi sync.WaitGroup\n\twgapi.Add(len(yml.APIs))\n\n\t// Throttle to rate limit for Async request\n\trl := ratelimit.NewUnlimited()\n\tif yml.APIs[0].AsyncRate != 0 {\n\t\trl = ratelimit.New(yml.APIs[0].AsyncRate)\n\t}\n\tload.Logrus.WithFields(logrus.Fields{\n\t\t\"Async Rate\": yml.APIs[0].AsyncRate,\n\t\t\"apis\": yml.APIs[0].Name,\n\t}).Debug(\"API Async Throttle Setting: \")\n\n\tfor i := range yml.APIs {\n\t\trl.Take()\n\t\tgo func(originalAPINo int, i int) {\n\t\t\tdefer wgapi.Done()\n\t\t\tdataSets := FetchData(i, &yml, samplesToMerge)\n\t\t\tprocessor.RunDataHandler(dataSets, samplesToMerge, i, &yml, originalAPINo)\n\t\t}(originalAPINo, i)\n\t}\n\twgapi.Wait()\n\n\tload.Logrus.WithFields(logrus.Fields{\n\t\t\"name\": yml.Name,\n\t\t\"apis\": len(yml.APIs),\n\t}).Debug(\"config: finished processing apis: ASYNC Mode\")\n\n\t// processor.ProcessSamplesToMerge(&samplesToMerge, &yml)\n\t// hren joinAndMerge processing - replacing processor.ProcessSamplesToMerge\n\t// ProcessSamplesMergeJoin will be processed in the run() function for the whole config\n\t// processor.ProcessSamplesMergeJoin(&samplesToMerge, &yml)\n}", "func (_Onesplitaudit *OnesplitauditCallerSession) FLAGENABLEMULTIPATHETH() (*big.Int, error) {\n\treturn _Onesplitaudit.Contract.FLAGENABLEMULTIPATHETH(&_Onesplitaudit.CallOpts)\n}", "func (o *InvestmentsTransactionsGetRequestOptions) GetAsyncUpdate() bool {\n\tif o == nil || o.AsyncUpdate == nil {\n\t\tvar ret bool\n\t\treturn ret\n\t}\n\treturn *o.AsyncUpdate\n}", "func (txn TxnProbe) IsAsyncCommit() bool {\n\treturn txn.committer.isAsyncCommit()\n}", "func (bf StripedBloomFilter) LookupAsync(entry string) (bool, error) {\n\thashes := hashEntry([]byte(entry), bf.hf)\n\tfor i := 0; i < bf.hf; i++ {\n\t\tlookup_idx := hashes[i] & (bf.size - 1)\n\t\tif exists, err := bf.getBitAsync(lookup_idx); !exists {\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\treturn false, nil\n\t\t}\n\t}\n\treturn true, nil\n}", "func Async() Fitting {\n\treturn &asyncFitting{}\n}", "func (s *Synchronizer) AddAsyncChannel(group, identifier interface{}, c channels.SimpleOutChannel) {\n\tif group == nil {\n\t\tgroup = \"global_internal\"\n\t\ts.SetGroupPipeline(group, s.globalPipeline)\n\t}\n\n\ts.asyncChannels[group] = append(s.asyncChannels[group], ChannelContainer{c, identifier})\n}", "func (_Onesplitaudit *OnesplitauditSession) FLAGENABLEMULTIPATHETH() (*big.Int, error) {\n\treturn _Onesplitaudit.Contract.FLAGENABLEMULTIPATHETH(&_Onesplitaudit.CallOpts)\n}", "func SupportFlags(cmd *cobra.Command) {\n\tcmd.Flags().StringVarP(&URL, \"url\", \"u\", \"\", \"Recipe URL\")\n\tcmd.Flags().StringVarP(&FilePath, \"filepath\", \"f\", \"\", \"Recipe file path\")\n}", "func WrapAsyncProducer(p sarama.AsyncProducer, conf *sarama.Config, sensor instana.TracerLogger) *AsyncProducer {\n\tap := &AsyncProducer{\n\t\tAsyncProducer: p,\n\t\tsensor: sensor,\n\t\tinput: make(chan *sarama.ProducerMessage),\n\t\tsuccesses: make(chan *sarama.ProducerMessage),\n\t\terrors: make(chan *sarama.ProducerError),\n\t\tchannelStates: apAllChansReady,\n\t}\n\n\tif conf != nil {\n\t\tap.propageContext = contextPropagationSupported(conf.Version)\n\t\tap.awaitResult = conf.Producer.Return.Successes && conf.Producer.Return.Errors\n\t\tap.activeSpans = newSpanRegistry()\n\t}\n\n\tgo ap.consume()\n\n\treturn ap\n}", "func (e *Exclusive) CallAsync(key interface{}, value func() (interface{}, error)) <-chan *ExclusiveOutcome {\n\treturn e.CallAfterAsync(key, value, 0)\n}", "func (rb *RequestBuilder) AsyncPatch(url string, body interface{}, f func(*Response)) {\n\tgo func() {\n\t\tf(rb.Patch(url, body))\n\t}()\n}", "func (c *remotingClient) InvokeAsync(ctx context.Context, addr string, request *RemotingCommand, callback func(*ResponseFuture)) error {\n\tconn, err := c.connect(ctx, addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresp := NewResponseFuture(ctx, request.Opaque, callback)\n\tc.responseTable.Store(resp.Opaque, resp)\n\terr = c.sendRequest(conn, request)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo primitive.WithRecover(func() {\n\t\tc.receiveAsync(resp)\n\t})\n\treturn nil\n}", "func (m *SearchAlterationOptions) SetEnableSuggestion(value *bool)() {\n m.enableSuggestion = value\n}", "func (m *Manager) doAsync(ctx context.Context, target string, arg interface{}, period, timeout time.Duration, ops ...interface{}) {\n\tlogger := logging.FromContext(ctx)\n\tgo func() {\n\t\tdefer func() {\n\t\t\tm.mu.Lock()\n\t\t\tdefer m.mu.Unlock()\n\t\t\tm.keys.Delete(target)\n\t\t}()\n\t\tvar (\n\t\t\tresult bool\n\t\t\tinErr error\n\t\t)\n\t\terr := wait.PollImmediate(period, timeout, func() (bool, error) {\n\t\t\tresult, inErr = Do(ctx, m.transport, target, ops...)\n\t\t\t// Do not return error, which is from verifierError, as retry is expected until timeout.\n\t\t\treturn result, nil\n\t\t})\n\t\tif inErr != nil {\n\t\t\tlogger.Errorw(\"Unable to read sockstat\", zap.Error(inErr))\n\t\t}\n\t\tm.cb(arg, result, err)\n\t}()\n}", "func (d *Detector) RunAsync() chan (error) {\n\tgo func() {\n\t\tdefer close(d.c)\n\t\tif err := d.Run(); err != nil {\n\t\t\t// Return the error to the calling thread\n\t\t\td.c <- err\n\t\t}\n\t}()\n\treturn d.c\n}", "func (_Onesplitaudit *OnesplitauditCaller) FLAGENABLEMULTIPATHDAI(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Onesplitaudit.contract.Call(opts, &out, \"FLAG_ENABLE_MULTI_PATH_DAI\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (nopBroadcaster) SendAsync(Message) error { return nil }", "func (stream *NopStream) PublishAsync(event interface{}) <-chan error {\n\terrChan := make(chan error, 1)\n\terrChan <- nil\n\treturn errChan\n}", "func updateAsync(updateStruct *Update, callback chan *Callback) {\n\trecords, err := update(updateStruct)\n\tcb := new(Callback)\n\tcb.Data = records\n\tcb.Error = err\n\tcallback <- cb\n}", "func (m *Manager) NextPendingSupported() bool {\n\tm.pendingLock.RLock()\n\tdefer m.pendingLock.RUnlock()\n\tif len(m.pending) == 0 {\n\t\treturn true\n\t}\n\n\treturn m.SupportedVersions().Supports(m.pending[0].ProtocolVersion)\n}", "func AddPersistentBoolFlag(cmd *cobra.Command, name string, aliases, nonPersistentAliases []string, value bool, env, usage string) {\n\tif env != \"\" {\n\t\tusage = fmt.Sprintf(\"%s [$%s]\", usage, env)\n\t}\n\tif envV, ok := os.LookupEnv(env); ok {\n\t\tvar err error\n\t\tvalue, err = strconv.ParseBool(envV)\n\t\tif err != nil {\n\t\t\tlogrus.WithError(err).Warnf(\"Invalid boolean value for `%s`\", env)\n\t\t}\n\t}\n\taliasesUsage := fmt.Sprintf(\"Alias of --%s\", name)\n\tp := new(bool)\n\tflags := cmd.Flags()\n\tfor _, a := range nonPersistentAliases {\n\t\tif len(a) == 1 {\n\t\t\t// pflag doesn't support short-only flags, so we have to register long one as well here\n\t\t\tflags.BoolVarP(p, a, a, value, aliasesUsage)\n\t\t} else {\n\t\t\tflags.BoolVar(p, a, value, aliasesUsage)\n\t\t}\n\t}\n\n\tpersistentFlags := cmd.PersistentFlags()\n\tpersistentFlags.BoolVar(p, name, value, usage)\n\tfor _, a := range aliases {\n\t\tif len(a) == 1 {\n\t\t\t// pflag doesn't support short-only flags, so we have to register long one as well here\n\t\t\tpersistentFlags.BoolVarP(p, a, a, value, aliasesUsage)\n\t\t} else {\n\t\t\tpersistentFlags.BoolVar(p, a, value, aliasesUsage)\n\t\t}\n\t}\n}", "func awaitSync(ctx context.Context, client api.Server, revision string, timeout time.Duration) error {\n\treturn backoff(1*time.Second, 2, 10, timeout, func() (bool, error) {\n\t\trefs, err := client.SyncStatus(ctx, revision)\n\t\treturn err == nil && len(refs) == 0, err\n\t})\n}", "func (c *Controller) SetDeviceStatusAsync(d *ControllerDevice, status bool) error {\n\treturn c.setDeviceStatus(d, status, true)\n}", "func (client PrimitiveClient) PutBoolResponder(resp *http.Response) (result autorest.Response, err error) { \n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByClosing())\n result.Response = resp\n return\n}", "func SupportCAS(flagSet *pflag.FlagSet, p *string) func() bool {\n\tconst casName = \"cas\"\n\n\tflagSet.StringVar(p, casName, \"\", \"make changes to a resource conditional upon matching the provided version\")\n\n\treturn func() bool {\n\t\treturn flagSet.Changed(casName)\n\t}\n}", "func (server *Server) asyncCallService(conn *ConnDriver, seq uint64, service *service, methodType *methodType, argv, replyv reflect.Value) {\n\tserver.replyCmd(conn, seq, nil, CmdTypeAck)\n\tfunction := methodType.method.Func\n\t// Invoke the method, providing a new value for the reply.\n\tfunction.Call([]reflect.Value{service.rcvr, argv, replyv})\n\treturn\n}", "func TestBool(t *testing.T) {\n\ttestCases := []struct {\n\t\tname string\n\t\tbroker CeleryBroker\n\t\tbackend CeleryBackend\n\t\ttaskName string\n\t\ttaskFunc interface{}\n\t\tinA bool\n\t\tinB bool\n\t\texpected bool\n\t}{\n\t\t{\n\t\t\tname: \"boolean and operation with redis broker/backend\",\n\t\t\tbroker: redisBroker,\n\t\t\tbackend: redisBackend,\n\t\t\ttaskName: uuid.Must(uuid.NewV4(), nil).String(),\n\t\t\ttaskFunc: andBool,\n\t\t\tinA: true,\n\t\t\tinB: false,\n\t\t\texpected: false,\n\t\t},\n\t}\n\tfor _, tc := range testCases {\n\t\tcli, _ := NewCeleryClient(tc.broker, tc.backend, 1)\n\t\tcli.Register(tc.taskName, tc.taskFunc)\n\t\tcli.StartWorker()\n\t\tasyncResult, err := cli.Delay(tc.taskName, tc.inA, tc.inB)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"test '%s': failed to get result for task %s: %+v\", tc.name, tc.taskName, err)\n\t\t\tcli.StopWorker()\n\t\t\tcontinue\n\t\t}\n\t\tres, err := asyncResult.Get(TIMEOUT)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"test '%s': failed to get result for task %s: %+v\", tc.name, tc.taskName, err)\n\t\t\tcli.StopWorker()\n\t\t\tcontinue\n\t\t}\n\t\tif tc.expected != res.(bool) {\n\t\t\tt.Errorf(\"test '%s': returned result %+v is different from expected result %+v\", tc.name, res, tc.expected)\n\t\t}\n\t\tcli.StopWorker()\n\t}\n}", "func RPC() bool {\n\treturn rpc\n}", "func RPC() bool {\n\treturn rpc\n}", "func (_Onesplitaudit *OnesplitauditCaller) FLAGENABLEMULTIPATHUSDC(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Onesplitaudit.contract.Call(opts, &out, \"FLAG_ENABLE_MULTI_PATH_USDC\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func BoolCommand(e Executor, args ...string) <-chan bool {\n\tc := make(chan bool, 1)\n\te.Execute(boolCommand{args, c})\n\treturn c\n}", "func StartWatchingAsyncARMRequests(ctx context.Context) (armclient.ResponseProcessor, error) {\n\trequestChan := make(chan response)\n\n\tinflightRequests := map[string]pollItem{}\n\n\tgo func() {\n\t\tfor {\n\t\t\tdefer errorhandling.RecoveryWithCleanup()\n\n\t\t\t// Stop the routine if the context is canceled\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\t// returning not to leak the goroutine\n\t\t\t\treturn\n\t\t\tcase request := <-requestChan:\n\t\t\t\tif !isAsyncResponse(request.httpResponse) {\n\t\t\t\t\t// Not an async action, move on.\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tvar pollLocation []string\n\t\t\t\tvar exists bool\n\n\t\t\t\t// Azure header isn't canonical\n\t\t\t\tpollLocation, exists = request.httpResponse.Header[\"Azure-AsyncOperation\"] //nolint:staticcheck\n\t\t\t\tif !exists {\n\t\t\t\t\tpollLocation, exists = request.httpResponse.Header[\"Location\"]\n\t\t\t\t\tif !exists {\n\t\t\t\t\t\teventing.SendFailureStatusFromError(\"Failed to find async poll header\", fmt.Errorf(\"Missing header in %+v\", request.httpResponse.Header))\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tparsedURL, err := url.Parse(request.requestPath)\n\t\t\t\tif err != nil {\n\t\t\t\t\teventing.SendFailureStatusFromError(\"Failed to parse url while making async request\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tresource := request.requestPath\n\t\t\t\tpathSegments := strings.Split(parsedURL.Path, \"/\")\n\t\t\t\tif len(pathSegments) >= 2 {\n\t\t\t\t\tresource = strings.Join(pathSegments[len(pathSegments)-2:], \"/\")\n\t\t\t\t}\n\n\t\t\t\titem := pollItem{\n\t\t\t\t\tpollURI: strings.Join(pollLocation, \"\"),\n\t\t\t\t\ttitle: request.httpResponse.Request.Method + \" \" + resource,\n\t\t\t\t\tstatus: \"unknown\",\n\t\t\t\t\tevent: &eventing.StatusEvent{\n\t\t\t\t\t\tMessage: \"Tracing async event to completion\",\n\t\t\t\t\t\tTimeout: time.Minute * 15,\n\t\t\t\t\t\tInProgress: true,\n\t\t\t\t\t\tIsToast: true,\n\t\t\t\t\t},\n\t\t\t\t}\n\n\t\t\t\teventing.SendStatusEvent(item.event)\n\t\t\t\tinflightRequests[request.requestPath] = item\n\t\t\t}\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tfor {\n\t\t\tdefer errorhandling.RecoveryWithCleanup()\n\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\t// returning not to leak the goroutine\n\t\t\t\treturn\n\t\t\tcase <-time.After(time.Second * 1):\n\t\t\t\t// Continue\n\t\t\t}\n\n\t\t\tfor ID, pollItem := range inflightRequests {\n\t\t\t\t_, done := eventing.SendStatusEvent(&eventing.StatusEvent{\n\t\t\t\t\tMessage: \"Polling async completion \" + pollItem.pollURI,\n\t\t\t\t\tTimeout: time.Second * 5,\n\t\t\t\t\tInProgress: true,\n\t\t\t\t})\n\t\t\t\treq, err := http.NewRequest(\"GET\", pollItem.pollURI, nil)\n\t\t\t\tif err != nil {\n\t\t\t\t\teventing.SendFailureStatusFromError(\"Failed create async poll request\", err)\n\t\t\t\t\tpollItem.event.InProgress = false\n\t\t\t\t\tpollItem.event.Message = \"Async check failed\"\n\t\t\t\t\tpollItem.event.SetTimeout(time.Second * 5)\n\t\t\t\t\tdelete(inflightRequests, ID)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tresponse, err := armclient.LegacyInstance.DoRawRequest(ctx, req)\n\t\t\t\tif err != nil {\n\t\t\t\t\teventing.SendFailureStatusFromError(\"Failed making async poll request\", err)\n\t\t\t\t\tpollItem.event.InProgress = false\n\t\t\t\t\tpollItem.event.Message = \"Async check failed\"\n\t\t\t\t\tpollItem.event.SetTimeout(time.Second * 5)\n\t\t\t\t\tpollItem.event.Done()\n\t\t\t\t\tdelete(inflightRequests, ID)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif response.StatusCode == 200 {\n\t\t\t\t\t// completed\n\t\t\t\t\tpollItem.event.InProgress = false\n\t\t\t\t\tpollItem.event.Message = pollItem.title + \" COMPLETED\"\n\t\t\t\t\tpollItem.event.SetTimeout(time.Second * 5)\n\t\t\t\t\teventing.SendStatusEvent(pollItem.event)\n\n\t\t\t\t\tdelete(inflightRequests, ID)\n\t\t\t\t}\n\n\t\t\t\tif isAsyncResponse(response) {\n\t\t\t\t\t// continue processing\n\t\t\t\t\tpollItem.event.Message = pollItem.title\n\t\t\t\t\teventing.SendStatusEvent(pollItem.event)\n\t\t\t\t}\n\n\t\t\t\t// Pause between each poll item so as not to make huge volume of requests.\n\t\t\t\t<-time.After(time.Second * 2)\n\t\t\t\tdone()\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn func(requestPath string, httpResponse *http.Response, responseBody string) {\n\t\trequestChan <- response{\n\t\t\trequestPath: requestPath,\n\t\t\thttpResponse: httpResponse,\n\t\t\tbody: responseBody,\n\t\t}\n\t}, nil\n}", "func (m *SearchAlterationOptions) GetEnableSuggestion()(*bool) {\n return m.enableSuggestion\n}", "func (adminVdc *AdminVdc) UpdateAsync() (Task, error) {\n\tapiVersion, err := adminVdc.client.MaxSupportedVersion()\n\tif err != nil {\n\t\treturn Task{}, err\n\t}\n\tvdcFunctions := getVdcVersionedFuncsByVdcVersion(\"vdc\" + apiVersionToVcdVersion[apiVersion])\n\tif vdcFunctions.UpdateVdcAsync == nil {\n\t\treturn Task{}, fmt.Errorf(\"function UpdateVdcAsync is not defined for %s\", \"vdc\"+apiVersion)\n\t}\n\tutil.Logger.Printf(\"[DEBUG] UpdateAsync call function for version %s\", vdcFunctions.SupportedVersion)\n\n\treturn vdcFunctions.UpdateVdcAsync(adminVdc)\n\n}", "func (cli *FakeDatabaseClient) DataPumpExportAsync(ctx context.Context, in *dbdpb.DataPumpExportAsyncRequest, opts ...grpc.CallOption) (*lropb.Operation, error) {\n\tpanic(\"implement me\")\n}", "func (bo *BoolOptions) enable(name string) {\n\tif bo.Library != nil {\n\t\tif _, opt := bo.Library.Lookup(name); opt != nil {\n\t\t\tfor _, dependency := range opt.Requires {\n\t\t\t\tbo.enable(dependency)\n\t\t\t}\n\t\t}\n\t}\n\n\tbo.Opts[name] = true\n}", "func TestBoolNamedArguments(t *testing.T) {\n\ttestCases := []struct {\n\t\tname string\n\t\tbroker CeleryBroker\n\t\tbackend CeleryBackend\n\t\ttaskName string\n\t\ttaskFunc interface{}\n\t\tinA bool\n\t\tinB bool\n\t\texpected bool\n\t}{\n\t\t{\n\t\t\tname: \"boolean and operation (named arguments) with redis broker/backend\",\n\t\t\tbroker: redisBroker,\n\t\t\tbackend: redisBackend,\n\t\t\ttaskName: uuid.Must(uuid.NewV4(), nil).String(),\n\t\t\ttaskFunc: &andBoolTask{},\n\t\t\tinA: true,\n\t\t\tinB: false,\n\t\t\texpected: false,\n\t\t},\n\t}\n\tfor _, tc := range testCases {\n\t\tcli, _ := NewCeleryClient(tc.broker, tc.backend, 1)\n\t\tcli.Register(tc.taskName, tc.taskFunc)\n\t\tcli.StartWorker()\n\t\tasyncResult, err := cli.DelayKwargs(\n\t\t\ttc.taskName,\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"a\": tc.inA,\n\t\t\t\t\"b\": tc.inB,\n\t\t\t},\n\t\t)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"test '%s': failed to get result for task %s: %+v\", tc.name, tc.taskName, err)\n\t\t\tcli.StopWorker()\n\t\t\tcontinue\n\t\t}\n\t\tres, err := asyncResult.Get(TIMEOUT)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"test '%s': failed to get result for task %s: %+v\", tc.name, tc.taskName, err)\n\t\t\tcli.StopWorker()\n\t\t\tcontinue\n\t\t}\n\t\tif tc.expected != res.(bool) {\n\t\t\tt.Errorf(\"test '%s': returned result %+v is different from expected result %+v\", tc.name, res, tc.expected)\n\t\t}\n\t\tcli.StopWorker()\n\t}\n}", "func (rn *RemoteNode) SendMessageAsync(msg *protobuf.Message) error {\n\t_, err := rn.SendMessage(msg, false)\n\treturn err\n}", "func (m *Monitor) RunAsync() chan error {\n\tklog.V(5).Info(\"starting leader elect bit\")\n\tgo func() {\n\t\tdefer close(m.c)\n\t\tif err := m.runLeaderElect(); err != nil {\n\t\t\t// Return the error to the calling thread\n\t\t\tm.c <- err\n\t\t}\n\t}()\n\tklog.V(5).Info(\"starting leader elect bit started\")\n\treturn m.c\n}", "func TestAsync(t *testing.T) {\n\tchannelCreate := make(chan bool)\n\tchannelLogin := make(chan bool)\n\tgo createServer()\n\tgo func(channelCreate chan bool) {\n\t\tcreateUser()\n\t\tchannelCreate <- true\n\t}(channelCreate)\n\tgo func(channelCreate chan bool, channelLogin chan bool) {\n\t\ta := <-channelCreate\n\t\tfmt.Printf(\"Create user finished %t \\n\", a)\n\t\tloginClient()\n\t\tchannelLogin <- true\n\t}(channelCreate, channelLogin)\n\tfmt.Printf(\"Login finished %t \\n\", <-channelLogin)\n}", "func OptionalURLParamBool(request *http.Request, name string) (null.Bool, IResponse) {\n\tvalueStr := chi.URLParam(request, name)\n\tif valueStr == \"\" {\n\t\treturn null.Bool{}, nil\n\t}\n\n\tvalue, err := strconv.ParseBool(valueStr)\n\tif err != nil {\n\t\treturn null.Bool{}, BadRequest(request, \"Invalid url param %s (value: '%s'): %s\", name, valueStr, err)\n\t}\n\n\treturn null.BoolFrom(value), nil\n}", "func (s *Server) apiAsync(fn func() error) error {\n\terr := make(chan error)\n\ts.apiAsyncCh <- &Fn{fn: fn, err: err}\n\treturn <-err\n}", "func EnableJSON() {\n\tjsonFlag = true\n\tquietFlag = true\n}", "func main() {\n\tresultChan := make(chan *result)\n\n\t//Async\n\tgo doWorkAsync(resultChan)\n\t//Sync\n\tresult := doWork()\n\n\t//Wait for Async to catch up\n\tresultAsync := <-resultChan\n\t//Merge results\n\tfmt.Println(result.success && resultAsync.success)\n}", "func (t *TestProcessor) CloseAsync() {\n\tprintln(\"Closing async\")\n}", "func readLanguageSettingAsync(userID uuid.UUID, userInfoInReq *UserInfoInReq) <-chan UsersLangSettingsResultAsync {\n\tr := make(chan UsersLangSettingsResultAsync)\n\tgo func() {\n\t\tdefer close(r)\n\n\t\tsettings, err := getUsersLangSettings([]uuid.UUID{userID}, userInfoInReq)\n\t\tif err != nil {\n\t\t\tr <- UsersLangSettingsResultAsync{Error: err}\n\t\t\treturn\n\t\t}\n\t\tr <- UsersLangSettingsResultAsync{settings: settings}\n\n\t}()\n\treturn r\n}", "func CheckAndPrintAsync(printPrefix string, inContainer, isDSImage bool) {\n\tgo func() {\n\t\tPrintCheckVersion(nil, printPrefix, Check(inContainer, isDSImage))\n\t}()\n}", "func processAsyncGroupNotification(commandMessage ctrlservice.AsyncCommandMessage, groupFunction func(lock *commands.CommandLock, groupId string) error) {\n\tcmd, ok := commandMessage.ParsedCommand().(*commands.ConsumerGroupAsyncCommand)\n\tif !ok {\n\t\treturn\n\t}\n\tif cmd.Version != commands.ConsumerGroupAsyncCommandVersion {\n\t\tcommandMessage.NotifyFailed(fmt.Errorf(\"version mismatch; expected %d but got %d\", commands.ConsumerGroupAsyncCommandVersion, cmd.Version))\n\t\treturn\n\t}\n\terr := groupFunction(cmd.Lock, cmd.GroupId)\n\tif err != nil {\n\t\tcommandMessage.NotifyFailed(err)\n\t\treturn\n\t}\n\tcommandMessage.NotifySuccess()\n}", "func (rb *RequestBuilder) AsyncPost(url string, body interface{}, f func(*Response)) {\n\tgo func() {\n\t\tf(rb.Post(url, body))\n\t}()\n}", "func (msf *ModuleSetFlag) RegisterFlag(set *pflag.FlagSet, helpCommand string) {\n\tdescription := \"define the enabled modules (available modules: \" +\n\t\tmsf.availableModules.String() + \")\"\n\tif helpCommand != \"\" {\n\t\tdescription += \" use '\" + helpCommand + \"' for more information\"\n\t}\n\tif msf.shortFlag != \"\" {\n\t\tset.VarP(msf, msf.longFlag, msf.shortFlag, description)\n\t\treturn\n\t}\n\tset.Var(msf, msf.longFlag, description)\n}", "func (server *Server) RunAsync(callback func(errors.Error)) errors.Error {\n\tserver.asyncServer = &http.Server{Addr: server.config.ListenAddress, Handler: server.engine}\n\tvar returnErr errors.Error\n\tgo func() {\n\t\tserver.notifyBeginServing()\n\t\terr := server.asyncServer.ListenAndServe()\n\t\tif err != nil {\n\t\t\tif err == http.ErrServerClosed {\n\t\t\t\treturnErr = ErrGraceShutdown.Make()\n\t\t\t} else {\n\t\t\t\treturnErr = ErrServeFailed.Make().Cause(err)\n\t\t\t}\n\t\t}\n\t\tserver.notifyStopServing()\n\t\tif callback != nil {\n\t\t\tcallback(returnErr)\n\t\t}\n\t}()\n\ttime.Sleep(100 * time.Millisecond)\n\treturn returnErr\n}" ]
[ "0.57410234", "0.56631655", "0.5608101", "0.54808307", "0.5286042", "0.52698576", "0.51638967", "0.5153074", "0.50868076", "0.5010291", "0.5009224", "0.49018347", "0.48715803", "0.4856494", "0.4827606", "0.48106834", "0.48056036", "0.4793825", "0.47810698", "0.46765104", "0.4616788", "0.4614183", "0.45850754", "0.4581969", "0.45751134", "0.4574995", "0.45735654", "0.44957322", "0.4446709", "0.44399366", "0.44221932", "0.440991", "0.4395715", "0.43827462", "0.4382448", "0.43768966", "0.4369941", "0.4368898", "0.43624067", "0.4362345", "0.43539366", "0.43491068", "0.43426624", "0.43282795", "0.43191463", "0.43184707", "0.43051842", "0.42928103", "0.42862776", "0.42740637", "0.4256181", "0.42543444", "0.424511", "0.42343333", "0.42341128", "0.42275792", "0.42267203", "0.42219514", "0.42159888", "0.42073438", "0.42031738", "0.4170725", "0.41677532", "0.41508433", "0.41475943", "0.41351113", "0.41223365", "0.41111547", "0.41078943", "0.41069204", "0.41053358", "0.41012028", "0.40835762", "0.40706056", "0.40623918", "0.40546843", "0.4052308", "0.4052308", "0.40521958", "0.404952", "0.40474996", "0.4046543", "0.40460545", "0.40430555", "0.40270376", "0.4018352", "0.40135777", "0.4013462", "0.4009633", "0.4001926", "0.39983258", "0.39952567", "0.39881778", "0.39876387", "0.39862207", "0.3984863", "0.3984315", "0.39808398", "0.39785796", "0.39719492" ]
0.8311384
0
WarnAboutValueBeingOverwrittenByK8s adds a required flag that makes sure that the user undertstand that the values being set will be overwrtitten by the kubernetes controller label synchronisation mechanism
func WarnAboutValueBeingOverwrittenByK8s(flagSet *pflag.FlagSet) { // ignore the returned boolean pointer - we don't need to check what the value of this flag is _ = flagSet.Bool("i-understand-that-this-value-will-be-overwritten-by-kubernetes", false, "this flag must be set to indicate that the user understands the label synchronisation behaviour "+ "of the kubernetes controller. The flag value (true/false) does not matter.") // we know that the flag exist, so we can safely ingore the returned error _ = cobra.MarkFlagRequired(flagSet, "i-understand-that-this-value-will-be-overwritten-by-kubernetes") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *RetentionLabelSettings) SetIsLabelUpdateAllowed(value *bool)() {\n err := m.GetBackingStore().Set(\"isLabelUpdateAllowed\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *Setting) SetOverwriteAllowed(value *bool)() {\n err := m.GetBackingStore().Set(\"overwriteAllowed\", value)\n if err != nil {\n panic(err)\n }\n}", "func handleOverridableErrs(cmd *cobra.Command, e errors) {\n\tfmt.Println(\"\\nWARN:\")\n\tif len(e) > 0 {\n\t\tsort.Sort(e)\n\t\tfor _, err := range e {\n\t\t\tfmt.Printf(\"%s%s\\n\", indent, err)\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"%s[none]\\n\", indent)\n\t}\n\n\tiw, _ := cmd.Flags().GetBool(\"ignore-warns\")\n\tif !iw && len(e) > 0 {\n\t\tfmt.Printf(\"\\n%sWarnings encountered, partition map not created. Override with --ignore-warns.\\n\", indent)\n\t\tos.Exit(1)\n\t}\n}", "func (m *RetentionLabelSettings) SetIsMetadataUpdateAllowed(value *bool)() {\n err := m.GetBackingStore().Set(\"isMetadataUpdateAllowed\", value)\n if err != nil {\n panic(err)\n }\n}", "func mutationRequired(labels map[string]string) bool {\n\tinject := false\n\tif _, ok := labels[dockhand.AutoUpdateLabelKey]; ok {\n\t\tinject = true\n\t}\n\treturn inject\n}", "func Test_validateImmutableValues(t *testing.T) {\n\toldValues := GetAppInstallOverrideValues(testCluster, \"\")\n\n\t// copy oldValues to newValues to modify\n\tequalValues := make(map[string]any)\n\trawValues, _ := json.Marshal(oldValues)\n\terr := json.Unmarshal(rawValues, &equalValues)\n\tif err != nil {\n\t\tt.Fatalf(\"values unmarshalling failed: %s\", err)\n\t}\n\n\talteredCluster := testCluster.DeepCopy()\n\talteredCluster.Spec.ClusterNetwork.Pods.CIDRBlocks = []string{\"192.123.123.0/24\"}\n\talteredValues := GetAppInstallOverrideValues(alteredCluster, \"\")\n\n\ttests := []struct {\n\t\tname string\n\t\twant field.ErrorList\n\t\timmutableValues []string\n\t\tfieldPath *field.Path\n\t\toldValues map[string]any\n\t\tnewValues map[string]any\n\t}{\n\t\t{\n\t\t\tname: \"equal spec\",\n\t\t\timmutableValues: []string{\"values\"},\n\t\t\twant: field.ErrorList{},\n\t\t\tfieldPath: field.NewPath(\"spec\"),\n\t\t\toldValues: oldValues,\n\t\t\tnewValues: equalValues,\n\t\t},\n\t\t{\n\t\t\tname: \"equal values\",\n\t\t\timmutableValues: []string{\"cni\", \"ipam\", \"ipv6\"},\n\t\t\twant: field.ErrorList{},\n\t\t\tfieldPath: field.NewPath(\"spec\").Child(\"values\"),\n\t\t\toldValues: oldValues,\n\t\t\tnewValues: equalValues,\n\t\t},\n\t\t{\n\t\t\tname: \"ipam modified\",\n\t\t\timmutableValues: []string{\"cni\", \"ipam\", \"ipv6\"},\n\t\t\twant: field.ErrorList{field.Invalid(field.NewPath(\"spec\").Child(\"values\").Child(\"ipam\"), alteredValues[\"ipam\"], \"value is immutable\")},\n\t\t\tfieldPath: field.NewPath(\"spec\").Child(\"values\"),\n\t\t\toldValues: oldValues,\n\t\t\tnewValues: alteredValues,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(\"Test map comparison\", func(t *testing.T) {\n\t\t\tif got := validateImmutableValues(tt.newValues, tt.oldValues, tt.fieldPath, tt.immutableValues); !reflect.DeepEqual(got, tt.want) {\n\t\t\t\tt.Errorf(\"%s: validateImmutableValues() = %v, want %v\", tt.name, got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}", "func AllowOverwrite(existing, new Source) bool {\n\tswitch existing {\n\n\t// KubeAPIServer state can only be overwritten by other kube-apiserver\n\t// state.\n\tcase KubeAPIServer:\n\t\treturn new == KubeAPIServer\n\n\t// Local state can only be overwritten by other local state or\n\t// kube-apiserver state.\n\tcase Local:\n\t\treturn new == Local || new == KubeAPIServer\n\n\t// KVStore can be overwritten by other kvstore, local state, or\n\t// kube-apiserver state.\n\tcase KVStore:\n\t\treturn new == KVStore || new == Local || new == KubeAPIServer\n\n\t// Custom-resource state can be overwritten by everything except\n\t// generated, unspecified and Kubernetes (non-CRD) state\n\tcase CustomResource:\n\t\treturn new != Generated && new != Unspec && new != Kubernetes\n\n\t// Kubernetes state can be overwritten by everything except generated\n\t// and unspecified state\n\tcase Kubernetes:\n\t\treturn new != Generated && new != Unspec\n\n\t// Generated can be overwritten by everything except by Unspecified\n\tcase Generated:\n\t\treturn new != Unspec\n\n\t// Unspecified state can be overwritten by everything\n\tcase Unspec:\n\t\treturn true\n\t}\n\n\treturn true\n}", "func TestAdmissionUpdateRequestsNotApplicable(t *testing.T) {\n\tadmission := clusterResourceOverrideAdmission{}\n\treq := &admissionv1.AdmissionRequest{\n\t\tOperation: \"UPDATE\",\n\t\tResource: metav1.GroupVersionResource{Resource: string(corev1.ResourcePods)},\n\t\tSubResource: \"\",\n\t}\n\tapplicable := admission.IsApplicable(req)\n\tassert.False(t, applicable)\n}", "func setOVNObjectAnnotation(objs []*uns.Unstructured, key, value string) error {\n\tfor _, obj := range objs {\n\t\tif obj.GetAPIVersion() == \"apps/v1\" &&\n\t\t\t(obj.GetKind() == \"DaemonSet\" || obj.GetKind() == \"StatefulSet\") &&\n\t\t\t(obj.GetName() == \"ovnkube-master\" || obj.GetName() == \"ovnkube-node\") {\n\t\t\t// set daemonset annotation\n\t\t\tanno := obj.GetAnnotations()\n\t\t\tif anno == nil {\n\t\t\t\tanno = map[string]string{}\n\t\t\t}\n\t\t\tanno[key] = value\n\t\t\tobj.SetAnnotations(anno)\n\n\t\t\t// set pod template annotation\n\t\t\tanno, _, _ = uns.NestedStringMap(obj.Object, \"spec\", \"template\", \"metadata\", \"annotations\")\n\t\t\tif anno == nil {\n\t\t\t\tanno = map[string]string{}\n\t\t\t}\n\t\t\tanno[key] = value\n\t\t\tif err := uns.SetNestedStringMap(obj.Object, anno, \"spec\", \"template\", \"metadata\", \"annotations\"); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (bmc *Controller) updateNodeLabelsAndAnnotation(k8sNode *coreV1.Node, nodeUUID string) (ctrl.Result, error) {\n\tll := bmc.log.WithField(\"method\", \"updateNodeLabelsAndAnnotation\")\n\n\ttoUpdate := false\n\t// check for annotations\n\tval, ok := k8sNode.GetAnnotations()[bmc.annotationKey]\n\tif bmc.externalAnnotation && !ok {\n\t\tll.Errorf(\"external annotaion %s is not accesible on node %s\", bmc.annotationKey, k8sNode)\n\t}\n\tif !bmc.externalAnnotation && ok {\n\t\tif val == nodeUUID {\n\t\t\tll.Tracef(\"%s value for node %s is already %s\", bmc.annotationKey, k8sNode.Name, nodeUUID)\n\t\t} else {\n\t\t\tll.Warnf(\"%s value for node %s is %s, however should have (according to corresponding Node's UUID) %s, going to update annotation's value.\",\n\t\t\t\tbmc.annotationKey, k8sNode.Name, val, nodeUUID)\n\t\t\tk8sNode.ObjectMeta.Annotations[bmc.annotationKey] = nodeUUID\n\t\t\ttoUpdate = true\n\t\t}\n\t}\n\tif !bmc.externalAnnotation && !ok {\n\t\tll.Errorf(\"annotaion %s is not accesible on node %s\", bmc.annotationKey, k8sNode)\n\t\tif k8sNode.ObjectMeta.Annotations == nil {\n\t\t\tk8sNode.ObjectMeta.Annotations = make(map[string]string, 1)\n\t\t}\n\t\tk8sNode.ObjectMeta.Annotations[bmc.annotationKey] = nodeUUID\n\t\ttoUpdate = true\n\t}\n\n\t// initialize labels map if needed\n\tif k8sNode.Labels == nil {\n\t\tk8sNode.ObjectMeta.Labels = make(map[string]string, 1)\n\t}\n\t// check for OS labels\n\tname, version, err := util.GetOSNameAndVersion(k8sNode.Status.NodeInfo.OSImage)\n\tif err == nil {\n\t\t// os name\n\t\tif k8sNode.Labels[common.NodeOSNameLabelKey] != name {\n\t\t\t// not set or matches\n\t\t\tll.Infof(\"Setting label %s=%s on node %s\", common.NodeOSNameLabelKey, name, k8sNode.Name)\n\t\t\tk8sNode.Labels[common.NodeOSNameLabelKey] = name\n\t\t\ttoUpdate = true\n\t\t}\n\t\t// os version\n\t\tif k8sNode.Labels[common.NodeOSVersionLabelKey] != version {\n\t\t\t// not set or matches\n\t\t\tll.Infof(\"Setting label %s=%s on node %s\", common.NodeOSVersionLabelKey, version, k8sNode.Name)\n\t\t\tk8sNode.Labels[common.NodeOSVersionLabelKey] = version\n\t\t\ttoUpdate = true\n\t\t}\n\t} else {\n\t\tll.Errorf(\"Failed to obtain OS information: %s\", err)\n\t}\n\n\t// check for kernel version label\n\tversion, err = util.GetKernelVersion(k8sNode.Status.NodeInfo.KernelVersion)\n\tif err == nil {\n\t\t// os name\n\t\tif k8sNode.Labels[common.NodeKernelVersionLabelKey] != version {\n\t\t\t// not set or matches\n\t\t\tll.Infof(\"Setting label %s=%s on node %s\", common.NodeKernelVersionLabelKey, version, k8sNode.Name)\n\t\t\tk8sNode.Labels[common.NodeKernelVersionLabelKey] = version\n\t\t\ttoUpdate = true\n\t\t\tif bmc.observer != nil {\n\t\t\t\tbmc.observer.Notify(version)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tll.Errorf(\"Failed to obtain Kernel version information: %s\", err)\n\t}\n\n\tif toUpdate {\n\t\tif err := bmc.k8sClient.UpdateCR(context.Background(), k8sNode); err != nil {\n\t\t\tll.Errorf(\"Unable to update node object: %v\", err)\n\t\t\treturn ctrl.Result{Requeue: true}, err\n\t\t}\n\t}\n\n\treturn ctrl.Result{}, nil\n}", "func emptyObjectDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {\n\t// When a map inside a list contains only default values without explicit values set by\n\t// the user Terraform inteprets the map as not being present and the array length being\n\t// zero, resulting in bogus update that does nothing. Allow ignoring those.\n\tif old == \"1\" && new == \"0\" && strings.HasSuffix(k, \".#\") {\n\t\treturn true\n\t}\n\n\t// When a field is not set to any value and consequently is null (empty string) but had\n\t// a non-empty parameter before. Allow ignoring those.\n\tif new == \"\" && old != \"\" {\n\t\treturn true\n\t}\n\n\t// There is a bug in Terraform 0.11 which interprets \"true\" as \"0\" and \"false\" as \"1\"\n\tif (new == \"0\" && old == \"false\") || (new == \"1\" && old == \"true\") {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func updateOptionalKubeDefaults(desired []entry) {\n\tdefaults := map[string]interface{}{\n\t\t\"disable_local_ca_jwt\": false,\n\t\t\"kubernetes_ca_cert\": \"\",\n\t}\n\tfor _, auth := range desired {\n\t\tif strings.ToLower(auth.Type) == \"kubernetes\" {\n\t\t\tfor _, cfg := range auth.Settings {\n\t\t\t\tfor k, v := range defaults {\n\t\t\t\t\t// denotes that attr was not included in definition and graphql assigned nil\n\t\t\t\t\t// proceed with assigning default value that api would assign if attribute was omitted\n\t\t\t\t\tif cfg[k] == nil {\n\t\t\t\t\t\tcfg[k] = v\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *WorkloadEndpointClient) patchOutAnnotations(ctx context.Context, key model.Key, revision string, uid *types.UID) (*model.KVPair, error) {\n\t// Passing nil for annotations will result in all annotations being explicitly set to the empty string.\n\t// Setting the podIPs to empty string is used to signal that the CNI DEL has removed the IP from the Pod.\n\t// We leave the container ID in place to allow any repeat invocations of the CNI DEL to tell which instance of a Pod they are seeing.\n\tannotations := map[string]string{\n\t\tconversion.AnnotationPodIP: \"\",\n\t\tconversion.AnnotationPodIPs: \"\",\n\t}\n\treturn c.patchPodAnnotations(ctx, key, revision, uid, annotations)\n}", "func (a *KnativeServingConfigurator) mutate(ctx context.Context, ks *servingv1alpha1.KnativeServing) error {\n\tconst (\n\t\tconfigmap = \"network\"\n\t\tkey = \"istio.sidecar.includeOutboundIPRanges\"\n\t\tvalue = \"10.0.0.1/24\"\n\t)\n\tif ks.Spec.Config == nil {\n\t\tks.Spec.Config = map[string]map[string]string{}\n\t}\n\tif len(ks.Spec.Config[configmap][key]) == 0 {\n\t\tif ks.Spec.Config[configmap] == nil {\n\t\t\tks.Spec.Config[configmap] = map[string]string{}\n\t\t}\n\t\tks.Spec.Config[configmap][key] = value\n\t}\n\treturn nil\n}", "func (podPresetStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}", "func (strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}", "func patchK8SConfig(local *ClusterInfo, request *apistructs.ClusterInfo) error {\n\tif request.SchedConfig != nil {\n\t\tif request.SchedConfig.MasterURL != \"\" {\n\t\t\tu, err := url.Parse(request.SchedConfig.MasterURL)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Errorf(\"k8s cluster addr is invalid, addr: %s\", request.SchedConfig.MasterURL)\n\t\t\t}\n\t\t\tlocal.Options[\"ADDR\"] = u.String()\n\t\t}\n\t\tc, err := url.Parse(request.SchedConfig.CPUSubscribeRatio)\n\t\tif err != nil {\n\t\t\treturn errors.Errorf(\"k8s cluster addr is invalid, addr: %s\", request.SchedConfig.MasterURL)\n\t\t}\n\t\tlocal.Options[\"DEV_CPU_SUBSCRIBE_RATIO\"] = c.String()\n\t\tlocal.Options[\"TEST_CPU_SUBSCRIBE_RATIO\"] = c.String()\n\t\tlocal.Options[\"STAGING_CPU_SUBSCRIBE_RATIO\"] = c.String()\n\t}\n\treturn nil\n}", "func forceOnlyRulesWarning(cfg *mybase.Config, names ...string) {\n\twantNames := make(map[string]bool, len(names))\n\tfor _, name := range names {\n\t\twantNames[name] = true\n\t}\n\tfor name, rule := range rulesByName {\n\t\tif wantNames[name] {\n\t\t\tcfg.SetRuntimeOverride(rule.optionName(), string(SeverityWarning))\n\t\t} else {\n\t\t\tcfg.SetRuntimeOverride(rule.optionName(), string(SeverityIgnore))\n\t\t}\n\t}\n}", "func checkValAndDefaultStringSuppress(defaultVal string, checkVal string) schema.SchemaDiffSuppressFunc {\n\treturn func(k, old, new string, d *schema.ResourceData) bool {\n\t\tif _, ok := d.GetOkExists(checkVal); ok {\n\t\t\treturn false\n\t\t}\n\t\treturn (old == \"\" && new == defaultVal) || (new == \"\" && old == defaultVal)\n\t}\n}", "func TestUnknownValues(t *testing.T) {\n\tt.Skip(\"https://github.com/pulumi/pulumi-policy/issues/263\")\n\trunPolicyPackIntegrationTest(t, \"unknown_values\", NodeJS, map[string]string{\n\t\t\"aws:region\": \"us-west-2\",\n\t}, []policyTestScenario{\n\t\t{\n\t\t\tWantErrors: []string{\n\t\t\t\t\"[advisory] unknown-values-policy v0.0.1 unknown-values-resource-validation (random:index/randomPet:RandomPet: pet)\",\n\t\t\t\t\"can't run policy 'unknown-values-resource-validation' during preview: string value at .prefix can't be known during preview\",\n\t\t\t\t\"[advisory] unknown-values-policy v0.0.1 unknown-values-stack-validation\",\n\t\t\t\t\"can't run policy 'unknown-values-stack-validation' during preview: string value at .prefix can't be known during preview\",\n\t\t\t},\n\t\t\tAdvisory: true,\n\t\t},\n\t})\n}", "func updateLabels(pod *corev1.Pod, envoyUID string) *JSONPatchOperation {\n\tif len(pod.Labels) == 0 {\n\t\treturn &JSONPatchOperation{\n\t\t\tOp: \"add\",\n\t\t\tPath: labelsPath,\n\t\t\tValue: map[string]string{constants.EnvoyUniqueIDLabelName: envoyUID},\n\t\t}\n\t}\n\n\tgetOp := func() string {\n\t\tif _, exists := pod.Labels[constants.EnvoyUniqueIDLabelName]; exists {\n\t\t\treturn \"replace\"\n\t\t}\n\t\treturn \"add\"\n\t}\n\n\treturn &JSONPatchOperation{\n\t\tOp: getOp(),\n\t\tPath: path.Join(labelsPath, constants.EnvoyUniqueIDLabelName),\n\t\tValue: envoyUID,\n\t}\n}", "func (m *RetentionLabelSettings) SetIsContentUpdateAllowed(value *bool)() {\n err := m.GetBackingStore().Set(\"isContentUpdateAllowed\", value)\n if err != nil {\n panic(err)\n }\n}", "func setLabelsRetainExisting(src labels.Labels, additionalLabels ...labels.Label) labels.Labels {\n\tlb := labels.NewBuilder(src)\n\n\tfor _, additionalL := range additionalLabels {\n\t\tif oldValue := src.Get(additionalL.Name); oldValue != \"\" {\n\t\t\tlb.Set(\n\t\t\t\tretainExistingPrefix+additionalL.Name,\n\t\t\t\toldValue,\n\t\t\t)\n\t\t}\n\t\tlb.Set(additionalL.Name, additionalL.Value)\n\t}\n\n\treturn lb.Labels()\n}", "func (strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }", "func (m *SecureScoreControlProfile) SetDeprecated(value *bool)() {\n m.deprecated = value\n}", "func (m *SecureScoreControlProfile) SetDeprecated(value *bool)() {\n err := m.GetBackingStore().Set(\"deprecated\", value)\n if err != nil {\n panic(err)\n }\n}", "func (s *NamespaceWebhook) unauthorizedLabelChanges(req admissionctl.Request) (bool, error) {\n\t// When there's a delete operation there are no meaningful changes to protected labels\n\tif req.Operation == admissionv1.Delete {\n\t\treturn false, nil\n\t}\n\n\tnewNamespace, oldNamespace, err := s.renderOldAndNewNamespaces(req)\n\tif err != nil {\n\t\treturn true, err\n\t}\n\tif req.Operation == admissionv1.Create {\n\t\t// For creations, we look to newNamespace and ensure no protectedLabels are set\n\t\t// We don't care about oldNamespace.\n\t\tprotectedLabelsFound := doesNamespaceContainProtectedLabels(newNamespace)\n\t\tif len(protectedLabelsFound) == 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\t// There were some found\n\t\treturn true, fmt.Errorf(\"Managed OpenShift customers may not directly set certain protected labels (%s) on Namespaces\", protectedLabels)\n\t} else if req.Operation == admissionv1.Update {\n\t\t// For Updates we must see if the new object is making a change to the old one for any protected labels.\n\t\t// First, let's see if the old object had any protected labels we ought to\n\t\t// care about. If it has, then we can use that resulting list to compare to\n\t\t// the newNamespace for any changes. However, just because the oldNamespace\n\t\t// did not have any protected labels doesn't necessarily mean that we can\n\t\t// ignore potential setting of those labels' values in the newNamespace.\n\n\t\t// protectedLabelsFoundInOld is a slice of all instances of protectedLabels\n\t\t// that appeared in the oldNamespace that we need to be sure have not\n\t\t// changed.\n\t\tprotectedLabelsFoundInOld := doesNamespaceContainProtectedLabels(oldNamespace)\n\t\t// protectedLabelsFoundInNew is a slice of all instances of protectedLabels\n\t\t// that appeared in the newNamespace that we need to be sure do not have a\n\t\t// value different than oldNamespace.\n\t\tprotectedLabelsFoundInNew := doesNamespaceContainProtectedLabels(newNamespace)\n\n\t\t// First check: Were any protectedLabels deleted?\n\t\tif len(protectedLabelsFoundInOld) != len(protectedLabelsFoundInNew) {\n\t\t\t// If we have x protectedLabels in the oldNamespace then we expect to also\n\t\t\t// have x protectedLabels in the newNamespace. Any difference is a removal or addition\n\t\t\treturn true, fmt.Errorf(\"Managed OpenShift customers may not add or remove protected labels (%s) from Namespaces\", protectedLabels)\n\t\t}\n\t\t// Next check: Compare values to ensure there are no changes in the protected labels\n\t\tfor _, labelKey := range protectedLabelsFoundInOld {\n\t\t\tif oldNamespace.Labels[labelKey] != newNamespace.ObjectMeta.Labels[labelKey] {\n\t\t\t\treturn true, fmt.Errorf(\"Managed OpenShift customers may not change the value or certain protected labels (%s) on Namespaces. %s changed from %s to %s\", protectedLabels, labelKey, oldNamespace.Labels[labelKey], newNamespace.ObjectMeta.Labels[labelKey])\n\t\t\t}\n\t\t}\n\t}\n\treturn false, nil\n}", "func testImmutableOrderField(t *testing.T, fldPath *field.Path, setter func(*cmacme.Order, testValue)) {\n\tt.Run(\"should reject updates to \"+fldPath.String(), func(t *testing.T) {\n\t\texpectedErrs := []*field.Error{\n\t\t\tfield.Forbidden(fldPath, \"field is immutable once set\"),\n\t\t}\n\t\tvar expectedWarnings []string\n\t\told := &cmacme.Order{}\n\t\tnew := &cmacme.Order{}\n\t\tsetter(old, testValueOptionOne)\n\t\tsetter(new, testValueOptionTwo)\n\t\terrs, warnings := ValidateOrderUpdate(someAdmissionRequest, old, new)\n\t\tif len(errs) != len(expectedErrs) {\n\t\t\tt.Errorf(\"Expected errors %v but got %v\", expectedErrs, errs)\n\t\t\treturn\n\t\t}\n\t\tfor i, e := range errs {\n\t\t\texpectedErr := expectedErrs[i]\n\t\t\tif !reflect.DeepEqual(e, expectedErr) {\n\t\t\t\tt.Errorf(\"Expected error %v but got %v\", expectedErr, e)\n\t\t\t}\n\t\t}\n\t\tif !reflect.DeepEqual(warnings, expectedWarnings) {\n\t\t\tt.Errorf(\"Expected warnings %+#v but got %+#v\", expectedWarnings, warnings)\n\t\t}\n\t})\n\tt.Run(\"should allow updates to \"+fldPath.String()+\" if not already set\", func(t *testing.T) {\n\t\texpectedErrs := []*field.Error{}\n\t\tvar expectedWarnings []string\n\t\told := &cmacme.Order{}\n\t\tnew := &cmacme.Order{}\n\t\tsetter(old, testValueNone)\n\t\tsetter(new, testValueOptionOne)\n\t\terrs, warnings := ValidateOrderUpdate(someAdmissionRequest, old, new)\n\t\tif len(errs) != len(expectedErrs) {\n\t\t\tt.Errorf(\"Expected errors %v but got %v\", expectedErrs, errs)\n\t\t\treturn\n\t\t}\n\t\tfor i, e := range errs {\n\t\t\texpectedErr := expectedErrs[i]\n\t\t\tif !reflect.DeepEqual(e, expectedErr) {\n\t\t\t\tt.Errorf(\"Expected error %v but got %v\", expectedErr, e)\n\t\t\t}\n\t\t}\n\t\tif !reflect.DeepEqual(warnings, expectedWarnings) {\n\t\t\tt.Errorf(\"Expected warnings %+#v but got %+#v\", expectedWarnings, warnings)\n\t\t}\n\t})\n}", "func setIgnoreValue(key string, mSubStringIndex *map[string] []int){\n\tignoreKey := key\n\tfor len(ignoreKey) + len(key) <= 10 {\n\t\tignoreKey += key\n\t\t(*mSubStringIndex)[ignoreKey] = []int{-1}\n\t}\n\t\t\n}", "func updateExistingConfigFromFlags(cmd *cobra.Command, existing *config.ClusterConfig) config.ClusterConfig { //nolint to suppress cyclomatic complexity 45 of func `updateExistingConfigFromFlags` is high (> 30)\n\n\tvalidateFlags(cmd, existing.Driver)\n\n\tcc := *existing\n\n\tif cmd.Flags().Changed(memory) && getMemorySize(cmd, cc.Driver) != cc.Memory {\n\t\tout.WarningT(\"You cannot change the memory size for an existing minikube cluster. Please first delete the cluster.\")\n\t}\n\n\tif cmd.Flags().Changed(cpus) && viper.GetInt(cpus) != cc.CPUs {\n\t\tout.WarningT(\"You cannot change the CPUs for an existing minikube cluster. Please first delete the cluster.\")\n\t}\n\n\t// validate the memory size in case user changed their system memory limits (example change docker desktop or upgraded memory.)\n\tvalidateRequestedMemorySize(cc.Memory, cc.Driver)\n\n\tif cmd.Flags().Changed(humanReadableDiskSize) && getDiskSize() != existing.DiskSize {\n\t\tout.WarningT(\"You cannot change the disk size for an existing minikube cluster. Please first delete the cluster.\")\n\t}\n\n\tcheckExtraDiskOptions(cmd, cc.Driver)\n\tif cmd.Flags().Changed(extraDisks) && viper.GetInt(extraDisks) != existing.ExtraDisks {\n\t\tout.WarningT(\"You cannot add or remove extra disks for an existing minikube cluster. Please first delete the cluster.\")\n\t}\n\n\tif cmd.Flags().Changed(staticIP) && viper.GetString(staticIP) != existing.StaticIP {\n\t\tout.WarningT(\"You cannot change the static IP of an existing minikube cluster. Please first delete the cluster.\")\n\t}\n\n\tupdateBoolFromFlag(cmd, &cc.KeepContext, keepContext)\n\tupdateBoolFromFlag(cmd, &cc.EmbedCerts, embedCerts)\n\tupdateStringFromFlag(cmd, &cc.MinikubeISO, isoURL)\n\tupdateStringFromFlag(cmd, &cc.KicBaseImage, kicBaseImage)\n\tupdateStringFromFlag(cmd, &cc.Network, network)\n\tupdateStringFromFlag(cmd, &cc.HyperkitVpnKitSock, vpnkitSock)\n\tupdateStringSliceFromFlag(cmd, &cc.HyperkitVSockPorts, vsockPorts)\n\tupdateStringSliceFromFlag(cmd, &cc.NFSShare, nfsShare)\n\tupdateStringFromFlag(cmd, &cc.NFSSharesRoot, nfsSharesRoot)\n\tupdateStringFromFlag(cmd, &cc.HostOnlyCIDR, hostOnlyCIDR)\n\tupdateStringFromFlag(cmd, &cc.HypervVirtualSwitch, hypervVirtualSwitch)\n\tupdateBoolFromFlag(cmd, &cc.HypervUseExternalSwitch, hypervUseExternalSwitch)\n\tupdateStringFromFlag(cmd, &cc.HypervExternalAdapter, hypervExternalAdapter)\n\tupdateStringFromFlag(cmd, &cc.KVMNetwork, kvmNetwork)\n\tupdateStringFromFlag(cmd, &cc.KVMQemuURI, kvmQemuURI)\n\tupdateBoolFromFlag(cmd, &cc.KVMGPU, kvmGPU)\n\tupdateBoolFromFlag(cmd, &cc.KVMHidden, kvmHidden)\n\tupdateBoolFromFlag(cmd, &cc.DisableDriverMounts, disableDriverMounts)\n\tupdateStringFromFlag(cmd, &cc.UUID, uuid)\n\tupdateBoolFromFlag(cmd, &cc.NoVTXCheck, noVTXCheck)\n\tupdateBoolFromFlag(cmd, &cc.DNSProxy, dnsProxy)\n\tupdateBoolFromFlag(cmd, &cc.HostDNSResolver, hostDNSResolver)\n\tupdateStringFromFlag(cmd, &cc.HostOnlyNicType, hostOnlyNicType)\n\tupdateStringFromFlag(cmd, &cc.NatNicType, natNicType)\n\tupdateDurationFromFlag(cmd, &cc.StartHostTimeout, waitTimeout)\n\tupdateStringSliceFromFlag(cmd, &cc.ExposedPorts, ports)\n\tupdateStringFromFlag(cmd, &cc.SSHIPAddress, sshIPAddress)\n\tupdateStringFromFlag(cmd, &cc.SSHUser, sshSSHUser)\n\tupdateStringFromFlag(cmd, &cc.SSHKey, sshSSHKey)\n\tupdateIntFromFlag(cmd, &cc.SSHPort, sshSSHPort)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.Namespace, startNamespace)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.APIServerName, apiServerName)\n\tupdateStringSliceFromFlag(cmd, &cc.KubernetesConfig.APIServerNames, \"apiserver-names\")\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.DNSDomain, dnsDomain)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.FeatureGates, featureGates)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.ContainerRuntime, containerRuntime)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.CRISocket, criSocket)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.NetworkPlugin, networkPlugin)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.ServiceCIDR, serviceCIDR)\n\tupdateBoolFromFlag(cmd, &cc.KubernetesConfig.ShouldLoadCachedImages, cacheImages)\n\tupdateIntFromFlag(cmd, &cc.KubernetesConfig.NodePort, apiServerPort)\n\tupdateDurationFromFlag(cmd, &cc.CertExpiration, certExpiration)\n\tupdateBoolFromFlag(cmd, &cc.Mount, createMount)\n\tupdateStringFromFlag(cmd, &cc.MountString, mountString)\n\tupdateStringFromFlag(cmd, &cc.Mount9PVersion, mount9PVersion)\n\tupdateStringFromFlag(cmd, &cc.MountGID, mountGID)\n\tupdateStringFromFlag(cmd, &cc.MountIP, mountIPFlag)\n\tupdateIntFromFlag(cmd, &cc.MountMSize, mountMSize)\n\tupdateStringSliceFromFlag(cmd, &cc.MountOptions, mountOptions)\n\tupdateUint16FromFlag(cmd, &cc.MountPort, mountPortFlag)\n\tupdateStringFromFlag(cmd, &cc.MountType, mountTypeFlag)\n\tupdateStringFromFlag(cmd, &cc.MountUID, mountUID)\n\tupdateStringFromFlag(cmd, &cc.BinaryMirror, binaryMirror)\n\tupdateBoolFromFlag(cmd, &cc.DisableOptimizations, disableOptimizations)\n\tupdateStringFromFlag(cmd, &cc.CustomQemuFirmwarePath, qemuFirmwarePath)\n\tupdateStringFromFlag(cmd, &cc.SocketVMnetClientPath, socketVMnetClientPath)\n\tupdateStringFromFlag(cmd, &cc.SocketVMnetPath, socketVMnetPath)\n\n\tif cmd.Flags().Changed(kubernetesVersion) {\n\t\tkubeVer, err := getKubernetesVersion(existing)\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"failed getting Kubernetes version: %v\", err)\n\t\t}\n\t\tcc.KubernetesConfig.KubernetesVersion = kubeVer\n\t}\n\tif cmd.Flags().Changed(containerRuntime) {\n\t\tcc.KubernetesConfig.ContainerRuntime = getContainerRuntime(existing)\n\t}\n\n\tif cmd.Flags().Changed(\"extra-config\") {\n\t\tcc.KubernetesConfig.ExtraOptions = getExtraOptions()\n\t}\n\n\tif cmd.Flags().Changed(cniFlag) || cmd.Flags().Changed(enableDefaultCNI) {\n\t\tcc.KubernetesConfig.CNI = getCNIConfig(cmd)\n\t}\n\n\tif cmd.Flags().Changed(waitComponents) {\n\t\tcc.VerifyComponents = interpretWaitFlag(*cmd)\n\t}\n\n\tif cmd.Flags().Changed(\"apiserver-ips\") {\n\t\t// IPSlice not supported in Viper\n\t\t// https://github.com/spf13/viper/issues/460\n\t\tcc.KubernetesConfig.APIServerIPs = apiServerIPs\n\t}\n\n\t// Handle flags and legacy configuration upgrades that do not contain KicBaseImage\n\tif cmd.Flags().Changed(kicBaseImage) || cc.KicBaseImage == \"\" {\n\t\tcc.KicBaseImage = viper.GetString(kicBaseImage)\n\t}\n\n\t// If this cluster was stopped by a scheduled stop, clear the config\n\tif cc.ScheduledStop != nil && time.Until(time.Unix(cc.ScheduledStop.InitiationTime, 0).Add(cc.ScheduledStop.Duration)) <= 0 {\n\t\tcc.ScheduledStop = nil\n\t}\n\n\treturn cc\n}", "func WarnKV(ctx context.Context, msg string, args ...field.Field) {\n\tglobal.WarnKV(ctx, msg, args...)\n}", "func suppressMissingOptionalConfigurationBlock(k, old, new string, d *schema.ResourceData) bool {\n\treturn old == \"1\" && new == \"0\"\n}", "func (c *evictionClient) LabelPod(podInfo *types.PodInfo, priority string, action string) error {\n\tif podInfo.Name == \"\" {\n\t\treturn fmt.Errorf(\"pod name should not be empty\")\n\t}\n\toldPod, err := c.client.CoreV1().Pods(podInfo.Namespace).Get(podInfo.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\tlog.Errorf(\"get pod %s error\", podInfo.Name)\n\t\treturn err\n\t}\n\toldData, err := json.Marshal(oldPod)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal old node for node %v : %v\", c.nodeName, err)\n\t}\n\tnewPod := oldPod.DeepCopy()\n\n\tif newPod.Labels == nil {\n\t\tlog.Infof(\"there is no label on this pod: %v, create it\", podInfo.Name)\n\t\tnewPod.Labels = make(map[string]string)\n\t}\n\tif action == \"Add\" {\n\t\tnewPod.Labels[priority] = \"true\"\n\t} else if action == \"Delete\" {\n\t\tdelete(newPod.Labels, priority)\n\t}\n\n\tnewData, err := json.Marshal(newPod)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal new pod %v : %v\", podInfo.Name, err)\n\t}\n\n\tpatchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, v1.Pod{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create patch for pod %v\", podInfo.Name)\n\t}\n\t_, err = c.client.CoreV1().Pods(oldPod.Namespace).Patch(oldPod.Name, k8stypes.StrategicMergePatchType, patchBytes)\n\n\tlog.Infof(\"Label pod: %v, action:%v\", podInfo.Name, action)\n\treturn err\n}", "func CTCLossIgnoreLongerOutputsThanInputs(value bool) CTCLossAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"ignore_longer_outputs_than_inputs\"] = value\n\t}\n}", "func (r *replicatorProps) needsDataUpdate(object *metav1.ObjectMeta, sourceObject *metav1.ObjectMeta) (bool, bool, error) {\n\t// target was \"replicated\" from a delete source, or never replicated\n\tif targetVersion, ok := object.Annotations[ReplicatedFromVersionAnnotation]; !ok {\n\t\treturn true, false, nil\n\t// target and source share the same version\n\t} else if ok && targetVersion == sourceObject.ResourceVersion {\n\t\treturn false, false, fmt.Errorf(\"target %s/%s is already up-to-date\", object.Namespace, object.Name)\n\t}\n\n\thasOnce := false\n\t// no once annotation, nothing to check\n\tif annotationOnce, ok := sourceObject.Annotations[ReplicateOnceAnnotation]; !ok {\n\t// once annotation is not a boolean\n\t} else if once, err := strconv.ParseBool(annotationOnce); err != nil {\n\t\treturn false, false, fmt.Errorf(\"source %s/%s has illformed annotation %s: %s\",\n\t\t\tsourceObject.Namespace, sourceObject.Name, ReplicateOnceAnnotation, err)\n\t// once annotation is present\n\t} else if once {\n\t\thasOnce = true\n\t}\n\t// no once annotation, nothing to check\n\tif annotationOnce, ok := object.Annotations[ReplicateOnceAnnotation]; !ok {\n\t// once annotation is not a boolean\n\t} else if once, err := strconv.ParseBool(annotationOnce); err != nil {\n\t\treturn false, false, fmt.Errorf(\"target %s/%s has illformed annotation %s: %s\",\n\t\t\tobject.Namespace, object.Name, ReplicateOnceAnnotation, err)\n\t// once annotation is present\n\t} else if once {\n\t\thasOnce = true\n\t}\n\n\tif !hasOnce {\n\t// no once version annotation in the source, only replicate once\n\t} else if annotationVersion, ok := sourceObject.Annotations[ReplicateOnceVersionAnnotation]; !ok {\n\t// once version annotation is not a valid version\n\t} else if sourceVersion, err := semver.NewVersion(annotationVersion); err != nil {\n\t\treturn false, false, fmt.Errorf(\"source %s/%s has illformed annotation %s: %s\",\n\t\t\tsourceObject.Namespace, sourceObject.Name, ReplicateOnceVersionAnnotation, err)\n\t// the source has a once version annotation but it is \"0.0.0\" anyway\n\t} else if version0, _ := semver.NewVersion(\"0\"); sourceVersion.Equal(version0) {\n\t// no once version annotation in the target, should update\n\t} else if annotationVersion, ok := object.Annotations[ReplicateOnceVersionAnnotation]; !ok {\n\t\thasOnce = false\n\t// once version annotation is not a valid version\n\t} else if targetVersion, err := semver.NewVersion(annotationVersion); err != nil {\n\t\treturn false, false, fmt.Errorf(\"target %s/%s has illformed annotation %s: %s\",\n\t\t\tobject.Namespace, object.Name, ReplicateOnceVersionAnnotation, err)\n\t// source version is greatwe than source version, should update\n\t} else if sourceVersion.GreaterThan(targetVersion) {\n\t\thasOnce = false\n\t// source version is not greater than target version\n\t} else {\n\t\treturn false, true, fmt.Errorf(\"target %s/%s is already replicated once at version %s\",\n\t\t\tobject.Namespace, object.Name, sourceVersion)\n\t}\n\n\tif hasOnce {\n\t\treturn false, true, fmt.Errorf(\"target %s/%s is already replicated once\",\n\t\t\tobject.Namespace, object.Name)\n\t}\n\n\treturn true, false, nil\n}", "func (m *DeviceManagementConfigurationSettingDefinition) SetApplicability(value DeviceManagementConfigurationSettingApplicabilityable)() {\n err := m.GetBackingStore().Set(\"applicability\", value)\n if err != nil {\n panic(err)\n }\n}", "func (kv *KVPaxos) setunreliable(what bool) {\n\tif what {\n\t\tatomic.StoreInt32(&kv.unreliable, 1)\n\t} else {\n\t\tatomic.StoreInt32(&kv.unreliable, 0)\n\t}\n}", "func (kv *KVPaxos) setunreliable(what bool) {\n\tif what {\n\t\tatomic.StoreInt32(&kv.unreliable, 1)\n\t} else {\n\t\tatomic.StoreInt32(&kv.unreliable, 0)\n\t}\n}", "func (kv *KVPaxos) setunreliable(what bool) {\n\tif what {\n\t\tatomic.StoreInt32(&kv.unreliable, 1)\n\t} else {\n\t\tatomic.StoreInt32(&kv.unreliable, 0)\n\t}\n}", "func (u NoopUpdater) Set(_, _, _ string) error { return nil }", "func addNodeLabel(clientset *kubernetes.Clientset, nodename string, labelkey string, labelvalue string) {\n // Getting node\n nodesClient := clientset.Core().Nodes()\n\n // Updating node\n retryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error {\n result, getErr := nodesClient.Get(nodename, metav1.GetOptions{})\n if getErr != nil {\n panic(fmt.Errorf(\"Failed to get latest version of Node: %v\", getErr))\n }\n\n fmt.Printf(\"Adding label %v:%v to node %v\\n\", labelkey, labelvalue, nodename)\n\n // Modify labels\n result.Labels[labelkey] = labelvalue\n _, updateErr := nodesClient.Update(result)\n return updateErr\n })\n if retryErr != nil {\n panic(fmt.Errorf(\"Update failed: %v\", retryErr))\n }\n fmt.Printf(\"Updated labels of node %v\\n\", nodename)\n}", "func (r *replicatorProps) needsFromAnnotationsUpdate(object *metav1.ObjectMeta, sourceObject *metav1.ObjectMeta) (bool, error) {\n\tupdate := false\n\t// check \"from\" annotation of the source\n\tif source, sOk := resolveAnnotation(sourceObject, ReplicateFromAnnotation); !sOk {\n\t\treturn false, fmt.Errorf(\"source %s/%s misses annotation %s\",\n\t\t\tsourceObject.Namespace, sourceObject.Name, ReplicateFromAnnotation)\n\n\t} else if !validPath.MatchString(source) ||\n\t\t\tsource == fmt.Sprintf(\"%s/%s\", sourceObject.Namespace, sourceObject.Name) {\n\t\treturn false, fmt.Errorf(\"source %s/%s has invalid annotation %s (%s)\",\n\t\t\tsourceObject.Namespace, sourceObject.Name, ReplicateFromAnnotation, source)\n\n\t// check that target has the same annotation\n\t} else if val, ok := object.Annotations[ReplicateFromAnnotation]; !ok || val != source {\n\t\tupdate = true\n\t}\n\n\tsource, sOk := sourceObject.Annotations[ReplicateOnceAnnotation]\n\t// check \"once\" annotation of the source\n\tif sOk {\n\t\tif _, err := strconv.ParseBool(source); err != nil {\n\t\t\treturn false, fmt.Errorf(\"source %s/%s has illformed annotation %s: %s\",\n\t\t\t\tsourceObject.Namespace, sourceObject.Name, ReplicateOnceAnnotation, err)\n\t\t}\n\t}\n\t// check that target has the same annotation\n\tif val, ok := object.Annotations[ReplicateOnceAnnotation]; sOk != ok || ok && val != source {\n\t\tupdate = true\n\t}\n\n\treturn update, nil\n}", "func CreateOrUpdate(ctx context.Context, kubeClient client.Client, scheme *runtime.Scheme, obj GCRuntimeObject, onPatchErr OnPatchError) (bool, error) {\n\tmodifiedEncoded, err := ensureAppliedConfigAnnotation(scheme, obj)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\terr = kubeClient.Create(ctx, obj, client.FieldOwner(fieldOwner))\n\tif err == nil {\n\t\treturn true, nil\n\t}\n\n\tif !apierrors.IsAlreadyExists(err) {\n\t\treturn false, err\n\t}\n\n\tcurrent, err := getCurrentResource(ctx, kubeClient, scheme, obj)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tpatchMeta, err := strategicpatch.NewPatchMetaFromStruct(current)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"failed to patch metadata from empty struct: %w\", err)\n\t}\n\n\toriginalEncoded := current.GetAnnotations()[lastAppliedAnnotation]\n\n\t// We reset the creation timestamp here.\n\t// This is done because the object is not recognized as \"empty\" in the json encoder. Unless we reset the creation\n\t// time of the current resource, it will show up in any patch we want to submit.\n\tcurrent.SetCreationTimestamp(metav1.Time{})\n\tcurrentEncoded, err := runtime.Encode(unstructured.UnstructuredJSONScheme, current)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"failed to re-encoded current resource: %w\", err)\n\t}\n\n\tpatch, err := strategicpatch.CreateThreeWayMergePatch([]byte(originalEncoded), modifiedEncoded, currentEncoded, patchMeta, true, defaultPreconditions...)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"failed to generate patch data: %w\", err)\n\t}\n\n\tif string(patch) == \"{}\" {\n\t\treturn false, nil\n\t}\n\n\terr = kubeClient.Patch(ctx, obj, client.RawPatch(types.StrategicMergePatchType, patch), client.FieldOwner(fieldOwner))\n\tif err != nil {\n\t\tif apierrors.IsInvalid(err) && onPatchErr != nil {\n\t\t\terr := onPatchErr(ctx, kubeClient, current, obj)\n\n\t\t\treturn err == nil, err\n\t\t}\n\n\t\treturn false, fmt.Errorf(\"failed to apply patch: %w\", err)\n\t}\n\n\treturn true, nil\n}", "func updateLabelOp(metric pmetric.Metric, mtpOp internalOperation, f internalFilter) {\n\top := mtpOp.configOperation\n\trangeDataPointAttributes(metric, func(attrs pcommon.Map) bool {\n\t\tif !f.matchAttrs(attrs) {\n\t\t\treturn true\n\t\t}\n\n\t\tattrKey := op.Label\n\t\tattrVal, ok := attrs.Get(attrKey)\n\t\tif !ok {\n\t\t\treturn true\n\t\t}\n\n\t\tif op.NewLabel != \"\" {\n\t\t\tattrVal.CopyTo(attrs.PutEmpty(op.NewLabel))\n\t\t\tattrs.Remove(attrKey)\n\t\t\tattrKey = op.NewLabel\n\t\t}\n\n\t\tif newValue, ok := mtpOp.valueActionsMapping[attrVal.Str()]; ok {\n\t\t\tattrs.PutStr(attrKey, newValue)\n\t\t}\n\t\treturn true\n\t})\n}", "func (m *MacOSMinimumOperatingSystem) SetV120(value *bool)() {\n err := m.GetBackingStore().Set(\"v12_0\", value)\n if err != nil {\n panic(err)\n }\n}", "func (e Environment) Overridef(name string, format string, a ...interface{}) {\n\te[fmt.Sprintf(\"%s.override\", name)] = fmt.Sprintf(format, a...)\n}", "func (strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn warningsForSecret(obj.(*api.Secret))\n}", "func (rcc *CassandraClusterReconciler) CheckNonAllowedChanges(cc *api.CassandraCluster,\n\tstatus *api.CassandraClusterStatus) bool {\n\tvar oldCRD api.CassandraCluster\n\tif cc.Annotations[api.AnnotationLastApplied] == \"\" {\n\t\treturn false\n\t}\n\n\tif lac, _ := cc.ComputeLastAppliedConfiguration(); string(lac) == cc.Annotations[api.AnnotationLastApplied] {\n\t\t//there are no changes to take care about\n\t\treturn false\n\t}\n\n\t//We retrieved our last-applied-configuration stored in the CRD\n\terr := json.Unmarshal([]byte(cc.Annotations[api.AnnotationLastApplied]), &oldCRD)\n\tif err != nil {\n\t\tlogrus.WithFields(logrus.Fields{\"cluster\": cc.Name}).Error(\"Can't get Old version of CRD\")\n\t\treturn false\n\t}\n\n\t//Global scaleDown to 0 is forbidden\n\tif cc.Spec.NodesPerRacks == 0 {\n\t\tlogrus.WithFields(logrus.Fields{\"cluster\": cc.Name}).\n\t\t\tWarningf(\"The Operator has refused the change on NodesPerRack=0 restore to OldValue[%d]\",\n\t\t\t\toldCRD.Spec.NodesPerRacks)\n\t\tcc.Spec.NodesPerRacks = oldCRD.Spec.NodesPerRacks\n\t\tneedUpdate = true\n\t}\n\n\tfor dc := 0; dc < cc.GetDCSize(); dc++ {\n\t\tdcName := cc.GetDCName(dc)\n\t\t//DataCapacity change is forbidden\n\t\tif cc.GetDataCapacityForDC(dcName) != oldCRD.GetDataCapacityForDC(dcName) {\n\t\t\tlogrus.WithFields(logrus.Fields{\"cluster\": cc.Name, \"dcName\": dcName}).\n\t\t\t\tWarningf(\"The Operator has refused the change on DataCapacity from [%s] to NewValue[%s]\",\n\t\t\t\t\toldCRD.GetDataCapacityForDC(dcName), cc.GetDataCapacityForDC(dcName))\n\t\t\tcc.Spec.DataCapacity = oldCRD.Spec.DataCapacity\n\t\t\tcc.Spec.Topology.DC[dc].DataCapacity = oldCRD.Spec.Topology.DC[dc].DataCapacity\n\t\t\tneedUpdate = true\n\t\t}\n\t\t//DataStorage\n\t\tif cc.GetDataStorageClassForDC(dcName) != oldCRD.GetDataStorageClassForDC(dcName) {\n\t\t\tlogrus.WithFields(logrus.Fields{\"cluster\": cc.Name, \"dcName\": dcName}).\n\t\t\t\tWarningf(\"The Operator has refused the change on DataStorageClass from [%s] to NewValue[%s]\",\n\t\t\t\t\toldCRD.GetDataStorageClassForDC(dcName), cc.GetDataStorageClassForDC(dcName))\n\t\t\tcc.Spec.DataStorageClass = oldCRD.Spec.DataStorageClass\n\t\t\tcc.Spec.Topology.DC[dc].DataStorageClass = oldCRD.Spec.Topology.DC[dc].DataStorageClass\n\t\t\tneedUpdate = true\n\t\t}\n\t}\n\n\tif needUpdate {\n\t\tstatus.LastClusterAction = api.ActionCorrectCRDConfig.Name\n\t\tClusterActionMetric.set(api.ActionCorrectCRDConfig, cc.Name)\n\t\treturn true\n\t}\n\n\tvar updateStatus string\n\tif needUpdate, updateStatus = CheckTopologyChanges(rcc, cc, status, &oldCRD); needUpdate {\n\t\tif updateStatus != \"\" {\n\t\t\tstatus.LastClusterAction = updateStatus\n\t\t}\n\t\tif updateStatus == api.ActionCorrectCRDConfig.Name {\n\t\t\tcc.Spec.Topology = (&oldCRD).Spec.Topology\n\t\t\tClusterActionMetric.set(api.ActionCorrectCRDConfig, cc.Name)\n\t\t}\n\n\t\treturn true\n\t}\n\n\tif updateStatus == api.ActionDeleteRack.Name {\n\t\tClusterActionMetric.set(api.ActionDeleteRack, cc.Name)\n\t\treturn true\n\t}\n\n\tif needUpdate = rcc.CheckNonAllowedScaleDown(cc, &oldCRD); needUpdate {\n\t\tstatus.LastClusterAction = api.ActionCorrectCRDConfig.Name\n\t\tClusterActionMetric.set(api.ActionCorrectCRDConfig, cc.Name)\n\t\treturn true\n\t}\n\n\t//What if we ask to changes Pod ressources ?\n\t// It is authorized, but the operator needs to detect it to prevent multiple statefulsets updates in the same time\n\t// the operator must handle thoses updates sequentially, so we flag each dcrackname with this information\n\tif !reflect.DeepEqual(cc.Spec.Resources, oldCRD.Spec.Resources) {\n\t\tlogrus.Infof(\"[%s]: We ask to Change Pod Resources from %v to %v\", cc.Name, oldCRD.Spec.Resources, cc.Spec.Resources)\n\n\t\tfor dc := 0; dc < cc.GetDCSize(); dc++ {\n\t\t\tdcName := cc.GetDCName(dc)\n\t\t\tfor rack := 0; rack < cc.GetRackSize(dc); rack++ {\n\n\t\t\t\trackName := cc.GetRackName(dc, rack)\n\t\t\t\tdcRackName := cc.GetDCRackName(dcName, rackName)\n\t\t\t\tdcRackStatus := status.CassandraRackStatus[dcRackName]\n\n\t\t\t\tlogrus.Infof(\"[%s][%s]: Update Rack Status UpdateResources=Ongoing\", cc.Name, dcRackName)\n\t\t\t\tdcRackStatus.CassandraLastAction.Name = api.ActionUpdateResources.Name\n\t\t\t\tClusterActionMetric.set(api.ActionUpdateResources, cc.Name)\n\t\t\t\tdcRackStatus.CassandraLastAction.Status = api.StatusToDo\n\t\t\t\tnow := metav1.Now()\n\t\t\t\tstatus.CassandraRackStatus[dcRackName].CassandraLastAction.StartTime = &now\n\t\t\t\tstatus.CassandraRackStatus[dcRackName].CassandraLastAction.EndTime = nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}", "func forceRulesWarning(cfg *mybase.Config) {\n\tfor _, rule := range rulesByName {\n\t\tif !rule.hidden() {\n\t\t\tcfg.SetRuntimeOverride(rule.optionName(), string(SeverityWarning))\n\t\t}\n\t}\n}", "func (px *Paxos) setunreliable(what bool) {\n if what {\n atomic.StoreInt32(&px.unreliable, 1)\n } else {\n atomic.StoreInt32(&px.unreliable, 0)\n }\n}", "func WarningKV(args ...interface{}) {\n\tcurrentLogger.WarningKVDepth(context.Background(), defaultDepth, args...)\n}", "func (c *PCPCounterVector) MustSet(val int64, instance string) {\n\tif err := c.Set(val, instance); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (c *Controller) validateBackupAnnotations(key string, volumeMissing prometheus.GaugeVec, excludeAnnotation string, backupAnnotation string) error {\n\n\tobj, exists, err := c.indexer.GetByKey(key)\n\tif err != nil {\n\t\tklog.Errorf(\"fetching object with key %s from store failed with %v\", key, err)\n\t\treturn err\n\t}\n\tif !exists {\n\t\tklog.Infof(\"pod %s does not exist anymore\", key)\n\t\tif obj, exists, err = c.deletedIndexer.GetByKey(key); err == nil && exists {\n\n\t\t\tpod := obj.(*v1.Pod)\n\t\t\townerInfo := getPodOwnerInfo(pod)\n\t\t\tklog.Infof(\"disabling metric %s\", ownerInfo.name)\n\t\t\tc.disableMetric(ownerInfo)\n\t\t\t_ = c.deletedIndexer.Delete(key)\n\t\t}\n\n\t} else {\n\t\tpod := obj.(*v1.Pod)\n\t\townerInfo := getPodOwnerInfo(pod)\n\n\t\tif _, ok := c.podCache[ownerInfo.name]; !ok {\n\t\t\tc.podCache[ownerInfo.name] = map[VolumeName]bool{}\n\t\t}\n\t\tklog.Infof(\"controlling backup config for %s\", pod.GetName())\n\t\tmissings := c.getMissingBackups(pod)\n\t\tif len(missings) > 0 {\n\t\t\tklog.Infof(\"backup missing enable metric for %s\", ownerInfo.name)\n\t\t\tc.enableMetric(ownerInfo, missings)\n\t\t}\n\t}\n\n\treturn nil\n}", "func InjectLabel(key, value string, overwritePolicy OverwritePolicy, kinds ...string) mf.Transformer {\n\treturn func(u *unstructured.Unstructured) error {\n\t\tkind := u.GetKind()\n\t\tif len(kinds) != 0 && !ItemInSlice(kind, kinds) {\n\t\t\treturn nil\n\t\t}\n\t\tlabels, found, err := unstructured.NestedStringMap(u.Object, \"metadata\", \"labels\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not find labels set, %q\", err)\n\t\t}\n\t\tif overwritePolicy == Retain && found {\n\t\t\tif _, ok := labels[key]; ok {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tlabels = map[string]string{}\n\t\t}\n\t\tlabels[key] = value\n\t\terr = unstructured.SetNestedStringMap(u.Object, labels, \"metadata\", \"labels\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error updateing labes for %s:%s, %s\", kind, u.GetName(), err)\n\t\t}\n\t\treturn nil\n\t}\n}", "func canReplace(resource *unstructured.Unstructured, patchErr error) bool {\n\tk := resource.GetKind()\n\te := patchErr.Error()\n\tif (k == \"DaemonSet\" || k == \"Deployment\" || k == \"Job\") && strings.Contains(e, \"field is immutable\") {\n\t\treturn true\n\t}\n\tif k == \"Service\" && (strings.Contains(e, \"field is immutable\") || strings.Contains(e, \"may not change once set\") || strings.Contains(e, \"can not be unset\")) {\n\t\treturn true\n\t}\n\tif k == \"PersistentVolume\" && strings.Contains(e, \"is immutable after creation\") {\n\t\tv, ok, err := unstructured.NestedString(resource.Object, \"spec\", \"persistentVolumeReclaimPolicy\")\n\t\tif err == nil && ok && v == \"Retain\" {\n\t\t\treturn true\n\t\t}\n\t\tlog.Printf(\"Not replacing PersistentVolume since reclaim policy is not Retain but %q\", v)\n\t}\n\tif (k == \"ValidatingWebhookConfiguration\" || k == \"MutatingWebhookConfiguration\") && strings.Contains(e, \"must be specified for an update\") {\n\t\treturn true\n\t}\n\n\t// TODO(rodrigoq): can other resources be safely replaced?\n\treturn false\n}", "func shouldUpdateOVNKonIPFamilyChange(ovn bootstrap.OVNBootstrapResult, ipFamilyMode string) (updateNode, updateMaster bool) {\n\t// Fresh cluster - full steam ahead!\n\tif ovn.NodeUpdateStatus == nil || ovn.MasterUpdateStatus == nil {\n\t\treturn true, true\n\t}\n\t// check current IP family mode\n\n\tnodeIPFamilyMode := ovn.NodeUpdateStatus.IPFamilyMode\n\tmasterIPFamilyMode := ovn.MasterUpdateStatus.IPFamilyMode\n\t// if there are no annotations this is a fresh cluster\n\tif nodeIPFamilyMode == \"\" || masterIPFamilyMode == \"\" {\n\t\treturn true, true\n\t}\n\t// exit if there are no IP family mode changes\n\tif nodeIPFamilyMode == ipFamilyMode && masterIPFamilyMode == ipFamilyMode {\n\t\treturn true, true\n\t}\n\t// If the master config has changed update only the master, the node will be updated later\n\tif masterIPFamilyMode != ipFamilyMode {\n\t\tklog.V(2).Infof(\"IP family mode change detected to %s, updating OVN-Kubernetes master\", ipFamilyMode)\n\t\treturn false, true\n\t}\n\t// Don't rollout the changes on nodes until the master daemonset rollout has finished\n\tif ovn.MasterUpdateStatus.Progressing {\n\t\tklog.V(2).Infof(\"Waiting for OVN-Kubernetes master daemonset IP family mode rollout before updating node\")\n\t\treturn false, true\n\t}\n\n\tklog.V(2).Infof(\"OVN-Kubernetes master daemonset rollout complete, updating IP family mode on node daemonset\")\n\treturn true, true\n}", "func (g *PCPGaugeVector) MustSet(val float64, instance string) {\n\tif err := g.Set(val, instance); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (m *DeviceHealthScriptRunSummary) SetDetectionScriptNotApplicableDeviceCount(value *int32)() {\n err := m.GetBackingStore().Set(\"detectionScriptNotApplicableDeviceCount\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *MacOSMinimumOperatingSystem) SetV1012(value *bool)() {\n err := m.GetBackingStore().Set(\"v10_12\", value)\n if err != nil {\n panic(err)\n }\n}", "func resourceVolterraK8SPodSecurityPolicyUpdate(d *schema.ResourceData, meta interface{}) error {\n\tclient := meta.(*APIClient)\n\n\tupdateMeta := &ves_io_schema.ObjectReplaceMetaType{}\n\tupdateSpec := &ves_io_schema_k8s_pod_security_policy.ReplaceSpecType{}\n\tupdateReq := &ves_io_schema_k8s_pod_security_policy.ReplaceRequest{\n\t\tMetadata: updateMeta,\n\t\tSpec: updateSpec,\n\t}\n\tif v, ok := d.GetOk(\"annotations\"); ok && !isIntfNil(v) {\n\n\t\tms := map[string]string{}\n\n\t\tfor k, v := range v.(map[string]interface{}) {\n\t\t\tval := v.(string)\n\t\t\tms[k] = val\n\t\t}\n\t\tupdateMeta.Annotations = ms\n\t}\n\n\tif v, ok := d.GetOk(\"description\"); ok && !isIntfNil(v) {\n\t\tupdateMeta.Description =\n\t\t\tv.(string)\n\t}\n\n\tif v, ok := d.GetOk(\"disable\"); ok && !isIntfNil(v) {\n\t\tupdateMeta.Disable =\n\t\t\tv.(bool)\n\t}\n\n\tif v, ok := d.GetOk(\"labels\"); ok && !isIntfNil(v) {\n\n\t\tms := map[string]string{}\n\n\t\tfor k, v := range v.(map[string]interface{}) {\n\t\t\tval := v.(string)\n\t\t\tms[k] = val\n\t\t}\n\t\tupdateMeta.Labels = ms\n\t}\n\n\tif v, ok := d.GetOk(\"name\"); ok && !isIntfNil(v) {\n\t\tupdateMeta.Name =\n\t\t\tv.(string)\n\t}\n\n\tif v, ok := d.GetOk(\"namespace\"); ok && !isIntfNil(v) {\n\t\tupdateMeta.Namespace =\n\t\t\tv.(string)\n\t}\n\n\tconfigMethodChoiceTypeFound := false\n\n\tif v, ok := d.GetOk(\"psp_spec\"); ok && !configMethodChoiceTypeFound {\n\n\t\tconfigMethodChoiceTypeFound = true\n\t\tconfigMethodChoiceInt := &ves_io_schema_k8s_pod_security_policy.ReplaceSpecType_PspSpec{}\n\t\tconfigMethodChoiceInt.PspSpec = &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType{}\n\t\tupdateSpec.ConfigMethodChoice = configMethodChoiceInt\n\n\t\tsl := v.(*schema.Set).List()\n\t\tfor _, set := range sl {\n\t\t\tcs := set.(map[string]interface{})\n\n\t\t\tif v, ok := cs[\"allow_privilege_escalation\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tconfigMethodChoiceInt.PspSpec.AllowPrivilegeEscalation = v.(bool)\n\n\t\t\t}\n\n\t\t\tallowedCapabilitiesChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"allowed_capabilities\"]; ok && !isIntfNil(v) && !allowedCapabilitiesChoiceTypeFound {\n\n\t\t\t\tallowedCapabilitiesChoiceTypeFound = true\n\t\t\t\tallowedCapabilitiesChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_AllowedCapabilities{}\n\t\t\t\tallowedCapabilitiesChoiceInt.AllowedCapabilities = &ves_io_schema_k8s_pod_security_policy.CapabilityListType{}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.AllowedCapabilitiesChoice = allowedCapabilitiesChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"capabilities\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tls := make([]string, len(v.([]interface{})))\n\t\t\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tallowedCapabilitiesChoiceInt.AllowedCapabilities.Capabilities = ls\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"no_allowed_capabilities\"]; ok && !isIntfNil(v) && !allowedCapabilitiesChoiceTypeFound {\n\n\t\t\t\tallowedCapabilitiesChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tallowedCapabilitiesChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_NoAllowedCapabilities{}\n\t\t\t\t\tallowedCapabilitiesChoiceInt.NoAllowedCapabilities = &ves_io_schema.Empty{}\n\t\t\t\t\tconfigMethodChoiceInt.PspSpec.AllowedCapabilitiesChoice = allowedCapabilitiesChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"allowed_csi_drivers\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tls := make([]string, len(v.([]interface{})))\n\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.AllowedCsiDrivers = ls\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"allowed_flex_volumes\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tls := make([]string, len(v.([]interface{})))\n\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.AllowedFlexVolumes = ls\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"allowed_host_paths\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.([]interface{})\n\t\t\t\tallowedHostPaths := make([]*ves_io_schema_k8s_pod_security_policy.HostPathType, len(sl))\n\t\t\t\tconfigMethodChoiceInt.PspSpec.AllowedHostPaths = allowedHostPaths\n\t\t\t\tfor i, set := range sl {\n\t\t\t\t\tallowedHostPaths[i] = &ves_io_schema_k8s_pod_security_policy.HostPathType{}\n\t\t\t\t\tallowedHostPathsMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\tif w, ok := allowedHostPathsMapStrToI[\"path_prefix\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\tallowedHostPaths[i].PathPrefix = w.(string)\n\t\t\t\t\t}\n\n\t\t\t\t\tif w, ok := allowedHostPathsMapStrToI[\"read_only\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\tallowedHostPaths[i].ReadOnly = w.(bool)\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"allowed_proc_mounts\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tls := make([]string, len(v.([]interface{})))\n\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.AllowedProcMounts = ls\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"allowed_unsafe_sysctls\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tls := make([]string, len(v.([]interface{})))\n\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.AllowedUnsafeSysctls = ls\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"default_allow_privilege_escalation\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tconfigMethodChoiceInt.PspSpec.DefaultAllowPrivilegeEscalation = v.(bool)\n\n\t\t\t}\n\n\t\t\tdefaultCapabilitiesChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"default_capabilities\"]; ok && !isIntfNil(v) && !defaultCapabilitiesChoiceTypeFound {\n\n\t\t\t\tdefaultCapabilitiesChoiceTypeFound = true\n\t\t\t\tdefaultCapabilitiesChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_DefaultCapabilities{}\n\t\t\t\tdefaultCapabilitiesChoiceInt.DefaultCapabilities = &ves_io_schema_k8s_pod_security_policy.CapabilityListType{}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.DefaultCapabilitiesChoice = defaultCapabilitiesChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"capabilities\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tls := make([]string, len(v.([]interface{})))\n\t\t\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefaultCapabilitiesChoiceInt.DefaultCapabilities.Capabilities = ls\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"no_default_capabilities\"]; ok && !isIntfNil(v) && !defaultCapabilitiesChoiceTypeFound {\n\n\t\t\t\tdefaultCapabilitiesChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tdefaultCapabilitiesChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_NoDefaultCapabilities{}\n\t\t\t\t\tdefaultCapabilitiesChoiceInt.NoDefaultCapabilities = &ves_io_schema.Empty{}\n\t\t\t\t\tconfigMethodChoiceInt.PspSpec.DefaultCapabilitiesChoice = defaultCapabilitiesChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tdropCapabilitiesChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"drop_capabilities\"]; ok && !isIntfNil(v) && !dropCapabilitiesChoiceTypeFound {\n\n\t\t\t\tdropCapabilitiesChoiceTypeFound = true\n\t\t\t\tdropCapabilitiesChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_DropCapabilities{}\n\t\t\t\tdropCapabilitiesChoiceInt.DropCapabilities = &ves_io_schema_k8s_pod_security_policy.CapabilityListType{}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.DropCapabilitiesChoice = dropCapabilitiesChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"capabilities\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tls := make([]string, len(v.([]interface{})))\n\t\t\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdropCapabilitiesChoiceInt.DropCapabilities.Capabilities = ls\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"no_drop_capabilities\"]; ok && !isIntfNil(v) && !dropCapabilitiesChoiceTypeFound {\n\n\t\t\t\tdropCapabilitiesChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tdropCapabilitiesChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_NoDropCapabilities{}\n\t\t\t\t\tdropCapabilitiesChoiceInt.NoDropCapabilities = &ves_io_schema.Empty{}\n\t\t\t\t\tconfigMethodChoiceInt.PspSpec.DropCapabilitiesChoice = dropCapabilitiesChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"forbidden_sysctls\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tls := make([]string, len(v.([]interface{})))\n\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.ForbiddenSysctls = ls\n\n\t\t\t}\n\n\t\t\tfsGroupChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"fs_group_strategy_options\"]; ok && !isIntfNil(v) && !fsGroupChoiceTypeFound {\n\n\t\t\t\tfsGroupChoiceTypeFound = true\n\t\t\t\tfsGroupChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_FsGroupStrategyOptions{}\n\t\t\t\tfsGroupChoiceInt.FsGroupStrategyOptions = &ves_io_schema_k8s_pod_security_policy.IDStrategyOptionsType{}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.FsGroupChoice = fsGroupChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"id_ranges\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\tidRanges := make([]*ves_io_schema_k8s_pod_security_policy.IDRangeType, len(sl))\n\t\t\t\t\t\tfsGroupChoiceInt.FsGroupStrategyOptions.IdRanges = idRanges\n\t\t\t\t\t\tfor i, set := range sl {\n\t\t\t\t\t\t\tidRanges[i] = &ves_io_schema_k8s_pod_security_policy.IDRangeType{}\n\t\t\t\t\t\t\tidRangesMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif w, ok := idRangesMapStrToI[\"max_id\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\tidRanges[i].MaxId = uint32(w.(int))\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif w, ok := idRangesMapStrToI[\"min_id\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\tidRanges[i].MinId = uint32(w.(int))\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"rule\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tfsGroupChoiceInt.FsGroupStrategyOptions.Rule = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"no_fs_groups\"]; ok && !isIntfNil(v) && !fsGroupChoiceTypeFound {\n\n\t\t\t\tfsGroupChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tfsGroupChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_NoFsGroups{}\n\t\t\t\t\tfsGroupChoiceInt.NoFsGroups = &ves_io_schema.Empty{}\n\t\t\t\t\tconfigMethodChoiceInt.PspSpec.FsGroupChoice = fsGroupChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tgroupChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"no_run_as_group\"]; ok && !isIntfNil(v) && !groupChoiceTypeFound {\n\n\t\t\t\tgroupChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tgroupChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_NoRunAsGroup{}\n\t\t\t\t\tgroupChoiceInt.NoRunAsGroup = &ves_io_schema.Empty{}\n\t\t\t\t\tconfigMethodChoiceInt.PspSpec.GroupChoice = groupChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"run_as_group\"]; ok && !isIntfNil(v) && !groupChoiceTypeFound {\n\n\t\t\t\tgroupChoiceTypeFound = true\n\t\t\t\tgroupChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_RunAsGroup{}\n\t\t\t\tgroupChoiceInt.RunAsGroup = &ves_io_schema_k8s_pod_security_policy.IDStrategyOptionsType{}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.GroupChoice = groupChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"id_ranges\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\tidRanges := make([]*ves_io_schema_k8s_pod_security_policy.IDRangeType, len(sl))\n\t\t\t\t\t\tgroupChoiceInt.RunAsGroup.IdRanges = idRanges\n\t\t\t\t\t\tfor i, set := range sl {\n\t\t\t\t\t\t\tidRanges[i] = &ves_io_schema_k8s_pod_security_policy.IDRangeType{}\n\t\t\t\t\t\t\tidRangesMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif w, ok := idRangesMapStrToI[\"max_id\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\tidRanges[i].MaxId = uint32(w.(int))\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif w, ok := idRangesMapStrToI[\"min_id\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\tidRanges[i].MinId = uint32(w.(int))\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"rule\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tgroupChoiceInt.RunAsGroup.Rule = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"host_ipc\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tconfigMethodChoiceInt.PspSpec.HostIpc = v.(bool)\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"host_network\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tconfigMethodChoiceInt.PspSpec.HostNetwork = v.(bool)\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"host_pid\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tconfigMethodChoiceInt.PspSpec.HostPid = v.(bool)\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"host_port_ranges\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tconfigMethodChoiceInt.PspSpec.HostPortRanges = v.(string)\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"privileged\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tconfigMethodChoiceInt.PspSpec.Privileged = v.(bool)\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"read_only_root_filesystem\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tconfigMethodChoiceInt.PspSpec.ReadOnlyRootFilesystem = v.(bool)\n\n\t\t\t}\n\n\t\t\truntimeClassChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"no_runtime_class\"]; ok && !isIntfNil(v) && !runtimeClassChoiceTypeFound {\n\n\t\t\t\truntimeClassChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\truntimeClassChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_NoRuntimeClass{}\n\t\t\t\t\truntimeClassChoiceInt.NoRuntimeClass = &ves_io_schema.Empty{}\n\t\t\t\t\tconfigMethodChoiceInt.PspSpec.RuntimeClassChoice = runtimeClassChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"runtime_class\"]; ok && !isIntfNil(v) && !runtimeClassChoiceTypeFound {\n\n\t\t\t\truntimeClassChoiceTypeFound = true\n\t\t\t\truntimeClassChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_RuntimeClass{}\n\t\t\t\truntimeClassChoiceInt.RuntimeClass = &ves_io_schema_k8s_pod_security_policy.RuntimeClassStrategyOptions{}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.RuntimeClassChoice = runtimeClassChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"allowed_runtime_class_names\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tls := make([]string, len(v.([]interface{})))\n\t\t\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t\t\t}\n\t\t\t\t\t\truntimeClassChoiceInt.RuntimeClass.AllowedRuntimeClassNames = ls\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"default_runtime_class_name\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\truntimeClassChoiceInt.RuntimeClass.DefaultRuntimeClassName = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tseLinuxChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"no_se_linux_options\"]; ok && !isIntfNil(v) && !seLinuxChoiceTypeFound {\n\n\t\t\t\tseLinuxChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tseLinuxChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_NoSeLinuxOptions{}\n\t\t\t\t\tseLinuxChoiceInt.NoSeLinuxOptions = &ves_io_schema.Empty{}\n\t\t\t\t\tconfigMethodChoiceInt.PspSpec.SeLinuxChoice = seLinuxChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"se_linux_options\"]; ok && !isIntfNil(v) && !seLinuxChoiceTypeFound {\n\n\t\t\t\tseLinuxChoiceTypeFound = true\n\t\t\t\tseLinuxChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_SeLinuxOptions{}\n\t\t\t\tseLinuxChoiceInt.SeLinuxOptions = &ves_io_schema_k8s_pod_security_policy.SELinuxStrategyOptions{}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.SeLinuxChoice = seLinuxChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"level\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tseLinuxChoiceInt.SeLinuxOptions.Level = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"role\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tseLinuxChoiceInt.SeLinuxOptions.Role = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"rule\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tseLinuxChoiceInt.SeLinuxOptions.Rule = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"type\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tseLinuxChoiceInt.SeLinuxOptions.Type = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"user\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tseLinuxChoiceInt.SeLinuxOptions.User = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tsupplementalGroupChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"no_supplemental_groups\"]; ok && !isIntfNil(v) && !supplementalGroupChoiceTypeFound {\n\n\t\t\t\tsupplementalGroupChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tsupplementalGroupChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_NoSupplementalGroups{}\n\t\t\t\t\tsupplementalGroupChoiceInt.NoSupplementalGroups = &ves_io_schema.Empty{}\n\t\t\t\t\tconfigMethodChoiceInt.PspSpec.SupplementalGroupChoice = supplementalGroupChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"supplemental_groups\"]; ok && !isIntfNil(v) && !supplementalGroupChoiceTypeFound {\n\n\t\t\t\tsupplementalGroupChoiceTypeFound = true\n\t\t\t\tsupplementalGroupChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_SupplementalGroups{}\n\t\t\t\tsupplementalGroupChoiceInt.SupplementalGroups = &ves_io_schema_k8s_pod_security_policy.IDStrategyOptionsType{}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.SupplementalGroupChoice = supplementalGroupChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"id_ranges\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\tidRanges := make([]*ves_io_schema_k8s_pod_security_policy.IDRangeType, len(sl))\n\t\t\t\t\t\tsupplementalGroupChoiceInt.SupplementalGroups.IdRanges = idRanges\n\t\t\t\t\t\tfor i, set := range sl {\n\t\t\t\t\t\t\tidRanges[i] = &ves_io_schema_k8s_pod_security_policy.IDRangeType{}\n\t\t\t\t\t\t\tidRangesMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif w, ok := idRangesMapStrToI[\"max_id\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\tidRanges[i].MaxId = uint32(w.(int))\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif w, ok := idRangesMapStrToI[\"min_id\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\tidRanges[i].MinId = uint32(w.(int))\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"rule\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsupplementalGroupChoiceInt.SupplementalGroups.Rule = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tuserChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"no_run_as_user\"]; ok && !isIntfNil(v) && !userChoiceTypeFound {\n\n\t\t\t\tuserChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tuserChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_NoRunAsUser{}\n\t\t\t\t\tuserChoiceInt.NoRunAsUser = &ves_io_schema.Empty{}\n\t\t\t\t\tconfigMethodChoiceInt.PspSpec.UserChoice = userChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"run_as_user\"]; ok && !isIntfNil(v) && !userChoiceTypeFound {\n\n\t\t\t\tuserChoiceTypeFound = true\n\t\t\t\tuserChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_RunAsUser{}\n\t\t\t\tuserChoiceInt.RunAsUser = &ves_io_schema_k8s_pod_security_policy.IDStrategyOptionsType{}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.UserChoice = userChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"id_ranges\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\tidRanges := make([]*ves_io_schema_k8s_pod_security_policy.IDRangeType, len(sl))\n\t\t\t\t\t\tuserChoiceInt.RunAsUser.IdRanges = idRanges\n\t\t\t\t\t\tfor i, set := range sl {\n\t\t\t\t\t\t\tidRanges[i] = &ves_io_schema_k8s_pod_security_policy.IDRangeType{}\n\t\t\t\t\t\t\tidRangesMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif w, ok := idRangesMapStrToI[\"max_id\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\tidRanges[i].MaxId = uint32(w.(int))\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif w, ok := idRangesMapStrToI[\"min_id\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\tidRanges[i].MinId = uint32(w.(int))\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"rule\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tuserChoiceInt.RunAsUser.Rule = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"volumes\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tls := make([]string, len(v.([]interface{})))\n\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.Volumes = ls\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tif v, ok := d.GetOk(\"yaml\"); ok && !configMethodChoiceTypeFound {\n\n\t\tconfigMethodChoiceTypeFound = true\n\t\tconfigMethodChoiceInt := &ves_io_schema_k8s_pod_security_policy.ReplaceSpecType_Yaml{}\n\n\t\tupdateSpec.ConfigMethodChoice = configMethodChoiceInt\n\n\t\tconfigMethodChoiceInt.Yaml = v.(string)\n\n\t}\n\n\tlog.Printf(\"[DEBUG] Updating Volterra K8SPodSecurityPolicy obj with struct: %+v\", updateReq)\n\n\terr := client.ReplaceObject(context.Background(), ves_io_schema_k8s_pod_security_policy.ObjectType, updateReq)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error updating K8SPodSecurityPolicy: %s\", err)\n\t}\n\n\treturn resourceVolterraK8SPodSecurityPolicyRead(d, meta)\n}", "func (m *DeviceCompliancePolicySettingStateSummary) SetNotApplicableDeviceCount(value *int32)() {\n err := m.GetBackingStore().Set(\"notApplicableDeviceCount\", value)\n if err != nil {\n panic(err)\n }\n}", "func (machine *VirtualMachine) validateWriteOnceProperties(old runtime.Object) (admission.Warnings, error) {\n\toldObj, ok := old.(*VirtualMachine)\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\n\treturn genruntime.ValidateWriteOnceProperties(oldObj, machine)\n}", "func Warningv(name string, value interface{}) {\n\tWarningf(\"%s: %v\", keyf(name), value)\n}", "func (w *Warning) UpdateWarningUponToxicity(toxicity constants.ToxicType) {\n\tif toxicity == constants.ToxicTypeHigh {\n\t\tw.RedWarnings++\n\t} else if toxicity == constants.ToxicTypeMedium {\n\t\tw.YellowWarnings++\n\t}\n\n\tif w.YellowWarnings >= 2 {\n\t\tw.YellowWarnings = 0\n\t\tw.RedWarnings++\n\t}\n}", "func NotifyUlimit(ctx context.Context, desired UlimitRequirement) {\n\tvar nofile syscall.Rlimit\n\tif err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &nofile); err != nil {\n\t\tlogger.Of(ctx).Debugf(logger.CatStorage, \"Could not get RLIMIT_NOFILE, skipped ulimit check: %v\", err)\n\t\treturn\n\t}\n\tif nofile.Cur < uint64(desired.NoFiles) {\n\t\tlogger.Of(ctx).Warnf(logger.CatStorage, \"Current value of RLIMIT_NOFILE is %d but current server configuration needs %d at least. Please consider to increase ulimit nofile.\", nofile.Cur, desired.NoFiles)\n\t}\n}", "func (kube Kubernetes) setHardKillLock(node string) bool {\n\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tkube.log.PrintErr(err.(error))\n\t\t}\n\t}()\n\n\tnow := time.Now()\n\tleaseDuration := time.Minute * 10\n\n\tfor i := 0; i < 10; i++ {\n\n\t\t// 1. get current value\n\n\t\tnsInstance, err := kube.Kubeclient.CoreV1().Nodes().Get(node, meta.GetOptions{})\n\n\t\tif err != nil {\n\t\t\tkube.log.PrintErr(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tcurrentAnnotations := nsInstance.GetAnnotations()\n\n\t\tif value, exists := currentAnnotations[\"ZombieKiller.HardKill\"]; exists {\n\n\t\t\texistingTimeStamp, err := strconv.ParseInt(value, 10, 64)\n\n\t\t\t// no error can proceed\n\t\t\tif err == nil {\n\t\t\t\t// this is our annotation means we have the lock\n\t\t\t\tif existingTimeStamp == now.Unix() {\n\n\t\t\t\t\tleaseTimeStamp := now.Add(leaseDuration).Unix()\n\t\t\t\t\tcurrentAnnotations[\"ZombieKiller.HardKill\"] = strconv.FormatInt(leaseTimeStamp, 10)\n\t\t\t\t\tnsInstance.SetAnnotations(currentAnnotations)\n\t\t\t\t\t_, err = kube.Kubeclient.CoreV1().Nodes().Update(nsInstance)\n\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tkube.log.PrintErr(err)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\t\tif existingTimeStamp > now.Unix() {\n\t\t\t\t\t// someone else lease is current, wont do anything\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// update now value since it is different retry\n\t\tnow = time.Now()\n\n\t\t// if we are here then annotation is old or garbage or missing so we overwrite it\n\t\tcurrentAnnotations[\"ZombieKiller.HardKill\"] = strconv.FormatInt(now.Unix(), 10)\n\n\t\tnsInstance.SetAnnotations(currentAnnotations)\n\t\t_, err = kube.Kubeclient.CoreV1().Nodes().Update(nsInstance)\n\n\t\tif err != nil {\n\t\t\tkube.log.PrintErr(err)\n\t\t\tcontinue\n\t\t}\n\t}\n\t// fallback since we unable to get the lock\n\treturn false\n}", "func (x *fastReflection_FlagOptions) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value {\n\tswitch fd.FullName() {\n\tcase \"cosmos.autocli.v1.FlagOptions.name\":\n\t\tpanic(fmt.Errorf(\"field name of message cosmos.autocli.v1.FlagOptions is not mutable\"))\n\tcase \"cosmos.autocli.v1.FlagOptions.shorthand\":\n\t\tpanic(fmt.Errorf(\"field shorthand of message cosmos.autocli.v1.FlagOptions is not mutable\"))\n\tcase \"cosmos.autocli.v1.FlagOptions.usage\":\n\t\tpanic(fmt.Errorf(\"field usage of message cosmos.autocli.v1.FlagOptions is not mutable\"))\n\tcase \"cosmos.autocli.v1.FlagOptions.default_value\":\n\t\tpanic(fmt.Errorf(\"field default_value of message cosmos.autocli.v1.FlagOptions is not mutable\"))\n\tcase \"cosmos.autocli.v1.FlagOptions.deprecated\":\n\t\tpanic(fmt.Errorf(\"field deprecated of message cosmos.autocli.v1.FlagOptions is not mutable\"))\n\tcase \"cosmos.autocli.v1.FlagOptions.shorthand_deprecated\":\n\t\tpanic(fmt.Errorf(\"field shorthand_deprecated of message cosmos.autocli.v1.FlagOptions is not mutable\"))\n\tcase \"cosmos.autocli.v1.FlagOptions.hidden\":\n\t\tpanic(fmt.Errorf(\"field hidden of message cosmos.autocli.v1.FlagOptions is not mutable\"))\n\tdefault:\n\t\tif fd.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: cosmos.autocli.v1.FlagOptions\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message cosmos.autocli.v1.FlagOptions does not contain field %s\", fd.FullName()))\n\t}\n}", "func validatePVCAnnotationForVolumeHealth(ctx context.Context, request admission.Request) admission.Response {\n\tlog := logger.GetLogger(ctx)\n\tusername := request.UserInfo.Username\n\tisCSIServiceAccount := validateCSIServiceAccount(request.UserInfo.Username)\n\tlog.Debugf(\"validatePVCAnnotationForVolumeHealth called with the request %v by user: %v\", request, username)\n\tif request.Operation == admissionv1.Delete {\n\t\t// PVC volume health annotation validation is not required for delete PVC calls\n\t\treturn admission.Allowed(\"\")\n\t}\n\tnewPVC := corev1.PersistentVolumeClaim{}\n\tif err := json.Unmarshal(request.Object.Raw, &newPVC); err != nil {\n\t\tlog.Errorf(\"error unmarshalling pvc: %v\", err)\n\t\treason := \"skipped validation when failed to deserialize PVC from new request object\"\n\t\tlog.Warn(reason)\n\t\treturn admission.Allowed(reason)\n\t}\n\n\tif request.Operation == admissionv1.Create {\n\t\t_, ok := newPVC.Annotations[common.AnnVolumeHealth]\n\t\tif ok && !isCSIServiceAccount {\n\t\t\treturn admission.Denied(fmt.Sprintf(NonCreatablePVCAnnotation, common.AnnVolumeHealth, username))\n\t\t}\n\t} else if request.Operation == admissionv1.Update {\n\t\toldPVC := corev1.PersistentVolumeClaim{}\n\t\tif err := json.Unmarshal(request.OldObject.Raw, &oldPVC); err != nil {\n\t\t\tlog.Errorf(\"error unmarshalling pvc: %v\", err)\n\t\t\treason := \"skipped validation when failed to deserialize PVC from old request object\"\n\t\t\tlog.Warn(reason)\n\t\t\treturn admission.Allowed(reason)\n\t\t}\n\n\t\tif !isCSIServiceAccount {\n\t\t\toldAnnVolumeHealthValue, oldOk := oldPVC.Annotations[common.AnnVolumeHealth]\n\t\t\tnewAnnVolumeHealthValue, newOk := newPVC.Annotations[common.AnnVolumeHealth]\n\n\t\t\t// We only need to prevent updates to volume health annotation.\n\t\t\t// Other PVC edit requests should go through.\n\n\t\t\tif oldOk && newOk {\n\t\t\t\t// Disallow updating the annotation of AnnVolumeHealth in an existing PVC.\n\t\t\t\tif oldAnnVolumeHealthValue != newAnnVolumeHealthValue {\n\t\t\t\t\treturn admission.Denied(fmt.Sprintf(NonUpdatablePVCAnnotation, common.AnnVolumeHealth, username))\n\t\t\t\t}\n\t\t\t} else if oldOk || newOk {\n\t\t\t\t// Disallow adding/removing the annotation of AnnVolumeHealth in an existing PVC.\n\t\t\t\treturn admission.Denied(fmt.Sprintf(NonUpdatablePVCAnnotation, common.AnnVolumeHealth, username))\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Debugf(\"validatePVCAnnotationForVolumeHealth completed for the request %v\", request)\n\treturn admission.Allowed(\"\")\n}", "func OverwriteChartDefaultValues(chart *helmchart.Chart, valuesFile string) (bool, error) {\n\tif valuesFile == \"\" || valuesFile == chartutil.ValuesfileName {\n\t\treturn false, nil\n\t}\n\n\t// Find override file and retrieve contents\n\tvar valuesData []byte\n\tfor _, f := range chart.Files {\n\t\tif f.Name == valuesFile {\n\t\t\tvaluesData = f.Data\n\t\t\tbreak\n\t\t}\n\t}\n\tif valuesData == nil {\n\t\treturn false, fmt.Errorf(\"failed to locate override values file: %s\", valuesFile)\n\t}\n\n\t// Read override values file data\n\tvalues, err := chartutil.ReadValues(valuesData)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"failed to parse override values file: %s\", valuesFile)\n\t}\n\n\t// Replace current values file in Raw field\n\tfor _, f := range chart.Raw {\n\t\tif f.Name == chartutil.ValuesfileName {\n\t\t\t// Do nothing if contents are equal\n\t\t\tif reflect.DeepEqual(f.Data, valuesData) {\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\t// Replace in Files field\n\t\t\tfor _, f := range chart.Files {\n\t\t\t\tif f.Name == chartutil.ValuesfileName {\n\t\t\t\t\tf.Data = valuesData\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tf.Data = valuesData\n\t\t\tchart.Values = values\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\t// This should never happen, helm charts must have a values.yaml file to be valid\n\treturn false, fmt.Errorf(\"failed to locate values file: %s\", chartutil.ValuesfileName)\n}", "func PatchValue(a, b, dst interface{}) error {\n\tvar err error\n\n\tif a, err = coerce(a); err != nil {\n\t\treturn err\n\t}\n\n\tif b, err = coerce(b); err != nil {\n\t\treturn err\n\t}\n\n\treturn marshalValue(a, b, dst)\n}", "func TestChange(t *testing.T) {\n\tschema := config.Schema{\n\t\t\"foo\": {},\n\t\t\"bar\": {Setter: upperCase},\n\t\t\"egg\": {Type: config.Bool},\n\t\t\"yuk\": {Type: config.Bool, Default: \"true\"},\n\t\t\"xyz\": {Hidden: true},\n\t}\n\n\tvalues := map[string]string{ // Initial values\n\t\t\"foo\": \"hello\",\n\t\t\"bar\": \"x\",\n\t\t\"xyz\": \"sekret\",\n\t}\n\n\tcases := []struct {\n\t\ttitle string\n\t\tvalues map[string]any // New values\n\t\tresult map[string]string // Expected values after change\n\t}{\n\t\t{\n\t\t\t`plain change of regular key`,\n\t\t\tmap[string]any{\"foo\": \"world\"},\n\t\t\tmap[string]string{\"foo\": \"world\"},\n\t\t},\n\t\t{\n\t\t\t`key setter is honored`,\n\t\t\tmap[string]any{\"bar\": \"y\"},\n\t\t\tmap[string]string{\"bar\": \"Y\"},\n\t\t},\n\t\t{\n\t\t\t`bool true values are normalized`,\n\t\t\tmap[string]any{\"egg\": \"yes\"},\n\t\t\tmap[string]string{\"egg\": \"true\"},\n\t\t},\n\t\t{\n\t\t\t`bool false values are normalized`,\n\t\t\tmap[string]any{\"yuk\": \"0\"},\n\t\t\tmap[string]string{\"yuk\": \"false\"},\n\t\t},\n\t\t{\n\t\t\t`the special value 'true' is a passthrough for hidden keys`,\n\t\t\tmap[string]any{\"xyz\": true},\n\t\t\tmap[string]string{\"xyz\": \"sekret\"},\n\t\t},\n\t\t{\n\t\t\t`the special value nil is converted to empty string`,\n\t\t\tmap[string]any{\"foo\": nil},\n\t\t\tmap[string]string{\"foo\": \"\"},\n\t\t},\n\t\t{\n\t\t\t`multiple values are all mutated`,\n\t\t\tmap[string]any{\"foo\": \"x\", \"bar\": \"hey\", \"egg\": \"0\"},\n\t\t\tmap[string]string{\"foo\": \"x\", \"bar\": \"HEY\", \"egg\": \"\"},\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\tt.Run(c.title, func(t *testing.T) {\n\t\t\tm, err := config.Load(schema, values)\n\t\t\trequire.NoError(t, err)\n\n\t\t\t_, err = m.Change(c.values)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tfor name, value := range c.result {\n\t\t\t\tassert.Equal(t, value, m.GetRaw(name))\n\t\t\t}\n\t\t})\n\t}\n}", "func (c *Config) propagateValuesDown() {\n\tfor i := range c.Monitors {\n\t\tif c.Monitors[i].ValidateDiscoveryRule == nil {\n\t\t\tc.Monitors[i].ValidateDiscoveryRule = c.ValidateDiscoveryRules\n\t\t}\n\t\tif c.Monitors[i].ProcPath == \"\" {\n\t\t\tc.Monitors[i].ProcPath = c.ProcPath\n\t\t}\n\t}\n\n\tanyCollectdMonitors := false\n\tfor i := range c.Monitors {\n\t\tanyCollectdMonitors = anyCollectdMonitors || c.Monitors[i].IsCollectdBased()\n\t}\n\n\tc.Collectd.DisableCollectd = c.Collectd.DisableCollectd || !anyCollectdMonitors\n\tc.Collectd.IntervalSeconds = utils.FirstNonZero(c.Collectd.IntervalSeconds, c.IntervalSeconds)\n\tc.Collectd.BundleDir = c.BundleDir\n\n\tc.Writer.MetricsToInclude = c.MetricsToInclude\n\tc.Writer.MetricsToExclude = c.MetricsToExclude\n\tc.Writer.PropertiesToExclude = c.PropertiesToExclude\n\tc.Writer.IngestURL = c.IngestURL\n\tc.Writer.APIURL = c.APIURL\n\tc.Writer.EventEndpointURL = c.EventEndpointURL\n\tc.Writer.TraceEndpointURL = c.TraceEndpointURL\n\tc.Writer.SignalFxAccessToken = c.SignalFxAccessToken\n\tc.Writer.GlobalDimensions = c.GlobalDimensions\n\tc.Writer.GlobalSpanTags = c.GlobalSpanTags\n}", "func (m *DeviceCompliancePolicySettingStateSummary) SetConflictDeviceCount(value *int32)() {\n err := m.GetBackingStore().Set(\"conflictDeviceCount\", value)\n if err != nil {\n panic(err)\n }\n}", "func updateAnnotations(obj runtime.Object) error {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tannotations := accessor.GetAnnotations()\n\tif annotations == nil {\n\t\tannotations = make(map[string]string)\n\t}\n\n\tannotations[\"helm.sh/hook\"] = \"pre-install\"\n\n\taccessor.SetAnnotations(annotations)\n\n\treturn nil\n}", "func (m *DeviceHealthAttestationState) SetHealthStatusMismatchInfo(value *string)() {\n err := m.GetBackingStore().Set(\"healthStatusMismatchInfo\", value)\n if err != nil {\n panic(err)\n }\n}", "func setLabel(object metav1.Object, key string, value string) {\n\tlabels := object.GetLabels()\n\tif labels == nil {\n\t\tlabels = map[string]string{}\n\t}\n\tif value != \"\" {\n\t\tlabels[key] = value\n\t} else {\n\t\tdelete(labels, key)\n\t}\n\tobject.SetLabels(labels)\n}", "func (m *MacOSMinimumOperatingSystem) SetV1010(value *bool)() {\n err := m.GetBackingStore().Set(\"v10_10\", value)\n if err != nil {\n panic(err)\n }\n}", "func (r *OpenStackCluster) ValidateUpdate(oldRaw runtime.Object) (admission.Warnings, error) {\n\tvar allErrs field.ErrorList\n\told, ok := oldRaw.(*OpenStackCluster)\n\tif !ok {\n\t\treturn nil, apierrors.NewBadRequest(fmt.Sprintf(\"expected an OpenStackCluster but got a %T\", oldRaw))\n\t}\n\n\tif r.Spec.IdentityRef != nil && r.Spec.IdentityRef.Kind != defaultIdentityRefKind {\n\t\tallErrs = append(allErrs,\n\t\t\tfield.Invalid(field.NewPath(\"spec\", \"identityRef\", \"kind\"),\n\t\t\t\tr.Spec.IdentityRef, \"must be a Secret\"),\n\t\t)\n\t}\n\n\t// Allow changes to Spec.IdentityRef.Name.\n\tif old.Spec.IdentityRef != nil && r.Spec.IdentityRef != nil {\n\t\told.Spec.IdentityRef.Name = \"\"\n\t\tr.Spec.IdentityRef.Name = \"\"\n\t}\n\n\t// Allow changes to Spec.IdentityRef if it was unset.\n\tif old.Spec.IdentityRef == nil && r.Spec.IdentityRef != nil {\n\t\told.Spec.IdentityRef = &OpenStackIdentityReference{}\n\t\tr.Spec.IdentityRef = &OpenStackIdentityReference{}\n\t}\n\n\tif old.Spec.IdentityRef != nil && r.Spec.IdentityRef == nil {\n\t\tallErrs = append(allErrs,\n\t\t\tfield.Invalid(field.NewPath(\"spec\", \"identityRef\"),\n\t\t\t\tr.Spec.IdentityRef, \"field cannot be set to nil\"),\n\t\t)\n\t}\n\n\t// Allow change only for the first time.\n\tif old.Spec.ControlPlaneEndpoint.Host == \"\" {\n\t\told.Spec.ControlPlaneEndpoint = clusterv1.APIEndpoint{}\n\t\tr.Spec.ControlPlaneEndpoint = clusterv1.APIEndpoint{}\n\t}\n\n\t// Allow change only for the first time.\n\tif old.Spec.DisableAPIServerFloatingIP && old.Spec.APIServerFixedIP == \"\" {\n\t\tr.Spec.APIServerFixedIP = \"\"\n\t}\n\n\t// If API Server floating IP is disabled, allow the change of the API Server port only for the first time.\n\tif old.Spec.DisableAPIServerFloatingIP && old.Spec.APIServerPort == 0 && r.Spec.APIServerPort > 0 {\n\t\tr.Spec.APIServerPort = 0\n\t}\n\n\t// Allow changes to the bastion spec.\n\told.Spec.Bastion = &Bastion{}\n\tr.Spec.Bastion = &Bastion{}\n\n\t// Allow changes on AllowedCIDRs\n\tif r.Spec.APIServerLoadBalancer.Enabled {\n\t\told.Spec.APIServerLoadBalancer.AllowedCIDRs = []string{}\n\t\tr.Spec.APIServerLoadBalancer.AllowedCIDRs = []string{}\n\t}\n\n\t// Allow changes to the availability zones.\n\told.Spec.ControlPlaneAvailabilityZones = []string{}\n\tr.Spec.ControlPlaneAvailabilityZones = []string{}\n\n\tif !reflect.DeepEqual(old.Spec, r.Spec) {\n\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"spec\"), \"cannot be modified\"))\n\t}\n\n\treturn aggregateObjErrors(r.GroupVersionKind().GroupKind(), r.Name, allErrs)\n}", "func (vca *VapmControlApi) ChangeVulnerabilityIgnorance(ctx context.Context, wstrVulnerabilityUid, wstrHostId string, bIgnore bool) ([]byte, error) {\n\tpostData := []byte(fmt.Sprintf(`{\"wstrVulnerabilityUid\": \"%s\", \"wstrHostId\": \"%s\", \"bIgnore\": %v}`,\n\t\twstrVulnerabilityUid, wstrHostId, bIgnore))\n\trequest, err := http.NewRequest(\"POST\", vca.client.Server+\"/api/v1.0/VapmControlApi.ChangeVulnerabilityIgnorance\", bytes.NewBuffer(postData))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\traw, err := vca.client.Do(ctx, request, nil)\n\treturn raw, err\n}", "func (m *DeviceHealthScriptRunSummary) SetNoIssueDetectedDeviceCount(value *int32)() {\n err := m.GetBackingStore().Set(\"noIssueDetectedDeviceCount\", value)\n if err != nil {\n panic(err)\n }\n}", "func populateConfigOverrideConfigMap(clusterdContext *clusterd.Context, namespace string, ownerInfo *k8sutil.OwnerInfo, clusterMetadata metav1.ObjectMeta) error {\n\tctx := context.TODO()\n\n\texistingCM, err := clusterdContext.Clientset.CoreV1().ConfigMaps(namespace).Get(ctx, k8sutil.ConfigOverrideName, metav1.GetOptions{})\n\tif err != nil {\n\t\tif !kerrors.IsNotFound(err) {\n\t\t\tlogger.Warningf(\"failed to get cm %q to check labels and annotations\", k8sutil.ConfigOverrideName)\n\t\t\treturn nil\n\t\t}\n\n\t\tlabels := map[string]string{}\n\t\tannotations := map[string]string{}\n\t\tinitRequiredMetadata(clusterMetadata, labels, annotations)\n\n\t\t// Create the configmap since it doesn't exist yet\n\t\tplaceholderConfig := map[string]string{\n\t\t\tk8sutil.ConfigOverrideVal: \"\",\n\t\t}\n\t\tcm := &v1.ConfigMap{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: k8sutil.ConfigOverrideName,\n\t\t\t\tNamespace: namespace,\n\t\t\t\tLabels: labels,\n\t\t\t\tAnnotations: annotations,\n\t\t\t},\n\t\t\tData: placeholderConfig,\n\t\t}\n\n\t\terr := ownerInfo.SetControllerReference(cm)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to set owner reference to override configmap %q\", cm.Name)\n\t\t}\n\t\t_, err = clusterdContext.Clientset.CoreV1().ConfigMaps(namespace).Create(ctx, cm, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to create override configmap %s\", namespace)\n\t\t}\n\t\tlogger.Infof(\"created placeholder configmap for ceph overrides %q\", cm.Name)\n\t\treturn nil\n\t}\n\n\t// Ensure the annotations and labels are initialized\n\tif existingCM.Annotations == nil {\n\t\texistingCM.Annotations = map[string]string{}\n\t}\n\tif existingCM.Labels == nil {\n\t\texistingCM.Labels = map[string]string{}\n\t}\n\n\t// Add recommended labels and annotations to the existing configmap if it doesn't have any yet\n\tupdateRequired := initRequiredMetadata(clusterMetadata, existingCM.Labels, existingCM.Annotations)\n\tif updateRequired {\n\t\t_, err = clusterdContext.Clientset.CoreV1().ConfigMaps(namespace).Update(ctx, existingCM, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\tlogger.Warningf(\"failed to add recommended labels and annotations to configmap %q. %v\", existingCM.Name, err)\n\t\t} else {\n\t\t\tlogger.Infof(\"added expected labels and annotations to configmap %q\", existingCM.Name)\n\t\t}\n\t}\n\treturn nil\n}", "func (record *PrivateDnsZonesSRVRecord) validateWriteOnceProperties(old runtime.Object) (admission.Warnings, error) {\n\toldObj, ok := old.(*PrivateDnsZonesSRVRecord)\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\n\treturn genruntime.ValidateWriteOnceProperties(oldObj, record)\n}", "func (x *fastReflection_RpcCommandOptions) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value {\n\tswitch fd.FullName() {\n\tcase \"cosmos.autocli.v1.RpcCommandOptions.alias\":\n\t\tif x.Alias == nil {\n\t\t\tx.Alias = []string{}\n\t\t}\n\t\tvalue := &_RpcCommandOptions_6_list{list: &x.Alias}\n\t\treturn protoreflect.ValueOfList(value)\n\tcase \"cosmos.autocli.v1.RpcCommandOptions.suggest_for\":\n\t\tif x.SuggestFor == nil {\n\t\t\tx.SuggestFor = []string{}\n\t\t}\n\t\tvalue := &_RpcCommandOptions_7_list{list: &x.SuggestFor}\n\t\treturn protoreflect.ValueOfList(value)\n\tcase \"cosmos.autocli.v1.RpcCommandOptions.flag_options\":\n\t\tif x.FlagOptions == nil {\n\t\t\tx.FlagOptions = make(map[string]*FlagOptions)\n\t\t}\n\t\tvalue := &_RpcCommandOptions_10_map{m: &x.FlagOptions}\n\t\treturn protoreflect.ValueOfMap(value)\n\tcase \"cosmos.autocli.v1.RpcCommandOptions.positional_args\":\n\t\tif x.PositionalArgs == nil {\n\t\t\tx.PositionalArgs = []*PositionalArgDescriptor{}\n\t\t}\n\t\tvalue := &_RpcCommandOptions_11_list{list: &x.PositionalArgs}\n\t\treturn protoreflect.ValueOfList(value)\n\tcase \"cosmos.autocli.v1.RpcCommandOptions.rpc_method\":\n\t\tpanic(fmt.Errorf(\"field rpc_method of message cosmos.autocli.v1.RpcCommandOptions is not mutable\"))\n\tcase \"cosmos.autocli.v1.RpcCommandOptions.use\":\n\t\tpanic(fmt.Errorf(\"field use of message cosmos.autocli.v1.RpcCommandOptions is not mutable\"))\n\tcase \"cosmos.autocli.v1.RpcCommandOptions.long\":\n\t\tpanic(fmt.Errorf(\"field long of message cosmos.autocli.v1.RpcCommandOptions is not mutable\"))\n\tcase \"cosmos.autocli.v1.RpcCommandOptions.short\":\n\t\tpanic(fmt.Errorf(\"field short of message cosmos.autocli.v1.RpcCommandOptions is not mutable\"))\n\tcase \"cosmos.autocli.v1.RpcCommandOptions.example\":\n\t\tpanic(fmt.Errorf(\"field example of message cosmos.autocli.v1.RpcCommandOptions is not mutable\"))\n\tcase \"cosmos.autocli.v1.RpcCommandOptions.deprecated\":\n\t\tpanic(fmt.Errorf(\"field deprecated of message cosmos.autocli.v1.RpcCommandOptions is not mutable\"))\n\tcase \"cosmos.autocli.v1.RpcCommandOptions.version\":\n\t\tpanic(fmt.Errorf(\"field version of message cosmos.autocli.v1.RpcCommandOptions is not mutable\"))\n\tcase \"cosmos.autocli.v1.RpcCommandOptions.skip\":\n\t\tpanic(fmt.Errorf(\"field skip of message cosmos.autocli.v1.RpcCommandOptions is not mutable\"))\n\tdefault:\n\t\tif fd.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: cosmos.autocli.v1.RpcCommandOptions\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message cosmos.autocli.v1.RpcCommandOptions does not contain field %s\", fd.FullName()))\n\t}\n}", "func OverwriteMetadata(config *overwriteConfig, dir string) error {\n\tfmt.Printf(\"Replacing the default values of the variables: %s in %s\\n\",\n\t\tconfig.Variables, metadataFile)\n\n\tdata, err := os.ReadFile(path.Join(dir, metadataFile))\n\tif err != nil {\n\t\t// CLI only modules will not have a metadata file. Ignore file not found errors\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\tjson, err := yaml.YAMLToJSON(data)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failure parsing %s error: %w\", metadataFile, err)\n\t}\n\n\tfor _, variable := range config.Variables {\n\t\tquery := fmt.Sprintf(`spec.interfaces.variables.#(name==\"%s\").defaultValue`, variable)\n\t\tdefaultVal := gjson.GetBytes(json, query).String()\n\t\tif defaultVal == \"\" {\n\t\t\treturn fmt.Errorf(\"Missing valid default value for variable: %s in %s\",\n\t\t\t\tvariable, metadataFile)\n\t\t}\n\t\treplaceVal, ok := config.Replacements[defaultVal]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"default value: %s of variable: %s in %s not found\"+\n\t\t\t\t\" in replacements\", defaultVal, variable, metadataFile)\n\t\t}\n\n\t\tjson, err = sjson.SetBytes(json, query, replaceVal)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error setting default value of variable: %s. error: %w\",\n\t\t\t\tvariable, err)\n\t\t}\n\t}\n\n\tmodifiedYaml, err := yaml.JSONToYAML([]byte(json))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.WriteFile(path.Join(dir, metadataFile), modifiedYaml, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"Successfully replaced default values in %s\\n\", metadataFile)\n\treturn nil\n}", "func (endpointSliceStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}", "func TestCommonLabelsImmutable(t *testing.T) {\n\trootDir := \"..\"\n\n\t// Directories to exclude. Thee paths should be relative to rootDir.\n\t// Subdirectories won't be searched\n\texcludes := map[string]bool{\n\t\t\"tests\": true,\n\t\t\".git\": true,\n\t\t\".github\": true,\n\t}\n\n\t// These labels are likely to be mutable and should not be part of commonLabels\n\tforbiddenLabels := []string{VersionLabel, ManagedByLabel, InstanceLabel, PartOfLabel}\n\n\terr := filepath.Walk(\"..\", func(path string, info os.FileInfo, err error) error {\n\t\trelPath, err := filepath.Rel(rootDir, path)\n\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Could not compute relative path(%v, %v); error: %v\", rootDir, path, err)\n\t\t}\n\n\t\tif _, ok := excludes[relPath]; ok {\n\t\t\tt.Logf(\"Skipping directory %v\", path)\n\t\t\treturn filepath.SkipDir\n\t\t}\n\n\t\t// skip directories\n\t\tif info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\tif info.Name() != KustomizationFile {\n\t\t\treturn nil\n\t\t}\n\n\t\tk, err := readKustomization(path)\n\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Error reading file: %v; error: %v\", path, err)\n\t\t\treturn nil\n\t\t}\n\n\t\tif k.CommonLabels == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tfor _, l := range forbiddenLabels {\n\t\t\tif _, ok := k.CommonLabels[l]; ok {\n\t\t\t\tt.Errorf(\"%v has forbidden commonLabel %v\", path, l)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tt.Errorf(\"error walking the path %v; error: %v\", rootDir, err)\n\n\t}\n}", "func deleteLabelValueOp(metric pmetric.Metric, mtpOp internalOperation) {\n\top := mtpOp.configOperation\n\t//exhaustive:enforce\n\tswitch metric.Type() {\n\tcase pmetric.MetricTypeGauge:\n\t\tmetric.Gauge().DataPoints().RemoveIf(func(dp pmetric.NumberDataPoint) bool {\n\t\t\treturn hasAttr(dp.Attributes(), op.Label, op.LabelValue)\n\t\t})\n\tcase pmetric.MetricTypeSum:\n\t\tmetric.Sum().DataPoints().RemoveIf(func(dp pmetric.NumberDataPoint) bool {\n\t\t\treturn hasAttr(dp.Attributes(), op.Label, op.LabelValue)\n\t\t})\n\tcase pmetric.MetricTypeHistogram:\n\t\tmetric.Histogram().DataPoints().RemoveIf(func(dp pmetric.HistogramDataPoint) bool {\n\t\t\treturn hasAttr(dp.Attributes(), op.Label, op.LabelValue)\n\t\t})\n\tcase pmetric.MetricTypeExponentialHistogram:\n\t\tmetric.ExponentialHistogram().DataPoints().RemoveIf(func(dp pmetric.ExponentialHistogramDataPoint) bool {\n\t\t\treturn hasAttr(dp.Attributes(), op.Label, op.LabelValue)\n\t\t})\n\tcase pmetric.MetricTypeSummary:\n\t\tmetric.Summary().DataPoints().RemoveIf(func(dp pmetric.SummaryDataPoint) bool {\n\t\t\treturn hasAttr(dp.Attributes(), op.Label, op.LabelValue)\n\t\t})\n\t}\n}", "func validateExtraConfig(reflectValue reflect.Value) schema.SchemaValidateDiagFunc {\n\treturn func(v interface{}, path cty.Path) diag.Diagnostics {\n\t\tvar diags diag.Diagnostics\n\n\t\textraConfig := v.(map[string]interface{})\n\n\t\tfor i := 0; i < reflectValue.NumField(); i++ {\n\t\t\tfield := reflectValue.Field(i)\n\t\t\tjsonKey := strings.Split(reflectValue.Type().Field(i).Tag.Get(\"json\"), \",\")[0]\n\n\t\t\tif jsonKey != \"-\" && field.CanSet() {\n\t\t\t\tif _, ok := extraConfig[jsonKey]; ok {\n\t\t\t\t\tdiags = append(diags, diag.Diagnostic{\n\t\t\t\t\t\tSeverity: diag.Error,\n\t\t\t\t\t\tSummary: \"Invalid extra_config key\",\n\t\t\t\t\t\tDetail: fmt.Sprintf(`extra_config key \"%s\" is not allowed, as it conflicts with a top-level schema attribute`, jsonKey),\n\t\t\t\t\t\tAttributePath: append(path, cty.IndexStep{\n\t\t\t\t\t\t\tKey: cty.StringVal(jsonKey),\n\t\t\t\t\t\t}),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn diags\n\t}\n}", "func (strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn warningsForSecret(obj.(*api.Secret))\n}", "func (b *Builder) PanicsAndRecoveredValue() *Builder {\n\tb.p.RegisterTransformation(impl.PanicsAndRecoveredValue())\n\treturn b\n}", "func mutationRequired(ignoredList []string, metadata *metav1.ObjectMeta) bool {\n\n\tif metadata == nil {\n\t\treturn false\n\t}\n\n\t// If the environment variable MATCH_NAMESPACE exists,\n\t// only the namespaces in the environment variable will be matched\n\te := os.Getenv(\"MATCH_NAMESPACE\")\n\tif e != \"\" {\n\t\te = strings.Replace(e, \" \", \"\", -1)\n\t\tmatchNamespaces := strings.Split(e, \",\")\n\t\tmatchNamespacesMap := make(map[string]struct{})\n\t\tfor _, ns := range matchNamespaces {\n\t\t\tmatchNamespacesMap[ns] = struct{}{}\n\t\t}\n\t\tif _, ok := matchNamespacesMap[metadata.Namespace]; !ok {\n\t\t\tglog.Infof(\n\t\t\t\t\"Skip mutation %s/%s, it's not in the MATCH_NAMESPACE %v\",\n\t\t\t\tmetadata.Namespace, metadata.Name, matchNamespaces,\n\t\t\t)\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// skip special kubernete system namespaces\n\tfor _, namespace := range ignoredList {\n\t\tif metadata.Namespace == namespace {\n\t\t\tglog.Infof(\"Skip mutation for %v for it's in special namespace:%v\", metadata.Name, metadata.Namespace)\n\t\t\treturn false\n\t\t}\n\t}\n\n\tannotations := metadata.GetAnnotations()\n\tif annotations == nil {\n\t\tannotations = map[string]string{}\n\t}\n\n\t// ignore recreate resource for devend\n\tif annotations[\"nocalhost-dep-ignore\"] == \"true\" {\n\t\treturn false\n\t}\n\n\t//status := annotations[admissionWebhookAnnotationStatusKey]\n\n\t// determine whether to perform mutation based on annotation for the target resource\n\tvar required = true\n\n\t//glog.Infof(\"Mutation policy for %v/%v: status: %q required:%v\", metadata.Namespace, metadata.Name, status, required)\n\treturn required\n}", "func NeedOverwriteSelector(kd *kanaryv1alpha1.KanaryStatefulset) bool {\n\t// if we dont want that\n\tswitch kd.Spec.Traffic.Source {\n\tcase kanaryv1alpha1.ServiceKanaryStatefulsetSpecTrafficSource, kanaryv1alpha1.BothKanaryStatefulsetSpecTrafficSource:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (m *CloudPcBulkActionSummary) SetNotSupportedCount(value *int32)() {\n err := m.GetBackingStore().Set(\"notSupportedCount\", value)\n if err != nil {\n panic(err)\n }\n}", "func disallowMutateBootstrapSQLConfigMapName(old, new *v1alpha1.TiDBSpec, p *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif old == nil || new == nil {\n\t\treturn allErrs\n\t}\n\n\tbootstrapSQLSpecified := old.BootstrapSQLConfigMapName != nil && new.BootstrapSQLConfigMapName != nil\n\tif (bootstrapSQLSpecified && *old.BootstrapSQLConfigMapName != *new.BootstrapSQLConfigMapName) ||\n\t\t(!bootstrapSQLSpecified && new.BootstrapSQLConfigMapName != nil) {\n\t\treturn append(allErrs, field.Invalid(p, new.BootstrapSQLConfigMapName, \"bootstrapSQLConfigMapName is immutable\"))\n\t}\n\n\treturn allErrs\n}", "func addLabelToResource(resource *metav1.ObjectMeta, ctx *ReporterContext) {\n\t// k8s labels may be nil,need to make it\n\tif resource.Labels == nil {\n\t\tresource.Labels = make(map[string]string)\n\t}\n\n\tresource.Labels[ClusterLabel] = ctx.ClusterName()\n\t// support for CM sequential checking\n\tresource.Labels[EdgeVersionLabel] = resource.ResourceVersion\n}", "func EnsureValue(m map[string]map[string]string, key string, defaultValue map[string]string) {\n\tif _, ok := m[key]; !ok {\n\t\tm[key] = defaultValue\n\t}\n}", "func (c *AgentConfig) loadDeprecatedValues() error {\n\tcfg := config.Datadog\n\tif cfg.IsSet(\"apm_config.api_key\") {\n\t\tc.Endpoints[0].APIKey = config.Datadog.GetString(\"apm_config.api_key\")\n\t}\n\tif cfg.IsSet(\"apm_config.log_level\") {\n\t\tc.LogLevel = config.Datadog.GetString(\"apm_config.log_level\")\n\t}\n\tif v := cfg.GetString(\"apm_config.extra_aggregators\"); len(v) > 0 {\n\t\taggs, err := splitString(v, ',')\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.ExtraAggregators = append(c.ExtraAggregators, aggs...)\n\t}\n\tif cfg.IsSet(\"apm_config.log_throttling\") {\n\t\tc.LogThrottling = cfg.GetBool(\"apm_config.log_throttling\")\n\t}\n\tif cfg.IsSet(\"apm_config.bucket_size_seconds\") {\n\t\td := time.Duration(cfg.GetInt(\"apm_config.bucket_size_seconds\"))\n\t\tc.BucketInterval = d * time.Second\n\t}\n\tif cfg.IsSet(\"apm_config.receiver_timeout\") {\n\t\tc.ReceiverTimeout = cfg.GetInt(\"apm_config.receiver_timeout\")\n\t}\n\tif cfg.IsSet(\"apm_config.watchdog_check_delay\") {\n\t\td := time.Duration(cfg.GetInt(\"apm_config.watchdog_check_delay\"))\n\t\tc.WatchdogInterval = d * time.Second\n\t}\n\treturn nil\n}", "func (kv *ShardKV) Setunreliable(what bool) {\n\tif what {\n\t\tatomic.StoreInt32(&kv.unreliable, 1)\n\t} else {\n\t\tatomic.StoreInt32(&kv.unreliable, 0)\n\t}\n}", "func (kv *ShardKV) Setunreliable(what bool) {\n\tif what {\n\t\tatomic.StoreInt32(&kv.unreliable, 1)\n\t} else {\n\t\tatomic.StoreInt32(&kv.unreliable, 0)\n\t}\n}", "func (kv *ShardKV) Setunreliable(what bool) {\n\tif what {\n\t\tatomic.StoreInt32(&kv.unreliable, 1)\n\t} else {\n\t\tatomic.StoreInt32(&kv.unreliable, 0)\n\t}\n}" ]
[ "0.57387376", "0.56770146", "0.5325457", "0.52686155", "0.5221165", "0.5115243", "0.5090307", "0.5084478", "0.5011687", "0.5003867", "0.4992041", "0.49483496", "0.4907851", "0.4899597", "0.48568922", "0.48058712", "0.47964463", "0.47960916", "0.47834474", "0.47803378", "0.4761119", "0.47582644", "0.47457424", "0.47388834", "0.47325444", "0.47163874", "0.47095647", "0.47094405", "0.47045875", "0.4695371", "0.46870327", "0.46753517", "0.46740693", "0.46740404", "0.46716115", "0.46714228", "0.46697107", "0.46697107", "0.46697107", "0.46616897", "0.46526384", "0.4626432", "0.46186617", "0.46180138", "0.46130908", "0.45891622", "0.45889148", "0.45786694", "0.45614153", "0.4552659", "0.4550552", "0.45435303", "0.45283636", "0.45268437", "0.45258176", "0.4521207", "0.45155498", "0.45153064", "0.4511149", "0.45042834", "0.44795573", "0.44668508", "0.44650286", "0.4457061", "0.44502667", "0.44500017", "0.44478664", "0.4447529", "0.44427007", "0.44382307", "0.4438146", "0.4422171", "0.44157138", "0.44139034", "0.44134524", "0.44128618", "0.4409532", "0.44093877", "0.4407743", "0.4404211", "0.43989533", "0.43963322", "0.4394716", "0.43920115", "0.4391575", "0.43902704", "0.43893835", "0.43890122", "0.43853366", "0.43804255", "0.43726784", "0.4366043", "0.43633157", "0.43632007", "0.43497226", "0.4333209", "0.43326625", "0.4332543", "0.4332543", "0.4332543" ]
0.8512307
0
newParser creates a parser that can parse AC's binary ping/pong protocol into structs.
func newParser(b []byte) parser { return parser{ bytes: b, i: 0, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newParser(filename string, b []byte, opts ...Option) *parser {\n\tstats := Stats{\n\t\tChoiceAltCnt: make(map[string]map[string]int),\n\t}\n\n\tp := &parser{\n\t\tfilename: filename,\n\t\terrs: new(errList),\n\t\tdata: b,\n\t\tpt: savepoint{position: position{line: 1}},\n\t\trecover: true,\n\t\tcur: current{\n\t\t\tglobalStore: make(storeDict),\n\t\t},\n\t\tmaxFailPos: position{col: 1, line: 1},\n\t\tmaxFailExpected: make([]string, 0, 20),\n\t\tStats: &stats,\n\t\t// start rule is rule [0] unless an alternate entrypoint is specified\n\t\tentrypoint: g.rules[0].name,\n\t}\n\tp.setOptions(opts)\n\n\tif p.maxExprCnt == 0 {\n\t\tp.maxExprCnt = math.MaxUint64\n\t}\n\n\treturn p\n}", "func newParser(filename string, b []byte, opts ...Option) *parser {\n\tstats := Stats{\n\t\tChoiceAltCnt: make(map[string]map[string]int),\n\t}\n\n\tp := &parser{\n\t\tfilename: filename,\n\t\terrs: new(errList),\n\t\tdata: b,\n\t\tpt: savepoint{position: position{line: 1}},\n\t\trecover: true,\n\t\tcur: current{\n\t\t\tstate: make(storeDict),\n\t\t\tglobalStore: make(storeDict),\n\t\t},\n\t\tmaxFailPos: position{col: 1, line: 1},\n\t\tmaxFailExpected: make([]string, 0, 20),\n\t\tStats: &stats,\n\t\t// start rule is rule [0] unless an alternate entrypoint is specified\n\t\tentrypoint: g.rules[0].name,\n\t}\n\tp.setOptions(opts)\n\n\tif p.maxExprCnt == 0 {\n\t\tp.maxExprCnt = math.MaxUint64\n\t}\n\n\treturn p\n}", "func newParser(filename string, b []byte, opts ...Option) *parser {\n\tstats := Stats{\n\t\tChoiceAltCnt: make(map[string]map[string]int),\n\t}\n\n\tp := &parser{\n\t\tfilename: filename,\n\t\terrs: new(errList),\n\t\tdata: b,\n\t\tpt: savepoint{position: position{line: 1}},\n\t\trecover: true,\n\t\tcur: current{\n\t\t\tstate: make(storeDict),\n\t\t\tglobalStore: make(storeDict),\n\t\t},\n\t\tmaxFailPos: position{col: 1, line: 1},\n\t\tmaxFailExpected: make([]string, 0, 20),\n\t\tStats: &stats,\n\t\t// start rule is rule [0] unless an alternate entrypoint is specified\n\t\tentrypoint: g.rules[0].name,\n\t}\n\tp.setOptions(opts)\n\n\tif p.maxExprCnt == 0 {\n\t\tp.maxExprCnt = math.MaxUint64\n\t}\n\n\treturn p\n}", "func newParser(filename string, b []byte, opts ...Option) *parser {\n\tstats := Stats{\n\t\tChoiceAltCnt: make(map[string]map[string]int),\n\t}\n\n\tp := &parser{\n\t\tfilename: filename,\n\t\terrs: new(errList),\n\t\tdata: b,\n\t\tpt: savepoint{position: position{line: 1}},\n\t\trecover: true,\n\t\tcur: current{\n\t\t\tstate: make(storeDict),\n\t\t\tglobalStore: make(storeDict),\n\t\t},\n\t\tmaxFailPos: position{col: 1, line: 1},\n\t\tmaxFailExpected: make([]string, 0, 20),\n\t\tStats: &stats,\n\t\t// start rule is rule [0] unless an alternate entrypoint is specified\n\t\tentrypoint: g.rules[0].name,\n\t}\n\tp.setOptions(opts)\n\n\tif p.maxExprCnt == 0 {\n\t\tp.maxExprCnt = math.MaxUint64\n\t}\n\n\treturn p\n}", "func newParser(src []byte) *blockParser {\n\tp := &parser{\n\t\tsrc: src,\n\t}\n\tbp := &blockParser{parser: p, blockChan: make(chan Block)}\n\tgo bp.run()\n\treturn bp\n}", "func newParser(filename string, b []byte, opts ...Option) *parser {\n\tp := &parser{\n\t\tfilename: filename,\n\t\terrs: new(errList),\n\t\tdata: b,\n\t\tpt: savepoint{position: position{line: 1}},\n\t\trecover: true,\n\t}\n\tp.setOptions(opts)\n\treturn p\n}", "func NewParser(listener ParserListener) *Parser {\n\tasciiParser := newAsciiParser(listener)\n\treturn &Parser{listener, asciiParser, binary.BigEndian}\n}", "func NewParser() *Parser {\n\treturn &Parser{\n\t\tProfile: Profile{\n\t\t\tServiceUnits: make([]ServiceUnit, 0),\n\t\t},\n\t}\n}", "func NewParser() *Parser {\r\n\treturn &Parser{\"\",make(map[string]*NonTerminal)}\r\n}", "func newParser(invocation string, verbose bool) *parser {\n\tp := &parser{\n\t\tScanner: &scanner.Scanner{},\n\t\toriginal: invocation,\n\t\tverbose: verbose,\n\t\terrors: make([]error, 0),\n\t}\n\tp.Init(strings.NewReader(invocation))\n\tp.Error = func(s *scanner.Scanner, msg string) {\n\t\tp.errors = append(p.errors, p.error(s.Position, msg))\n\t}\n\treturn p\n}", "func NewParser(transactionFunc TransactionFunc) *Parser {\n\n\treturn &Parser{\n\t\ttransaction: nil,\n\t\tcallback: transactionFunc,\n\t\tstateMachine: fsm.NewFSM(\n\t\t\tstate.Idle,\n\t\t\tfsm.Events{\n\t\t\t\t{\n\t\t\t\t\tName: event.BeginIn,\n\t\t\t\t\tDst: state.Start,\n\t\t\t\t\tSrc: []string{state.Idle},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: event.BeginOut,\n\t\t\t\t\tDst: state.Started,\n\t\t\t\t\tSrc: []string{state.Start},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: event.OperationIn,\n\t\t\t\t\tDst: state.Store,\n\t\t\t\t\tSrc: []string{state.Started, state.Stored},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: event.OperationOut,\n\t\t\t\t\tDst: state.Stored,\n\t\t\t\t\tSrc: []string{state.Store},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: event.CommitIn,\n\t\t\t\t\tDst: state.Publish,\n\t\t\t\t\tSrc: []string{state.Stored, state.Started},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: event.CommitOut,\n\t\t\t\t\tDst: state.Idle,\n\t\t\t\t\tSrc: []string{state.Publish},\n\t\t\t\t},\n\t\t\t},\n\t\t\tfsm.Callbacks{\n\t\t\t\t\"enter_state\": func(e *fsm.Event) {\n\t\t\t\t\tlogger.Debug(\"enter state\",\n\t\t\t\t\t\tzap.String(\"event\", e.Event),\n\t\t\t\t\t\tzap.String(\"src\", e.Src),\n\t\t\t\t\t\tzap.String(\"dst\", e.Dst),\n\t\t\t\t\t)\n\t\t\t\t},\n\t\t\t},\n\t\t),\n\t}\n}", "func NewParser(waf *engine.Waf) (*Parser, error) {\n\tif waf == nil {\n\t\treturn nil, errors.New(\"must use a valid waf instance\")\n\t}\n\tp := &Parser{\n\t\tWaf: waf,\n\t\tdefaultActions: []string{},\n\t\tDisabledDirectives: []string{},\n\t}\n\treturn p, nil\n}", "func NewPacketParser(source string, dst chan<- *Message) *PacketParser {\n\tpp := &PacketParser{\n\t\tasync: make(chan sendSentence, 200),\n\t\tsourceName: source,\n\t}\n\tgo pp.decodeSentences(dst)\n\treturn pp\n}", "func New(l *lexer.Lexer) *Parser {\n\tp := &Parser{\n\t\tLexer: l,\n\t\tacceptBlock: true,\n\t}\n\n\tp.fsm = fsm.NewFSM(\n\t\tstates.Normal,\n\t\tfsm.Events{\n\t\t\t{Name: events.ParseFuncCall, Src: []string{states.Normal}, Dst: states.ParsingFuncCall},\n\t\t\t{Name: events.ParseMethodParam, Src: []string{states.Normal, states.ParsingAssignment}, Dst: states.ParsingMethodParam},\n\t\t\t{Name: events.ParseAssignment, Src: []string{states.Normal, states.ParsingFuncCall}, Dst: states.ParsingAssignment},\n\t\t\t{Name: events.BackToNormal, Src: []string{states.ParsingFuncCall, states.ParsingMethodParam, states.ParsingAssignment}, Dst: states.Normal},\n\t\t},\n\t\tfsm.Callbacks{},\n\t)\n\n\tp.prefixParseFns = make(map[token.Type]prefixParseFn)\n\tp.registerPrefix(token.Ident, p.parseIdentifier)\n\tp.registerPrefix(token.Constant, p.parseConstant)\n\tp.registerPrefix(token.InstanceVariable, p.parseInstanceVariable)\n\tp.registerPrefix(token.Int, p.parseIntegerLiteral)\n\tp.registerPrefix(token.String, p.parseStringLiteral)\n\tp.registerPrefix(token.True, p.parseBooleanLiteral)\n\tp.registerPrefix(token.False, p.parseBooleanLiteral)\n\tp.registerPrefix(token.Null, p.parseNilExpression)\n\tp.registerPrefix(token.Minus, p.parsePrefixExpression)\n\tp.registerPrefix(token.Plus, p.parsePrefixExpression)\n\tp.registerPrefix(token.Asterisk, p.parsePrefixExpression)\n\tp.registerPrefix(token.Bang, p.parsePrefixExpression)\n\tp.registerPrefix(token.LParen, p.parseGroupedExpression)\n\tp.registerPrefix(token.If, p.parseIfExpression)\n\tp.registerPrefix(token.Case, p.parseCaseExpression)\n\tp.registerPrefix(token.Self, p.parseSelfExpression)\n\tp.registerPrefix(token.LBracket, p.parseArrayExpression)\n\tp.registerPrefix(token.LBrace, p.parseHashExpression)\n\tp.registerPrefix(token.Semicolon, p.parseSemicolon)\n\tp.registerPrefix(token.Yield, p.parseYieldExpression)\n\tp.registerPrefix(token.GetBlock, p.parseGetBlockExpression)\n\n\tp.infixParseFns = make(map[token.Type]infixParseFn)\n\tp.registerInfix(token.Plus, p.parseInfixExpression)\n\tp.registerInfix(token.PlusEq, p.parseAssignExpression)\n\tp.registerInfix(token.Minus, p.parseInfixExpression)\n\tp.registerInfix(token.MinusEq, p.parseAssignExpression)\n\tp.registerInfix(token.Modulo, p.parseInfixExpression)\n\tp.registerInfix(token.Slash, p.parseInfixExpression)\n\tp.registerInfix(token.Pow, p.parseInfixExpression)\n\tp.registerInfix(token.Eq, p.parseInfixExpression)\n\tp.registerInfix(token.NotEq, p.parseInfixExpression)\n\tp.registerInfix(token.LT, p.parseInfixExpression)\n\tp.registerInfix(token.LTE, p.parseInfixExpression)\n\tp.registerInfix(token.GT, p.parseInfixExpression)\n\tp.registerInfix(token.GTE, p.parseInfixExpression)\n\tp.registerInfix(token.COMP, p.parseInfixExpression)\n\tp.registerInfix(token.And, p.parseInfixExpression)\n\tp.registerInfix(token.Or, p.parseInfixExpression)\n\tp.registerInfix(token.OrEq, p.parseAssignExpression)\n\tp.registerInfix(token.Comma, p.parseMultiVariables)\n\tp.registerInfix(token.ResolutionOperator, p.parseInfixExpression)\n\tp.registerInfix(token.Assign, p.parseAssignExpression)\n\tp.registerInfix(token.Range, p.parseRangeExpression)\n\tp.registerInfix(token.Dot, p.parseCallExpressionWithReceiver)\n\tp.registerInfix(token.LParen, p.parseCallExpressionWithoutReceiver)\n\tp.registerInfix(token.LBracket, p.parseIndexExpression)\n\tp.registerInfix(token.Colon, p.parseArgumentPairExpression)\n\tp.registerInfix(token.Asterisk, p.parseInfixExpression)\n\n\treturn p\n}", "func New(data []byte) *Parser {\n\treturn &Parser{\n\t\tbook: data,\n\t}\n}", "func New(conf config.Config) Parser {\n\tmethods := map[string]bool{\n\t\thttp.MethodGet: true,\n\t\thttp.MethodHead: true,\n\t\thttp.MethodPost: true,\n\t\thttp.MethodPut: true,\n\t\thttp.MethodPatch: true,\n\t\thttp.MethodDelete: true,\n\t\thttp.MethodConnect: true,\n\t\thttp.MethodOptions: true,\n\t\thttp.MethodTrace: true,\n\t}\n\n\treturn Parser{\n\t\tconf: conf,\n\t\tmethods: methods,\n\t}\n}", "func newParser(input string) *parser {\n\tp := &parser{\n\t\tlex: lex(input),\n\t}\n\treturn p\n}", "func newParser(pcidbs []string) *parser {\n\n\tfor _, db := range pcidbs {\n\t\tfile, err := os.ReadFile(db)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\treturn newParserFromReader(bufio.NewReader(bytes.NewReader(file)))\n\n\t}\n\t// We're using go embed above to have the byte array\n\t// correctly initialized with the internal shipped db\n\t// if we cannot find an up to date in the filesystem\n\treturn newParserFromReader(bufio.NewReader(bytes.NewReader(defaultPCIdb)))\n}", "func NewParser(strg dataStore, clck commandClock) *Parser {\n\treturn &Parser{strg: strg, clck: clck}\n}", "func New(c *types.Config) types.TypeParser {\n\tp := &Parser{\n\t\tConfig: c,\n\t}\n\treturn p\n}", "func NewParser() *Parser {\n\treturn &Parser{\n\t\tLCh: make(chan *Lexeme),\n\t}\n}", "func newParser(br string) (*parser, []string, error) {\n\tloc, err := bugreportutils.TimeZone(br)\n\tif err != nil {\n\t\treturn nil, []string{}, err\n\t}\n\tpm, warnings := bugreportutils.ExtractPIDMappings(br)\n\t// Extract the year and month from the bugreport dumpstate line.\n\td, err := bugreportutils.DumpState(br)\n\tif err != nil {\n\t\treturn nil, warnings, fmt.Errorf(\"could not find dumpstate information in the bugreport: %v\", err)\n\t}\n\tbuf := new(bytes.Buffer)\n\treturn &parser{\n\t\treferenceYear: d.Year(),\n\t\treferenceMonth: d.Month(),\n\t\tloc: loc,\n\t\tbuf: buf,\n\t\tcsvState: csv.NewState(buf, true),\n\t\tpidMappings: pm,\n\t}, warnings, nil\n}", "func NewParser(description string, p Parser) Parser {\n\treturn p\n}", "func NewParser() *Parser {\n\treturn &Parser{}\n}", "func NewParser() *Parser {\n\treturn &Parser{}\n}", "func NewParser() *Parser {\n\treturn &Parser{}\n}", "func NewParser() *Parser {\n\treturn &Parser{}\n}", "func NewParser(filepath string) *Parser {\n\tnewParse := &Parser{filepath: filepath, CurrentCommandType: -1}\n\treturn newParse\n}", "func New(l *lexer.Lexer) *Parser {\n\n\t// Create the parser, and prime the pump\n\tp := &Parser{l: l, errors: []Error{}}\n\tp.nextToken()\n\tp.nextToken()\n\n\t// Register prefix-functions\n\tp.prefixParseFns = [tokentype.TokenType_Count]prefixParseFn{\n\t\ttokentype.BACKTICK: p.parseBacktickLiteral,\n\t\ttokentype.BANG: p.parsePrefixExpression,\n\t\ttokentype.DEFINE_FUNCTION: p.parseFunctionDefinition,\n\t\ttokentype.EOF: p.parsingBroken,\n\t\ttokentype.FALSE: p.parseBoolean,\n\t\ttokentype.FLOAT: p.parseFloatLiteral,\n\t\ttokentype.FOR: p.parseForLoopExpression,\n\t\ttokentype.FOREACH: p.parseForEach,\n\t\ttokentype.FUNCTION: p.parseFunctionLiteral,\n\t\ttokentype.IDENT: p.parseIdentifier,\n\t\ttokentype.IF: p.parseIfExpression,\n\t\ttokentype.ILLEGAL: p.parsingBroken,\n\t\ttokentype.INT: p.parseIntegerLiteral,\n\t\ttokentype.LBRACE: p.parseHashLiteral,\n\t\ttokentype.LBRACKET: p.parseArrayLiteral,\n\t\ttokentype.LPAREN: p.parseGroupedExpression,\n\t\ttokentype.MINUS: p.parsePrefixExpression,\n\t\ttokentype.REGEXP: p.parseRegexpLiteral,\n\t\ttokentype.STRING: p.parseStringLiteral,\n\t\ttokentype.SWITCH: p.parseSwitchStatement,\n\t\ttokentype.TRUE: p.parseBoolean,\n\t}\n\n\t// Register infix functions\n\tp.infixParseFns = [tokentype.TokenType_Count]infixParseFn{\n\t\ttokentype.AND: p.parseInfixExpression,\n\t\ttokentype.ASSIGN: p.parseAssignExpression,\n\t\ttokentype.ASTERISK: p.parseInfixExpression,\n\t\ttokentype.ASTERISK_EQUALS: p.parseAssignExpression,\n\t\ttokentype.CONTAINS: p.parseInfixExpression,\n\t\ttokentype.DOTDOT: p.parseInfixExpression,\n\t\ttokentype.EQ: p.parseInfixExpression,\n\t\ttokentype.GT: p.parseInfixExpression,\n\t\ttokentype.GT_EQUALS: p.parseInfixExpression,\n\t\ttokentype.LBRACKET: p.parseIndexExpression,\n\t\ttokentype.LPAREN: p.parseCallExpression,\n\t\ttokentype.LT: p.parseInfixExpression,\n\t\ttokentype.LT_EQUALS: p.parseInfixExpression,\n\t\ttokentype.MINUS: p.parseInfixExpression,\n\t\ttokentype.MINUS_EQUALS: p.parseAssignExpression,\n\t\ttokentype.MOD: p.parseInfixExpression,\n\t\ttokentype.NOT_CONTAINS: p.parseInfixExpression,\n\t\ttokentype.NOT_EQ: p.parseInfixExpression,\n\t\ttokentype.OR: p.parseInfixExpression,\n\t\ttokentype.PERIOD: p.parseMethodCallExpression,\n\t\ttokentype.PLUS: p.parseInfixExpression,\n\t\ttokentype.PLUS_EQUALS: p.parseAssignExpression,\n\t\ttokentype.POW: p.parseInfixExpression,\n\t\ttokentype.QUESTION: p.parseTernaryExpression,\n\t\ttokentype.SLASH: p.parseInfixExpression,\n\t\ttokentype.SLASH_EQUALS: p.parseAssignExpression,\n\t}\n\n\t// Register postfix functions.\n\tp.postfixParseFns = [tokentype.TokenType_Count]postfixParseFn{\n\t\ttokentype.MINUS_MINUS: p.parsePostfixExpression,\n\t\ttokentype.PLUS_PLUS: p.parsePostfixExpression,\n\t}\n\n\t// All done\n\treturn p\n}", "func NewPacketParser(canConfigs map[int][]*configs.CanConfigType) *PacketParser {\n\treturn &PacketParser{\n\t\tState: idle,\n\t\tPacketBuffer: make([]byte, 12),\n\t\tPreambleBuffer: make([]byte, 0),\n\t\tCANConfigs: canConfigs,\n\t}\n}", "func newConfigParser(conf *dlcConfig, options flags.Options) *flags.Parser {\n\tparser := flags.NewParser(conf, options)\n\treturn parser\n}", "func NewParser(dir string) *Parser {\n\treturn &Parser{\n\t\tdir: dir,\n\t}\n}", "func NewParser(rules []*rule.Rule, ignorer *ignore.Ignore) *Parser {\n\treturn &Parser{\n\t\tRules: rules,\n\t\tIgnorer: ignorer,\n\t\trchan: make(chan result.FileResults),\n\t}\n}", "func New(cmdCandidates []pakelib.CommandCandidate, cv pakelib.CommentValidator) *Parser {\n\treturn &Parser{\n\t\tcommandCandidates: cmdCandidates,\n\t\tcommentValidator: cv,\n\t}\n}", "func New() *Parser {\n\treturn &Parser{\n\t\thclParser: hclparse.NewParser(),\n\t\tfiles: make(map[string]bool),\n\t}\n}", "func NewParser() *Parser {\n\tp := &Parser{PartialMap: NewPartialMap()}\n\tp.Imports.Init()\n\treturn p\n}", "func New(r io.Reader) *Parser {\n\tp := &Parser{\n\t\ts: bufio.NewScanner(r),\n\t\thasMoreCommand: true,\n\t}\n\treturn p\n}", "func NewParser() parser.IngressAnnotation {\n\treturn waf{}\n}", "func NewParser() *Parser {\n\treturn &Parser{parser.New()}\n}", "func NewParser() *Parser {\n\treturn &Parser{\n\t\tCommentCharacter: \"#\",\n\t\tRepoSplitCharacter: \"=\",\n\t\tSafetyCharacter: \"~\",\n\t\tGroupCharacter: \"@\",\n\t\tStack: &OpStack{},\n\t}\n}", "func NewParser(handler *MetricHandler) *Parser {\n\treturn &Parser{\n\t\tmachine: NewMachine(handler),\n\t\thandler: handler,\n\t}\n}", "func New() *Parser {\n\treturn &Parser{\n\t\tdelimiter: \".\",\n\t}\n}", "func NewParser() *Parser {\n\tp := Parser{}\n\treturn &p\n}", "func NewParser() *Parser {\n\treturn NewParserWithPostProcessors(StandardPostProcessors...)\n}", "func New(target, filename string) *Parser {\n\treturn &Parser{\n\t\ttarget: target,\n\t\tfilename: filename,\n\t\tfields: make(map[string]*types.Field),\n\t\ttypeConv: make(map[string]string),\n\t}\n}", "func New(l *lexer.Lexer) *Parser {\n\tp := &Parser{l: l}\n\n\tp.nextToken()\n\tp.nextToken()\n\n\treturn p\n}", "func New(l *lexer.Lexer) *Parser {\n\tp := &Parser{\n\t\tl: l,\n\t\terrors: []string{},\n\t\tacceptBlock: true,\n\t}\n\n\t// Read two tokens, so curToken and peekToken are both set.\n\tp.nextToken()\n\tp.nextToken()\n\n\tp.prefixParseFns = make(map[token.Type]prefixParseFn)\n\tp.registerPrefix(token.Ident, p.parseIdentifier)\n\tp.registerPrefix(token.Constant, p.parseConstant)\n\tp.registerPrefix(token.InstanceVariable, p.parseInstanceVariable)\n\tp.registerPrefix(token.Int, p.parseIntegerLiteral)\n\tp.registerPrefix(token.String, p.parseStringLiteral)\n\tp.registerPrefix(token.True, p.parseBooleanLiteral)\n\tp.registerPrefix(token.False, p.parseBooleanLiteral)\n\tp.registerPrefix(token.Null, p.parseNilExpression)\n\tp.registerPrefix(token.Minus, p.parsePrefixExpression)\n\tp.registerPrefix(token.Bang, p.parsePrefixExpression)\n\tp.registerPrefix(token.LParen, p.parseGroupedExpression)\n\tp.registerPrefix(token.If, p.parseIfExpression)\n\tp.registerPrefix(token.Self, p.parseSelfExpression)\n\tp.registerPrefix(token.LBracket, p.parseArrayExpression)\n\tp.registerPrefix(token.LBrace, p.parseHashExpression)\n\tp.registerPrefix(token.Semicolon, p.parseSemicolon)\n\tp.registerPrefix(token.Yield, p.parseYieldExpression)\n\n\tp.infixParseFns = make(map[token.Type]infixParseFn)\n\tp.registerInfix(token.Plus, p.parseInfixExpression)\n\tp.registerInfix(token.Minus, p.parseInfixExpression)\n\tp.registerInfix(token.Slash, p.parseInfixExpression)\n\tp.registerInfix(token.Eq, p.parseInfixExpression)\n\tp.registerInfix(token.Asterisk, p.parseInfixExpression)\n\tp.registerInfix(token.Pow, p.parseInfixExpression)\n\tp.registerInfix(token.NotEq, p.parseInfixExpression)\n\tp.registerInfix(token.LT, p.parseInfixExpression)\n\tp.registerInfix(token.LTE, p.parseInfixExpression)\n\tp.registerInfix(token.GT, p.parseInfixExpression)\n\tp.registerInfix(token.GTE, p.parseInfixExpression)\n\tp.registerInfix(token.COMP, p.parseInfixExpression)\n\tp.registerInfix(token.Dot, p.parseCallExpression)\n\tp.registerInfix(token.LParen, p.parseCallExpression)\n\tp.registerInfix(token.LBracket, p.parseArrayIndexExpression)\n\tp.registerInfix(token.Incr, p.parsePostfixExpression)\n\tp.registerInfix(token.Decr, p.parsePostfixExpression)\n\tp.registerInfix(token.And, p.parseInfixExpression)\n\tp.registerInfix(token.Or, p.parseInfixExpression)\n\tp.registerInfix(token.ResolutionOperator, p.parseInfixExpression)\n\n\treturn p\n}", "func NewParser(tokenizer *Tokenizer) *Parser {\n\treturn &Parser{\n\t\ttokenizer: tokenizer,\n\t\tloopCount: 0,\n\t\tskipSemicolon: false,\n\t}\n}", "func NewParser(maxAge int, hashKey, blockKey []byte) Parser {\n\tif len(hashKey) == 0 {\n\t\thashKey = RandBytes(16)\n\t}\n\trv := &tokenParser{hashKey: hashKey, maxAge: maxAge}\n\n\tif len(blockKey) > 0 {\n\t\tif block, err := aes.NewCipher(blockKey); err == nil {\n\t\t\trv.block = block\n\t\t} else {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tn := len(hashKey)\n\tswitch {\n\tcase n < 32:\n\t\trv.hashFunc = sha1.New\n\t\trv.hashSize = sha1.Size\n\tcase n < 48:\n\t\trv.hashFunc = sha256.New\n\t\trv.hashSize = sha256.Size\n\tcase n < 64:\n\t\trv.hashFunc = sha512.New384\n\t\trv.hashSize = sha512.Size384\n\tdefault:\n\t\trv.hashFunc = sha512.New\n\t\trv.hashSize = sha512.Size\n\t}\n\n\treturn rv\n}", "func NewParser(config ParserConfig) *Parser {\n\treturn &Parser{config}\n}", "func NewParser(symbols interfaces.SymbolCollector) *Parser {\n\tparser := new(Parser)\n\tparser.symbols = symbols\n\treturn parser\n}", "func New() *Parser {\n\treturn &Parser{\n\t\tViper: viper.New(),\n\t}\n}", "func NewParser(r io.Reader) *Parser {\n\treturn &Parser{s: NewBufScanner(r)}\n}", "func Parse(b []byte) (Packet, error) {\n var p Packet\n opcode := binary.BigEndian.Uint16(b[:TFTP_HEADER_SIZE])\n\n switch opcode {\n case RRQ_CODE:\n fallthrough\n case WRQ_CODE:\n p = &Request{Opcode: opcode}\n case DATA_CODE:\n p = &Data{}\n case ACK_CODE:\n p = &Ack{}\n case ERR_CODE:\n p = &Err{}\n default:\n return nil, fmt.Errorf(\"invalid opcode %v found\", opcode)\n }\n err := p.Build(b)\n return p, err\n}", "func NewParser() *Parser {\n\treturn CustomParser(NewConfig())\n}", "func NewParser(input string) *Parser {\n\tlexer := newLexer(Tokens, input)\n\n\tparser := &Parser{\n\t\tlexer: lexer,\n\t\trule: &ParsedRule{},\n\t}\n\n\treturn parser\n}", "func newConfigParser(conf *config, options flags.Options) *flags.Parser {\n\tparser := flags.NewParser(conf, options)\n\treturn parser\n}", "func New(usage string) *Parser {\n\tp := &Parser{}\n\tp.long2options = make(map[string]*option)\n\tp.short2options = make(map[string]*option)\n\tp.OptPadding = 20\n\tp.ParseHelp = true\n\tp.Usage = usage\n\treturn p\n}", "func NewParser(pkg string) *Parser {\n\treturn &Parser{\n\t\tpkg: pkg,\n\t}\n}", "func newConfigParser(conf *litConfig, options flags.Options) *flags.Parser {\n\tparser := flags.NewParser(conf, options)\n\treturn parser\n}", "func New(l *lexer.Lexer) *Parser {\n\tp := &Parser{\n\t\tl: l,\n\t\terrors: []string{},\n\t}\n\n\t// Intialize the prefixParseFns map on Parser and register a parsing function\n\tp.prefixParseFns = make(map[token.TokenType]prefixParseFn)\n\tp.registerPrefix(token.IDENT, p.parseIdentifier)\n\tp.registerPrefix(token.INT, p.parseIntegerLiteral)\n\tp.registerPrefix(token.MINUS, p.parsePrefixExpression)\n\tp.registerPrefix(token.BANG, p.parsePrefixExpression)\n\tp.registerPrefix(token.LPAREN, p.parseGroupedExpression)\n\n\t// Intialize the infixParseFns map on Parser and register a parsing function\n\tp.infixParseFns = make(map[token.TokenType]infixParseFn)\n\tp.registerInfix(token.PLUS, p.parseInfixExpression)\n\tp.registerInfix(token.MINUS, p.parseInfixExpression)\n\tp.registerInfix(token.SLASH, p.parseInfixExpression)\n\tp.registerInfix(token.ASTERISK, p.parseInfixExpression)\n\tp.registerInfix(token.EQ, p.parseInfixExpression)\n\tp.registerInfix(token.NOT_EQ, p.parseInfixExpression)\n\tp.registerInfix(token.LT, p.parseInfixExpression)\n\tp.registerInfix(token.GT, p.parseInfixExpression)\n\n\t// Read two token so curToken and peekToken are both set\n\tp.nextToken()\n\tp.nextToken()\n\n\treturn p\n}", "func NewParser(table *lua.LTable) (Parser, error) {\n\tt := table.RawGet(lua.LString(\"type\")).String()\n\tswitch t {\n\tcase \"re2\":\n\t\tregexp, err := regexp.Compile(table.RawGet(lua.LString(\"expression\")).String())\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"invalid regular expression\")\n\t\t}\n\t\treturn &RE2{regexp: regexp}, nil\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"parser type not found\")\n\t}\n}", "func NewParser(source io.Reader) *Parser {\n\treturn &Parser{\n\t\tsource: source,\n\t\tscanner: bufio.NewScanner(source),\n\t}\n}", "func NewParser(lxr *lexer.Lexer) *Parser {\n\treturn &Parser{lexer: lxr}\n}", "func NewParser(r io.Reader, lang *Language) *Parser {\n\treturn &Parser{s: NewScanner(r), lang: lang}\n}", "func NewParser(r io.Reader) *Parser {\n\tparser := &Parser{\n\t\tscanner: NewScanner(r),\n\t\tnext: buf{tok: ILLEGAL, lit: \"\"},\n\t}\n\tparser.buffer()\n\treturn parser\n}", "func NewPowerBuilderParser(input antlr.TokenStream) *PowerBuilderParser {\n\tthis := new(PowerBuilderParser)\n\tdeserializer := antlr.NewATNDeserializer(nil)\n\tdeserializedATN := deserializer.DeserializeFromUInt16(parserATN)\n\tdecisionToDFA := make([]*antlr.DFA, len(deserializedATN.DecisionToState))\n\tfor index, ds := range deserializedATN.DecisionToState {\n\t\tdecisionToDFA[index] = antlr.NewDFA(ds, index)\n\t}\n\tthis.BaseParser = antlr.NewBaseParser(input)\n\n\tthis.Interpreter = antlr.NewParserATNSimulator(this, deserializedATN, decisionToDFA, antlr.NewPredictionContextCache())\n\tthis.RuleNames = ruleNames\n\tthis.LiteralNames = literalNames\n\tthis.SymbolicNames = symbolicNames\n\tthis.GrammarFileName = \"PowerBuilderParser.g4\"\n\n\treturn this\n}", "func NewParser(lexer *Lexer) *Parser {\n\tp := Parser{lexer: lexer}\n\tp.currentToken = p.lexer.getNextToken()\n\treturn &p\n}", "func New(l *lexer.Lexer) *Parser {\n\tp := &Parser{l: l}\n\n\tlog.Println(\"Making new parser\")\n\n\tp.prefixParseFns = make(map[token.Typ]prefixParseFn)\n\tp.prefixParseFns[token.IDENT] = p.parseIdent\n\tp.prefixParseFns[token.INT] = p.parseIntegerLiteral\n\tp.prefixParseFns[token.NOT] = p.parsePrefixExpr\n\tp.prefixParseFns[token.MINUS] = p.parsePrefixExpr\n\n\tp.infixParseFns = make(map[token.Typ]infixParseFn)\n\tp.infixParseFns[token.PLUS] = p.parseInfixExpr\n\tp.infixParseFns[token.MINUS] = p.parseInfixExpr\n\tp.infixParseFns[token.MULT] = p.parseInfixExpr\n\tp.infixParseFns[token.DIVIDE] = p.parseInfixExpr\n\tp.infixParseFns[token.GREATER] = p.parseInfixExpr\n\tp.infixParseFns[token.LESS] = p.parseInfixExpr\n\tp.infixParseFns[token.EQ] = p.parseInfixExpr\n\tp.infixParseFns[token.NEQ] = p.parseInfixExpr\n\n\tp.nextToken()\n\tp.nextToken()\n\n\treturn p\n}", "func NewParser(r io.Reader) *Parser {\n\tvar rr *bufio.Reader\n\tif br, ok := r.(*bufio.Reader); ok {\n\t\trr = br\n\t} else {\n\t\trr = bufio.NewReader(r)\n\t}\n\n\treturn &Parser{\n\t\tr: rr,\n\n\t\tComments: \"#;\",\n\n\t\tEscaper: '\\\\',\n\t\tEscapes: map[rune]string{\n\t\t\t'0': \"\\000\",\n\t\t\t'a': \"\\a\",\n\t\t\t'b': \"\\b\",\n\t\t\t't': \"\\t\",\n\t\t\t'r': \"\\r\",\n\t\t\t'n': \"\\n\",\n\t\t\t'\\n': \"\",\n\t\t},\n\t\tAllowUnknownEscapeSequence: true,\n\n\t\tSectionStart: '[',\n\t\tSectionEnd: ']',\n\n\t\tEquals: '=',\n\t}\n}", "func New(l *lexer.Lexer) *Parser {\n\tp := &Parser{\n\t\tl: l,\n\t\terrors: []string{},\n\t}\n\n\t// Read two tokens, so curToken and peekToken are both set\n\tp.nextToken()\n\tp.nextToken()\n\n\tp.prefixParseFns = make(map[token.Type]prefixParseFn)\n\n\tp.registerPrefix(token.IDENT, p.parseIdentifier)\n\tp.registerPrefix(token.TRUE, p.parseBoolean)\n\tp.registerPrefix(token.FALSE, p.parseBoolean)\n\tp.registerPrefix(token.INT, p.parseIntegerLiteral)\n\tp.registerPrefix(token.BANG, p.parsePrefixExpression)\n\tp.registerPrefix(token.MINUS, p.parsePrefixExpression)\n\tp.registerPrefix(token.LPAREN, p.parseGroupedExpression)\n\tp.registerPrefix(token.IF, p.parseIfExpression)\n\tp.registerPrefix(token.FUNCTION, p.parseFunctionLiteral)\n\n\tp.infixParseFns = make(map[token.Type]infixParseFn)\n\n\tp.registerInfix(token.PLUS, p.parseInfixExpression)\n\tp.registerInfix(token.MINUS, p.parseInfixExpression)\n\tp.registerInfix(token.SLASH, p.parseInfixExpression)\n\tp.registerInfix(token.ASTERISK, p.parseInfixExpression)\n\tp.registerInfix(token.EQ, p.parseInfixExpression)\n\tp.registerInfix(token.NEQ, p.parseInfixExpression)\n\tp.registerInfix(token.LT, p.parseInfixExpression)\n\tp.registerInfix(token.GT, p.parseInfixExpression)\n\tp.registerInfix(token.LPAREN, p.parseCallExpression)\n\n\treturn p\n}", "func NewParser(lexer *Lexer, config conf.Config) *Parser {\n\treturn &Parser{\n\t\tLexer: lexer,\n\t\terrHandlerFunc: config.ErrorHandlerFunc,\n\t\tbuilder: position.NewBuilder(),\n\t}\n}", "func NewParser(f io.Reader) *Parser {\n\tlex := lexer.New(f)\n\tp := &Parser{\n\t\tlex: lex,\n\t\terrors: make([]*ParserError, 0),\n\t}\n\tp.advanceTokens()\n\tp.advanceTokens()\n\treturn p\n}", "func NewParser(r io.Reader, logw io.Writer) (*Parser, <-chan Command, <-chan struct{}) {\n\tcommandch := make(chan Command, 0) // unbuffered\n\tstopch := make(chan struct{}, 1)\n\tparser := &Parser{\n\t\tcommandch: commandch,\n\t\tstopch: stopch,\n\t\treader: bufio.NewReader(r),\n\t\tlogger: log.New(logw, \"parser: \", log.LstdFlags),\n\t}\n\treturn parser, commandch, stopch\n}", "func New(l *lexer.Lexer) *Parser {\n\tp := &Parser{\n\t\tl: l,\n\t\terrors: []error{},\n\t}\n\tp.Next() // Roll forward once to set the peek token\n\tp.Next() // Roll forward twice to make the first peek token the current token\n\treturn p\n}", "func NewParser(tokens []lexer.Token) parser {\n\tp := parser{}\n\tp.tokens = tokens\n\tp.current = 0\n\n\treturn p\n}", "func NewParser(r io.Reader) *Parser {\n\treturn &Parser{s: NewScanner(r)}\n}", "func NewParser(r io.Reader) *Parser {\n\treturn &Parser{s: NewScanner(r)}\n}", "func NewParser(r io.Reader) *Parser {\n\treturn &Parser{s: NewScanner(r)}\n}", "func NewParser(r io.Reader) *Parser {\n\treturn &Parser{s: NewScanner(r)}\n}", "func NewParser(r io.Reader) *Parser {\n\treturn &Parser{s: NewScanner(r)}\n}", "func NewParser(r resolver.Resolver) parser.IngressAnnotation {\n\treturn weight{r}\n}", "func NewParser(l *Lexer) *Parser {\n\tp := &Parser{\n\t\tl: l,\n\t\terrors: []string{},\n\t}\n\n\tp.prefixParseFns = map[TokenType]prefixParseFn{}\n\tp.registerPrefix(IDENT, p.parseIdentifier)\n\tp.registerPrefix(NOT, p.parsePrefixExpression)\n\tp.registerPrefix(LPAREN, p.parseGroupedExpression)\n\tp.registerPrefix(SET, p.parseSetExpression)\n\n\tp.infixParseFns = make(map[TokenType]infixParseFn)\n\tp.registerInfix(EQ, p.parseInfixExpression)\n\tp.registerInfix(NotEQ, p.parseInfixExpression)\n\tp.registerInfix(LBRACKET, p.parseIndexExpression)\n\tp.registerInfix(DOT, p.parseIndexExpression)\n\tp.registerInfix(BETWEEN, p.parseBetweenExpression)\n\tp.registerInfix(LT, p.parseInfixExpression)\n\tp.registerInfix(GT, p.parseInfixExpression)\n\tp.registerInfix(LTE, p.parseInfixExpression)\n\tp.registerInfix(GTE, p.parseInfixExpression)\n\tp.registerInfix(AND, p.parseInfixExpression)\n\tp.registerInfix(OR, p.parseInfixExpression)\n\tp.registerInfix(LPAREN, p.parseCallExpression)\n\n\tp.registerInfix(PLUS, p.parseInfixExpression)\n\tp.registerInfix(MINUS, p.parseInfixExpression)\n\n\t// Read two tokens, so curToken and peekToken are both set\n\tp.nextToken()\n\tp.nextToken()\n\n\treturn p\n}", "func NewParser(tokens []Token) *Parser {\n\treturn &Parser{tokens: tokens}\n}", "func NewParser(builder builder.TestSuitesBuilder, stream bool) parser.TestOutputParser {\n\treturn &testOutputParser{\n\t\tbuilder: builder,\n\t\tstream: stream,\n\t}\n}", "func New(l *lexer.Lexer, context string) *Parser {\n\tp := &Parser{\n\t\tl: l,\n\t\tContext: context,\n\t\terrors: []string{},\n\t}\n\n\tp.prefixParseFns = make(map[token.Type]prefixParseFn)\n\tp.registerPrefix(token.Ident, p.parseIdentifier)\n\tp.registerPrefix(token.Int, p.parseIntegerLiteral)\n\tp.registerPrefix(token.String, p.parseStringLiteral)\n\tp.registerPrefix(token.Bang, p.parsePrefixExpression)\n\tp.registerPrefix(token.Minus, p.parsePrefixExpression)\n\tp.registerPrefix(token.True, p.parseBoolean)\n\tp.registerPrefix(token.False, p.parseBoolean)\n\tp.registerPrefix(token.Lparen, p.parseGroupedExpression)\n\tp.registerPrefix(token.If, p.parseIfExpression)\n\tp.registerPrefix(token.Function, p.parseFunctionLiteral)\n\tp.registerPrefix(token.Lbracket, p.parseArray)\n\n\tp.infixParseFns = make(map[token.Type]infixParseFn)\n\tp.registerInfix(token.Plus, p.parseInfixExpression)\n\tp.registerInfix(token.Minus, p.parseInfixExpression)\n\tp.registerInfix(token.Slash, p.parseInfixExpression)\n\tp.registerInfix(token.Astersik, p.parseInfixExpression)\n\tp.registerInfix(token.EQ, p.parseInfixExpression)\n\tp.registerInfix(token.NEQ, p.parseInfixExpression)\n\tp.registerInfix(token.LT, p.parseInfixExpression)\n\tp.registerInfix(token.GT, p.parseInfixExpression)\n\tp.registerInfix(token.LTE, p.parseInfixExpression)\n\tp.registerInfix(token.GTE, p.parseInfixExpression)\n\tp.registerInfix(token.Lparen, p.parseCallExpression)\n\tp.registerInfix(token.Dot, p.parseInfixCallExpression)\n\tp.registerInfix(token.Assign, p.parseAssignmentExpression)\n\n\tp.nextToken() // set currToken\n\tp.nextToken() // set peekToken\n\n\treturn p\n}", "func NewParser(r io.Reader, filename string) *Parser {\n return &Parser{ NewScanner(r, filename) }\n}", "func NewParser(r resolver.Resolver) parser.IngressAnnotation {\n\treturn su{r}\n}", "func NewParser(options ...Option) Parser {\n\tconfig := NewConfig()\n\tfor _, opt := range options {\n\t\topt.SetParserOption(config)\n\t}\n\n\tp := &parser{\n\t\toptions: map[OptionName]interface{}{},\n\t\tconfig: config,\n\t}\n\n\treturn p\n}", "func New(service string, environment string, prefix string) *Parser {\n\treturn &Parser{\n\t\ttagparsers: map[string]TagParser{},\n\t\tservice: service,\n\t\tenvironment: environment,\n\t\tprefix: prefix,\n\t}\n}", "func New(fp string) *Parser {\n\tfile, _ := os.Open(fp)\n\tbytes, _ := os.ReadFile(fp)\n\tfileObj := &obj.File{Path: fp, File: file}\n\tfileObj.Lines = strings.Split(string(bytes), \"\\n\")\n\tfor i, line := range fileObj.Lines {\n\t\tfileObj.Lines[i] = strings.TrimRightFunc(line, unicode.IsSpace)\n\t}\n\treturn &Parser{\n\t\tfuncTempVars: -1,\n\t\tLex: &lex.Lex{File: fileObj, Line: 1},\n\t}\n}", "func NewParser(fileName string, scanner *scan.Scanner, context value.Context) *Parser {\n\treturn &Parser{\n\t\tscanner: scanner,\n\t\tfileName: fileName,\n\t\tcontext: context.(*exec.Context),\n\t}\n}", "func NewParser(storage storage.IStorage) *Parser {\n\treturn &Parser{storage}\n}", "func New(l *lexer.Lexer) *Parser {\n\tp := &Parser{l: l}\n\tp.readNextToken()\n\tp.readNextToken() // To set the init value of curToken and the nextToken.\n\tp.ParseFnForPrefixToken = make(map[string]prefixTokenParseFn) // Need to assign a non-nil map, otherwise cannot assign to a nil nap.\n\tp.registerParseFuncForPrefixToken(token.IDENTIFIER, p.parseIdentifier)\n\tp.registerParseFuncForPrefixToken(token.INT, p.parseIntegerLiteral)\n\tp.registerParseFuncForPrefixToken(token.STRING, p.parseStringLiteral)\n\tp.registerParseFuncForPrefixToken(token.BANG, p.parsePrefixExpression)\n\tp.registerParseFuncForPrefixToken(token.MINUS, p.parsePrefixExpression)\n\tp.registerParseFuncForPrefixToken(token.TRUE, p.parseBooleanLiteral)\n\tp.registerParseFuncForPrefixToken(token.FALSE, p.parseBooleanLiteral)\n\tp.registerParseFuncForPrefixToken(token.LPAREN, p.parseGroupedExpression)\n\tp.registerParseFuncForPrefixToken(token.IF, p.parseIfExpression)\n\tp.registerParseFuncForPrefixToken(token.FUNCTION, p.parseFunctionLiteralExpression)\n\tp.ParseFnForInfixToken = make(map[string]infixTokenParseFn)\n\tp.registerParseFuncForInfixToken(token.PLUS, p.parseInfixExpression)\n\tp.registerParseFuncForInfixToken(token.MINUS, p.parseInfixExpression)\n\tp.registerParseFuncForInfixToken(token.ASTERISK, p.parseInfixExpression)\n\tp.registerParseFuncForInfixToken(token.LT, p.parseInfixExpression)\n\tp.registerParseFuncForInfixToken(token.GT, p.parseInfixExpression)\n\tp.registerParseFuncForInfixToken(token.EQ, p.parseInfixExpression)\n\tp.registerParseFuncForInfixToken(token.NOTEQ, p.parseInfixExpression)\n\tp.registerParseFuncForInfixToken(token.LPAREN, p.parseCallExpression)\n\tp.registerParseFuncForInfixToken(token.SLASH, p.parseInfixExpression)\n\treturn p\n}", "func NewParser(fileName string, scanner *scan.Scanner, context value.Context) *Parser {\n\treturn &Parser{\n\t\tscanner: scanner,\n\t\tfileName: fileName,\n\t\tcontext: context,\n\t}\n}", "func NewParser(r io.Reader) textparse.Parser {\n\t// TODO(dipack95): Maybe use bufio.Reader.Readline instead?\n\t// https://stackoverflow.com/questions/21124327/how-to-read-a-text-file-line-by-line-in-go-when-some-lines-are-long-enough-to-ca\n\treturn &Parser{s: bufio.NewScanner(r)}\n}", "func NewParser() NumberParser {\n\treturn &libNumberParser{}\n}", "func New(client *scm.Client) core.HookParser {\n\treturn &parser{client}\n}", "func New(l *lexer.Lexer) *Parser {\n\tp := &Parser{\n\t\tl: l,\n\t\terrors: []string{},\n\t}\n\n\tp.prefixParseFns = make(map[token.Type]prefixParseFn)\n\tp.registerPrefix(token.IDENT, p.parseIdentifier)\n\tp.registerPrefix(token.INT, p.parseIntegerLiteral)\n\tp.registerPrefix(token.NOT, p.parsePrefixExpression)\n\tp.registerPrefix(token.LPAREN, p.parseGroupedExpression)\n\n\tp.infixParseFns = make(map[token.Type]infixParseFn)\n\tp.registerInfix(token.PLUS, p.parseInfixExpression)\n\tp.registerInfix(token.MINUS, p.parseInfixExpression)\n\tp.registerInfix(token.DIVIDE, p.parseInfixExpression)\n\tp.registerInfix(token.MULTIPLY, p.parseInfixExpression)\n\tp.registerInfix(token.ASSIGN, p.parseInfixExpression)\n\tp.registerInfix(token.EQ, p.parseInfixExpression)\n\tp.registerInfix(token.LT, p.parseInfixExpression)\n\tp.registerInfix(token.AND, p.parseInfixExpression)\n\tp.registerInfix(token.OR, p.parseInfixExpression)\n\tp.registerInfix(token.LPAREN, p.parseCallExpression)\n\n\tp.nextToken()\n\tp.nextToken()\n\treturn p\n}", "func New(r io.Reader) *Parser {\n\treturn &Parser{s: NewScanner(r)}\n}" ]
[ "0.715827", "0.71475464", "0.71475464", "0.71475464", "0.7114476", "0.69998455", "0.6625179", "0.6551293", "0.6518934", "0.6502652", "0.64814895", "0.6480666", "0.64672434", "0.6461906", "0.6448895", "0.6404644", "0.63888294", "0.63648206", "0.63550526", "0.63176465", "0.63164395", "0.629809", "0.62822425", "0.6279465", "0.6279465", "0.6279465", "0.6279465", "0.623294", "0.6218597", "0.6201398", "0.6185745", "0.618085", "0.617458", "0.615219", "0.61503327", "0.61419004", "0.6131435", "0.6130321", "0.61221194", "0.6105765", "0.6090185", "0.6075859", "0.60690665", "0.60687965", "0.60664415", "0.6054261", "0.6023547", "0.60198814", "0.6001749", "0.5995791", "0.59932286", "0.597138", "0.59550625", "0.59540725", "0.5950364", "0.5946893", "0.59406227", "0.59303176", "0.5919109", "0.5903397", "0.5889036", "0.587578", "0.5875651", "0.5863255", "0.5851733", "0.58340454", "0.58329046", "0.58168244", "0.58126074", "0.58121943", "0.5799858", "0.57965726", "0.5791943", "0.5777759", "0.5777448", "0.5752816", "0.5750898", "0.5750898", "0.5750898", "0.5750898", "0.5750898", "0.57505715", "0.5738898", "0.57256013", "0.57145745", "0.5713075", "0.56981915", "0.569221", "0.5688653", "0.5685193", "0.5672656", "0.5663729", "0.5661879", "0.5656344", "0.5652274", "0.5646139", "0.56277806", "0.5623285", "0.5623056", "0.56214505" ]
0.7244323
0
/ ==================== body ====================
func getMoneyAmount(n int) int { }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Body(attrs []htmlgo.Attribute, children ...HTML) HTML {\n\treturn &htmlgo.Tree{Tag: \"body\", Attributes: attrs, Children: children}\n}", "func (d *Document) Body() Body { return d.body }", "func (p *Post) RenderBody() (buf []byte, err error) {\n if buf, err = p.Body(); err != nil {\n return\n }\n\n buf = blackfriday.MarkdownCommon(buf)\n\n return\n}", "func (f LetFunction) Body() interface{} {\n\treturn f.body\n}", "func (c *Card) Body(_ context.Context, _ int) (string, error) {\n\tbody, err := Asset(\"done.html\")\n\treturn string(body), err\n}", "func Body(props *BodyProps, children ...Element) *BodyElem {\n\trProps := &_BodyProps{\n\t\tBasicHTMLElement: newBasicHTMLElement(),\n\t}\n\n\tif props != nil {\n\t\tprops.assign(rProps)\n\t}\n\n\treturn &BodyElem{\n\t\tElement: createElement(\"body\", rProps, children...),\n\t}\n}", "func (s *Server) body(handler http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tbody, err := ioutil.ReadAll(io.LimitReader(r.Body, int64(s.bodyLimit)))\n\t\tif err != nil {\n\t\t\tlog.Error().Err(err).Msg(\"body read fail\")\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tr.Body.Close()\n\t\tr.Body = ioutil.NopCloser(bytes.NewBuffer(body))\n\n\t\thandler.ServeHTTP(w, r)\n\t})\n}", "func body(resp *http.Response) ([]byte, error) {\n\tvar buf bytes.Buffer\n\t_, err := buf.ReadFrom(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (b *Block) Body() *Body { return &Body{b.transactions, b.signs} }", "func ServeBody(w http.ResponseWriter, body string) {\n\tw.Write([]byte(\"<html><style>a { display: block }</style><body>\" + body + \"</html></body>\"))\n}", "func (*XMLDocument) Body() (body window.HTMLElement) {\n\tmacro.Rewrite(\"$_.body\")\n\treturn body\n}", "func pagemain(w http.ResponseWriter, r *http.Request){\n w.Write([]byte( `\n <!doctype html>\n <title>Ciao</title>\n <h1>Come stai</h1>\n <img src=\"https://www.4gamehz.com/wp-content/uploads/2019/10/league-of-legends-4.jpg\">\n `))\n }", "func readBody(win *acme.Win) ([]byte, error) {\n\tvar body []byte\n\tbuf := make([]byte, 8000)\n\tfor {\n\t\tn, err := win.Read(\"body\", buf)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbody = append(body, buf[0:n]...)\n\t}\n\treturn body, nil\n}", "func streamcode_bodyscripts(qw422016 *qt422016.Writer, lang string) {\n//line template/code.qtpl:16\n\tqw422016.N().S(`\n `)\n//line template/code.qtpl:17\n\tqw422016.N().S(`<script src='`)\n//line template/code.qtpl:18\n\tqw422016.E().S(prefix)\n//line template/code.qtpl:18\n\tqw422016.N().S(`/prism.js'></script>`)\n//line template/code.qtpl:19\n\tif lang != \"\" && lang != \"none\" {\n//line template/code.qtpl:19\n\t\tqw422016.N().S(`<script src='`)\n//line template/code.qtpl:20\n\t\tqw422016.E().S(prefix)\n//line template/code.qtpl:20\n\t\tqw422016.N().S(`/components/prism-`)\n//line template/code.qtpl:20\n\t\tqw422016.E().S(lang)\n//line template/code.qtpl:20\n\t\tqw422016.N().S(`.js'></script>`)\n//line template/code.qtpl:21\n\t}\n//line template/code.qtpl:22\n\tqw422016.N().S(`\n`)\n//line template/code.qtpl:23\n}", "func (dao *blockDAO) Body(h hash.Hash256) (*block.Body, error) {\n\treturn dao.body(h)\n}", "func (p Page) Body() []byte {\n\treturn p.body\n}", "func Body_(children ...HTML) HTML {\n return Body(nil, children...)\n}", "func (f *Function) Body() string {\n\treturn extractSrc(f.file.src, f.fn.Body)\n}", "func scheduleBody(e *executor, j *jobInfo) func() {\n\treturn func() {\n\t\tlog.Println(j.c.Name, \"woke up\")\n\t\tinfo := &runInfo{\n\t\t\te: e,\n\t\t\tj: j,\n\t\t}\n\t\te.run(info)\n\t\tlog.Println(j.c.Name, \"finished in\", time.Now().Sub(info.start))\n\t}\n}", "func (s *BasecluListener) EnterBody(ctx *BodyContext) {}", "func buildBody(level, title string) map[string]interface{} {\n\ttimestamp := time.Now().Unix()\n\thostname, _ := os.Hostname()\n\n\treturn map[string]interface{}{\n\t\t\"access_token\": Token,\n\t\t\"data\": map[string]interface{}{\n\t\t\t\"environment\": Environment,\n\t\t\t\"title\": title,\n\t\t\t\"level\": level,\n\t\t\t\"timestamp\": timestamp,\n\t\t\t\"platform\": runtime.GOOS,\n\t\t\t\"language\": \"go\",\n\t\t\t\"server\": map[string]interface{}{\n\t\t\t\t\"host\": hostname,\n\t\t\t},\n\t\t\t\"notifier\": map[string]interface{}{\n\t\t\t\t\"name\": NAME,\n\t\t\t\t\"version\": VERSION,\n\t\t\t},\n\t\t},\n\t}\n}", "func (b *BitcoinClient) createBody(rpcBody *RPCBody) (*bytes.Buffer, error) {\n\tbodyJSON, err := json.Marshal(rpcBody)\n\tif err != nil {\n\t\tlog.Println(ErrCreatingBody)\n\t\treturn nil, ErrCreatingBody\n\t}\n\n\treturn bytes.NewBuffer(bodyJSON), nil\n}", "func (e *TestMilter) Body(m *milter.Modifier) (milter.Response, error) {\n\t// prepare buffer\n\t_ = bytes.NewReader(e.message.Bytes())\n\tfmt.Println(\"size of body: \", e.message.Len())\n\tm.AddHeader(\"name\", \"value\")\n\tm.AddRecipient(\"[email protected]\")\n\tm.ChangeFrom(\"[email protected]\")\n\tm.ChangeHeader(0, \"Subject\", \"New Subject\")\n\tm.DeleteRecipient(\"[email protected]\")\n\tm.InsertHeader(0, \"new\", \"value\")\n\tm.ReplaceBody([]byte(\"new body\"))\n\n\t// accept message by default\n\treturn milter.RespAccept, nil\n}", "func (ge *GollumEvent) Body() string {\n\treturn \"\"\n}", "func getBody(rw http.ResponseWriter, r *http.Request, requestBody *structs.Request) (error, string) {\n\tbuf, _ := ioutil.ReadAll(r.Body)\n\trdr1 := ioutil.NopCloser(bytes.NewBuffer(buf))\n\trdr2 := ioutil.NopCloser(bytes.NewBuffer(buf))\n\n\t//Save the state back into the body for later use (Especially useful for getting the AOD/QOD because if the AOD has not been set a random AOD is set and the function called again)\n\tr.Body = rdr2\n\tif err := json.NewDecoder(rdr1).Decode(&requestBody); err != nil {\n\t\tlog.Printf(\"Got error when decoding: %s\", err)\n\t\terr = errors.New(\"request body is not structured correctly. Please refer to the /docs page for information on how to structure the request body\")\n\t\trw.WriteHeader(http.StatusBadRequest)\n\t\tjson.NewEncoder(rw).Encode(structs.ErrorResponse{Message: err.Error()})\n\t\treturn err, \"\"\n\t}\n\treturn nil, string(buf)\n}", "func (t *TOMLParser) Body() []byte {\n\treturn t.body.Bytes()\n}", "func RenderBody(body []byte, vars map[string]string) ([]byte, error) {\n\ttmpl, err := template.New(\"\").Funcs(sprig.TxtFuncMap()).Parse(string(body))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar out bytes.Buffer\n\tif err := tmpl.Execute(&out, map[string]interface{}{\n\t\t\"Vars\": vars,\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\treturn out.Bytes(), nil\n}", "func (_this *Report) Body() *ReportBody {\n\tvar ret *ReportBody\n\tvalue := _this.Value_JS.Get(\"body\")\n\tif value.Type() != js.TypeNull && value.Type() != js.TypeUndefined {\n\t\tret = ReportBodyFromJS(value)\n\t}\n\treturn ret\n}", "func main() {\n\tlog.Println(\"Hello TPL!\")\n\n\t// Use the main.html template or die\n\ttpl, err := gtpl.Open(\"templates/main.html\")\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\t// Assign a global variable\n\ttpl.AssignGlobal(\"a_global_var\", \"Global Varaible Here\")\n\n\t// Parse out the \"top_body\" block.\n\ttpl.Parse(\"top_body\")\n\n\t// Assign a value to {foo}\n\ttpl.Assign(\"foo\", \"Something about foobar!\")\n\t// Parse \"some_row\" which is nested in \"content_body\"\n\ttpl.Parse(\"content_body.some_row\")\n\n\t// Assign a new value to {foo}\n\ttpl.Assign(\"foo\", \"Putting something else here...\")\n\t// Parse \"some_row\" which is nested in \"content_body\"\n\ttpl.Parse(\"content_body.some_row\")\n\n\t// Parse content_body\n\ttpl.Parse(\"content_body\")\n\n\t// Spit out the parsed page content\n\tlog.Println(\"Page Content is:\")\n\tfmt.Print(tpl.Out(), \"\\n\")\n}", "func (s *Nap) Body(body io.Reader) *Nap {\n\tif body == nil {\n\t\treturn s\n\t}\n\treturn s.BodyProvider(bodyProvider{body: body})\n}", "func (s *BasePlSqlParserListener) EnterBody(ctx *BodyContext) {}", "func (self *Graphics) Body() interface{}{\n return self.Object.Get(\"body\")\n}", "func (p *parser) parseBlockBody(term token.Type) tree.Block {\n\tblock := p.parseBlock()\n\tif p.tok != term {\n\t\tp.error(p.off, term.String()+\" expected\")\n\t}\n\treturn block\n}", "func NewBody() *Body {\n\tb := new(Body)\n\tb.Element = NewElement(\"body\")\n\treturn b\n}", "func (req MinRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error {\n\targs := minArgs{Space: req.space, Index: req.index, Opts: req.opts}\n\treq.impl = req.impl.Args(args)\n\treturn req.impl.Body(res, enc)\n}", "func Body(resp *http.Response) (string, error) {\n\tdefer resp.Body.Close()\n\tb, e := ioutil.ReadAll(resp.Body)\n\treturn string(b), e\n}", "func (i *BodyInterceptor) Body() []byte {\n\treturn i.BodyBytes\n}", "func Body(t Term) Callable {\n\treturn t.(*Compound).Arguments()[1].(Callable)\n}", "func (p *Post) Body() (buf []byte, err error) {\n if buf, err = ioutil.ReadFile(p.Path); err != nil {\n return\n }\n\n buf = buf[p.BodyIdx:]\n\n return\n}", "func main() {\n\t// flag.Parse()\n\t// args := flag.Args()\n\t// if len(args) < 1 {\n\t// \tfmt.Println(\"Please specify start page\") // if a starting page wasn't provided as an argument\n\t// \tos.Exit(1) // show a message and exit.\n\t// }\n\t// getBody(args[0])\n\tgetBody(\"https://ng.indeed.com/jobs-in-Lagos\")\n}", "func parsingbody(data, namecontrol string) (body string) {\n\tlistbody := strings.Split(data, \"var data request.\")\n\tgetvalue := strings.Split(listbody[1], \"\\n\")\n\tnamestructbody := getvalue[0]\n\tdir := config.GetDir()\n\tparsingstruct(dir+\"/vendor/request/\"+namecontrol+\".go\", namestructbody)\n\treturn\n}", "func createBody(f *os.File, releaseTag, branch, docURL, exampleURL, releaseTars string) error {\n\tvar title string\n\tif *preview {\n\t\ttitle = \"Branch \"\n\t}\n\n\tif releaseTag == \"HEAD\" || releaseTag == branchHead {\n\t\ttitle += branch\n\t} else {\n\t\ttitle += releaseTag\n\t}\n\n\tif *preview {\n\t\tf.WriteString(fmt.Sprintf(\"**Release Note Preview - generated on %s**\\n\", time.Now().Format(\"Mon Jan 2 15:04:05 MST 2006\")))\n\t}\n\n\tf.WriteString(fmt.Sprintf(\"\\n# %s\\n\\n\", title))\n\tf.WriteString(fmt.Sprintf(\"[Documentation](%s) & [Examples](%s)\\n\\n\", docURL, exampleURL))\n\n\tif releaseTars != \"\" {\n\t\tf.WriteString(fmt.Sprintf(\"## Downloads for %s\\n\\n\", title))\n\t\ttables := []struct {\n\t\t\theading string\n\t\t\tfilename []string\n\t\t}{\n\t\t\t{\"\", []string{releaseTars + \"/kubernetes.tar.gz\", releaseTars + \"/kubernetes-src.tar.gz\"}},\n\t\t\t{\"Client Binaries\", []string{releaseTars + \"/kubernetes-client*.tar.gz\"}},\n\t\t\t{\"Server Binaries\", []string{releaseTars + \"/kubernetes-server*.tar.gz\"}},\n\t\t\t{\"Node Binaries\", []string{releaseTars + \"/kubernetes-node*.tar.gz\"}},\n\t\t}\n\n\t\tfor _, table := range tables {\n\t\t\terr := createDownloadsTable(f, releaseTag, table.heading, table.filename...)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to create downloads table: %v\", err)\n\t\t\t}\n\t\t}\n\t\tf.WriteString(\"\\n\")\n\t}\n\treturn nil\n}", "func RenderAsBody(comp Component) {\n\tdoc := js.Global.Get(\"document\")\n\tbody := doc.Call(\"createElement\", \"body\")\n\tRender(comp, body)\n\tif doc.Get(\"readyState\").String() == \"loading\" {\n\t\tdoc.Call(\"addEventListener\", \"DOMContentLoaded\", func() { // avoid duplicate body\n\t\t\tdoc.Set(\"body\", body)\n\t\t})\n\t\treturn\n\t}\n\tdoc.Set(\"body\", body)\n}", "func (r *Request) Body(body io.Reader) *Request {\n\tpanic(\"TODO\")\n\t//if rc, ok := r.(io.ReadCloser); ok {\n\t//r.body = r\n\treturn r\n}", "func getBody(resp *http.Response) ([]byte, error) {\n\tbody, err := ioutil.ReadAll(resp.Body)\n\treturn body, err\n}", "func (s *BasevhdlListener) EnterPackage_body(ctx *Package_bodyContext) {}", "func (b *Block) Body() *Body {\n\treturn &Body{append(tx.Transactions(nil), b.txs...)}\n}", "func (c *Control) Body(data interface{}) {\n\tvar content []byte\n\n\tif str, ok := data.(string); ok {\n\t\tcontent = []byte(str)\n\t\tif c.ContentType != \"\" {\n\t\t\tc.Writer.Header().Add(\"Content-type\", c.ContentType)\n\t\t} else {\n\t\t\tc.Writer.Header().Add(\"Content-type\", MIMETEXT)\n\t\t}\n\t} else {\n\t\tif c.useMetaData {\n\t\t\tc.header.Data = data\n\t\t\tif !c.timer.IsZero() {\n\t\t\t\ttook := time.Now()\n\t\t\t\tc.header.Duration = took.Sub(c.timer)\n\t\t\t\tc.header.Took = took.Sub(c.timer).String()\n\t\t\t}\n\t\t\tif c.header.Params == nil && len(c.params) > 0 {\n\t\t\t\tc.header.Params = c.params\n\t\t\t}\n\t\t\tif c.errorHeader.Code != 0 || c.errorHeader.Message != \"\" || len(c.errorHeader.Errors) > 0 {\n\t\t\t\tc.header.Error = c.errorHeader\n\t\t\t}\n\t\t\tdata = c.header\n\t\t}\n\t\tvar err error\n\t\tif c.compactJSON {\n\t\t\tcontent, err = json.Marshal(data)\n\t\t} else {\n\t\t\tcontent, err = json.MarshalIndent(data, \"\", \" \")\n\t\t}\n\t\tif err != nil {\n\t\t\tc.Writer.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tc.Writer.Header().Add(\"Content-type\", MIMEJSON)\n\t}\n\tif strings.Contains(c.Request.Header.Get(\"Accept-Encoding\"), \"gzip\") {\n\t\tc.Writer.Header().Add(\"Content-Encoding\", \"gzip\")\n\t\tif c.code > 0 {\n\t\t\tc.Writer.WriteHeader(c.code)\n\t\t}\n\t\tgz := gzip.NewWriter(c.Writer)\n\t\tgz.Write(content)\n\t\tgz.Close()\n\t} else {\n\t\tif c.code > 0 {\n\t\t\tc.Writer.WriteHeader(c.code)\n\t\t}\n\t\tc.Writer.Write(content)\n\t}\n}", "func (e *TestMilter) Body(m *Modifier) (Response, error) {\n\t// prepare buffer\n\t_ = bytes.NewReader(e.message.Bytes())\n\n\tm.AddHeader(\"name\", \"value\")\n\tm.AddRecipient(\"[email protected]\")\n\tm.ChangeFrom(\"[email protected]\")\n\tm.ChangeHeader(0, \"Subject\", \"New Subject\")\n\tm.DeleteRecipient(\"[email protected]\")\n\tm.InsertHeader(0, \"new\", \"value\")\n\tm.ReplaceBody([]byte(\"new body\"))\n\n\t// accept message by default\n\treturn RespAccept, nil\n}", "func (l Lambda) Body() Expression {\n\treturn l.body\n}", "func getBody(id string, actionType models.ActionType) ([]byte, error) {\n\treturn json.Marshal(models.CallbackAlert{ActionType: actionType, Id: id})\n}", "func (es *EmailDeliverer) getBody(alertCtx AlertContext) (string, error) {\n\tout := &bytes.Buffer{}\n\ttemplate := getTemplate(alertCtx)\n\terr := es.render.Render(out, alertCtx, \"content\", template)\n\tif err != nil {\n\t\treturn \"\", errors.WithStack(err)\n\t}\n\treturn out.String(), nil\n}", "func main() {\n\tdomTarget := dom.GetWindow().Document().GetElementByID(\"app\")\n\n\tr.Render(container.Container(), domTarget)\n}", "func home(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(`<html>\n\t<body>\n\t\tThanks for playing with <a href=\"https://www.honeycomb.io\">Honeycomb.io</a>\n\t</body>\n</html>\n`))\n}", "func getBody(resp *http.Response) ([]byte, error) {\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\treturn body, err\n}", "func mainHandler(w http.ResponseWriter, r *http.Request) {\n\n table := InitDB()\n if (table == nil) {\n fmt.Println(\"ERROR: SQL is NIL\")\n return\n }\n\n requests := libEvents(table, \"Guildhall Public\", \"request\")\n hosts := libEvents(table, \"Guildhall Public\", \"host\")\n\n strContents := readHtml(\"../index.html\", requests, hosts)\n fmt.Println(strContents)\n fmt.Fprint(w, strContents)\n}", "func (self *Client) body(res *http.Response) (io.ReadCloser, error) {\n\tvar body io.ReadCloser\n\tvar err error\n\n\tif res.Header.Get(\"Content-Encoding\") == \"gzip\" {\n\t\tif body, err = gzip.NewReader(res.Body); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tbody = res.Body\n\t}\n\n\treturn body, nil\n}", "func (s *BasecluListener) EnterRoutine_body(ctx *Routine_bodyContext) {}", "func (bc *BodyCollection) ModBody(id int, name, class string, mods []string) grpcsimcb.ModBodyResult {\n\tbc.modBodyCh <- struct {\n\t\tid int\n\t\tname, class string\n\t\tmods []string\n\t}{id: id, name: name, class: class, mods: mods}\n\treturn <-bc.modBodyResultCh\n}", "func (req *MinRequest) Body(res tarantool.SchemaResolver, enc *encoder) error {\n\targs := minArgs{Space: req.space, Index: req.index, Opts: req.opts}\n\treq.impl = req.impl.Args(args)\n\treturn req.impl.Body(res, enc)\n}", "func (c *client) PRTitleBody() (string, string, error) {\n\treturn \"Update index.md\", \"\", nil\n}", "func Tbody(attrs []htmlgo.Attribute, children ...HTML) HTML {\n\treturn &htmlgo.Tree{Tag: \"tbody\", Attributes: attrs, Children: children}\n}", "func request(w http.ResponseWriter, r *http.Request) {\n\n\tt, _ := template.ParseFiles(\"head.html\")\n\tt.Execute(w, nil)\n\tu, _ := template.ParseFiles(\"footer.html\")\n\tu.Execute(w, nil)\n}", "func (h echoHTTPService) EchoBody(ctx context.Context, in *pb.SimpleMessage) (*pb.SimpleMessage, error) {\n\tt := time.Now()\n\n\tresp := new(pb.SimpleMessage)\n\tresp.Id = \"Echo \" + in.Id + \".\"\n\n\telapsed := time.Duration(time.Since(t))\n\ttoolbox.StatisticsMap.AddStatistics(\"POST\", \"/v1/echo_body\", \"&echoPBController.EchoBody\", time.Duration(elapsed.Nanoseconds()))\n\n\treturn resp, nil\n}", "func readBody(msg []byte, state *readState) error {\n\tline := msg[0 : len(msg)-2]\n\tvar err error\n\tif line[0] == '$' {\n\t\t// bulk reply\n\t\tstate.bulkLen, err = strconv.ParseInt(string(line[1:]), 10, 64)\n\t\tif err != nil {\n\t\t\treturn errors.New(\"protocol error: \" + string(msg))\n\t\t}\n\t\tif state.bulkLen <= 0 { // null bulk in multi bulks\n\t\t\tstate.args = append(state.args, []byte{})\n\t\t\tstate.bulkLen = 0\n\t\t}\n\t} else {\n\t\tstate.args = append(state.args, line)\n\t}\n\treturn nil\n}", "func (p *BasePage) WriteBody(qq422016 qtio422016.Writer) {\n\t//line base.qtpl:32\n\tqw422016 := qt422016.AcquireWriter(qq422016)\n\t//line base.qtpl:32\n\tp.StreamBody(qw422016)\n\t//line base.qtpl:32\n\tqt422016.ReleaseWriter(qw422016)\n//line base.qtpl:32\n}", "func (self *PhysicsP2) GetBody(object interface{}) *P2Body{\n return &P2Body{self.Object.Call(\"getBody\", object)}\n}", "func createBodies() {\n\tspace = chipmunk.NewSpace()\n\tspace.Gravity = vect.Vect{0, -900}\n\n\tstaticBody := chipmunk.NewBodyStatic()\n\tstaticLines = []*chipmunk.Shape{\n\t\tchipmunk.NewSegment(vect.Vect{111.0, 280.0}, vect.Vect{407.0, 246.0}, 0),\n\t\tchipmunk.NewSegment(vect.Vect{407.0, 246.0}, vect.Vect{407.0, 343.0}, 0),\n\t}\n\tfor _, segment := range staticLines {\n\t\tsegment.SetElasticity(0.6)\n\t\tstaticBody.AddShape(segment)\n\t}\n\tspace.AddBody(staticBody)\n}", "func Tbody_(children ...HTML) HTML {\n return Tbody(nil, children...)\n}", "func BodyAll(req *http.Request) ([]byte, error) {\n\tdata, err := ioutil.ReadAll(req.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer req.Body.Close()\n\treturn data, nil\n}", "func main() {\n\terr := tpl.ExecuteTemplate(os.Stdout, \"tpl.gohtml\", nil)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}", "func (s *BasePlSqlParserListener) EnterFunction_body(ctx *Function_bodyContext) {}", "func readBody(t *testing.T, r io.ReadCloser) *bytes.Buffer {\n\tdefer r.Close()\n\n\tvar b []byte\n\tbuf := bytes.NewBuffer(b)\n\t_, err := buf.ReadFrom(r)\n\tcheck(t, err)\n\n\treturn buf\n}", "func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n p, _ := loadPage(\"/src/github.com/mrgirlyman/watcher/frontman/build/index.html\")\n\n fmt.Fprintf(w, string(p.Body))\n // log.Fatal(err)\n\n // if (err != nil) {\n // fmt.Fprintf(w, string(p.Body))\n // } else {\n // fmt.Fprintf(w, \"Error reading index.html\")\n // }\n}", "func (llp *LogLineParsed) UpdateBody() {\n\tllp.Body = fmt.Sprintf(\"%s %s %s %s : %s\",\n\t\tllp.Msg.UserID, llp.Msg.Nick,\n\t\tfunc(em EmoteReplaceListFromBack) string { // Emote String\n\t\t\tif len(em) == 0 {\n\t\t\t\treturn \"\"\n\t\t\t}\n\n\t\t\treturn fmt.Sprintf(\"{%s}\", em)\n\t\t}(llp.Msg.Emotes),\n\t\tfunc(bits int) string { // Bit String\n\t\t\tif bits <= 0 {\n\t\t\t\treturn \"\"\n\t\t\t}\n\n\t\t\treturn fmt.Sprintf(\"[%d]\", bits)\n\t\t}(llp.Msg.Bits), llp.Msg.Content)\n\n}", "func (s *BasecluListener) ExitBody(ctx *BodyContext) {}", "func index(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\terr := tpl.ExecuteTemplate(w, \"index.html\", nil)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\tlog.Fatalln(err)\n\t}\n\tfmt.Println(\"HERE INDEX\")\n}", "func (r *GoFuncBodyRenderer[T]) Body(f func(r *GoRenderer[T])) {\n\tvar buf strings.Builder\n\n\tbuf.WriteString(\"func \")\n\tif r.r.rcvr != nil {\n\t\tbuf.WriteByte('(')\n\t\tbuf.WriteString(r.r.r.S(*r.r.rcvr))\n\t\tbuf.WriteString(\") \")\n\t}\n\tbuf.WriteString(r.r.r.S(r.r.name))\n\tbuf.WriteByte('(')\n\tfor i, p := range r.r.params {\n\t\tif i > 0 {\n\t\t\tbuf.WriteString(\", \")\n\t\t}\n\t\tbuf.WriteString(r.r.r.S(p[0]))\n\t\tbuf.WriteByte(' ')\n\t\tbuf.WriteString(r.r.r.S(p[1]))\n\t}\n\tbuf.WriteString(\") \")\n\n\tif len(r.r.results) > 0 {\n\t\tbuf.WriteByte('(')\n\t\tfor i, p := range r.r.results {\n\t\t\tif i > 0 {\n\t\t\t\tbuf.WriteString(\", \")\n\t\t\t}\n\t\t\tbuf.WriteString(r.r.r.S(p[0]))\n\t\t\tbuf.WriteByte(' ')\n\t\t\tbuf.WriteString(r.r.r.S(p[1]))\n\t\t}\n\t\tbuf.WriteString(\") \")\n\t}\n\n\tbuf.WriteByte('{')\n\n\tr.r.r.R(buf.String())\n\tf(r.r.r)\n\tr.r.r.R(\"}\")\n}", "func (c *Client) parseBody(body interface{}) (io.Reader, error) {\n\tvar bodyData io.Reader\n\tvar err error\n\tvar bdata []byte\n\tif body == nil {\n\t\treturn nil, nil\n\t}\n\tswitch body.(type) {\n\tcase string:\n\t\tbodyStr := body.(string)\n\t\tif len(strings.TrimSpace(bodyStr)) == 0 || bodyStr == \"\" {\n\t\t\tbodyData = nil\n\t\t} else {\n\t\t\tbodyData = strings.NewReader(bodyStr)\n\t\t}\n\t\t//json字符串\n\t\tif gjson.Valid(bodyStr) {\n\t\t\tif c.prettyQsl {\n\t\t\t\tbodyStr = string(pretty.Pretty([]byte(bodyStr)))\n\t\t\t}\n\t\t}\n\t\tlogs.Debug(\"the body data:\\n%s\", bodyStr)\n\tdefault:\n\t\tif c.prettyQsl {\n\t\t\tbdata, err = json.MarshalIndent(body, \"\", \"\\t\")\n\t\t} else {\n\t\t\tbdata, err = json.Marshal(body)\n\t\t}\n\t\tif err != nil {\n\t\t\tlogs.Error(\"the body is decoded error:%s\", err.Error())\n\t\t\treturn nil, err\n\t\t}\n\t\tbodyData = bytes.NewReader(bdata)\n\t\tlogs.Debug(\"the body data:\\n%s\", string(bdata))\n\t}\n\treturn bodyData, nil\n}", "func mainPage(w http.ResponseWriter, r *http.Request) {\n\n\t// Pick an image if there are images to pick from (otherwise 404)\n\tfile := \"assets/404.jpg\"\n\tif len(images) > 0 {\n\t\tfile = pickRandom()\n\t} else {\n\t\t// TODO use a different image to say there are no images\n\t}\n\n\t// Read the code in page.html\n\thtml, err := ioutil.ReadFile(\"page.html\")\n\terrFail(err) // it's bad if you can't read the GUI's code\n\n\t// Replace variables in the HTML with current values\n\thtml = bytes.Replace(html, []byte(\"RANDOM\"), []byte(file), 1)\n\thtml = bytes.Replace(html, []byte(\"FILENAME\"), []byte(file), 1)\n\thtml = bytes.Replace(html, []byte(\"FOLDER\"), []byte(folder), 1)\n\n\t// Serve the finished page up\n\tw.Write(html)\n}", "func (r *Request) Body(body io.Reader) *Request {\n\tr.BodyBuffer, r.Error = ioutil.ReadAll(body)\n\treturn r\n}", "func (self *TileSprite) Body() interface{}{\n return self.Object.Get(\"body\")\n}", "func main() {\n\tp1 := &gowiki.Page{Title: \"TestPage\", Body: []byte(\"This is a sample Page.\")}\n\tp1.Save()\n\tp2, _ := gowiki.LoadPage(\"TestPage\")\n\tfmt.Println(string(p2.Body))\n}", "func (llp *LogLineParsed) HTMLBody(vp viewerProvider) string {\n\tif llp.Msg == nil {\n\t\treturn llp.Body\n\t}\n\n\treturn llp.Msg.Emotes.Replace(llp.Msg.Content)\n}", "func (c *Ctx) Body() []byte {\n\treturn c.Request.Body()\n}", "func (t Text) Body() string {\n\treturn t.body\n}", "func mainpage(resp http.ResponseWriter, req *http.Request) {\n\trenderPage(resp, \"../ui/main.html\")\t\n}", "func (b *Block) Body() *Body {\n\treturn b.body.content.(*Body)\n}", "func (b *Block) Body() *Body {\n\treturn b.body.content.(*Body)\n}", "func (app *application) home(res http.ResponseWriter, req *http.Request) {\n\tsnippets, err := app.snippets.Lasted()\n\tif err != nil {\n\t\tapp.serverError(res, err)\n\t}\n\n\ttemlsData := &Templates{\n\t\tSnippets: snippets,\n\t}\n\n\tapp.render(res, req, \"home.page.html\", temlsData)\n}", "func getMain(c *gin.Context) {\n\n\tc.HTML(http.StatusOK, \"index.html\", gin.H{\n\t\t\"module\": biModule,\n\t})\n}", "func body(s string) string {\t\n\tn := len(s)\n\tif n <= 3 {\n\t\treturn s\n\t}\n\treturn body(s[:n-3]) + \",\" + s[n-3:]\n}", "func home(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"text/html\") // sets page as text/html\n\tfmt.Fprint(w, \"<h1>This is my home page</h1>\")\n}", "func rootPage(w http.ResponseWriter, r *http.Request) {\n\thttpHTML(w, \"hello, world\")\n}", "func closeBody(resp *http.Response) {\n\terr := resp.Body.Close()\n\tif err != nil {\n\t\tutil.Logger.Printf(\"error closing response body - Called by %s: %s\\n\", util.CallFuncName(), err)\n\t}\n}", "func homePage(w http.ResponseWriter, r *http.Request, _ httprouter.Params){\n\tfmt.Fprintf(w, \"<h1>Welcome to the HomePage!<h1>\")\n\tlines, err := File2lines(config_readmepath)\n\tif err != nil {\n\t\tfmt.Println(\"Problem with Readme\")\n\t} else {\n\t\tfor _, line := range lines{\n\t\t\tfmt.Fprintf(w, \"<div style=\\\"font-size: 14px\\\"><p>\"+line+\"<p></div>\")\n\t\t}\n\t\tfmt.Println(\"Endpoint Hit: homePage\")\n\t}\n\t//requestChannel <- \"Home\"\n}", "func (ds *DrawServer) canvas(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\tt, err := template.ParseFiles(\"templates/main.html\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdata := struct {\n\t\tPort string\n\t}{\n\t\tPort: ds.port,\n\t}\n\tt.Execute(w, data)\n}", "func page(content string) string {\n\treturn \"<html><body>\\n\" + content + \"\\n</body></html>\"\n}", "func Html_home_page(w http.ResponseWriter, r *http.Request) {\n\t\n\t//context := &TemplateContext{Name: \"Foobar\", Addr: \"localhost:9999\"}\n\tfmt.Println(\"HOMe_handler()\")\n\n page := &Page{Title: \"Welcome\", Foo: \"Bar\", SiteInfo: GSiteInfo}\n if err := HomeTemplates.Execute(w, page); err != nil {\n http.Error(w, err.Error(), http.StatusInternalServerError)\n }\n\n}", "func (r *Response) Body(b []byte) *Response {\n\tr.body = b\n\treturn r\n}", "func (current OffsetPageBase) GetBody() interface{} {\n\treturn current.Body\n}" ]
[ "0.6661668", "0.6278422", "0.61816967", "0.61491895", "0.60555077", "0.60518575", "0.5979324", "0.59473485", "0.59407425", "0.59278893", "0.58994603", "0.58750373", "0.5864826", "0.58636975", "0.5846771", "0.58353", "0.58179003", "0.5798684", "0.5797721", "0.5795872", "0.5751987", "0.5667699", "0.56438625", "0.56411463", "0.56397754", "0.5628165", "0.5591171", "0.5556442", "0.555192", "0.5540178", "0.55314195", "0.5530768", "0.54916215", "0.5474545", "0.5467856", "0.54579705", "0.54534847", "0.54509234", "0.54494834", "0.5448827", "0.5442527", "0.5406959", "0.5403437", "0.5383044", "0.5381202", "0.5380396", "0.53756976", "0.53725463", "0.5369225", "0.5365953", "0.5363147", "0.5357112", "0.5342803", "0.53425986", "0.5334222", "0.533337", "0.533135", "0.5326421", "0.5317926", "0.5316752", "0.53022975", "0.52914125", "0.52909726", "0.52810335", "0.52715504", "0.5243257", "0.52403754", "0.5231081", "0.5229908", "0.5225488", "0.5220406", "0.5218671", "0.5216173", "0.5215898", "0.5211871", "0.52081054", "0.52048737", "0.51978266", "0.5188752", "0.51884156", "0.5185783", "0.5183958", "0.51813585", "0.5173826", "0.5168278", "0.51573616", "0.51542544", "0.5149256", "0.5149256", "0.51486105", "0.5139372", "0.51379836", "0.51375383", "0.5135338", "0.5124337", "0.5123925", "0.5121997", "0.5119069", "0.5108653", "0.51084065", "0.51080436" ]
0.0
-1
EntryCost calculates the cost in Entry Credits of adding an Entry to a Chain on the Factom protocol. The cost is the size of the Entry in Kilobytes excluding the Entry Header with any remainder being charged as a whole Kilobyte.
func EntryCost(e *Entry) (int8, error) { p, err := e.MarshalBinary() if err != nil { return 0, err } // caulculate the length exluding the header size 35 for Milestone 1 l := len(p) - 35 if l > 10240 { return 10, fmt.Errorf("Entry cannot be larger than 10KB") } // n is the capacity of the entry payment in KB n := int8(l / 1024) if r := l % 1024; r > 0 { n++ } // The Entry Cost should never be less than one if n < 1 { n = 1 } return n, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p *Resolver) GetEntryCacheSize() float64 {\n\treturn float64(p.cacheSize.Load())\n}", "func Cost(ctx context.Context, rpcURL string, contract common.Address, bytes, hrs int64) (rate *big.Int, cost *big.Int, err error) {\n\trate, err = Rate(ctx, rpcURL, contract)\n\tif err != nil {\n\t\treturn\n\t}\n\tbh := new(big.Int).Mul(big.NewInt(bytes), big.NewInt(hrs))\n\tcost = bh.Mul(bh, rate)\n\treturn\n}", "func (cr *Core) Cost(req CostRequest) (res CostResponse, err error) {\n\turlPath := \"cost\"\n\theaders := map[string]string{\n\t\t\"key\": cr.Client.APIKey,\n\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t}\n\terr = cr.CallPro(fasthttp.MethodPost, urlPath, headers, bytes.NewBufferString(StructToMap(&req).Encode()), &res)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func (b *CompactableBuffer) EntrySize() int {\n\treturn int(b.entrySize)\n}", "func (p Planner) AddEntry(planIdentifier string, user users.User, startAtUnix, duration int64) (PlanEntry, error) {\n\t// Get the plan based on identifier\n\tplan, err := p.data.GetPlan(planIdentifier)\n\tif err != nil {\n\t\treturn PlanEntry{}, fmt.Errorf(\"no plan: %w\", err)\n\t}\n\t// Check that the duration is longer than the plan's minimum availability\n\tif plan.MinimumAvailabilitySeconds > uint(duration) {\n\t\treturn PlanEntry{}, dataerror.ErrBasic(fmt.Sprintf(\"Entry duration cannot be shorter than the plan's (%d)\", plan.MinimumAvailabilitySeconds))\n\t}\n\n\tcreatedEntry, err := p.data.AddEntry(&plan, user, startAtUnix, duration)\n\tif err != nil {\n\t\treturn PlanEntry{}, fmt.Errorf(\"failed saving entry: %w\", err)\n\t}\n\n\t// Now just convert createdEntry to PlanEntry\n\tfinalEntry := PlanEntry{}\n\tfinalEntry.FillFromDataType(createdEntry)\n\n\treturn finalEntry, nil\n}", "func (c *directClient) PutEntry(ctx context.Context, _ cipher.SecKey, entry *disc.Entry) error {\n\tc.mx.Lock()\n\tdefer c.mx.Unlock()\n\tc.entries[entry.Static] = entry\n\treturn nil\n}", "func (instance *cache) AddEntry(content Cacheable) (_ *Entry, xerr fail.Error) {\n\tif instance == nil {\n\t\treturn nil, fail.InvalidInstanceError()\n\t}\n\tif content == nil {\n\t\treturn nil, fail.InvalidParameterCannotBeNilError(\"content\")\n\t}\n\n\tinstance.lock.Lock()\n\tdefer instance.lock.Unlock()\n\n\tid := content.GetID()\n\tif xerr := instance.unsafeReserveEntry(id); xerr != nil {\n\t\treturn nil, xerr\n\t}\n\tdefer func() {\n\t\tif xerr != nil {\n\t\t\tif derr := instance.unsafeFreeEntry(id); derr != nil {\n\t\t\t\t_ = xerr.AddConsequence(fail.Wrap(derr, \"cleaning up on failure, failed to free cache entry '%s'\", id))\n\t\t\t}\n\t\t}\n\t}()\n\n\tcacheEntry, xerr := instance.unsafeCommitEntry(id, content)\n\tif xerr != nil {\n\t\treturn nil, xerr\n\t}\n\n\treturn cacheEntry, nil\n}", "func (t *SimpleTable) AddEntry(addr Address, nextHop Node) {\n\tt.Lock()\n\tdefer t.Unlock()\n\tt.entries = append(t.entries, NewTableEntry(addr, nextHop))\n}", "func (d Download) TotalCost() time.Duration {\n\treturn time.Now().Sub(d.startedAt)\n}", "func (c *Client) FilterEntryAdd(tenant, filter, entry, etherType, ipProto, srcPortFrom, srcPortTo, dstPortFrom, dstPortTo string) error {\n\n\tme := \"FilterEntryAdd\"\n\n\trn := rnFilterEntry(entry)\n\tdn := dnFilterEntry(tenant, filter, entry)\n\n\tapi := \"/api/node/mo/uni/\" + dn + \".json\"\n\n\turl := c.getURL(api)\n\n\tj := fmt.Sprintf(`{\"vzEntry\":{\"attributes\":{\"dn\":\"uni/%s\",\"name\":\"%s\",\"etherT\":\"%s\",\"status\":\"created,modified\",\"prot\":\"%s\",\"sFromPort\":\"%s\",\"sToPort\":\"%s\",\"dFromPort\":\"%s\",\"dToPort\":\"%s\",\"rn\":\"%s\"}}}`,\n\t\tdn, entry, etherType, ipProto, srcPortFrom, srcPortTo, dstPortFrom, dstPortTo, rn)\n\n\tc.debugf(\"%s: url=%s json=%s\", me, url, j)\n\n\tbody, errPost := c.post(url, contentTypeJSON, bytes.NewBufferString(j))\n\tif errPost != nil {\n\t\treturn fmt.Errorf(\"%s: %v\", me, errPost)\n\t}\n\n\tc.debugf(\"%s: reply: %s\", me, string(body))\n\n\treturn parseJSONError(body)\n}", "func (pb *PutBlock) Cost() (*big.Int, error) {\n\tintrinsicGas, err := pb.IntrinsicGas()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get intrinsic gas for the start-sub chain action\")\n\t}\n\tfee := big.NewInt(0).Mul(pb.GasPrice(), big.NewInt(0).SetUint64(intrinsicGas))\n\treturn fee, nil\n}", "func (vind *UTF8cihash) Cost() int {\n\treturn 1\n}", "func Cost(m map[string]*list.Element, capacity int) int {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tif len(m) >= capacity {\n\t\treturn 2\n\t} else {\n\t\treturn 0\n\t}\n}", "func NewEntryUseCase(er repository.EntryRepository) usecase.EntryUseCase {\n\treturn &entryUsecase{entryRepo: er}\n}", "func (instance *cache) CommitEntry(key string, content Cacheable) (ce *Entry, xerr fail.Error) {\n\tif instance.isNull() {\n\t\treturn nil, fail.InvalidInstanceError()\n\t}\n\tif key = strings.TrimSpace(key); key == \"\" {\n\t\treturn nil, fail.InvalidParameterCannotBeEmptyStringError(\"key\")\n\t}\n\n\tinstance.lock.Lock()\n\tdefer instance.lock.Unlock()\n\n\treturn instance.unsafeCommitEntry(key, content)\n}", "func (wlt *Wallet) AddEntry(entry Entry) error {\n\t// dup check\n\tfor _, e := range wlt.Entries {\n\t\tif e.Address == entry.Address {\n\t\t\treturn errors.New(\"duplicate address entry\")\n\t\t}\n\t}\n\n\twlt.Entries = append(wlt.Entries, entry)\n\treturn nil\n}", "func (o GoogleCloudRetailV2alphaPriceInfoOutput) Cost() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaPriceInfo) *float64 { return v.Cost }).(pulumi.Float64PtrOutput)\n}", "func (rs *Restake) Cost() (*big.Int, error) {\n\tintrinsicGas, err := rs.IntrinsicGas()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get intrinsic gas for the stake creates\")\n\t}\n\trestakeFee := big.NewInt(0).Mul(rs.GasPrice(), big.NewInt(0).SetUint64(intrinsicGas))\n\treturn restakeFee, nil\n}", "func (c *ETHController) RentCost(domain string) (*big.Int, error) {\n\tname, err := UnqualifiedName(domain, c.domain)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid name %s\", domain)\n\t}\n\treturn c.Contract.RentPrice(nil, name, big.NewInt(1))\n}", "func (e *clfEncoder) EncodeEntry(entry zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) {\n\tfinal := e.clone()\n\n\tbuf := pool.Get()\n\tif entry.Message != \"\" {\n\t\tbuf.AppendString(entry.Message + \"\\n\")\n\t}\n\tif len(fields) == 0 {\n\t\treturn buf, nil\n\t}\n\n\tfor i := range fields {\n\t\tfields[i].AddTo(final)\n\t}\n\n\tbuf.AppendString(final.data[0])\n\tbuf.AppendByte(' ')\n\tbuf.AppendString(final.data[1])\n\tbuf.AppendByte(' ')\n\tbuf.AppendString(final.data[2])\n\tbuf.AppendByte(' ')\n\tbuf.AppendString(final.data[3])\n\tbuf.AppendByte(' ')\n\tbuf.AppendString(final.data[4])\n\tbuf.AppendByte(' ')\n\tbuf.AppendString(final.data[5])\n\tbuf.AppendString(\" \\\"\")\n\tbuf.AppendString(final.data[6])\n\tbuf.AppendByte(' ')\n\tbuf.AppendString(final.data[7])\n\tbuf.AppendByte(' ')\n\tbuf.AppendString(final.data[8])\n\tbuf.AppendString(\"\\\" \")\n\tbuf.AppendString(final.data[9])\n\tbuf.AppendByte(' ')\n\tbuf.AppendString(final.data[10])\n\tbuf.AppendByte('\\n')\n\treturn buf, nil\n}", "func updateTTEntry(entry *TTEntryT, eval EvalCp, bestMove dragon.Move, depthToGo int, evalType TTEvalT) {\n\tdepthToGo8 := uint8(depthToGo)\n\tpEntry := &entry.parityHits[depthToGoParity(depthToGo)]\n\n\tif evalIsBetter(pEntry, eval, depthToGo8, evalType) {\n\t\tpEntry.eval = eval\n\t\tpEntry.bestMove = bestMove\n\t\tpEntry.depthToGo = depthToGo8\n\t\tpEntry.evalType = evalType\n\t}\n}", "func Entry2CFDBEntry(e *Entry) *CFDBEntry {\n\tmac := (*C.struct_ether_addr)(unsafe.Pointer(&e.MacAddr[0]))\n\n\tce := &CFDBEntry{\n\t\tmac: *mac,\n\t}\n\n\tif ip := e.RemoteIP.To4(); ip != nil {\n\t\tce.ver = C.IPVERSION\n\t\tce.len = C.IP4_ADDR_LEN\n\t\tcopy(ce.remote_ip.ip[:], ip[:])\n\t} else {\n\t\tce.ver = C.IP6_VERSION\n\t\tce.len = C.IP6_ADDR_LEN\n\t\tcopy(ce.remote_ip.ip[:], e.RemoteIP[:])\n\t}\n\n\treturn ce\n}", "func (b *TaskExecBuilder) Entry(fn TaskFn) *TaskExecBuilder {\n\tb.Executor.Stages = append([]Stage{{Name: EntryStage, Fn: fn}}, b.Executor.Stages...)\n\treturn b\n}", "func (keyDB *KeyDB) AddHashChainEntry(\n\tdomain string,\n\tposition uint64,\n\tentry string,\n) error {\n\tdmn := identity.MapDomain(domain)\n\t_, err := keyDB.addHashChainEntryQuery.Exec(dmn, position, entry)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (cs cacheSize) add(bytes, entries int32) cacheSize {\n\treturn newCacheSize(cs.bytes()+bytes, cs.entries()+entries)\n}", "func (o GoogleCloudRetailV2alphaPriceInfoPtrOutput) Cost() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v *GoogleCloudRetailV2alphaPriceInfo) *float64 {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Cost\n\t}).(pulumi.Float64PtrOutput)\n}", "func (f *File) calculateEntryHash() string {\n\thash := 0\n\tfor _, batch := range f.Batches {\n\t\thash = hash + batch.GetControl().EntryHash\n\t}\n\treturn f.numericField(hash, 10)\n}", "func (p *program) addCost(cost types.Currency) error {\n\tif !p.staticBudget.Withdraw(cost) {\n\t\treturn modules.ErrMDMInsufficientBudget\n\t}\n\tp.executionCost = p.executionCost.Add(cost)\n\treturn nil\n}", "func (s SE) Cost(exp, act mat.Matrix) mat.Matrix {\n\tdiff := mat.Sub(act, exp)\n\tdiff.Pow(2)\n\treturn diff\n}", "func (j *Journal) AddEntry(entry entry.Entry) {\n\tj.Entries = append(j.Entries, entry)\n\tj.NumEntries++\n\n\treturn\n}", "func (ds *DepositToStake) Cost() (*big.Int, error) {\n\tintrinsicGas, err := ds.IntrinsicGas()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get intrinsic gas for the stake creates\")\n\t}\n\tdepositToStakeFee := big.NewInt(0).Mul(ds.GasPrice(), big.NewInt(0).SetUint64(intrinsicGas))\n\treturn big.NewInt(0).Add(ds.Amount(), depositToStakeFee), nil\n}", "func (o *AddOn) ResourceCost() float64 {\n\tif o != nil && o.bitmap_&32768 != 0 {\n\t\treturn o.resourceCost\n\t}\n\treturn 0.0\n}", "func (b *CompactableBuffer) ReadEntry(address *EntryAddress) (*Entry, error) {\n\taddress.LockForRead()\n\tdefer address.UnlockRead()\n\treturn b.ReadEntryWithoutLocking(address)\n}", "func (protocol *CacheStorageProtocol) DeleteEntry(\n\tparams *storage.DeleteEntryParams,\n) <-chan *storage.DeleteEntryResult {\n\tresultChan := make(chan *storage.DeleteEntryResult)\n\tcommand := NewCommand(protocol.Socket, \"CacheStorage.deleteEntry\", params)\n\tresult := &storage.DeleteEntryResult{}\n\n\tgo func() {\n\t\tresponse := <-protocol.Socket.SendCommand(command)\n\t\tif nil != response.Error && 0 != response.Error.Code {\n\t\t\tresult.Err = response.Error\n\t\t}\n\t\tresultChan <- result\n\t\tclose(resultChan)\n\t}()\n\n\treturn resultChan\n}", "func (v TestValues) Cost() (cost, failureRefund, collateral, instructionRefund types.Currency) {\n\t// Calculate the init cost.\n\tcost = modules.MDMInitCost(v.staticPT, uint64(*v.programDataLength), uint64(*v.numInstructions))\n\n\t// Add the cost of the added instructions\n\tcost = cost.Add(v.executionCost)\n\n\treturn cost, v.failureRefund, v.collateral, v.earlyRefund\n}", "func (t *dataType) Cost(cost int) *dataType {\n\tt.cost = &cost\n\treturn t\n}", "func (o GoogleCloudRetailV2alphaPriceInfoResponseOutput) Cost() pulumi.Float64Output {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaPriceInfoResponse) float64 { return v.Cost }).(pulumi.Float64Output)\n}", "func (d *Deployer) AddEntry(name, value string) (*r.ChangeResourceRecordSetsResponse, error) {\n\tif !strings.HasPrefix(name, \"_dnslink.\") {\n\t\treturn nil, errors.New(\"invalid dnslink name\")\n\t}\n\tformattedValue := fmt.Sprintf(\"\\\"%s\\\"\", value)\n\treturn d.client.Zone(d.zoneID).Add(\"TXT\", name, formattedValue)\n}", "func (r Row) Add(e Entry) Row {\n\tif e.Size.Size() > r.W*r.H-r.C {\n\t\treturn r\n\t}\n\n\t// Interate over the part of the grid where the entry could be added\n\tfor j := 0; j < r.H-e.Size.H+1; j++ {\n\t\tfor i := 0; i < r.W-e.Size.W+1; i++ {\n\t\t\t// Iterate over the Entry\n\t\t\tif r.Coverage.empty(e.Size.W, e.Size.H, i, j) {\n\t\t\t\tr.Entries = append(r.Entries, e.Pos(i, j))\n\t\t\t\tr.C += e.Size.Size()\n\t\t\t\tr.Coverage.fill(e.Size.W, e.Size.H, i, j)\n\t\t\t\treturn r\n\t\t\t}\n\t\t}\n\t}\n\n\treturn r\n}", "func (c *StakingPriceRecord) CloneEntryData() *StakingPriceRecord {\n\tn := NewStakingPriceRecord()\n\tn.SPRChainID = c.SPRChainID\n\tn.Dbht = c.Dbht\n\tn.Version = c.Version\n\tn.CoinbaseAddress = c.CoinbaseAddress\n\tn.CoinbasePEGAddress = c.CoinbasePEGAddress\n\n\tn.Assets = make(StakingPriceRecordAssetList)\n\tfor k, v := range c.Assets {\n\t\tn.Assets[k] = v\n\t}\n\treturn n\n}", "func (api *Cmtt) CommentEntry(entryID int, text string, replyTo int, attachments map[string]string) (*Comment, error) {\n\tbody := map[string]string{\n\t\t\"text\": text,\n\t\t\"reply_to\": strconv.Itoa(replyTo),\n\t}\n\tif attachments != nil {\n\t\tfor k, v := range attachments {\n\t\t\tbody[k] = v\n\t\t}\n\t}\n\tres, err := api.execute(\"entry/{id}/comments\", map[string]string{\n\t\t\"id\": strconv.Itoa(entryID),\n\t}, nil, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := &Comment{}\n\terr = castStruct(res, result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, err\n}", "func (p *pvc) Cost() float64 {\n\tif p == nil || p.Volume == nil {\n\t\treturn 0.0\n\t}\n\n\tgib := p.Bytes / 1024 / 1024 / 1024\n\thrs := p.minutes() / 60.0\n\n\treturn p.Volume.CostPerGiBHour * gib * hrs\n}", "func (adaType *AdaSuperType) AddSubEntry(name string, from uint16, to uint16) {\n\tvar code [2]byte\n\tcopy(code[:], name)\n\tentry := subSuperEntries{Name: code, From: from, To: to}\n\tadaType.Entries = append(adaType.Entries, entry)\n\tadaType.calcLength()\n}", "func (t *RicTable) Add(c *RicEntry) {\n\tt.Mutex.Lock()\n\tdefer t.Mutex.Unlock()\n\n\tt.Entries[c.Rt] = c\n}", "func (r *Report) TotalCost() float64 {\n\ttotal := 0.0\n\tfor i := range r.Items {\n\t\ttotal += r.Items[i].Cost\n\t}\n\treturn total\n}", "func (znp *Znp) UtilSrcMatchAddEntry(addrMode AddrMode, address string, panId uint16) (rsp *StatusResponse, err error) {\n\treq := &UtilSrcMatchAddEntry{AddrMode: addrMode, Address: address, PanID: panId}\n\terr = znp.ProcessRequest(unp.C_SREQ, unp.S_UTIL, 0x21, req, &rsp)\n\treturn\n}", "func AddENCEntry(hostName string, class string, entry Entry, backend gitlab.ENCBackend, force bool) {\n\t// TODO class should be directly injected in the entry array\n\tb := []string{class}\n\tentry.Classes = b\n\n\t// Marshal to yaml\n\tenc, err := yaml.Marshal(entry)\n\tif err != nil {\n\t\tlog.Fatalf(\"error: %v\", err)\n\t}\n\tfileName, err := writeToFile(enc, hostName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// TODO implement error handling for\n\tgitlab.AddToGitlab(fileName, enc, backend, force)\n}", "func (a *Archive) AddEntry(typ EntryType, name string, mtime int64, uid, gid int, mode os.FileMode, size int64, r io.Reader) {\n\toff, err := a.f.Seek(0, os.SEEK_END)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tn, err := fmt.Fprintf(a.f, entryHeader, exactly16Bytes(name), mtime, uid, gid, mode, size)\n\tif err != nil || n != entryLen {\n\t\tlog.Fatal(\"writing entry header: \", err)\n\t}\n\tn1, _ := io.CopyN(a.f, r, size)\n\tif n1 != size {\n\t\tlog.Fatal(err)\n\t}\n\tif (off+size)&1 != 0 {\n\t\ta.f.Write([]byte{0}) // pad to even byte\n\t}\n\ta.Entries = append(a.Entries, Entry{\n\t\tName: name,\n\t\tType: typ,\n\t\tMtime: mtime,\n\t\tUid: uid,\n\t\tGid: gid,\n\t\tMode: mode,\n\t\tData: Data{off + entryLen, size},\n\t})\n}", "func (f *Feed) AddEntry(\n\ttitle string,\n\turl string,\n\tid string,\n\tupdatedDate time.Time,\n\tpubDate time.Time,\n\tauthorName string,\n\tauthorURL string,\n\tauthorEmail string,\n\tcontentHTML string) error {\n\n\tf.Entries = append(f.Entries, Entry{\n\t\tTitle: title,\n\t\tLink: Link{\n\t\t\tRel: \"alternate\",\n\t\t\tType: \"text/html\",\n\t\t\tHref: url,\n\t\t},\n\t\tID: id,\n\t\tUpdated: updatedDate,\n\t\tPublished: pubDate,\n\t\tAuthor: Author{\n\t\t\tName: authorName,\n\t\t\tURI: authorURL,\n\t\t\tEmail: authorEmail,\n\t\t},\n\t\tContent: Content{\n\t\t\tType: \"html\",\n\t\t\tText: contentHTML,\n\t\t},\n\t})\n\n\treturn nil\n}", "func (entry *UtxoEntry) size() uint64 {\n\tsize := baseEntrySize + len(entry.pkScript)\n\tif entry.ticketMinOuts != nil {\n\t\tsize += len(entry.ticketMinOuts.data)\n\t}\n\treturn uint64(size)\n}", "func (t *Tile) PathNeighborCost(to astar.Pather) float64 {\n\ttoT := to.(*Tile)\n\treturn t.DistanceTo(toT) * (float64(toT.Type) + 1)\n}", "func (r *Report) addEntry(key string, suppressedKinds []string, kind string, context int, diffs []difflib.DiffRecord, changeType string) {\n\tentry := ReportEntry{\n\t\tkey,\n\t\tsuppressedKinds,\n\t\tkind,\n\t\tcontext,\n\t\tdiffs,\n\t\tchangeType,\n\t}\n\tr.entries = append(r.entries, entry)\n}", "func (d *Data) baseAddressForEntry(e *Entry) (*Entry, uint64, error) {\n\tvar cu *Entry\n\tif e.Tag == TagCompileUnit {\n\t\tcu = e\n\t} else {\n\t\ti := d.offsetToUnit(e.Offset)\n\t\tif i == -1 {\n\t\t\treturn nil, 0, errors.New(\"no unit for entry\")\n\t\t}\n\t\tu := &d.unit[i]\n\t\tb := makeBuf(d, u, \"info\", u.off, u.data)\n\t\tcu = b.entry(nil, u.atable, u.base, u.vers)\n\t\tif b.err != nil {\n\t\t\treturn nil, 0, b.err\n\t\t}\n\t}\n\n\tif cuEntry, cuEntryOK := cu.Val(AttrEntrypc).(uint64); cuEntryOK {\n\t\treturn cu, cuEntry, nil\n\t} else if cuLow, cuLowOK := cu.Val(AttrLowpc).(uint64); cuLowOK {\n\t\treturn cu, cuLow, nil\n\t}\n\n\treturn cu, 0, nil\n}", "func Cost(v int) predicate.Product {\n\treturn predicate.Product(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldCost), v))\n\t})\n}", "func (room *Room) AddEntry(entry, issuer string) error {\n\tif room.game == nil {\n\t\treturn errors.New(\"there isn't a started game\")\n\t}\n\n\tif err := room.game.AddEntry(entry, issuer); err != nil {\n\t\treturn err\n\t}\n\n\tif room.game.Finished {\n\t\troom.previousGame = room.game\n\t\troom.game = nil\n\t}\n\treturn nil\n}", "func EntryEqual(e1, e2 *spb.Entry) bool {\n\treturn (e1 == e2) || (e1.GetFactName() == e2.GetFactName() && e1.GetEdgeKind() == e2.GetEdgeKind() && VNameEqual(e1.Target, e2.Target) && VNameEqual(e1.Source, e2.Source) && bytes.Equal(e1.FactValue, e2.FactValue))\n}", "func (this *RouterTable) AddEntries(entry ...*RouterEntry) (*RouterTable, error) {\n\t//copy the router table\n\trouterTable, err := this.Rebuild()\n\tif err != nil {\n\t\treturn routerTable, err\n\t}\n\n\tentries := make([]*RouterEntry, 0)\n\n\t//build a new entries array with every *except the ones we are adding\n\tfor _, e := range routerTable.Entries {\n\t\t//check if this entry matches any of the entries we are adding.\n\t\tfound := false\n\t\tfor _, en := range entry {\n\t\t\tif e.Id() == en.Id() {\n\t\t\t\tfound = true\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tentries = append(entries, e)\n\t\t}\n\t}\n\t//now add the new ones\n\tfor _, en := range entry {\n\t\tentries = append(entries, en)\n\t}\n\trouterTable.Entries = entries\n\trouterTable.UpdateRevision()\n\trouterTable, err = routerTable.Rebuild()\n\treturn routerTable, err\n}", "func (c *directClient) PostEntry(ctx context.Context, entry *disc.Entry) error {\n\tc.mx.Lock()\n\tdefer c.mx.Unlock()\n\tc.entries[entry.Static] = entry\n\treturn nil\n}", "func (api *Cmtt) GetEntry(entryID int) (*Entry, error) {\n\tres, err := api.execute(\"entry/{id}\", map[string]string{\n\t\t\"id\": strconv.Itoa(entryID),\n\t}, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := &Entry{}\n\terr = castStruct(res, result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, err\n}", "func ParseFactomEntry(e *lite.EntryHolder) (iae IApplyEntry, err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = fmt.Errorf(\"[ParseFactomEntry] A panic has occurred while parsing a factom entry: %s\", r)\n\t\t\treturn\n\t\t}\n\t}()\n\n\tif len(e.Entry.ExtIDs) < 2 {\n\t\treturn nil, fmt.Errorf(\"ExternalID length is less than 2. This is too short\")\n\t}\n\n\t// This is how we designate the entry type\n\t// and parse appropriately\n\tswitch string(e.Entry.ExtIDs[1]) {\n\tcase \"Master Chain\":\n\t\tiae = NewMasterChainApplyEntry()\n\tcase \"Channel Root Chain\": // Root Create\n\t\tiae = NewRootChainApplyEntry()\n\tcase \"Channel Management Chain\": // Manage Create\n\t\tiae = NewManageChainApplyEntry()\n\tcase \"Channel Content Chain\": // Content Create\n\t\tiae = NewContentChainApplyEntry()\n\tcase \"Channel Chain\": // Register Root\n\t\tiae = NewRootRegisterApplyEntry()\n\tcase \"Register Management Chain\": // Register Manage\n\t\tiae = NewManageRegisterApplyEntry()\n\tcase \"Register Content Chain\": // Register Content\n\t\tiae = NewContentRegisterApplyEntry()\n\tcase \"Channel Management Metadata Main\": // Channel Metadata\n\t\tiae = NewManageMetaApplyEntry()\n\tcase \"Content Signing Key\":\n\t\tiae = NewContentSigningKeyApplyEntry()\n\tcase \"Content Link\": // Hyperlink\n\t\tiae = NewContentLinkApplyEntry()\n\tcase \"Content Chain\": // Need to stich entries in the chain.\n\t\t// We actually process Content Chains by the \"Content Link\", so we can\n\t\t// toss these\n\t\tiae = NewBitBucketApplyEntry()\n\tdefault:\n\t\t// Toss the entry, I have no clue what it is, do you?\n\t\tiae = NewBitBucketApplyEntry()\n\t}\n\n\terr = iae.ParseFactomEntry(e)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn iae, nil\n}", "func RegisterCredEntry(opts ...CredEntryOption) *CredEntry {\n\tentry := &CredEntry{\n\t\tEventLoggerEntry: GlobalAppCtx.GetEventLoggerEntryDefault(),\n\t\tZapLoggerEntry: GlobalAppCtx.GetZapLoggerEntryDefault(),\n\t\tEntryName: CredEntryName,\n\t\tEntryType: CredEntryType,\n\t\tEntryDescription: CredEntryDescription,\n\t\tStore: &CredStore{\n\t\t\tCred: make(map[string][]byte, 0),\n\t\t},\n\t}\n\n\tfor i := range opts {\n\t\topts[i](entry)\n\t}\n\n\tGlobalAppCtx.AddCredEntry(entry)\n\n\treturn entry\n}", "func (s *DnsServer) AddEntry(name string, rr dns.RR) {\n\tc := s.NewControllerForName(dns.CanonicalName(name))\n\tc.AddRecords([]dns.RR{rr})\n}", "func (p *Resolver) AddForkEntry(entry *model.ProcessCacheEntry) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tp.insertForkEntry(entry, model.ProcessCacheEntryFromEvent)\n}", "func NewAliasEntry(owner, CNAMETarget string) *Entry {\n\te := new(Entry)\n\te.owner = strings.ToLower(dns.Fqdn(owner))\n\te.cNAMETarget = strings.ToLower(dns.Fqdn(CNAMETarget))\n\treturn e\n}", "func Entry(description string, parameters ...interface{}) TableEntry {\n\treturn TableEntry{description, parameters, false, false}\n}", "func AddEntry(storage core.StorageClient) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tvar (\n\t\t\terr error\n\t\t\tentry models.Entry\n\t\t)\n\n\t\terr = c.Bind(&entry)\n\t\tif err != nil {\n\t\t\tc.Status(http.StatusBadRequest)\n\n\t\t\treturn\n\t\t}\n\n\t\tentry.Id = uuid.New().String()\n\n\t\terr = storage.Add(entry)\n\t\tif err != nil {\n\t\t\tvar storageError *core.StorageError\n\n\t\t\tif errors.As(err, &storageError) {\n\t\t\t\tc.Status(storageError.StatusCode())\n\t\t\t} else {\n\t\t\t\tc.Status(http.StatusInternalServerError)\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\n\t\tc.JSON(http.StatusCreated, entry)\n\t}\n}", "func (s *Set) Add(e *spb.Entry) error {\n\tif e == nil {\n\t\ts.addErrors++\n\t\treturn errors.New(\"entryset: nil entry\")\n\t} else if (e.Target == nil) != (e.EdgeKind == \"\") {\n\t\ts.addErrors++\n\t\treturn fmt.Errorf(\"entryset: invalid entry: target=%v/kind=%v\", e.Target == nil, e.EdgeKind == \"\")\n\t}\n\ts.addCalls++\n\tsrc := s.addVName(e.Source)\n\tif e.Target != nil {\n\t\ts.addEdge(src, edge{\n\t\t\tkind: s.enter(e.EdgeKind),\n\t\t\ttarget: s.addVName(e.Target),\n\t\t})\n\t} else {\n\t\ts.addFact(src, fact{\n\t\t\tname: s.enter(e.FactName),\n\t\t\tvalue: s.enter(string(e.FactValue)),\n\t\t})\n\t}\n\treturn nil\n}", "func (t *OpenconfigAcl_Acl_Interfaces_Interface_EgressAclSets_EgressAclSet_AclEntries_AclEntry) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigAcl_Acl_Interfaces_Interface_EgressAclSets_EgressAclSet_AclEntries_AclEntry\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *directClient) Entry(ctx context.Context, pubKey cipher.PubKey) (*disc.Entry, error) {\n\tc.mx.RLock()\n\tdefer c.mx.RUnlock()\n\tfor _, entry := range c.entries {\n\t\tif entry.Static == pubKey {\n\t\t\treturn entry, nil\n\t\t}\n\t}\n\treturn &disc.Entry{}, nil\n}", "func entrySize(e *logging.LogEntry) (int, error) {\n\tb, err := json.Marshal(e)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn len(b), nil\n}", "func (b *CompactableBuffer) Add(data []byte) (*EntryAddress, error) {\n\tentry := b.allocateEntry(data)\n\tbytes, err := entry.ToBytes()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Invalid entry size %v\", err)\n\t}\n\tif len(bytes) >= int(entry.entrySize) {\n\t\treturn nil, fmt.Errorf(\"Invalid entry size e:%v,h:%v\", len(bytes), int(entry.entrySize))\n\t}\n\n\twritableBuffer := b.writableBuffer()\n\tposition, err := writableBuffer.acquireAddress(entry)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = writableBuffer.Write(position, bytes...)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to write data at %v due %v\", position, err)\n\t}\n\tatomic.AddInt64(&b.count, 1)\n\tatomic.AddInt64(&b.entrySize, entry.entrySize)\n\tatomic.AddInt64(&b.dataSize, entry.dataSize)\n\n\tresult := NewEntryAddress(writableBuffer.config.BufferId, position)\n\n\twritableBuffer.addAddress(result)\n\treturn result, nil\n}", "func (c *EntryCache) add(e *Entry) error {\n\thashes, err := allHashes(e, c.hashes)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tif _, present := c.entries[e.name]; present {\n\t\t// log or fail...?\n\t\tc.log.Warning(\"[cache] Overwriting cache entry '%s'\", e.name)\n\t} else {\n\t\tc.log.Info(\"[cache] Adding entry for '%s'\", e.name)\n\t}\n\tc.entries[e.name] = e\n\tfor _, h := range hashes {\n\t\tc.lookupMap[h] = e\n\t}\n\treturn nil\n}", "func (cache *Cache) AddEntry (path string) *FilePrint {\n ent, ok := cache.FilePrints[path]\n if ! ok {\n ent = new(FilePrint)\n ent.Local.Changed = true\n ent.Remote.Changed = true\n cache.FilePrints[path] = ent\n }\n return ent\n}", "func NewEntry(name string) EntryBase {\n\tif name == \"\" {\n\t\tpanic(\"plugin.NewEntry: received an empty name\")\n\t}\n\n\te := EntryBase{\n\t\tentryName: name,\n\t\tslashReplacerCh: '#',\n\t}\n\tfor op := range e.ttl {\n\t\te.SetTTLOf(defaultOpCode(op), 15*time.Second)\n\t}\n\treturn e\n}", "func NewEntry(ctx *pulumi.Context,\n\tname string, args *EntryArgs, opts ...pulumi.ResourceOption) (*Entry, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.EntryGroup == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'EntryGroup'\")\n\t}\n\tif args.EntryId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'EntryId'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Entry\n\terr := ctx.RegisterResource(\"gcp:datacatalog/entry:Entry\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewEntry(ctx *pulumi.Context,\n\tname string, args *EntryArgs, opts ...pulumi.ResourceOption) (*Entry, error) {\n\tif args == nil || args.EntryGroup == nil {\n\t\treturn nil, errors.New(\"missing required argument 'EntryGroup'\")\n\t}\n\tif args == nil || args.EntryId == nil {\n\t\treturn nil, errors.New(\"missing required argument 'EntryId'\")\n\t}\n\tif args == nil {\n\t\targs = &EntryArgs{}\n\t}\n\tvar resource Entry\n\terr := ctx.RegisterResource(\"gcp:datacatalog/entry:Entry\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func cellsCost(markedVals []int, index indexedCluster) int {\n\treturn len(cellsPainted(markedVals, index))\n}", "func EntryMatchesScan(req *spb.ScanRequest, entry *spb.Entry) bool {\n\treturn (req.Target == nil || VNameEqual(entry.Target, req.Target)) &&\n\t\t(req.GetEdgeKind() == \"\" || entry.GetEdgeKind() == req.GetEdgeKind()) &&\n\t\tstrings.HasPrefix(entry.GetFactName(), req.GetFactPrefix())\n}", "func (e DataEntry) Size() int { return binary.Size(e) }", "func (c *EntryCache) AddFromRequest(req *ocsp.Request, upstream []string) ([]byte, error) {\n\te := NewEntry(c.log, c.clk)\n\te.serial = req.SerialNumber\n\tvar err error\n\te.request, err = req.Marshal()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\te.responders = upstream\n\tserialHash := sha256.Sum256(e.serial.Bytes())\n\tkey := sha256.Sum256(append(append(req.IssuerNameHash, req.IssuerKeyHash...), serialHash[:]...))\n\te.name = fmt.Sprintf(\"%X\", key)\n\te.issuer = c.issuers.getFromRequest(req.IssuerNameHash, req.IssuerKeyHash)\n\tif e.issuer == nil {\n\t\treturn nil, errors.New(\"No issuer in cache for request\")\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), c.requestTimeout)\n\tdefer cancel()\n\terr = e.init(ctx, c.StableBackings, c.client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.addSingle(e, key)\n\treturn e.response, nil\n}", "func (api *Cmtt) LikeEntry(entryID int) (*Likes, error) {\n\treturn api.rate(entryID, 1)\n}", "func computeCost(new, old float64) float64 {\n\treturn new*newBookCost + old*oldBookCost\n}", "func NewEntryCache(clk clock.Clock, logger *log.Logger, monitorTick time.Duration, stableBackings []scache.Cache, client *http.Client, timeout time.Duration, issuers []*x509.Certificate, supportedHashes config.SupportedHashes, disableMonitor bool) *EntryCache {\n\tc := &EntryCache{\n\t\tlog: logger,\n\t\tentries: make(map[string]*Entry),\n\t\tlookupMap: make(map[[32]byte]*Entry),\n\t\tStableBackings: stableBackings,\n\t\tclient: client,\n\t\trequestTimeout: timeout,\n\t\tclk: clk,\n\t\tissuers: newIssuerCache(issuers, supportedHashes),\n\t\thashes: supportedHashes,\n\t}\n\tif !disableMonitor {\n\t\tgo c.monitor(monitorTick)\n\t}\n\treturn c\n}", "func (_RandomBeacon *RandomBeaconTransactor) SubmitRelayEntry(opts *bind.TransactOpts, entry []byte, groupMembers []uint32) (*types.Transaction, error) {\n\treturn _RandomBeacon.contract.Transact(opts, \"submitRelayEntry\", entry, groupMembers)\n}", "func (p *Resolver) AddExecEntry(entry *model.ProcessCacheEntry) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tp.insertExecEntry(entry, model.ProcessCacheEntryFromEvent)\n}", "func (s *Service) CreateEntry(ctx context.Context, in *pb.CreateEntryRequest) (*pb.Entry, error) {\n\tcurrentUser, err := s.getCurrentUser(ctx)\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.PermissionDenied, \"Authentication failed\")\n\t}\n\n\tvar year int\n\terr = s.db.Get(&year, \"select year from calendars where id = ?\", in.GetCalendarId())\n\tif err == sql.ErrNoRows {\n\t\treturn nil, status.Errorf(codes.NotFound, \"Calendar not found\")\n\t}\n\tif err != nil {\n\t\treturn nil, xerrors.Errorf(\"Failed query to fetch calendar: %w\", err)\n\t}\n\n\tday := in.GetDay()\n\tif day < 1 || day > 25 {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"Invalid day: %d\", day)\n\t}\n\n\tlastID, err := s.insertEntry(currentUser.ID, in.GetCalendarId(), day)\n\tif err != nil {\n\t\treturn nil, xerrors.Errorf(\"Failed to insert entry: %w\", err)\n\t}\n\n\tvar entryID int64\n\terr = s.db.Get(&entryID, \"select id from entries where id = ?\", lastID)\n\tif err != nil {\n\t\treturn nil, xerrors.Errorf(\"Failed query to fetch entry: %w\", err)\n\t}\n\n\treturn &pb.Entry{Id: entryID}, nil\n}", "func (cache Cache) Add(key string, value string, costFunc func(m map[string]*list.Element, capacity int) int) bool {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\ttotalCost := 0\n\telem, found := cache.cacheMap[key]\n\tif found {\n\t\telem.Value = value\n\t\tcache.linkedList.MoveBefore(elem, cache.linkedList.Front())\n\t\treturn true\n\t} else {\n\t\tif len(cache.cacheMap) >= cache.capacity {\n\t\t\ttotalCost = costFunc(cache.cacheMap, cache.capacity)\n\t\t\tfmt.Println(\"Cost : \", totalCost)\n\t\t\tel := cache.linkedList.Back()\n\t\t\tcache.linkedList.Remove(el)\n\t\t\tnewKey := el.Value.(CacheStruct).key\n\t\t\tdelete(cache.cacheMap, newKey)\n\t\t}\n\t\tentry := CacheStruct{key: key, value: value}\n\t\tnewItem := cache.linkedList.PushFront(entry)\n\t\tcache.cacheMap[key] = newItem\n\t\treturn true\n\t}\n\n}", "func (s *HTTPServer) entrySubmitHandler(w http.ResponseWriter, r *http.Request) {\n\n\t// Extract the arguments from the http request. The request comes\n\t// in externally, hence we have no control over what might be in the\n\t// request forms, make sure we sanitize the input.\n\targs := ArgsFromRequest(r)\n\tDieNil(args)\n\n\t// Get entry storage\n\testore := s.EntryStore()\n\tDieNil(estore) // GAK\n\n\t// Store the entry - the entries name must be unique, hence we need\n\t// to create new storge for this item.\n\tentry := EntryFromArgs(args)\n\tif entry == nil {\n\t\tRespondError(w, 500, \"failed to create entry\")\n\t\treturn\n\t}\n\terr := estore.Create(entry.Name, entry.JSON())\n\tif err != nil {\n\t\tRespondError(w, 500, \"failed to create entry\")\n\t\treturn\n\t}\n\tRespondJSON(w, entry)\n}", "func Cost(v int) predicate.Surgeryappointment {\n\treturn predicate.Surgeryappointment(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldCost), v))\n\t})\n}", "func (t *OpenconfigAcl_Acl_Interfaces_Interface_EgressAclSets_EgressAclSet_AclEntries) NewAclEntry(SequenceId uint32) (*OpenconfigAcl_Acl_Interfaces_Interface_EgressAclSets_EgressAclSet_AclEntries_AclEntry, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.AclEntry == nil {\n\t\tt.AclEntry = make(map[uint32]*OpenconfigAcl_Acl_Interfaces_Interface_EgressAclSets_EgressAclSet_AclEntries_AclEntry)\n\t}\n\n\tkey := SequenceId\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.AclEntry[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list AclEntry\", key)\n\t}\n\n\tt.AclEntry[key] = &OpenconfigAcl_Acl_Interfaces_Interface_EgressAclSets_EgressAclSet_AclEntries_AclEntry{\n\t\tSequenceId: &SequenceId,\n\t}\n\n\treturn t.AclEntry[key], nil\n}", "func NewMDEntrySize(val decimal.Decimal, scale int32) MDEntrySizeField {\n\treturn MDEntrySizeField{quickfix.FIXDecimal{Decimal: val, Scale: scale}}\n}", "func (e *Entry) Size() int64 {\n\treturn e.st.Size()\n}", "func CalculateCost(carsCount int) uint {\n\tgroupCount := carsCount / 10\n\tindividualCount := carsCount % 10\n\n\treturn (uint(groupCount) * 95000) + (uint(individualCount) * 10000)\n}", "func makeEntry(f *FormInfo, c *Char) uint16 {\n\te := uint16(0)\n\tif r := c.codePoint; HangulBase <= r && r < HangulEnd {\n\t\te |= 0x40\n\t}\n\tif f.combinesForward {\n\t\te |= 0x20\n\t}\n\tif f.quickCheck[MDecomposed] == QCNo {\n\t\te |= 0x4\n\t}\n\tswitch f.quickCheck[MComposed] {\n\tcase QCYes:\n\tcase QCNo:\n\t\te |= 0x10\n\tcase QCMaybe:\n\t\te |= 0x18\n\tdefault:\n\t\tlog.Fatalf(\"Illegal quickcheck value %v.\", f.quickCheck[MComposed])\n\t}\n\te |= uint16(c.nTrailingNonStarters)\n\treturn e\n}", "func (dr *DarkRoast) Cost() float64 {\n\treturn float64(300)\n}", "func GetCost(elev esm.ElevData, order elevio.ButtonEvent) int {\n\n\tcost := 0\n\tswitch elev.State {\n\n\tcase esm.Idle:\n\t\treturn abs(elev.Floor - order.Floor)\n\n\tcase esm.DoorOpen:\n\t\treturn 1 + abs(elev.Floor-order.Floor)\n\n\tcase esm.Moving:\n\t\tif !isMovingTowards(elev, order) {\n\t\t\tcost += 5\n\t\t} else {\n\t\t\tcost += abs(elev.Floor-order.Floor) * 2\n\t\t}\n\t}\n\treturn cost\n}", "func (tree *DNFTree) CreateNodeEntry(phi br.ClauseSet, depth int, isFinal bool) int {\n\tn := &DNFTreeNodeContent{phi, -1, -1, isFinal, depth}\n\ttree.Content = append(tree.Content, n)\n\treturn len(tree.Content) - 1\n}", "func SetCost(c int) {\n\tcost = c\n}", "func (s *Processor) ProcessEntry(entry interfaces.IEBEntry, dblock interfaces.IDirectoryBlock) error {\n\tif len(entry.ExternalIDs()) == 0 {\n\t\treturn nil\n\t}\n\tswitch string(entry.ExternalIDs()[0]) {\n\tcase \"TwitterBank Chain\":\n\t\t// TODO: Remove this hack\n\t\tif len(entry.ExternalIDs()) == 3 {\n\t\t\treturn s.ProcessTwitterChain(entry, dblock)\n\t\t}\n\t\treturn s.ProcessTwitterEntry(entry, dblock)\n\tcase \"TwitterBank Record\":\n\t\treturn s.ProcessTwitterChain(entry, dblock)\n\t}\n\n\treturn nil\n}", "func (marketOrder MarketOrder) TotalCost() decimal.Decimal {\n\treturn marketOrder.Price.Mul(marketOrder.Volume)\n}" ]
[ "0.56218654", "0.5478037", "0.5406175", "0.53386706", "0.5268795", "0.5219574", "0.5201627", "0.5197092", "0.5190688", "0.5178546", "0.5136147", "0.5081392", "0.502089", "0.50178033", "0.50176954", "0.49997976", "0.4938561", "0.49210775", "0.49052235", "0.48887512", "0.48790345", "0.48589784", "0.48425737", "0.48410946", "0.48400775", "0.48225892", "0.48034227", "0.47967216", "0.47670728", "0.4763921", "0.4759177", "0.4743696", "0.4740403", "0.47328857", "0.46908656", "0.46697283", "0.46626547", "0.46582156", "0.4647185", "0.46347126", "0.46305263", "0.46279323", "0.46232978", "0.46224347", "0.46089077", "0.4581858", "0.45760807", "0.4575376", "0.45752344", "0.45688474", "0.456788", "0.45493856", "0.4537976", "0.45364726", "0.45292786", "0.45214605", "0.45180637", "0.45156947", "0.45013237", "0.44964638", "0.4492391", "0.44904393", "0.44848216", "0.44814885", "0.44786552", "0.44743505", "0.44660485", "0.4463952", "0.44601545", "0.44596574", "0.4451896", "0.44518533", "0.44459465", "0.44442964", "0.44372502", "0.4433577", "0.44297507", "0.44245398", "0.44237965", "0.44236678", "0.44196913", "0.44189888", "0.4416986", "0.44144014", "0.44128245", "0.4412518", "0.44107464", "0.44006085", "0.4400115", "0.4398642", "0.4386916", "0.43860078", "0.43845025", "0.43840754", "0.43830243", "0.4381703", "0.43734565", "0.4372803", "0.43724284", "0.4370857" ]
0.8154941
0
FactoshiToFactoid converts a uint64 factoshi ammount into a fixed point number represented as a string
func FactoshiToFactoid(i uint64) string { d := i / 1e8 r := i % 1e8 ds := fmt.Sprintf("%d", d) rs := fmt.Sprintf("%08d", r) rs = strings.TrimRight(rs, "0") if len(rs) > 0 { ds = ds + "." } return fmt.Sprintf("%s%s", ds, rs) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func FactoidToFactoshi(amt string) uint64 {\n\tvalid := regexp.MustCompile(`^([0-9]+)?(\\.[0-9]+)?$`)\n\tif !valid.MatchString(amt) {\n\t\treturn 0\n\t}\n\n\tvar total uint64 = 0\n\n\tdot := regexp.MustCompile(`\\.`)\n\tpieces := dot.Split(amt, 2)\n\twhole, _ := strconv.Atoi(pieces[0])\n\ttotal += uint64(whole) * 1e8\n\n\tif len(pieces) > 1 {\n\t\ta := regexp.MustCompile(`(0*)([0-9]+)$`)\n\n\t\tas := a.FindStringSubmatch(pieces[1])\n\t\tpart, _ := strconv.Atoi(as[0])\n\t\tpower := len(as[1]) + len(as[2])\n\t\ttotal += uint64(part * 1e8 / int(math.Pow10(power)))\n\t}\n\n\treturn total\n}", "func StringUI64(i64 uint64) string { return strconv.FormatUint(i64, 10) }", "func StringUint(i uint) string { return strconv.FormatUint(uint64(i), 10) }", "func conv(n float64) uint64 {\n\ts := fmt.Sprintf(\"%.0f\", n)\n\tresult, _ := strconv.ParseUint(s, 10, 64)\n\treturn result\n}", "func StringI64(i64 int64) string { return strconv.FormatInt(i64, 10) }", "func itos(i int64) string {\n\ts := strconv.FormatUint(uint64(i)+int64Adjust, 32)\n\tconst z = \"0000000000000\"\n\treturn z[len(s):] + s\n}", "func itod(i uint) string {\n\tif i == 0 {\n\t\treturn \"0\"\n\t}\n\n\t// Assemble decimal in reverse order.\n\tvar b [32]byte\n\tbp := len(b)\n\tfor ; i > 0; i /= 10 {\n\t\tbp--\n\t\tb[bp] = byte(i%10) + '0'\n\t}\n\n\treturn string(b[bp:])\n}", "func PriceToString(n float64) string {\n return strconv.FormatFloat(n, 'f', 3, 64)\n}", "func toSatoshi(v float64) uint64 {\n\treturn uint64(math.Round(v * 1e8))\n}", "func ConvertFixedPoint(amt string) (string, error) {\n\tvar v int64\n\tvar err error\n\tindex := strings.Index(amt, \".\")\n\tif index == 0 {\n\t\tamt = \"0\" + amt\n\t\tindex++\n\t}\n\tif index < 0 {\n\t\tv, err = strconv.ParseInt(amt, 10, 64)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tv *= 100000000 // Convert to Factoshis\n\t} else {\n\t\ttp := amt[:index]\n\t\tv, err = strconv.ParseInt(tp, 10, 64)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tv = v * 100000000 // Convert to Factoshis\n\n\t\tbp := amt[index+1:]\n\t\tif len(bp) > 8 {\n\t\t\tbp = bp[:8]\n\t\t}\n\t\tbpv, err := strconv.ParseInt(bp, 10, 64)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tfor i := 0; i < 8-len(bp); i++ {\n\t\t\tbpv *= 10\n\t\t}\n\t\tv += bpv\n\t}\n\treturn strconv.FormatInt(v, 10), nil\n}", "func AmountToString(n float64) string {\n return strconv.FormatFloat(n, 'f', 8, 64)\n}", "func convertToSatoshi(btc []byte) uint64 {\n\n\ts := uint64(0)\n\tpoint := false\n\tdecimals := 0\n\tfor _, b := range btc {\n\t\tif b >= '0' && b <= '9' {\n\t\t\ts *= 10\n\t\t\ts += uint64(b - '0')\n\t\t\tif point {\n\t\t\t\tdecimals += 1\n\t\t\t\tif decimals >= 8 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t} else if '.' == b {\n\t\t\tpoint = true\n\t\t}\n\t}\n\tfor decimals < 8 {\n\t\ts *= 10\n\t\tdecimals += 1\n\t}\n\n\treturn s\n}", "func ToString(h H3Index) string {\n\treturn strconv.FormatUint(uint64(h), 16)\n}", "func ToString(h H3Index) string {\n\treturn strconv.FormatUint(uint64(h), 16)\n}", "func (s Snowflake) String() string {\n\treturn strconv.FormatUint(uint64(s), 10)\n}", "func ToScalar(pubkey ecdsa.PublicKey) string {\n\tpubkeyX := fmt.Sprintf(\"%x\", pubkey.X)\n\t// pubkeyY := fmt.Sprintf(\"%x\", keyPair.PublicKey.Y)\n\t// if pubkeyY is even => prefix is 02\n\t// if pubkeyY is odd => prefix is 03\n\treturn \"02\" + pubkeyX\n}", "func BigIntToHexStr(i *big.Int) string {\n\th := i.Text(16)\n\tif len(h)%2 == 1 {\n\t\th = \"0\" + h // make sure that the length is even\n\t}\n\treturn \"0x\" + h\n}", "func uitoa(val uint) string {\n\tvar buf [32]byte // big enough for int64\n\ti := len(buf) - 1\n\tfor val >= 10 {\n\t\tbuf[i] = byte(val%10 + '0')\n\t\ti--\n\t\tval /= 10\n\t}\n\tbuf[i] = byte(val + '0')\n\treturn string(buf[i:])\n}", "func (blob *Blob) FN(sum string) string {\n\treturn fmt.Sprintf(\"%016x_%s\", blob.Time.UnixNano(), sum[:16])\n}", "func Decoct(x int64) string {\n\n\treturn strconv.FormatInt(x, 8)\n}", "func facto(x uint) uint {\n\tif x == 1 {\n\t\treturn 1\n\t}\n\treturn x * facto(x-1)\n}", "func Uint64(i uint64) string {\n\t// Base 10\n\treturn strconv.FormatUint(i, 10)\n}", "func (this *unsignedFixed) String() string {\n\tm := this.mantissa\n\tdigits := strconv.FormatUint(m, 10)\n\tnumDigits := len(digits)\n\te := this.exponent\n\teInt := int(e)\n\tnumLeadingZeros := (eInt - numDigits) + 1\n\n\t/*\n\t * Add leading zeros if necessary.\n\t */\n\tif numLeadingZeros > 0 {\n\n\t\t/*\n\t\t * Add as many zeros as required.\n\t\t */\n\t\tfor i := 0; i < numLeadingZeros; i++ {\n\t\t\tdigits = \"0\" + digits\n\t\t}\n\n\t\tnumDigits += numLeadingZeros\n\t}\n\n\tdotPos := numDigits - eInt\n\n\t/*\n\t * Insert dot if it is not past the last digit.\n\t */\n\tif dotPos < numDigits {\n\t\tr := []rune(digits)\n\t\tfirst := r[:dotPos]\n\t\tsecond := r[dotPos:]\n\t\tfirstString := string(first)\n\t\tsecondString := string(second)\n\t\tdigits = firstString + \".\" + secondString\n\t}\n\n\treturn digits\n}", "func From64To3(id64 uint64) string {\n\treturn FromIDTo3(From64ToID(id64))\n}", "func FromIDTo3(id string) string {\n\tidParts := strings.Split(id, \":\")\n\tidLastPart, err := strconv.ParseUint(idParts[len(idParts)-1], 10, 64)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn \"[U:1:\" + strconv.FormatUint(idLastPart*2, 10) + \"]\"\n}", "func ftoh(n int) (string, error) {\n\tf, err := ioutil.ReadFile(\"blocks/\" + strconv.Itoa(n) + \".block\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn hash(f)\n}", "func i64toa(i int64) string {\n\treturn strconv.FormatInt(i, 10)\n}", "func fdToClockID(fd uintptr) int32 {\n\treturn int32((int(^fd) << 3) | 3)\n}", "func toPluralCountValue(in any) any {\n\tk := reflect.TypeOf(in).Kind()\n\tswitch {\n\tcase hreflect.IsFloat(k):\n\t\tf := cast.ToString(in)\n\t\tif !strings.Contains(f, \".\") {\n\t\t\tf += \".0\"\n\t\t}\n\t\treturn f\n\tcase k == reflect.String:\n\t\tif _, err := cast.ToFloat64E(in); err == nil {\n\t\t\treturn in\n\t\t}\n\t\t// A non-numeric value.\n\t\treturn nil\n\tdefault:\n\t\tif i, err := cast.ToIntE(in); err == nil {\n\t\t\treturn i\n\t\t}\n\t\treturn nil\n\t}\n}", "func Ftoa(num float64, offset int) string {\n\tf := fmt.Sprintf(\"%%.%df\", offset)\n\treturn stripTrailingZeros(fmt.Sprintf(f, num))\n}", "func UInt64ToString(x uint64) string {\n\treturn fmt.Sprintf(\"%d\", x)\n}", "func int64ToStr(i64 int64) string {\r\n\treturn strconv.FormatInt(i64, 10)\r\n}", "func Float642String(v float64) string {\n\treturn strconv.FormatFloat(v, 'f', -1, 64)\n}", "func (blob *Blob) FN(sum *Sum) string {\n\treturn fmt.Sprintf(\"%016x_%s\", blob.Time.UnixNano(),\n\t\tsum.FullString()[:16])\n}", "func itoaShort(v uint64) string {\n\tunits := []string{\"\", \"K\", \"M\", \"B\", \"T\"}\n\tp := int(math.Floor(math.Log10(float64(v)))) / 3\n\tif max := len(units) - 1; p > max {\n\t\tp = max\n\t}\n\tif p > 0 {\n\t\treturn fmt.Sprintf(\"%.1f%s\", math.Floor(float64(v)/math.Pow10(3*p-1))/10, units[p])\n\t}\n\treturn strconv.FormatUint(v, 10)\n}", "func StringInt(i int) string { return strconv.FormatInt(int64(i), 10) }", "func toAtoms(v float64) uint64 {\n\treturn uint64(math.Round(v * 1e8))\n}", "func toAtoms(v float64) uint64 {\n\treturn uint64(math.Round(v * 1e8))\n}", "func valString(v uint64) string {\n\treturn fmt.Sprintf(\"%.8f\", float64(v)/1e8)\n}", "func StringF64(f float64) string { return strconv.FormatFloat(f, 'f', -1, 64) }", "func (fcid FileContractID) String() string {\n\treturn fmt.Sprintf(\"%x\", fcid[:])\n}", "func FnvHashDigit(data string, digitLimit int) int {\n\th := fnv.New32a()\n\t_, _ = h.Write([]byte(data))\n\n\tif digitLimit < 2 {\n\t\tdigitLimit = 2\n\t}\n\n\treturn int(h.Sum32()%uint32(digitLimit-1) + 1)\n}", "func FastrandUint64() uint64 {\n\treturn (uint64(FastrandUint32()) << 32) | uint64(FastrandUint32())\n}", "func gfToString(a *[4]uint64) string {\n\tvar t [4]uint64\n\tcopy(t[:], a[:])\n\treturn \"K(\" + int256ToString(&t) + \")\"\n}", "func (c *Counter) String() string {\n\treturn strconv.FormatUint(c.Get().(uint64), 10)\n}", "func (n *N36) Ntoi(s string) (uint64, error) {\n\tvar r uint64\n\tbase := len(n.charset)\n\tfbase := float64(base)\n\tl := len(s)\n\n\tr = 0\n\n\tfor i := 0; i < l; i++ {\n\t\tn := strings.Index(n.charset, s[i:i+1])\n\n\t\tif n < 0 {\n\t\t\treturn 0, errors.New(\"n36.Ntoi: character not part of charset\")\n\t\t}\n\n\t\t//n * base^(l-i-1) + r\n\t\tr = uint64(n)*uint64(math.Pow(fbase, float64(l-i)-1)) + r\n\t}\n\n\treturn uint64(r), nil\n}", "func IntText(x *big.Int, base int) string", "func FixedNumeric(l uint) string {\n\treturn fixedString(l, alphaNumerics[52:])\n}", "func calculateLookupID(id uint64, metric string) string {\n\tasset := strconv.FormatUint(id, 10)\n\thash := sha256.New()\n\thash.Write([]byte(asset))\n\thash.Write([]byte(metric))\n\n\treturn hex.EncodeToString(hash.Sum(nil))\n}", "func (p *Int64) String() string {\n\tl := p.Len()\n\tif l == 0 {\n\t\treturn \"0\"\n\t}\n\tvar s string\n\tdegs := p.Degrees()\n\ts += fmt.Sprint(p.c[degs[0]])\n\ts += \"x^\"\n\ts += fmt.Sprint(degs[0])\n\tif l > 2 {\n\t\tfor _, n := range degs[1:] {\n\t\t\tif p.c[n] < 0 {\n\t\t\t\ts += fmt.Sprint(p.c[n])\n\t\t\t} else {\n\t\t\t\ts += \"+\" + fmt.Sprint(p.c[n])\n\t\t\t}\n\t\t\ts += \"x^\"\n\t\t\ts += fmt.Sprint(n)\n\t\t}\n\t}\n\treturn s\n}", "func (d Decimal) StringFixedCash(interval uint8) string {\n\trounded := d.RoundCash(interval)\n\treturn rounded.string(false)\n}", "func FingerprintToUInt64(input string) (result uint64, err error) {\n\treturn parser.FingerprintToUInt64(input)\n}", "func toAtoms(v float64) uint64 {\n\treturn uint64(math.Round(v * conventionalConversionFactor))\n}", "func Int64ToFloat64String(i int64) string {\n\treturn fmt.Sprintf(\"%.2f\", float64(i)/float64(100))\n}", "func formatCompact(x int64) []byte {\n\tif x < 0 {\n\t\tx = -x\n\t}\n\tvar b [20]byte\n\treturn strconv.AppendUint(b[0:0], uint64(x), 10)\n}", "func FNV64a(s string) (string, error) {\n\th := fnv.New64a()\n\tif _, err := h.Write([]byte(s)); err != nil {\n\t\treturn \"\", fmt.Errorf(\"Could not write hash: %w\", err)\n\t}\n\treturn fmt.Sprintf(\"%x\", h.Sum64()), nil\n}", "func hashFieldNameToNumber(s string) uint8 {\n\th := fnv.New32a()\n\th.Write([]byte(s))\n\treturn uint8(h.Sum32() % 2047)\n}", "func (this *BigInteger) ToString(b int64) string {\n\tif this.S < 0 {\n\t\treturn \"-\" + this.Negate().ToString(b)\n\t}\n\tvar k int64\n\tif b == 16 {\n\t\tk = 4\n\t} else if b == 8 {\n\t\tk = 3\n\t} else if b == 2 {\n\t\tk = 1\n\t} else if b == 32 {\n\t\tk = 5\n\t} else if b == 4 {\n\t\tk = 2\n\t} else {\n\t\treturn this.ToRadix(b)\n\t}\n\tvar km int64 = (1 << uint(k)) - 1\n\tvar d int64\n\tvar m bool = false\n\tvar r string = \"\"\n\tvar i int64 = this.T\n\tvar p int64 = DB - (i*DB)%k\n\tif i > 0 {\n\t\ti--\n\t\tif p < DB {\n\t\t\td = this.V[i] >> uint(p)\n\t\t\tif d > 0 {\n\t\t\t\tm = true\n\t\t\t\tr = Int2char(int(d))\n\t\t\t}\n\t\t}\n\t\tfor i >= 0 {\n\t\t\tif p < k {\n\t\t\t\td = this.V[i] & ((1 << uint(p)) - 1) << uint(k-p)\n\t\t\t\ti--\n\t\t\t\tp += DB - k\n\t\t\t\td |= this.V[i] >> uint(p)\n\t\t\t} else {\n\t\t\t\tp -= k\n\t\t\t\td = (this.V[i] >> uint(p)) & km\n\t\t\t\tif p <= 0 {\n\t\t\t\t\tp += DB\n\t\t\t\t\ti--\n\t\t\t\t}\n\t\t\t}\n\t\t\tif d > 0 {\n\t\t\t\tm = true\n\t\t\t}\n\t\t\tif m {\n\t\t\t\tr += Int2char(int(d))\n\t\t\t}\n\t\t}\n\t}\n\tif m {\n\t\treturn r\n\t} else {\n\t\treturn \"0\"\n\t}\n}", "func str2dec(what string) uint64 {\n\twhat = strings.TrimLeft(what, \"0\")\n\tif len(what) == 0 {\n\t\treturn 0\n\t}\n\tout, err := strconv.ParseUint(what, 10, 64)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn out\n}", "func uint642Big(in uint64) *big.Int {\n\treturn new(big.Int).SetUint64(in)\n}", "func (sc *Contract) Uid() uint64 {\n\treturn (uint64(sc.TimeStamp)&0xFFFFFFFFFF)<<24 | (binary.BigEndian.Uint64(sc.TransactionHash[:8]) & 0xFFFFFF)\n}", "func jamcoin(i int64, length int) string {\n\ta := strconv.FormatInt(i, 2)\n\tformat := \"1%0\" + strconv.Itoa(length-2) + \"s1\"\n\treturn fmt.Sprintf(format, a)\n}", "func (stream *Stream) WriteUint64(val uint64) {\n\tstream.ensure(20)\n\tn := stream.n\n\tq1 := val / 1000\n\tif q1 == 0 {\n\t\tstream.n = writeFirstBuf(stream.buf, digits[val], n)\n\t\treturn\n\t}\n\tr1 := val - q1*1000\n\tq2 := q1 / 1000\n\tif q2 == 0 {\n\t\tn := writeFirstBuf(stream.buf, digits[q1], n)\n\t\twriteBuf(stream.buf, digits[r1], n)\n\t\tstream.n = n + 3\n\t\treturn\n\t}\n\tr2 := q1 - q2*1000\n\tq3 := q2 / 1000\n\tif q3 == 0 {\n\t\tn = writeFirstBuf(stream.buf, digits[q2], n)\n\t\twriteBuf(stream.buf, digits[r2], n)\n\t\twriteBuf(stream.buf, digits[r1], n+3)\n\t\tstream.n = n + 6\n\t\treturn\n\t}\n\tr3 := q2 - q3*1000\n\tq4 := q3 / 1000\n\tif q4 == 0 {\n\t\tn = writeFirstBuf(stream.buf, digits[q3], n)\n\t\twriteBuf(stream.buf, digits[r3], n)\n\t\twriteBuf(stream.buf, digits[r2], n+3)\n\t\twriteBuf(stream.buf, digits[r1], n+6)\n\t\tstream.n = n + 9\n\t\treturn\n\t}\n\tr4 := q3 - q4*1000\n\tq5 := q4 / 1000\n\tif q5 == 0 {\n\t\tn = writeFirstBuf(stream.buf, digits[q4], n)\n\t\twriteBuf(stream.buf, digits[r4], n)\n\t\twriteBuf(stream.buf, digits[r3], n+3)\n\t\twriteBuf(stream.buf, digits[r2], n+6)\n\t\twriteBuf(stream.buf, digits[r1], n+9)\n\t\tstream.n = n + 12\n\t\treturn\n\t}\n\tr5 := q4 - q5*1000\n\tq6 := q5 / 1000\n\tif q6 == 0 {\n\t\tn = writeFirstBuf(stream.buf, digits[q5], n)\n\t} else {\n\t\tn = writeFirstBuf(stream.buf, digits[q6], n)\n\t\tr6 := q5 - q6*1000\n\t\twriteBuf(stream.buf, digits[r6], n)\n\t\tn += 3\n\t}\n\twriteBuf(stream.buf, digits[r5], n)\n\twriteBuf(stream.buf, digits[r4], n+3)\n\twriteBuf(stream.buf, digits[r3], n+6)\n\twriteBuf(stream.buf, digits[r2], n+9)\n\twriteBuf(stream.buf, digits[r1], n+12)\n\tstream.n = n + 15\n}", "func Int642String(v int64) string {\n\treturn strconv.Itoa(int(v))\n}", "func (me TSAFTaxonomyCode) String() string { return xsdt.Integer(me).String() }", "func FactTableID(tm time.Time) int64 {\n\treturn int64(tm.Sub(epoch).Hours()) + 1\n}", "func makeFact(line *parser.Quad, resolveXID func(string) uint64) (rpc.Fact, error) {\n\txidOf := func(node interface{}, field string) (string, error) {\n\t\tswitch n := node.(type) {\n\t\tcase *parser.Entity:\n\t\t\treturn n.Value, nil\n\t\tcase *parser.QName:\n\t\t\treturn n.Value, nil\n\t\tdefault:\n\t\t\treturn \"\", fmt.Errorf(\"value %s not a valid type for field %s\", node, field)\n\t\t}\n\t}\n\tvar res rpc.Fact\n\tsubjectXID, err := xidOf(line.Subject, \"Subject\")\n\tif err != nil {\n\t\treturn rpc.Fact{}, err\n\t}\n\tres.Subject = resolveXID(subjectXID)\n\tpredicateXID, err := xidOf(line.Predicate, \"Predicate\")\n\tif err != nil {\n\t\treturn rpc.Fact{}, err\n\t}\n\tres.Predicate = resolveXID(predicateXID)\n\n\tresolveUnitLanguageID := func(xid string) uint64 {\n\t\tif len(xid) > 0 {\n\t\t\treturn resolveXID(xid)\n\t\t}\n\t\treturn 0\n\t}\n\tswitch t := line.Object.(type) {\n\tcase *parser.LiteralBool:\n\t\tres.Object = rpc.ABool(t.Value, resolveUnitLanguageID(t.Unit.Value))\n\tcase *parser.LiteralFloat:\n\t\tres.Object = rpc.AFloat64(t.Value, resolveUnitLanguageID(t.Unit.Value))\n\tcase *parser.LiteralInt:\n\t\tres.Object = rpc.AInt64(t.Value, resolveUnitLanguageID(t.Unit.Value))\n\tcase *parser.LiteralTime:\n\t\tres.Object = rpc.ATimestamp(t.Value,\n\t\t\tlogentry.TimestampPrecision(t.Precision),\n\t\t\tresolveUnitLanguageID(t.Unit.Value))\n\tcase *parser.LiteralString:\n\t\tres.Object = rpc.AString(t.Value, resolveUnitLanguageID(t.Language.Value))\n\tdefault:\n\t\tobjectXID, err := xidOf(line.Object, \"Object\")\n\t\tif err != nil {\n\t\t\treturn rpc.Fact{}, err\n\t\t}\n\t\tres.Object = rpc.AKID(resolveXID(objectXID))\n\t}\n\treturn res, nil\n}", "func FNV64(s string) uint64 {\n\treturn uint64Hasher(fnv.New64(), s)\n}", "func Atoi(str string) uint64 {\n\tstr = strings.Trim(str, \" \")\n\tif len(str) > 0 {\n\t\ti, err := strconv.ParseUint(str, 10, 0)\n\t\tif err != nil {\n\t\t\treturn 0\n\t\t}\n\t\treturn i\n\t}\n\treturn 0\n}", "func toFreq(s semi, tonic freq) freq {\n\treturn tonic * freq(math.Pow(root12, float64(s)))\n}", "func From64ToID(id64 uint64) string {\n\tid := new(big.Int).SetInt64(int64(id64))\n\tmagic, _ := new(big.Int).SetString(\"76561197960265728\", 10)\n\tid = id.Sub(id, magic)\n\tisServer := new(big.Int).And(id, big.NewInt(1))\n\tid = id.Sub(id, isServer)\n\tid = id.Div(id, big.NewInt(2))\n\treturn \"STEAM_0:\" + isServer.String() + \":\" + id.String()\n}", "func cutoff64(base int) uint64 {\n\tif base < 2 {\n\t\treturn 0\n\t}\n\treturn (1<<64-1)/uint64(base) + 1\n}", "func FromIDTo64(id string) uint64 {\n\tidParts := strings.Split(id, \":\")\n\tmagic, _ := new(big.Int).SetString(\"76561197960265728\", 10)\n\tsteam64, _ := new(big.Int).SetString(idParts[2], 10)\n\tsteam64 = steam64.Mul(steam64, big.NewInt(2))\n\tsteam64 = steam64.Add(steam64, magic)\n\tauth, _ := new(big.Int).SetString(idParts[1], 10)\n\treturn steam64.Add(steam64, auth).Uint64()\n}", "func U64ToString(i uint64) string {\n\treturn fmt.Sprint(i)\n}", "func calcID(n *ast.MsgNode) uint64 {\n\tvar buf bytes.Buffer\n\twriteFingerprint(&buf, n, false)\n\n\tvar fp = fingerprint(buf.Bytes())\n\tif n.Meaning != \"\" {\n\t\tvar topbit uint64\n\t\tif fp&(1<<63) > 0 {\n\t\t\ttopbit = 1\n\t\t}\n\t\tfp = (fp << 1) + topbit + fingerprint([]byte(n.Meaning))\n\t}\n\n\treturn fp & 0x7fffffffffffffff\n}", "func ToFixed(x float32) fixed.Int26_6 {\n\treturn fixed.Int26_6(x * 64)\n}", "func From3To64(id3 string) uint64 {\n\treturn From32To64(From3To32(id3))\n}", "func HelloQueryFacto(c echo.Context) error {\n\n\tid := c.QueryParam(\"id\") //id의 값만 보게 변경\n\n\t//strconv.Atoi idInt 변수에 입력\n\tidInt, strConverr := strconv.Atoi(id)\n\n\t// strConverr가 nil이면 factorial.GetFacto 응답하기로 변경 else 문 제거,\n\tif strConverr != nil {\n\t\tlog.Println(strConverr)\n\t\treturn c.String(http.StatusOK, \"Please input only number.\")\n\t}\n\n\t// GetFacto 입력값 int로 변경\n\t// strconv 대신 fmt.Sprintf 사용. -> 더 빠르다고 함\n\t// 다시 strconv 사용. -> fmt.Sprintf 는 타입 변환과 출력을 동시에 할때 빠르고, 여기처럼 함수에 넣어서 바로 사용할땐 strconv가 더 빠르다고 함\n\tresult := strconv.Itoa(factorial.GetFacto(idInt))\n\treturn c.String(http.StatusOK, result)\n}", "func fingerprint(str []byte) uint64 {\n\tvar hi = hash32(str, 0, len(str), 0)\n\tvar lo = hash32(str, 0, len(str), 102072)\n\tif (hi == 0) && (lo == 0 || lo == 1) {\n\t\t// Turn 0/1 into another fingerprint\n\t\thi ^= 0x130f9bef\n\t\tlo ^= 0x94a0a928\n\t}\n\treturn (uint64(hi) << 32) | uint64(lo&0xffffffff)\n}", "func go_ipfs_cache_ipns_id() *C.char {\n\tpid, err := peer.IDFromPrivateKey(g.node.PrivateKey)\n\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tcstr := C.CString(pid.Pretty())\n\treturn cstr\n}", "func (id *Id) String() string {\n\treturn strconv.FormatUint(uint64(*id), 16)\n}", "func FastrandUint32() uint32", "func convertFtoc() {\n\tconst freezingF, boilingF = 32.0, 212.0\n\n\tfmt.Printf(\"%gF = %gC\\n\", freezingF, ftoc(freezingF)) //\"32F = 0C\"\t\n\tfmt.Printf(\"%gF = %gC\\n\", boilingF, ftoc(boilingF)) //\"212F\" = 100C\"\n\n}", "func RatFloatString(x *big.Rat, prec int) string", "func dataFrequencyToJQData(frequency string) (string, error) {\n\t_, err := strconv.ParseInt(frequency, 10, 64)\n\tif err != nil {\n\t\tswitch frequency {\n\t\tcase \"d\":\n\t\t\treturn \"1\" + \"d\", nil\n\t\tcase \"w\":\n\t\t\treturn \"1\" + \"w\", nil\n\t\tcase \"m\":\n\t\t\treturn \"1\" + \"M\", nil\n\t\tdefault:\n\t\t\treturn \"\", utils.Errorf(nil, \"返回数据错误 %+v\", frequency)\n\t\t}\n\t}\n\treturn frequency + \"m\", nil\n}", "func Acatui(str, b string, n uint64) string {\n\tns := strconv.FormatUint(n, 10)\n\treturn str + b + ns\n}", "func ChuckFact() string {\n\tresp, err := http.Get(\"https://api.chucknorris.io/jokes/random\")\n\tif err != nil {\n\t\treturn \"I had a problem...\"\n\t}\n\tdefer resp.Body.Close()\n\n\tbodyBytes, err := ioutil.ReadAll(resp.Body)\n\n\tvar fact chuck\n\tjson.Unmarshal([]byte(bodyBytes), &fact)\n\treturn fact.Value\n}", "func toBase62WithPaddingZeros(u uint64, padding int64) string {\n\tformatter := \"%+0\" + strconv.FormatInt(padding, 10) + \"s\"\n\treturn fmt.Sprintf(formatter, toBase62(u))\n}", "func getDimensionHash(dimensions map[string]string) string {\n\tvar keys []string\n\tfor k := range dimensions {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\n\th := fnv.New32a()\n\tfor _, key := range keys {\n\t\t_, _ = io.WriteString(h, key+\"\\t\"+dimensions[key]+\"\\n\")\n\t}\n\treturn strconv.Itoa(int(h.Sum32()))\n}", "func get6BCDFrom3Bytes(bytes []byte) int64 {\n\tnibble_one := (bytes[0] & 0xF0) >> 4\n\tnibble_two := bytes[0] & 0xF\n\tnibble_three := (bytes[1] & 0xF0) >> 4\n\tnibble_four := bytes[1] & 0xF\n\tnibble_five := (bytes[2] & 0xF0) >> 4\n\tnibble_six := bytes[2] & 0xF\n\n\treturn (int64(nibble_one) * 100000) + (int64(nibble_two) * 10000) + (int64(nibble_three) * 1000) + (int64(nibble_four) * 100) + (int64(nibble_five) * 10) + (int64(nibble_six))\n}", "func (n *Nonce) String() string {\n\tn.mtx.Lock()\n\tresult := strconv.FormatInt(n.n, 10)\n\tn.mtx.Unlock()\n\treturn result\n}", "func opI64ToStr(expr *CXExpression, fp int) {\n\toutB0 := FromStr(strconv.FormatInt(ReadI64(fp, expr.Inputs[0]), 10))\n\tWriteObject(GetOffset_str(fp, expr.Outputs[0]), outB0)\n}", "func (me TSAFTaxonomyCode) ToXsdtInteger() xsdt.Integer { return xsdt.Integer(me) }", "func float64ToDimValue(f float64) string {\n\t// Parameters below are the same used by Prometheus\n\t// see https://github.com/prometheus/common/blob/b5fe7d854c42dc7842e48d1ca58f60feae09d77b/expfmt/text_create.go#L450\n\t// SignalFx agent uses a different pattern\n\t// https://github.com/signalfx/signalfx-agent/blob/5779a3de0c9861fa07316fd11b3c4ff38c0d78f0/internal/monitors/prometheusexporter/conversion.go#L77\n\t// The important issue here is consistency with the exporter, opting for the\n\t// more common one used by Prometheus.\n\tswitch {\n\tcase f == 0:\n\t\treturn \"0\"\n\tcase f == 1:\n\t\treturn \"1\"\n\tcase math.IsInf(f, +1):\n\t\treturn \"+Inf\"\n\tdefault:\n\t\treturn strconv.FormatFloat(f, 'g', -1, 64)\n\t}\n}", "func opUI64ToStr(prgrm *CXProgram) {\n\texpr := prgrm.GetExpr()\n\tfp := prgrm.GetFramePointer()\n\n\toutB0 := FromStr(strconv.FormatUint(ReadUI64(fp, expr.Inputs[0]), 10))\n\tWriteObject(GetFinalOffset(fp, expr.Outputs[0]), outB0)\n}", "func SanitizeFrequency(frequency float64) uint64 {\n\t// 868.1 to 868100000 - but we will lose the decimals\n\tif frequency < 1000.0 {\n\t\tfrequency = frequency * 1000000\n\t}\n\n\t// 868400000000000 to 868400000\n\tif frequency > 1000000000 {\n\t\tfrequency = frequency / 1000000\n\t}\n\n\t// 869099976 to 869100000\n\tfrequency = math.Round(frequency/1000) * 1000\n\tfrequencyInt := uint64(frequency)\n\n\treturn frequencyInt\n}", "func (me TxsdRedefineTimeSyncTokenTypeComplexContentRestrictionSeedLength) String() string {\n\treturn xsdt.Integer(me).String()\n}", "func (kademliaID *KademliaID) String() string {\n\treturn hex.EncodeToString(kademliaID[0:IDLength])\n}", "func (kademliaID *KademliaID) String() string {\n\treturn hex.EncodeToString(kademliaID[0:IDLength])\n}", "func (kademliaID *KademliaID) String() string {\n\treturn hex.EncodeToString(kademliaID[0:IDLength])\n}" ]
[ "0.8041262", "0.57181907", "0.56364214", "0.5539708", "0.5407172", "0.5381648", "0.5340634", "0.5319151", "0.5249352", "0.522959", "0.5226018", "0.5112381", "0.5098673", "0.5098673", "0.50704056", "0.5027605", "0.50028676", "0.49748233", "0.49742544", "0.49554738", "0.49515212", "0.4915475", "0.4899223", "0.48939583", "0.48688835", "0.48543584", "0.48467207", "0.4829823", "0.4829446", "0.48167932", "0.4815582", "0.48089588", "0.47835582", "0.47722048", "0.4764844", "0.47549835", "0.47519705", "0.47519705", "0.47511756", "0.47486916", "0.47412178", "0.47397658", "0.47359115", "0.47352263", "0.4732732", "0.47259164", "0.4724235", "0.4722035", "0.4717265", "0.4712197", "0.47038049", "0.46890947", "0.46885383", "0.46748206", "0.4669194", "0.4665765", "0.46528542", "0.46420085", "0.46419638", "0.46384168", "0.4638355", "0.46281064", "0.462734", "0.4623002", "0.46227196", "0.4618217", "0.46139675", "0.45978546", "0.4593734", "0.45915332", "0.4584152", "0.45806363", "0.45798656", "0.4577491", "0.45770407", "0.4567949", "0.45678595", "0.45666027", "0.4566282", "0.45620704", "0.4561026", "0.4554127", "0.45490637", "0.45368096", "0.45295224", "0.452799", "0.45274007", "0.4513408", "0.45080003", "0.45034775", "0.45029688", "0.4499134", "0.44991314", "0.4498538", "0.4494844", "0.4494607", "0.44870818", "0.4484085", "0.4484085", "0.4484085" ]
0.85751027
0
FactoidToFactoshi takes a Factoid amount as a string and returns the value in factoids
func FactoidToFactoshi(amt string) uint64 { valid := regexp.MustCompile(`^([0-9]+)?(\.[0-9]+)?$`) if !valid.MatchString(amt) { return 0 } var total uint64 = 0 dot := regexp.MustCompile(`\.`) pieces := dot.Split(amt, 2) whole, _ := strconv.Atoi(pieces[0]) total += uint64(whole) * 1e8 if len(pieces) > 1 { a := regexp.MustCompile(`(0*)([0-9]+)$`) as := a.FindStringSubmatch(pieces[1]) part, _ := strconv.Atoi(as[0]) power := len(as[1]) + len(as[2]) total += uint64(part * 1e8 / int(math.Pow10(power))) } return total }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func FactoshiToFactoid(i uint64) string {\n\td := i / 1e8\n\tr := i % 1e8\n\tds := fmt.Sprintf(\"%d\", d)\n\trs := fmt.Sprintf(\"%08d\", r)\n\trs = strings.TrimRight(rs, \"0\")\n\tif len(rs) > 0 {\n\t\tds = ds + \".\"\n\t}\n\treturn fmt.Sprintf(\"%s%s\", ds, rs)\n}", "func AmountToString(n float64) string {\n return strconv.FormatFloat(n, 'f', 8, 64)\n}", "func makeFact(line *parser.Quad, resolveXID func(string) uint64) (rpc.Fact, error) {\n\txidOf := func(node interface{}, field string) (string, error) {\n\t\tswitch n := node.(type) {\n\t\tcase *parser.Entity:\n\t\t\treturn n.Value, nil\n\t\tcase *parser.QName:\n\t\t\treturn n.Value, nil\n\t\tdefault:\n\t\t\treturn \"\", fmt.Errorf(\"value %s not a valid type for field %s\", node, field)\n\t\t}\n\t}\n\tvar res rpc.Fact\n\tsubjectXID, err := xidOf(line.Subject, \"Subject\")\n\tif err != nil {\n\t\treturn rpc.Fact{}, err\n\t}\n\tres.Subject = resolveXID(subjectXID)\n\tpredicateXID, err := xidOf(line.Predicate, \"Predicate\")\n\tif err != nil {\n\t\treturn rpc.Fact{}, err\n\t}\n\tres.Predicate = resolveXID(predicateXID)\n\n\tresolveUnitLanguageID := func(xid string) uint64 {\n\t\tif len(xid) > 0 {\n\t\t\treturn resolveXID(xid)\n\t\t}\n\t\treturn 0\n\t}\n\tswitch t := line.Object.(type) {\n\tcase *parser.LiteralBool:\n\t\tres.Object = rpc.ABool(t.Value, resolveUnitLanguageID(t.Unit.Value))\n\tcase *parser.LiteralFloat:\n\t\tres.Object = rpc.AFloat64(t.Value, resolveUnitLanguageID(t.Unit.Value))\n\tcase *parser.LiteralInt:\n\t\tres.Object = rpc.AInt64(t.Value, resolveUnitLanguageID(t.Unit.Value))\n\tcase *parser.LiteralTime:\n\t\tres.Object = rpc.ATimestamp(t.Value,\n\t\t\tlogentry.TimestampPrecision(t.Precision),\n\t\t\tresolveUnitLanguageID(t.Unit.Value))\n\tcase *parser.LiteralString:\n\t\tres.Object = rpc.AString(t.Value, resolveUnitLanguageID(t.Language.Value))\n\tdefault:\n\t\tobjectXID, err := xidOf(line.Object, \"Object\")\n\t\tif err != nil {\n\t\t\treturn rpc.Fact{}, err\n\t\t}\n\t\tres.Object = rpc.AKID(resolveXID(objectXID))\n\t}\n\treturn res, nil\n}", "func (a amount) String() string {\n\treturn fmt.Sprintf(\"$%0.2f\", float64(a)/100.0)\n}", "func convertToSatoshi(btc []byte) uint64 {\n\n\ts := uint64(0)\n\tpoint := false\n\tdecimals := 0\n\tfor _, b := range btc {\n\t\tif b >= '0' && b <= '9' {\n\t\t\ts *= 10\n\t\t\ts += uint64(b - '0')\n\t\t\tif point {\n\t\t\t\tdecimals += 1\n\t\t\t\tif decimals >= 8 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t} else if '.' == b {\n\t\t\tpoint = true\n\t\t}\n\t}\n\tfor decimals < 8 {\n\t\ts *= 10\n\t\tdecimals += 1\n\t}\n\n\treturn s\n}", "func (bill Amount) ToUnitString(unit_name string) string {\n\tunit_name = strings.ToLower(unit_name)\n\tsetunit := -1\n\tif unit_name == \"mei\" {\n\t\tsetunit = 248\n\t}\n\tif unit_name == \"zhu\" {\n\t\tsetunit = 240\n\t}\n\tif unit_name == \"shuo\" {\n\t\tsetunit = 232\n\t}\n\tif unit_name == \"ai\" {\n\t\tsetunit = 224\n\t}\n\tif unit_name == \"miao\" {\n\t\tsetunit = 216\n\t}\n\tif setunit == -1 {\n\t\t// fin string\n\t\treturn bill.ToFinString()\n\t}\n\tbigunit := bill.ToUnitBigFloat(setunit)\n\tmeistr := bigunit.Text('f', 9)\n\tspx := strings.Split(meistr, \".\")\n\tif len(spx) == 2 {\n\t\tif len(spx[1]) == 9 {\n\t\t\tspx[1] = strings.TrimRight(spx[1], spx[1][8:])\n\t\t\tmeistr = strings.Join(spx, \".\")\n\t\t}\n\t}\n\treturn strings.TrimRight(strings.TrimRight(meistr, \"0\"), \".\")\n\n}", "func PriceToString(n float64) string {\n return strconv.FormatFloat(n, 'f', 3, 64)\n}", "func HelloQueryFacto(c echo.Context) error {\n\n\tid := c.QueryParam(\"id\") //id의 값만 보게 변경\n\n\t//strconv.Atoi idInt 변수에 입력\n\tidInt, strConverr := strconv.Atoi(id)\n\n\t// strConverr가 nil이면 factorial.GetFacto 응답하기로 변경 else 문 제거,\n\tif strConverr != nil {\n\t\tlog.Println(strConverr)\n\t\treturn c.String(http.StatusOK, \"Please input only number.\")\n\t}\n\n\t// GetFacto 입력값 int로 변경\n\t// strconv 대신 fmt.Sprintf 사용. -> 더 빠르다고 함\n\t// 다시 strconv 사용. -> fmt.Sprintf 는 타입 변환과 출력을 동시에 할때 빠르고, 여기처럼 함수에 넣어서 바로 사용할땐 strconv가 더 빠르다고 함\n\tresult := strconv.Itoa(factorial.GetFacto(idInt))\n\treturn c.String(http.StatusOK, result)\n}", "func ToUSD(cache Repository, name string, value float64, pure bool) (result float64, err error) {\n\tswitch {\n\tcase value == 0 || name == hitbtc.USD:\n\t\treturn value, nil\n\tcase name == hitbtc.BTC || name == hitbtc.ETH:\n\t\tBaseUsd := cache.GetPrice(name+hitbtc.USD, hitbtc.Exchange)\n\n\t\treturn value * BaseUsd, nil\n\t}\n\n\tsymbol, err := ToSymbol(cache, name)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tswitch symbol.Quote {\n\tcase hitbtc.USD:\n\t\tif !pure {\n\t\t\tBaseUsd := cache.GetPrice(symbol.Base+hitbtc.USD, hitbtc.Exchange)\n\n\t\t\treturn value * BaseUsd, err\n\t\t}\n\n\t\treturn value, err\n\tcase hitbtc.BTC:\n\t\tBaseBtc := cache.GetPrice(symbol.Base+hitbtc.BTC, hitbtc.Exchange)\n\t\tBtcUsd := cache.GetPrice(hitbtc.BTC+hitbtc.USD, hitbtc.Exchange)\n\n\t\tif !pure {\n\t\t\treturn value * BtcUsd * BaseBtc, err\n\t\t}\n\n\t\treturn value * BtcUsd, err\n\tcase hitbtc.ETH:\n\t\tBaseEth := cache.GetPrice(symbol.Base+hitbtc.ETH, hitbtc.Exchange)\n\t\tEthUsd := cache.GetPrice(hitbtc.ETH+hitbtc.USD, hitbtc.Exchange)\n\n\t\tif !pure {\n\t\t\treturn value * EthUsd * BaseEth, err\n\t\t}\n\n\t\treturn value * EthUsd, err\n\tdefault:\n\t\treturn value, nil\n\t}\n}", "func amount(n int) string {\n\treturn amountRange(n, 1, 120000)\n}", "func toSatoshi(v float64) uint64 {\n\treturn uint64(math.Round(v * 1e8))\n}", "func NewAmountFromFinString(finstr string) (*Amount, error) {\n\tfinstr = strings.ToUpper(finstr)\n\tfinstr = strings.Replace(finstr, \" \", \"\", -1) // Remove spaces\n\tfinstr = strings.Replace(finstr, \",\", \"\", -1) // Remove commas\n\tvar sig = 1\n\tif strings.HasPrefix(finstr, \"HCX\") {\n\t\tfinstr = string([]byte(finstr)[3:])\n\t} else if strings.HasPrefix(finstr, \"HAC\") {\n\t\tfinstr = string([]byte(finstr)[3:])\n\t} else if strings.HasPrefix(finstr, \"ㄜ\") {\n\t\tfinstr = string([]byte(finstr)[3:])\n\t}\n\t// negative\n\tif strings.HasPrefix(finstr, \"-\") {\n\t\tfinstr = string([]byte(finstr)[1:])\n\t\tsig = -1 // negative\n\t}\n\tvar main, dum, unit string\n\tvar main_num, dum_num *big.Int\n\tvar unit_num int\n\tvar e error\n\tvar ok bool\n\tpart := strings.Split(finstr, \":\")\n\tif len(part) != 2 {\n\t\treturn nil, fmt.Errorf(\"format error\")\n\t}\n\tunit = part[1]\n\tunit_num, e = strconv.Atoi(unit)\n\tif e != nil {\n\t\treturn nil, fmt.Errorf(\"format error\")\n\t}\n\tif unit_num < 0 || unit_num > 255 {\n\t\treturn nil, fmt.Errorf(\"format error\")\n\t}\n\tpart2 := strings.Split(part[0], \":\")\n\tif len(part2) < 1 || len(part2) > 2 {\n\t\treturn nil, fmt.Errorf(\"format error\")\n\t}\n\n\tmain = part2[0]\n\tmain_num, ok = new(big.Int).SetString(main, 10)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"format error\")\n\t}\n\tif len(part2) == 2 {\n\t\tdum = part2[1]\n\t\tdum_num, ok = new(big.Int).SetString(dum, 10)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"format error\")\n\t\t}\n\t}\n\t// Process decimal parts\n\tbigint0, _ := new(big.Int).SetString(\"0\", 10)\n\tbigint1, _ := new(big.Int).SetString(\"1\", 10)\n\tbigint10, _ := new(big.Int).SetString(\"10\", 10)\n\tdum_wide10 := 0\n\tif dum_num != nil && dum_num.Cmp(bigint0) == 1 {\n\t\tmover := dum_num.Div(dum_num, bigint10).Add(dum_num, bigint1)\n\t\tdum_wide10 = int(mover.Int64())\n\t\tif unit_num-dum_wide10 < 0 {\n\t\t\treturn nil, fmt.Errorf(\"format error\")\n\t\t}\n\t\tmain_num = main_num.Sub(main_num, mover)\n\t\tunit_num = unit_num - int(dum_wide10)\n\t}\n\t// negative\n\tif sig == -1 {\n\t\tmain_num = main_num.Neg(main_num)\n\t}\n\t// transformation\n\treturn NewAmountByBigIntWithUnit(main_num, unit_num)\n}", "func (me TSAFTaxonomyCode) String() string { return xsdt.Integer(me).String() }", "func (me TSAFmonetaryType) String() string { return xsdt.Decimal(me).String() }", "func franc(f int) *Money {\n\treturn &Money{\n\t\tamount: f,\n\t\tcurrency: \"CHF\",\n\t}\n}", "func QuarksToKin(amount int64) string {\n\tquarks := big.NewFloat(0)\n\tquarks.SetInt64(amount)\n\n\treturn new(big.Float).Quo(quarks, quarkCoeff).Text('f', 5)\n}", "func amountToNumber(amount string) (float64, error) {\n\tre := regexp.MustCompile(`\\$(\\d[\\d,]*[\\.]?[\\d{2}]*)`)\n\tmatches := re.FindStringSubmatch(amount)\n\tif matches == nil {\n\t\treturn 0.0, ErrBadLoadAmount\n\t}\n\tmatch := matches[1]\n\tamountFloat, err := strconv.ParseFloat(match, 64)\n\tif err != nil {\n\t\treturn 0.0, ErrBadLoadAmount\n\t}\n\treturn amountFloat, nil\n}", "func ConvertFixedPoint(amt string) (string, error) {\n\tvar v int64\n\tvar err error\n\tindex := strings.Index(amt, \".\")\n\tif index == 0 {\n\t\tamt = \"0\" + amt\n\t\tindex++\n\t}\n\tif index < 0 {\n\t\tv, err = strconv.ParseInt(amt, 10, 64)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tv *= 100000000 // Convert to Factoshis\n\t} else {\n\t\ttp := amt[:index]\n\t\tv, err = strconv.ParseInt(tp, 10, 64)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tv = v * 100000000 // Convert to Factoshis\n\n\t\tbp := amt[index+1:]\n\t\tif len(bp) > 8 {\n\t\t\tbp = bp[:8]\n\t\t}\n\t\tbpv, err := strconv.ParseInt(bp, 10, 64)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tfor i := 0; i < 8-len(bp); i++ {\n\t\t\tbpv *= 10\n\t\t}\n\t\tv += bpv\n\t}\n\treturn strconv.FormatInt(v, 10), nil\n}", "func toFahrenheit(t Celsius) Fahrenheit {\n\n\tvar temp Fahrenheit\n\tvar tt float32\n\ttt = (float32(t) * 1.8) + float32(32)\n\ttemp = Fahrenheit(tt)\n\treturn temp\n\n}", "func StringToAmount(s string) (massutil.Amount, error) {\n\ts1 := strings.Split(s, \".\")\n\tif len(s1) > 2 {\n\t\treturn massutil.ZeroAmount(), fmt.Errorf(\"illegal number format\")\n\t}\n\tvar sInt, sFrac string\n\t// preproccess integral part\n\tsInt = strings.TrimLeft(s1[0], \"0\")\n\tif len(sInt) == 0 {\n\t\tsInt = \"0\"\n\t}\n\t// preproccess fractional part\n\tif len(s1) == 2 {\n\t\tsFrac = strings.TrimRight(s1[1], \"0\")\n\t\tif len(sFrac) > 8 {\n\t\t\treturn massutil.ZeroAmount(), fmt.Errorf(\"precision is too high\")\n\t\t}\n\t}\n\tsFrac += strings.Repeat(\"0\", 8-len(sFrac))\n\n\t// convert\n\ti, err := strconv.ParseInt(sInt, 10, 64)\n\tif err != nil {\n\t\treturn massutil.ZeroAmount(), err\n\t}\n\tif i < 0 || uint64(i) > consensus.MaxMass {\n\t\treturn massutil.ZeroAmount(), fmt.Errorf(\"integral part is out of range\")\n\t}\n\n\tf, err := strconv.ParseInt(sFrac, 10, 64)\n\tif err != nil {\n\t\treturn massutil.ZeroAmount(), err\n\t}\n\tif f < 0 {\n\t\treturn massutil.ZeroAmount(), fmt.Errorf(\"illegal number format\")\n\t}\n\n\tu := safetype.NewUint128FromUint(consensus.MaxwellPerMass)\n\tu, err = u.MulInt(i)\n\tif err != nil {\n\t\treturn massutil.ZeroAmount(), err\n\t}\n\tu, err = u.AddInt(f)\n\tif err != nil {\n\t\treturn massutil.ZeroAmount(), err\n\t}\n\ttotal, err := massutil.NewAmount(u)\n\tif err != nil {\n\t\treturn massutil.ZeroAmount(), err\n\t}\n\treturn total, nil\n}", "func KToF(k Kelvin) Fahrenheit { return CToF(KToC(k)) }", "func ChuckFact() string {\n\tresp, err := http.Get(\"https://api.chucknorris.io/jokes/random\")\n\tif err != nil {\n\t\treturn \"I had a problem...\"\n\t}\n\tdefer resp.Body.Close()\n\n\tbodyBytes, err := ioutil.ReadAll(resp.Body)\n\n\tvar fact chuck\n\tjson.Unmarshal([]byte(bodyBytes), &fact)\n\treturn fact.Value\n}", "func ToScalar(pubkey ecdsa.PublicKey) string {\n\tpubkeyX := fmt.Sprintf(\"%x\", pubkey.X)\n\t// pubkeyY := fmt.Sprintf(\"%x\", keyPair.PublicKey.Y)\n\t// if pubkeyY is even => prefix is 02\n\t// if pubkeyY is odd => prefix is 03\n\treturn \"02\" + pubkeyX\n}", "func HelloQueryFactoJSON(c echo.Context) error {\n\n\tid := c.QueryParam(\"id\")\n\tidInt, err := strconv.Atoi(id)\n\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn c.String(http.StatusOK, \"Please input only number.\")\n\t}\n\n\tfactoResultJSON := new(ResponseJSON)\n\n\tfactoResultJSON.Input = c.QueryParam(\"id\")\n\tfactoResultJSON.Data = fmt.Sprintf(\"%d\", factorial.GetFacto(idInt)) //Same with test:= ResponseJSON{}\n\n\treturn c.JSON(http.StatusOK, factoResultJSON)\n}", "func (d Decimal) StringFixedCash(interval uint8) string {\n\trounded := d.RoundCash(interval)\n\treturn rounded.string(false)\n}", "func AmountToString(m int64) (string, error) {\n\tif m > massutil.MaxAmount().IntValue() {\n\t\treturn \"\", fmt.Errorf(\"amount is out of range: %d\", m)\n\t}\n\tu, err := safetype.NewUint128FromInt(m)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tu, err = u.AddUint(consensus.MaxwellPerMass)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\ts := u.String()\n\tsInt, sFrac := s[:len(s)-8], s[len(s)-8:]\n\tsFrac = strings.TrimRight(sFrac, \"0\")\n\ti, err := strconv.Atoi(sInt)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tsInt = strconv.Itoa(i - 1)\n\tif len(sFrac) > 0 {\n\t\treturn sInt + \".\" + sFrac, nil\n\t}\n\treturn sInt, nil\n}", "func (kh kelvinHandler) ToFahrenheit(temp float64) float64 {\n\treturn (kh.ToCelsius(temp) * fahrenheitMultiplier) + FahrenheitBase\n}", "func ConvertStringDollarsToPennies(amount string) (int64, error) {\n\t// check if amount can convert to a valid float\n\t_, err := strconv.ParseFloat(amount, 64)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// split the value on \".\"\n\tgroups := strings.Split(amount, \".\")\n\n\t// if there is no . result will still be\n\t// captured here\n\tresult := groups[0]\n\n\t// base string\n\tr := \"\"\n\n\t// handle the data after the \".\"\n\tif len(groups) == 2 {\n\t\tif len(groups[1]) != 2 {\n\t\t\treturn 0, errors.New(\"invalid cents\")\n\t\t}\n\t\tr = groups[1]\n\t}\n\n\t// pad with 0, this will be\n\t// 2 0's if there was no .\n\tfor len(r) < 2 {\n\t\tr += \"0\"\n\t}\n\n\tresult += r\n\n\t// convert it to an int\n\treturn strconv.ParseInt(result, 10, 64)\n}", "func (cti CubicThousandthInch) ToCubicFeet() CubicFeet {\n\tcubicThousandthInchPerCubicFoot := thousandthInchPerFoot * thousandthInchPerFoot * thousandthInchPerFoot\n\treturn CubicFeet(float64(cti) / float64(cubicThousandthInchPerCubicFoot))\n}", "func (m money) String() string {\n\ts := strconv.Itoa(int(m))\n\tvar cents, dollars string\n\tif len(s) > 2 {\n\t\tdollars = s[0 : len(s)-2]\n\t\tcents = s[len(dollars):len(s)]\n\t} else {\n\t\tdollars = \"0\"\n\t\tcents = s\n\t}\n\n\t// Add a comma at the thousanths place in reverse\n\tchars := make([]byte, 0, len(dollars)+((len(dollars)-1)/3))\n\tfor i := len(dollars) - 1; i >= 0; i-- {\n\t\tchars = append(chars, dollars[i])\n\t\tif n := len(dollars) - i; i > 0 && n >= 3 && n%3 == 0 {\n\t\t\tchars = append(chars, byte(','))\n\t\t}\n\t}\n\n\t// Swap the slice\n\tfor i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {\n\t\tchars[i], chars[j] = chars[j], chars[i]\n\t}\n\n\treturn string(chars) + \".\" + cents\n}", "func (text *TextHashValue) ToString() string {\n\tv := strconv.FormatInt(int64(text.Value), 10)\n\treturn v\n}", "func Satoshi() Fixed8 {\n\treturn Fixed8(1)\n}", "func moneyToString(cents int, thousandsSep, decimalSep string) string {\n\tcentsStr := fmt.Sprintf(\"%03d\", cents) // Pad to 3 digits\n\tcentsPart := centsStr[len(centsStr)-2:]\n\trest := centsStr[:len(centsStr)-2]\n\tvar parts []string\n\tfor len(rest) > 3 {\n\t\tparts = append(parts, rest[len(rest)-3:])\n\t\trest = rest[:len(rest)-3]\n\t}\n\tif len(rest) > 0 {\n\t\tparts = append(parts, rest)\n\t}\n\trevParts := make([]string, 0, len(parts))\n\tfor i := len(parts) - 1; i >= 0; i-- {\n\t\trevParts = append(revParts, parts[i])\n\t}\n\tvar buf bytes.Buffer\n\tbuf.WriteString(strings.Join(revParts, thousandsSep))\n\tbuf.WriteString(decimalSep)\n\tbuf.WriteString(centsPart)\n\treturn buf.String()\n}", "func AmountToString(amount *Amount) string {\n\treturn fmt.Sprintf(\"%d\", amount.Amount)\n}", "func cashDiscount(s string) string {\n\treturn addFees(s) + \":cashDiscount\"\n}", "func facto(x uint) uint {\n\tif x == 1 {\n\t\treturn 1\n\t}\n\treturn x * facto(x-1)\n}", "func itod(i uint) string {\n\tif i == 0 {\n\t\treturn \"0\"\n\t}\n\n\t// Assemble decimal in reverse order.\n\tvar b [32]byte\n\tbp := len(b)\n\tfor ; i > 0; i /= 10 {\n\t\tbp--\n\t\tb[bp] = byte(i%10) + '0'\n\t}\n\n\treturn string(b[bp:])\n}", "func (bq BaseQuantity) ToUnitDollarString() string {\n\t// drop the numbers after two decimal points to make sure Sprintf doesn't round up\n\t// then convert to dollars\n\td := math.Floor(float64(bq)/100.0) / 100.0\n\ts := fmt.Sprintf(\"$%.2f\", d)\n\treturn s\n}", "func (a Amount) String() string {\n\tvar n float64\n\tvar suffix string\n\tif a.Quantity >= 1000000 {\n\t\tn = a.Quantity / 1000000\n\t\tsuffix = \"M\"\n\t} else if a.Quantity >= 1000 {\n\t\tn = a.Quantity / 1000\n\t\tsuffix = \"K\"\n\t} else {\n\t\tn = a.Quantity\n\t}\n\tnum := trimDecimal(n)\n\tif a.Currency != \"\" {\n\t\treturn fmt.Sprintf(\"%s%s %s\", num, suffix, a.Currency)\n\t}\n\treturn fmt.Sprint(num, suffix)\n}", "func FToK(f Fahrenheit) Kelvin {\n\treturn Kelvin((f + 459.67) * 5 / 9)\n}", "func parseFactoid(row []interface{}, out chan *factoids.Factoid) {\n\tvalues := parseMultipleValues(toString(row[cValue]))\n\tc := &factoids.FactoidStat{\n\t\tNick: bot.Nick(toString(row[cCreator])),\n\t\tChan: \"\",\n\t\tCount: 1,\n\t}\n\tc.Timestamp, _ = parseTimestamp(row[cCreated])\n\tm := &factoids.FactoidStat{Chan: \"\", Count: 0}\n\tif ts, ok := parseTimestamp(row[cModified]); ok {\n\t\tm.Timestamp = ts\n\t\tm.Nick = bot.Nick(toString(row[cModifier]))\n\t\tm.Count = 1\n\t} else {\n\t\tm.Timestamp = c.Timestamp\n\t\tm.Nick = c.Nick\n\t}\n\tp := &factoids.FactoidPerms{\n\t\tparseReadOnly(row[cAccess]),\n\t\tbot.Nick(toString(row[cCreator])),\n\t}\n\tfor _, val := range values {\n\t\tt, v := parseValue(toString(row[cKey]), toString(row[cRel]), val)\n\t\tif v == \"\" {\n\t\t\t// skip the many factoids with empty values.\n\t\t\tcontinue\n\t\t}\n\t\tout <- &factoids.Factoid{\n\t\t\tKey: toString(row[cKey]), Value: v, Type: t, Chance: 1.0,\n\t\t\tCreated: c, Modified: m, Accessed: c, Perms: p,\n\t\t\tId: bson.NewObjectId(),\n\t\t}\n\t}\n}", "func SI(value float64, unit string) string {\n\tvalue, prefix := reduce(value)\n\treturn fmt.Sprintf(\"%6.2f %s%s\", value, prefix, unit)\n}", "func (me TSAFPTPortugueseVatNumber) String() string { return xsdt.Integer(me).String() }", "func ToWei(iamount interface{}, decimals int) *big.Int {\n amount := decimal.NewFromFloat(0)\n switch v := iamount.(type) {\n case string:\n amount, _ = decimal.NewFromString(v)\n case int:\n amount = decimal.NewFromInt(int64(v))\n case float64:\n amount = decimal.NewFromFloat(v)\n case int64:\n amount = decimal.NewFromFloat(float64(v))\n case decimal.Decimal:\n amount = v\n case *decimal.Decimal:\n amount = *v\n }\n\n mul := decimal.NewFromFloat(float64(10)).Pow(decimal.NewFromFloat(float64(decimals)))\n result := amount.Mul(mul)\n\n wei := new(big.Int)\n wei.SetString(result.String(), 10)\n\n return wei\n}", "func (me Tangle360Type) String() string { return xsdt.Double(me).String() }", "func (f *FactoidTransaction) Decode(data []byte) (i int, err error) {\n\tif len(data) < TransactionTotalMinLen {\n\t\treturn 0, fmt.Errorf(\"insufficient length\")\n\t}\n\n\t// Decode header\n\tversion, i := varintf.Decode(data)\n\tif i < 0 {\n\t\treturn 0, fmt.Errorf(\"version bytes invalid\")\n\t}\n\tf.Version = version\n\n\tmsdata := make([]byte, 8)\n\t// TS + counts length check\n\tif len(data) < i+(6+3) {\n\t\treturn 0, fmt.Errorf(\"not enough bytes to decode tx\")\n\t}\n\tcopy(msdata[2:], data[i:i+6])\n\tms := binary.BigEndian.Uint64(msdata)\n\tf.TimestampSalt = time.Unix(0, int64(ms)*1e6)\n\ti += 6\n\tinputCount := uint8(data[i])\n\ti += 1\n\tfctOutputCount := uint8(data[i])\n\ti += 1\n\tecOutputCount := uint8(data[i])\n\ti += 1\n\n\t// Decode the body\n\n\t// Decode the inputs\n\tf.FCTInputs = make([]FactoidTransactionIO, inputCount)\n\tread, err := factoidTransactionIOs(f.FCTInputs).Decode(data[i:])\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ti += read\n\n\t// Decode the FCT Outputs\n\tf.FCTOutputs = make([]FactoidTransactionIO, fctOutputCount)\n\tread, err = factoidTransactionIOs(f.FCTOutputs).Decode(data[i:])\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ti += read\n\n\t// Decode the EC Outputs\n\tf.ECOutputs = make([]FactoidTransactionIO, ecOutputCount)\n\tread, err = factoidTransactionIOs(f.ECOutputs).Decode(data[i:])\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ti += read\n\n\t// All data minus the signatures is the needed binary data to compute\n\t// the txid\n\tledgerData := data[:i]\n\n\t// Decode the signature blocks, one per input\n\tf.Signatures = make([]FactoidTransactionSignature, len(f.FCTInputs))\n\tfor c := uint8(0); c < uint8(len(f.FCTInputs)); c++ {\n\t\t// f.Signatures[i] = new(FactoidTransactionSignature)\n\t\tread, err := f.Signatures[c].Decode(data[i:])\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ti += read\n\t}\n\n\ttxid, err := f.computeTransactionID(ledgerData)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// If the txid is already set, validate the txid\n\tif f.TransactionID != nil {\n\t\tif *f.TransactionID != txid {\n\t\t\treturn 0, fmt.Errorf(\"invalid txid\")\n\t\t}\n\t}\n\n\tf.TransactionID = &txid\n\n\treturn i, err\n}", "func (bq BaseQuantity) ToUnitFloatString() string {\n\td := float64(bq) / 10000.0\n\ts := fmt.Sprintf(\"%.4f\", d)\n\treturn s\n}", "func IntPriceToString(p int) string {\n\treturn fmt.Sprintf(\"£%.4f\", float64(p)/10000.0)\n}", "func conv(n float64) uint64 {\n\ts := fmt.Sprintf(\"%.0f\", n)\n\tresult, _ := strconv.ParseUint(s, 10, 64)\n\treturn result\n}", "func (bill Amount) ToMeiString() string {\n\treturn bill.ToUnitString(\"mei\")\n}", "func mojito(needle int32, base int) byte {\n\treturn pick(\n\t\tingredients[Mojito].haystack,\n\t\tingredients[Mojito].charset,\n\t\ttransform(needle, -65, 32),\n\t\tbase,\n\t\t14, 22,\n\t)\n}", "func KinToQuarks(val string) (int64, error) {\n\tx, _, err := big.ParseFloat(val, 10, 64, big.ToZero)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tr, accuracy := new(big.Float).Mul(x, quarkCoeff).Int64()\n\tif accuracy != big.Exact {\n\t\treturn 0, errors.New(\"value cannot be represented with quarks\")\n\t}\n\n\treturn r, nil\n}", "func FdxToFountain(in io.Reader, out io.Writer) error {\n\tsrc, err := ioutil.ReadAll(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdocument, err := fdx.Parse(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Fprintf(out, \"%s\", document.String())\n\treturn nil\n}", "func toFreq(s semi, tonic freq) freq {\n\treturn tonic * freq(math.Pow(root12, float64(s)))\n}", "func (f Fahrenheit) String() string {\n\treturn fmt.Sprintf(\"%.2f F\", float32(f))\n}", "func HashToScalar(msg []byte) coconutGo.Attribute {\n\th := sha256.New()\n\th.Write(msg)\n\tdigest := h.Sum([]byte{})\n\n\tpadSize := 64 - h.Size()\n\tvar bytes [64]byte\n\tcopy(bytes[64-padSize:], digest)\n\n\treturn utils.ScalarFromBytesWide(bytes)\n}", "func dollars(cents int64) string {\n\t// Get the value in dollars.\n\tdollars := float64(cents) / 100\n\n\t// Initialize the buffer to store the string result.\n\tvar buf bytes.Buffer\n\n\t// Check for a negative value.\n\tif dollars < 0 {\n\t\tbuf.WriteString(\"-\")\n\t\t// Convert the negative value to a positive value.\n\t\t// The code below can only handle positive values.\n\t\tdollars = 0 - dollars\n\t}\n\tbuf.WriteString(\"$\")\n\n\t// Convert the dollar value into a string and split it into a\n\t// integer and decimal. This is done so that commas can be added\n\t// to the integer.\n\tvar (\n\t\tf = strconv.FormatFloat(dollars, 'f', -1, 64)\n\t\ts = strings.Split(f, \".\")\n\t\tinteger = s[0]\n\n\t\t// The value may or may not have a decimal. Default to 0.\n\t\tdecimal = \".00\"\n\t)\n\tif len(s) > 1 {\n\t\t// The value includes a decimal. Overwrite the default.\n\t\tdecimal = \".\" + s[1]\n\t}\n\n\t// Write the integer to the buffer one character at a time. Commas\n\t// are inserted in their appropriate places.\n\t//\n\t// Examples\n\t// \"100000\" to \"100,000\"\n\t// \"1000000\" to \"1,000,000\"\n\tfor i, c := range integer {\n\t\t// A comma should be inserted if the character index is divisible\n\t\t// by 3 when counting from the right side of the string.\n\t\tdivByThree := (len(integer)-i)%3 == 0\n\n\t\t// A comma should never be inserted for the first character.\n\t\t// Ex: \"100000\" should not be \",100,000\"\n\t\tif divByThree && i > 0 {\n\t\t\tbuf.WriteString(\",\")\n\t\t}\n\n\t\t// Write the character to the buffer.\n\t\tbuf.WriteRune(c)\n\t}\n\n\t// Write the decimal to the buffer.\n\tbuf.WriteString(decimal)\n\n\treturn buf.String()\n}", "func getMoneyAmount(n int) int {\n \n}", "func (me TSAFPTAccountingPeriod) String() string { return xsdt.Integer(me).String() }", "func convertTemperature(fromUOM, toUOM string, value float64) float64 {\n\tfromUOM = resolveTemperatureSynonyms(fromUOM)\n\ttoUOM = resolveTemperatureSynonyms(toUOM)\n\tif fromUOM == toUOM {\n\t\treturn value\n\t}\n\t// convert to Kelvin\n\tswitch fromUOM {\n\tcase \"F\":\n\t\tvalue = (value-32)/1.8 + 273.15\n\tcase \"C\":\n\t\tvalue += 273.15\n\tcase \"Rank\":\n\t\tvalue /= 1.8\n\tcase \"Reau\":\n\t\tvalue = value*1.25 + 273.15\n\t}\n\t// convert from Kelvin\n\tswitch toUOM {\n\tcase \"F\":\n\t\tvalue = (value-273.15)*1.8 + 32\n\tcase \"C\":\n\t\tvalue -= 273.15\n\tcase \"Rank\":\n\t\tvalue *= 1.8\n\tcase \"Reau\":\n\t\tvalue = (value - 273.15) * 0.8\n\t}\n\treturn value\n}", "func (me TSAFdecimalType) String() string { return xsdt.Decimal(me).String() }", "func toPluralCountValue(in any) any {\n\tk := reflect.TypeOf(in).Kind()\n\tswitch {\n\tcase hreflect.IsFloat(k):\n\t\tf := cast.ToString(in)\n\t\tif !strings.Contains(f, \".\") {\n\t\t\tf += \".0\"\n\t\t}\n\t\treturn f\n\tcase k == reflect.String:\n\t\tif _, err := cast.ToFloat64E(in); err == nil {\n\t\t\treturn in\n\t\t}\n\t\t// A non-numeric value.\n\t\treturn nil\n\tdefault:\n\t\tif i, err := cast.ToIntE(in); err == nil {\n\t\t\treturn i\n\t\t}\n\t\treturn nil\n\t}\n}", "func (t *TX) Amount() uint64 {\n\ts := strings.Split(t.Quantity, \" \")\n\tf, _ := strconv.ParseFloat(s[0], 64)\n\treturn uint64(f * 1e4)\n}", "func (c card) toStr() string {\n\treturn c.value + \" of \" + c.house\n}", "func ToString(h H3Index) string {\n\treturn strconv.FormatUint(uint64(h), 16)\n}", "func ToString(h H3Index) string {\n\treturn strconv.FormatUint(uint64(h), 16)\n}", "func StringToTokenValue(input string, decimals uint8) (*big.Int, error) {\n\toutput := big.NewInt(0)\n\tif input == \"\" {\n\t\treturn output, nil\n\t}\n\n\t// Count the number of items after the decimal point.\n\tparts := strings.Split(input, \".\")\n\tvar additionalZeros int\n\tif len(parts) == 2 {\n\t\t// There is a decimal place.\n\t\tadditionalZeros = int(decimals) - len(parts[1])\n\t} else {\n\t\t// There is not a decimal place.\n\t\tadditionalZeros = int(decimals)\n\t}\n\t// Remove the decimal point.\n\ttmp := strings.ReplaceAll(input, \".\", \"\")\n\t// Add zeros to ensure that there are an appropriate number of decimals.\n\ttmp += strings.Repeat(\"0\", additionalZeros)\n\n\t// Set the output\n\toutput.SetString(tmp, 10)\n\n\treturn output, nil\n}", "func (c Currency) Ftoa() []byte {\n\treturn c.FtoaAppend(nil)\n}", "func FToK(f Fahrenheit) Kelvin { return Kelvin(((f - 32.0) * 5.0 / 9.0) + 273.15) }", "func (node *Node) CallFaucetContract(walletAddress common.Address) common.Hash {\n\treturn node.createSendingMoneyTransaction(walletAddress)\n}", "func FormatDecimalAmount(locale string) pongo2.FilterFunction {\n\tl := loc.Get(locale)\n\tcName := \"GBP\"\n\tif l != nil {\n\t\tcName = l.CurrencyCode\n\t}\n\tcurrency := c.Get(cName)\n\tdefaultDigits := currency.DecimalDigits\n\treturn func(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {\n\n\t\tlog.Tracef(\"[FormatDecimalAmount] 000 IN: %s PARAM: %s LOCALE: %d\", in.String(), param.String(), locale)\n\n\t\tif len(in.String()) == 0 {\n\t\t\treturn pongo2.AsValue(\"\"), nil\n\t\t}\n\n\t\tfAmount, err := strconv.ParseFloat(in.String(), 64)\n\t\tif err != nil {\n\t\t\treturn nil, &pongo2.Error{\n\t\t\t\tSender: \"filterFormatDecimalAmount\",\n\t\t\t\tErrorMsg: fmt.Sprintf(\"Error formatting value - not parseable '%v': error: %s\", in, err),\n\t\t\t}\n\t\t}\n\n\t\tdigits := defaultDigits\n\t\tif param.IsInteger() {\n\t\t\tdigits = param.Integer()\n\t\t\tlog.Tracef(\"[FormatDecimalAmount] IN: %s PARAM: %s LOCALE: %s DIGITS: %d\", in.String(), param.String(), locale, digits)\n\t\t} else if param.IsString() && len(param.String()) > 0 {\n\t\t\tcName = param.String()\n\t\t\tcurrency := c.Get(cName)\n\t\t\tlog.Tracef(\"[FormatDecimalAmount] IN: %s PARAM: %s LOCALE: %d CURRENCY: %s DIGITS: %d\", in.String(), param.String(), locale, cName, digits)\n\t\t\tdigits = currency.DecimalDigits\n\t\t}\n\n\t\tlog.Tracef(\"[FormatDecimalAmount] IN: %s PARAM: %s LOCALE: %d DIGITS: %d\", in.String(), param.String(), locale, digits)\n\n\t\tif digits > 0 {\n\t\t\treturn pongo2.AsValue(strconv.FormatFloat(fAmount, 'f', digits, 64)), nil\n\t\t}\n\t\treturn pongo2.AsValue(strconv.FormatInt(int64(fAmount), 10)), nil\n\t}\n}", "func getMoney(name, token string) money {\n\ttokens := strings.Split(token, \":\")\n\tn := tokens[1]\n\tstart, _ := strconv.Atoi(tokens[2])\n\tstop, _ := strconv.Atoi(tokens[3])\n\n\tvar feesOnly, cashDiscount bool\n\tvar add, txfeeRate int\n\tvar mult, flatfeeRate float64\n\tfor i := range tokens {\n\t\tswitch tokens[i] {\n\t\tcase \"add\":\n\t\t\tadd, _ = strconv.Atoi(tokens[i+1])\n\t\tcase \"mult\":\n\t\t\tmult, _ = strconv.ParseFloat(tokens[i+1], 64)\n\t\tcase \"txfee\":\n\t\t\ttxfeeRate, _ = strconv.Atoi(tokens[i+1])\n\t\tcase \"flatfee\":\n\t\t\tflatfeeRate, _ = strconv.ParseFloat(tokens[i+1], 64)\n\t\tcase \"fees\":\n\t\t\tfeesOnly = true\n\t\tcase \"cashDiscount\":\n\t\t\tcashDiscount = true\n\t\t}\n\t}\n\n\tif _, ok := testCache[name]; !ok {\n\t\ttestCache[name] = map[string]money{}\n\t}\n\n\tvar result money\n\tif m, ok := testCache[name][n]; ok {\n\t\tresult = m\n\t} else {\n\t\tresult = newMoney(start, stop)\n\t\ttestCache[name][n] = result\n\t}\n\n\tresult = result.mult(mult).add(add)\n\n\ttxfee := money(txfeeRate)\n\n\tvar flatfee money\n\tif flatfeeRate > 0 {\n\t\tflatfee = result.mult(flatfeeRate)\n\t}\n\n\tif feesOnly {\n\t\treturn txfee.add(int(flatfee))\n\t}\n\tif cashDiscount {\n\t\tflatfee = -flatfee\n\t\ttxfee = -txfee\n\t}\n\n\treturn result.add(int(txfee)).add(int(flatfee))\n}", "func (n *N36) Ntoi(s string) (uint64, error) {\n\tvar r uint64\n\tbase := len(n.charset)\n\tfbase := float64(base)\n\tl := len(s)\n\n\tr = 0\n\n\tfor i := 0; i < l; i++ {\n\t\tn := strings.Index(n.charset, s[i:i+1])\n\n\t\tif n < 0 {\n\t\t\treturn 0, errors.New(\"n36.Ntoi: character not part of charset\")\n\t\t}\n\n\t\t//n * base^(l-i-1) + r\n\t\tr = uint64(n)*uint64(math.Pow(fbase, float64(l-i)-1)) + r\n\t}\n\n\treturn uint64(r), nil\n}", "func ToF(str string) float64 {\n\tval, err := strconv.ParseFloat(str, 64)\n\tL.IsError(err, str)\n\treturn val\n}", "func (f *Feature) ValueOf(cat Category) string {\n\tif f.Kind != Feature_CATEGORICAL || !IsCat(cat) {\n\t\treturn \"?\"\n\t}\n\n\tpos := int(cat)\n\tif f.Strategy == Feature_IDENTITY {\n\t\treturn strconv.Itoa(pos)\n\t}\n\n\tif pos < len(f.Vocabulary) {\n\t\treturn f.Vocabulary[pos]\n\t}\n\n\tif n := pos - len(f.Vocabulary); n < int(f.HashBuckets) {\n\t\treturn \"#\" + strconv.Itoa(n)\n\t}\n\n\treturn \"?\"\n}", "func WeiToEth(wei *big.Int) (*big.Float, error) {\n\tvar (\n\t\tok bool\n\t\tchecks = make([]bool, 0)\n\t)\n\n\tweiLocal, ok := big.NewFloat(0).SetString(wei.String())\n\tchecks = append(checks, ok)\n\n\tdivider, ok := big.NewFloat(0).SetString(WeiEth.String())\n\tchecks = append(checks, ok)\n\n\tethLocal := big.NewFloat(0).Quo(weiLocal, divider)\n\tif any(checks) {\n\t\treturn nil, ErrTranslation\n\t}\n\n\treturn ethLocal, nil\n}", "func ToSymbol(cache Repository, currency string) (symbol *hitbtc.Symbol, err error) {\n\tif len(currency) >= 6 {\n\t\tsymbol = cache.GetSymbol(currency, hitbtc.Exchange).(*hitbtc.Symbol)\n\t\tif symbol.ID == \"\" {\n\t\t\treturn nil, hitbtc.ErrSymbolNotFound\n\t\t}\n\n\t\treturn\n\t}\n\n\tif util.Contains(hitbtcCurrencies, currency) {\n\t\tsymbol = &hitbtc.Symbol{\n\t\t\tBase: currency,\n\t\t\tQuote: hitbtc.USD,\n\t\t}\n\n\t\tif symbol.Base == hitbtc.USD {\n\t\t\tsymbol.Base = hitbtc.BTC\n\t\t}\n\n\t\tsymbol.ID = symbol.Base + symbol.Quote\n\n\t\treturn\n\t}\n\n\tfor _, base := range hitbtcCurrencies {\n\t\tsymbol = cache.GetSymbol(currency+base, hitbtc.Exchange).(*hitbtc.Symbol)\n\t\tif symbol.ID != \"\" {\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn nil, hitbtc.ErrCurrencyNotFound\n}", "func FountainToOSF(in io.Reader, out io.Writer) error {\n\tsrc, err := ioutil.ReadAll(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdocument, err := fountain.Parse(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tnewDoc := fountainToOSF(document)\n\tsrc, err = newDoc.ToXML()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Fprintf(out, \"%s\", src)\n\treturn nil\n}", "func KtoF(k Kalvin) Fahrenheit {\n\tif k < AbsoluteZeroK {\n\t\tpanic(\"Your input cannot be below absolute zero.\")\n\t}\n\n\t// Conversation formula\n\t// (t°K - 273.15) * 9/5 + 32\n\treturn Fahrenheit(round((float64(k)-273.15)*1.8+32, 100))\n}", "func writeIETFScalarJSON(i any) any {\n\tswitch reflect.ValueOf(i).Kind() {\n\tcase reflect.Uint64, reflect.Int64, reflect.Float64:\n\t\treturn fmt.Sprintf(\"%v\", i)\n\t}\n\treturn i\n}", "func toInt(card z.Card) int {\n\tresult := MapRankToInt[card.Rank]*10 + MapSuitToInt[card.Suit]\n\treturn result\n}", "func toInt(card z.Card) int {\n\tresult := MapRankToInt[card.Rank]*10 + MapSuitToInt[card.Suit]\n\treturn result\n}", "func (me TSAFPTTransactionID) String() string { return xsdt.String(me).String() }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CreateZebraFotaArtifactFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewZebraFotaArtifact(), nil\n}", "func (blob *Blob) FN(sum string) string {\n\treturn fmt.Sprintf(\"%016x_%s\", blob.Time.UnixNano(), sum[:16])\n}", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9.0/5.0 + 32.0) }", "func (c Cents) ToDollarString() string {\n\td := float64(c) / 100.0\n\ts := fmt.Sprintf(\"$%.2f\", d)\n\treturn s\n}", "func siacoinString(siacoins types.Currency) string {\n\tif siacoins.Cmp(types.NewCurrency64(0)) == 0 {\n\t\treturn \"0 SC\"\n\t}\n\n\tcoinStr := siacoins.String()\n\n\tunitIndex := (len(coinStr) - 1) / 3\n\n\tif unitIndex >= len(coinPostfixes) {\n\t\tunitIndex = len(coinPostfixes) - 1\n\t}\n\n\tdecPoint := len(coinStr) - (unitIndex * 3)\n\n\tpostStr := coinStr[decPoint:]\n\tif len(postStr) > 6 {\n\t\tpostStr = postStr[:6]\n\t}\n\n\treturn fmt.Sprintf(\"%s.%s %s\", coinStr[:decPoint], postStr, coinPostfixes[unitIndex])\n}", "func toAtoms(v float64) uint64 {\n\treturn uint64(math.Round(v * conventionalConversionFactor))\n}", "func makeCosmosObject(cosmosType string, value string) reflect.Value {\n\tif cosmosType == \"types.Dec\" {\n\t\tdec := sdk.MustNewDecFromStr(value)\n\t\treturn reflect.ValueOf(dec)\n\t}\n\n\tif cosmosType == \"types.Coin\" {\n\t\tcoin, err := sdk.ParseCoin(value)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn reflect.ValueOf(coin)\n\t}\n\n\tif cosmosType == \"types.AccAddress\" {\n\t\taddress, err := sdk.AccAddressFromBech32(value)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn reflect.ValueOf(address)\n\t}\n\n\treturn reflect.ValueOf(value)\n}", "func (me TSAFPTUNNumber) String() string { return xsdt.String(me).String() }", "func CToF(c Celsius) Farenheit { return Farenheit(c*9/5 + 32) }" ]
[ "0.7521287", "0.53579456", "0.5102894", "0.5050258", "0.50151306", "0.49723515", "0.495978", "0.4955872", "0.4860711", "0.48466676", "0.48427755", "0.47854778", "0.46699467", "0.46629822", "0.46406147", "0.462473", "0.4571831", "0.45697492", "0.45567185", "0.4553939", "0.45402402", "0.45274466", "0.45093316", "0.45026937", "0.44893968", "0.44880673", "0.4472868", "0.44668695", "0.44616055", "0.4430011", "0.44298092", "0.4420842", "0.4417579", "0.4415225", "0.44119662", "0.44054517", "0.43743584", "0.43719634", "0.43479556", "0.43352002", "0.43256286", "0.43165773", "0.42846632", "0.4284424", "0.42764544", "0.4268609", "0.42601073", "0.42530775", "0.42478576", "0.4247711", "0.42449096", "0.42419297", "0.42353663", "0.42353478", "0.42314237", "0.4227224", "0.42262548", "0.42201713", "0.42095456", "0.41997388", "0.41945058", "0.41925222", "0.41918033", "0.4189965", "0.41852427", "0.41852427", "0.4183093", "0.41828725", "0.41823882", "0.41728833", "0.41620195", "0.4158827", "0.41541988", "0.41535133", "0.41482535", "0.41476455", "0.41379407", "0.4130236", "0.41213024", "0.41146845", "0.4112412", "0.4112412", "0.4110944", "0.4105119", "0.4105119", "0.4105119", "0.4105119", "0.4105119", "0.4105119", "0.4105119", "0.4105119", "0.41019902", "0.40990072", "0.4091836", "0.4091564", "0.40906465", "0.40811753", "0.40799603", "0.40782085", "0.40770733" ]
0.7781455
0
milliTime returns a 6 byte slice representing the unix time in milliseconds
func milliTime() (r []byte) { buf := new(bytes.Buffer) t := time.Now().UnixNano() m := t / 1e6 binary.Write(buf, binary.BigEndian, m) return buf.Bytes()[2:] }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func unixMilli(msec int64) time.Time {\n\treturn time.Unix(msec/1e3, (msec%1e3)*1e6)\n}", "func ExampleTime_TimestampMilli() {\n\tt := gtime.TimestampMilli()\n\n\tfmt.Println(t)\n\n\t// May output:\n\t// 1533686888000\n}", "func unixMilli(t time.Time) int64 {\n\treturn t.UnixNano() / int64(time.Millisecond)\n}", "func UnixMilli(t time.Time) int64 {\n\treturn t.Round(time.Millisecond).UnixNano() / (int64(time.Millisecond) / (int64(time.Millisecond)))\n}", "func currentTimeMillis() int64 {\n\tresult := time.Nanoseconds()\n\treturn result / 1e6\n}", "func UnixMilli(ms int64) time.Time {\n\treturn time.Unix(0, ms*int64(time.Millisecond))\n}", "func UnixMilli(t time.Time) int64 {\n\treturn t.UTC().UnixNano() / 1000000\n}", "func (t Time) UnixMilli() int64 {\n\treturn (time.Time)(t).UnixNano() / int64(time.Millisecond)\n}", "func UnixMilli() int64 {\n\treturn time.Now().UnixNano() / DivideMilliseconds\n}", "func UnixMilliseconds(t time.Time) float64 {\n\tnanosPerSecond := float64(time.Second) / float64(time.Nanosecond)\n\treturn float64(t.UnixNano()) / nanosPerSecond\n}", "func GetCurrentTimeStampMilli() int64 {\n\treturn time.Now().UnixNano() / int64(time.Millisecond)\n}", "func ToMillis(t time.Time) int64 {\n\treturn t.UnixNano() / 1e6\n}", "func AsMillis(t time.Time, offset int) int {\n\treturn int(t.UTC().UnixNano()/1000000) + offset*1000\n}", "func (t Time) Milliseconds() int64 {\n\treturn time.Time(t).UnixNano() / DivideMilliseconds\n}", "func ToUnixMillis(t time.Time) int64 {\n\treturn t.UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))\n}", "func UnixMilli() int64 {\n\treturn time.Now().UnixNano() / int64(time.Millisecond)\n}", "func toMSTimestamp(t time.Time) int64 {\n\treturn t.UnixNano() / 1e6\n}", "func makeTimestampMilli() int64 {\n\treturn time.Now().UnixNano() / int64(time.Millisecond)\n}", "func makeTimestampMilli() int64 {\n\treturn time.Now().UnixNano() / int64(time.Millisecond)\n}", "func to_ms(nano int64) int64 {\n\treturn nano / int64(time.Millisecond)\n}", "func Time(t time.Time) int64 {\n\treturn t.UnixNano() / 1000000\n}", "func timeToMillis(t time.Time) float64 {\n\treturn float64(t.UnixNano() / 1000000)\n}", "func GetMonoTime() int64 {\n\tsec, nsec := getRawMonoTime()\n\n\t// to milliseconds\n\treturn sec * 1000 + (nsec / (1 * 1000 * 1000))\n}", "func nanotime() int64", "func nanotime() int64", "func nanotime() int64", "func nanotime() int64", "func ToMilliSec(date time.Time) int64 {\n\treturn date.UnixNano() / 1000000\n}", "func TimestampToUnixMillisecondsString(time time.Time) string {\n\treturn strconv.FormatInt(time.Unix()*1000, 10)\n}", "func fromUnixMilli(ms int64) time.Time {\n\treturn time.Unix(ms/int64(millisInSecond), (ms%int64(millisInSecond))*int64(nsInSecond))\n}", "func run_timeNano() int64", "func timeFromMillis(millis int64) time.Time {\n\treturn time.Unix(0, millis*1e6)\n}", "func Unix(sec int64, nsec int64) Time {}", "func timeToUnixMS(t time.Time) int64 {\n\treturn t.UnixNano() / int64(time.Millisecond)\n}", "func msToTime(t int64) time.Time {\n\treturn time.Unix(t/int64(1000), (t%int64(1000))*int64(1000000))\n}", "func MakeTimestampMilli() int64 {\n\treturn time.Now().UnixNano() / int64(time.Millisecond)\n}", "func FormatTimeMillis(ms int64) string {\n\treturn TimeFromMillis(ms).String()\n}", "func millisToTime(millis float64) time.Time {\n\treturn time.Unix(0, int64(millis*1000000.0))\n}", "func (p Packet) TimeUnixNano() int64 {\n\t// 1.0737... is 2^30 (collectds' subsecond interval) / 10^-9 (nanoseconds)\n\treturn int64(float64(p.CdTime) / 1.073741824)\n}", "func milliseconds(ms int64) time.Duration {\n\treturn time.Duration(ms * 1000 * 1000)\n}", "func unixMSToTime(ms int64) time.Time {\n\treturn time.Unix(0, ms*int64(time.Millisecond))\n}", "func GetTime() int64 {\n\treturn time.Now().UnixNano() / int64(time.Millisecond)\n}", "func FormatTimeMillis(tsMillis uint64) string {\n\treturn time.Unix(0, int64(tsMillis*UnixTimeUnitOffset)).Format(TimeFormat)\n}", "func GetTime(m int64) time.Time {\n\treturn time.Unix(0, m*1000000)\n}", "func TimeUnix(inputTime time.Time) int64 {\n\treturn (inputTime.UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond)))\n}", "func NsMilliseconds(count int64) int64 { return NsMicroseconds(count * 1e3) }", "func GetCurrentTimeMillis() int64 {\n\tnanos := time.Now().UnixNano()\n\n\treturn nanos / 1000000\n}", "func NanoTime() int64", "func NowMs() int64 {\n\treturn time.Now().UnixNano() / 1000000\n}", "func Time(t time.Time) Val {\n\treturn Val{t: bsontype.DateTime}.writei64(t.Unix()*1e3 + int64(t.Nanosecond()/1e6))\n}", "func StrTime13() string {\n\treturn strconv.FormatInt(time.Now().UnixNano()/1e6, 10) //\"1576395361\"\n}", "func (t Time) Nanosecond() int {}", "func ParseMillis(dt int64) (t time.Time, err error) {\n\tt = time.Unix(0, dt*1000*1000)\n\treturn\n}", "func getEpochMillis(timestamp time.Time) int64 {\n\treturn timestamp.UnixNano() / int64(time.Millisecond)\n}", "func (t Time) Unix() int64 {}", "func epochMSToTime(ms int64) string {\n\tt := time.Unix(0, ms*1000000)\n\treturn t.Format(time.RFC3339)\n}", "func msToTime(ms int64) time.Time {\n\treturn time.Unix(0, ms*int64(time.Millisecond))\n}", "func (t Time) Microseconds() int64 {\n\treturn time.Time(t).UnixNano() / DivideMicroseconds\n}", "func (p Packet) TimeUnix() int64 {\n\treturn int64(p.CdTime >> 30)\n}", "func Snotime() uint64 {\n\t// Note: Division is left here instead of being impl in asm since the compiler optimizes this\n\t// into mul+shift, which is easier to read when left in as simple division.\n\t// This doesn't affect performance. The asm won't get inlined anyway while this function\n\t// will.\n\t//\n\t// 4e4 instead of TimeUnit (4e6) because the time we get from the OS is in units of 100ns.\n\treturn ostime() / 4e4\n}", "func getCPUMilli(cpu int) string {\n\treturn fmt.Sprintf(\"%s%s\", strconv.Itoa(cpu), \"m\")\n}", "func getTimestreamTime(t time.Time) (timeUnit types.TimeUnit, timeValue string) {\n\tnanosTime := t.UnixNano()\n\tif nanosTime%1e9 == 0 {\n\t\ttimeUnit = types.TimeUnitSeconds\n\t\ttimeValue = strconv.FormatInt(nanosTime/1e9, 10)\n\t} else if nanosTime%1e6 == 0 {\n\t\ttimeUnit = types.TimeUnitMilliseconds\n\t\ttimeValue = strconv.FormatInt(nanosTime/1e6, 10)\n\t} else if nanosTime%1e3 == 0 {\n\t\ttimeUnit = types.TimeUnitMicroseconds\n\t\ttimeValue = strconv.FormatInt(nanosTime/1e3, 10)\n\t} else {\n\t\ttimeUnit = types.TimeUnitNanoseconds\n\t\ttimeValue = strconv.FormatInt(nanosTime, 10)\n\t}\n\treturn timeUnit, timeValue\n}", "func GetTimestampMicroSec() int64 {\n\treturn time.Now().UnixNano() / int64(time.Microsecond)\n}", "func timeToEpochMS(t time.Time) int64 {\n\treturn t.UnixNano() / 1000000\n}", "func MTime(file string) (int64, error) {\n\tf, err := os.Stat(file)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn f.ModTime().Unix(), nil\n}", "func NsMicroseconds(count int64) int64 { return count * 1e3 }", "func toUnixMsec(t time.Time) int64 {\n\treturn t.UnixNano() / 1e6\n}", "func TimeFromMillis(ms int64) time.Time {\n\treturn time.Unix(0, ms*nanosecondsInMillisecond)\n}", "func formatTimestamp(t time.Time, milli bool) string {\n\tif milli {\n\t\treturn fmt.Sprintf(\"%d.%03d\", t.Unix(), t.Nanosecond()/1000000)\n\t}\n\n\treturn fmt.Sprintf(\"%d\", t.Unix())\n}", "func (val Time) Unix() (sec, nsec int64) {\n\tsec = int64(val) / 1000000\n\tnsec = (int64(val) % 1000000) * 1000\n\treturn\n}", "func bytesToTime(b []byte) time.Time {\n\tvar nsec int64\n\tfor i := uint8(0); i < timeByteSize; i++ {\n\t\tnsec += int64(b[i]) << ((7 - i) * timeByteSize)\n\t}\n\treturn time.Unix(nsec/1000000000, nsec%1000000000)\n}", "func makeTimestamp() int64 {\n return time.Now().UnixNano() / int64(time.Millisecond)\n}", "func tickspersecond() int64", "func humanToNanoTime(value []byte) ([]byte) {\n\tdura, err := time.ParseDuration(string(value))\n\tif err != nil {\n\t\treturn value\n\t}\n\treturn []byte(strconv.FormatInt(dura.Nanoseconds(), 10))\n}", "func TimeStr2UnixMilli(timeStr string) (int64, error) {\n\tt, err := time.ParseInLocation(\"2006-01-02 15:04:05\", timeStr, time.Local)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn int64(t.UnixNano() / 1000000), nil\n}", "func ExampleTime_TimestampMicro() {\n\tt := gtime.TimestampMicro()\n\n\tfmt.Println(t)\n\n\t// May output:\n\t// 1533686888000000\n}", "func UnixMicro() int64 {\n\treturn time.Now().UnixNano() / DivideMicroseconds\n}", "func DurationToTimeMillisField(duration time.Duration) zapcore.Field {\n\treturn zap.Float32(\"grpc.time_ms\", durationToMilliseconds(duration))\n}", "func DropMilliseconds(t time.Time) time.Time {\n\treturn t.Truncate(time.Second)\n}", "func FromMillis(timestampMillis int64) time.Time {\n\treturn time.Unix(0, timestampMillis*1e6)\n}", "func (f SingleWorkerID) Time() int64 {\n\treturn (int64(f) >> timestampLeftShift) + snowflake.TW_EPOCH\n}", "func convertMillToTime(originalTime int64) time.Time {\n\ti := time.Unix(0, originalTime*int64(time.Millisecond))\n\treturn i\n}", "func timeParse(microsecs string) time.Time {\n\tt := time.Date(1601, time.January, 1, 0, 0, 0, 0, time.UTC)\n\tm, err := strconv.ParseInt(microsecs, 10, 64)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%s\\n\", err.Error())\n\t\tos.Exit(1)\n\t}\n\tvar u int64 = 100000000000000\n\tdu := time.Duration(u) * time.Microsecond\n\tf := float64(m)\n\tx := float64(u)\n\tn := f / x\n\tr := int64(n)\n\tremainder := math.Mod(f, x)\n\tiRem := int64(remainder)\n\tvar i int64\n\tfor i = 0; i < r; i++ {\n\t\tt = t.Add(du)\n\t}\n\n\tt = t.Add(time.Duration(iRem) * time.Microsecond)\n\n\t// RFC1123 = \"Mon, 02 Jan 2006 15:04:05 MST\"\n\t// t.Format(time.RFC1123)\n\treturn t\n}", "func ExampleTime_TimestampNano() {\n\tt := gtime.TimestampNano()\n\n\tfmt.Println(t)\n\n\t// May output:\n\t// 1533686888000000\n}", "func CurrentTimeInMilliseconds() int64 {\n\treturn UnixMilli(time.Now())\n}", "func CurrentTimeMillis() uint64 {\n\treturn CurrentClock().CurrentTimeMillis()\n}", "func millisI(nanos int64) float64 {\n\treturn millisF(float64(nanos))\n}", "func (v TimestampNano) Time() time.Time {\n\tif !v.Valid() {\n\t\treturn time.Unix(0, 0)\n\t}\n\treturn v.time\n}", "func TimeUnix() string {\r\n\tnaiveTime := time.Now().Unix()\r\n\tnaiveTimeString := strconv.FormatInt(naiveTime, 10)\r\n\treturn naiveTimeString\r\n}", "func DurationInMilliseconds(d time.Duration) string {\n\treturn fmt.Sprintf(\"%.0fms\", d.Seconds()*1e3)\n}", "func NowTimeUnixNano() uint64 {\n\treturn uint64(time.Now().UnixNano())\n}", "func MsSince(start time.Time) float64 {\n\treturn float64(time.Since(start) / time.Millisecond)\n}", "func MsSince(start time.Time) float64 {\n\treturn float64(time.Since(start) / time.Millisecond)\n}", "func (x XID) Time() time.Time {\n\treturn time.Unix(int64(x[0])<<32|int64(x[1])<<16|int64(x[2])<<8|int64(x[3]), 0)\n}", "func SyncRuntimeNanoTime() int64", "func getUnixTime(val []byte) (uint64, error) {\n\tif len(val) < 8 {\n\t\treturn 0, errors.New(\"len(val) < 8, want len(val) => 8\")\n\t}\n\tunixTime := ((uint64)(val[0]) | // 1st\n\t\t((uint64)(val[1]) << 8) | // 2nd\n\t\t((uint64)(val[2]) << 16) | // 3rd\n\t\t((uint64)(val[3]) << 24) | // 4th\n\t\t((uint64)(val[4]) << 32) | // 5th\n\t\t((uint64)(val[5]) << 40) | // 6th\n\t\t((uint64)(val[6]) << 48) | // 7th\n\t\t((uint64)(val[7]) << 56)) // 8th\n\treturn unixTime, nil\n}", "func Time() int64 {\n\n\treturn time.Now().Unix()\n}", "func Timestamp() int64 {\n\treturn time.Now().UnixNano() / int64(time.Millisecond)\n}", "func Nanotime() int64 {\n\treturn nanotime()\n}" ]
[ "0.7101721", "0.69069314", "0.68803227", "0.6791198", "0.6777413", "0.6734928", "0.67218816", "0.6640226", "0.65585893", "0.65047765", "0.641932", "0.638792", "0.6372564", "0.6362559", "0.6360365", "0.6352605", "0.6330645", "0.63179547", "0.63179547", "0.6275363", "0.62735087", "0.6264697", "0.62547296", "0.62501544", "0.62501544", "0.62501544", "0.62501544", "0.6212344", "0.61832345", "0.6182011", "0.616438", "0.61400515", "0.6118057", "0.61053395", "0.607816", "0.607462", "0.6042979", "0.601269", "0.59889704", "0.59808224", "0.5949364", "0.5942923", "0.5885377", "0.58584076", "0.58576065", "0.58574384", "0.585213", "0.5818792", "0.58010995", "0.57799435", "0.5774714", "0.57659346", "0.5763235", "0.57596564", "0.5714259", "0.57142586", "0.57084805", "0.5700015", "0.569819", "0.5681223", "0.5678237", "0.5658518", "0.5628383", "0.56232905", "0.56201446", "0.5612391", "0.5608479", "0.5587839", "0.5569277", "0.55627805", "0.5529095", "0.5504872", "0.54906636", "0.5471248", "0.5470123", "0.54371274", "0.5434016", "0.5425637", "0.5425247", "0.542212", "0.541597", "0.5407826", "0.5402065", "0.53961194", "0.53633916", "0.53569245", "0.5343675", "0.5335818", "0.531818", "0.53068966", "0.5292133", "0.5288836", "0.5288836", "0.52870345", "0.52851164", "0.5279809", "0.5277561", "0.527", "0.52512825" ]
0.82570755
1
shad Double Sha256 Hash; sha256(sha256(data))
func shad(data []byte) []byte { h1 := sha256.Sum256(data) h2 := sha256.Sum256(h1[:]) return h2[:] }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Sha256d(input []byte) Hash {\n sha := sha256.New()\n sha.Write(input)\n intermediate := sha.Sum(nil)\n sha.Reset()\n sha.Write(intermediate)\n hash, err := HashFromBytes(sha.Sum(nil), LittleEndian)\n if err != nil {\n panic(\"impossible flow, this is a bug: \" + err.Error())\n }\n return hash\n}", "func Sha256Hash(data []byte) [32]byte {\n\tsum := sha256.Sum256(data)\n\treturn sum\n}", "func DoubleSha256(data []byte) Hash {\n\th := sha256.Sum256(data)\n\th = sha256.Sum256(h[:])\n\n\treturn NewHash(h[:])\n}", "func DoubleSha256SH(b []byte) ShaHash {\n\tfirst := fastsha256.Sum256(b)\n\treturn ShaHash(fastsha256.Sum256(first[:]))\n}", "func getSHA256Hash(data []byte) string {\n\treturn hex.EncodeToString(getSHA256Sum(data))\n}", "func Sha256(data []byte) []byte {\n\n\thash := sha256.New()\n\thash.Write(data)\n\treturn hash.Sum(nil)\n}", "func SHA256(raw []byte) Hash {\n\treturn gosha256.Sum256(raw)\n}", "func SHA256Hash(data []byte) []byte {\n\tsum := sha256.Sum256(data)\n\treturn sum[:]\n}", "func Sha256(data []byte) Hash {\n\th := sha256.Sum256(data)\n\n\treturn NewHash(h[:])\n}", "func Sha256(data string, salt string) string {\n\tb := []byte(data + salt)\n\treturn fmt.Sprintf(\"%X\", sha256.Sum256(b))\n}", "func Sha256Hash(password string) string {\n h := sha256.Sum256([]byte(password))\n return \"{SHA256}\" + base64.StdEncoding.EncodeToString(h[:])\n}", "func getSHA256Sum(data []byte) []byte {\n\thash := sha256.New()\n\thash.Write(data)\n\treturn hash.Sum(nil)\n}", "func SHA256(data []byte) []byte {\n\tb := sha256.Sum256(data)\n\treturn b[:]\n}", "func UsingSha256(data []byte) []byte {\n\th := sha256.New()\n\th.Write(data)\n\tout := h.Sum(nil)\n\n\treturn out\n}", "func DoubleSHA256(raw []byte) Hash {\n\th := SHA256(raw)\n\treturn SHA256(h[:])\n}", "func Sha256Hmac(secret string, data string) string {\n\t// Create a new HMAC by defining the hash type and the key (as byte array)\n\th := hmac.New(sha256.New, []byte(secret))\n\n\t// Write Data to it\n\th.Write([]byte(data))\n\n\t// Get result and encode as hexadecimal string\n\tsha := hex.EncodeToString(h.Sum(nil))\n\n\treturn sha\n}", "func ComputeSHA256(data []byte) (hash []byte) {\r\n\treturn util.ComputeSHA256(data)\r\n}", "func SumDoubleSha256(data []byte) [sha256.Size]byte {\n\th := sha256.Sum256(data)\n\treturn sha256.Sum256(h[:])\n}", "func (a *A25) doubleSHA256() []byte {\n\th := sha256.New()\n\th.Write(a[:21])\n\td := h.Sum([]byte{})\n\th = sha256.New()\n\th.Write(d)\n\treturn h.Sum(d[:0])\n}", "func SHA256Hex(data []byte) string {\n\treturn hex.EncodeToString(SHA256(data))\n}", "func SHA256(in []byte) []byte {\n\thash := sha256.Sum256(in)\n\treturn hash[:]\n}", "func SignSha256(data, secretKey string) string {\n\tdata, err := url.QueryUnescape(data)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\thm := hmac.New(sha256.New, []byte(secretKey))\n\thm.Write([]byte(data + \"&key=\" + secretKey))\n\treturn fmt.Sprintf(\"%X\", hm.Sum(nil))\n}", "func MASSSHA256(raw []byte) Hash {\n\treturn sha256.Sum256(raw)\n}", "func hashSHA256(str string) string {\n\ts := sha256.New()\n\ts.Write([]byte(str))\n\treturn base64.StdEncoding.EncodeToString(s.Sum(nil))\n}", "func (n Node) CalSHA256Hash(input []byte) []byte {\r\n\th := sha256.New()\r\n\th.Write(input)\r\n\treturn h.Sum(nil)\r\n}", "func hashSHA256(input string) string {\n\th := sha1.New()\n\th.Write([]byte(input))\n\treturn hex.EncodeToString(h.Sum(nil))\n}", "func Sha256(buf []byte) []byte {\n\treturn CalcHash(buf, sha256.New())\n}", "func DoubleSha256(b []byte) []byte {\n\tfirst := fastsha256.Sum256(b)\n\tsecond := fastsha256.Sum256(first[:])\n\treturn second[:]\n}", "func MASSDoubleSHA256(raw []byte) Hash {\n\th := MASSSHA256(raw)\n\treturn MASSSHA256(h[:])\n}", "func sum256(data []byte) []byte {\n\thash := sha256.New()\n\thash.Write(data)\n\treturn hash.Sum(nil)\n}", "func newSHA256() hash.Hash { return sha256.New() }", "func Sha256(in, out []byte) error {\n\th := poolSha256.Get().(hash.Hash)\n\tif _, err := h.Write(in); err != nil {\n\t\th.Reset()\n\t\tpoolSha256.Put(h)\n\t\treturn err\n\t}\n\th.Sum(out)\n\th.Reset()\n\tpoolSha256.Put(h)\n\treturn nil\n}", "func hash(data []byte) [32]byte {\n\tvar hash [32]byte\n\n\th := sha256.New()\n\t// The hash interface never returns an error, for that reason\n\t// we are not handling the error below. For reference, it is\n\t// stated here https://golang.org/pkg/hash/#Hash\n\t// #nosec G104\n\th.Write(data)\n\th.Sum(hash[:0])\n\n\treturn hash\n}", "func Sha256() (sum [sha256.Size]byte) {\n\ts, err := hex.DecodeString(packerSHA256)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tcopy(sum[0:], s)\n\treturn\n}", "func Sha256(o interface{}) ([]byte, error) {\n\thash := sha256.New()\n\tif _, err := hash.Write([]byte(fmt.Sprintf(\"%+v\", o))); err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\treturn hash.Sum(nil), nil\n}", "func SHA256(s string) string {\n\treturn stringHasher(sha256.New(), s)\n}", "func Sha256Hash(file io.Reader) (string, error) {\n\tbuf := bytes.NewBuffer(nil)\n\tif _, err := io.Copy(buf, file); err != nil {\n\t\tlog.Println(\"Failed to copy file to buffer in hashing function...\")\n\t\treturn \"\", err\n\t}\n\n\thasher := sha256.New()\n\thasher.Write(buf.Bytes())\n\n\tsha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))\n\n\treturn sha, nil\n}", "func Hash256(pass string, salt string) string {\n\tcombined_bytes := []byte(pass + salt)\n\thash_bytes := hasher256.Sum(combined_bytes)\n\treturn hex.EncodeToString(hash_bytes)\n}", "func SHA256RNDS2(x, mx, x1 operand.Op) { ctx.SHA256RNDS2(x, mx, x1) }", "func Sha256(k []byte) []byte {\n\thash := sha256.New()\n\thash.Write(k)\n\treturn hash.Sum(nil)\n}", "func Sha256(source io.Reader) (string, int64, error) {\n\thash := hash.New()\n\tsize, err := io.Copy(hash, source)\n\tif err != nil {\n\t\treturn \"\", 0, err\n\t}\n\treturn hex.EncodeToString(hash.Sum(nil)) + \"-sha256\", size, nil\n}", "func SHA256(text string) string {\n\talgorithm := sha256.New()\n\treturn stringHasher(algorithm, text)\n}", "func Hash(data []byte) []byte {\n\treturn hash.SHA256(data)\n}", "func Sha256(buf []byte) []byte {\n\tdigest := sha256.Sum256(buf)\n\treturn digest[:]\n}", "func (t SimpleHash) Sum256(data []byte) []byte {\n\tsha3Hash := t.wrapper.Sha256(data)\n\tblakeHash := t.wrapper.Blake2s(sha3Hash[:])\n\treturn blakeHash[:]\n}", "func Sum256(data []byte) [Size]byte {\n\tvar d digest\n\td.hashSize = 256\n\td.Reset()\n\td.Write(data)\n\treturn d.checkSum()\n}", "func EncryptSHA256(text string) string {\n h := sha256.New()\n h.Write([]byte(text))\n s := base64.URLEncoding.EncodeToString(h.Sum(nil))\n return (s)\n}", "func SHA256(secret, salt string) string {\n key := []byte(secret)\n h := hmac.New(sha256.New, key)\n h.Write([]byte(\"_remote_db\"))\n return base64.StdEncoding.EncodeToString(h.Sum(nil))\n}", "func sha256a(authKey Key, msgKey bin.Int128, x int) []byte {\n\th := getSHA256()\n\tdefer sha256Pool.Put(h)\n\n\t_, _ = h.Write(msgKey[:])\n\t_, _ = h.Write(authKey[x : x+36])\n\n\treturn h.Sum(nil)\n}", "func HS256(value string, key string) ([]byte, error) {\n\tcipher := hmac.New(sha256.New, []byte(key))\n\t_, err := cipher.Write([]byte(value))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cipher.Sum(nil), nil\n}", "func TestSha2_256(t *testing.T) {\n\tinput := []byte(\"test\")\n\texpected, _ := hex.DecodeString(\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\")\n\n\talg := NewSHA2_256()\n\thash := alg.ComputeHash(input)\n\tcheckBytes(t, input, expected, hash)\n\n\talg.Reset()\n\t_, _ = alg.Write([]byte(\"te\"))\n\t_, _ = alg.Write([]byte(\"s\"))\n\t_, _ = alg.Write([]byte(\"t\"))\n\thash = alg.SumHash()\n\tcheckBytes(t, input, expected, hash)\n}", "func Hash(data []byte) [blake2b.Size]byte {\n\treturn blake2b.Sum512(data)\n}", "func (this *serviceImpl) HmacSha256(key, input []byte) (h []byte) {\n\tmac := hmac.New(sha256.New, key)\n\tmac.Write(input)\n\th = mac.Sum(nil)\n\treturn\n}", "func (trans *Transaction) HashSHA256() [32]byte {\n\tmessage, err := json.Marshal(trans)\n\tif err != nil {\n\t\tlog.Fatalf(\"Fail to marshal transaction with error: %s\", err)\n\t}\n\treturn sha256.Sum256([]byte(message))\n}", "func TestSha3_256(t *testing.T) {\n\tinput := []byte(\"test\")\n\texpected, _ := hex.DecodeString(\"36f028580bb02cc8272a9a020f4200e346e276ae664e45ee80745574e2f5ab80\")\n\n\talg := NewSHA3_256()\n\thash := alg.ComputeHash(input)\n\tcheckBytes(t, input, expected, hash)\n\n\talg.Reset()\n\t_, _ = alg.Write([]byte(\"te\"))\n\t_, _ = alg.Write([]byte(\"s\"))\n\t_, _ = alg.Write([]byte(\"t\"))\n\thash = alg.SumHash()\n\tcheckBytes(t, input, expected, hash)\n}", "func Hash(data []byte) []byte {\n\th := sha256.Sum256(data)\n\treturn types.ByteSlice(h[:])\n}", "func GetSHA256Hash(text string) string {\n\thasher := sha256.New()\n\thasher.Write([]byte(text))\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}", "func (t X12Hash) Sum256(data []byte) ([]byte, error) {\n\tval := t.wrapper.X11(data)\n\tscryptHash, err := t.wrapper.Scrypt(val, nil, 32768, 8, 1, 32)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn scryptHash, nil\n}", "func calcHash(data string) string {\n\th := sha256.New()\n\th.Write([]byte(data))\n\thash := fmt.Sprintf(\"%x\", h.Sum(nil))\n\treturn hash\n}", "func generateSHA256HashInHexForm(preimage string) string {\n\thasher := sha256.New()\n\thasher.Write([]byte(preimage))\n\tshaHash := hasher.Sum(nil)\n\tshaHashHex := hex.EncodeToString(shaHash)\n\treturn shaHashHex\n}", "func Hash(data []byte) {\n\tfor i := 0; i < 50; i++ {\n\t\tsha256.Sum256(data)\n\t}\n}", "func (seal *Seal) DSha256(path string) string {\n // precondition: the manifest is required\n if seal.Manifest == nil {\n core.RaiseErr(\"seal has no manifest, cannot create checksum\")\n }\n // read the compressed file\n file, err := ioutil.ReadFile(path)\n core.CheckErr(err, \"cannot open seal file\")\n // serialise the seal info to json\n info := core.ToJsonBytes(seal.Manifest)\n core.Debug(\"manifest before checksum:\\n>> start on next line\\n%s\\n>> ended on previous line\", string(info))\n hash := sha256.New()\n written, err := hash.Write(file)\n core.CheckErr(err, \"cannot write package file to hash\")\n core.Debug(\"%d bytes from package written to hash\", written)\n written, err = hash.Write(info)\n core.CheckErr(err, \"cannot write manifest to hash\")\n core.Debug(\"%d bytes from manifest written to hash\", written)\n checksum := hash.Sum(nil)\n core.Debug(\"seal calculated base64 encoded checksum:\\n>> start on next line\\n%s\\n>> ended on previous line\", base64.StdEncoding.EncodeToString(checksum))\n return fmt.Sprintf(\"sha256:%s\", base64.StdEncoding.EncodeToString(checksum))\n}", "func Sha2Sum(b []byte) (out [32]byte) {\n\ts := sha256.New()\n\ts.Write(b[:])\n\ttmp := s.Sum(nil)\n\ts.Reset()\n\ts.Write(tmp)\n\tcopy(out[:], s.Sum(nil))\n\treturn\n}", "func Hashit(tox string) string {\n h:= sha256.New()\n h.Write([]byte(tox))\n bs := h.Sum([]byte{})\n str := base64.StdEncoding.EncodeToString(bs)\n return str\n}", "func CalcHash(data string) string {\r\n\thashed := sha256.Sum256([]byte(data))\r\n\treturn hex.EncodeToString(hashed[:])\r\n}", "func ShaSum256HexEncoded(b []byte) string {\n\tsha := sha256.Sum256(b)\n\tshaHex := hex.EncodeToString(sha[:])\n\n\treturn shaHex\n}", "func ShaSum256HexEncoded(b []byte) string {\n\tsha := sha256.Sum256(b)\n\tshaHex := hex.EncodeToString(sha[:])\n\n\treturn shaHex\n}", "func sha256hex(buf []byte) (string, error) {\n\thasher := sha256.New()\n\tif _, err := hasher.Write(buf); err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to get sha256 hash: %w\", err)\n\t}\n\tcCodeHash := hasher.Sum(nil)\n\treturn hex.EncodeToString(cCodeHash), nil\n}", "func HMAC_SHA256(src, key string) string {\n\tm := hmac.New(sha256.New, []byte(key))\n\tm.Write([]byte(src))\n\treturn hex.EncodeToString(m.Sum(nil))\n}", "func Hash(data ...[]byte) []byte {\n\treturn crypto.Keccak256(data...)\n}", "func FingerprintSHA256(b []byte) string {\n\tdigest := sha256.Sum256(b)\n\treturn hex.EncodeToString(digest[:])\n}", "func (c *ChunkLister) Sha256() []byte {\n\treturn nil\n}", "func Sum256(data []byte) (sum256 [Size256]byte) {\n\tvar d digest\n\td.is256 = true\n\td.Reset()\n\td.Write(data)\n\tsum := d.checkSum()\n\tcopy(sum256[:], sum[Size256:])\n\treturn\n}", "func (sshConfig *SSHConfig) Sha256sum(path string) (result string, err error) {\n\treturn sshConfig.internalSum(\"sha256sum\", path)\n}", "func (d Data256) Hash() Hash {\n\treturn hash(d)\n}", "func Hash(input []byte) string {\n\treturn fmt.Sprintf(\"%x\", sha256.Sum256(input))\n}", "func EncryptSHA256(data []byte, p Passphrase) (EncryptedData, error) {\n\tsalt := make([]byte, saltSize)\n\n\t// Generate a Salt\n\tif _, err := rand.Read(salt); err != nil {\n\t\treturn EncryptedData(\"\"), err\n\t}\n\n\t// convert string to bytes\n\tkey, err := CreateHashArgon(string(p), salt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create a new cipher block from the key\n\tblock, err := aes.NewCipher([]byte(key))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create a new GCM\n\taesGCM, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create a nonce (12 bytes)\n\tnonce := make([]byte, aesGCM.NonceSize())\n\tif _, err = io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// encrypt the data using aesGCM.Seal\n\tcipherData := append([]byte(encryptionVer), salt...)\n\tcipherData = append(cipherData, aesGCM.Seal(nonce, nonce, data, nil)...)\n\treturn cipherData, nil\n\n}", "func fingerprintSHA256(key ssh.PublicKey) string {\r\n\thash := sha256.Sum256(key.Marshal())\r\n\tb64hash := base64.StdEncoding.EncodeToString(hash[:])\r\n\treturn strings.TrimRight(b64hash, \"=\")\r\n}", "func Hash256(N int, data []byte) []byte {\n\treturn hasher.Hash(u, data, 0, uint64(N))\n}", "func Hashbin(tox string) []byte {\n h:= sha256.New()\n h.Write([]byte(tox))\n bs := h.Sum([]byte{})\n return bs \n}", "func Keccak256Hash(data []byte) []byte {\n\tb := sha3.Sum256(data)\n\treturn b[:]\n}", "func VerifySha256(password, hash string) bool {\n return Sha256Hash(password) == hash\n}", "func HashStringSha256(hs string) []byte {\n\tdata := []byte(hs)\n\thash := sha256.Sum256(data)\n\treturn hash[:]\n}", "func hashData(src io.Reader) (string, error) {\n\th := sha256.New()\n\tif _, err := io.Copy(h, src); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn \"sha256:\" + hex.EncodeToString(h.Sum(nil)), nil\n}", "func EncodeHash256(s string) string {\n\th := sha256.New()\n\th.Write([]byte(s))\n\treturn hex.EncodeToString(h.Sum(nil))\n}", "func Hash(src string, secret string) string {\n key := []byte(secret)\n h := hmac.New(sha256.New, key)\n h.Write([]byte(src))\n return base64.StdEncoding.EncodeToString(h.Sum(nil))\n}", "func generateSHA256HashInBase64Form(preimage string) string {\n\thasher := sha256.New()\n\thasher.Write([]byte(preimage))\n\tshaHash := hasher.Sum(nil)\n\tshaHashBase64 := base64.StdEncoding.EncodeToString(shaHash)\n\treturn shaHashBase64\n}", "func hash(key uint64) uint64 {\r\n\tkey ^= key >> 33\r\n\tkey *= 0xff51afd7ed558ccd\r\n\tkey ^= key >> 33\r\n\tkey *= 0xc4ceb9fe1a85ec53\r\n\tkey ^= key >> 33\r\n\treturn key\r\n}", "func GenerateSHA256Hash() string {\n\tkey := getSecretPhrase()\n\thasher := sha256.New()\n\thasher.Write([]byte(key))\n\n\tactual, err := strkey.Encode(strkey.VersionByteHashX, hasher.Sum(nil))\n\tif err != nil {\n\t\tpanic(err);\n\t\t//LOGGER.Fatal(err)\n\t\treturn \"\"\n\t}\n\treturn actual\n}", "func ScryptSHA256(password string, salt []byte, N, r, p int) string {\n\tpasswordb := []byte(password)\n\n\thash, err := scrypt.Key(passwordb, salt, N, r, p, 32)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\thstr := base64.StdEncoding.EncodeToString(hash)\n\tsstr := base64.StdEncoding.EncodeToString(salt)\n\n\treturn fmt.Sprintf(\"$s2$%d$%d$%d$%s$%s\", N, r, p, sstr, hstr)\n}", "func Sha2(s string) string {\n\treturn hashing(sha256.New(), s)\n}", "func (s *DHT) hashKey(data []byte) []byte {\n\tsha := sha3.Sum256(data)\n\treturn sha[:]\n}", "func (b *Bundler) ChecksumSHA256(name, sum string) {\n\tb.checksumsSHA256.Add(name, sum)\n}", "func hash(ba string) string {\n\th := sha256.New()\n\th.Write([]byte(ba))\n\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}", "func getHS256Signature(encHeader string, encPayload string, pubKeyHexa string) string {\n\topenssl := exec.Command(\"openssl\", \"dgst\", \"-sha256\", \"-mac\", \"HMAC\", \"-macopt\", \"hexkey:\"+pubKeyHexa)\n\n\topenssl.Stdin = bytes.NewReader([]byte(encHeader + \".\" + encPayload))\n\n\tcmdOutput := &bytes.Buffer{}\n\topenssl.Stdout = cmdOutput\n\topenssl.Start()\n\topenssl.Wait()\n\thmac := string(cmdOutput.Bytes())\n\treturn hex.EncodeToString([]byte(hmac))\n}", "func Hash256Bytes(bytes []byte) string {\n\thasher := sha256.New()\n\thasher.Write(bytes)\n\tmsgDigest := hasher.Sum(nil)\n\tsha256Hex := hex.EncodeToString(msgDigest)\n\treturn sha256Hex\n}", "func computeHash(w http.ResponseWriter, req *http.Request) {\n\tvalues := req.URL.Query()\n\tdata := values.Get(\"data\")\n\tif data == \"\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"400 - data param not present\"))\n\t\treturn\n\t}\n\tsalt := values.Get(\"salt\")\n\tif salt == \"\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"400 - salt param not present\"))\n\t\treturn\n\t}\n\th := sha256.Sum256([]byte(data+salt))\n\tencodedStr := hex.EncodeToString(h[:])\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(encodedStr))\n}", "func SSHFingerprintSHA256(key ssh.PublicKey) string {\n\thash := sha256.Sum256(key.Marshal())\n\tb64hash := base64.StdEncoding.EncodeToString(hash[:])\n\treturn strings.TrimRight(b64hash, \"=\")\n}", "func hash(elements ...[32]byte) [32]byte {\n\tvar hash []byte\n\tfor i := range elements {\n\t\thash = append(hash, elements[i][:]...)\n\t}\n\treturn sha256.Sum256(hash)\n}", "func sha3hash(t *testing.T, data ...[]byte) []byte {\n\tt.Helper()\n\th := sha3.NewLegacyKeccak256()\n\tr, err := doSum(h, nil, data...)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn r\n}" ]
[ "0.80343264", "0.7977035", "0.79371136", "0.78847826", "0.7820462", "0.77817565", "0.7781602", "0.7755658", "0.7713797", "0.7704969", "0.76733696", "0.7553372", "0.7516322", "0.7513384", "0.75047284", "0.74886376", "0.7439429", "0.7417883", "0.7394907", "0.732519", "0.73068845", "0.7295614", "0.72848266", "0.7276869", "0.7266031", "0.7239706", "0.7232307", "0.71969616", "0.7196125", "0.71625113", "0.71338445", "0.71258324", "0.7064684", "0.70298344", "0.70218587", "0.70216525", "0.7009046", "0.7000133", "0.69963187", "0.6982519", "0.69773525", "0.69471353", "0.6946146", "0.6922896", "0.69223154", "0.6849941", "0.6839314", "0.68363446", "0.6817802", "0.68030477", "0.6793487", "0.6772909", "0.6730089", "0.66980875", "0.6697582", "0.66922015", "0.66876197", "0.6684637", "0.6676901", "0.6676595", "0.66756606", "0.6647739", "0.6592846", "0.65873456", "0.65811455", "0.6564177", "0.6564177", "0.6563995", "0.65492773", "0.65487486", "0.65442437", "0.6542314", "0.6493013", "0.6486589", "0.64712244", "0.6466204", "0.64509314", "0.6443134", "0.64370936", "0.6430964", "0.6418407", "0.6416184", "0.6412395", "0.6408828", "0.6396298", "0.6392345", "0.6382759", "0.6380763", "0.63800424", "0.63706887", "0.6367111", "0.63634825", "0.6339623", "0.63330835", "0.6326153", "0.631451", "0.6312895", "0.62945855", "0.6288769", "0.6281039" ]
0.7916198
3
sha52 Sha512+Sha256 Hash; sha256(sha512(data)+data)
func sha52(data []byte) []byte { h1 := sha512.Sum512(data) h2 := sha256.Sum256(append(h1[:], data...)) return h2[:] }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func SHA512(text string) string {\n\treturn stringHasher(sha512.New(), text)\n}", "func Hash512(tag string, data []byte) []byte {\n\th := hmac.New(sha512.New512_256, []byte(tag))\n\th.Write(data)\n\treturn h.Sum(nil)\n}", "func expandHash(data []byte) []byte {\n\tpart0 := sha512.Sum512(append(data, 0))\n\tpart1 := sha512.Sum512(append(data, 1))\n\tpart2 := sha512.Sum512(append(data, 2))\n\tpart3 := sha512.Sum512(append(data, 3))\n\treturn bytes.Join([][]byte{\n\t\tpart0[:],\n\t\tpart1[:],\n\t\tpart2[:],\n\t\tpart3[:],\n\t}, []byte{})\n}", "func xx512x1(inner_512 []byte) [20]byte {\n\touter_512 := sha512.Sum512(inner_512)\n\treturn sha1.Sum(outer_512[:])\n}", "func Sum512(data []byte) [Size]byte {\n\tvar d digest\n\td.Reset()\n\td.Write(data)\n\treturn d.checkSum()\n}", "func hashSHA512(text string) []byte {\n\thash := sha512.New()\n\thash.Write([]byte(text))\n\treturn hash.Sum(nil)\n}", "func Hash(data []byte) [blake2b.Size]byte {\n\treturn blake2b.Sum512(data)\n}", "func Hmac512(key string, data io.Reader) (b64 string, err error) {\n\thash := hmac.New(sha512.New, []byte(key))\n\tb, err := ioutil.ReadAll(data)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to read data from reader\")\n\t}\n\tif _, err := hash.Write(b); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to hash data\")\n\t}\n\treturn base64.StdEncoding.EncodeToString(hash.Sum(nil)), nil\n}", "func SHA512(text string) string {\n\thasher := sha512.New()\n\thasher.Write([]byte(text))\n\treturn strings.ToUpper(hex.EncodeToString(hasher.Sum(nil)))\n}", "func SHA512Digest(s string) string {\n\th := sha512.Sum512([]byte(s))\n\treturn hex.EncodeToString(h[:])\n}", "func Sha512(master, salt, info []byte) ([32]byte, error) {\n\thash := sha512.New\n\thkdf := hkdf.New(hash, master, salt, info)\n\n\tkey := make([]byte, 32) // 256 bit\n\t_, err := io.ReadFull(hkdf, key)\n\n\tvar result [32]byte\n\tcopy(result[:], key)\n\n\treturn result, err\n}", "func shad(data []byte) []byte {\n\th1 := sha256.Sum256(data)\n\th2 := sha256.Sum256(h1[:])\n\treturn h2[:]\n}", "func EncodeHash512(s string) string {\n\th := sha512.New()\n\th.Write([]byte(s))\n\treturn hex.EncodeToString(h.Sum(nil))\n}", "func SignatureHash(signature string) string {\n\treturn fmt.Sprintf(\"%x\", sha512.Sum384([]byte(signature)))\n}", "func SHA512ChecksumData(data []byte) ([]byte, error) {\n\th := sha512.New()\n\tif _, err := h.Write(data); err != nil {\n\t\tpanic(errors.Wrap(err, `\"It never returns an error.\" -- https://golang.org/pkg/hash`))\n\t}\n\treturn h.Sum(nil), nil\n}", "func Sha3256(bs []byte) ([]byte, error) {\n\treturn PerformHash(sha3.New256(), bs)\n}", "func KeccakSum512(data []byte) (digest [64]byte) {\n\th := NewKeccak512()\n\th.Write(data)\n\th.Sum(digest[:0])\n\treturn\n}", "func Sha512(in, out []byte) error {\n\th := poolSha512.Get().(hash.Hash)\n\tif _, err := h.Write(in); err != nil {\n\t\th.Reset()\n\t\tpoolSha512.Put(h)\n\t\treturn err\n\t}\n\th.Sum(out)\n\th.Reset()\n\tpoolSha512.Put(h)\n\treturn nil\n}", "func Sha256Hash(password string) string {\n h := sha256.Sum256([]byte(password))\n return \"{SHA256}\" + base64.StdEncoding.EncodeToString(h[:])\n}", "func shaEncode(input string) string {\n\tsha := sha512.Sum512([]byte(input))\n\treturn hex.EncodeToString(sha[:])\n}", "func Sha256Hash(data []byte) [32]byte {\n\tsum := sha256.Sum256(data)\n\treturn sum\n}", "func (p *Password) SHA512(saltConf ...*SaltConf) ([64]byte, []byte) {\n\tif len(saltConf) > 0 {\n\t\tvar saltLength int\n\n\t\tfor _, i := range saltConf[0:] {\n\t\t\tsaltLength = i.Length\n\t\t}\n\n\t\tsalt := getRandomBytes(saltLength)\n\t\treturn sha512.Sum512([]byte(fmt.Sprintf(\"%s%x\", p.Pass, salt))), salt\n\t}\n\treturn sha512.Sum512([]byte(p.Pass)), nil\n}", "func hash(password string) string {\n\thash := sha512.New()\n\thash.Write([]byte(password))\n\tb := hash.Sum(nil)\n\treturn base64.StdEncoding.EncodeToString(b)\n}", "func new512Asm() hash.Hash { return nil }", "func TestSsha512(t *testing.T) {\n\tconst plain = \"Hi, arche.\"\n\tencode, err := nut.SumSsha512(plain, 32)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tt.Logf(`doveadm pw -t {SSHA512}%s -p \"%s\"`, encode, plain)\n\tif !nut.EqualSsha512(encode, plain) {\n\t\tt.Error(\"check password failed\")\n\t}\n}", "func Sha2Sum(b []byte) (out [32]byte) {\n\ts := sha256.New()\n\ts.Write(b[:])\n\ttmp := s.Sum(nil)\n\ts.Reset()\n\ts.Write(tmp)\n\tcopy(out[:], s.Sum(nil))\n\treturn\n}", "func Encrypt(password []byte, e interface{}) (data, hash []byte, err error) {\n\tvar encoded bytes.Buffer\n\n\tif err = gob.NewEncoder(&encoded).Encode(e); err != nil {\n\t\treturn\n\t}\n\n\tvar compressed bytes.Buffer\n\tw := gzip.NewWriter(&compressed)\n\n\tif _, err = w.Write(encoded.Bytes()); err != nil {\n\t\treturn\n\t}\n\n\tif err = w.Close(); err != nil {\n\t\treturn\n\t}\n\n\tsalt := make([]byte, saltSize)\n\tif _, err = rand.Read(salt); err != nil {\n\t\treturn\n\t}\n\n\tc, err := aes.NewCipher(derive(password, salt))\n\tif err != nil {\n\t\treturn\n\t}\n\n\tgcm, err := cipher.NewGCM(c)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tnonce := make([]byte, gcm.NonceSize())\n\tif _, err = rand.Read(nonce); err != nil {\n\t\treturn\n\t}\n\n\tvar buf bytes.Buffer\n\tsha := sha512.New()\n\tmw := io.MultiWriter(&buf, sha)\n\n\tver := make([]byte, 8)\n\tbinary.LittleEndian.PutUint64(ver, Version)\n\n\tif _, err = mw.Write(ver); err != nil {\n\t\treturn\n\t}\n\n\tif _, err = mw.Write(salt); err != nil {\n\t\treturn\n\t}\n\n\tif _, err = mw.Write(nonce); err != nil {\n\t\treturn\n\t}\n\n\tif _, err = mw.Write(gcm.Seal(nil, nonce, compressed.Bytes(), nil)); err != nil {\n\t\treturn\n\t}\n\n\treturn buf.Bytes(), sha.Sum(nil), nil\n}", "func SHA256(raw []byte) Hash {\n\treturn gosha256.Sum256(raw)\n}", "func Keccak512(data ...[]byte) []byte {\n\td := sha3.NewKeccak512()\n\tfor _, b := range data {\n\t\td.Write(b)\n\t}\n\treturn d.Sum(nil)\n}", "func Keccak512(data ...[]byte) []byte {\n\td := sha3.NewKeccak512()\n\tfor _, b := range data {\n\t\td.Write(b)\n\t}\n\treturn d.Sum(nil)\n}", "func Keccak512(data ...[]byte) []byte {\n\td := sha3.NewKeccak512()\n\tfor _, b := range data {\n\t\td.Write(b)\n\t}\n\treturn d.Sum(nil)\n}", "func getSHA256Hash(data []byte) string {\n\treturn hex.EncodeToString(getSHA256Sum(data))\n}", "func IsSHA512(str string) bool {\n\treturn IsHash(str, \"sha512\")\n}", "func (e *sha512Encryptor) Hash(password []byte) []byte {\n\te.hashFn.Reset()\n\te.hashFn.Write(password)\n\treturn e.hashFn.Sum(nil)\n}", "func hash(passphrase, token string, timestamp int64) string {\n\tbase := fmt.Sprintf(\"%s-%s-%d\", passphrase, token, timestamp)\n\treturn fmt.Sprintf(\"%x\", sha512.Sum512([]byte(base)))\n}", "func Encrypt512(block *[8]uint64, keys *[9]uint64, tweak *[3]uint64) {\n\tb0, b1, b2, b3 := block[0], block[1], block[2], block[3]\n\tb4, b5, b6, b7 := block[4], block[5], block[6], block[7]\n\n\tfor r := 0; r < 17; r++ {\n\t\tb0 += keys[r%9]\n\t\tb1 += keys[(r+1)%9]\n\t\tb2 += keys[(r+2)%9]\n\t\tb3 += keys[(r+3)%9]\n\t\tb4 += keys[(r+4)%9]\n\t\tb5 += keys[(r+5)%9] + tweak[r%3]\n\t\tb6 += keys[(r+6)%9] + tweak[(r+1)%3]\n\t\tb7 += keys[(r+7)%9] + uint64(r)\n\n\t\tb0 += b1\n\t\tb1 = (b1<<46 | b1>>(64-46)) ^ b0\n\t\tb2 += b3\n\t\tb3 = (b3<<36 | b3>>(64-36)) ^ b2\n\t\tb4 += b5\n\t\tb5 = (b5<<19 | b5>>(64-19)) ^ b4\n\t\tb6 += b7\n\t\tb7 = (b7<<37 | b7>>(64-37)) ^ b6\n\n\t\tb2 += b1\n\t\tb1 = (b1<<33 | b1>>(64-33)) ^ b2\n\t\tb4 += b7\n\t\tb7 = (b7<<27 | b7>>(64-27)) ^ b4\n\t\tb6 += b5\n\t\tb5 = (b5<<14 | b5>>(64-14)) ^ b6\n\t\tb0 += b3\n\t\tb3 = (b3<<42 | b3>>(64-42)) ^ b0\n\n\t\tb4 += b1\n\t\tb1 = (b1<<17 | b1>>(64-17)) ^ b4\n\t\tb6 += b3\n\t\tb3 = (b3<<49 | b3>>(64-49)) ^ b6\n\t\tb0 += b5\n\t\tb5 = (b5<<36 | b5>>(64-36)) ^ b0\n\t\tb2 += b7\n\t\tb7 = (b7<<39 | b7>>(64-39)) ^ b2\n\n\t\tb6 += b1\n\t\tb1 = (b1<<44 | b1>>(64-44)) ^ b6\n\t\tb0 += b7\n\t\tb7 = (b7<<9 | b7>>(64-9)) ^ b0\n\t\tb2 += b5\n\t\tb5 = (b5<<54 | b5>>(64-54)) ^ b2\n\t\tb4 += b3\n\t\tb3 = (b3<<56 | b3>>(64-56)) ^ b4\n\n\t\tr++\n\n\t\tb0 += keys[r%9]\n\t\tb1 += keys[(r+1)%9]\n\t\tb2 += keys[(r+2)%9]\n\t\tb3 += keys[(r+3)%9]\n\t\tb4 += keys[(r+4)%9]\n\t\tb5 += keys[(r+5)%9] + tweak[r%3]\n\t\tb6 += keys[(r+6)%9] + tweak[(r+1)%3]\n\t\tb7 += keys[(r+7)%9] + uint64(r)\n\n\t\tb0 += b1\n\t\tb1 = (b1<<39 | b1>>(64-39)) ^ b0\n\t\tb2 += b3\n\t\tb3 = (b3<<30 | b3>>(64-30)) ^ b2\n\t\tb4 += b5\n\t\tb5 = (b5<<34 | b5>>(64-34)) ^ b4\n\t\tb6 += b7\n\t\tb7 = (b7<<24 | b7>>(64-24)) ^ b6\n\n\t\tb2 += b1\n\t\tb1 = (b1<<13 | b1>>(64-13)) ^ b2\n\t\tb4 += b7\n\t\tb7 = (b7<<50 | b7>>(64-50)) ^ b4\n\t\tb6 += b5\n\t\tb5 = (b5<<10 | b5>>(64-10)) ^ b6\n\t\tb0 += b3\n\t\tb3 = (b3<<17 | b3>>(64-17)) ^ b0\n\n\t\tb4 += b1\n\t\tb1 = (b1<<25 | b1>>(64-25)) ^ b4\n\t\tb6 += b3\n\t\tb3 = (b3<<29 | b3>>(64-29)) ^ b6\n\t\tb0 += b5\n\t\tb5 = (b5<<39 | b5>>(64-39)) ^ b0\n\t\tb2 += b7\n\t\tb7 = (b7<<43 | b7>>(64-43)) ^ b2\n\n\t\tb6 += b1\n\t\tb1 = (b1<<8 | b1>>(64-8)) ^ b6\n\t\tb0 += b7\n\t\tb7 = (b7<<35 | b7>>(64-35)) ^ b0\n\t\tb2 += b5\n\t\tb5 = (b5<<56 | b5>>(64-56)) ^ b2\n\t\tb4 += b3\n\t\tb3 = (b3<<22 | b3>>(64-22)) ^ b4\n\t}\n\n\tb0 += keys[0]\n\tb1 += keys[1]\n\tb2 += keys[2]\n\tb3 += keys[3]\n\tb4 += keys[4]\n\tb5 += keys[5] + tweak[0]\n\tb6 += keys[6] + tweak[1]\n\tb7 += keys[7] + 18\n\n\tblock[0], block[1], block[2], block[3] = b0, b1, b2, b3\n\tblock[4], block[5], block[6], block[7] = b4, b5, b6, b7\n}", "func ValidHash512(s string) bool {\n\treturn len(s) == sha512.Size*2\n}", "func Sha256d(input []byte) Hash {\n sha := sha256.New()\n sha.Write(input)\n intermediate := sha.Sum(nil)\n sha.Reset()\n sha.Write(intermediate)\n hash, err := HashFromBytes(sha.Sum(nil), LittleEndian)\n if err != nil {\n panic(\"impossible flow, this is a bug: \" + err.Error())\n }\n return hash\n}", "func getSHA256Sum(data []byte) []byte {\n\thash := sha256.New()\n\thash.Write(data)\n\treturn hash.Sum(nil)\n}", "func DoubleSha256SH(b []byte) ShaHash {\n\tfirst := fastsha256.Sum256(b)\n\treturn ShaHash(fastsha256.Sum256(first[:]))\n}", "func (h SenHash) Sum(b []byte) []byte {\n\tb = append(b, h.blake512hasher.Sum(nil)[:32]...)\n\treturn b\n}", "func siphash(k0, k1, m uint64) uint64 {\n\t// Initialization.\n\tv0 := k0 ^ 0x736f6d6570736575\n\tv1 := k1 ^ 0x646f72616e646f6d\n\tv2 := k0 ^ 0x6c7967656e657261\n\tv3 := k1 ^ 0x7465646279746573\n\tt := uint64(8) << 56\n\n\t// Compression.\n\tv3 ^= m\n\n\t// Round 1.\n\tv0 += v1\n\tv1 = v1<<13 | v1>>(64-13)\n\tv1 ^= v0\n\tv0 = v0<<32 | v0>>(64-32)\n\n\tv2 += v3\n\tv3 = v3<<16 | v3>>(64-16)\n\tv3 ^= v2\n\n\tv0 += v3\n\tv3 = v3<<21 | v3>>(64-21)\n\tv3 ^= v0\n\n\tv2 += v1\n\tv1 = v1<<17 | v1>>(64-17)\n\tv1 ^= v2\n\tv2 = v2<<32 | v2>>(64-32)\n\n\t// Round 2.\n\tv0 += v1\n\tv1 = v1<<13 | v1>>(64-13)\n\tv1 ^= v0\n\tv0 = v0<<32 | v0>>(64-32)\n\n\tv2 += v3\n\tv3 = v3<<16 | v3>>(64-16)\n\tv3 ^= v2\n\n\tv0 += v3\n\tv3 = v3<<21 | v3>>(64-21)\n\tv3 ^= v0\n\n\tv2 += v1\n\tv1 = v1<<17 | v1>>(64-17)\n\tv1 ^= v2\n\tv2 = v2<<32 | v2>>(64-32)\n\n\tv0 ^= m\n\n\t// Compress last block.\n\tv3 ^= t\n\n\t// Round 1.\n\tv0 += v1\n\tv1 = v1<<13 | v1>>(64-13)\n\tv1 ^= v0\n\tv0 = v0<<32 | v0>>(64-32)\n\n\tv2 += v3\n\tv3 = v3<<16 | v3>>(64-16)\n\tv3 ^= v2\n\n\tv0 += v3\n\tv3 = v3<<21 | v3>>(64-21)\n\tv3 ^= v0\n\n\tv2 += v1\n\tv1 = v1<<17 | v1>>(64-17)\n\tv1 ^= v2\n\tv2 = v2<<32 | v2>>(64-32)\n\n\t// Round 2.\n\tv0 += v1\n\tv1 = v1<<13 | v1>>(64-13)\n\tv1 ^= v0\n\tv0 = v0<<32 | v0>>(64-32)\n\n\tv2 += v3\n\tv3 = v3<<16 | v3>>(64-16)\n\tv3 ^= v2\n\n\tv0 += v3\n\tv3 = v3<<21 | v3>>(64-21)\n\tv3 ^= v0\n\n\tv2 += v1\n\tv1 = v1<<17 | v1>>(64-17)\n\tv1 ^= v2\n\tv2 = v2<<32 | v2>>(64-32)\n\n\tv0 ^= t\n\n\t// Finalization.\n\tv2 ^= 0xff\n\n\t// Round 1.\n\tv0 += v1\n\tv1 = v1<<13 | v1>>(64-13)\n\tv1 ^= v0\n\tv0 = v0<<32 | v0>>(64-32)\n\n\tv2 += v3\n\tv3 = v3<<16 | v3>>(64-16)\n\tv3 ^= v2\n\n\tv0 += v3\n\tv3 = v3<<21 | v3>>(64-21)\n\tv3 ^= v0\n\n\tv2 += v1\n\tv1 = v1<<17 | v1>>(64-17)\n\tv1 ^= v2\n\tv2 = v2<<32 | v2>>(64-32)\n\n\t// Round 2.\n\tv0 += v1\n\tv1 = v1<<13 | v1>>(64-13)\n\tv1 ^= v0\n\tv0 = v0<<32 | v0>>(64-32)\n\n\tv2 += v3\n\tv3 = v3<<16 | v3>>(64-16)\n\tv3 ^= v2\n\n\tv0 += v3\n\tv3 = v3<<21 | v3>>(64-21)\n\tv3 ^= v0\n\n\tv2 += v1\n\tv1 = v1<<17 | v1>>(64-17)\n\tv1 ^= v2\n\tv2 = v2<<32 | v2>>(64-32)\n\n\t// Round 3.\n\tv0 += v1\n\tv1 = v1<<13 | v1>>(64-13)\n\tv1 ^= v0\n\tv0 = v0<<32 | v0>>(64-32)\n\n\tv2 += v3\n\tv3 = v3<<16 | v3>>(64-16)\n\tv3 ^= v2\n\n\tv0 += v3\n\tv3 = v3<<21 | v3>>(64-21)\n\tv3 ^= v0\n\n\tv2 += v1\n\tv1 = v1<<17 | v1>>(64-17)\n\tv1 ^= v2\n\tv2 = v2<<32 | v2>>(64-32)\n\n\t// Round 4.\n\tv0 += v1\n\tv1 = v1<<13 | v1>>(64-13)\n\tv1 ^= v0\n\tv0 = v0<<32 | v0>>(64-32)\n\n\tv2 += v3\n\tv3 = v3<<16 | v3>>(64-16)\n\tv3 ^= v2\n\n\tv0 += v3\n\tv3 = v3<<21 | v3>>(64-21)\n\tv3 ^= v0\n\n\tv2 += v1\n\tv1 = v1<<17 | v1>>(64-17)\n\tv1 ^= v2\n\tv2 = v2<<32 | v2>>(64-32)\n\n\treturn v0 ^ v1 ^ v2 ^ v3\n}", "func ShortHash(data ...string) string {\n\th := sha1.New()\n\tio.WriteString(h, strings.Join(data, \"\"))\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil)[:4])\n}", "func generateSHA256HashInHexForm(preimage string) string {\n\thasher := sha256.New()\n\thasher.Write([]byte(preimage))\n\tshaHash := hasher.Sum(nil)\n\tshaHashHex := hex.EncodeToString(shaHash)\n\treturn shaHashHex\n}", "func Hash(data []byte) {\n\tfor i := 0; i < 50; i++ {\n\t\tsha256.Sum256(data)\n\t}\n}", "func MASSSHA256(raw []byte) Hash {\n\treturn sha256.Sum256(raw)\n}", "func (d *Avx512Digest) Sum(in []byte) (result []byte) {\n\n\tif d.final {\n\t\treturn append(in, d.result[:]...)\n\t}\n\n\ttrail := make([]byte, 0, 128)\n\ttrail = append(trail, d.x[:d.nx]...)\n\n\tlen := d.len\n\t// Padding. Add a 1 bit and 0 bits until 56 bytes mod 64.\n\tvar tmp [64]byte\n\ttmp[0] = 0x80\n\tif len%64 < 56 {\n\t\ttrail = append(trail, tmp[0:56-len%64]...)\n\t} else {\n\t\ttrail = append(trail, tmp[0:64+56-len%64]...)\n\t}\n\td.nx = 0\n\n\t// Length in bits.\n\tlen <<= 3\n\tfor i := uint(0); i < 8; i++ {\n\t\ttmp[i] = byte(len >> (56 - 8*i))\n\t}\n\ttrail = append(trail, tmp[0:8]...)\n\n\tsumCh := make(chan [Size]byte)\n\td.a512srv.blocksCh <- blockInput{uid: d.uid, msg: trail, final: true, sumCh: sumCh}\n\td.result = <-sumCh\n\td.final = true\n\treturn append(in, d.result[:]...)\n}", "func SHA256Hash(data []byte) []byte {\n\tsum := sha256.Sum256(data)\n\treturn sum[:]\n}", "func CalcHash(r io.Reader) (b []byte, err error) {\n\thash := sha512.New()\n\t_, err = io.Copy(hash, r)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tsum := hash.Sum(b)\n\tb = make([]byte, hex.EncodedLen(len(sum)))\n\thex.Encode(b, sum)\n\n\treturn\n}", "func hash(data []byte) [32]byte {\n\tvar hash [32]byte\n\n\th := sha256.New()\n\t// The hash interface never returns an error, for that reason\n\t// we are not handling the error below. For reference, it is\n\t// stated here https://golang.org/pkg/hash/#Hash\n\t// #nosec G104\n\th.Write(data)\n\th.Sum(hash[:0])\n\n\treturn hash\n}", "func Sha256Hmac(secret string, data string) string {\n\t// Create a new HMAC by defining the hash type and the key (as byte array)\n\th := hmac.New(sha256.New, []byte(secret))\n\n\t// Write Data to it\n\th.Write([]byte(data))\n\n\t// Get result and encode as hexadecimal string\n\tsha := hex.EncodeToString(h.Sum(nil))\n\n\treturn sha\n}", "func sumHash(c byte, h uint32) uint32 {\n\treturn (h * hashPrime) ^ uint32(c)\n}", "func hash(elements ...[32]byte) [32]byte {\n\tvar hash []byte\n\tfor i := range elements {\n\t\thash = append(hash, elements[i][:]...)\n\t}\n\treturn sha256.Sum256(hash)\n}", "func Hash(t *Token) (hash []byte) {\n var sum []byte\n\n // Compute the SHA1 sum of the Token\n {\n shasum := sha1.Sum([]byte(salt+string(*t)))\n copy(sum[:], shasum[:20])\n }\n\n // Encode the sum to hexadecimal\n hex.Encode(sum, sum)\n\n return\n}", "func hashSHA256(str string) string {\n\ts := sha256.New()\n\ts.Write([]byte(str))\n\treturn base64.StdEncoding.EncodeToString(s.Sum(nil))\n}", "func Sum128(data []byte) (h1 uint64, h2 uint64)", "func HashASM(k0, k1 uint64, p []byte) uint64", "func SHA512Half(v []byte) (string, error) {\n\th := sha512.New()\n\t_, err := io.Copy(h, bytes.NewBuffer(v))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil)[:sha512.Size/2]), nil\n}", "func SHA256RNDS2(x, mx, x1 operand.Op) { ctx.SHA256RNDS2(x, mx, x1) }", "func Sha3512(bs []byte) ([]byte, error) {\n\treturn PerformHash(sha3.New512(), bs)\n}", "func HS512(secret []byte) SignerVerifier {\n\treturn SymmetricSignature(&HMACSignerVerifier{\n\t\th: sha512.New,\n\t\tsecret: secret,\n\t\talg: ALG_HS512,\n\t})\n}", "func BlobHash(blob []byte) string {\n\thashBytes := sha512.Sum384(blob)\n\treturn hex.EncodeToString(hashBytes[:])\n}", "func generateSHA256HashInBase64Form(preimage string) string {\n\thasher := sha256.New()\n\thasher.Write([]byte(preimage))\n\tshaHash := hasher.Sum(nil)\n\tshaHashBase64 := base64.StdEncoding.EncodeToString(shaHash)\n\treturn shaHashBase64\n}", "func hash(ba string) string {\n\th := sha256.New()\n\th.Write([]byte(ba))\n\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}", "func RS512(priv *rsa.PrivateKey, pub *rsa.PublicKey) Signer {\n\treturn &rsasha{priv: priv, pub: pub, hash: crypto.SHA512, alg: MethodRS512}\n}", "func UsingSha256(data []byte) []byte {\n\th := sha256.New()\n\th.Write(data)\n\tout := h.Sum(nil)\n\n\treturn out\n}", "func Sha256(data string, salt string) string {\n\tb := []byte(data + salt)\n\treturn fmt.Sprintf(\"%X\", sha256.Sum256(b))\n}", "func Sha256Hash(file io.Reader) (string, error) {\n\tbuf := bytes.NewBuffer(nil)\n\tif _, err := io.Copy(buf, file); err != nil {\n\t\tlog.Println(\"Failed to copy file to buffer in hashing function...\")\n\t\treturn \"\", err\n\t}\n\n\thasher := sha256.New()\n\thasher.Write(buf.Bytes())\n\n\tsha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))\n\n\treturn sha, nil\n}", "func calcHash(data string) string {\n\th := sha256.New()\n\th.Write([]byte(data))\n\thash := fmt.Sprintf(\"%x\", h.Sum(nil))\n\treturn hash\n}", "func Sum(bz []byte) []byte {\n\thash := sha256.Sum256(bz)\n\treturn hash[:20]\n}", "func (n Node) CalSHA256Hash(input []byte) []byte {\r\n\th := sha256.New()\r\n\th.Write(input)\r\n\treturn h.Sum(nil)\r\n}", "func Sha2(s string) string {\n\treturn hashing(sha256.New(), s)\n}", "func sum256(data []byte) []byte {\n\thash := sha256.New()\n\thash.Write(data)\n\treturn hash.Sum(nil)\n}", "func Hash20(v []byte) []byte {\n\th := sha512.New()\n\th.Write(v)\n\treturn h.Sum(nil)[:20]\n}", "func h(data string) string {\n\tdigest := md5.New()\n\tdigest.Write([]byte(data))\n\treturn fmt.Sprintf(\"%x\", digest.Sum(nil))\n}", "func encrypt512(dst, src *[8]uint64, k *[8]uint64, t *[2]uint64) {\n\tvar p0, p1, p2, p3, p4, p5, p6, p7 = src[0], src[1], src[2], src[3], src[4], src[5], src[6], src[7]\n\tt2 := t[0] ^ t[1]\n\tk8 := c240 ^ k[0] ^ k[1] ^ k[2] ^ k[3] ^ k[4] ^ k[5] ^ k[6] ^ k[7]\n\n\tp0 += k[0]\n\n\tp1 += k[1]\n\n\tp2 += k[2]\n\n\tp3 += k[3]\n\n\tp4 += k[4]\n\n\tp5 += k[5] + t[0]\n\n\tp6 += k[6] + t[1]\n\n\tp7 += k[7] + 0\n\n\tp0 += p1\n\tp1 = p1<<46 | p1>>(64-46)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<36 | p3>>(64-36)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<19 | p5>>(64-19)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<37 | p7>>(64-37)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<33 | p1>>(64-33)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<27 | p7>>(64-27)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<14 | p5>>(64-14)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<42 | p3>>(64-42)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<17 | p1>>(64-17)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<49 | p3>>(64-49)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<36 | p5>>(64-36)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<39 | p7>>(64-39)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<44 | p1>>(64-44)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<9 | p7>>(64-9)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<54 | p5>>(64-54)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<56 | p3>>(64-56)\n\tp3 ^= p4\n\n\tp0 += k[1]\n\n\tp1 += k[2]\n\n\tp2 += k[3]\n\n\tp3 += k[4]\n\n\tp4 += k[5]\n\n\tp5 += k[6] + t[1]\n\n\tp6 += k[7] + t2\n\n\tp7 += k8 + 1\n\n\tp0 += p1\n\tp1 = p1<<39 | p1>>(64-39)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<30 | p3>>(64-30)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<34 | p5>>(64-34)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<24 | p7>>(64-24)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<13 | p1>>(64-13)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<50 | p7>>(64-50)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<10 | p5>>(64-10)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<17 | p3>>(64-17)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<25 | p1>>(64-25)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<29 | p3>>(64-29)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<39 | p5>>(64-39)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<43 | p7>>(64-43)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<8 | p1>>(64-8)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<35 | p7>>(64-35)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<56 | p5>>(64-56)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<22 | p3>>(64-22)\n\tp3 ^= p4\n\n\tp0 += k[2]\n\n\tp1 += k[3]\n\n\tp2 += k[4]\n\n\tp3 += k[5]\n\n\tp4 += k[6]\n\n\tp5 += k[7] + t2\n\n\tp6 += k8 + t[0]\n\n\tp7 += k[0] + 2\n\n\tp0 += p1\n\tp1 = p1<<46 | p1>>(64-46)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<36 | p3>>(64-36)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<19 | p5>>(64-19)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<37 | p7>>(64-37)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<33 | p1>>(64-33)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<27 | p7>>(64-27)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<14 | p5>>(64-14)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<42 | p3>>(64-42)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<17 | p1>>(64-17)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<49 | p3>>(64-49)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<36 | p5>>(64-36)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<39 | p7>>(64-39)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<44 | p1>>(64-44)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<9 | p7>>(64-9)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<54 | p5>>(64-54)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<56 | p3>>(64-56)\n\tp3 ^= p4\n\n\tp0 += k[3]\n\n\tp1 += k[4]\n\n\tp2 += k[5]\n\n\tp3 += k[6]\n\n\tp4 += k[7]\n\n\tp5 += k8 + t[0]\n\n\tp6 += k[0] + t[1]\n\n\tp7 += k[1] + 3\n\n\tp0 += p1\n\tp1 = p1<<39 | p1>>(64-39)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<30 | p3>>(64-30)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<34 | p5>>(64-34)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<24 | p7>>(64-24)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<13 | p1>>(64-13)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<50 | p7>>(64-50)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<10 | p5>>(64-10)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<17 | p3>>(64-17)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<25 | p1>>(64-25)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<29 | p3>>(64-29)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<39 | p5>>(64-39)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<43 | p7>>(64-43)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<8 | p1>>(64-8)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<35 | p7>>(64-35)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<56 | p5>>(64-56)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<22 | p3>>(64-22)\n\tp3 ^= p4\n\n\tp0 += k[4]\n\n\tp1 += k[5]\n\n\tp2 += k[6]\n\n\tp3 += k[7]\n\n\tp4 += k8\n\n\tp5 += k[0] + t[1]\n\n\tp6 += k[1] + t2\n\n\tp7 += k[2] + 4\n\n\tp0 += p1\n\tp1 = p1<<46 | p1>>(64-46)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<36 | p3>>(64-36)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<19 | p5>>(64-19)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<37 | p7>>(64-37)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<33 | p1>>(64-33)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<27 | p7>>(64-27)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<14 | p5>>(64-14)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<42 | p3>>(64-42)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<17 | p1>>(64-17)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<49 | p3>>(64-49)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<36 | p5>>(64-36)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<39 | p7>>(64-39)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<44 | p1>>(64-44)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<9 | p7>>(64-9)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<54 | p5>>(64-54)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<56 | p3>>(64-56)\n\tp3 ^= p4\n\n\tp0 += k[5]\n\n\tp1 += k[6]\n\n\tp2 += k[7]\n\n\tp3 += k8\n\n\tp4 += k[0]\n\n\tp5 += k[1] + t2\n\n\tp6 += k[2] + t[0]\n\n\tp7 += k[3] + 5\n\n\tp0 += p1\n\tp1 = p1<<39 | p1>>(64-39)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<30 | p3>>(64-30)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<34 | p5>>(64-34)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<24 | p7>>(64-24)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<13 | p1>>(64-13)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<50 | p7>>(64-50)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<10 | p5>>(64-10)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<17 | p3>>(64-17)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<25 | p1>>(64-25)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<29 | p3>>(64-29)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<39 | p5>>(64-39)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<43 | p7>>(64-43)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<8 | p1>>(64-8)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<35 | p7>>(64-35)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<56 | p5>>(64-56)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<22 | p3>>(64-22)\n\tp3 ^= p4\n\n\tp0 += k[6]\n\n\tp1 += k[7]\n\n\tp2 += k8\n\n\tp3 += k[0]\n\n\tp4 += k[1]\n\n\tp5 += k[2] + t[0]\n\n\tp6 += k[3] + t[1]\n\n\tp7 += k[4] + 6\n\n\tp0 += p1\n\tp1 = p1<<46 | p1>>(64-46)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<36 | p3>>(64-36)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<19 | p5>>(64-19)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<37 | p7>>(64-37)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<33 | p1>>(64-33)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<27 | p7>>(64-27)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<14 | p5>>(64-14)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<42 | p3>>(64-42)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<17 | p1>>(64-17)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<49 | p3>>(64-49)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<36 | p5>>(64-36)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<39 | p7>>(64-39)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<44 | p1>>(64-44)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<9 | p7>>(64-9)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<54 | p5>>(64-54)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<56 | p3>>(64-56)\n\tp3 ^= p4\n\n\tp0 += k[7]\n\n\tp1 += k8\n\n\tp2 += k[0]\n\n\tp3 += k[1]\n\n\tp4 += k[2]\n\n\tp5 += k[3] + t[1]\n\n\tp6 += k[4] + t2\n\n\tp7 += k[5] + 7\n\n\tp0 += p1\n\tp1 = p1<<39 | p1>>(64-39)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<30 | p3>>(64-30)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<34 | p5>>(64-34)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<24 | p7>>(64-24)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<13 | p1>>(64-13)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<50 | p7>>(64-50)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<10 | p5>>(64-10)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<17 | p3>>(64-17)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<25 | p1>>(64-25)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<29 | p3>>(64-29)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<39 | p5>>(64-39)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<43 | p7>>(64-43)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<8 | p1>>(64-8)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<35 | p7>>(64-35)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<56 | p5>>(64-56)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<22 | p3>>(64-22)\n\tp3 ^= p4\n\n\tp0 += k8\n\n\tp1 += k[0]\n\n\tp2 += k[1]\n\n\tp3 += k[2]\n\n\tp4 += k[3]\n\n\tp5 += k[4] + t2\n\n\tp6 += k[5] + t[0]\n\n\tp7 += k[6] + 8\n\n\tp0 += p1\n\tp1 = p1<<46 | p1>>(64-46)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<36 | p3>>(64-36)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<19 | p5>>(64-19)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<37 | p7>>(64-37)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<33 | p1>>(64-33)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<27 | p7>>(64-27)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<14 | p5>>(64-14)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<42 | p3>>(64-42)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<17 | p1>>(64-17)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<49 | p3>>(64-49)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<36 | p5>>(64-36)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<39 | p7>>(64-39)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<44 | p1>>(64-44)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<9 | p7>>(64-9)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<54 | p5>>(64-54)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<56 | p3>>(64-56)\n\tp3 ^= p4\n\n\tp0 += k[0]\n\n\tp1 += k[1]\n\n\tp2 += k[2]\n\n\tp3 += k[3]\n\n\tp4 += k[4]\n\n\tp5 += k[5] + t[0]\n\n\tp6 += k[6] + t[1]\n\n\tp7 += k[7] + 9\n\n\tp0 += p1\n\tp1 = p1<<39 | p1>>(64-39)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<30 | p3>>(64-30)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<34 | p5>>(64-34)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<24 | p7>>(64-24)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<13 | p1>>(64-13)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<50 | p7>>(64-50)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<10 | p5>>(64-10)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<17 | p3>>(64-17)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<25 | p1>>(64-25)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<29 | p3>>(64-29)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<39 | p5>>(64-39)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<43 | p7>>(64-43)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<8 | p1>>(64-8)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<35 | p7>>(64-35)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<56 | p5>>(64-56)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<22 | p3>>(64-22)\n\tp3 ^= p4\n\n\tp0 += k[1]\n\n\tp1 += k[2]\n\n\tp2 += k[3]\n\n\tp3 += k[4]\n\n\tp4 += k[5]\n\n\tp5 += k[6] + t[1]\n\n\tp6 += k[7] + t2\n\n\tp7 += k8 + 10\n\n\tp0 += p1\n\tp1 = p1<<46 | p1>>(64-46)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<36 | p3>>(64-36)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<19 | p5>>(64-19)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<37 | p7>>(64-37)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<33 | p1>>(64-33)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<27 | p7>>(64-27)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<14 | p5>>(64-14)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<42 | p3>>(64-42)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<17 | p1>>(64-17)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<49 | p3>>(64-49)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<36 | p5>>(64-36)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<39 | p7>>(64-39)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<44 | p1>>(64-44)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<9 | p7>>(64-9)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<54 | p5>>(64-54)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<56 | p3>>(64-56)\n\tp3 ^= p4\n\n\tp0 += k[2]\n\n\tp1 += k[3]\n\n\tp2 += k[4]\n\n\tp3 += k[5]\n\n\tp4 += k[6]\n\n\tp5 += k[7] + t2\n\n\tp6 += k8 + t[0]\n\n\tp7 += k[0] + 11\n\n\tp0 += p1\n\tp1 = p1<<39 | p1>>(64-39)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<30 | p3>>(64-30)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<34 | p5>>(64-34)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<24 | p7>>(64-24)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<13 | p1>>(64-13)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<50 | p7>>(64-50)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<10 | p5>>(64-10)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<17 | p3>>(64-17)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<25 | p1>>(64-25)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<29 | p3>>(64-29)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<39 | p5>>(64-39)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<43 | p7>>(64-43)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<8 | p1>>(64-8)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<35 | p7>>(64-35)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<56 | p5>>(64-56)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<22 | p3>>(64-22)\n\tp3 ^= p4\n\n\tp0 += k[3]\n\n\tp1 += k[4]\n\n\tp2 += k[5]\n\n\tp3 += k[6]\n\n\tp4 += k[7]\n\n\tp5 += k8 + t[0]\n\n\tp6 += k[0] + t[1]\n\n\tp7 += k[1] + 12\n\n\tp0 += p1\n\tp1 = p1<<46 | p1>>(64-46)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<36 | p3>>(64-36)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<19 | p5>>(64-19)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<37 | p7>>(64-37)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<33 | p1>>(64-33)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<27 | p7>>(64-27)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<14 | p5>>(64-14)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<42 | p3>>(64-42)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<17 | p1>>(64-17)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<49 | p3>>(64-49)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<36 | p5>>(64-36)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<39 | p7>>(64-39)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<44 | p1>>(64-44)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<9 | p7>>(64-9)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<54 | p5>>(64-54)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<56 | p3>>(64-56)\n\tp3 ^= p4\n\n\tp0 += k[4]\n\n\tp1 += k[5]\n\n\tp2 += k[6]\n\n\tp3 += k[7]\n\n\tp4 += k8\n\n\tp5 += k[0] + t[1]\n\n\tp6 += k[1] + t2\n\n\tp7 += k[2] + 13\n\n\tp0 += p1\n\tp1 = p1<<39 | p1>>(64-39)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<30 | p3>>(64-30)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<34 | p5>>(64-34)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<24 | p7>>(64-24)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<13 | p1>>(64-13)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<50 | p7>>(64-50)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<10 | p5>>(64-10)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<17 | p3>>(64-17)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<25 | p1>>(64-25)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<29 | p3>>(64-29)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<39 | p5>>(64-39)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<43 | p7>>(64-43)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<8 | p1>>(64-8)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<35 | p7>>(64-35)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<56 | p5>>(64-56)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<22 | p3>>(64-22)\n\tp3 ^= p4\n\n\tp0 += k[5]\n\n\tp1 += k[6]\n\n\tp2 += k[7]\n\n\tp3 += k8\n\n\tp4 += k[0]\n\n\tp5 += k[1] + t2\n\n\tp6 += k[2] + t[0]\n\n\tp7 += k[3] + 14\n\n\tp0 += p1\n\tp1 = p1<<46 | p1>>(64-46)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<36 | p3>>(64-36)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<19 | p5>>(64-19)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<37 | p7>>(64-37)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<33 | p1>>(64-33)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<27 | p7>>(64-27)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<14 | p5>>(64-14)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<42 | p3>>(64-42)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<17 | p1>>(64-17)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<49 | p3>>(64-49)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<36 | p5>>(64-36)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<39 | p7>>(64-39)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<44 | p1>>(64-44)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<9 | p7>>(64-9)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<54 | p5>>(64-54)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<56 | p3>>(64-56)\n\tp3 ^= p4\n\n\tp0 += k[6]\n\n\tp1 += k[7]\n\n\tp2 += k8\n\n\tp3 += k[0]\n\n\tp4 += k[1]\n\n\tp5 += k[2] + t[0]\n\n\tp6 += k[3] + t[1]\n\n\tp7 += k[4] + 15\n\n\tp0 += p1\n\tp1 = p1<<39 | p1>>(64-39)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<30 | p3>>(64-30)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<34 | p5>>(64-34)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<24 | p7>>(64-24)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<13 | p1>>(64-13)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<50 | p7>>(64-50)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<10 | p5>>(64-10)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<17 | p3>>(64-17)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<25 | p1>>(64-25)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<29 | p3>>(64-29)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<39 | p5>>(64-39)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<43 | p7>>(64-43)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<8 | p1>>(64-8)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<35 | p7>>(64-35)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<56 | p5>>(64-56)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<22 | p3>>(64-22)\n\tp3 ^= p4\n\n\tp0 += k[7]\n\n\tp1 += k8\n\n\tp2 += k[0]\n\n\tp3 += k[1]\n\n\tp4 += k[2]\n\n\tp5 += k[3] + t[1]\n\n\tp6 += k[4] + t2\n\n\tp7 += k[5] + 16\n\n\tp0 += p1\n\tp1 = p1<<46 | p1>>(64-46)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<36 | p3>>(64-36)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<19 | p5>>(64-19)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<37 | p7>>(64-37)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<33 | p1>>(64-33)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<27 | p7>>(64-27)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<14 | p5>>(64-14)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<42 | p3>>(64-42)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<17 | p1>>(64-17)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<49 | p3>>(64-49)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<36 | p5>>(64-36)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<39 | p7>>(64-39)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<44 | p1>>(64-44)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<9 | p7>>(64-9)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<54 | p5>>(64-54)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<56 | p3>>(64-56)\n\tp3 ^= p4\n\n\tp0 += k8\n\n\tp1 += k[0]\n\n\tp2 += k[1]\n\n\tp3 += k[2]\n\n\tp4 += k[3]\n\n\tp5 += k[4] + t2\n\n\tp6 += k[5] + t[0]\n\n\tp7 += k[6] + 17\n\n\tp0 += p1\n\tp1 = p1<<39 | p1>>(64-39)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<30 | p3>>(64-30)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<34 | p5>>(64-34)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<24 | p7>>(64-24)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<13 | p1>>(64-13)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<50 | p7>>(64-50)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<10 | p5>>(64-10)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<17 | p3>>(64-17)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<25 | p1>>(64-25)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<29 | p3>>(64-29)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<39 | p5>>(64-39)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<43 | p7>>(64-43)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<8 | p1>>(64-8)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<35 | p7>>(64-35)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<56 | p5>>(64-56)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<22 | p3>>(64-22)\n\tp3 ^= p4\n\n\tp0 += k[0]\n\n\tp1 += k[1]\n\n\tp2 += k[2]\n\n\tp3 += k[3]\n\n\tp4 += k[4]\n\n\tp5 += k[5] + t[0]\n\n\tp6 += k[6] + t[1]\n\n\tp7 += k[7] + 18\n\n\tdst[0], dst[1], dst[2], dst[3], dst[4], dst[5], dst[6], dst[7] = p0, p1, p2, p3, p4, p5, p6, p7\n}", "func H(data string) string {\n\tdigest := md5.New()\n\tdigest.Write([]byte(data))\n\treturn fmt.Sprintf(\"%x\", digest.Sum(nil))\n}", "func H(data string) string {\n\tdigest := md5.New()\n\tdigest.Write([]byte(data))\n\treturn fmt.Sprintf(\"%x\", digest.Sum(nil))\n}", "func hashSHA256(input string) string {\n\th := sha1.New()\n\th.Write([]byte(input))\n\treturn hex.EncodeToString(h.Sum(nil))\n}", "func shortHash(name string) string {\n\th := sha1.Sum([]byte(name))\n\treturn fmt.Sprintf(\"%0x\", h)[:6]\n}", "func Hashit(tox string) string {\n h:= sha256.New()\n h.Write([]byte(tox))\n bs := h.Sum([]byte{})\n str := base64.StdEncoding.EncodeToString(bs)\n return str\n}", "func hasher(s string) []byte {\n\tval := sha256.Sum256([]byte(s))\n\tvar hex []string\n\n\t// Iterate through the bytes.\n\tfor i := 0; i < len(val); i++ {\n\t\t// We want each number to be represented by 2 chars.\n\t\tplaceHolder := []string{\"0\"}\n\t\tvalue := strconv.FormatInt(int64(val[i]), 16)\n\n\t\tif len(value) != 2 {\n\t\t\tplaceHolder = append(placeHolder, value)\n\t\t\thex = append(hex, strings.Join(placeHolder, \"\"))\n\t\t} else {\n\t\t\thex = append(hex, value)\n\t\t}\n\t}\n\treturn []byte(strings.Join(hex, \"\"))\n\n}", "func SHA256Hex(data []byte) string {\n\treturn hex.EncodeToString(SHA256(data))\n}", "func (xxh xxHash) Sum(b []byte) []byte {\n\th64 := xxh.Sum64()\n\treturn append(b, byte(h64), byte(h64>>8), byte(h64>>16), byte(h64>>24), byte(h64>>32), byte(h64>>40), byte(h64>>48), byte(h64>>56))\n}", "func SumDoubleSha256(data []byte) [sha256.Size]byte {\n\th := sha256.Sum256(data)\n\treturn sha256.Sum256(h[:])\n}", "func Of(data []byte) (hash Hash) {\n\treturn sha256.Sum256(data)\n}", "func BlobHash(data []byte) SHA256 {\n\treturn SumSHA256(data)\n}", "func computeHash(w http.ResponseWriter, req *http.Request) {\n\tvalues := req.URL.Query()\n\tdata := values.Get(\"data\")\n\tif data == \"\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"400 - data param not present\"))\n\t\treturn\n\t}\n\tsalt := values.Get(\"salt\")\n\tif salt == \"\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"400 - salt param not present\"))\n\t\treturn\n\t}\n\th := sha256.Sum256([]byte(data+salt))\n\tencodedStr := hex.EncodeToString(h[:])\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(encodedStr))\n}", "func sha256hex(buf []byte) (string, error) {\n\thasher := sha256.New()\n\tif _, err := hasher.Write(buf); err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to get sha256 hash: %w\", err)\n\t}\n\tcCodeHash := hasher.Sum(nil)\n\treturn hex.EncodeToString(cCodeHash), nil\n}", "func Hash(strings ...string) uint32 {\n\tdigester := fnv.New32()\n\tfor _, s := range strings {\n\t\t_, _ = io.WriteString(digester, s)\n\t}\n\treturn digester.Sum32()\n}", "func Hashbin(tox string) []byte {\n h:= sha256.New()\n h.Write([]byte(tox))\n bs := h.Sum([]byte{})\n return bs \n}", "func (d *digest) compress() {\n\tvar m, v [16]uint32\n\tfor i := 0; i < 16; i++ {\n\t\tm[i] = binary.LittleEndian.Uint32(d.buf[i*4:])\n\t}\n\tfor i := 0; i < 8; i++ {\n\t\tv[i] = d.h[i]\n\t}\n\tv[8] = iv[0]\n\tv[9] = iv[1]\n\tv[10] = iv[2]\n\tv[11] = iv[3]\n\tv[12] = d.t[0] ^ iv[4]\n\tv[13] = d.t[1] ^ iv[5]\n\tv[14] = d.f[0] ^ iv[6]\n\tv[15] = d.f[1] ^ iv[7]\n\n\trotr32 := func (w uint32, c uint32) uint32 {\n\t\treturn (w>>c) | (w<<(32-c))\n\t}\n\tG := func(r, i, a, b, c, d int) {\n\t\tv[a] = v[a] + v[b] + m[sigma[r][2*i+0]]\n\t\tv[d] = rotr32(v[d] ^ v[a], 16)\n\t\tv[c] = v[c] + v[d]\n\t\tv[b] = rotr32(v[b] ^ v[c], 12)\n\t\tv[a] = v[a] + v[b] + m[sigma[r][2*i+1]]\n\t\tv[d] = rotr32(v[d] ^ v[a], 8)\n\t\tv[c] = v[c] + v[d]\n\t\tv[b] = rotr32(v[b] ^ v[c], 7)\n\t}\n\tfor i := 0; i < 10; i++ {\n\t\tG(i, 0, 0, 4, 8, 12);\n\t\tG(i, 1, 1, 5, 9, 13);\n\t\tG(i, 2, 2, 6, 10, 14);\n\t\tG(i, 3, 3, 7, 11, 15);\n\t\tG(i, 4, 0, 5, 10, 15);\n\t\tG(i, 5, 1, 6, 11, 12);\n\t\tG(i, 6, 2, 7, 8, 13);\n\t\tG(i, 7, 3, 4, 9, 14);\n\t}\n\tfor i := 0; i < 8; i++ {\n\t\td.h[i] = d.h[i] ^ v[i] ^ v[i+8]\n\t}\n}", "func Sha256(data []byte) []byte {\n\n\thash := sha256.New()\n\thash.Write(data)\n\treturn hash.Sum(nil)\n}", "func (r *Restriction) hash() ([]byte, error) {\n\tj, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\treturn hashUtils.SHA512(j), nil\n}", "func sha256a(authKey Key, msgKey bin.Int128, x int) []byte {\n\th := getSHA256()\n\tdefer sha256Pool.Put(h)\n\n\t_, _ = h.Write(msgKey[:])\n\t_, _ = h.Write(authKey[x : x+36])\n\n\treturn h.Sum(nil)\n}", "func hash(s string) uint32 {\n h := fnv.New32a()\n h.Write([]byte(s))\n return h.Sum32()\n}", "func hash(key uint64) uint64 {\r\n\tkey ^= key >> 33\r\n\tkey *= 0xff51afd7ed558ccd\r\n\tkey ^= key >> 33\r\n\tkey *= 0xc4ceb9fe1a85ec53\r\n\tkey ^= key >> 33\r\n\treturn key\r\n}", "func generatePasswordHash(password string) string {\n sum := sha256.Sum256([]byte(password))\n return hex.EncodeToString(sum[:])\n}", "func isSHA512(fl FieldLevel) bool {\n\treturn sha512Regex.MatchString(fl.Field().String())\n}", "func smash(s string) string {\n\th := md5.New()\n\tio.WriteString(h, s)\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}" ]
[ "0.71457267", "0.7137372", "0.71343416", "0.7030582", "0.7016465", "0.69781184", "0.69202495", "0.6910378", "0.68863237", "0.6845672", "0.669029", "0.66801846", "0.6605951", "0.65616447", "0.6538958", "0.652667", "0.6514055", "0.64949244", "0.6492306", "0.64635265", "0.645904", "0.643501", "0.6400413", "0.63999534", "0.6355423", "0.6290897", "0.62871015", "0.6261302", "0.6239916", "0.6239916", "0.6239916", "0.6239509", "0.6208377", "0.6207036", "0.61905396", "0.61548257", "0.6150303", "0.61454564", "0.6137102", "0.6132429", "0.613213", "0.61071664", "0.6106962", "0.60835356", "0.608022", "0.6073046", "0.60712296", "0.6065794", "0.6064683", "0.6039611", "0.60342425", "0.60298455", "0.60157037", "0.601134", "0.6003275", "0.59953374", "0.59928787", "0.59775645", "0.59680164", "0.59627306", "0.5940875", "0.59356475", "0.5916646", "0.59151816", "0.5914529", "0.5913536", "0.590937", "0.5909111", "0.5903013", "0.5886783", "0.5885533", "0.58681965", "0.58644855", "0.5860713", "0.58556193", "0.5853182", "0.58524144", "0.58524144", "0.5849702", "0.58431846", "0.58163744", "0.58122677", "0.5809838", "0.58093107", "0.58063495", "0.5788263", "0.57814014", "0.5780816", "0.57807916", "0.57764614", "0.57746226", "0.57743794", "0.57722634", "0.5761517", "0.5760191", "0.5756978", "0.5756642", "0.5752242", "0.5750138", "0.57495046" ]
0.7974872
0
this example must panic!
func ExampleFind() { //sl := []int{1,2,3,4,5} //Find(sl, func(elem int) bool { // if elem == 99 { // return true // } // return false //}) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func tryPanic() {\n\tpanic(\"panik ga?! panik ga?! ya panik lah masa ngga!\")\n}", "func bug(err error) error {\n\treturn fmt.Errorf(\"BUG(go-landlock): This should not have happened: %w\", err)\n}", "func panicRecover(input *models.RunningInput) {\n\tif err := recover(); err != nil {\n\t\ttrace := make([]byte, 2048)\n\t\truntime.Stack(trace, true)\n\t\tlog.Printf(\"E! FATAL: [%s] panicked: %s, Stack:\\n%s\",\n\t\t\tinput.LogName(), err, trace)\n\t\tlog.Println(\"E! PLEASE REPORT THIS PANIC ON GITHUB with \" +\n\t\t\t\"stack trace, configuration, and OS information: \" +\n\t\t\t\"https://github.com/influxdata/telegraf/issues/new/choose\")\n\t}\n}", "func secp256k1GoPanicIllegal(msg *C.char, data unsafe.Pointer) {\n\tpanic(\"illegal argument: \" + C.GoString(msg))\n}", "func crash1(msg string) {\n\tif msg == \"good-bye\" {\n\t\tpanic(errors.New(\"something went wrong\"))\n\t}\n}", "func TestParseCarFromCSVPanicEmptyLine(t *testing.T) {\n defer func() {\n if r := recover(); r == nil {\n t.Errorf(\"The code didn't panic\")\n }\n\t}()\n\tcar, _ := parseCarFromCSV(\"\")\n\tt.Fatalf(\"Car %v shoulden't be reached here, this must panic\",car)\n}", "func ejemploPanic() {\n\ta := 1\n\tif a == 1 {\n\t\tpanic(\"Se encontró el valor de 1\") //fuerza el error y aborta el programa\n\t}\n}", "func TestGetAndRecoverPanic(t *testing.T) {\n\tassert.NotNil(t, GetAndRecoverPanic(), \"error on panic can't be nil\")\n}", "func shouldPanic(t *testing.T, context string, fx func()) {\r\n\tdefer func() {\r\n\t\tif err := recover(); err == nil {\r\n\t\t\tt.Errorf(\"\\t\\t%s Should paniced when giving unknown key %q.\", failed, context)\r\n\t\t} else {\r\n\t\t\tt.Logf(\"\\t\\t%s Should paniced when giving unknown key %q.\", succeed, context)\r\n\t\t}\r\n\t}()\r\n\r\n\tfx()\r\n}", "func recover() interface{} {\n\treturn nil\n}", "func forcePanic() {\n\tpanic(\"picknicking... :)\")\n}", "func testPanic() (err error) {\n\tdefer catchPanic(&err, \"TestPanic\")\n\tfmt.Printf(\"\\nTestPanic: Start Test\\n\")\n\n\terr = mimicError(\"1\")\n\n\tpanic(\"Mimic Panic\")\n}", "func panicIfErr(err error) {\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}", "func panicIfErr(err error) {\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}", "func badstate() {\n\tdefer func() {\n\t\trecover()\n\t}()\n\tvar i I = Tiny{}\n\ti.M()\n}", "func checkErr(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n}", "func check(e error){\n\tif e!=nil{\n\t\tpanic(e)\n\t}\n}", "func checkForPanics(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func main() {\n\tif err := testPanic(); err != nil {\n\t\tfmt.Println(\"Test Error:\", err)\n\t}\n\n\tif err := testPanic(); err != nil {\n\t\tfmt.Println(\"Test Panic:\", err)\n\t}\n}", "func PanicAfterPrepareRebuild() {}", "func TestPanicSafety(t *testing.T) {\n\tpredeclared := starlark.StringDict{\n\t\t\"panic\": starlark.NewBuiltin(\"panic\", func(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\t\t\tpanic(args[0])\n\t\t}),\n\t\t\"list\": starlark.NewList([]starlark.Value{starlark.MakeInt(0)}),\n\t}\n\n\t// This program is executed twice, using the same Thread,\n\t// and panics both times, with values 1 and 2, while\n\t// main is on the stack and a for-loop is active.\n\t//\n\t// It mutates list, a predeclared variable.\n\t// This operation would fail if the previous\n\t// for-loop failed to close its iterator during the panic.\n\t//\n\t// It also calls main a second time without recursion enabled.\n\t// This operation would fail if the previous\n\t// call failed to pop main from the stack during the panic.\n\tconst src = `\nlist[0] += 1\n\ndef main():\n for x in list:\n panic(x)\n\nmain()\n`\n\tthread := new(starlark.Thread)\n\tfor _, i := range []int{1, 2} {\n\t\t// Use a func to limit the scope of recover.\n\t\tfunc() {\n\t\t\tdefer func() {\n\t\t\t\tif got := fmt.Sprint(recover()); got != fmt.Sprint(i) {\n\t\t\t\t\tt.Fatalf(\"recover: got %v, want %v\", got, i)\n\t\t\t\t}\n\t\t\t}()\n\t\t\tv, err := starlark.ExecFile(thread, \"panic.star\", src, predeclared)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"ExecFile returned error %q, expected panic\", err)\n\t\t\t} else {\n\t\t\t\tt.Fatalf(\"ExecFile returned %v, expected panic\", v)\n\t\t\t}\n\t\t}()\n\t}\n}", "func test(f func(), s string) {\n\tdefer func() {\n\t\tif err := recover(); err == nil {\n\t\t\t_, file, line, _ := runtime.Caller(2)\n\t\t\tbug()\n\t\t\tprint(file, \":\", line, \": \", s, \" did not panic\\n\")\n\t\t}\n\t}()\n\tf()\n}", "func Bug(s string, args ...interface{}) {\n\tpanic(fmt.Sprintf(\"BUG: \"+s, args...))\n}", "func TestTryOtherPanic(t *testing.T) {\n\tassert.Panics(t, func() {\n\t\tTry(func(throw Thrower) int {\n\t\t\tpanic(\"A real panic!\")\n\t\t})\n\t})\n}", "func catchPanic(err *error, functionName string) {\n\tif r := recover(); r != nil {\n\t\tfmt.Printf(\"%s : PANIC Defered : %v\\n\", functionName, r)\n\n\t\t// Capture the stack trace\n\t\tbuf := make([]byte, 10000)\n\t\truntime.Stack(buf, false)\n\n\t\tfmt.Printf(\"%s : Stack Trace : %s\", functionName, string(buf))\n\n\t\tif err != nil {\n\t\t\t*err = fmt.Errorf(\"%v\", r)\n\t\t}\n\t}\n}", "func check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func checkErr(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func catchPanic(err *error, functionName string) {\n\tif r := recover(); r != nil {\n\t\tfmt.Printf(\"%s : PANIC Defered : %v\\n\", functionName, r)\n\n\t\t// Capture the stack trace\n\t\tbuf := make([]byte, 10000)\n\t\truntime.Stack(buf, false)\n\n\t\tfmt.Printf(\"%s : Stack Trace : %s\", functionName, string(buf))\n\n\t\tif err != nil {\n\t\t\t*err = fmt.Errorf(\"%v\", r)\n\t\t}\n\t} else if err != nil && *err != nil {\n\t\tfmt.Printf(\"%s : ERROR : %v\\n\", functionName, *err)\n\n\t\t// Capture the stack trace\n\t\tbuf := make([]byte, 10000)\n\t\truntime.Stack(buf, false)\n\n\t\tfmt.Printf(\"%s : Stack Trace : %s\", functionName, string(buf))\n\t}\n}", "func check(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\n\t}\n}", "func assertPanic(t *testing.T, f func()) {\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Errorf(\"The code did not panic\")\n\t\t}\n\t}()\n\tf()\n}", "func checkErr(err error) {\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}", "func checkErr(err error) {\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}", "func check(e error) {\r\n if e != nil {\r\n panic(e)\r\n }\r\n}", "func TestLookupHostMetaPanicsOnInvalidType(t *testing.T) {\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Error(\"lookupHostMeta should panic if an invalid conntype is specified.\")\n\t\t}\n\t}()\n\tlookupHostMeta(context.Background(), nil, \"name\", \"wssorbashorsomething\")\n}", "func check(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}", "func check(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}", "func check(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}", "func check(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}", "func check(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}", "func check(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}", "func check(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}", "func check(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}", "func check(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}", "func check(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}", "func check(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}", "func check(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}", "func check(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}", "func check(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}", "func check(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}", "func handlePanic() {\n\tif r := recover(); r != nil {\n\t\tlog.Printf(\"panic recovered: %s \\n %s\", r, debug.Stack())\n\t}\n}", "func TestPanicWithGenericValueOnAccess(t *testing.T) {\n\trunTest(t, func(s *Session) {\n\t\ts.Handle(\"model\", res.Access(func(r res.AccessRequest) {\n\t\t\tpanic(42)\n\t\t}))\n\t}, func(s *Session) {\n\t\tinb := s.Request(\"access.test.model\", nil)\n\t\ts.GetMsg(t).\n\t\t\tAssertSubject(t, inb).\n\t\t\tAssertErrorCode(t, \"system.internalError\")\n\t})\n}", "func slicePanic() {\n\tn := []int{1, 2, 3}\n\tfmt.Println(n[4])\n\tfmt.Println(\"Executia in slice s-a terminat cu succes\")\n}", "func Panic(errorData lisp.Object) {\n\t{\n\t} // Prevent inlining (#REFS: 37)\n\tlisp.Call(\"signal\", lisp.Intern(\"error\"), lisp.Call(\"list\", errorData))\n}", "func Panic(err error) {\n\tpanic(errors.Wrap(err.Error()+\"\\n\"+string(errors.Wrap(err, 1).Stack()), 1))\n}", "func check(e error) {\n if e != nil {\n log.Fatal( e )\n panic(e)\n }\n}", "func assertNoPanic(t *testing.T, f func()) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tt.Errorf(\"The code did panic\")\n\t\t}\n\t}()\n\tf()\n}", "func writeSomething() {\n\t//Anything\n\tpanic(\"Write operation error\")\n}", "func testPanic() {\n\tdefer func() {\n\t\trecover()\n\t}()\n\tcheck(LINE, 1)\n\tpanic(\"should not get next line\")\n\tcheck(LINE, 0) // this is GoCover.Count[panicIndex]\n\t// The next counter is in testSimple and it will be non-zero.\n\t// If the panic above does not trigger a counter, the test will fail\n\t// because GoCover.Count[panicIndex] will be the one in testSimple.\n}", "func ExampleMustSqueezeTrytes() {}", "func doRecover(err *error) {\n\tr := recover()\n\tswitch r := r.(type) {\n\tcase nil:\n\t\treturn\n\tcase runtime.Error:\n\t\tpanic(r)\n\tcase error:\n\t\t*err = r\n\tdefault:\n\t\tpanic(r)\n\t}\n}", "func panicRecover() {\n\tif rec := recover(); rec != nil {\n\t\tlog.Printf(\"Panic: %v\", rec)\n\t}\n}", "func Panic(format string, v ...interface{}) {\n\tpanic(\"UNASSERT: \" + fmt.Sprintf(format, v...))\n}", "func checkErr(e error) {\n\tif e != nil {\n\t\tlog.Panic(e)\n\t}\n}", "func stub() {\n\tpanic( \"calling a stub.\")\n}", "func check_err(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func brokenSlicedArray(names [4]string) {\n\n\t//The following code will be invalid because we're slicing a array from position 1 to 2 which means that we will get only 1 index from the array and we will assign value to the Index 1 which will be out of range for the array.\n\tfmt.Println(\"/////////////////////////////////////// Index out of range with recover ///////////////////////////////////////\")\n\tfmt.Println(names)\n\n\tslicedNamesOne := names[0:2]\n\n\tfmt.Println(slicedNamesOne)\n\n\t// Correct will be // slicedNamesTwo := names[0:2]\n\t// this will 'panic' must recover\n\tslicedNamesTwo := names[1:2]\n\n\t// The program is going to 'panic' and enter the if statement.\n\tif r := recover(); r != nil {\n\t\tslicedNamesTwo[1] = \"XXX Nicholas XXX\"\n\t}\n\n\tfmt.Println(slicedNamesTwo)\n\tfmt.Println(names)\n\n\tfmt.Println(\"///////////////////////////////////////\")\n}", "func must(err error) {\n\tif err == nil {\n\t\treturn\n\t}\n\n\tpanic(err)\n}", "func ExampleMustAbsorbTrytes() {}", "func Panic(args ...interface{}) {\n\tglobal.Panic(args...)\n}", "func Panic(err error, segmentName string) {\n\tif err != nil {\n\t\tlog.Panicf(\"Panic in '%s' : %v\", segmentName, err)\n\t}\n}", "func checkErr(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}", "func imprimir() {\n\tfmt.Println(\"Hola Alex!\")\n\t//panic(\"Error\")\n\t//\n\t//cadena := recover()\n\t//}\n\n\n\n\n\n\tdefer func() {\n\t\tsomeString := recover()\n\t\tfmt.Println(someString)\n\t} ()\n\tpanic(\"Error\")\n\n\n\n\n\n\n\n}", "func (e *recoverableError) recover() {\n}", "func x() {\n\n\tdefer recoverfunc()\n\tnx := []int{8, 7, 3}\n\tfmt.Println(nx[3])\n\tfmt.Println(\"successfully returned to main\")\n}", "func ExampleAbsorbTrytes() {}", "func catchPanic(err *error) {\n\tif r := recover(); r != nil {\n\t\tif err != nil {\n\t\t\t*err = fmt.Errorf(\"%v\", r)\n\t\t}\n\t}\n}", "func will_panic() {\n\tvar x uint8 = 8\n\tvar value interface{}\n\tvalue = x\n\tstr := value.(*string) // When forcing to use another type, it fail\n\tfmt.Println(str)\n}", "func test7() (err error) {\n\tdefer func() {\n\t\tfmt.Println(\"panic defer start *************\")\n\t\tif r := recover(); r != nil {\n\t\t\tfmt.Println(\"Defer panic: \", r)\n\t\t}\n\t\tfmt.Println(\"panic defer end. ***************\")\n\t}()\n\n\tdefer func() {\n\t\tfmt.Println(\"error defer start ###########\")\n\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Defer error: \", err)\n\t\t}\n\n\t\tfmt.Println(\"error defer end ###########\")\n\t}()\n\tfmt.Println(\"start test7\")\n\terr = simulateError(\"哈哈错误\")\n\t//simulatePanic(\"2\")\n\tpanic(\"我panic了\")\n}", "func check(e error) {\n if e != nil {\n panic(e)\n }\n}", "func check(e error) {\n if e != nil {\n panic(e)\n }\n}", "func check(e error) {\n if e != nil {\n panic(e)\n }\n}", "func check(e error) {\n if e != nil {\n panic(e)\n }\n}", "func test1WithClosures() {\n\tdefer func() {\n\t\tv := recover()\n\t\tif v != nil {\n\t\t\tprintln(\"spurious recover in closure\")\n\t\t\tdie()\n\t\t}\n\t}()\n\tdefer func(x interface{}) {\n\t\tmustNotRecover()\n\t\tv := recover()\n\t\tif v == nil {\n\t\t\tprintln(\"missing recover\", x.(int))\n\t\t\tdie()\n\t\t}\n\t\tif v != x {\n\t\t\tprintln(\"wrong value\", v, x)\n\t\t\tdie()\n\t\t}\n\t}(1)\n\tdefer func() {\n\t\tmustNotRecover()\n\t}()\n\tpanic(1)\n}", "func main() {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlog.Fatalln(\"Unexpected error:\", r)\n\t\t}\n\t}()\n\tif errMain := run(); errMain != nil {\n\t\tlog.Fatalln(errMain)\n\t}\n}", "func checkErr(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\tpanic(err)\n\t}\n}", "func (ev *evaluator) recover(errp *error) {\n\te := recover()\n\tif e != nil {\n\t\tif _, ok := e.(runtime.Error); ok {\n\t\t\t// Print the stack trace but do not inhibit the running application.\n\t\t\tbuf := make([]byte, 64<<10)\n\t\t\tbuf = buf[:runtime.Stack(buf, false)]\n\n\t\t\tlog.Errorf(\"parser panic: %v\\n%s\", e, buf)\n\t\t\t*errp = fmt.Errorf(\"unexpected error\")\n\t\t} else {\n\t\t\t*errp = e.(error)\n\t\t}\n\t}\n}", "func CheckPanic(e error) {\n _, file, line, _ := runtime.Caller(1)\n if e != nil {\n logrus.WithFields(logrus.Fields{\"file\": file,\n \"line\": line,\n }).Panic(e)\n }\n}", "func checkError(err error) {\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n}", "func check(e error) {\n if e != nil {\n\t\tlog.Fatal(\"Error\", e)\n panic(e)\n }\n}", "func main() {\n\tif err := do(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func must(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func must(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func must(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func must(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func must(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func must(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}" ]
[ "0.6112382", "0.6089716", "0.6037435", "0.60083765", "0.59469646", "0.592577", "0.58915156", "0.58853745", "0.58349574", "0.57836074", "0.57765853", "0.5768175", "0.5747444", "0.5747444", "0.5727745", "0.57131875", "0.56936836", "0.56836283", "0.5672012", "0.56711036", "0.5668834", "0.56625897", "0.5632067", "0.56266034", "0.56164396", "0.5609639", "0.5609639", "0.5609639", "0.5609639", "0.5609639", "0.5609639", "0.5575913", "0.5570939", "0.55667835", "0.55639523", "0.5548699", "0.5548699", "0.5534114", "0.55241346", "0.55210376", "0.55210376", "0.55210376", "0.55210376", "0.55210376", "0.55210376", "0.55210376", "0.55210376", "0.55210376", "0.55210376", "0.55210376", "0.55210376", "0.55210376", "0.55210376", "0.55210376", "0.551936", "0.55183434", "0.5517922", "0.5501077", "0.5499329", "0.5491331", "0.5482363", "0.54795194", "0.5478409", "0.54726875", "0.54650193", "0.54597163", "0.5459711", "0.54560214", "0.5455801", "0.54449517", "0.5443699", "0.54312193", "0.54304403", "0.542623", "0.5422077", "0.5417877", "0.5409477", "0.54072", "0.5396402", "0.539571", "0.5374005", "0.5369994", "0.5368343", "0.5353495", "0.5353495", "0.5353495", "0.5353495", "0.53533787", "0.5350013", "0.53465277", "0.5346177", "0.53460675", "0.5341002", "0.5337584", "0.5335588", "0.5333025", "0.5333025", "0.5333025", "0.5333025", "0.5333025", "0.5333025" ]
0.0
-1
/ Get address from context
func GetAddressFromCtx(ctx context.Context) (string, bool) { pr, ok := peer.FromContext(ctx) if !ok { return "", false } if pr.Addr == net.Addr(nil) { return "", false } return pr.Addr.String(), true }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (q *Address) GetContext() string {\n\treturn q.Context\n}", "func RemoteAddrFromContext(ctx context.Context) string {\n\tv := ctx.Value(remoteAddrKey)\n\tif str, ok := v.(string); ok {\n\t\treturn str\n\t}\n\n\treturn \"\"\n}", "func (p *dnsOverTLS) Address() string { return p.boot.URL.String() }", "func (rs *requestContext) RemoteAddress() string {\n\treturn rs.remoteAddress\n}", "func (chrome *Chrome) Address() string {\n\tif !chrome.Flags().Has(\"addr\") {\n\t\tchrome.Flags().Set(\"addr\", \"localhost\")\n\t}\n\tvalue, _ := chrome.Flags().Get(\"addr\")\n\treturn value.(string)\n}", "func GetAddress(h *string, p *int) string {\n\treturn *h + \":\" + strconv.FormatUint(uint64(*p), 10)\n}", "func GetIPFromContext(ctx context.Context) string {\n\tif ip, ok := ctx.Value(ipAddressCtxKey{}).(string); ok {\n\t\treturn ip\n\t}\n\treturn \"\"\n}", "func (b *ClientAdaptor) Address() string { return b.address }", "func (r *ProviderRegister) GetAddress() string {\n\treturn r.Address\n}", "func (s *SingleShard) GetAddress() string { return \"\" }", "func (h *CookiejarHandler) getAddress(name string) string {\n\thashedName := Hexdigest(name)\n\treturn h.namespace + hashedName[:64]\n}", "func LoadAddressFromContext(ctx context.Context, id string) (*Address, error) {\n\tv, err := viewer.ForContext(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn LoadAddress(v, id)\n}", "func (w *NodeWrapper) GetAddress() string {\n\treturn w.node.addr\n}", "func (c VaultConfig) GetAddress() string {\n\treturn c.Address\n}", "func AddAddrContext(email, context string) (string, error) {\n\taddr, err := mail.ParseAddress(email)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to parse %q as email: %v\", email, err)\n\t}\n\tat := strings.IndexByte(addr.Address, '@')\n\tif at == -1 {\n\t\treturn \"\", fmt.Errorf(\"failed to parse %q as email: no @\", email)\n\t}\n\tresult := addr.Address[:at] + \"+\" + context + addr.Address[at:]\n\tif addr.Name != \"\" {\n\t\taddr.Address = result\n\t\tresult = addr.String()\n\t}\n\treturn result, nil\n}", "func (m *BookingBusiness) GetAddress()(PhysicalAddressable) {\n val, err := m.GetBackingStore().Get(\"address\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(PhysicalAddressable)\n }\n return nil\n}", "func (g *RESTFrontend) GetAddr() string {\n\treturn g.Listener.Addr().String()\n}", "func remoteAddrToContext(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tnext.ServeHTTP(w, req.WithContext(context.WithValue(req.Context(), remoteAddrKey, req.RemoteAddr)))\n\t})\n}", "func Addr(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tr = r.WithContext(context.WithValue(r.Context(), RemoteAddrKey, r.RemoteAddr))\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func (config *GinConfig) GetAddress() string {\n\treturn fmt.Sprintf(\"%s:%d\", config.Host, config.Port)\n}", "func op_ADDRESS(pc *uint64, in *interpreter, ctx *callCtx) uint64 {\n\tctx.stack.Push(new(uint256.Int).SetBytes(ctx.contract.Address().Bytes()))\n\treturn 0\n}", "func (n *Node) GetAddr() string{\n return n.peer.GetAddr()\n}", "func KNCAddressFromContext(c *cli.Context) ethereum.Address {\n\tdeploymentMode := deployment.MustGetDeploymentFromContext(c)\n\tswitch deploymentMode {\n\tcase deployment.Ropsten:\n\t\treturn ethereum.HexToAddress(\"0x4e470dc7321e84ca96fcaedd0c8abcebbaeb68c6\")\n\tdefault:\n\t\treturn ethereum.HexToAddress(\"0xdd974d5c2e2928dea5f71b9825b8b646686bd200\")\n\t}\n}", "func (e CastEntry) GetAddr() string {\n\treturn fmt.Sprintf(\"%s\", e.AddrV4)\n}", "func (kp *FromAddress) Address() string {\n\treturn kp.address\n}", "func (v *Context) RemoteAddr() net.Addr {\n\treturn v.raddr\n}", "func (result ContractFunctionResult) GetAddress(index uint64) []byte {\n\treturn result.ContractCallResult[(index*32)+12 : (index*32)+32]\n}", "func (p Profile) Address() *attribute.StringAttribute {\n\treturn p.GetStringAttribute(AttrConstAddress)\n}", "func (c *client) Address() string {\n\treturn c.address\n}", "func (s *WindowsDesktopServiceV3) GetAddr() string {\n\treturn s.Spec.Addr\n}", "func (f *Factory) Address() string { return f.address }", "func (o InstanceListenerEndpointOutput) Address() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InstanceListenerEndpoint) *string { return v.Address }).(pulumi.StringPtrOutput)\n}", "func (a AppContext) DiscoveryAddress() string {\n\treturn DiscoveryURL\n}", "func (ctx *Context) RemoteAddr() string {\n\tif ctx.HTTPReq != nil {\n\t\treturn ctx.HTTPReq.RemoteAddr\n\t} else if ctx.WSConn != nil {\n\t\treturn ctx.WSConn.GetRemoteAddr()\n\t}\n\treturn \"\"\n}", "func (bq *BRQuerier) GetAddress() string {\n\treturn bq.Address\n}", "func (b *Backend) Address() string {\n\treturn b.address\n}", "func (c *Container) GetAddress(t *testing.T) string {\n\tif c.address != \"\" {\n\t\treturn c.address\n\t}\n\tcontainer := c.parentContainer\n\tif container == \"\" {\n\t\tcontainer = c.container\n\t}\n\tresult := icmd.RunCommand(dockerCli.path, \"port\", container, strconv.Itoa(c.privatePort)).Assert(t, icmd.Success)\n\tc.address = fmt.Sprintf(\"127.0.0.1:%v\", strings.Trim(strings.Split(result.Stdout(), \":\")[1], \" \\r\\n\"))\n\treturn c.address\n}", "func (delegateObject *delegateObject) Address() common.Address {\n\treturn delegateObject.address\n}", "func (s *SessionTrackerV1) GetAddress() string {\n\treturn s.Spec.Address\n}", "func (c *ChannelLocation) GetAddress() (value string) {\n\tif c == nil {\n\t\treturn\n\t}\n\treturn c.Address\n}", "func (c *X509Certificate) GetAddress() string {\r\n\tpub := publicKeyToBytes(c.PublicKey)\r\n\tshaPub := sha256.Sum256(pub)\r\n\treturn hex.EncodeToString(shaPub[:])\r\n}", "func (this *AppItem) Address() string {\n return this.address\n}", "func (c connection) GetAddress() mynet.Address {\n\treturn c.address\n}", "func (stateObj *stateObject) Address() common.Address {\n\treturn stateObj.address\n}", "func (d *WindowsDesktopV3) GetAddr() string {\n\treturn d.Spec.Addr\n}", "func (_Contract *ContractCaller) Addr(opts *bind.CallOpts, node [32]byte) (common.Address, error) {\n\tvar out []interface{}\n\terr := _Contract.contract.Call(opts, &out, \"addr\", node)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (c *Client) Address() string {\n\treturn c.config.Address\n}", "func (e Endpoints) GetAddress(ctx context.Context, profileID string, addressID string) (Address, error) {\n\n\t// TODO: Create detailed ref spec\n\trequest := getAddressRequest{ProfileID: profileID, AddressID: addressID}\n\n\tresponse, err := e.GetAddressEndpoint(ctx, request)\n\n\tif err != nil {\n\t\treturn Address{}, err\n\t}\n\n\tresp := response.(getAddressResponse)\n\n\treturn resp.Address, resp.Err\n}", "func (w *ServerInterfaceWrapper) GetDepositAddress(ctx echo.Context) error {\n\tvar err error\n\t// ------------- Path parameter \"currency\" -------------\n\tvar currency CurrencyParam\n\n\terr = runtime.BindStyledParameterWithLocation(\"simple\", false, \"currency\", runtime.ParamLocationPath, ctx.Param(\"currency\"), &currency)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter currency: %s\", err))\n\t}\n\n\tctx.Set(ApiKeyAuthScopes, []string{\"\"})\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.GetDepositAddress(ctx, currency)\n\treturn err\n}", "func (_ResolverContract *ResolverContractCaller) Addr(opts *bind.CallOpts, node [32]byte) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _ResolverContract.contract.Call(opts, out, \"addr\", node)\n\treturn *ret0, err\n}", "func getExternalBindAddr(conn *socks5ClientConn) *net.TCPAddr {\n\tctx := conn.GetServer().GetContext()\n\treturn (*ctx).Value(proxyconn.CtxKey(\"externalAddr\")).(*net.TCPAddr)\n}", "func GetAddress(addr string) (*model.Address, error) {\n\n\turl := fmt.Sprintf(bchapi.AddressUrl, addr)\n\tresult, err := bchapi.HttpGet(url, bchapi.ConnTimeoutMS, bchapi.ServeTimeoutMS)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taddress, err := model.StringToAddress(result)\n\treturn address, err\n}", "func (_LvRecording *LvRecordingCaller) ContentAddress(opts *bind.CallOpts) (common.Address, error) {\n\tvar out []interface{}\n\terr := _LvRecording.contract.Call(opts, &out, \"contentAddress\")\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (manager Manager) HTTPAddress() string {\n\treturn manager.viperConfig.GetString(httpAddress)\n}", "func GenLoadAddressFromContext(ctx context.Context, id string) <-chan *AddressResult {\n\tres := make(chan *AddressResult)\n\tgo func() {\n\t\taddress, err := LoadAddressFromContext(ctx, id)\n\t\tres <- &AddressResult{\n\t\t\tErr: err,\n\t\t\tAddress: address,\n\t\t}\n\t}()\n\treturn res\n}", "func (c *ChannelsCreateChannelRequest) GetAddress() (value string, ok bool) {\n\tif !c.Flags.Has(2) {\n\t\treturn value, false\n\t}\n\treturn c.Address, true\n}", "func (cm *ConnectMethod) addr() string {\n\treturn cm.targetAddr\n}", "func GetAddress() *common.Address {\n\treturn &skrAddress\n}", "func (response YaGeoResponse) Address() string {\n\tif len(response.Response.ObjectCollection.Members) > 0 {\n\t\treturn response.Response.ObjectCollection.Members[0].GeoObject.MetaData.Meta.Text\n\t}\n\treturn \"\"\n}", "func (server *RPCServer) Address() string {\n\treturn server.listener.Addr().String()\n}", "func (s *dnsTestServer) Address() string {\n\treturn s.Server.PacketConn.LocalAddr().String()\n}", "func (a *Account) GetAddress() evm.Address {\n\treturn a.account.GetAddress()\n}", "func (s *Service) GetExplorerAddress(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tid := r.FormValue(\"id\")\n\tif strings.HasPrefix(id, \"0x\") {\n\t\tparsedAddr := common2.ParseAddr(id)\n\t\toneAddr, err := common2.AddressToBech32(parsedAddr)\n\t\tif err != nil {\n\t\t\tutils.Logger().Warn().Err(err).Msg(\"unrecognized address format\")\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tid = oneAddr\n\t}\n\tkey := GetAddressKey(id)\n\ttxViewParam := r.FormValue(\"tx_view\")\n\tpageParam := r.FormValue(\"page\")\n\toffsetParam := r.FormValue(\"offset\")\n\torder := r.FormValue(\"order\")\n\ttxView := txViewNone\n\tif txViewParam != \"\" {\n\t\ttxView = txViewParam\n\t}\n\tutils.Logger().Info().Str(\"Address\", id).Msg(\"Querying address\")\n\tdata := &Data{}\n\tdefer func() {\n\t\tif err := json.NewEncoder(w).Encode(data.Address); err != nil {\n\t\t\tutils.Logger().Warn().Err(err).Msg(\"cannot JSON-encode Address\")\n\t\t}\n\t}()\n\tif id == \"\" {\n\t\tutils.Logger().Warn().Msg(\"missing address id param\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\tvar err error\n\tvar offset int\n\tif offsetParam != \"\" {\n\t\toffset, err = strconv.Atoi(offsetParam)\n\t\tif err != nil || offset < 1 {\n\t\t\tutils.Logger().Warn().Msg(\"invalid offset parameter\")\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\toffset = paginationOffset\n\t}\n\tvar page int\n\tif pageParam != \"\" {\n\t\tpage, err = strconv.Atoi(pageParam)\n\t\tif err != nil {\n\t\t\tutils.Logger().Warn().Err(err).Msg(\"invalid page parameter\")\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tpage = 0\n\t}\n\n\tdata.Address.ID = id\n\t// Try to populate the banace by directly calling get balance.\n\t// Check the balance from blockchain rather than local DB dump\n\tbalanceAddr := big.NewInt(0)\n\tif s.GetAccountBalance != nil {\n\t\taddress := common2.ParseAddr(id)\n\t\tbalance, err := s.GetAccountBalance(address)\n\t\tif err == nil {\n\t\t\tbalanceAddr = balance\n\t\t}\n\t}\n\n\tdb := s.Storage.GetDB()\n\tbytes, err := db.Get([]byte(key))\n\tif err != nil {\n\t\tutils.Logger().Warn().Err(err).Str(\"id\", id).Msg(\"cannot fetch address from db\")\n\t\tdata.Address.Balance = balanceAddr\n\t\treturn\n\t}\n\n\tif err = rlp.DecodeBytes(bytes, &data.Address); err != nil {\n\t\tutils.Logger().Warn().Str(\"id\", id).Msg(\"cannot convert address data\")\n\t\tdata.Address.Balance = balanceAddr\n\t\treturn\n\t}\n\n\tdata.Address.Balance = balanceAddr\n\n\tswitch txView {\n\tcase txViewNone:\n\t\tdata.Address.TXs = nil\n\tcase Received:\n\t\treceivedTXs := make([]*Transaction, 0)\n\t\tfor _, tx := range data.Address.TXs {\n\t\t\tif tx.Type == Received {\n\t\t\t\treceivedTXs = append(receivedTXs, tx)\n\t\t\t}\n\t\t}\n\t\tdata.Address.TXs = receivedTXs\n\tcase Sent:\n\t\tsentTXs := make([]*Transaction, 0)\n\t\tfor _, tx := range data.Address.TXs {\n\t\t\tif tx.Type == Sent {\n\t\t\t\tsentTXs = append(sentTXs, tx)\n\t\t\t}\n\t\t}\n\t\tdata.Address.TXs = sentTXs\n\t}\n\tif offset*page >= len(data.Address.TXs) {\n\t\tdata.Address.TXs = []*Transaction{}\n\t} else if offset*page+offset > len(data.Address.TXs) {\n\t\tdata.Address.TXs = data.Address.TXs[offset*page:]\n\t} else {\n\t\tdata.Address.TXs = data.Address.TXs[offset*page : offset*page+offset]\n\t}\n\tif order == \"DESC\" {\n\t\tsort.Slice(data.Address.TXs[:], func(i, j int) bool {\n\t\t\treturn data.Address.TXs[i].Timestamp > data.Address.TXs[j].Timestamp\n\t\t})\n\t} else {\n\t\tsort.Slice(data.Address.TXs[:], func(i, j int) bool {\n\t\t\treturn data.Address.TXs[i].Timestamp < data.Address.TXs[j].Timestamp\n\t\t})\n\t}\n}", "func (p *MemoryProposer) Address() string {\n\treturn p.id\n}", "func CtxPeerAddr(ctx context.Context) string {\n\tif p, ok := ctx.Value(contextKeyPeerAddr).(string); ok {\n\t\treturn p\n\t}\n\treturn \"\"\n}", "func (h *Host) Adress() string {\n}", "func GetAddress(client *etcd.Client, name string, id uint64) (string, error) {\n\tresp, err := client.Get(TaskMasterPath(name, id), false, false)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn resp.Node.Value, nil\n}", "func (self *testSystemBackend) Address() common.Address {\n\treturn self.address\n}", "func (_Contract *ContractCallerSession) Addr(node [32]byte) (common.Address, error) {\n\treturn _Contract.Contract.Addr(&_Contract.CallOpts, node)\n}", "func (_ResolverContract *ResolverContractCallerSession) Addr(node [32]byte) (common.Address, error) {\n\treturn _ResolverContract.Contract.Addr(&_ResolverContract.CallOpts, node)\n}", "func (this *ValueTransaction) GetAddress() (result trinary.Trytes) {\n\tthis.addressMutex.RLock()\n\tif this.address == nil {\n\t\tthis.addressMutex.RUnlock()\n\t\tthis.addressMutex.Lock()\n\t\tdefer this.addressMutex.Unlock()\n\t\tif this.address == nil {\n\t\t\taddress := trinary.MustTritsToTrytes(this.trits[ADDRESS_OFFSET:ADDRESS_END])\n\n\t\t\tthis.address = &address\n\t\t}\n\t} else {\n\t\tdefer this.addressMutex.RUnlock()\n\t}\n\n\tresult = *this.address\n\n\treturn\n}", "func (s *ProvisionedServer) Address() string { return s.Server.AdvertiseIP }", "func (s *Store) getBindAddressTx(tx *bolt.Tx, depositAddr, coinType string) (*BoundAddress, error) {\n\tbindBktFullName, err := GetBindAddressBkt(coinType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar boundAddr BoundAddress\n\terr = dbutil.GetBucketObject(tx, bindBktFullName, depositAddr, &boundAddr)\n\tswitch err.(type) {\n\tcase nil:\n\t\treturn &boundAddr, nil\n\tcase dbutil.ObjectNotExistErr:\n\t\treturn nil, nil\n\tdefault:\n\t\treturn nil, err\n\t}\n}", "func (c *StateObject) Address() helper.Address {\n\treturn c.address\n}", "func (_UsersData *UsersDataCallerSession) GetUserAddress(uuid [16]byte) (common.Address, error) {\n\treturn _UsersData.Contract.GetUserAddress(&_UsersData.CallOpts, uuid)\n}", "func (ba *buddyAllocator) getBuddyAddress(\n\tindex, order uint32, first bool,\n) (addr uint32) {\n\treturn ba.getAddress(index, order, !first)\n}", "func (id *publicAddress) Address() Address {\n\tvar a Address\n\ta, _ = id.address()\n\treturn a\n}", "func (f *FormationAssignment) GetAddress() uintptr {\n\treturn uintptr(unsafe.Pointer(f))\n}", "func (s *SSH) Address() string {\n\tif s.listener != nil {\n\t\treturn s.listener.Addr().String()\n\t}\n\treturn \"\"\n}", "func (status *ServerStatus) GetAddress() string {\n\taddr := status.Host\n\tif status.Port != 25565 {\n\t\taddr += \":\" + strconv.Itoa(status.Port)\n\t}\n\treturn addr\n}", "func (_UsersData *UsersDataCaller) GetUserAddress(opts *bind.CallOpts, uuid [16]byte) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _UsersData.contract.Call(opts, out, \"getUserAddress\", uuid)\n\treturn *ret0, err\n}", "func (ta TransAddress) GetAddress() IAddress {\n\treturn ta.address\n}", "func (c *ConfigurationData) GetHTTPAddress() string {\n\treturn c.v.GetString(varHTTPAddress)\n}", "func (n *GRPCNode) GetAddress() (url.URL, error) {\n\tif n == nil {\n\t\treturn url.URL{}, errors.Wrap(e.ErrNil, \"failed to get node address\")\n\t}\n\treturn n.address, nil\n}", "func (m *MuxedAccount) Address() string {\n\taddress, err := m.GetAddress()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn address\n}", "func (c *Config) BindAddress() string {\n\treturn c.Address\n}", "func (_Contract *ContractSession) Addr(node [32]byte) (common.Address, error) {\n\treturn _Contract.Contract.Addr(&_Contract.CallOpts, node)\n}", "func (i *Info) GetContext() string {\n\treturn i.Name + \"@\" + i.Name\n}", "func (ag AccessGrant) GetAddress() sdk.AccAddress {\n\taddr, err := sdk.AccAddressFromBech32(ag.Address)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn addr\n}", "func (_ResolverContract *ResolverContractSession) Addr(node [32]byte) (common.Address, error) {\n\treturn _ResolverContract.Contract.Addr(&_ResolverContract.CallOpts, node)\n}", "func (address *Address) GetViewer() viewer.ViewerContext {\n\treturn address.viewer\n}", "func (s *GrpcServer) Address() string {\n\treturn s.listener.Addr().String()\n}", "func (ma *MixedcaseAddress) Address() Address {\n\treturn ma.addr\n}", "func (h *envoyBootstrapHook) grpcAddress(env map[string]string) string {\n\tif address := env[grpcConsulVariable]; address != \"\" {\n\t\treturn address\n\t}\n\n\ttg := h.alloc.Job.LookupTaskGroup(h.alloc.TaskGroup)\n\tswitch tg.Networks[0].Mode {\n\tcase \"host\":\n\t\treturn grpcDefaultAddress\n\tdefault:\n\t\treturn \"unix://\" + allocdir.AllocGRPCSocket\n\t}\n}", "func (server *Server) Address() string {\n\treturn server.address\n}", "func (s *Store) GetBindAddress(depositAddr, coinType string) (*BoundAddress, error) {\n\tvar boundAddr *BoundAddress\n\tif err := s.db.View(func(tx *bolt.Tx) error {\n\t\tvar err error\n\t\tboundAddr, err = s.getBindAddressTx(tx, depositAddr, coinType)\n\t\treturn err\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn boundAddr, nil\n}", "func (c *CFAuthProxyApp) DebugAddr() string {\n\tc.debugMu.Lock()\n\tdefer c.debugMu.Unlock()\n\n\tif c.debugLis != nil {\n\t\treturn c.debugLis.Addr().String()\n\t}\n\n\treturn \"\"\n}", "func (thread *ThreadContext) ReturnAddress() (uint64, error) {\n\tregs, err := thread.Registers()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tlocations, err := thread.Process.stacktrace(regs.PC(), regs.SP(), 1)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn locations[0].addr, nil\n}", "func (c *Client) GetAddress() (addrType, address string) {\n\treturn c.addrType, c.dbServer\n}", "func (svc *inmemService) GetAddress(ctx context.Context, profileID string, addressID string) (Address, error) {\n\n\t// Get a Read Lock on the svc for atomic read access to the datastore\n\tsvc.mtx.RLock()\n\n\t// Immediately set up a lock release to occur when the function finishes\n\tdefer svc.mtx.RUnlock()\n\n\t// Check the data store to make sure the requested profile exists and set\n\tprofile, ok := svc.profiles[profileID]\n\n\t// If no entry for the profile was fund in the datastore\n\tif !ok {\n\n\t\t// Return an empty valued Address and an error informing the caller that no profile was found with the provided ID.\n\t\treturn Address{}, ErrNotFound\n\t}\n\n\t// Loop through each address attached to the found profile\n\tfor _, address := range profile.Addresses {\n\n\t\t// Check to see if the current address's ID matches the addressID passed in\n\t\tif address.ID == addressID {\n\n\t\t\t// Return that address and a nil error for a value\n\t\t\treturn address, nil\n\t\t}\n\t}\n\n\t// Return an empty Address value and a not found error since we were unable to find the specified address.\n\treturn Address{}, ErrNotFound\n}" ]
[ "0.7252135", "0.63855195", "0.6368289", "0.6272641", "0.6262093", "0.6251235", "0.62455213", "0.6242507", "0.6127023", "0.61111563", "0.61109245", "0.6094559", "0.6090996", "0.60762966", "0.6031942", "0.60195524", "0.60150754", "0.6005225", "0.59998214", "0.59571177", "0.5949096", "0.59479046", "0.5943601", "0.5940929", "0.59171474", "0.59162277", "0.5903313", "0.5891539", "0.58789915", "0.58431375", "0.58310986", "0.5826251", "0.58250374", "0.5821152", "0.58151704", "0.5810645", "0.58058435", "0.58047235", "0.5800161", "0.5791302", "0.5790322", "0.5788491", "0.57879657", "0.57669735", "0.57647145", "0.5758713", "0.5752914", "0.5747571", "0.57373416", "0.5733135", "0.57227325", "0.57166564", "0.5699457", "0.56972885", "0.569595", "0.56813884", "0.56768316", "0.56751484", "0.5673868", "0.56666195", "0.5666145", "0.5658748", "0.56476015", "0.56403923", "0.5640168", "0.5636175", "0.56345993", "0.56326944", "0.562571", "0.5618212", "0.5610251", "0.56078666", "0.5606624", "0.5594055", "0.55937445", "0.5590344", "0.5582669", "0.5582034", "0.55781496", "0.55780417", "0.55705476", "0.55687636", "0.55556273", "0.5551762", "0.554715", "0.55452657", "0.55441636", "0.554288", "0.55395824", "0.5538309", "0.5537908", "0.55366933", "0.55326724", "0.5527858", "0.5523422", "0.5521649", "0.5518453", "0.5516935", "0.5516481", "0.5510816" ]
0.7074733
1
funcion para encontrar el minimo y el maximo de cualquier numero
func minmax(x, y, z int) (int, int) { var min int var max int if x > y && x > z { max = x if y < z { min = y } else { min = z } } else if y > x && y > z { max = y if x < z { min = x } else { min = z } } else { max = z if x < y { min = x } else { min = y } } return min, max }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func maxYmin2(numeros []int) (max int, min int) { //indicamos los tipos y nombre que va retornar (int, int)\n\tfor _, v := range numeros {\n\t\tif v > max {\n\t\t\tmax = v\n\t\t}\n\n\t\tif v < min {\n\t\t\tmin = v\n\t\t}\n\t}\n\n\treturn //ya no necesita return porque ya le indicamos como va retornar y que orden\n}", "func maxYmin(numeros []int) (int, int) { //indicamos los tipos que va retornar (int, int)\n\tvar max, min int\n\n\tfor _, v := range numeros {\n\t\tif v > max {\n\t\t\tmax = v\n\t\t}\n\n\t\tif v < min {\n\t\t\tmin = v\n\t\t}\n\t}\n\n\treturn max, min //indicamos el orden en el que se debe retornar\n}", "func MinMax(x, min, max int) int { return x }", "func (p parseSpec) minMax() (int, int) {\n\tmaxVal := -math.MaxInt64\n\tminVal := math.MaxInt64\n\tfor _, v := range p {\n\t\tif v > maxVal {\n\t\t\tmaxVal = v\n\t\t} else if v < minVal {\n\t\t\tminVal = v\n\t\t}\n\t}\n\treturn minVal, maxVal\n}", "func findMinAndMax(a []int) (min int, max int) {\n\tmin = a[0]\n\tmax = a[0]\n\tfor _, value := range a {\n\t\tif value < min {\n\t\t\tmin = value\n\t\t}\n\t\tif value > max {\n\t\t\tmax = value\n\t\t}\n\t}\n\treturn min, max\n}", "func main() {\n\tvar minMax = func(n []int) (int, int) {\n\t\tvar min, max int\n\n\t\tfor key, val := range n {\n\n\t\t\tif key == 0 {\n\t\t\t\tmin, max = val, val\n\t\t\t}\n\n\t\t\tif val < min {\n\t\t\t\tmin = val\n\t\t\t}\n\n\t\t\tif val > max {\n\t\t\t\tmax = val\n\t\t\t}\n\t\t}\n\n\t\treturn min, max\n\t}\n\n\tvar number = []int{10, 22, 3, 77, 1, 5}\n\n\tvar min, max = minMax(number)\n\n\tfmt.Printf(\"min : %d \", min)\n\tfmt.Printf(\"max : %d\", max)\n}", "func FindNumberRange(nums []int, key int) [2]int {\n\tresult := [2]int{-1, -1}\n\n\tresult[0] = getFirstInstance(nums, key)\n\tif result[0] != -1 {\n\t\tresult[1] = getLastInstance(nums, key)\n\t}\n\n\treturn result\n}", "func findMapRange(rm RobMap) (int, int, int, int) {\n\tvar minX, maxX, minY, maxY int\n\tfor coord := range rm {\n\t\tif int(real(coord)) < minX {\n\t\t\tminX = int(real(coord))\n\t\t}\n\t\tif int(real(coord)) > maxX {\n\t\t\tmaxX = int(real(coord))\n\t\t}\n\t\tif int(imag(coord)) < minY {\n\t\t\tminY = int(imag(coord))\n\t\t}\n\t\tif int(imag(coord)) > maxY {\n\t\t\tmaxY = int(imag(coord))\n\t\t}\n\t}\n\treturn minX, maxX, minY, maxY\n}", "func getPosLimit(pos Point, max *Point, rv int32) (start, end Point) {\n\tif (pos.X - rv) < 0 {\n\t\tstart.X = 0\n\t\tend.X = 2 * rv\n\t} else if (pos.X + rv) > max.X {\n\t\tend.X = max.X\n\t\tstart.X = max.X - 2*rv\n\t} else {\n\t\tstart.X = pos.X - rv\n\t\tend.X = pos.X + rv\n\t}\n\n\tif (pos.Y - rv) < 0 {\n\t\tstart.Y = 0\n\t\tend.Y = 2 * rv\n\t} else if (pos.Y + rv) > max.Y {\n\t\tend.Y = max.Y\n\t\tstart.Y = max.Y - 2*rv\n\t} else {\n\t\tstart.Y = pos.Y - rv\n\t\tend.Y = pos.Y + rv\n\t}\n\n\tif start.X < 0 {\n\t\tstart.X = 0\n\t}\n\n\tif end.X > max.X {\n\t\tend.X = max.X\n\t}\n\n\tif start.Y < 0 {\n\t\tstart.Y = 0\n\t}\n\n\tif end.Y > max.Y {\n\t\tend.Y = max.Y\n\t}\n\n\treturn\n}", "func Mimax(nums ...int) (int, int) {\n\tmin, max := nums[0], nums[0]\n\n\tfor _, num := range nums {\n\t\tif min > num {\n\t\t\tmin = num\n\t\t}\n\n\t\tif max < num {\n\t\t\tmax = num\n\t\t}\n\t}\n\n\treturn min, max\n}", "func getRange(min, max int) int {\n\treturn max * min\n}", "func findMax(number []int, max int) (int, func() []int) {\n\tvar res []int\n\tfor _, p := range number {\n\t\tif p <= max {\n\t\t\tres = append(res, p)\n\t\t}\n\t}\n\n\treturn len(res), func() []int {\n\t\treturn res\n\t}\n}", "func MinMaxInt32(x, min, max int32) int32 { return x }", "func findGreaterOrEqualIn(base int, acceptable []int) int {\n\tif base < 0 {\n\t\tpanic(fmt.Sprintf(\"%v is not a positive integer!\", base))\n\t}\n\tfor _, value := range acceptable {\n\t\tif value >= base {\n\t\t\treturn value\n\t\t}\n\t}\n\treturn -1\n}", "func findLargestNumber(args ...int) int {\n\tnumber := args[0]\n\n\tfor _, value := range args {\n\t\tif value > number {\n\t\t\tnumber = value\n\t\t}\n\t}\n\treturn number\n}", "func findgreatestnum(nums ...int) int {\n\tfmt.Printf(\"%T\\n\", nums)\n\tvar max int\n\tfor _, i := range nums {\n\t\tif max < i {\n\t\t\tmax = i\n\t\t}\n\t}\n\treturn max\n}", "func maxi(x int, y int) int {\n if x >= y {\n return x\n } else {\n return y\n }\n}", "func minimumBribes(q []int32) {\n\tvar bribes = 0\n\n\t// Iterate from the last element\n\tfor i := int32(len(q) - 1); i >= 0; i-- {\n\n\t\t// Since the original array was a sorted number array of 1 to n with interval of 1,\n\t\t// For example:\n\t\t// In Test Case of {2, 5, 1, 3, 4}\n\t\t// The element 5 (with original position of 5, index of 4) can only be placed up to position 3, index of 2\n\t\t// On this case, element 5 is placed on index 1 or position 2, so we need to find whether the position is valid or not\n\t\t// KEY: The difference must not be greater than 2\n\t\t// So, we substract the current position (which is array index + 1) from the current value, which is 5\n\t\t// and the difference = 5 - (1 + 1) = 5 - 2 = 3, indicated that there was an invalid move\n\t\tif q[i]-int32(i+1) > 2 {\n\t\t\tfmt.Println(\"Too chaotic\")\n\t\t\treturn\n\t\t}\n\n\t\t// Here, we need to find out how many briberies were happened, knowing that the bribery limit is 2.\n\t\t// So, we need to ensure that the two queue number in front of the current number is always lower than the current number.\n\t\t// For example:\n\t\t//\n\t\t// Under the Test Case of {2, 1, 5, 3, 4}\n\t\t// Let's say we are checking the first element from the back, which is 4.\n\t\t// We expect that the two people in front of number 4 has lower number\n\t\tvar max int32\n\t\t// i: 4 -> Is 0 >= 4 - 2? false, then max = 2\n\t\t// i: 3 -> Is 0 >= 3 - 2? false, then max = 1\n\t\t// i: 2 -> Is 0 >= 5 - 2? false, then max = 3\n\t\t// i: 1 -> Is 0 >= 1 - 2? true, then max = 0\n\t\t// i: 0 -> Is 0 >= 0 - 2? true, then max = 0\n\n\t\t// To prevent looping from negative index\n\t\tif 0 >= q[i]-2 {\n\t\t\tmax = 0\n\t\t} else {\n\t\t\tmax = q[i] - 2\n\t\t}\n\n\t\t// Loop through the ranged specification\n\t\t// The first element from the back is 4, and the two in front of it is 2.\n\t\t// We start from the 2nd index element.\n\t\t// The element at 2nd index is 5, and 5 is greater than the element at 4th index which is 4.\n\t\t// This indicated that number 5 had bribed number 4.\n\t\t// On the next step, the 3rd index contains number 3, and 3 is lower than 4. That means no bribery happened.\n\t\t//\n\t\t// Then we check the second element from the back, which is 3.\n\t\t// The second element from the back is placed at 3rd index position, so we loop through 1st index position.\n\t\t// The element at 1st index is 1, and 1 is not greater than 3. No bribery happened.\n\t\t// Then we check the element at 2nd index, which is 5. 5 is greater than 3, that means 5 had bribed 3.\n\t\tfor j := max; j < i; j++ {\n\t\t\t// max: 2; i: 4\n\t\t\t// 5 > 4? true, bribes++\n\t\t\t// 3 > 4? false\n\t\t\t//\n\t\t\t// max: 1; i: 3\n\t\t\t// 1 > 3? false\n\t\t\t// 5 > 3? true, bribes++\n\t\t\t//\n\t\t\t// max: 3; i: 2\n\t\t\t// no checking\n\t\t\t//\n\t\t\t// max: 0; i: 1\n\t\t\t// 2 > 1? true, bribes++\n\t\t\t//\n\t\t\t// max: 0; i: 0\n\t\t\t// no checking\n\n\t\t\tif q[j] > q[i] {\n\t\t\t\tbribes++\n\t\t\t}\n\t\t}\n\t}\n\t// Expected result: 3\n\tfmt.Println(bribes)\n}", "func (a *IntegerArray) FindRange(min, max int64) (int, int) {\n\tif a.Len() == 0 || min > max {\n\t\treturn -1, -1\n\t}\n\n\tminVal := a.MinTime()\n\tmaxVal := a.MaxTime()\n\n\tif maxVal < min || minVal > max {\n\t\treturn -1, -1\n\t}\n\n\treturn a.search(min), a.search(max)\n}", "func (rn *RangedNumber) Max() int {\n\tif rn.min > rn.max {\n\t\trn.Set(rn.max, rn.min)\n\t}\n\n\treturn rn.max\n}", "func findGreaterOrEqualInLooping(base int, acceptable []int) (int, bool) {\n\tlooped := false\n\tclosest := findGreaterOrEqualIn(base, acceptable)\n\tif closest == -1 {\n\t\tlooped = true\n\t\tclosest = findGreaterOrEqualIn(0, acceptable)\n\t}\n\tif closest == -1 {\n\t\tpanic(fmt.Sprintf(\"All acceptable integers given are negative!\"))\n\t}\n\treturn closest, looped\n}", "func max(m, n int) (int, bool) {\n\tif m > n {\n\t\treturn m, true\n\t}\n\treturn n, false\n}", "func minmax() (min float64, max float64) {\n\tmin = math.NaN()\n\tmax = math.NaN()\n\tfor i := 0; i < cells; i++ {\n\t\tfor j := 0; j < cells; j++ {\n\t\t\tfor xoff := 0; xoff <= 1; xoff++ {\n\t\t\t\tfor yoff := 0; yoff <= 1; yoff++ {\n\t\t\t\t\tx := xyrange * (float64(i+xoff)/cells - 0.5)\n\t\t\t\t\ty := xyrange * (float64(j+yoff)/cells - 0.5)\n\t\t\t\t\tz := f(x, y)\n\t\t\t\t\tif math.IsNaN(min) || z < min {\n\t\t\t\t\t\tmin = z\n\t\t\t\t\t}\n\t\t\t\t\tif math.IsNaN(max) || z > max {\n\t\t\t\t\t\tmax = z\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func getMinMaxScores(scores framework.NodeScoreList) (int64, int64) {\n\tvar max int64 = math.MinInt64 // Set to min value\n\tvar min int64 = math.MaxInt64 // Set to max value\n\n\tfor _, nodeScore := range scores {\n\t\tif nodeScore.Score > max {\n\t\t\tmax = nodeScore.Score\n\t\t}\n\t\tif nodeScore.Score < min {\n\t\t\tmin = nodeScore.Score\n\t\t}\n\t}\n\t// return min and max scores\n\treturn min, max\n}", "func Min(numbers ...int) int {\n\tmax := numbers[0]\n\tfor i, number := range numbers {\n\t\tif i == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif max > number {\n\t\t\tmax = number\n\t\t}\n\t}\n\treturn max\n}", "func (m mathUtil) MinAndMax(values ...float64) (min float64, max float64) {\n\tif len(values) == 0 {\n\t\treturn\n\t}\n\tmin = values[0]\n\tmax = values[0]\n\tfor _, v := range values {\n\t\tif max < v {\n\t\t\tmax = v\n\t\t}\n\t\tif min > v {\n\t\t\tmin = v\n\t\t}\n\t}\n\treturn\n}", "func Range(instructions []string) (int, int) {\n\tmax := 0\n\tmin := 4294967295\n\tfor _, instruction := range instructions {\n\t\tid := getID(instruction)\n\t\tif id > max {\n\t\t\tmax = id\n\t\t}\n\t\tif id < min {\n\t\t\tmin = id\n\t\t}\n\t}\n\treturn max, min\n}", "func max(a, b int) int {\nif a < b {\nreturn b\n}\nreturn a\n}", "func max(first int, second int) int {\n\tif first >= second {\n\t\treturn first\n\t} else {\n\t\treturn second\n\t}\n}", "func FindNb(m int) int {\n\tfor n := 1; m > 0; n++ {\n\t\tm -= n * n * n\n\t\tfmt.Println(\"the m : \", m)\n\t\tif m == 0 {\n\t\t\treturn n\n\t\t}\n\t}\n\treturn -1\n}", "func Min(x, min int) int { return x }", "func (rn *RangedNumber) Min() int {\n\tif rn.min > rn.max {\n\t\trn.Set(rn.max, rn.min)\n\t}\n\n\treturn rn.min\n}", "func extrema(data []float64) (float64, float64) {\n\tmin := largest\n\tmax := smallest\n\n\tfor _, d := range data {\n\t\tif d > max {\n\t\t\tmax = d\n\t\t}\n\t\tif d < min {\n\t\t\tmin = d\n\t\t}\n\t}\n\treturn min, max\n}", "func min(n int, rest ...int) int {\n\tm := n\n\tfor _, v := range rest {\n\t\tif v < m {\n\t\t\tm = v\n\t\t}\n\t}\n\treturn m\n}", "func min(integers ...int) int {\n\tm := integers[0]\n\tfor i, integer := range integers {\n\t\tif i == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif m > integer {\n\t\t\tm = integer\n\t\t}\n\t}\n\treturn m\n}", "func minimumBribes(q []int32) {\n\tvar min int32\n\tminor := make([]int32, 0, len(q))\n\tfor i := 0; i < len(q); i++ {\n\t\toffset := q[i] - int32(i) - 1\n\t\tif offset > 2 {\n\t\t\tfmt.Println(\"Too chaotic\")\n\t\t\treturn\n\t\t} else if offset > 0 {\n\t\t\tmin += offset\n\t\t} else if offset <= 0 {\n\t\t\tminor = append(minor, q[i])\n\t\t\t/*\n\t\t\t\tfor j := i; j < len(q); j++ {\n\t\t\t\t\tif q[j] < q[i] {\n\t\t\t\t\t\tmin++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t*/\n\t\t}\n\t}\n\tvar curMax int32\n\tmax := make([]int32, len(minor))\n\tfor i := 0; i < len(minor); i++ {\n\t\tif minor[i] > curMax {\n\t\t\tmax[i] = minor[i]\n\t\t\tcurMax = minor[i]\n\t\t} else {\n\t\t\tmax[i] = curMax\n\n\t\t\tback := i - 1\n\t\t\tfor back >= 0 {\n\t\t\t\tif minor[i] < max[i] {\n\t\t\t\t\tif minor[i] < minor[back] {\n\t\t\t\t\t\tmin++\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tback--\n\t\t\t}\n\t\t}\n\t}\n\n\t/*\n\t\tfor i := len(q) - 1; i >= 0; i-- {\n\t\t\toffset := q[i] - int32(i) - 1\n\t\t\toffset1 := int32(i) + 1 - q[i]\n\t\t\tif offset > 2 {\n\t\t\t\tfmt.Println(\"Too chaotic\")\n\t\t\t\treturn\n\t\t\t} else if offset1 >= 0 {\n\t\t\t\tmin += offset1\n\t\t\t\tif offset1 == 0 {\n\t\t\t\t\tmin++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t*/\n\n\tfmt.Println(min)\n}", "func findBiggest(numbers ...int) int {\n\tvar biggest int\n\t//iterate over numbers\n\tfor _, v := range numbers {\n\t\tif v > biggest {\n\t\t\tbiggest = v\n\t\t}\n\t}\n\n\treturn biggest\n}", "func (a *UnsignedArray) FindRange(min, max int64) (int, int) {\n\tif a.Len() == 0 || min > max {\n\t\treturn -1, -1\n\t}\n\n\tminVal := a.MinTime()\n\tmaxVal := a.MaxTime()\n\n\tif maxVal < min || minVal > max {\n\t\treturn -1, -1\n\t}\n\n\treturn a.search(min), a.search(max)\n}", "func MinMaxDiff(vals []string) int {\n\tmin, _ := strconv.Atoi(vals[0])\n\tmax := min\n\tfor _, v := range vals {\n\t\td, err := strconv.Atoi(v)\n\t\tif err != nil {\n\t\t\tpanic(\"could not parse number!\")\n\t\t}\n\t\tif int(d) < min {\n\t\t\tmin = int(d)\n\t\t} else if int(d) > max {\n\t\t\tmax = int(d)\n\t\t}\n\t}\n\n\treturn max - min\n}", "func min(x, y int) int {\n\tif x > y {\n\t\treturn y\n\t}\n\treturn x\n}", "func Max(x, y int) int {\n if x < y {\n return y\n }\n return x\n}", "func min(a, b int) int {\n\tif a > b {\n\t\treturn b\n\t}\n\treturn a\n}", "func max(num1, num2 int) int {\nresult int\n\n\tif (num1 > num2){\n\t\tresult = num1\n\t} else{\n\t\tresult = num2\n\t}\nreturn result\n}", "func min(x, y int) int {\n\tif x > y {\n\t\treturn y\n\t}\n\n\treturn x\n}", "func testMaxMin(f interface{}) (passed, failed int, err error) {\n\tintArr := &pr.ArrayMatcher{M: &pr.KindMatcher{Kind: reflect.Int}}\n\twantFn := &pr.FuncMatcher{\n\t\tIn: []pr.TypeMatcher{intArr},\n\t\tOut: []pr.TypeMatcher{\n\t\t\t&pr.KindMatcher{Kind: reflect.Int},\n\t\t\t&pr.KindMatcher{Kind: reflect.Int},\n\t\t},\n\t}\n\tif !wantFn.MatchType(reflect.TypeOf(f)) {\n\t\treturn 0, 0, errors.New(\"want func([N]int)(min, max int)\")\n\t}\n\n\tvalF := reflect.ValueOf(f)\n\tcallF := func(in reflect.Value) (max, min int) {\n\t\targs := []reflect.Value{in.Elem()}\n\t\tret := valF.Call(args)\n\t\treturn int(ret[0].Int()), int(ret[1].Int())\n\t}\n\n\tal := intArr.Len\n\tbuilder := func() *pr.IntArrayBuilder {\n\t\treturn &pr.IntArrayBuilder{Count: al}\n\t}\n\n\tfor _, test := range []struct {\n\t\tname string\n\t\tin *pr.IntArrayBuilder\n\t\twantMin, wantMax int\n\t}{\n\t\t{name: \"zero value\", wantMin: 0, wantMax: 0, in: builder()},\n\t\t{name: \"straight up\", wantMin: 1, wantMax: al, in: builder().FillRange(1, 1)},\n\t\t{name: \"straight down\", wantMin: -al, wantMax: -1, in: builder().FillRange(-1, -1)},\n\t\t{name: \"shuffle\", wantMin: -al / 2, wantMax: -al/2 + al - 1, in: builder().FillRange(-al/2, 1).Shuffle()},\n\t} {\n\t\tactualMax, actualMin := callF(test.in.Build())\n\t\tif actualMin == test.wantMin && actualMax == test.wantMax {\n\t\t\tlog.Println(\"PASS:\", test.name)\n\t\t\tpassed++\n\t\t} else {\n\t\t\tlog.Println(\"FAIL:\", test.name)\n\t\t\tfailed++\n\t\t}\n\t}\n\treturn\n}", "func getMaxNumber(numbers ...int) int {\n highest := numbers[0] // first value by default\n for _, value := range numbers {\n if value > highest {\n highest = value\n }\n }\n return highest\n}", "func min(a, b int32) int32 {\n\tif a <= b {\n\t\treturn a\n\t}\n\treturn b\n}", "func max(x, y int) int {\n\tif x < y {\n\t\treturn y\n\t}\n\treturn x\n}", "func MinMaxExclusiveInt(min, max int, minExclusive, maxExclusive bool) (int, int, bool, bool) {\n\tif min > max {\n\t\treturn max, min, maxExclusive, minExclusive\n\t}\n\treturn min, max, minExclusive, maxExclusive\n}", "func min(one int, two int) (rtn int) {\n if one < two {\n rtn = one\n } else {\n rtn = two\n }\n\n return\n}", "func MinMaxInt64(x, min, max int64) int64 { return x }", "func max(num1, num2 int) (int, int) {\n\tif num1 > num2 {\n\t\treturn num1, num2\n\t} else {\n\t\treturn num2, num1\n\t}\n}", "func (tf tFiles) getRange(icmp *iComparer) (imin, imax internalKey) {\n\tfor i, t := range tf {\n\t\tif i == 0 {\n\t\t\timin, imax = t.imin, t.imax\n\t\t\tcontinue\n\t\t}\n\t\tif icmp.Compare(t.imin, imin) < 0 {\n\t\t\timin = t.imin\n\t\t}\n\t\tif icmp.Compare(t.imax, imax) > 0 {\n\t\t\timax = t.imax\n\t\t}\n\t}\n\n\treturn\n}", "func (this *ExDomain) GetMinAndMax() (int, int) {\n\tif this.IsEmpty() {\n\t\tlogger.If(\"Domain %s\", *this)\n\t\tdebug.PrintStack()\n\t\tpanic(\"GetMinMax on empty domain\")\n\t}\n\treturn this.Min, this.Max\n}", "func (x IntRange) orMax(y IntRange) *big.Int {\n\tif x[0].Sign() == 0 && y[0].Sign() == 0 {\n\t\ti := big.NewInt(0)\n\t\ti.And(x[1], y[1])\n\t\tbitFillRight(i)\n\t\ti.Rsh(i, 1)\n\t\ti.Or(i, x[1])\n\t\ti.Or(i, y[1])\n\t\treturn i\n\t}\n\n\t// Four examples:\n\t// - Example #0: x is [1, 3] and y is [ 4, 9], orMax is 11.\n\t// - Example #1: x is [3, 4] and y is [ 5, 6], orMax is 7.\n\t// - Example #2: x is [4, 5] and y is [ 6, 7], orMax is 7.\n\t// - Example #3: x is [7, 7] and y is [12, 14], orMax is 15.\n\n\ti := big.NewInt(0)\n\tj := big.NewInt(0)\n\n\t// j = droppable = bitFillRight((xMax & ~xMin) | (yMax & ~yMin))\n\t//\n\t// For example #0, j = bfr((3 & ~1) | ( 9 & ~ 4)) = bfr(2 | 9) = 15.\n\t// For example #1, j = bfr((4 & ~3) | ( 6 & ~ 5)) = bfr(4 | 2) = 7.\n\t// For example #2, j = bfr((5 & ~4) | ( 7 & ~ 6)) = bfr(1 | 1) = 1.\n\t// For example #3, j = bfr((7 & ~7) | (14 & ~12)) = bfr(0 | 2) = 3.\n\ti.AndNot(x[1], x[0])\n\tj.AndNot(y[1], y[0])\n\tj.Or(j, i)\n\tbitFillRight(j)\n\n\t// j = available = xMax & yMax & j\n\t//\n\t// For example #0, j = 3 & 9 & 15 = 1.\n\t// For example #1, j = 4 & 6 & 7 = 4.\n\t// For example #2, j = 5 & 7 & 1 = 1.\n\t// For example #3, j = 7 & 14 & 3 = 2.\n\tj.And(j, x[1])\n\tj.And(j, y[1])\n\n\t// j = bitFillRight(j) >> 1\n\t//\n\t// For example #0, j = bfr(1) >> 1 = 0.\n\t// For example #1, j = bfr(4) >> 1 = 3.\n\t// For example #2, j = bfr(1) >> 1 = 0.\n\t// For example #3, j = bfr(2) >> 1 = 1.\n\tbitFillRight(j)\n\tj.Rsh(j, 1)\n\n\t// return xMax | yMax | j\n\t//\n\t// For example #0, return 3 | 9 | 0 = 11.\n\t// For example #1, return 4 | 6 | 3 = 7.\n\t// For example #2, return 5 | 7 | 0 = 7.\n\t// For example #3, return 7 | 14 | 1 = 15.\n\tj.Or(j, x[1])\n\tj.Or(j, y[1])\n\treturn j\n}", "func MinMaxInt(min, max int) (int, int) {\n\tif min > max {\n\t\treturn max, min\n\t}\n\treturn min, max\n}", "func max(integers ...int) int {\n\tm := integers[0]\n\tfor i, integer := range integers {\n\t\tif i == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif m < integer {\n\t\t\tm = integer\n\t\t}\n\t}\n\treturn m\n}", "func mini(x int, y int) int {\n // Return the minimum of two integers.\n if x <= y {\n return x\n } else {\n return y\n }\n}", "func (g *graph) find_max_value(chk *checklist) int {\n\tcurrent := 0\n\tidx := -1\n\tfor i,c := range chk.nodes_count {\n\t\tif c > current {\n\t\t\tidx = i\n\t\t\tcurrent = c\n\t\t}\n\t}\n\tif idx >= 0 { chk.nodes_count[idx] = -1 }\n\treturn idx\n}", "func maxI(a int, b int) (res int) {\n\tif a < b {\n\t\tres = b\n\t} else {\n\t\tres = a\n\t}\n\n\treturn\n}", "func MaxInt(x, y int) int {\n\tif x < y {\n\t\treturn y\n\t}\n\treturn x\n}", "func find_min_working(workers map[int]int) int {\n min := math.MaxInt32\n for i := 0; i < 5; i++ {\n if workers[i] > 0 && workers[i] < min{\n min = workers[i]\n }\n }\n return min\n}", "func (a *FloatArray) FindRange(min, max int64) (int, int) {\n\tif a.Len() == 0 || min > max {\n\t\treturn -1, -1\n\t}\n\n\tminVal := a.MinTime()\n\tmaxVal := a.MaxTime()\n\n\tif maxVal < min || minVal > max {\n\t\treturn -1, -1\n\t}\n\n\treturn a.search(min), a.search(max)\n}", "func Max(a int, b int) int {\n\tif a >= b {\n\t\treturn a\n\t}\n\treturn b\n}", "func constrain(min, n, max float64) float64 {\n\tn = math.Max(min, n)\n\tn = math.Min(n, max)\n\treturn n\n}", "func max(a, b int32) int32 {\n\tif a >= b {\n\t\treturn a\n\t}\n\treturn b\n}", "func max(x, y int) int {\n\tif x > y {\n\t\treturn x\n\t}\n\treturn y\n}", "func max(x, y int) int {\n\tif x > y {\n\t\treturn x\n\t}\n\treturn y\n}", "func max(x, y int) int {\n\tif x > y {\n\t\treturn x\n\t}\n\treturn y\n}", "func max(x, y int) int {\n\tif x > y {\n\t\treturn x\n\t}\n\treturn y\n}", "func max(x, y int) int {\n\tif x > y {\n\t\treturn x\n\t}\n\treturn y\n}", "func findPivot(values []uint64, minIndex int) (pivot int, maxBefore uint64) {\n\t// First construct a table where minRight[i] is the minimum value in [i..n)\n\tn := len(values)\n\tminRight := make([]uint64, n)\n\tvar min uint64 = math.MaxUint64\n\tfor i := n - 1; i >= 0; i-- {\n\t\tif values[i] < min {\n\t\t\tmin = values[i]\n\t\t}\n\t\tminRight[i] = min\n\t}\n\t// Now scan left-to-right tracking the running max and looking for a pivot:\n\tmaxBefore = 0\n\tfor pivot = 0; pivot < n-1; pivot++ {\n\t\tif values[pivot] > maxBefore {\n\t\t\tmaxBefore = values[pivot]\n\t\t}\n\t\tif pivot >= minIndex && maxBefore < minRight[pivot+1] {\n\t\t\tbreak\n\t\t}\n\t}\n\t//log.Printf(\"PIVOT: %v @%d -> %d\", values, minIndex, pivot)\n\treturn\n}", "func Max(x, y int) int {\n\tif x < y {\n\t\treturn y\n\t}\n\treturn x\n}", "func (s *GoSort) FindMaxElementAndIndex() (interface{},int) {\n var index = 0\n \n for i := 1; i < s.Len(); i++ {\n if s.GreaterThan(i, index) {\n index = i\n }\n }\n return s.values[index], index\n}", "func min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func (qs ControlQS) IntabsmaxNe(v float64) ControlQS {\n\treturn qs.filter(`\"intabsmax\" <>`, v)\n}", "func min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\n\treturn b\n}", "func findMax(sum map[int64]int64) int64 {\n\tdx := int64(0)\n\n\tfor _, v := range sum {\n\t\tdx = int64(math.Max(float64(dx), float64(v)))\n\t}\n\treturn dx\n}", "func min(x, y int64) int64 {\n\tif x > y {\n\t\treturn y\n\t}\n\treturn x\n}", "func max(a, b int) int {\n\tif a < b {\n\t\treturn b\n\t}\n\treturn a\n}", "func min(x, y int) int {\n\tif x < y {\n\t\treturn x\n\t}\n\treturn y\n}", "func min(x, y int) int {\n\tif x < y {\n\t\treturn x\n\t}\n\treturn y\n}", "func min(x, y int) int {\n\tif x < y {\n\t\treturn x\n\t}\n\treturn y\n}", "func max(x int, y int) int {\n\tif x > y {\n\t\treturn x\n\t}\n\treturn y\n}", "func min(a, b int) int {\n\tif b < a {\n\t\treturn b\n\t}\n\treturn a\n}", "func min(a, b int) int {\n\tif b < a {\n\t\treturn b\n\t}\n\treturn a\n}", "func min(a, b int) int {\r\n\tif a < b {\r\n\t\treturn a\r\n\t}\r\n\treturn b\r\n}", "func min(a, b int) int {\r\n\tif a < b {\r\n\t\treturn a\r\n\t}\r\n\treturn b\r\n}", "func min(a int, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func FindMaxValueFromList(list []int) (int, int) {\n\tmax := list[0]\n\tindexOfMaxElement := 0\n\tfor i := 1; i < len(list); i++ {\n\t\tif list[i] > max {\n\t\t\tmax = list[i]\n\t\t\tindexOfMaxElement = i\n\t\t}\n\t}\n\treturn max, indexOfMaxElement\n}" ]
[ "0.696737", "0.6776321", "0.645765", "0.636155", "0.62201566", "0.6208302", "0.6009031", "0.5961037", "0.5939408", "0.5930139", "0.5914764", "0.58389395", "0.5824885", "0.5724125", "0.5715359", "0.5698225", "0.56750005", "0.5663219", "0.5623163", "0.5582709", "0.55790997", "0.5572614", "0.55704296", "0.5562928", "0.55459034", "0.5535624", "0.55353373", "0.5527654", "0.55000067", "0.549931", "0.54953086", "0.54948", "0.54929805", "0.5486739", "0.5480024", "0.5478724", "0.54723287", "0.54639554", "0.5447174", "0.54471344", "0.54382825", "0.54282886", "0.5423305", "0.54205376", "0.5399495", "0.53940916", "0.5379987", "0.5377337", "0.5373487", "0.53722745", "0.53552556", "0.53525734", "0.5348218", "0.534763", "0.5346216", "0.53441423", "0.53358465", "0.53349674", "0.5334792", "0.53112215", "0.53074527", "0.5302443", "0.53015405", "0.529928", "0.5294567", "0.52906543", "0.52879584", "0.52879584", "0.52879584", "0.52879584", "0.52879584", "0.52866167", "0.5286028", "0.52859855", "0.5280911", "0.5280911", "0.5280911", "0.5280911", "0.5280911", "0.5280911", "0.5280911", "0.5280911", "0.5280911", "0.5280911", "0.5280911", "0.5278971", "0.5270913", "0.5270558", "0.5267721", "0.52597034", "0.5253484", "0.5253484", "0.5253484", "0.525225", "0.5252164", "0.5252164", "0.52422285", "0.52422285", "0.52405113", "0.52391714" ]
0.53503966
52
Tagged is only visible with tags.
func Tagged() int { return 7 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func HasForbiddenTag(tags []string) error {\n\tfor _, tag := range tags {\n\t\tfor _, forbiddenTag := range secretTypes.ForbiddenTags {\n\t\t\tif tag == forbiddenTag {\n\t\t\t\treturn ForbiddenError{\n\t\t\t\t\tForbiddenTag: tag,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (o *FiltersNet) HasTagKeys() bool {\n\tif o != nil && o.TagKeys != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *FiltersSecurityGroup) HasTagKeys() bool {\n\tif o != nil && o.TagKeys != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func checkTag(tag string) bool {\n\tfor _, c := range tag {\n\t\tif !isTagAuthorizedChar(c) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func IsTag(name string) bool {\n\treturn plumbing.ReferenceName(name).IsTag()\n}", "func (o *PublicIp) HasTags() bool {\n\tif o != nil && o.Tags != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *PublicIp) HasTags() bool {\n\tif o != nil && o.Tags != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *FiltersNet) HasTags() bool {\n\tif o != nil && o.Tags != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func CommandShowTags(conf Config, ctx, query Query) error {\n\tts, err := LoadTaskSet(conf.Repo, conf.IDsFile, false)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tquery = query.Merge(ctx)\n\tts.Filter(query)\n\n\tfor tag := range ts.GetTags() {\n\t\tfmt.Println(tag)\n\t}\n\treturn nil\n}", "func (o *FiltersVirtualGateway) HasTagKeys() bool {\n\tif o != nil && o.TagKeys != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *FiltersNatService) HasTagKeys() bool {\n\tif o != nil && o.TagKeys != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func isInTag(s state) bool {\n\tswitch s {\n\tcase stateTag, stateAttrName, stateAfterName, stateBeforeValue, stateAttr:\n\t\treturn true\n\t}\n\treturn false\n}", "func (u User) HasTag(t frameworks.Tag) bool {\n\tresult := false\n\treturn result\n}", "func (r *PrivateVirtualInterface) Tags() pulumi.MapOutput {\n\treturn (pulumi.MapOutput)(r.s.State[\"tags\"])\n}", "func (o *FiltersVirtualGateway) HasTags() bool {\n\tif o != nil && o.Tags != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *FiltersVmGroup) HasTagKeys() bool {\n\tif o != nil && o.TagKeys != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (a Article) HasTag(aTag string) bool {\n\tfor _, tag := range a.Tags {\n\t\tif aTag == tag.Name {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (r ReferenceName) IsTag() bool {\n\treturn strings.HasPrefix(string(r), refTagPrefix)\n}", "func (f NoStrikesField) Tag() quickfix.Tag { return tag.NoStrikes }", "func (this *Tidy) HideEndtags(val bool) (bool, error) {\n\treturn this.optSetBool(C.TidyHideEndTags, cBool(val))\n}", "func (m *TagManager) IsTagged(name string, node nodes.OsqueryNode) bool {\n\treturn m.IsTaggedID(name, node.ID)\n}", "func GetHidden() (tags []Type, err error) {\n\ttags = make([]Type, 0)\n\n\t_, err = mongo.Find(\"blotter\", \"tags\", bson.M{\n\t\t\"hide\": true,\n\t}, nil, &tags)\n\n\tif err != nil {\n\t\treturn\n\t}\n\treturn tags, nil\n}", "func (profession Profession) HasTag(tag string) bool {\n\tfor _, t := range profession.Tags {\n\t\tif t == tag {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (containerRepository *ContainerRepository) IsTag(column string) bool {\n\tfor _, tag := range recommendation_entity.ContainerTags {\n\t\tif column == string(tag) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (o *FiltersSecurityGroup) HasTags() bool {\n\tif o != nil && o.Tags != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (dtk *DcmTagKey) IsSignableTag() bool {\n\t//no group length tags (element number of 0000)\n\tif dtk.element == 0x0000 {\n\t\treturn false\n\t}\n\t// no Length to End Tag\n\tif (dtk.group == 0x0008) && (dtk.element == 0x0001) {\n\t\treturn false\n\t}\n\n\t//no tags with group number less than 0008\n\tif dtk.group < 0x0008 {\n\t\treturn false\n\t}\n\n\t//no tags from group FFFA (digital signatures sequence)\n\tif dtk.group == 0xFFFA {\n\t\treturn false\n\t}\n\n\t// no MAC Parameters sequence\n\tif (dtk.group == 0x4ffe) && (dtk.element == 0x0001) {\n\t\treturn false\n\t}\n\n\t//no Data Set trailing Padding\n\tif (dtk.group == 0xfffc) && (dtk.element == 0xfffc) {\n\t\treturn false\n\t}\n\n\t//no Sequence or Item Delimitation Tag\n\tif (dtk.group == 0xfffe) && ((dtk.element == 0xe00d) || (dtk.element == 0xe0dd)) {\n\t\treturn false\n\t}\n\treturn true\n}", "func IsTag(ref string) bool {\n\treturn strings.HasPrefix(ref, \"refs/tags/\")\n}", "func (o *SecurityGroup) HasTags() bool {\n\tif o != nil && o.Tags != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func isTagAuthorizedChar(c rune) bool {\n\treturn ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') || c == '-'\n}", "func hasTags(cmd *cobra.Command) bool {\n\tfor curr := cmd; curr != nil; curr = curr.Parent() {\n\t\tif len(curr.Tags) > 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (o *FiltersNatService) HasTags() bool {\n\tif o != nil && o.Tags != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func hasTags(tags map[string]string) bool {\n\tn := len(tags)\n\tif n == 0 {\n\t\treturn false\n\t}\n\treturn true\n}", "func (o BucketIntelligentTieringConfigurationFilterOutput) Tags() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v BucketIntelligentTieringConfigurationFilter) map[string]string { return v.Tags }).(pulumi.StringMapOutput)\n}", "func (c *ContainerRepository) IsTag(column string) bool {\n\tfor _, tag := range EntityInfluxPlanning.ContainerTags {\n\t\tif column == string(tag) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (f *flags) Tags() []string {\n\tif f.opt.Tags == modeFlagUnUsed {\n\t\treturn nil\n\t}\n\treturn f.exclude(f.getvalue(f.opt.Tags, \"tags\", \"t\"),\n\t\tf.getvalue(f.opt.ExcludeTags, \"nt\", \"\"))\n\n}", "func (o *Member) HasTags() bool {\n\tif o != nil && o.Tags != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *NetworkingProjectNetadpCreate) HasTag() bool {\n\tif o != nil && o.Tag != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func NewGetTagForbidden() *GetTagForbidden {\n\n\treturn &GetTagForbidden{}\n}", "func (o ReservedInstanceOutput) Tags() pulumi.MapOutput {\n\treturn o.ApplyT(func(v *ReservedInstance) pulumi.MapOutput { return v.Tags }).(pulumi.MapOutput)\n}", "func (o *ViewMilestone) HasTags() bool {\n\tif o != nil && o.Tags != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (n *node) HasTag(name string) bool {\n\tfor _, v := range n.tags {\n\t\tif v == name {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (sp *Space) HasTags(tags ...string) bool {\n\n\tfor _, shape := range *sp {\n\t\tif !shape.HasTags(tags...) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n\n}", "func (l Info) HasTag(tag string) bool {\n\tfor _, t := range l.Tags {\n\t\tif tag == t {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (e *RawExecutor) tagSetIsLimited(tagset string) bool {\n\t_, ok := e.limitedTagSets[tagset]\n\treturn ok\n}", "func (o *VirtualGateway) HasTags() bool {\n\tif o != nil && o.Tags != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *NetworkingProjectIpCreate) HasTag() bool {\n\tif o != nil && o.Tag != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *InlineResponse200115) HasTags() bool {\n\tif o != nil && o.Tags != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *CreateInstance) HasTags() bool {\n\tif o != nil && !IsNil(o.Tags) {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (outer outer) Visible() bool {\r\n\treturn false\r\n}", "func (o *FiltersVmGroup) HasTags() bool {\n\tif o != nil && o.Tags != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (f *FlagBase[T, C, V]) IsVisible() bool {\n\treturn !f.Hidden\n}", "func (o *LogContent) HasTags() bool {\n\tif o != nil && o.Tags != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (f InViewOfCommonField) Tag() quickfix.Tag { return tag.InViewOfCommon }", "func (o *TenantWithOfferWeb) HasTags() bool {\n\tif o != nil && o.Tags != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o NetworkOutput) Tags() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *Network) pulumi.StringArrayOutput { return v.Tags }).(pulumi.StringArrayOutput)\n}", "func hasTag(tags []*ec2.Tag, Key string, value string) bool {\n\tfor i := range tags {\n\t\tif *tags[i].Key == Key && *tags[i].Value == value {\n\t\t\tlog.Printf(\"\\t\\tTag %s already set with value %s\\n\",\n\t\t\t\t*tags[i].Key,\n\t\t\t\t*tags[i].Value)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (o *Volume) HasTags() bool {\n\tif o != nil && o.Tags != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *Volume) HasTags() bool {\n\tif o != nil && o.Tags != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (t Tagging) String() string {\n\tvar buf bytes.Buffer\n\tfor _, tag := range t.TagSet.Tags {\n\t\tif buf.Len() > 0 {\n\t\t\tbuf.WriteString(\"&\")\n\t\t}\n\t\tbuf.WriteString(tag.String())\n\t}\n\treturn buf.String()\n}", "func HasTag(tags []string, requiredTag string) bool {\n\tfor _, tag := range tags {\n\t\tif tag == requiredTag {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (vd *Verb_Index) Tag() string { return \"index\" }", "func (f *Fieldx) Tag(key string) string {\n\treturn f.data.Tag.Get(key)\n}", "func (f TotNoStrikesField) Tag() quickfix.Tag { return tag.TotNoStrikes }", "func (o *InlineObject86) HasTag() bool {\n\tif o != nil && o.Tag != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (m Mineral) HasTag(tag string) bool {\n\tfor _, t := range m.Tags {\n\t\tif t == tag {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (o *NetworkingProjectNetworkCreate) HasTag() bool {\n\tif o != nil && o.Tag != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func ListTags() []string {\n\treturn _tags\n}", "func (o *SyntheticsBrowserTest) HasTags() bool {\n\tif o != nil && o.Tags != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func TestIsTagged(t *testing.T) {\n\n\tstatus := statusHandler(404)\n\tts := httptest.NewServer(&status)\n\tdefer ts.Close()\n\n\tif isTagged(ts.URL) {\n\t\tt.Error(\"isTagged returned true, want false\")\n\t}\n\n\tstatus = 200\n\n\tif !isTagged(ts.URL) {\n\t\tt.Error(\"isTagged returned false, want true\")\n\t}\n\n}", "func (t ISILTagger) Tags(is finc.IntermediateSchema) []string {\n\tisils := container.NewStringSet()\n\tfor isil, filters := range t {\n\t\tfor _, f := range filters {\n\t\t\tif f.Apply(is) {\n\t\t\t\tisils.Add(isil)\n\t\t\t}\n\t\t}\n\t}\n\treturn isils.Values()\n}", "func (o *Vm) HasTag() bool {\n\tif o != nil && o.Tag != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *SoftwarerepositoryCategoryMapper) HasTagTypes() bool {\n\tif o != nil && o.TagTypes != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *FiltersNet) HasTagValues() bool {\n\tif o != nil && o.TagValues != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o BucketIntelligentTieringConfigurationFilterPtrOutput) Tags() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *BucketIntelligentTieringConfigurationFilter) map[string]string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Tags\n\t}).(pulumi.StringMapOutput)\n}", "func (o *IamProjectRoleCreate) HasTag() bool {\n\tif o != nil && o.Tag != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (m *ccMetric) HasTag(key string) bool {\n\t_, ok := m.tags[key]\n\treturn ok\n}", "func (v *View) TagFilter() map[string]string {\n\tfilter := map[string]string{}\n\tfor _, t := range v.tags {\n\t\tp := strings.Split(t, \"=\")\n\t\tif len(p) == 2 {\n\t\t\tfilter[p[0]] = p[1]\n\t\t} else {\n\t\t\tfilter[p[0]] = \"\"\n\t\t}\n\t}\n\treturn filter\n}", "func (dtk *DcmTagKey) IsPrivate() bool {\n\treturn ((dtk.group & 1) != 0) && dtk.HasValidGroup()\n}", "func (o InstanceOutput) Tags() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringArrayOutput { return v.Tags }).(pulumi.StringArrayOutput)\n}", "func (o InstanceOutput) Tags() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringArrayOutput { return v.Tags }).(pulumi.StringArrayOutput)\n}", "func (r *Role) HasTag(tag string) bool {\n\tfor _, t := range r.Tags {\n\t\tif t == tag {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (r *Role) HasTag(tag string) bool {\n\tfor _, t := range r.Tags {\n\t\tif t == tag {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (f SolicitedFlagField) Tag() quickfix.Tag { return tag.SolicitedFlag }", "func (sd *PrivateDescriptor) Tag() uint32 {\n\t// ensure JSONType is set\n\tsd.JSONType = sd.PrivateTag\n\treturn sd.PrivateTag\n}", "func (target *Target) FilterByTag(name string, value string) {\n\ttarget.Tags = append(target.Tags, Tag{Key: name, Value: value})\n}", "func (h *DBHelper) UserTagged(user *models.User, item *models.Item) {\n\th.ItemTags(item, user, models.Tags{})\n}", "func (o *ShortenBitlinkBodyAllOf) HasTags() bool {\n\tif o != nil && o.Tags != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (m *TagManager) IsTaggedID(name string, nodeID uint) bool {\n\tvar results int64\n\tif name == \"\" {\n\t\treturn true\n\t}\n\tm.DB.Model(&TaggedNode{}).Where(\"tag = ? AND node_id = ?\", name, nodeID).Count(&results)\n\treturn (results > 0)\n}", "func (lg *logger) Tag(k, v string) {\n\n\tlg.buffer.Tags[k] = v\n\n}", "func (o *NewData) HasTags() bool {\n\tif o != nil && o.Tags != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func containsTags(a map[string]string, b []*elb.Tag) bool {\n\tfor k, v := range a {\n\t\tt := elbTag(k, v)\n\t\tif !containsTag(t, b) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func TagsFilter(t map[string]string) Filter {\n\tj := tagsEncoder(t)\n\treturn Param(\"tags\", j)\n}", "func (o *LocalDatabaseProvider) HasTags() bool {\n\tif o != nil && o.Tags != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *FiltersSecurityGroup) HasTagValues() bool {\n\tif o != nil && o.TagValues != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (sp *Space) FilterOutByTags(tags ...string) *Space {\n\treturn sp.Filter(func(s Shape) bool {\n\t\tif s.HasTags(tags...) {\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t})\n}", "func (o *ViewMilestone) HasTagIds() bool {\n\tif o != nil && o.TagIds != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *MonitorSearchResult) HasTags() bool {\n\tif o != nil && o.Tags != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func BoolTag(name interface{}, value bool) Tag {\n\treturn &tag{\n\t\ttagType: TagBool,\n\t\tname: name,\n\t\tvalue: value,\n\t}\n}", "func (sp *Space) FilterByTags(tags ...string) *Space {\n\treturn sp.Filter(func(s Shape) bool {\n\t\tif s.HasTags(tags...) {\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t})\n}", "func (o *GroupReplaceRequest) HasTags() bool {\n\tif o != nil && o.Tags != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}" ]
[ "0.59058535", "0.5747772", "0.5712632", "0.564194", "0.56417316", "0.5597776", "0.5597776", "0.55729264", "0.5532937", "0.5527611", "0.5500002", "0.5486283", "0.5485485", "0.54750425", "0.5470477", "0.545517", "0.542379", "0.54054505", "0.5397518", "0.5378228", "0.537284", "0.53709304", "0.53652346", "0.53649485", "0.5355797", "0.53349584", "0.53194386", "0.5317637", "0.52992296", "0.52914625", "0.5273722", "0.52542704", "0.5244432", "0.5242985", "0.52423155", "0.5239656", "0.5222696", "0.5219155", "0.5202405", "0.5200775", "0.5194695", "0.5189786", "0.5182952", "0.5177625", "0.5176846", "0.51681453", "0.515922", "0.51554614", "0.5155092", "0.51543206", "0.515194", "0.5143938", "0.51423985", "0.51195717", "0.5111388", "0.5100746", "0.50940245", "0.50940245", "0.50925493", "0.5082749", "0.50823784", "0.5078315", "0.5076302", "0.50760734", "0.50682306", "0.50677764", "0.5065435", "0.50647163", "0.5062821", "0.5060194", "0.5051765", "0.50462425", "0.50461274", "0.5044182", "0.5034743", "0.50273556", "0.50267464", "0.5022913", "0.5010214", "0.5010214", "0.5008779", "0.5008779", "0.5004619", "0.499847", "0.49880338", "0.49801797", "0.4978367", "0.49761012", "0.49752286", "0.4974445", "0.49620637", "0.49601862", "0.49601045", "0.49596998", "0.49591142", "0.49527124", "0.49485025", "0.49484828", "0.4948138", "0.4947557" ]
0.5107007
55
writeTime writes the current system time to the timeWidget. Exits when the context expires.
func writeTime(ctx context.Context, t *text.Text, delay time.Duration) { ticker := time.NewTicker(delay) defer ticker.Stop() for { select { case <-ticker.C: currentTime := time.Now() t.Reset() if err := t.Write(fmt.Sprintf("%s\n", currentTime.Format("2006-01-02\n03:04:05 PM"))); err != nil { panic(err) } case <-ctx.Done(): return } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (w *Writer) WriteTime(t *time.Time) {\n\tptr := unsafe.Pointer(t)\n\ttyp := reflect.TypeOf(t)\n\tif writeRef(w, ptr, typ) {\n\t\treturn\n\t}\n\tsetWriterRef(w, ptr, typ)\n\tyear, month, day := t.Date()\n\thour, min, sec := t.Clock()\n\tnsec := t.Nanosecond()\n\tbuf := make([]byte, 9)\n\tif hour == 0 && min == 0 && sec == 0 && nsec == 0 {\n\t\twriteDate(w, buf, year, int(month), day)\n\t} else if year == 1970 && month == 1 && day == 1 {\n\t\twriteTime(w, buf, hour, min, sec, nsec)\n\t} else {\n\t\twriteDate(w, buf, year, int(month), day)\n\t\twriteTime(w, buf, hour, min, sec, nsec)\n\t}\n\tloc := TagSemicolon\n\tif t.Location() == time.UTC {\n\t\tloc = TagUTC\n\t}\n\tw.writeByte(loc)\n}", "func (s *Stub) WriteTime(key string, val string, time string) error {\n\ts.m[key] = &runtimeconfig.Variable{Name: key, Value: val, UpdateTime: time}\n\treturn nil\n}", "func WriteTime(t time.Time, w io.Writer, n *int, err *error) {\n\tif t.IsZero() {\n\t\tWriteInt64(0, w, n, err)\n\t} else {\n\t\tnanosecs := t.UnixNano()\n\t\tmillisecs := nanosecs / 1000000\n\t\tWriteInt64(millisecs*1000000, w, n, err)\n\t}\n}", "func (bw *BufWriter) Time(t time.Time) {\n\tif bw.Error != nil {\n\t\treturn\n\t}\n\tbw.stringBuf, bw.Error = Time(t, bw.stringBuf[:0])\n\tif bw.Error != nil {\n\t\treturn\n\t}\n\t_, bw.Error = bw.writer.Write(bw.stringBuf)\n}", "func SetTime(ct int) {\n\tcurrenttime = ct\n}", "func (c *Context) SetTime(time float64) {\n\tC.glfwSetTime(C.double(time))\n}", "func (c *Context) SetTime(time float64) {\n\tC.glfwSetTime(C.double(time))\n}", "func (val *Time) writeTo(buf *bytes.Buffer) error {\n\tif val == nil {\n\t\t_, err := buf.WriteString(\"null\")\n\t\treturn err\n\t}\n\tsec := int64(*val) / 1000000\n\tusec := int64(*val) % 1000000\n\t_, err := fmt.Fprintf(buf, \"%d.%06d\", sec, usec)\n\treturn err\n}", "func (w *Writer) Time(t time.Time, layout string) {\n\tw.buf = t.AppendFormat(w.buf, layout)\n}", "func (w *FormSerializationWriter) WriteTimeValue(key string, value *time.Time) error {\n\tif key != \"\" && value != nil {\n\t\tw.writePropertyName(key)\n\t}\n\tif value != nil {\n\t\tw.writeStringValue((*value).Format(time.RFC3339))\n\t}\n\tif key != \"\" && value != nil {\n\t\tw.writePropertySeparator()\n\t}\n\treturn nil\n}", "func TimeServer(w http.ResponseWriter, req *http.Request) {\n\t// if user goes to another website after time/...\n\tif req.URL.Path != \"/time/\" {\n\t\terrorHandler(w, req, http.StatusNotFound)\n\t\treturn\n\t}\n\t//html code\n\tfmt.Fprint(w, \"<html><head><style> p{font-size: xx-large}\")\n\tfmt.Fprint(w, \"span.time {color:red}\")\n\tfmt.Fprint(w, \"</style></head><body><p> The time is now \")\n\tfmt.Fprint(w, \"<span class=\\\"time\\\">\")\n\tfmt.Fprint(w, time.Now().Format(\"3:04:04 PM\"))\n\tfmt.Fprint(w, \"</span>.</p></body></html>\")\n}", "func (m *Msg) PrintTime(w io.Writer) (n int, err error) {\n\thour, min, sec := m.Time.Clock()\n\tmicro := m.Time.Nanosecond() / 1000\n\treturn fmt.Fprintf(w, \"%02d:%02d:%02d.%06d\", hour, min, sec, micro)\n}", "func (w *Weather) SetTime(t time.Time) {\n\tstr := t.Format(\"Mon 15:04\")\n\tw.clock.SetText(str)\n}", "func (m *MetricsProvider) CASWriteTime(value time.Duration) {\n}", "func (t *TimeTravelCtx) SetTime(newTime time.Time) {\n\tt.mutex.Lock()\n\tdefer t.mutex.Unlock()\n\tt.ts = newTime\n}", "func (d Display) SetTime(usec int) error {\n\tret, err := C.caca_set_display_time(d.Dp, C.int(usec))\n\n\tif int(ret) == -1 {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *BaseRFC5424Listener) ExitTime(ctx *TimeContext) {}", "func (o *WidgetMarker) SetTime(v string) {\n\to.Time = &v\n}", "func (c *StoppedClock) SetTime(time time.Time) {\n\tc.time = time\n}", "func (c *TCPClient) WriteTimed(\n\tmetric aggregated.Metric,\n\tmetadata metadata.TimedMetadata,\n) error {\n\tpayload := payloadUnion{\n\t\tpayloadType: timedType,\n\t\ttimed: timedPayload{\n\t\t\tmetric: metric,\n\t\t\tmetadata: metadata,\n\t\t},\n\t}\n\n\tc.metrics.writeForwarded.Inc(1)\n\treturn c.write(metric.ID, metric.TimeNanos, payload)\n}", "func (se *SimpleElement) SetTime(value time.Time) {\n\tse.value = formatTime(value)\n}", "func (s Serializer) Time(buf cmpbin.WriteableBytesBuffer, t time.Time) error {\n\tname, off := t.Zone()\n\tif name != \"UTC\" || off != 0 {\n\t\tpanic(fmt.Errorf(\"helper: UTC OR DEATH: %s\", t))\n\t}\n\n\t_, err := cmpbin.WriteInt(buf, TimeToInt(t))\n\treturn err\n}", "func (c *Config) SetTime(k string, t time.Time) {\n\tc.SetString(k, t.Format(time.RFC3339))\n}", "func timeHandlerOneOff(w http.ResponseWriter, r *http.Request) {\n\ttm := time.Now().Format(time.RFC1123)\n\tw.Write([]byte(\"The time is: \" + tm))\n}", "func SaveTime(t int64) (msg string, err error) {\n\t_, err = paramStore.PutParameter(\n\t\t&ssm.PutParameterInput{\n\t\t\tDescription: aws.String(`slack lastest log timestamp`),\n\t\t\tName: aws.String(awsDetails.TimeParameter),\n\t\t\tOverwrite: aws.Bool(true),\n\t\t\tType: aws.String(`String`),\n\t\t\tValue: aws.String(strconv.Itoa(int(t))),\n\t\t},\n\t)\n\tif err != nil {\n\t\tmsg = \"problem saving latest timestamp to SSM\"\n\t}\n\treturn\n}", "func TimeServer(ws *websocket.Conn) {\r\n\tfor {\r\n\t\tif _, err := ws.Write([]byte(time.Now().String())); err != nil {\r\n\t\t\tlog.Println(\"Write: \", err)\r\n\t\t\treturn\r\n\t\t}\r\n\t\ttime.Sleep(1e+9)\r\n\t}\r\n}", "func (p *Pcf8523) SetTime(date time.Time) error {\n\tdate = date.In(time.UTC)\n\n\t// Set the time\n\tw := []byte{\n\t\t0x03,\n\t\tencodeBcd(date.Second()),\n\t\tencodeBcd(date.Minute()),\n\t\tencodeBcd(date.Hour()),\n\t\tencodeBcd(date.Day()),\n\t\tencodeBcd(int(date.Weekday())),\n\t\tencodeBcd(int(date.Month())),\n\t\tencodeBcd(date.Year() - 2000),\n\t}\n\tr := []byte{}\n\tif err := p.Device.Tx(w, r); err != nil {\n\t\treturn err\n\t}\n\n\t// Clear the OS flag\n\treturn nil\n}", "func (manager *Manager) RecordTime(t interface{}) {\n\tmanager.metaWG.Add(1)\n\tmanager.metadata.timings <- t\n}", "func NewTime() Widget {\n\treturn &Time{time: time.Now()}\n}", "func (th *timeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ttm := time.Now().Format(th.format)\n\tw.Write([]byte(\"The time is: \" + tm))\n}", "func Time() string {\n\treturn time.Now().Format(TIME_FMT)\n}", "func (o *ViewProjectActivePages) SetTime(v bool) {\n\to.Time = &v\n}", "func (m *ResponseStatus) SetTime(value *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)() {\n m.time = value\n}", "func (p *PublishedDateTime) SetTime(time *time.Time) {\n\tp.time = time\n}", "func (s *Basememcached_protocolListener) ExitTime(ctx *TimeContext) {}", "func WithTime(ctx context.Context, v time.Time) context.Context {\n\treturn context.WithValue(ctx, keyTime, v)\n}", "func (as *AppStatusHandler) setTime() {\n\tas.Lock()\n\tdefer as.Unlock()\n\ttimeNow := time.Now()\n\t// Uptime is to be deprecated 19/03/2019\n\tas.state.Uptime = timeNow.Unix()\n\tas.state.StartTime = timeNow.Unix()\n\tas.state.StartTimeHuman = timeNow.Format(\"Mon Jan 2 2006 - 15:04:05 -0700 MST\")\n}", "func WriteProcessTime(w http.ResponseWriter) {\n\tif h := w.Header().Get(cdsclient.ResponseAPINanosecondsTimeHeader); h != \"\" {\n\t\tstart, err := strconv.ParseInt(h, 10, 64)\n\t\tif err != nil {\n\t\t\tlog.Error(\"WriteProcessTime> error on ParseInt header ResponseAPINanosecondsTimeHeader: %s\", err)\n\t\t}\n\t\tw.Header().Add(cdsclient.ResponseProcessTimeHeader, fmt.Sprintf(\"%d\", time.Now().UnixNano()-start))\n\t}\n}", "func timeHandler(res http.ResponseWriter, req *http.Request) {\n\tdefer server.LogRequest(req, http.StatusOK)\n\n\t// replace empty string with the username text if logged in.\n\tdata := struct {\n\t\tTime string\n\t\tMilitaryTime string\n\t\tUsername string\n\t}{\n\t\tTime: time.Now().Local().Format(TIME_LAYOUT),\n\t\tMilitaryTime: time.Now().UTC().Format(MILITARY_TIME_LAYOUT),\n\t}\n\n\t// TODO implement random load simulation\n\twait := int(rand.NormFloat64()*float64(config.Deviation) +\n\t\tfloat64(config.AvgResponse))\n\tif wait < 0 {\n\t\twait = 0\n\t}\n\ttime.Sleep(time.Duration(wait) * time.Millisecond)\n\tlog.Infof(\"sleep duration is %d\", wait)\n\n\tif username, err := session.Username(req); err == nil {\n\t\tdata.Username = username\n\t\tcounter.Increment(\"time-user\")\n\t} else {\n\t\tcounter.Increment(\"time-anon\")\n\t}\n\n\trenderBaseTemplate(res, \"time.html\", data)\n}", "func Time(time time.Time, formats ...string) got.HTML {\n\tlayout := \"Jan 2, 2006 15:04\"\n\tif len(formats) > 0 {\n\t\tlayout = formats[0]\n\t}\n\tvalue := fmt.Sprintf(time.Format(layout))\n\treturn got.HTML(Escape(value))\n}", "func Time(t time.Time) Val {\n\treturn Val{t: bsontype.DateTime}.writei64(t.Unix()*1e3 + int64(t.Nanosecond()/1e6))\n}", "func TimeHandler(res http.ResponseWriter, req *http.Request) {\n\tvars := mux.Vars(req)\n\tformat := vars[\"format\"]\n\tlog.Printf(\"Time format is %s\\n\", format)\n\n\ttimeValue := time.Now().Format(format)\n\n\ttimeReponse := TimeResponse{Value: timeValue, ContainerId: GetContainerId(), InstanceId: GetInstanceId()}\n\tif err := json.NewEncoder(res).Encode(timeReponse); err != nil {\n\t\tlog.Panic(err)\n\t}\n}", "func getTime(res http.ResponseWriter, req *http.Request) {\n\tnow := time.Now().Format(\"3:04:05 PM\")\n\tres.Header().Set(\"Content-Type\", \"text/html\")\n\tfmt.Fprintf(\n\t\tres,\n\t\t`<doctype html>\n <html>\n\t\t<head>\n\t\t<style>\n\t\tp {font-size: xx-large}\n\t\tspan.time {color: red}\n\t\t</style>\n\t\t</head>\n\t\t<body>\n\t\t<p>The time is now <span class=\"time\">`+now+`</span>.</p>\n\t\t</body>\n\t\t</html>`,\n\t)\n}", "func timeHandlerClosure(format string) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\ttm := time.Now().Format(format)\n\t\tw.Write([]byte(\"The time is \" + tm + \" | CLOSURE!\"))\n\t}\n\treturn http.HandlerFunc(fn)\n}", "func (o ServicePerimetersServicePerimeterOutput) UpdateTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ServicePerimetersServicePerimeter) *string { return v.UpdateTime }).(pulumi.StringPtrOutput)\n}", "func getTime(res http.ResponseWriter, req *http.Request) {\n\tnow := time.Now().Format(\"3:04:05 PM\")\n\tdisplayName := \"\"\n\tname, correctlyLogIn := getNameAndCookie(res, req)\n\tif correctlyLogIn {\n\t\tdisplayName = `, ` + name\n\t}\n\n\tres.Header().Set(\"Content-Type\", \"text/html\")\n\tfmt.Fprintf(\n\t\tres,\n\t\t`<doctype html>\n <html>\n\t\t<head>\n\t\t<style>\n\t\tp {font-size: xx-large}\n\t\tspan.time {color: red}\n\t\t</style>\n\t\t</head>\n\t\t<body>\n\t\t<p>The time is now \n\t\t<span class=\"time\">`+now+`</span>`+displayName+`.</p>\n\t\t</body>\n\t\t</html>`,\n\t)\n}", "func (e Fields) SetTime(unix int64) Fields {\n\te[FieldTime] = unix\n\treturn e\n}", "func (o ConnectorOutput) UpdateTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Connector) pulumi.StringOutput { return v.UpdateTime }).(pulumi.StringOutput)\n}", "func (dt *dateTime) updateTime() *dateTime {\n\t//Doing something on the\n\tcurrTime := now().UTC().String()\n\tdt.currTime = currTime\n\treturn dt\n}", "func Time(attrs []htmlgo.Attribute, children ...HTML) HTML {\n\treturn &htmlgo.Tree{Tag: \"time\", Attributes: attrs, Children: children}\n}", "func timeDisplay(t time.Time) string {\n\tif t.IsZero() {\n\t\treturn \"\"\n\t}\n\treturn t.Format(\"3:04pm\")\n}", "func timeFmt(w io.Writer, x interface{}, format string) {\n\t// note: os.Dir.Mtime_ns is in uint64 in ns!\n\ttemplate.HTMLEscape(w, strings.Bytes(time.SecondsToLocalTime(int64(x.(uint64)/1e9)).String()))\n}", "func (o AppGatewayOutput) UpdateTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AppGateway) pulumi.StringOutput { return v.UpdateTime }).(pulumi.StringOutput)\n}", "func (o *GetInstrumentsInstrumentOrderBookParams) SetTime(time *string) {\n\to.Time = time\n}", "func (t Time) Draw() string { return t.time.Format(\"Mon 2 Jan, 15:04\") }", "func (c Context) Time(key string, t time.Time) Context {\n\tc.l.context = appendTime(c.l.context, key, t)\n\treturn c\n}", "func (m *MetricsProvider) WriteAnchorTime(value time.Duration) {\n}", "func (m *MailboxSettings) SetTimeFormat(value *string)() {\n err := m.GetBackingStore().Set(\"timeFormat\", value)\n if err != nil {\n panic(err)\n }\n}", "func tickTimeHandler(duration string) http.HandlerFunc {\n\treturn func(respWriter http.ResponseWriter, request *http.Request) {\n\t\trespWriter.Write([]byte(duration))\n\t}\n}", "func (fs *FakeSession) SetTime(oid string, ticks int) *FakeSession {\n\treturn fs.Set(oid, gosnmp.TimeTicks, ticks)\n}", "func (l *Locale) FormatTime(datetime dates.DateTime) string {\n\treturn datetime.Format(l.TimeFormatGo)\n}", "func (m *ccMetric) SetTime(t time.Time) {\n\tm.tm = t\n}", "func Time(name string, value time.Duration) {\n\tmn := getWithNamespace(name)\n\tt := metrics.GetOrRegisterTimer(mn, nil)\n\tt.Update(value)\n\tdebug(\"time \" + name + \" \" + value.String())\n}", "func Time() Command {\n\treturn NewCommand(\"time\", func(args ...string) ([]byte, error) {\n\t\tt := time.Now().Format(time.RFC1123)\n\t\treturn []byte(\"Server time is: \" + t), nil\n\t})\n}", "func (w *FormSerializationWriter) WriteTimeOnlyValue(key string, value *absser.TimeOnly) error {\n\tif key != \"\" && value != nil {\n\t\tw.writePropertyName(key)\n\t}\n\tif value != nil {\n\t\tw.writeStringValue((*value).String())\n\t}\n\tif key != \"\" && value != nil {\n\t\tw.writePropertySeparator()\n\t}\n\treturn nil\n}", "func (llp *LogLineParsed) SetTime(newTime time.Time) {\n\thour, min, sec := newTime.Clock()\n\tllp.StampSeconds = hour*60*60 + min*60 + sec\n}", "func STime(t time.Time) string {\n\t_, month, day := t.Date()\n\thour, minute, second := t.Clock()\n\treturn fmt.Sprintf(\"%02d%02d %02d:%02d:%02d\", int(month), day, hour, minute, second)\n}", "func (m *PrintConnector) SetRegisteredDateTime(value *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)() {\n err := m.GetBackingStore().Set(\"registeredDateTime\", value)\n if err != nil {\n panic(err)\n }\n}", "func setSystemTime(t time.Time) error {\n\t// convert time types\n\tsystime := windows.Systemtime{\n\t\tYear: uint16(t.Year()),\n\t\tMonth: uint16(t.Month()),\n\t\tDay: uint16(t.Day()),\n\t\tHour: uint16(t.Hour()),\n\t\tMinute: uint16(t.Minute()),\n\t\tSecond: uint16(t.Second()),\n\t\tMilliseconds: uint16(t.Nanosecond() / 1000000),\n\t}\n\n\t// make call to windows api\n\tr1, _, err := procSetSystemTime.Call(uintptr(unsafe.Pointer(&systime)))\n\tif r1 == 0 {\n\t\tlog.Printf(\"%+v\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (o EnvironmentOutput) UpdateTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Environment) pulumi.StringOutput { return v.UpdateTime }).(pulumi.StringOutput)\n}", "func WithBlockTime(ctx Context, t time.Time) Context {\n\treturn context.WithValue(ctx, contextKeyTime, t.UTC())\n}", "func GetCurrentSysTime(instructionData reflect.Value, finished chan bool) int {\n\tfmt.Println(\"FIBER INFO: Getting sys time...\")\n\n\tvariable.SetVariable(instructionData.FieldByName(\"Output\").Interface().(string), time.Now())\n\tfinished <- true\n\treturn -1\n}", "func SetSystime(t int64) {\n\tif t == 0 {\n\t\ttransferTime = 0\n\t\tlocalTime = 0\n\t\tsysTimeDiff = 0\n\t\treturn\n\t}\n\ttransferTime = t\n\tlocalTime = time.Now().Unix()\n\tsysTimeDiff = transferTime - localTime\n\tif sysTimeDiff < 0 {\n\t\tsysTimeDiff = 0 - sysTimeDiff\n\t}\n}", "func (params *JourneyParams)SetTime(t time.Time){\n\tparams.Time=GetTimeFormat(t)\n}", "func (t *timer) UpdateTime() {\n\tt.afterTime = time.Now().UnixNano()\n}", "func SetTime(t testingT, tm time.Time) bool {\n\tt.Helper()\n\tname, ok := funcName(1)\n\tif !ok {\n\t\treturn false\n\t}\n\ttimeMap.Store(name, func() time.Time {\n\t\treturn tm\n\t})\n\n\tt.Cleanup(func() {\n\t\ttimeMap.Delete(name)\n\t})\n\n\treturn true\n}", "func (m *MetricsProvider) WriteAnchorSignLocalStoreTime(value time.Duration) {\n}", "func (o *NotebookLogStreamCellAttributes) SetTime(v NotebookCellTime) {\n\to.Time.Set(&v)\n}", "func (omad *OutputMessageAccountabilityData) OutputTimeField() string {\n\treturn omad.alphaField(omad.OutputTime, 4)\n}", "func (d Display) GetTime() int {\n\treturn int(C.caca_get_display_time(d.Dp))\n}", "func (o KeyOutput) UpdateTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Key) pulumi.StringOutput { return v.UpdateTime }).(pulumi.StringOutput)\n}", "func (o AuthorizationPolicyOutput) UpdateTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AuthorizationPolicy) pulumi.StringOutput { return v.UpdateTime }).(pulumi.StringOutput)\n}", "func (c *Context) GetTime() float64 {\n\treturn float64(C.glfwGetTime())\n}", "func (c *Context) GetTime() float64 {\n\treturn float64(C.glfwGetTime())\n}", "func (a *AGI) SayTime(when time.Time, escapeDigits string) (digit string, err error) {\n\treturn a.Command(\"SAY TIME\", toEpoch(when), escapeDigits).Val()\n}", "func (tso TimeWebsmsShortOne) Time() time.Time { return time.Time(tso) }", "func Time(message string) string {\n\treturn Encode(TIME, message)\n}", "func (b *backend) Time(ctx context.Context) (time.Time, error) {\n\tresp, err := pb.NewEntroQClient(b.conn).Time(ctx, new(pb.TimeRequest))\n\tif err != nil {\n\t\treturn time.Time{}, fmt.Errorf(\"grpc time: %w\", unpackGRPCError(err))\n\t}\n\treturn fromMS(resp.TimeMs).UTC(), nil\n}", "func (m *MetricsProvider) WriteAnchorSignLocalWatchTime(value time.Duration) {\n}", "func (rb *ShardsRecordBuilder) GetTime(gettime string) *ShardsRecordBuilder {\n\trb.v.GetTime = &gettime\n\treturn rb\n}", "func (m *BillMutation) SetTime(i int) {\n\tm.time = &i\n\tm.addtime = nil\n}", "func (o OrganizationMuteConfigOutput) UpdateTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *OrganizationMuteConfig) pulumi.StringOutput { return v.UpdateTime }).(pulumi.StringOutput)\n}", "func (m *StockMutation) SetTime(t time.Time) {\n\tm._Time = &t\n}", "func (o AiFeatureStoreEntityTypeFeatureOutput) UpdateTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AiFeatureStoreEntityTypeFeature) pulumi.StringOutput { return v.UpdateTime }).(pulumi.StringOutput)\n}", "func (o *WidgetMarker) GetTime() string {\n\tif o == nil || o.Time == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Time\n}", "func (o InstanceOutput) UpdateTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.UpdateTime }).(pulumi.StringOutput)\n}", "func (o InstanceOutput) UpdateTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.UpdateTime }).(pulumi.StringOutput)\n}", "func Time(props *TimeProps, children ...Element) *TimeElem {\n\trProps := &_TimeProps{\n\t\tBasicHTMLElement: newBasicHTMLElement(),\n\t}\n\n\tif props != nil {\n\t\tprops.assign(rProps)\n\t}\n\n\treturn &TimeElem{\n\t\tElement: createElement(\"time\", rProps, children...),\n\t}\n}", "func (o TrackerOutput) UpdateTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Tracker) pulumi.StringOutput { return v.UpdateTime }).(pulumi.StringOutput)\n}", "func TimeTrack(start time.Time, name string, writer io.Writer) {\n\telapsed := time.Since(start)\n\tmessage := fmt.Sprintf(\"\\n%s took %s\", name, elapsed)\n\tif writer == nil {\n\t\tfmt.Println(message)\n\t} else {\n\t\twriter.Write([]byte(message))\n\t}\n}" ]
[ "0.69650096", "0.675", "0.65183145", "0.6049034", "0.60231537", "0.5930819", "0.5930819", "0.5882703", "0.57653916", "0.56781745", "0.56588495", "0.5638151", "0.560225", "0.55528915", "0.54865587", "0.5434267", "0.5385264", "0.5384395", "0.53727233", "0.53716165", "0.5338702", "0.5321044", "0.5313441", "0.5308559", "0.53062683", "0.5277361", "0.52358663", "0.52170885", "0.52008706", "0.5194915", "0.51839274", "0.5173072", "0.5166301", "0.5163787", "0.51529473", "0.5149656", "0.51481575", "0.5132302", "0.51316977", "0.51205546", "0.5115487", "0.5114848", "0.5102971", "0.5100928", "0.50929767", "0.5075003", "0.5073444", "0.5066272", "0.5058763", "0.5056816", "0.50561535", "0.5047878", "0.5038024", "0.50364405", "0.50331956", "0.5027112", "0.50139403", "0.50066787", "0.5005534", "0.50024945", "0.500229", "0.50019455", "0.4996041", "0.499407", "0.49720123", "0.49451667", "0.49336255", "0.49191165", "0.49178302", "0.49146393", "0.4910236", "0.48981255", "0.48975706", "0.48945794", "0.48862267", "0.48420522", "0.48326126", "0.48323298", "0.48301405", "0.482846", "0.48151746", "0.480147", "0.47978267", "0.47978267", "0.47972175", "0.4790119", "0.47852758", "0.4782707", "0.47748446", "0.4772087", "0.47701997", "0.47668687", "0.47623703", "0.475989", "0.4755097", "0.47535542", "0.47535542", "0.47531837", "0.47439128", "0.47433686" ]
0.66403663
2
writeHealth writes the status to the healthWidget. Exits when the context expires.
func writeHealth(ctx context.Context, t *text.Text, delay time.Duration, connectionSignal chan string) { reconnect := false health := gjson.Get(getFromRPC("health"), "result") t.Reset() if health.Exists() { t.Write("🟢 good") } else { t.Write("🔴 no connection") } ticker := time.NewTicker(delay) defer ticker.Stop() for { select { case <-ticker.C: health := gjson.Get(getFromRPC("health"), "result") if health.Exists() { t.Write("🟢 good") if reconnect == true { connectionSignal <- "reconnect" connectionSignal <- "reconnect" connectionSignal <- "reconnect" reconnect = false } } else { t.Write("🔴 no connection") if reconnect == false { connectionSignal <- "no_connection" connectionSignal <- "no_connection" connectionSignal <- "no_connection" reconnect = true } } case <-ctx.Done(): return } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func healthHandler(w http.ResponseWriter, r *http.Request) {\n\tbeeline.AddField(r.Context(), \"alive\", true)\n\tw.Write([]byte(`{\"alive\": \"yes\"}`))\n}", "func serveHealthStatus(w http.ResponseWriter, req *http.Request) {\n\tfmt.Fprintf(w, \"OK\")\n}", "func (s *server) serveHealth(w http.ResponseWriter, r *http.Request) {\n\tif s.isShuttingDown {\n\t\thttp.Error(w, \"Shutting Down\", 503)\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n}", "func healthHandler(response http.ResponseWriter, req *http.Request, rcvr *receiver.Receiver) {\n\tdefer req.Body.Close()\n\tresponse.Header().Set(\"Content-Type\", \"application/json\")\n\n\trcvr.StateLock.Lock()\n\tdefer rcvr.StateLock.Unlock()\n\n\tvar lastChanged time.Time\n\tif rcvr.CurrentState != nil {\n\t\tlastChanged = rcvr.CurrentState.LastChanged\n\t}\n\n\tmessage, _ := json.Marshal(ApiStatus{\n\t\tMessage: \"Healthy!\",\n\t\tLastChanged: lastChanged,\n\t\tServiceChanged: rcvr.LastSvcChanged,\n\t})\n\n\tresponse.Write(message)\n}", "func healthHandler(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(\"Alive!\"))\n}", "func healthHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Passed\")\n}", "func Health(w http.ResponseWriter, r *http.Request) {\n\twriteJSON(w, http.StatusOK, healthResponse{\"alive\"})\n}", "func HealthHandler(w http.ResponseWriter, _ *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(healthMsg) //nolint:errcheck\n}", "func (h *handler) health(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"OK\")\n}", "func (r *oauthProxy) healthHandler(w http.ResponseWriter, req *http.Request) {\n\tw.Header().Set(\"Content-Type\", jsonMime)\n\tw.Header().Set(versionHeader, version.GetVersion())\n\tw.WriteHeader(http.StatusOK)\n\t_, _ = w.Write([]byte(`{\"status\":\"OK\"}`))\n}", "func healthHandler(w http.ResponseWriter, r *http.Request) {\n\tlogrus.Info(\"Check Health Status\")\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tresp := make(map[string]string)\n\tresp[\"status\"] = \"200 OK\"\n\tjsonResp, err := json.Marshal(resp)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error happened in JSON marshal. Err: %s\", err)\n\t}\n\n\t//return http code 200\n\tw.WriteHeader(http.StatusOK)\n\t// output\n\tw.Write(jsonResp)\n}", "func (h HealthHandler) Health(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\t_, _ = w.Write([]byte(\"ok\"))\n}", "func (c *Container) updateHealthStatus(status string) error {\n\thealthCheck, err := c.getHealthCheckLog()\n\tif err != nil {\n\t\treturn err\n\t}\n\thealthCheck.Status = status\n\tnewResults, err := json.Marshal(healthCheck)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to marshall healthchecks for writing status: %w\", err)\n\t}\n\treturn os.WriteFile(c.healthCheckLogPath(), newResults, 0700)\n}", "func HandleHealth(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Write([]byte(`{\"status\": \"ok\"}`))\n}", "func (h *Handler) Health(w http.ResponseWriter, r *http.Request) {\n\twriteResponse(r, w, http.StatusOK, &SimpleResponse{\n\t\tTraceID: tracing.FromContext(r.Context()),\n\t\tMessage: \"OK\",\n\t})\n}", "func health(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {\n\tw.WriteHeader(http.StatusOK)\n}", "func (api *API) health(w http.ResponseWriter, req *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(\"OK\"))\n}", "func (c *Container) updateHealthStatus(status string) error {\n\thealthCheck, err := c.GetHealthCheckLog()\n\tif err != nil {\n\t\treturn err\n\t}\n\thealthCheck.Status = status\n\tnewResults, err := json.Marshal(healthCheck)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"unable to marshall healthchecks for writing status\")\n\t}\n\treturn ioutil.WriteFile(c.healthCheckLogPath(), newResults, 0700)\n}", "func Healthy(writer http.ResponseWriter, request *http.Request) {\n\twriter.Write([]byte(\"Healthy\"))\n}", "func diskHealthWriter(ctx context.Context, w io.Writer) io.Writer {\n\t// Check if context has a disk health check.\n\ttracker, ok := ctx.Value(healthDiskCtxKey{}).(*healthDiskCtxValue)\n\tif !ok {\n\t\t// No need to wrap\n\t\treturn w\n\t}\n\treturn &diskHealthWrapper{w: w, tracker: tracker}\n}", "func HealthHandler(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\tio.WriteString(w, `OK`)\n}", "func HealthHandler(res http.ResponseWriter, req *http.Request) {\n\thc := Healthcheck{Status: \"OK\"}\n\tif err := json.NewEncoder(res).Encode(hc); err != nil {\n\t\tlog.Panic(err)\n\t}\n}", "func HealthHandler(res http.ResponseWriter, req *http.Request) {\n\thc := Healthcheck{Status: \"OK\"}\n\tif err := json.NewEncoder(res).Encode(hc); err != nil {\n\t\tlog.Panic(err)\n\t}\n}", "func (h healthHandler) ServeHTTP(writer http.ResponseWriter, _ *http.Request) {\n\tvar status int\n\tvar body []byte\n\tif h.status == Up {\n\t\tstatus = http.StatusOK\n\t} else {\n\t\tstatus = http.StatusInternalServerError\n\t}\n\tif h.useJSON {\n\t\twriter.Header().Set(\"Content-Type\", \"application/json\")\n\t\tbody = []byte(`{\"status\":\"` + h.status + `\"}`)\n\t} else {\n\t\tbody = []byte(h.status)\n\t}\n\twriter.WriteHeader(status)\n\t_, _ = writer.Write(body)\n}", "func (s *server) Health(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tw.WriteHeader(http.StatusOK)\n}", "func (s *server) Health(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tw.WriteHeader(http.StatusOK)\n}", "func HealthHandler(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\tfmt.Fprint(w, http.StatusText(http.StatusOK))\n}", "func (c *Check) Health(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\tctx, span := trace.StartSpan(ctx, \"handlers.Check.Health\")\n\tdefer span.End()\n\n\tvar health struct {\n\t\tStatus string `json:\"status\"`\n\t}\n\n\t// Check if the database is ready.\n\tif err := database.StatusCheck(ctx, c.db); err != nil {\n\n\t\t// If the database is not ready we will tell the client and use a 500\n\t\t// status. Do not respond by just returning an error because further up in\n\t\t// the call stack will interpret that as an unhandled error.\n\t\thealth.Status = \"db not ready\"\n\t\treturn web.Respond(ctx, w, health, http.StatusInternalServerError)\n\t}\n\n\thealth.Status = \"ok\"\n\treturn web.Respond(ctx, w, health, http.StatusOK)\n}", "func healthCheckHandler(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tio.WriteString(w, `{\"alive\": true}`)\n}", "func healthFunc(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\terr := r.Write(bytes.NewBufferString(\"OK\"))\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to write health response; %s\", err)\n\t}\n}", "func (c *controller) health(w http.ResponseWriter, r *http.Request) {\n\tlogger.Trace(\"health check\")\n\tw.WriteHeader(http.StatusNoContent)\n}", "func HealthCheckHandler(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\t_, err := io.WriteString(w, `{\"alive\": true}`)\n\tif err != nil {\n\t\t// fmt.Errorf(\"Unable to write to reponse with error: %w\", err)\n\t\tlog.Fatal(err)\n\t}\n}", "func HealthHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tw.WriteHeader(http.StatusOK)\n\treturn\n}", "func HealthHandler(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\treturn\n}", "func (s *Status) writeStatus() error {\n\tb, err := json.Marshal(s)\n\tif err != nil {\n\t\tlogrus.Errorf(\"Failed to marshal readiness: %s\", err)\n\t\treturn err\n\t}\n\n\t// Make sure the directory exists.\n\tif err := os.MkdirAll(filepath.Dir(s.statusFile), os.ModePerm); err != nil {\n\t\tlogrus.Errorf(\"Failed to prepare directory: %s\", err)\n\t\treturn err\n\t}\n\n\t// Write the file.\n\terr = os.WriteFile(s.statusFile, b, 0644)\n\tif err != nil {\n\t\tlogrus.Errorf(\"Failed to write readiness file: %s\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func HealthzHandler(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(GetHealthStatus())\n}", "func (v *View) health(c echo.Context) error {\n\tif err := v.core.DB.Ping(); err != nil {\n\t\tc.Logger().Error(err)\n\t\treturn c.String(http.StatusInternalServerError, \"unhealthy\")\n\t}\n\treturn c.String(http.StatusOK, \"healthy\")\n}", "func HealthzHandler(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(HealthzStatus())\n}", "func health(w http.ResponseWriter, _ *http.Request) {\n\tif !Storage.Healthy() {\n\t\tmsg := \"database is not healthy\"\n\t\thttp.Error(w, msg, http.StatusServiceUnavailable)\n\t}\n}", "func (m *DeviceHealth) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteTimeValue(\"lastConnectionTime\", m.GetLastConnectionTime())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func HealthCheckStatusHandler(w http.ResponseWriter, r *http.Request) {\n\tresponse := HealthCheckStatusResponse{\"OK\"}\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n\tif err := json.NewEncoder(w).Encode(response); err != nil {\n\t\tpanic(err)\n\t}\n}", "func GetHealth(w http.ResponseWriter, r *http.Request) {\n\tjson.NewEncoder(w).Encode(health)\n}", "func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\n\thealth := h.CompositeChecker.Check()\n\n\tif health.IsDown() {\n\t\tw.WriteHeader(http.StatusServiceUnavailable)\n\t}\n\n\tjson.NewEncoder(w).Encode(health)\n}", "func HealthHandler(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"Health called\")\n\tlog.Println(\"Request:\", r)\n\n\tw.WriteHeader(http.StatusOK)\n\n}", "func (o *StoragePhysicalDiskExtension) SetHealth(v string) {\n\to.Health = &v\n}", "func (h *allocHealthWatcherHook) watchHealth(ctx context.Context, deadline time.Time, tracker *allochealth.Tracker, done chan<- struct{}) {\n\tdefer close(done)\n\n\t// Default to unhealthy for the deadline reached case\n\thealthy := false\n\n\tselect {\n\tcase <-ctx.Done():\n\t\t// Graceful shutdown\n\t\treturn\n\n\tcase <-tracker.AllocStoppedCh():\n\t\t// Allocation has stopped so no need to set health\n\t\treturn\n\n\tcase <-time.After(time.Until(deadline)):\n\t\t// Time is up! Fallthrough to set unhealthy.\n\t\th.logger.Trace(\"deadline reached; setting unhealthy\", \"deadline\", deadline)\n\n\tcase healthy = <-tracker.HealthyCh():\n\t\t// Health received. Fallthrough to set it.\n\t}\n\n\th.logger.Trace(\"health set\", \"healthy\", healthy)\n\n\t// If this is an unhealthy deployment emit events for tasks\n\tvar taskEvents map[string]*structs.TaskEvent\n\tif !healthy && h.isDeploy {\n\t\ttaskEvents = tracker.TaskEvents()\n\t}\n\n\th.healthSetter.SetHealth(healthy, h.isDeploy, taskEvents)\n}", "func (h Handler) Status(w http.ResponseWriter, r *http.Request) {\n\tresponses := h.healthchecker.Status()\n\tfor _, r := range responses {\n\t\tif r.Error != nil {\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n}", "func (dc *DockerEnvContainer) SetHealth(isDeed bool) {\n\tif isDeed {\n\t\tdc.isAlive = false\n\t\treturn\n\t}\n\tdc.isAlive = true\n}", "func Health(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tio.WriteString(w, \"ok\")\n}", "func newHealthHandler(s *server) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != \"GET\" {\n\t\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\t\treturn\n\t\t}\n\n\t\tctx := context.TODO()\n\t\tif r.URL.Path == \"/local\" || r.URL.Path == \"/local/\" {\n\t\t\thandleLocalStatus(ctx, s, w, r)\n\t\t\treturn\n\t\t}\n\n\t\tif r.URL.Path == \"/history\" || r.URL.Path == \"/history/\" {\n\t\t\thandleHistory(ctx, s, w, r)\n\t\t\treturn\n\t\t}\n\n\t\tstatus, err := s.Status(ctx, nil)\n\t\tif err != nil {\n\t\t\troundtrip.ReplyJSON(w, http.StatusServiceUnavailable, map[string]string{\"error\": err.Error()})\n\t\t\treturn\n\t\t}\n\n\t\thttpStatus := http.StatusOK\n\t\tif isDegraded(*status.GetStatus()) {\n\t\t\thttpStatus = http.StatusServiceUnavailable\n\t\t}\n\n\t\troundtrip.ReplyJSON(w, httpStatus, status.GetStatus())\n\t}\n}", "func healthcheck(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n}", "func (h *Handler) Healthz(w http.ResponseWriter, r *http.Request) {\n\tlog := logr.FromContextOrDiscard(r.Context()).WithValues(\"handler\", \"status\")\n\n\tw.Header().Add(\"Content-Type\", \"text/plain\")\n\t_, err := w.Write([]byte(\"OK\"))\n\tif err != nil {\n\t\tlog.Error(err, \"error writing response body\")\n\t}\n}", "func health() func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\treturn func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tjson.NewEncoder(w).Encode(\"Why, hello!\")\n\t}\n}", "func healthCheckHandler(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n}", "func healthcheckok(writer http.ResponseWriter, request *http.Request) {\n\twriter.WriteHeader(200)\n}", "func (h *Health) Write(metrics []telegraf.Metric) error {\n\thealthy := true\n\tfor _, checker := range h.checkers {\n\t\tsuccess := checker.Check(metrics)\n\t\tif !success {\n\t\t\thealthy = false\n\t\t}\n\t}\n\n\th.setHealthy(healthy)\n\treturn nil\n}", "func health(c echo.Context) error {\n\tvar errResp ErrorResponseData\n\terr := storage.Health()\n\tif err != nil {\n\t\terrResp.Data.Code = \"database_connection_error\"\n\t\terrResp.Data.Description = err.Error()\n\t\terrResp.Data.Status = strconv.Itoa(http.StatusInternalServerError)\n\t\treturn c.JSON(http.StatusInternalServerError, errResp)\n\t}\n\treturn c.String(http.StatusOK, \"Healthy\")\n}", "func (h *Handler) HealthHandler(w http.ResponseWriter, r *http.Request) {\n\tif err := h.DB.Ping(); err != nil {\n\t\tlog.Printf(\"health check failed: %s\\n\", err)\n\t\twriteHTTPResponse(w, http.StatusInternalServerError, map[string]string{\"message\": \"I'm unhealthy\"})\n\t} else {\n\t\twriteHTTPResponse(w, http.StatusOK, map[string]string{\"message\": \"I'm healthy\"})\n\t}\n}", "func HealthCheckHandler(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tfmt.Fprint(w, `{\"alive\": true}`)\n}", "func (check *HealthCheck) ServeHealth(brokerUpdates <-chan Update, clusterUpdates <-chan Update, stop <-chan struct{}) {\n\tport := check.config.statusServerPort\n\n\tstatusServer := func(name, path, errorStatus string, updates <-chan Update) {\n\t\trequests := make(chan chan Update)\n\n\t\t// goroutine that encapsulates the current status\n\t\tgo func() {\n\t\t\tstatus := Update{errorStatus, simpleStatus(errorStatus)}\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase update := <-updates:\n\n\t\t\t\t\tif !bytes.Equal(status.Data, update.Data) {\n\t\t\t\t\t\tlog.WithField(\"status\", string(update.Data)).Info(name, \" now reported as \", update.Status)\n\t\t\t\t\t\tstatus = update\n\t\t\t\t\t}\n\n\t\t\t\tcase request := <-requests:\n\t\t\t\t\trequest <- status\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\thttp.HandleFunc(path, func(writer http.ResponseWriter, request *http.Request) {\n\t\t\tresponseChannel := make(chan Update)\n\t\t\trequests <- responseChannel\n\t\t\tcurrentStatus := <-responseChannel\n\t\t\tif currentStatus.Status == errorStatus {\n\t\t\t\thttp.Error(writer, string(currentStatus.Data), 500)\n\t\t\t} else {\n\t\t\t\twriter.Write(currentStatus.Data)\n\t\t\t\tio.WriteString(writer, \"\\n\")\n\t\t\t}\n\t\t})\n\t}\n\n\thttp.DefaultServeMux = http.NewServeMux()\n\tstatusServer(\"cluster\", \"/cluster\", red, clusterUpdates)\n\tstatusServer(\"broker\", \"/\", unhealthy, brokerUpdates)\n\n\tlistener, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", port))\n\tif err != nil {\n\t\tlog.Fatal(\"Unable to listen to port \", port, \": \", err)\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-stop:\n\t\t\t\tlistener.Close()\n\t\t\t}\n\t\t}\n\t}()\n\thttp.Serve(listener, nil)\n\treturn\n}", "func (c *Chargeback) healthinessHandler(w http.ResponseWriter, r *http.Request) {\n\tlogger := newRequestLogger(c.logger, r, c.rand)\n\tif !c.testWriteToPrestoSingleFlight(logger) {\n\t\twriteResponseAsJSON(logger, w, http.StatusInternalServerError,\n\t\t\tstatusResponse{\n\t\t\t\tStatus: \"not healthy\",\n\t\t\t\tDetails: \"cannot write to PrestoDB\",\n\t\t\t})\n\t\treturn\n\t}\n\twriteResponseAsJSON(logger, w, http.StatusOK, statusResponse{Status: \"ok\"})\n}", "func Health(ctx *gin.Context) {\n\tctx.JSON(http.StatusOK, gin.H{\n\t\t\"status\": 200,\n\t})\n}", "func health(c echo.Context) error {\n\th := &Health{\"Fluffy Radio Api\", \"1.0.0\", \"Just Keep Fluffing!\"}\n\treturn c.JSON(http.StatusOK, h)\n}", "func (c *HealthController) Health(ctx *app.HealthHealthContext) error {\n\t// HealthController_Health: start_implement\n\n\tfmt.Printf(\"DC: [%s]\\n\", ctx.Dc)\n\tfmt.Printf(\"Host Group: [%s]\\n\", ctx.Hgroup)\n\tfmt.Printf(\"Host Name: [%s]\\n\", ctx.Hostname)\n\n\tfor index, element := range c.zapi_list {\n\t\tfmt.Printf(\"zapi_alias: [%s]\\n\", index)\n\t\tfmt.Printf(\"zapi_url: [%s]\\n\", element.zapi_url)\n\t\tfmt.Printf(\"zapi_username: [%s]\\n\", element.zapi_username)\n\t\tfmt.Printf(\"zapi_password: [%s]\\n\", element.zapi_password)\n\t\tfmt.Printf(\"zapi_version: [%s]\\n\\n\", element.zapi_version)\n\t}\n\n\tresult, err := GetDCStatus(c.zapi_list[ctx.Dc])\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Erro communicating with ZAPI: %v\\n\", err)\n\t}\n\tretval, err := json.Marshal(result)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to UnMarshall JSON object\\n\", err)\n\t}\n\n\t// HealthController_Health: end_implement\n\treturn ctx.OK(retval)\n}", "func HealthCheck(w http.ResponseWriter, r *http.Request) {\n\t// Setando um header http de resposta\n\tw.Header().Set(\"content-type\", \"application/json\")\n\n\t// Gerando um objeto customizado à partir de um map, e o convertendo em json\n\tresponse, _ := json.Marshal(map[string]interface{}{\n\t\t\"status\": \"up\",\n\t})\n\n\t// Write escreve o conteúdo do slice de bytes no corpo da resposta\n\tw.Write(response)\n\t// WriteHeader seta o status code da resposta. É importante frisar que ele só pode ser chamado\n\t// uma única vez no contexto da resposta. Chamadas subsequentes são ignoradas, portanto convém\n\t// chamar essa função quando você estiver prestes a retornar do handler\n\tw.WriteHeader(http.StatusOK)\n\treturn\n}", "func HandlerHealthCheck(writer http.ResponseWriter, request *http.Request) {\n\twriter.WriteHeader(http.StatusOK)\n\tlog.Println(\"............Healthcheck success.............\")\n\treturn\n}", "func healthHandler(site site.API) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tif site == nil || !site.Healthy() {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tw.WriteHeader(http.StatusOK)\n\t\tfmt.Fprintln(w, \"OK\")\n\t}\n}", "func (hs *HealthStatusInfo) UpdateHealthInfo(details bool, registeredESS uint32, storedObjects uint32) {\n\ths.lock()\n\tdefer hs.unLock()\n\n\tHealthUsageInfo.RegisteredESS = registeredESS\n\tHealthUsageInfo.StoredObjects = storedObjects\n\n\tDBHealth.DBStatus = Green\n\ttimeSinceLastError := uint64(0)\n\tif DBHealth.DBReadFailures != 0 || DBHealth.DBWriteFailures != 0 {\n\t\ttimeSinceLastError = uint64(time.Since(DBHealth.lastReadWriteErrorTime).Seconds())\n\t\tDBHealth.TimeSinceLastReadWriteError = timeSinceLastError\n\t}\n\tif DBHealth.DisconnectedFromDB {\n\t\tDBHealth.DBStatus = Red\n\t} else if DBHealth.DBReadFailures != 0 || DBHealth.DBWriteFailures != 0 {\n\t\tif timeSinceLastError < uint64(Configuration.ResendInterval*12) {\n\t\t\tDBHealth.DBStatus = Red\n\t\t} else if timeSinceLastError < uint64(Configuration.ResendInterval*60) {\n\t\t\tDBHealth.DBStatus = Yellow\n\t\t}\n\t}\n\n\tMQTTHealth.MQTTConnectionStatus = Green\n\tif Configuration.CommunicationProtocol != HTTPProtocol {\n\t\ttimeSinceLastSubError := uint64(0)\n\t\tif MQTTHealth.SubscribeFailures != 0 {\n\t\t\ttimeSinceLastSubError = uint64(time.Since(MQTTHealth.lastSubscribeErrorTime).Seconds())\n\t\t\tMQTTHealth.TimeSinceLastSubscribeError = timeSinceLastSubError\n\t\t}\n\t\ttimeSinceLastPubError := uint64(0)\n\t\tif MQTTHealth.PublishFailures != 0 {\n\t\t\ttimeSinceLastPubError = uint64(time.Since(MQTTHealth.lastPublishErrorTime).Seconds())\n\t\t\tMQTTHealth.TimeSinceLastPublishError = timeSinceLastPubError\n\t\t}\n\t\tif MQTTHealth.DisconnectedFromMQTTBroker {\n\t\t\tMQTTHealth.MQTTConnectionStatus = Red\n\t\t} else {\n\t\t\tif MQTTHealth.SubscribeFailures != 0 {\n\t\t\t\tif timeSinceLastSubError < uint64(Configuration.ResendInterval*12) {\n\t\t\t\t\tMQTTHealth.MQTTConnectionStatus = Red\n\t\t\t\t} else if timeSinceLastSubError < uint64(Configuration.ResendInterval*60) {\n\t\t\t\t\tMQTTHealth.MQTTConnectionStatus = Yellow\n\t\t\t\t}\n\t\t\t}\n\t\t\tif MQTTHealth.PublishFailures != 0 && MQTTHealth.MQTTConnectionStatus == Green &&\n\t\t\t\ttimeSinceLastPubError < uint64(Configuration.ResendInterval*12) {\n\t\t\t\tMQTTHealth.MQTTConnectionStatus = Yellow\n\t\t\t}\n\t\t}\n\t}\n\n\tif DBHealth.DBStatus == Red || MQTTHealth.MQTTConnectionStatus == Red {\n\t\ths.HealthStatus = Red\n\t} else if DBHealth.DBStatus == Yellow || MQTTHealth.MQTTConnectionStatus == Yellow {\n\t\ths.HealthStatus = Yellow\n\t} else {\n\t\ths.HealthStatus = Green\n\t}\n\n\ths.UpTime = uint64(time.Since(hs.startTime).Seconds())\n\n\tif !details {\n\t\treturn\n\t}\n\n\tif Configuration.CommunicationProtocol != HTTPProtocol {\n\t\tMQTTHealth.LastDisconnectFromBrokerDuration = hs.GetLastDisconnectFromBrokerDuration()\n\t}\n\tDBHealth.LastDisconnectFromDBDuration = hs.GetLastDisconnectFromDBDuration()\n}", "func (h *handler) writeStatus(status int, message string) {\n\tif status < 300 {\n\t\th.response.WriteHeader(status)\n\t\th.setStatus(status, message)\n\t\treturn\n\t}\n\t// Got an error:\n\tvar errorStr string\n\tswitch status {\n\tcase http.StatusNotFound:\n\t\terrorStr = \"not_found\"\n\tcase http.StatusConflict:\n\t\terrorStr = \"conflict\"\n\tdefault:\n\t\terrorStr = http.StatusText(status)\n\t\tif errorStr == \"\" {\n\t\t\terrorStr = fmt.Sprintf(\"%d\", status)\n\t\t}\n\t}\n\n//\th.disableResponseCompression()\n\th.setHeader(\"Content-Type\", \"application/json\")\n\th.response.WriteHeader(status)\n\th.setStatus(status, message)\n\tjsonOut, _ := json.Marshal(db.Body{\"error\": errorStr, \"reason\": message})\n\th.response.Write(jsonOut)\n}", "func HealthzHandler(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(200)\n}", "func healthcheck(w http.ResponseWriter, r *http.Request) {\n\tduration := time.Since(time.Now())\n\tif duration.Seconds() > 10 {\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(fmt.Sprintf(\"error: %v\", duration.Seconds())))\n\t} else {\n\t\tw.WriteHeader(200)\n\t\tw.Header().Set(\"HOW-ARE-YOU\", \"FINE_THANK_YOU\")\n\t}\n}", "func WriteStatus(out io.Writer, status int) {\n\tif resp, ok := out.(http.ResponseWriter); ok {\n\t\tresp.WriteHeader(status)\n\t}\n}", "func (es *Eventstore) Health(ctx context.Context) error {\n\treturn es.repo.Health(ctx)\n}", "func (a *API) health(w http.ResponseWriter, r *http.Request) {\n\tinfo := buildinfo.Get()\n\ta.writeJSON(w, r, http.StatusOK, httputil.HealthCheckResponse{\n\t\tBuildInfo: info,\n\t\tStartedAt: a.startedAt,\n\t})\n}", "func Health(c *gin.Context) {\n\tfmt.Println(\"Service healthy\")\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"message\": \"Loan service is healthy!\"})\n}", "func (c *Client) ReportHealthStatus(key health.HealthStatusKey, value health.HealthStatus, expires time.Duration) error {\n\trequest := HealthStatusRequest{\n\t\tKey: key,\n\t\tValue: value,\n\t\tExpires: expires,\n\t}\n\treturn c.call(\"ReportHealthStatus\", request, nil)\n}", "func healthCheck(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"Ready\"))\n}", "func (app *application) healthcheckHandler(w http.ResponseWriter, r *http.Request) {\n\t// Create a fixed-format JSON response from a string.\n\t// js := `{\"status\":\"available\", \"environment\": %q, \"version\": %q}`\n\t// js = fmt.Sprintf(js, app.config.env, version)\n\n\t// Create a map which holds the information that we want to send in the response.\n\t// data := map[string]string{\n\t// \t\"status\": \"available\",\n\t// \t\"environment\": app.config.env,\n\t// \t\"version\": version,\n\t// }\n\tenv := envelope{\n\t\t\"status\": \"available\",\n\t\t\"system_info\": map[string]string{\n\t\t\t\"environment\": app.config.env,\n\t\t\t\"version\": version,\n\t\t},\n\t}\n\n\t// Add a 4 second delay.\n\t// time.Sleep(4 * time.Second)\n\n\terr := app.writeJSON(w, http.StatusOK, env, nil)\n\tif err != nil {\n\t\t// app.logger.Println(err)\n\t\t// http.Error(w, \"The server encountered a problem and could not process your request\", http.StatusInternalServerError)\n\t\tapp.serverErrorResponse(w, r, err)\n\t}\n\n\t// Pass the map to the json.Marshal() function.\n\t// This returns a []byte slice containing the encoded JSON.\n\t// If there was an error, we log it and send the client a generic error message.\n\t// js, err := json.Marshal(data)\n\t// if err != nil {\n\t// \tapp.logger.Println(err)\n\t// \thttp.Error(w, \"The server encountered a problem and could not process your request\", http.StatusInternalServerError)\n\t// \treturn\n\t// }\n\n\t// Append a newline to the JSON. This is just a small nicety to make it easier to view in terminal application.\n\t// js = append(js, '\\n')\n\n\t// Set the \"Content-Type: application/json\" header on the response.\n\t// If you forget to this, Go will default to sending\n\t// a \"Content-Type: text/plain; charset=utf-8\" header instead.\n\t// w.Header().Set(\"Content-Type\", \"application/json\")\n\n\t// Write the JSON as the HTTP response body.\n\t// w.Write([]byte(js))\n}", "func (o ServerEndpointCloudTieringStatusResponseOutput) Health() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ServerEndpointCloudTieringStatusResponse) string { return v.Health }).(pulumi.StringOutput)\n}", "func (h *handler) Health(ctx context.Context) error {\n\treturn h.dbClient.Ping()\n}", "func (ftc *fakeTabletConn) StreamHealth(ctx context.Context, callback func(*querypb.StreamHealthResponse) error) error {\n\tserving := true\n\tif s, ok := ftc.tablet.Tags[\"serving\"]; ok {\n\t\tserving = (s == \"serving\")\n\t}\n\tvar herr string\n\tif s, ok := ftc.tablet.Tags[\"healthy\"]; ok && s != \"healthy\" {\n\t\therr = \"err\"\n\t}\n\tcallback(&querypb.StreamHealthResponse{\n\t\tServing: serving,\n\t\tTarget: &querypb.Target{\n\t\t\tKeyspace: ftc.tablet.Keyspace,\n\t\t\tShard: ftc.tablet.Shard,\n\t\t\tTabletType: ftc.tablet.Type,\n\t\t},\n\t\tRealtimeStats: &querypb.RealtimeStats{HealthError: herr},\n\t})\n\treturn nil\n}", "func healthCheck(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Status OK.\\n\")\n}", "func (s *Server) HealthCheckHandler(w http.ResponseWriter, r *http.Request) {\n\ttime.Sleep(time.Duration(s.Config.Delay) * time.Second)\n\tstatus := 200\n\tif !s.Config.Healthy {\n\t\tstatus = 500\n\t}\n\tw.WriteHeader(status)\n\tlog.Info(\"host: \", r.Host, \" uri: \", r.RequestURI, \" status: \", status)\n\n}", "func healthHandler(healthFunc func() bool) gin.HandlerFunc {\n\thealthy := healthFunc\n\treturn func(ctx *gin.Context) {\n\t\thealth := struct {\n\t\t\tHealth bool `json:\"health\"`\n\t\t}{\n\t\t\tHealth: healthy(),\n\t\t}\n\n\t\tif !health.Health {\n\t\t\tctx.JSON(http.StatusServiceUnavailable, &health)\n\t\t} else {\n\t\t\tctx.JSON(http.StatusOK, &health)\n\t\t}\n\t}\n}", "func healthHandler(healthFunc func() bool) gin.HandlerFunc {\n\thealthy := healthFunc\n\treturn func(ctx *gin.Context) {\n\t\thealth := struct {\n\t\t\tHealth bool `json:\"health\"`\n\t\t}{\n\t\t\tHealth: healthy(),\n\t\t}\n\n\t\tif !health.Health {\n\t\t\tctx.JSON(http.StatusServiceUnavailable, &health)\n\t\t} else {\n\t\t\tctx.JSON(http.StatusOK, &health)\n\t\t}\n\t}\n}", "func (w *PrometheusWriter) Write(metric model.Metric) error {\n\tduration := float64(metric.Duration / time.Millisecond)\n\treason := \"\"\n\tif metric.Error != \"\" {\n\t\treason = strings.SplitN(metric.Error, \":\", 2)[0]\n\t\treason = strings.ToLower(reason)\n\t\thealthCheckStatusGauge.With(prometheus.Labels{\n\t\t\t\"name\": metric.Name,\n\t\t}).Set(0)\n\t\thealthCheckErrorCounter.With(prometheus.Labels{\n\t\t\t\"name\": metric.Name,\n\t\t\t\"reason\": reason,\n\t\t}).Inc()\n\t} else {\n\t\thealthCheckStatusGauge.With(prometheus.Labels{\n\t\t\t\"name\": metric.Name,\n\t\t}).Set(1)\n\t}\n\thealthCheckResponseTimeGauge.With(prometheus.Labels{\n\t\t\"name\": metric.Name,\n\t}).Set(duration)\n\n\treturn nil\n}", "func (o ServerEndpointCloudTieringStatusResponsePtrOutput) Health() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ServerEndpointCloudTieringStatusResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Health\n\t}).(pulumi.StringPtrOutput)\n}", "func (c *Client) Health(ctx context.Context) (err error) {\n\t_, err = c.HealthEndpoint(ctx, nil)\n\treturn\n}", "func (t *ssh2Server) WriteStatus(s *Stream, statusCode codes.Code, statusDesc string) error {\n\tlogrus.Debugln(\"WriteStatus\")\n\tlogrus.Debugln(\"WriteStatus -- statusCode:\", statusCode)\n\tlogrus.Debugln(\"WriteStatus -- statusDesc:\", statusDesc)\n\n\tch := t.channelsByStreamId[s.id]\n\terr := (*ch).CloseWrite()\n\treturn err\n\n\t// =================================== original code ======================================\n\t// s.mu.RLock()\n\t// if s.state == streamDone {\n\t// \ts.mu.RUnlock()\n\t// \treturn nil\n\t// }\n\t// s.mu.RUnlock()\n\t// if _, err := wait(s.ctx, t.shutdownChan, t.writableChan); err != nil {\n\t// \treturn err\n\t// }\n\t// t.hBuf.Reset()\n\t// t.hEnc.WriteField(hpack.HeaderField{Name: \":status\", Value: \"200\"})\n\t// t.hEnc.WriteField(\n\t// \thpack.HeaderField{\n\t// \t\tName: \"grpc-status\",\n\t// \t\tValue: strconv.Itoa(int(statusCode)),\n\t// \t})\n\t// t.hEnc.WriteField(hpack.HeaderField{Name: \"grpc-message\", Value: statusDesc})\n\t// // Attach the trailer metadata.\n\t// for k, v := range s.trailer {\n\t// \tt.hEnc.WriteField(hpack.HeaderField{Name: k, Value: v})\n\t// }\n\t// if err := t.writeHeaders(s, t.hBuf, true); err != nil {\n\t// \tt.Close()\n\t// \treturn err\n\t// }\n\t// t.closeStream(s)\n\t// t.writableChan <- 0\n\t// return nil\n}", "func (t ThriftHandler) Health(ctx context.Context) (response *health.HealthStatus, err error) {\n\tresponse, err = t.h.Health(ctx)\n\treturn response, thrift.FromError(err)\n}", "func makeHealthHandler() func(http.ResponseWriter, *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tswitch r.Method {\n\t\tcase http.MethodGet:\n\t\t\tif atomic.LoadInt32(&acceptingConnections) == 0 || lockFilePresent() == false {\n\t\t\t\tw.WriteHeader(http.StatusServiceUnavailable)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\tw.Write([]byte(\"OK\"))\n\n\t\t\tbreak\n\t\tdefault:\n\t\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\t}\n\t}\n}", "func (o *SummaryResponse) SetHealth(v SummaryHealthResponse) {\n\to.Health = &v\n}", "func (c *HealthController) Health(ctx *app.HealthHealthContext) error {\n\t// HealthController_Health: start_implement\n\tver := \"unknown\"\n\tsemVer, err := semver.Make(MajorMinorPatch + \"-\" + ReleaseType + \"+git.sha.\" + GitCommit)\n\tif err == nil {\n\t\tver = semVer.String()\n\t}\n\treturn ctx.OK([]byte(\"Health OK: \" + time.Now().String() + \", semVer: \" + ver + \"\\n\"))\n\t// HealthController_Health: end_implement\n}", "func NewHealthHandler(appCtx appcontext.AppContext, redisPool *redis.Pool, gitBranch string, gitCommit string) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\tdata := map[string]interface{}{\n\t\t\t\"gitBranch\": gitBranch,\n\t\t\t\"gitCommit\": gitCommit,\n\t\t}\n\t\t// Check and see if we should disable DB query with '?database=false'\n\t\t// Disabling the DB is useful for Route53 health checks which require the TLS\n\t\t// handshake be less than 4 seconds and the status code return in less than\n\t\t// two seconds. https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-determining-health-of-endpoints.html\n\t\tshowDB, ok := r.URL.Query()[\"database\"]\n\n\t\tvar dbID string\n\t\tvar dbURL string\n\t\t// Always show DB unless key set to \"false\"\n\t\tif !ok || (ok && showDB[0] != \"false\") {\n\t\t\tappCtx.Logger().Info(\"Health check connecting to the DB\")\n\t\t\t// include the request context for helpful tracing\n\t\t\tdb := appCtx.DB().WithContext(r.Context())\n\t\t\tdbID = db.ID\n\t\t\tdbURL = db.Dialect.Details().URL\n\t\t\tdbErr := db.RawQuery(\"SELECT 1;\").Exec()\n\t\t\tif dbErr != nil {\n\t\t\t\tappCtx.Logger().Error(\"Failed database health check\",\n\t\t\t\t\tzap.String(\"dbID\", dbID),\n\t\t\t\t\tzap.String(\"dbURL\", dbURL),\n\t\t\t\t\tzap.Error(dbErr))\n\t\t\t\tdata[\"database\"] = false\n\t\t\t\thealthCheckError(appCtx, w, data)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdata[\"database\"] = true\n\t\t\tif redisPool != nil {\n\t\t\t\tredisErr := redisHealthCheck(redisPool, appCtx.Logger())\n\t\t\t\tif redisErr != nil {\n\t\t\t\t\tdata[\"redis\"] = false\n\t\t\t\t\thealthCheckError(appCtx, w, data)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tdata[\"redis\"] = true\n\t\t\t}\n\t\t}\n\n\t\tnewEncoderErr := json.NewEncoder(w).Encode(data)\n\t\tif newEncoderErr != nil {\n\t\t\tappCtx.Logger().Error(\"Failed encoding health check response\", zap.Error(newEncoderErr))\n\t\t\thttp.Error(w, \"failed health check\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tappCtx.Logger().Info(\"Request health ok\",\n\t\t\tzap.String(\"dbID\", dbID),\n\t\t\tzap.String(\"dbURL\", dbURL))\n\t}\n}", "func healthz(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\t_, _ = fmt.Fprintf(w, \"OK\")\n}", "func getHealthStatus(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": \"ready\"})\n}", "func WriteStatus(status []byte, buf *goetty.ByteBuf) {\r\n\tbuf.WriteByte('+')\r\n\tbuf.Write(status)\r\n\tbuf.Write(Delims)\r\n}", "func (db *sqlstore) Health() error {\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second*5)\n\tdefer cancel()\n\n\treturn db.PingContext(ctx)\n}", "func statusHandler(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tenc := json.NewEncoder(w)\n\terr := enc.Encode(getCurrentStatus())\n\tif err != nil {\n\t\tsklog.Errorf(\"Failed to write or encode output: %s\", err)\n\t\treturn\n\t}\n}", "func PostHealth(w http.ResponseWriter, r *http.Request, db *sqlx.DB) {\n\tparams := mux.Vars(r)\n\treturnMessages := make(map[string][]string)\n\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tsession, err := store.Get(r, \"auth\")\n\tif err != nil {\n\t\treturnMessages[\"message\"] = append(returnMessages[\"message\"], err.Error())\n\t\treturnMessages[\"status\"] = append(returnMessages[\"status\"], \"error\")\n\t\t// http.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// Convert our session data into an instance of User\n\tuser := User{}\n\tuser, _ = session.Values[\"user\"].(User)\n\n\tif user.Username != \"\" && user.AccessLevel == \"admin\" {\n\t\tvar health []Health\n\n\t\tif err := json.Unmarshal(body, &health); err != nil {\n\t\t\treturnMessages[\"message\"] = append(returnMessages[\"message\"], err.Error())\n\t\t\treturnMessages[\"status\"] = append(returnMessages[\"status\"], \"error\")\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\t\tw.WriteHeader(http.StatusOK)\n\n\t\t\tlog.Println(returnMessages)\n\t\t\tif err := json.NewEncoder(w).Encode(returnMessages); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tif len(health) == 0 {\n\t\t\treturnMessages[\"message\"] = append(returnMessages[\"message\"], \"Warning: no items in health\")\n\t\t\treturnMessages[\"status\"] = append(returnMessages[\"status\"], \"warning\")\n\t\t} else {\n\t\t\tif params[\"keys\"] == \"u\" {\n\t\t\t\tfor _, item := range health {\n\t\t\t\t\t_, err := db.Exec(\"INSERT INTO public.health (\"+\n\t\t\t\t\t\t\"username, \"+\n\t\t\t\t\t\t\"ts, \"+\n\t\t\t\t\t\t\"variable, \"+\n\t\t\t\t\t\t\"value\"+\n\t\t\t\t\t\t\") VALUES (\"+\n\t\t\t\t\t\t\" $1,\"+\n\t\t\t\t\t\t\" $2,\"+\n\t\t\t\t\t\t\" $3,\"+\n\t\t\t\t\t\t\" $4\"+\n\t\t\t\t\t\t\") \"+\"ON CONFLICT (\"+\n\t\t\t\t\t\t\"ts, \"+\n\t\t\t\t\t\t\"variable \"+\n\t\t\t\t\t\t\") DO \"+\n\t\t\t\t\t\t\"UPDATE SET \"+\n\t\t\t\t\t\t\" username = $1,\"+\n\t\t\t\t\t\t\" value = $4\",\n\t\t\t\t\t\tuser.Username,\n\t\t\t\t\t\titem.Ts,\n\t\t\t\t\t\titem.Variable,\n\t\t\t\t\t\titem.Value)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturnMessages[\"message\"] = append(returnMessages[\"message\"], err.Error())\n\t\t\t\t\t\treturnMessages[\"status\"] = append(returnMessages[\"status\"], \"error\")\n\t\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturnMessages[\"message\"] = append(returnMessages[\"message\"], \"inserted item into health\")\n\t\t\t\t\t\treturnMessages[\"status\"] = append(returnMessages[\"status\"], \"info\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif params[\"keys\"] == \"p\" {\n\t\t\t\tfor _, item := range health {\n\t\t\t\t\t_, err := db.Exec(\"INSERT INTO public.health (\"+\n\t\t\t\t\t\t\"id, \"+\n\t\t\t\t\t\t\"username, \"+\n\t\t\t\t\t\t\"ts, \"+\n\t\t\t\t\t\t\"variable, \"+\n\t\t\t\t\t\t\"value\"+\n\t\t\t\t\t\t\") VALUES (\"+\n\t\t\t\t\t\t\" $1,\"+\n\t\t\t\t\t\t\" $2,\"+\n\t\t\t\t\t\t\" $3,\"+\n\t\t\t\t\t\t\" $4,\"+\n\t\t\t\t\t\t\" $5\"+\n\t\t\t\t\t\t\") \"+\n\t\t\t\t\t\t\"ON CONFLICT (\"+\n\t\t\t\t\t\t\"id \"+\n\t\t\t\t\t\t\") DO \"+\n\t\t\t\t\t\t\"UPDATE SET \"+\n\t\t\t\t\t\t\" username = $2,\"+\n\t\t\t\t\t\t\" ts = $3,\"+\n\t\t\t\t\t\t\" variable = $4,\"+\n\t\t\t\t\t\t\" value = $5\",\n\t\t\t\t\t\titem.ID,\n\t\t\t\t\t\tuser.Username,\n\t\t\t\t\t\titem.Ts,\n\t\t\t\t\t\titem.Variable,\n\t\t\t\t\t\titem.Value)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturnMessages[\"message\"] = append(returnMessages[\"message\"], err.Error())\n\t\t\t\t\t\treturnMessages[\"status\"] = append(returnMessages[\"status\"], \"error\")\n\t\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturnMessages[\"message\"] = append(returnMessages[\"message\"], \"inserted item into health\")\n\t\t\t\t\t\treturnMessages[\"status\"] = append(returnMessages[\"status\"], \"info\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\tw.WriteHeader(http.StatusOK)\n\n\t\tlog.Println(returnMessages)\n\t\tif err := json.NewEncoder(w).Encode(returnMessages); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t} else {\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\tw.WriteHeader(http.StatusOK)\n\n\t\tif err := json.NewEncoder(w).Encode(\"access denied\"); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tlogRequest(r)\n}" ]
[ "0.63933337", "0.6092843", "0.6077512", "0.60371065", "0.6022256", "0.59317994", "0.5899792", "0.58965546", "0.5840892", "0.5839557", "0.580958", "0.57847655", "0.5759944", "0.5752663", "0.5722315", "0.5718866", "0.570485", "0.5676137", "0.566885", "0.5662208", "0.5658867", "0.5617557", "0.5617557", "0.5606169", "0.55858225", "0.55858225", "0.5551634", "0.5543057", "0.5529049", "0.5521585", "0.5520378", "0.54875535", "0.54792434", "0.54786855", "0.54363", "0.54319984", "0.5395947", "0.5379039", "0.53623873", "0.5336325", "0.53356606", "0.53354996", "0.5330677", "0.53283155", "0.53257084", "0.5302373", "0.5280739", "0.5277705", "0.523656", "0.52265763", "0.5224208", "0.5222298", "0.5192144", "0.5189991", "0.51861554", "0.5153274", "0.5152054", "0.5138994", "0.5132698", "0.51308256", "0.5124126", "0.5122899", "0.51087135", "0.50942034", "0.50863844", "0.50795895", "0.5077459", "0.50696826", "0.5056814", "0.5056165", "0.50551766", "0.5048832", "0.5047519", "0.50466037", "0.5029681", "0.50281525", "0.5026546", "0.5025917", "0.5022226", "0.50171673", "0.50146013", "0.50111717", "0.5007915", "0.5001798", "0.5001798", "0.4999895", "0.49963441", "0.49825844", "0.4980607", "0.4978197", "0.49654007", "0.49588588", "0.49555585", "0.49545586", "0.49508467", "0.49403873", "0.49304843", "0.49269786", "0.49199525", "0.49085516" ]
0.6364347
1
writePeers writes the connected Peers to the peerWidget. Exits when the context expires.
func writePeers(ctx context.Context, t *text.Text, delay time.Duration) { peers := gjson.Get(getFromRPC("net_info"), "result.n_peers").String() t.Reset() if peers != "" { t.Write(peers) } if err := t.Write(peers); err != nil { panic(err) } ticker := time.NewTicker(delay) defer ticker.Stop() for { select { case <-ticker.C: t.Reset() peers := gjson.Get(getFromRPC("net_info"), "result.n_peers").String() if peers != "" { t.Write(peers) } case <-ctx.Done(): return } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p *peer) peerWriter(errorChan chan peerMessage) {\n\tlog.Infof(\"[%s] Writing messages to peer[%s]\", p.taskID, p.address)\n\tvar lastWriteTime time.Time\n\n\tfor msg := range p.writeChan {\n\t\tnow := time.Now()\n\t\tif len(msg) == 0 {\n\t\t\t// This is a keep-alive message.\n\t\t\tif now.Sub(lastWriteTime) < 2*time.Minute {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlog.Tracef(\"[%s] Sending keep alive to peer[%s]\", p.taskID, p.address)\n\t\t}\n\t\tlastWriteTime = now\n\n\t\t//log.Debugf(\"[%s] Sending message to peer[%s], length=%v\", p.taskID, p.address, uint32(len(msg)))\n\t\terr := writeNBOUint32(p.flowctrlWriter, uint32(len(msg)))\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tbreak\n\t\t}\n\t\t_, err = p.flowctrlWriter.Write(msg)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"[%s] Failed to write a message to peer[%s], length=%v, err=%v\", p.taskID, p.address, len(msg), err)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tlog.Infof(\"[%s] Exiting Writing messages to peer[%s]\", p.taskID, p.address)\n\terrorChan <- peerMessage{p, nil}\n}", "func savePeers(peers []repository.Peer) {\n\tfor _, peer := range peers {\n\t\tsavePeer(peer)\n\t}\n}", "func (c *Client) Write(ctx context.Context, chain *Chain) {\n\tticker := time.NewTicker(c.pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.conn.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(c.writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\n\t\t\t// Add queued chat messages to the current websocket message.\n\t\t\tn := len(c.send)\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\t//w.Write(newline)\n\t\t\t\tw.Write(<-c.send)\n\t\t\t}\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(c.writeWait))\n\t\t\tif err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (server *Server) SearchPeers() {\n\tfor _, peer := range server.otherPeers {\n\t\tif !peer.isConnected {\n\t\t\tconn, err := net.DialTCP(\"tcp\", nil, peer.TCPAddr)\n\t\t\tif err == nil {\n\t\t\t\tserver.Join(conn, peer)\n\t\t\t\t_, err = conn.Write([]byte{byte(len(peer.TCPAddr.String()))})\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(\"error, while sending IP adress\", \"error\", err)\n\t\t\t\t} else {\n\t\t\t\t\t_, err = conn.Write([]byte(server.myPeer.TCPAddr.String()))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Error(\"error, while sending IP adress\", \"error\", err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (m *Manager) AddPeers(peers peer.Peers) error {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\tadded := false\n\tfor _, peer := range peers {\n\t\tif !peer.IsAllowed() {\n\t\t\terr := errors.New(\"denied\")\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tadded = added || m.peers.Add(peer)\n\t}\n\tif !added {\n\t\treturn nil\n\t}\n\treturn m.self.WritePeers(m.peers)\n}", "func SetPeers(deviceName string, peers []wgtypes.PeerConfig) error {\n\twg, err := wgctrl.New()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif err := wg.Close(); err != nil {\n\t\t\tlog.Logger.Error(\n\t\t\t\t\"Failed to close wireguard client\", \"err\", err)\n\t\t}\n\t}()\n\tif deviceName == \"\" {\n\t\tdeviceName = defaultWireguardDeviceName\n\t}\n\tdevice, err := wg.Device(deviceName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, ep := range device.Peers {\n\t\tfound := false\n\t\tfor i, np := range peers {\n\t\t\tpeers[i].ReplaceAllowedIPs = true\n\t\t\tif ep.PublicKey.String() == np.PublicKey.String() {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tpeers = append(peers, wgtypes.PeerConfig{PublicKey: ep.PublicKey, Remove: true})\n\t\t}\n\t}\n\treturn wg.ConfigureDevice(deviceName, wgtypes.Config{Peers: peers})\n}", "func (p *peer) AddPeersPeers() {\n\tdefer p.ms.Done() // it's a goroutine\n\n\tif strings.Index(p.Url, getPeersUrl) < 0 {\n\t\tlog.Println(\"Error: you can only addpeers with a\", getPeersUrl, \"request\")\n\t\treturn\n\t}\n\n\t////\n\t// Get remote meshping server publich state. This may take a while!\n\t// That's why this is a goroutine...\n\trm, err := FetchRemotePeer(p.Url, p.PeerIP)\n\tif err != nil {\n\t\treturn // FetchRemotePeer reported to log(stderr) already\n\t}\n\n\tif p.ms.Verbose() > 2 {\n\t\tlog.Println(\"Got a remote server's state:\")\n\t\tenc := json.NewEncoder(os.Stdout)\n\t\tenc.SetIndent(\"\", \" \")\n\t\t// No need to take a lock on the mutex\n\t\tif err := enc.Encode(rm); err != nil {\n\t\t\tclient.LogSentry(sentry.LevelWarning, \"Error converting remote state to json: %s\", err)\n\t\t}\n\t}\n\n\tfor _, rmp := range rm.Peers {\n\t\turl := rmp.Url\n\t\tip := rmp.PeerIP\n\t\tpeer := p.ms.FindPeer(url, ip)\n\t\tif peer != nil {\n\t\t\tif p.ms.Verbose() > 2 {\n\t\t\t\tlog.Println(\"peer\", url, ip, \"-- PeerAlreadyPresent\")\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Println(\"adding peer\", url, ip)\n\t\tpeer = p.ms.NewPeer(url, ip, p.Location)\n\t\tpeer.ms.Add() // for the Ping goroutine\n\t\tgo peer.Ping()\n\t}\n}", "func (peer *PeerConnection) writeConnectionPump(sock *NamedWebSocket) {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tpeer.removeConnection(sock)\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tpeer.ws.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tpeer.ws.WriteMessage(websocket.PingMessage, []byte{})\n\t\t}\n\t}\n}", "func (g *Group) RegisterPeers(peers PeerPicker) {\n\tif g.peers != nil {\n\t\tpanic(\"RegisterPeers called more than once\")\n\t}\n\tg.peers = peers\n}", "func (p *Pointer) Write(w *sync.WaitGroup) {\n\t// tick and check everything ok with the pointer once every ~40 seconds\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tp.conn.Close()\n\t}()\n\tw.Done()\n\t//read from our send channel\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-p.send:\n\t\t\tp.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\tp.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err := p.conn.WriteMessage(websocket.TextMessage, message); err != nil {\n\t\t\t\tfmt.Println(\"failed to write to the connection \", err.Error())\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\t// when it ticks write the ping to the client socket. If it fails return so the the connection is closed\n\t\t\tp.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := p.conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {\n\t\t\t\tfmt.Println(\"error writing ping \", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (h HTTPHandler) HandlePeers(w http.ResponseWriter, r *http.Request) {\n\terr := processJWT(r, false, h.secret)\n\tif err != nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"\"+err.Error()+\"\\\"}\", 401)\n\t\treturn\n\t}\n\n\tpeers := h.p2p.GetPeers()\n\tif bytes.Compare(peers, []byte(\"null\")) == 0 {\n\t\tpeers = []byte(\"[]\")\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(peers)\n}", "func (app *application) Peers() error {\n\tpeers, err := app.appli.Sub().Peers().Retrieve()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tallPeers := []peer.Peer{}\n\tlocalPeers := peers.All()\n\tfor _, oneLocalPeer := range localPeers {\n\t\tremoteApplication, err := app.clientBuilder.Create().WithPeer(oneLocalPeer).Now()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tremotePeers, err := remoteApplication.Sub().Peers().Retrieve()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tallPeers = append(allPeers, oneLocalPeer)\n\t\tallPeers = append(allPeers, remotePeers.All()...)\n\t}\n\n\tupdatedPeers, err := app.peersBuilder.Create().WithPeers(allPeers).Now()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tupdatedPeersList := updatedPeers.All()\n\tfor _, onePeer := range updatedPeersList {\n\t\terr = app.appli.Sub().Peers().Save(onePeer)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (gossiper *Gossiper) UpdatePeers(peer_addr string) {\n\n\tgossiper.Peers.Mux.Lock()\n\tdefer gossiper.Peers.Mux.Unlock()\n\n\t// Try to find peer addr in self's buffer\n\tfor _, addr := range gossiper.Peers.Peers {\n\n\t\tif peer_addr == addr {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Put it in self's buffer if it is absent\n\tgossiper.Peers.Peers = append(gossiper.Peers.Peers, peer_addr)\n}", "func (sc *ServerConn) Peers(ctx context.Context) ([]*PeersResult, error) {\n\t// Note that the Electrum exchange wallet type does not currently use this\n\t// method since it follows the Electrum wallet server peer or one of the\n\t// wallets other servers. See (*electrumWallet).connect and\n\t// (*WalletClient).GetServers. We might wish to in the future though.\n\n\t// [[\"ip\", \"host\", [\"featA\", \"featB\", ...]], ...]\n\t// [][]interface{}{string, string, []interface{}{string, ...}}\n\tvar resp [][]interface{}\n\terr := sc.Request(ctx, \"server.peers.subscribe\", nil, &resp) // not really a subscription!\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpeers := make([]*PeersResult, 0, len(resp))\n\tfor _, peer := range resp {\n\t\tif len(peer) != 3 {\n\t\t\tsc.debug(\"bad peer data: %v (%T)\", peer, peer)\n\t\t\tcontinue\n\t\t}\n\t\taddr, ok := peer[0].(string)\n\t\tif !ok {\n\t\t\tsc.debug(\"bad peer IP data: %v (%T)\", peer[0], peer[0])\n\t\t\tcontinue\n\t\t}\n\t\thost, ok := peer[1].(string)\n\t\tif !ok {\n\t\t\tsc.debug(\"bad peer hostname: %v (%T)\", peer[1], peer[1])\n\t\t\tcontinue\n\t\t}\n\t\tfeatsI, ok := peer[2].([]interface{})\n\t\tif !ok {\n\t\t\tsc.debug(\"bad peer feature data: %v (%T)\", peer[2], peer[2])\n\t\t\tcontinue\n\t\t}\n\t\tfeats := make([]string, len(featsI))\n\t\tfor i, featI := range featsI {\n\t\t\tfeat, ok := featI.(string)\n\t\t\tif !ok {\n\t\t\t\tsc.debug(\"bad peer feature data: %v (%T)\", featI, featI)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfeats[i] = feat\n\t\t}\n\t\tpeers = append(peers, &PeersResult{\n\t\t\tAddr: addr,\n\t\t\tHost: host,\n\t\t\tFeats: feats,\n\t\t})\n\t}\n\treturn peers, nil\n}", "func GetPeers(w http.ResponseWriter, r *http.Request) {\n\t// Sends list of peers this node is connected to\n\tpeersStr := \"\"\n\tfor peer, v := range hub.peers {\n\t\tif v == true {\n\t\t\tpeersStr += peer.conn.RemoteAddr().String()\n\t\t\tpeersStr += \",\"\n\t\t}\n\t}\n\t//log.Printf(\"GetPeers: data=%s\\n\", peersStr)\n\tvar p peerStr\n\tp.Peer = peersStr\n\tjson.NewEncoder(w).Encode(p)\n}", "func writeBlocks(ctx context.Context, t *text.Text, connectionSignal <-chan string) {\n\n\tport := *givenPort\n\tsocket := gowebsocket.New(\"ws://localhost:\" + port + \"/websocket\")\n\n\tsocket.OnTextMessage = func(message string, socket gowebsocket.Socket) {\n\t\tcurrentBlock := gjson.Get(message, \"result.data.value.block.header.height\")\n\t\tif currentBlock.String() != \"\" {\n\t\t\tif err := t.Write(fmt.Sprintf(\"%s\\n\", \"Latest block height \"+currentBlock.String())); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\n\t}\n\n\tsocket.Connect()\n\n\tsocket.SendText(\"{ \\\"jsonrpc\\\": \\\"2.0\\\", \\\"method\\\": \\\"subscribe\\\", \\\"params\\\": [\\\"tm.event='NewBlock'\\\"], \\\"id\\\": 1 }\")\n\n\tfor {\n\t\tselect {\n\t\tcase s := <-connectionSignal:\n\t\t\tif s == \"no_connection\" {\n\t\t\t\tsocket.Close()\n\t\t\t}\n\t\t\tif s == \"reconnect\" {\n\t\t\t\twriteBlocks(ctx, t, connectionSignal)\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\tlog.Println(\"interrupt\")\n\t\t\tsocket.Close()\n\t\t\treturn\n\t\t}\n\t}\n}", "func (o *GenesisPeersListOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\trw.WriteHeader(200)\n\tpayload := o.Payload\n\tif payload == nil {\n\t\t// return empty array\n\t\tpayload = make([]*models.Peer, 0, 50)\n\t}\n\n\tif err := producer.Produce(rw, payload); err != nil {\n\t\tpanic(err) // let the recovery middleware deal with this\n\t}\n}", "func (h *DevicePluginHandlerImpl) writeCheckpoint() error {\n\tfilepath := h.devicePluginManager.CheckpointFile()\n\tvar data checkpointData\n\tfor resourceName, podDev := range h.allocatedDevices {\n\t\tfor podUID, conDev := range podDev {\n\t\t\tfor conName, devs := range conDev {\n\t\t\t\tfor _, devId := range devs.UnsortedList() {\n\t\t\t\t\tdata.Entries = append(data.Entries, checkpointEntry{podUID, conName, resourceName, devId})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tdataJson, err := json.Marshal(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(filepath, dataJson, 0644)\n}", "func (s *Server) resyncPeerList() error {\n\tnodes, err := s.client.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\tpeerMap := make(map[string]bool)\n\tfor _, node := range nodes.Items {\n\t\t// Don't add our own node as a peer\n\t\tif node.Name == s.config.NodeName {\n\t\t\tcontinue\n\t\t}\n\n\t\tpeerMap[node.Name] = true\n\t\tif _, ok := s.peers[node.Name]; !ok {\n\t\t\ts.peers[node.Name] = &peer{\n\t\t\t\tname: node.Name,\n\t\t\t\tlastStatusChange: s.clock.Now(),\n\t\t\t\taddr: &net.IPAddr{},\n\t\t\t}\n\t\t\ts.WithField(\"peer\", node.Name).Info(\"Adding peer.\")\n\t\t\t// Initialize the peer so it shows up in prometheus with a 0 count\n\t\t\ts.promPeerTimeout.WithLabelValues(s.config.NodeName, node.Name).Add(0)\n\t\t\ts.promPeerRequest.WithLabelValues(s.config.NodeName, node.Name).Add(0)\n\t\t}\n\t}\n\n\t// check for peers that have been deleted\n\tfor key := range s.peers {\n\t\tif _, ok := peerMap[key]; !ok {\n\t\t\ts.WithField(\"peer\", key).Info(\"Deleting peer.\")\n\t\t\tdelete(s.peers, key)\n\t\t\ts.promPeerRTT.DeleteLabelValues(s.config.NodeName, key)\n\t\t\ts.promPeerRTTSummary.DeleteLabelValues(s.config.NodeName, key)\n\t\t\ts.promPeerRequest.DeleteLabelValues(s.config.NodeName, key)\n\t\t\ts.promPeerTimeout.DeleteLabelValues(s.config.NodeName, key)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (r *Replica) waitForPeerConnections(done chan bool) {\n\tvar b [4]byte\n\tbs := b[:4]\n\n\tvar err error\n\tlAddr := r.PeerAddrList[r.Id][strings.Index(r.PeerAddrList[r.Id], \":\"):]\n\tlog.Printf(\"Listening for peers on %s\\n\", lAddr)\n\tr.Listener, err = net.Listen(\"tcp\", lAddr)\n\tif err != nil {\n\t\tlog.Printf(\"Error listening to peer %d: %v\\n\", r.Id, err)\n\t\tos.Exit(1)\n\t}\n\n\tfor i := r.Id + 1; i < int32(r.N); i++ {\n\t\tconn, err := r.Listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error accepting connection from peer: %v\\n\",\n\t\t\t\terr)\n\t\t\tcontinue\n\t\t}\n\t\tdlog.Printf(\"Accepted connection from peer %s.\\n\", conn.RemoteAddr().String())\n\t\tif n, err := io.ReadFull(conn, bs); err != nil || n != len(bs) {\n\t\t\tlog.Printf(\"Error reading peer id: %v (%d bytes read)\\n\", err, n)\n\t\t\tcontinue\n\t\t}\n\t\tid := int32(binary.LittleEndian.Uint32(bs))\n\t\tif id <= r.Id || id >= int32(r.N) {\n\t\t\tlog.Fatalf(\"Read incorrect id %d from connecting peer\\n\", id)\n\t\t}\n\t\tlog.Printf(\"Peer sent %d as id (%d total peers).\\n\", id, len(r.Peers))\n\t\tr.Peers[id] = conn\n\t\tr.PeerReaders[id] = bufio.NewReader(conn)\n\t\tr.PeerWriters[id] = bufio.NewWriter(conn)\n\t\tr.Alive[id] = true\n\t\tlog.Printf(\"Successfully established connection with peer %d\\n\", id)\n\t}\n\n\tdone <- true\n}", "func ConnectToPeers(newPeers string) {\n\tpeers := strings.Split(newPeers, \",\")\n\tlog.Println(peers)\n\tlog.Println(len(peers))\n\tif peers[0] == \"\" {\n\t\treturn\n\t}\n\tfor _, peer := range peers {\n\t\t// connect to peer\n\t\tu := url.URL{Scheme: \"ws\", Host: peer, Path: \"/ws\"}\n\t\tlog.Printf(\"Connecting to %s\", u.String())\n\n\t\tc, _, err := websocket.DefaultDialer.Dial(u.String(), nil)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"dial:\", err)\n\t\t}\n\t\taddWs(hub, c)\n\t}\n}", "func (c *Client) WritePump() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.Conn.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.Send:\n\t\t\tc.Conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The Hub closed the channel.\n\t\t\t\tc.Conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\t\t\tc.Conn.WriteJSON(message)\n\t\tcase <-ticker.C:\n\t\t\tc.Conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.Conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (p *Peer) pushPeers() {\n\tp.QueueMessage(p.peersMessage())\n}", "func (pm *peerManager) tryConnectPeers() {\n\tremained := pm.conf.NPMaxPeers - len(pm.remotePeers)\n\tfor ID, meta := range pm.peerPool {\n\t\tif _, found := pm.GetPeer(ID); found {\n\t\t\tdelete(pm.peerPool, ID)\n\t\t\tcontinue\n\t\t}\n\t\tif meta.IPAddress == \"\" || meta.Port == 0 {\n\t\t\tpm.logger.Warn().Str(LogPeerID, meta.ID.Pretty()).Str(\"addr\", meta.IPAddress).\n\t\t\t\tUint32(\"port\", meta.Port).Msg(\"Invalid peer meta informations\")\n\t\t\tcontinue\n\t\t}\n\t\t// in same go rountine.\n\t\tpm.addOutboundPeer(meta)\n\t\tremained--\n\t\tif remained <= 0 {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (bc *Blockchain) WriteChain() {\n\tjsonChain, err := json.Marshal(bc.Chain)\n\tif err != nil{\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\terr = ioutil.WriteFile(JSONCHAIN, jsonChain, 0644)\n\tif err != nil{\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n}", "func SendPeerList(c *gin.Context) {\n\tc.JSON(200, gin.H{\"success\": true, \"peers\": core.EnvironmentParams.Network.PeerList})\n}", "func (c *Client) WritePump() {\n\n\tticker := time.NewTicker(pingPeriod)\n\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.Conn.Close()\n\t}()\n\n\t// for i := 0; i < {\n\n\t// \tbreak\n\t// }\n\n\tfor {\n\n\t\tselect {\n\t\tcase message, ok := <-c.Send:\n\t\t\tc.Conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.Conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.Conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\t\t\t// Add queued chat messages to the current websocket message.\n\t\t\tn := len(c.Send)\n\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\tnewMessage := <-c.Send\n\t\t\t\tw.Write(newMessage)\n\t\t\t}\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.Conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.Conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (t *Transfer) peerManager() {\n\tt.log.Debug(\"Started peerManager\")\n\tfor {\n\t\tselect {\n\t\tcase <-t.stopC:\n\t\t\treturn\n\t\tcase peers := <-t.peersC:\n\t\t\tfor _, p := range peers {\n\t\t\t\tt.log.Debugln(\"Peer:\", p)\n\t\t\t\t// TODO send all peers to connecter for now\n\t\t\t\tgo func(addr *net.TCPAddr) {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase t.peerC <- addr:\n\t\t\t\t\tcase <-t.stopC:\n\t\t\t\t\t}\n\t\t\t\t}(p)\n\t\t\t}\n\t\t}\n\t}\n}", "func (w *HotCache) CheckWritePeerSync(peer *core.PeerInfo, region *core.RegionInfo) *HotPeerStat {\n\treturn w.writeFlow.CheckPeerFlow(peer, region)\n}", "func (connection Connection) writeCycle(network Network) {\n\tfor {\n\t\tselect {\n\t\tcase packet := <-connection.writeQueue: // Equivalent to socket select\n\t\t\tif raw, err := MarshalPacket(packet); err != nil {\n\t\t\t\tfmt.Println(\"Unable to marshal\")\n\t\t\t\tpanic(err)\n\t\t\t} else {\n\t\t\t\tif raw.Len() == 0 {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tfmt.Println(connection.conn.LocalAddr(), \"->\", connection.conn.RemoteAddr())\n\t\t\t\tfmt.Printf(\"ID=0x%04X, Size=%d, Total=%d\\n\", binary.BigEndian.Uint16(raw.Bytes()[0:2]), raw.Len(), raw.Len()+5)\n\t\t\t\tfmt.Println(hex.Dump(raw.Bytes()[2:]))\n\n\t\t\t\t_, _ = connection.conn.Write(Encrypt(raw))\n\t\t\t}\n\t\t}\n\t}\n}", "func (p *proxyGraphStore) Write(req *spb.WriteRequest) error {\n\terrors := make([]error, len(p.clients))\n\twg := new(sync.WaitGroup)\n\twg.Add(len(p.clients))\n\tfor idx, client := range p.clients {\n\t\tgo func(idx int, client GraphStore) {\n\t\t\tdefer wg.Done()\n\t\t\terrors[idx] = client.Write(req)\n\t\t}(idx, client)\n\t}\n\twg.Wait()\n\treturn lastError(proxyErrorPrefix, errors)\n}", "func (dht *FullRT) CheckPeers(ctx context.Context, peers ...peer.ID) (int, int) {\n\tctx, span := internal.StartSpan(ctx, \"FullRT.CheckPeers\", trace.WithAttributes(attribute.Int(\"NumPeers\", len(peers))))\n\tdefer span.End()\n\n\tvar peerAddrs chan interface{}\n\tvar total int\n\tif len(peers) == 0 {\n\t\tdht.peerAddrsLk.RLock()\n\t\ttotal = len(dht.peerAddrs)\n\t\tpeerAddrs = make(chan interface{}, total)\n\t\tfor k, v := range dht.peerAddrs {\n\t\t\tpeerAddrs <- peer.AddrInfo{\n\t\t\t\tID: k,\n\t\t\t\tAddrs: v,\n\t\t\t}\n\t\t}\n\t\tclose(peerAddrs)\n\t\tdht.peerAddrsLk.RUnlock()\n\t} else {\n\t\ttotal = len(peers)\n\t\tpeerAddrs = make(chan interface{}, total)\n\t\tdht.peerAddrsLk.RLock()\n\t\tfor _, p := range peers {\n\t\t\tpeerAddrs <- peer.AddrInfo{\n\t\t\t\tID: p,\n\t\t\t\tAddrs: dht.peerAddrs[p],\n\t\t\t}\n\t\t}\n\t\tclose(peerAddrs)\n\t\tdht.peerAddrsLk.RUnlock()\n\t}\n\n\tvar success uint64\n\n\tworkers(100, func(i interface{}) {\n\t\ta := i.(peer.AddrInfo)\n\t\tdialctx, dialcancel := context.WithTimeout(ctx, time.Second*3)\n\t\tif err := dht.h.Connect(dialctx, a); err == nil {\n\t\t\tatomic.AddUint64(&success, 1)\n\t\t}\n\t\tdialcancel()\n\t}, peerAddrs)\n\treturn int(success), total\n}", "func (state *State) IterPeers(avoid string, fct func(*Peer)) {\n\tstate.lock_peers.Lock()\n\tdefer state.lock_peers.Unlock()\n\tfor addr, peer := range state.known_peers {\n\t\tif avoid != addr {\n\t\t\tfct(peer)\n\t\t}\n\t}\n}", "func connectPeers(ctx context.Context, peers []*Peer) error {\n\tvar span opentracing.Span\n\tspan, ctx = opentracing.StartSpanFromContext(ctx, \"connectPeers\")\n\n\tvar wg sync.WaitGroup\n\tconnect := func(n *Peer, dst peer.ID, addr ma.Multiaddr) {\n\t\tlog.Debugf(\"dialing %s from %s\\n\", n.ID, dst)\n\n\t\tevt := log.EventBegin(ctx, \"DialPeer\", logging.LoggableMap{\n\t\t\t\"from\": n.ID.String(),\n\t\t\t\"to\": dst.String(),\n\t\t})\n\n\t\tn.Peerstore.AddAddr(dst, addr, pstore.PermanentAddrTTL)\n\t\tif _, err := n.Host.Network().DialPeer(ctx, dst); err != nil {\n\t\t\tlog.Errorf(\"error swarm dialing to peer\", err)\n\t\t\treturn\n\t\t}\n\n\t\tevt.Done()\n\t\twg.Done()\n\t}\n\n\tlog.Infof(\"Connecting swarms simultaneously.\")\n\tfor i, s1 := range peers {\n\t\tfor _, s2 := range peers[i+1:] {\n\t\t\twg.Add(1)\n\t\t\tconnect(s1, s2.Host.Network().LocalPeer(), s2.Host.Network().ListenAddresses()[0]) // try the first.\n\t\t}\n\t}\n\twg.Wait()\n\tspan.Finish()\n\n\t// for _, n := range peers {\n\t// \tlog.Debugf(\"%s swarm routing table: %s\\n\", n.ID, n.Peerstore.Peers())\n\t// }\n\treturn nil\n}", "func (rest *Restful) HandlerPeerList(w http.ResponseWriter, r *http.Request) {\n\n\tconnStatus := rest.server.PeerStatus()\n\tjs, err := json.Marshal(connStatus)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\trespSize, err := w.Write(js)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif respSize == 0 {\n\t\thttp.Error(w, fmt.Errorf(\"empty http respond\").Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}", "func (m *Model) PrintPeers() {\n\tPrintStatus(\"Peers: \" + strings.Join(m.GetPeersList(), \", \"))\n}", "func (c *UserClientWS) writePump() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.conn.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\n\t\t\t// Add queued chat messages to the current websocket message.\n\t\t\t/*n := len(c.send)\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\tw.Write(newline)\n\t\t\t\tw.Write(<-c.send)\n\t\t\t}*/\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *Switch) peersLoop(ctx context.Context) {\n\tfor {\n\t\tselect {\n\t\tcase <-s.morePeersReq:\n\t\t\tif s.isShuttingDown() {\n\t\t\t\treturn\n\t\t\t}\n\t\t\ts.logger.WithContext(ctx).Debug(\"loop: got morePeersReq\")\n\t\t\ts.askForMorePeers(ctx)\n\t\t// todo: try getting the connections (heartbeat)\n\t\tcase <-s.shutdownCtx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func (s *server) peerHandler() {\n\ts.addrManager.Start()\n\ts.syncManager.Start()\n\n\tlog.Printf(\"SERVER:Start peer handler\")\n\n\tstate := &peerState{\n\t\toutboundPeers: make(map[int32]*serverPeer),\n\t}\n\n\t// Add peers discovered through DNS to the address manager.\n\tconnmgr.SeedFromDNS(func(addrs []*wire.NetAddress) {\n\t\ts.addrManager.AddAddresses(addrs)\n\t})\n\n\tgo s.connManager.Start()\n\nout:\n\tfor {\n\t\tselect {\n\t\t// New peers connected to the server.\n\t\tcase p := <-s.newPeers:\n\t\t\ts.handleAddPeerMsg(state, p)\n\n\t\t\t// Disconnected peers.\n\t\tcase p := <-s.donePeers:\n\t\t\ts.handleDonePeerMsg(state, p)\n\n\t\tcase <-s.quit:\n\t\t\t// Disconnect all peers on server shutdown.\n\t\t\tfor _, sp := range state.outboundPeers {\n\t\t\t\tlog.Printf(\"SERVER:Shutdown peer %s\", sp)\n\t\t\t\tsp.Disconnect()\n\t\t\t}\n\t\t\tbreak out\n\t\t}\n\t}\n\n\ts.connManager.Stop()\n\ts.syncManager.Stop()\n\ts.addrManager.Stop()\n\n\t// Drain channels before exiting so nothing is left waiting around to send.\ncleanup:\n\tfor {\n\t\tselect {\n\t\tcase <-s.newPeers:\n\t\tcase <-s.donePeers:\n\t\tdefault:\n\t\t\tbreak cleanup\n\t\t}\n\t}\n\ts.wg.Done()\n\tlog.Printf(\"SERVER:Peer handler done\")\n}", "func (c *Client) WritePump() {\n\tlog.Println(\"WritePump Started\")\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tlog.Println(\"WritePump Ended\")\n\t\tticker.Stop()\n\t\tc.conn.Close()\n\t\tc.room.Done() // Anonymous WaitGroup\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tlog.Println(\"The hub closed the channel\")\n\t\t\t\tc.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\t\t\t//common.PrintJSON(message.(map[string]interface{}))\n\n\t\t\tw, err := c.conn.NextWriter(websocket.TextMessage) // Uses this instead of c.conn.WriteJSON to reuse Writer\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\twriteJSON(w, message)\n\n\t\t\t// Add queued chat messages to the current websocket message.\n\t\t\tn := len(c.send)\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\twriteJSON(w, <-c.send)\n\t\t\t}\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (w *chanWriter) Write(data []byte) (written int, err error) {\n\tfor len(data) > 0 {\n\t\tfor w.rwin < 1 {\n\t\t\twin, ok := <-w.win\n\t\t\tif !ok {\n\t\t\t\treturn 0, io.EOF\n\t\t\t}\n\t\t\tw.rwin += win\n\t\t}\n\t\tn := min(len(data), w.rwin)\n\t\tpeersId := w.clientChan.peersId\n\t\tpacket := []byte{\n\t\t\tmsgChannelData,\n\t\t\tbyte(peersId >> 24), byte(peersId >> 16), byte(peersId >> 8), byte(peersId),\n\t\t\tbyte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n),\n\t\t}\n\t\tif err = w.clientChan.writePacket(append(packet, data[:n]...)); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tdata = data[n:]\n\t\tw.rwin -= n\n\t\twritten += n\n\t}\n\treturn\n}", "func (s *Switch) publishNewPeer(peer p2pcrypto.PublicKey) {\n\ts.peerLock.RLock()\n\tfor _, p := range s.newPeerSub {\n\t\tselect {\n\t\tcase p <- peer:\n\t\tcase <-s.shutdownCtx.Done():\n\t\t}\n\t}\n\ts.peerLock.RUnlock()\n}", "func (c *Connection) writePump() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.conn.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\n\t\t\t// Add queued chat messages to the current websocket message.\n\t\t\tn := len(c.send)\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\tw.Write(<-c.send)\n\t\t\t}\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (g *Gossiper) ListenForPeers() {\n\tudpConn, err := net.ListenUDP(\"udp4\", g.udpAddr)\n\tif err != nil {\n\t\tfmt.Printf(\"Error: can't listen for peers on socket; %v\", err)\n\t\tos.Exit(-1)\n\t}\n\tg.udpConn = udpConn\n\n\tfmt.Printf(\"Listening for peer communication on port %d\\n\", g.udpAddr.Port)\n}", "func (px *Paxos) UpdatePeersDone(peer int, doneSeq int) {\n\tif doneSeq > px.peersDone[peer] {\n\t\tpx.peersDone[peer] = doneSeq\n\t}\n}", "func (client *Client) Write() {\n\tfor msg := range client.send {\n\t\tif err := client.socket.WriteJSON(msg); err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\t// close connection once finished.\n\tclient.socket.Close()\n}", "func (c *Client) writePump() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.conn.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\n\t\t\t// Add queued chat messages to the current websocket message.\n\t\t\tn := len(c.send)\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\tw.Write(newline)\n\t\t\t\tw.Write(<-c.send)\n\t\t\t}\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (h *handlerImpl) SendPeerList(cid common.CID, to net.Addr) (err error) {\n\tpeers := h.relay_peers.GetPeers(20)\n\tbuff := data.CreatePeerList(Version.Byte(), peers)\n\tpkt := comm.ResponsePacket(Version.Byte(), comm.OK, cid, buff)\n\n\t_, err = h.conn.WriteTo(pkt.Raw[:], to)\n\treturn\n}", "func (fs *Ipfs) connectToPeers(ctx context.Context, defaultCfg *config.Config) error {\n\taddrInfos := make(map[peer.ID]*peer.AddrInfo, len(fs.config.Peers))\n\tfor _, addrStr := range fs.config.Peers {\n\t\taddr, err := ma.NewMultiaddr(addrStr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tpii, err := peer.AddrInfoFromP2pAddr(addr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tpi, ok := addrInfos[pii.ID]\n\t\tif !ok {\n\t\t\tpi = &peer.AddrInfo{ID: pii.ID}\n\t\t\taddrInfos[pi.ID] = pi\n\t\t}\n\n\t\tpi.Addrs = append(pi.Addrs, pii.Addrs...)\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(len(addrInfos))\n\tfor _, addrInfo := range addrInfos {\n\t\tgo func(addrInfo *peer.AddrInfo) {\n\t\t\tdefer wg.Done()\n\t\t\terr := fs.coreAPI.Swarm().Connect(ctx, *addrInfo)\n\t\t\tif err != nil {\n\t\t\t\t// TODO get logger\n\t\t\t\tlog.Printf(\"failed to connect to %s: %s\", addrInfo.ID, err)\n\t\t\t}\n\t\t}(addrInfo)\n\t}\n\n\twg.Wait()\n\treturn nil\n}", "func (p *TCPPeer) writeLoop() {\n\t// clean up the connection.\n\tdefer func() {\n\t\tp.conn.Close()\n\t}()\n\n\tfor {\n\t\tmsg := <-p.send\n\n\t\tp.s.logger.Printf(\"OUT :: %s :: %+v\", msg.commandType(), msg.Payload)\n\n\t\t// should we disconnect here?\n\t\tif err := msg.encode(p.conn); err != nil {\n\t\t\tp.s.logger.Printf(\"encode error: %s\", err)\n\t\t}\n\t}\n}", "func savePeer(peer repository.Peer) {\n\tif peer.IpAddress == *nodeIp && peer.Port == *nodePort {\n\t\treturn\n\t}\n\tnodeKey := fmt.Sprintf(\"%v:%v\", *nodeIp, *nodePort)\n\tsqlRepository.SavePeer(nodeKey, peer.IpAddress, peer.Port)\n}", "func (s *Server) ConnectedPeers() []string {\n\ts.lock.RLock()\n\tdefer s.lock.RUnlock()\n\n\tpeers := make([]string, 0, len(s.peers))\n\tfor k := range s.peers {\n\t\tpeers = append(peers, k.PeerAddr().String())\n\t}\n\n\treturn peers\n}", "func (w *Writer) Connect(services protocol.ServiceFlag) error {\n\tif err := w.Handshake(services); err != nil {\n\t\t_ = w.Conn.Close()\n\t\treturn err\n\t}\n\n\tif config.Get().API.Enabled {\n\t\tgo func() {\n\t\t\tstore := capi.GetStormDBInstance()\n\t\t\taddr := w.Addr()\n\t\t\tpeerJSON := capi.PeerJSON{\n\t\t\t\tAddress: addr,\n\t\t\t\tType: \"Writer\",\n\t\t\t\tMethod: \"Connect\",\n\t\t\t\tLastSeen: time.Now(),\n\t\t\t}\n\n\t\t\terr := store.Save(&peerJSON)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"failed to save peerJSON into StormDB\")\n\t\t\t}\n\n\t\t\t// save count\n\t\t\tpeerCount := capi.PeerCount{\n\t\t\t\tID: addr,\n\t\t\t\tLastSeen: time.Now(),\n\t\t\t}\n\n\t\t\terr = store.Save(&peerCount)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"failed to save peerCount into StormDB\")\n\t\t\t}\n\t\t}()\n\t}\n\n\treturn nil\n}", "func (conn *Connection) WriteConn(parent context.Context, wsc config.WebSocketSettings, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\n\tif conn.done() {\n\t\treturn\n\t}\n\tconn.wGroup.Add(1)\n\tdefer func() {\n\t\tconn.wGroup.Done()\n\t\tutils.CatchPanic(\"connection.go WriteConn()\")\n\t}()\n\n\tticker := time.NewTicker(wsc.PingPeriod)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-parent.Done():\n\t\t\tfmt.Println(\"WriteConn done catched\")\n\t\t\treturn\n\t\tcase message, ok := <-conn.send:\n\n\t\t\t//fmt.Println(\"saw!\")\n\t\t\t//fmt.Println(\"server wrote:\", string(message))\n\t\t\tif !ok {\n\t\t\t\t//fmt.Println(\"errrrrr!\")\n\t\t\t\tconn.write(websocket.CloseMessage, []byte{}, wsc)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tstr := string(message)\n\t\t\tvar start, end, counter int\n\t\t\tfor i, s := range str {\n\t\t\t\tif s == '\"' {\n\t\t\t\t\tcounter++\n\t\t\t\t\tif counter == 3 {\n\t\t\t\t\t\tstart = i + 1\n\t\t\t\t\t} else if counter == 4 {\n\t\t\t\t\t\tend = i\n\t\t\t\t\t} else if counter > 4 {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif start != end {\n\t\t\t\tprint := str[start:end]\n\t\t\t\t//print = str\n\t\t\t\tfmt.Println(\"#\", conn.ID(), \" get that:\", print)\n\t\t\t}\n\n\t\t\tconn.ws.SetWriteDeadline(time.Now().Add(wsc.WriteWait))\n\t\t\tw, err := conn.ws.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tif err := conn.write(websocket.PingMessage, []byte{}, wsc); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (p *player) writePump() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tp.conn.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase <-p.disconnect:\n\t\t\t// Finish this goroutine to not to send messages anymore\n\t\t\treturn\n\t\tcase move, ok := <-p.sendMove: // Opponent moved a piece\n\t\t\tp.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tpayload := websocket.FormatCloseMessage(1001, \"\")\n\t\t\t\tp.conn.WriteMessage(websocket.CloseMessage, payload)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := p.conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(move)\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase msg, ok := <-p.sendChat: // Chat msg\n\t\t\tp.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tp.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif (msg.userId == p.userId) && (msg.Username == DEFAULT_USERNAME) {\n\t\t\t\tmsg.Username = \"you\"\n\t\t\t}\n\n\t\t\tmsgB, err := json.Marshal(msg)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Could not marshal data:\", err)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tw, err := p.conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Could not make next writer:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(msgB)\n\n\t\t\t// Add queued chat messages to the current websocket message.\n\t\t\tn := len(p.sendChat)\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\tmsg = <-p.sendChat\n\t\t\t\tif (msg.userId == p.userId) && (msg.Username == DEFAULT_USERNAME) {\n\t\t\t\t\tmsg.Username = \"you\"\n\t\t\t\t}\n\t\t\t\tmsgB, err := json.Marshal(msg)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(\"Could not marshal data:\", err)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tw.Write([]byte(newline))\n\t\t\t\tw.Write(msgB)\n\t\t\t}\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\tlog.Println(\"Could not close writer:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C: // ping\n\t\t\tp.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := p.conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\tlog.Println(\"Could not ping:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-p.clock.C: // Player ran out ouf time\n\t\t\t// Inform the opponent about this\n\t\t\tp.room.broadcastNoTime<- p.color\n\n\t\t\tdata := map[string]string{\n\t\t\t\t\"OOT\": \"MY_CLOCK\",\n\t\t\t}\n\t\t\tif err := sendTextMsg(data, p.conn); err != nil {\n\t\t\t\tlog.Println(\"Could not send text msg:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-p.oppRanOut: // Opponent ran out ouf time\n\t\t\tdata := map[string]string{\n\t\t\t\t\"OOT\": \"OPP_CLOCK\",\n\t\t\t}\n\t\t\tif err := sendTextMsg(data, p.conn); err != nil {\n\t\t\t\tlog.Println(\"Could not send text msg:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-p.drawOffer: // Opponent offered draw\n\t\t\tdata := map[string]string{\n\t\t\t\t\"drawOffer\": \"true\",\n\t\t\t}\n\t\t\tif err := sendTextMsg(data, p.conn); err != nil {\n\t\t\t\tlog.Println(\"Could not send text msg:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-p.oppAcceptedDraw: // opponent accepted draw\n\t\t\tdata := map[string]string{\n\t\t\t\t\"oppAcceptedDraw\": \"true\",\n\t\t\t}\n\t\t\tif err := sendTextMsg(data, p.conn); err != nil {\n\t\t\t\tlog.Println(\"Could not send text msg:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-p.oppResigned: // opponent resigned\n\t\t\tdata := map[string]string{\n\t\t\t\t\"oppResigned\": \"true\",\n\t\t\t}\n\t\t\tif err := sendTextMsg(data, p.conn); err != nil {\n\t\t\t\tlog.Println(\"Could not send text msg:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-p.rematchOffer: // Opponent offered rematch\n\t\t\tdata := map[string]string{\n\t\t\t\t\"rematchOffer\": \"true\",\n\t\t\t}\n\t\t\tif err := sendTextMsg(data, p.conn); err != nil {\n\t\t\t\tlog.Println(\"Could not send text msg:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-p.oppAcceptedRematch: // opponent accepted rematch\n\t\t\tdata := map[string]string{\n\t\t\t\t\"oppAcceptedRematch\": \"true\",\n\t\t\t}\n\t\t\tif err := sendTextMsg(data, p.conn); err != nil {\n\t\t\t\tlog.Println(\"Could not send text msg:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-p.oppReady: // opponent ready\n\t\t\tdata := map[string]string{\n\t\t\t\t\"oppReady\": \"true\",\n\t\t\t}\n\t\t\tif err := sendTextMsg(data, p.conn); err != nil {\n\t\t\t\tlog.Println(\"Could not send text msg:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-p.oppDisconnected: // opponent disconnected\n\t\t\tdata := map[string]string{\n\t\t\t\t\"waitingOpp\": \"true\",\n\t\t\t}\n\t\t\tif err := sendTextMsg(data, p.conn); err != nil {\n\t\t\t\tlog.Println(\"Could not send text msg:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-p.oppReconnected: // opponent reconnected\n\t\t\tdata := map[string]string{\n\t\t\t\t\"oppReady\": \"true\",\n\t\t\t}\n\t\t\tif err := sendTextMsg(data, p.conn); err != nil {\n\t\t\t\tlog.Println(\"Could not send text msg:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-p.oppGone: // opponent is gone\n\t\t\tdata := map[string]string{\n\t\t\t\t\"oppGone\": \"true\",\n\t\t\t}\n\t\t\tif err := sendTextMsg(data, p.conn); err != nil {\n\t\t\t\tlog.Println(\"Could not send text msg:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (s Server) connectToPeers(nodeList []string) {\n\tticker := time.NewTicker(PEER_CHECK * time.Millisecond)\n\tgo func() {\n\t\tfor _ = range ticker.C {\n\t\t\ts.tryToConnectToPeers(nodeList)\n\t\t}\n\t}()\n}", "func ConnectivityWrite(ctx Context, results types.ConnectivityResults) error {\n\trender := func(format func(subContext subContext) error) error {\n\t\tswitch ctx.Trunc {\n\t\tcase true:\n\t\t\tif err := format(&connectivityContext{ok: results.IsOK()}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase false:\n\t\t\tfor _, cr := range results {\n\t\t\t\tif err := format(&connectivityContext{result: cr}); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\treturn ctx.Write(&connectivityContext{}, render)\n}", "func (c *client) writePump() {\n\tticker := time.NewTicker(pingPeriod)\n\n\t// this will be executed on function exit\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.ws.Close()\n\t}()\n\n\t// loop running in coroutine\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\t// if something was wrong with message close connection\n\t\t\tif !ok {\n\t\t\t\tc.write(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err := c.ws.WriteJSON(message); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// if everything went fine increase life time of connection\n\t\t\tc.ws.SetWriteDeadline(time.Now().Add(writeWait))\n\n\t\t// send ping messages to connection\n\t\tcase <-ticker.C:\n\t\t\tif err := c.write(websocket.PingMessage, []byte{}); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *Switch) publishDelPeer(peer p2pcrypto.PublicKey) {\n\ts.peerLock.RLock()\n\tfor _, p := range s.delPeerSub {\n\t\tselect {\n\t\tcase p <- peer:\n\t\tcase <-s.shutdownCtx.Done():\n\t\t}\n\t}\n\ts.peerLock.RUnlock()\n}", "func (o *MacpoolPoolMemberAllOf) SetPeer(v MacpoolLeaseRelationship) {\n\to.Peer = &v\n}", "func (consensus *Consensus) AddPeers(peers []*p2p.Peer) int {\n\tcount := 0\n\n\tfor _, peer := range peers {\n\t\t_, ok := consensus.validators.Load(utils.GetUniqueIDFromPeer(*peer))\n\t\tif !ok {\n\t\t\tif peer.ValidatorID == -1 {\n\t\t\t\tpeer.ValidatorID = int(consensus.uniqueIDInstance.GetUniqueID())\n\t\t\t}\n\t\t\tconsensus.validators.Store(utils.GetUniqueIDFromPeer(*peer), *peer)\n\t\t\tconsensus.pubKeyLock.Lock()\n\t\t\tconsensus.PublicKeys = append(consensus.PublicKeys, peer.PubKey)\n\t\t\tconsensus.pubKeyLock.Unlock()\n\t\t\tutils.GetLogInstance().Debug(\"[SYNC] new peer added\", \"pubKey\", peer.PubKey, \"ip\", peer.IP, \"port\", peer.Port)\n\t\t}\n\t\tcount++\n\t}\n\treturn count\n}", "func (oc *OAuth2ClientCreate) SetTrustedPeers(s []string) *OAuth2ClientCreate {\n\toc.mutation.SetTrustedPeers(s)\n\treturn oc\n}", "func (pl *Peerlist) Save(dir string) error {\n\tpl.lock.RLock()\n\tdefer pl.lock.RUnlock()\n\n\tfilename := PeerDatabaseFilename\n\tfn := filepath.Join(dir, filename)\n\n\t// filter the peers that has retrytime > 10\n\tpeers := make(map[string]PeerJSON)\n\tfor k, p := range pl.peers {\n\t\tif p.RetryTimes <= 10 {\n\t\t\tpeers[k] = NewPeerJSON(*p)\n\t\t}\n\t}\n\n\terr := file.SaveJSON(fn, peers, 0600)\n\tif err != nil {\n\t\tlogger.Notice(\"SavePeerList Failed: %v\", err)\n\t}\n\n\treturn err\n}", "func (c *Client) writePump() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.conn.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\n\t\t\t//// Add queued chat messages to the current websocket message.\n\t\t\t//n := len(c.send)\n\t\t\t//for i := 0; i < n; i++ {\n\t\t\t//\tw.Write(newline)\n\t\t\t//\tw.Write(<-c.send)\n\t\t\t//}\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func TestPeerManagerOutboundSave(t *testing.T) {\n\tif testing.Short() {\n\t\tt.SkipNow()\n\t}\n\tt.Parallel()\n\n\t// Create enough gateways so that every gateway should automatically end up\n\t// with every other gateway as an outbound peer.\n\tvar gs []*Gateway\n\tfor i := 0; i < wellConnectedThreshold+1; i++ {\n\t\tgs = append(gs, newNamedTestingGateway(t, strconv.Itoa(i)))\n\t}\n\t// Connect g1 to each peer. This should be enough that every peer eventually\n\t// has the full set of outbound peers.\n\tfor _, g := range gs[1:] {\n\t\tif err := gs[0].Connect(g.Address()); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\n\t// Block until every peer has wellConnectedThreshold outbound peers.\n\terr := build.Retry(100, time.Millisecond*200, func() error {\n\t\tfor _, g := range gs {\n\t\t\tvar outboundNodes, outboundPeers int\n\t\t\tg.mu.RLock()\n\t\t\tfor _, node := range g.nodes {\n\t\t\t\tif node.WasOutboundPeer {\n\t\t\t\t\toutboundNodes++\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, peer := range g.peers {\n\t\t\t\tif !peer.Inbound {\n\t\t\t\t\toutboundPeers++\n\t\t\t\t}\n\t\t\t}\n\t\t\tg.mu.RUnlock()\n\t\t\tif outboundNodes < wellConnectedThreshold {\n\t\t\t\treturn errors.New(\"not enough outbound nodes: \" + strconv.Itoa(outboundNodes))\n\t\t\t}\n\t\t\tif outboundPeers < wellConnectedThreshold {\n\t\t\t\treturn errors.New(\"not enough outbound peers: \" + strconv.Itoa(outboundPeers))\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func (s *Status) Peers(args *structs.GenericRequest, reply *[]string) error {\n\tif args.Region == \"\" {\n\t\targs.Region = s.srv.config.Region\n\t}\n\tif done, err := s.srv.forward(\"Status.Peers\", args, args, reply); done {\n\t\treturn err\n\t}\n\n\tfuture := s.srv.raft.GetConfiguration()\n\tif err := future.Error(); err != nil {\n\t\treturn err\n\t}\n\n\tfor _, server := range future.Configuration().Servers {\n\t\t*reply = append(*reply, string(server.Address))\n\t}\n\treturn nil\n}", "func (connectionHandler *ConnectionHandler) broadcastToPeers(packet *ExtendedGossipPacket, peers []*net.UDPAddr) {\n\t//peers := gossiper.GetPeersAtomic()\n\tfor _, peer := range peers {\n\t\tif peer.String() != packet.SenderAddr.String() {\n\t\t\tconnectionHandler.sendPacket(packet.Packet, peer)\n\t\t}\n\t}\n}", "func (c *Client) writePump() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.ws.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\t// spew.Dump(c.clientID)\n\t\t\tc.ws.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.ws.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.ws.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\n\t\t\t// Add queued chat messages to the current websocket message.\n\t\t\tn := len(c.send)\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\tw.Write(newline)\n\t\t\t\tw.Write(<-c.send)\n\t\t\t}\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.ws.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.ws.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (sp *SyncProtocol) createOutboundWriter(ws *WrappedStream) error {\n\n\t// create stan connection with random client id\n\tpid := string(ws.remotePeerID())\n\tsc, err := NSSConnection(pid)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo func() {\n\t\terrc := make(chan error)\n\t\tdefer close(errc)\n\t\tdefer sc.Close()\n\n\t\t// main message sending routine\n\t\tsub, err := sc.Subscribe(\"feed\", func(m *stan.Msg) {\n\n\t\t\tsendMessage := true\n\n\t\t\t// get the block from the feed\n\t\t\tblk := DeserializeBlock(m.Data)\n\n\t\t\t// log.Printf(\"\\n\\n\\tauthor: %s\\n\\tremote-peer: %s\", blk.Author, ws.remotePeerID())\n\n\t\t\t// don't send if created by the remote peer\n\t\t\tif blk.Author == ws.remotePeerID() {\n\t\t\t\tsendMessage = false\n\t\t\t\t// log.Println(\"author is remote peer sendmessage:\", sendMessage)\n\t\t\t}\n\n\t\t\t// log.Printf(\"\\n\\n\\tsender: %s\\n\\tremote-peer: %s\", blk.Sender, ws.remotePeerID())\n\t\t\t// don't send if it came from the reomote peer\n\t\t\tif blk.Sender == ws.remotePeerID() {\n\t\t\t\tsendMessage = false\n\t\t\t\t// log.Println(\"sender is remote peer sendmessage:\", sendMessage)\n\t\t\t}\n\n\t\t\t// don't send if the remote peer has seen it before\n\t\t\tif sendMessage {\n\t\t\t\tblk.Receiver = ws.remotePeerID()\n\t\t\t\tif sp.node.msgCMS.Estimate(blk.CmsKey()) > 0 {\n\t\t\t\t\tsendMessage = false\n\t\t\t\t\t// log.Println(\"message:\", blk.BlockId, \" already sent to:\", ws.remotePeerID(), \" sendmaessage:\", sendMessage)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif sendMessage {\n\t\t\t\t// update the sender\n\t\t\t\tblk.Sender = ws.localPeerID()\n\t\t\t\tsendErr := sendBlock(blk, ws)\n\t\t\t\tif sendErr != nil {\n\t\t\t\t\tlog.Println(\"cannot send message to peer: \", sendErr)\n\t\t\t\t\terrc <- sendErr\n\t\t\t\t}\n\t\t\t\t// register that we've sent this message to this peer\n\t\t\t\tsp.node.msgCMS.Update(blk.CmsKey(), 1)\n\t\t\t}\n\n\t\t}, stan.DeliverAllAvailable())\n\t\tif err != nil {\n\t\t\tlog.Println(\"error creating feed subscription: \", err)\n\t\t\treturn\n\t\t}\n\n\t\t// wait for errors on writing, such as stream closing\n\t\t<-errc\n\t\tsub.Close()\n\t}()\n\n\treturn nil\n}", "func (c *Client) writeRoutine() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.conn.Close()\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.conn.WriteMessage(ws.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.conn.NextWriter(ws.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tmsg, err := json.Marshal(message)\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"error:\", err)\n\t\t\t}\n\n\t\t\tw.Write(msg)\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.conn.WriteMessage(ws.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (client *Client) Write() {\n\t// for each message in the outgoing channel\n\tfor data := range client.outgoing {\n\t\t// write the message to the buffer and flush\n\t\tclient.writer.WriteString(data)\n\t\tclient.writer.Flush()\n\t}\n}", "func (client *Client) write() {\n\tfor data := range client.Outgoing {\n\t\tclient.writer.WriteString(data)\n\t\tclient.writer.Flush()\n\t}\n}", "func (a *Agent) disconnectPeers(ctx context.Context) error {\n\tpeers, err := a.EthNode.Peers(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, node := range peers {\n\t\tif err := a.EthNode.DisconnectPeer(ctx, node.ID); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (g Gossiper) PrintPeers() {\n\tpeersSlice := g.peers.GetSlice()\n\tfmt.Println(strings.Join(peersSlice, \",\"))\n}", "func (c *Client) writePump() {\n\tticker := time.NewTicker(PingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.Conn.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.Send:\n\t\t\tc.Conn.SetWriteDeadline(time.Now().Add(WriteWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.Conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.Conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.Conn.SetWriteDeadline(time.Now().Add(WriteWait))\n\t\t\tif err := c.Conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *Service) processPeers() {\n\n\t// Obtain exclusive access to the map.\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\t// Avoid repeated calls to time.Now() by invoking it once here.\n\tcurTime := time.Now()\n\n\tfor id, peer := range s.peers {\n\t\tif peer.IsExpired(s.config.PeerTimeout, curTime) {\n\n\t\t\t// Send the peer ID over the PeerRemoved channel and remove it.\n\t\t\ts.PeerRemoved <- id\n\t\t\tdelete(s.peers, id)\n\t\t}\n\t}\n}", "func (c *connection) WritePump() {\r\n\tticker := time.NewTicker(pingPeriod)\r\n\tdefer func() {\r\n\t\tticker.Stop()\r\n\t\tc.ws.Close()\r\n\t}()\r\n\tfor {\r\n\t\tselect {\r\n\t\tcase message, ok := <-c.send:\r\n\t\t\tif !ok {\r\n\t\t\t\tc.Write(websocket.CloseMessage, []byte{})\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\t\t\tif err := c.Write(websocket.TextMessage, message); err != nil {\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\t\tcase <-ticker.C:\r\n\t\t\tif err := c.Write(websocket.PingMessage, []byte{}); err != nil {\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "func (c *Client) writePump() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tfmt.Println(\"Closing writePump\")\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tif !c.isAlive {\n\t\t\t\tfmt.Printf(\"Channel closed\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\n\t\t\t// Add queued chat messages to the current websocket message.\n\t\t\tn := len(c.send)\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\tw.Write(newline)\n\t\t\t\tw.Write(<-c.send)\n\t\t\t}\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (this *BlockSyncMgr) pingOutsyncNodes(curHeight uint32) {\n\tpeers := make([]*peer.Peer, 0)\n\tthis.lock.RLock()\n\tmaxHeight := curHeight\n\tfor id := range this.nodeWeights {\n\t\tpeer := this.server.getNode(id)\n\t\tif peer == nil {\n\t\t\tcontinue\n\t\t}\n\t\tpeerHeight := uint32(peer.GetHeight())\n\t\tif peerHeight >= maxHeight {\n\t\t\tmaxHeight = peerHeight\n\t\t}\n\t\tif peerHeight < curHeight {\n\t\t\tpeers = append(peers, peer)\n\t\t}\n\t}\n\tthis.lock.RUnlock()\n\tif curHeight > maxHeight-SYNC_MAX_HEIGHT_OFFSET && len(peers) > 0 {\n\t\tthis.server.pingTo(peers)\n\t}\n}", "func (c *Client) WriteJSON() {\n\tdefer func() {\n\t\tc.Conn.Close()\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tif !ok {\n\t\t\t\tc.Conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tc.Conn.WriteJSON(message)\n\t\t}\n\t}\n}", "func (mph *MockPeerHandler) GetPeers() []peer2.AddrInfo {\n\treturn nil\n}", "func (n *QriNode) ConnectedPeers() []string {\n\tconns := n.Host.Network().Conns()\n\tpeers := make([]string, len(conns))\n\tfor i, c := range conns {\n\t\tpeers[i] = c.RemotePeer().Pretty()\n\t}\n\n\treturn peers\n}", "func (c *Cache) Peers(peers PeerPicker) *Cache {\n\tc.peers = peers\n\treturn c\n}", "func (t *teeWriteSyncer) Write(p []byte) (int, error) {\n\tvar errs multiError\n\tnWritten := 0\n\tfor _, w := range t.writeSyncers {\n\t\tn, err := w.Write(p)\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t\tif nWritten == 0 && n != 0 {\n\t\t\tnWritten = n\n\t\t} else if n < nWritten {\n\t\t\tnWritten = n\n\t\t}\n\t}\n\treturn nWritten, errs.asError()\n}", "func (s *server) Peers() []*peer {\n\tresp := make(chan []*peer, 1)\n\n\ts.queries <- &listPeersMsg{resp}\n\n\treturn <-resp\n}", "func (n *P2P) ActivePeers() int {\n\treturn n.connManager.GetInfo().ConnCount\n}", "func writeConnections(cmd *cobra.Command, connectionName string) error {\n\tfmt.Fprintf(cmd.OutOrStdout(), \"writing connections to base directory [%s]\\n\", landscapeDir)\n\n\toutput := strings.ToUpper(bite.GetOutPutFlag(cmd))\n\n\tif connectionName != \"\" {\n\t\tconnection, err := config.Client.GetConnection(connectionName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfileName := fmt.Sprintf(\"connection-%s-%s.%s\", strings.ToLower(strings.ReplaceAll(connection.Name, \" \", \"_\")), connection.Name, strings.ToLower(output))\n\t\treturn utils.WriteFile(landscapeDir, pkg.ConnectionsFilePath, fileName, output, connection)\n\t}\n\n\tconnections, err := config.Client.GetConnections()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, connection := range connections {\n\t\tconnectionComplete, err := config.Client.GetConnection(connection.Name)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfileName := fmt.Sprintf(\"connection-%s-%s.%s\", strings.ToLower(strings.ReplaceAll(connection.Name, \" \", \"_\")), connection.Name, strings.ToLower(output))\n\t\terr = utils.WriteFile(landscapeDir, pkg.ConnectionsFilePath, fileName, output, connectionComplete)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not export connection to file %s\", fileName)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (tracker *PeerTracker) updatePeers(ctx context.Context, ps ...peer.ID) error {\n\tif tracker.updateFn == nil {\n\t\treturn errors.New(\"canot call PeerTracker peer update logic without setting an update function\")\n\t}\n\tif len(ps) == 0 {\n\t\tlogPeerTracker.Info(\"update peers aborting: no peers to update\")\n\t\treturn nil\n\t}\n\n\tvar updateErrs uint64\n\tgrp, ctx := errgroup.WithContext(ctx)\n\tfor _, p := range ps {\n\t\tpeer := p\n\t\tgrp.Go(func() error {\n\t\t\tci, err := tracker.updateFn(ctx, peer)\n\t\t\tif err != nil {\n\t\t\t\tatomic.AddUint64(&updateErrs, 1)\n\t\t\t\treturn errors.Wrapf(err, \"failed to update peer=%s\", peer.Pretty())\n\t\t\t}\n\t\t\ttracker.Track(ci)\n\t\t\treturn nil\n\t\t})\n\t}\n\t// check if anyone failed to update\n\tif err := grp.Wait(); err != nil {\n\t\t// full failure return an error\n\t\tif updateErrs == uint64(len(ps)) {\n\t\t\tlogPeerTracker.Errorf(\"failed to update all %d peers: %s\", len(ps), err)\n\t\t\treturn errors.New(\"all peers failed to update\")\n\t\t}\n\t\t// partial failure\n\t\tlogPeerTracker.Infof(\"failed to update %d of %d peers: %s\", updateErrs, len(ps), err)\n\t}\n\treturn nil\n}", "func ConnCloseWrite(c *tls.Conn,) error", "func (node *hostNode) CountPeers(id protocol.ID) int {\n\tcount := 0\n\tfor _, n := range node.host.Peerstore().Peers() {\n\t\tif sup, err := node.host.Peerstore().SupportsProtocols(n, string(id)); err != nil && len(sup) != 0 {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count\n}", "func (v *vncKBPlayback) writeEvents() {\n\tdefer v.Conn.Close()\n\n\tfor e := range v.out {\n\t\tif err := e.Write(v.Conn); err != nil {\n\t\t\tlog.Error(\"unable to write vnc event: %v\", err)\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// stop ourselves in a separate goroutine to avoid a deadlock\n\tgo v.Stop()\n\n\tfor range v.out {\n\t\t// drain the channel\n\t}\n}", "func (m *Mock) Connected(_ context.Context, peer p2p.Peer, _ bool) error {\n\tm.mtx.Lock()\n\tm.peers = append(m.peers, peer.Address)\n\tm.mtx.Unlock()\n\tm.Trigger()\n\treturn nil\n}", "func (c *Client) writePump() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tlog.Println(\"Closing write pump\", c.id)\n\t\tticker.Stop()\n\t\tc.ws.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tlog.Println(\"Hub closed channel\", c.id)\n\t\t\t\tc.write(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Println(\"Writing message\", c.id)\n\t\t\tc.ws.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.ws.WriteJSON(message); err != nil {\n\t\t\t\tlog.Println(\"Error writing message\", c.id, err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tlog.Println(\"Tick\", c.id)\n\t\t\tc.ws.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.write(websocket.PingMessage, []byte{}); err != nil {\n\t\t\t\tlog.Println(\"Could not ping client\", c.id)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *Client) writePump() {\n\tticker := time.NewTicker(c.Server.Config.PingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\t_ = c.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\t_ = c.Conn.SetWriteDeadline(time.Now().Add(c.Server.Config.WriteWait))\n\t\t\tif !ok {\n\t\t\t\t_ = c.Conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\tlog.Error(\"Socket closed\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif err := c.Conn.WriteMessage(websocket.TextMessage, message.Payload); err != nil {\n\t\t\t\tlog.Error(\"Socket error: \", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\t_ = c.Conn.SetWriteDeadline(time.Now().Add(c.Server.Config.WriteWait))\n\t\t\tif err := c.Conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\tlog.Error(\"Socket error: \", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *client) write() {\n\tfor {\n\t\ttoWrite := <-c.send\n\t\t_ = c.conn.WriteMessage(websocket.BinaryMessage, toWrite)\n\t}\n}", "func (gs *Service) writeToSocket(client Client) {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\t_ = client.Conn.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-client.Send:\n\t\t\t_ = client.Conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\t_ = client.Conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := client.Conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlogger.Info(\"writing message..\")\n\t\t\t_, _ = w.Write(message)\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\t_ = client.Conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := client.Conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func writeTransactions(ctx context.Context, t *text.Text, connectionSignal <-chan string) {\n\tport := *givenPort\n\tsocket := gowebsocket.New(\"ws://localhost:\" + port + \"/websocket\")\n\n\tsocket.OnTextMessage = func(message string, socket gowebsocket.Socket) {\n\t\tcurrentTx := gjson.Get(message, \"result.data.value.TxResult.result.log\")\n\t\tcurrentTime := time.Now()\n\t\tif currentTx.String() != \"\" {\n\t\t\tif err := t.Write(fmt.Sprintf(\"%s\\n\", currentTime.Format(\"2006-01-02 03:04:05 PM\")+\"\\n\"+currentTx.String())); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t}\n\n\tsocket.Connect()\n\n\tsocket.SendText(\"{ \\\"jsonrpc\\\": \\\"2.0\\\", \\\"method\\\": \\\"subscribe\\\", \\\"params\\\": [\\\"tm.event='Tx'\\\"], \\\"id\\\": 2 }\")\n\n\tfor {\n\t\tselect {\n\t\tcase s := <-connectionSignal:\n\t\t\tif s == \"no_connection\" {\n\t\t\t\tsocket.Close()\n\t\t\t}\n\t\t\tif s == \"reconnect\" {\n\t\t\t\twriteTransactions(ctx, t, connectionSignal)\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\tlog.Println(\"interrupt\")\n\t\t\tsocket.Close()\n\t\t\treturn\n\t\t}\n\t}\n}", "func (c *connection) writePump() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.ws.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tif !ok {\n\t\t\t\tc.write(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err := c.write(websocket.TextMessage, message); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tif err := c.write(websocket.PingMessage, []byte{}); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *Client) writePump() {\n\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.Connexion.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.Send:\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.SendMessage([]byte(\"{\\\"status\\\":\\\"error\\\",\\\"data\\\":\\\"Could not transfer the message\\\"}\"))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tc.SendMessage(message)\n\n\t\tcase <-ticker.C:\n\t\t\tc.Connexion.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.Connexion.WriteMessage(websocket.PingMessage, []byte{}); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (etcd *EtcdSource) Write(nodes map[string]Node) error {\n\tif etcd.writeChan == nil {\n\t\tetcd.writeChan = make(chan map[string]Node)\n\t\tetcd.flushChan = make(chan error)\n\n\t\tgo etcd.writer()\n\t}\n\n\tetcd.writeChan <- nodes\n\n\t// XXX: errors?\n\treturn nil\n}" ]
[ "0.6179806", "0.5627001", "0.55154735", "0.5345452", "0.5255786", "0.5245747", "0.50822175", "0.506212", "0.5045233", "0.5042398", "0.50127894", "0.49541664", "0.49517417", "0.49243873", "0.4913741", "0.49083865", "0.49018", "0.48422354", "0.48224813", "0.47768983", "0.47719437", "0.47679925", "0.4763562", "0.47545108", "0.47394744", "0.47052655", "0.47048992", "0.4677923", "0.4669746", "0.46628904", "0.46596682", "0.46402046", "0.46389872", "0.46382403", "0.4617096", "0.4590057", "0.45798057", "0.45797658", "0.45779154", "0.4575777", "0.45704103", "0.4560849", "0.455988", "0.45521894", "0.45474184", "0.45413414", "0.45411023", "0.4534477", "0.45219463", "0.4514437", "0.4508913", "0.45059478", "0.4504946", "0.45002967", "0.4493574", "0.4487336", "0.44772583", "0.4470282", "0.44676185", "0.44645822", "0.44591236", "0.4451531", "0.44451", "0.44406423", "0.4439224", "0.443665", "0.44354922", "0.44335476", "0.44247374", "0.44237736", "0.44204837", "0.4413824", "0.4411263", "0.44104868", "0.44086692", "0.44060156", "0.43989196", "0.43903455", "0.43783835", "0.4375767", "0.43677348", "0.43579182", "0.43527555", "0.4349891", "0.4346825", "0.4346202", "0.43433774", "0.43420857", "0.4340179", "0.4329031", "0.43273383", "0.43260425", "0.4323184", "0.43152368", "0.43129525", "0.4312843", "0.4311155", "0.42987278", "0.4292085", "0.4289191" ]
0.7081264
0
writeTransactions writes the latest Transactions to the transactionsWidget. Exits when the context expires.
func writeTransactions(ctx context.Context, t *text.Text, connectionSignal <-chan string) { port := *givenPort socket := gowebsocket.New("ws://localhost:" + port + "/websocket") socket.OnTextMessage = func(message string, socket gowebsocket.Socket) { currentTx := gjson.Get(message, "result.data.value.TxResult.result.log") currentTime := time.Now() if currentTx.String() != "" { if err := t.Write(fmt.Sprintf("%s\n", currentTime.Format("2006-01-02 03:04:05 PM")+"\n"+currentTx.String())); err != nil { panic(err) } } } socket.Connect() socket.SendText("{ \"jsonrpc\": \"2.0\", \"method\": \"subscribe\", \"params\": [\"tm.event='Tx'\"], \"id\": 2 }") for { select { case s := <-connectionSignal: if s == "no_connection" { socket.Close() } if s == "reconnect" { writeTransactions(ctx, t, connectionSignal) } case <-ctx.Done(): log.Println("interrupt") socket.Close() return } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client *Client) WriteTransaction(write TransactionCallback) error {\n\n\t// Start write transaction.\n\tif tx, err := client.Db.Begin(true); err != nil {\n\t\treturn errors.WithStack(err)\n\t} else {\n\t\tsuccess := false\n\t\tdefer DeferRollback(tx, &success)\n\n\t\tif err = write(tx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err = tx.Commit(); err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t} else {\n\t\t\tsuccess = true\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (api *API) getTransactions(w http.ResponseWriter, req *http.Request) {\n\ttransactions, err := transaction.GetAllTransactions(api.db)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tpayload, _ := json.Marshal(transactions)\n\tw.Write(payload)\n}", "func (store *MemoryTxStore) SaveTransaction(tx *types.Transaction) (err error) {\n\tstore.mutex.Lock()\n\tdefer store.mutex.Unlock()\n\n\ttimedtx := &TimestampedTransaction{tx, store.clock.Now().Unix()}\n\tfor e := store.transactions.Front(); e != nil; e = e.Next() {\n\t\tif e.Value.(*TimestampedTransaction).Nonce() > tx.Nonce() {\n\t\t\tstore.transactions.InsertBefore(timedtx, e)\n\t\t\treturn\n\t\t}\n\t}\n\n\tstore.transactions.PushBack(timedtx)\n\treturn\n}", "func (srv *Server) walletTransactionsHandler(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\t// Get the start and end blocks.\n\tstart, err := strconv.Atoi(req.FormValue(\"startheight\"))\n\tif err != nil {\n\t\twriteError(w, \"error after call to /wallet/transactions: \"+err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tend, err := strconv.Atoi(req.FormValue(\"endheight\"))\n\tif err != nil {\n\t\twriteError(w, \"error after call to /wallet/transactions: \"+err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tconfirmedTxns, err := srv.wallet.Transactions(types.BlockHeight(start), types.BlockHeight(end))\n\tif err != nil {\n\t\twriteError(w, \"error after call to /wallet/transactions: \"+err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tunconfirmedTxns := srv.wallet.UnconfirmedTransactions()\n\n\twriteJSON(w, WalletTransactionsGET{\n\t\tConfirmedTransactions: confirmedTxns,\n\t\tUnconfirmedTransactions: unconfirmedTxns,\n\t})\n}", "func (s *StatsPeriodStore) Transaction(callback func(*StatsPeriodStore) error) error {\n\tif callback == nil {\n\t\treturn kallax.ErrInvalidTxCallback\n\t}\n\n\treturn s.Store.Transaction(func(store *kallax.Store) error {\n\t\treturn callback(&StatsPeriodStore{store})\n\t})\n}", "func (t *Transactions) Close() error {\n\tdefer t.lock.Unlock()\n\tt.lock.Lock()\n\tif t.closed {\n\t\treturn ErrorTransactionsAlreadyClosed\n\t}\n\n\tt.closed = true\n\tfor key, responses := range t.pending {\n\t\tdelete(t.pending, key)\n\t\tclose(responses)\n\t}\n\n\treturn nil\n}", "func (tx *transaction) close() {\n\ttx.closed = true\n\n\t// Clear pending blocks that would have been written on commit.\n\ttx.pendingBlocks = nil\n\ttx.pendingBlockData = nil\n\n\t// Clear pending keys that would have been written or deleted on commit.\n\ttx.pendingKeys = nil\n\ttx.pendingRemove = nil\n\n\t// Release the snapshot.\n\tif tx.snapshot != nil {\n\t\ttx.snapshot.Release()\n\t\ttx.snapshot = nil\n\t}\n\n\ttx.db.closeLock.RUnlock()\n\n\t// Release the writer lock for writable transactions to unblock any\n\t// other write transaction which are possibly waiting.\n\tif tx.writable {\n\t\ttx.db.writeLock.Unlock()\n\t}\n}", "func (self* userRestAPI) transactions(w http.ResponseWriter, r *http.Request) {\n\n\t// Read arguments\n\tband,number,err := self.extractBandAndNumber(r)\n\tif err != nil {\n\t\tlogError(err)\n\t\thttp.Error(w, fmt.Sprintf(\"\\nFailed to parse arguments '%s'\\n\",err), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// Retrieve transactions for specified traveller\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\thistory,err := self.engine.TransactionsAsJSON(band,number)\n\tif err != nil {\n\t\tlogError(err)\n\t\thttp.Error(w, fmt.Sprintf(\"\\nFailed to retrieve transaction history with error '%s'\\n\",err), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tio.WriteString(w,history)\n\n}", "func Transaction(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tt, ctx := orm.NewTransaction(r.Context())\n\t\tdefer func() {\n\t\t\tif rec := recover(); rec != nil {\n\t\t\t\tt.Rollback()\n\t\t\t\t// Panic to let recoverer handle 500\n\t\t\t\tpanic(rec)\n\t\t\t} else {\n\t\t\t\terr := t.Commit()\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t}\n\treturn http.HandlerFunc(fn)\n}", "func WriteTransList(chain uint64, transList []Hash) error {\n\thk := GetHashOfTransList(transList)\n\tdata := TransListToBytes(transList)\n\treturn runtime.AdminDbSet(dbTransList{}, chain, hk[:], data, 2<<50)\n}", "func (m *BarRecordMutation) SetTransactions(i int32) {\n\tm.transactions = &i\n\tm.addtransactions = nil\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigSession) Transactions(arg0 *big.Int) (struct {\n\tDestination common.Address\n\tValue *big.Int\n\tData []byte\n\tExecuted bool\n}, error) {\n\treturn _ReserveSpenderMultiSig.Contract.Transactions(&_ReserveSpenderMultiSig.CallOpts, arg0)\n}", "func (c *Controller) generateTransactions(stopCh <-chan struct{}) {\n\ttransactionSize := 0\n\tparentCxt, parentCancel := context.WithCancel(context.Background())\n\tdefer parentCancel()\n\n\tctx := parentCxt\n\tvar cancel context.CancelFunc\n\n\tcommitTransaction := func() {\n\t\ttransactionSize = 0\n\t\tctx = parentCxt\n\t\tif err := c.ddlogProgram.CommitTransaction(); err != nil {\n\t\t\tklog.Errorf(\"Error when committing DDLog transaction: %v\", err)\n\t\t}\n\t}\n\n\thandleCommand := func(cmd ddlog.Command) {\n\t\tklog.V(2).Infof(\"Handling command\")\n\t\tif transactionSize == 0 {\n\t\t\t// start transaction\n\t\t\tif err := c.ddlogProgram.StartTransaction(); err != nil {\n\t\t\t\tklog.Errorf(\"Error when starting DDLog transaction: %v\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx, cancel = context.WithTimeout(parentCxt, maxTransactionDelay)\n\t\t}\n\t\t// add to transaction\n\t\tif err := c.ddlogProgram.ApplyUpdates(cmd); err != nil {\n\t\t\tklog.Errorf(\"Error when applying updates with DDLog: %v\", err)\n\t\t\treturn\n\t\t}\n\t\ttransactionSize++\n\t\tif transactionSize >= maxUpdatesPerTransaction {\n\t\t\tcancel()\n\t\t\tcommitTransaction()\n\t\t}\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase cmd := <-c.ddlogUpdatesCh:\n\t\t\thandleCommand(cmd)\n\t\tcase <-ctx.Done():\n\t\t\tcommitTransaction()\n\t\tcase <-stopCh:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (r *dsState) CommitTransaction(c context.Context) error {\n\treturn r.run(c, func() error { return nil })\n}", "func (tx *transaction) writePendingAndCommit() error {\n\t// Save the current block store write position for potential rollback.\n\t// These variables are only updated here in this function and there can\n\t// only be one write transaction active at a time, so it's safe to store\n\t// them for potential rollback.\n\twc := tx.db.store.writeCursor\n\twc.RLock()\n\toldBlkFileNum := wc.curFileNum\n\toldBlkOffset := wc.curOffset\n\twc.RUnlock()\n\n\t// rollback is a closure that is used to rollback all writes to the\n\t// block files.\n\trollback := func() {\n\t\t// Rollback any modifications made to the block files if needed.\n\t\ttx.db.store.handleRollback(oldBlkFileNum, oldBlkOffset)\n\t}\n\n\t// Loop through all of the pending blocks to store and write them.\n\tfor _, blockData := range tx.pendingBlockData {\n\t\tlog.Tracef(\"Storing block %v\", *blockData.key)\n\t\tlocation, err := tx.db.store.writeBlock(blockData.bytes)\n\t\tif err != nil {\n\t\t\trollback()\n\t\t\treturn err\n\t\t}\n\n\t\t// Add a record in the block index for the block. The record\n\t\t// includes the location information needed to locate the block\n\t\t// on the filesystem as well as the block header since they are\n\t\t// so commonly needed.\n\t\tblockRow := serializeBlockLoc(location)\n\t\terr = tx.blockIdxBucket.Put(blockData.key[:], blockRow)\n\t\tif err != nil {\n\t\t\trollback()\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Update the metadata for the current write file and offset.\n\twriteRow := serializeWriteRow(wc.curFileNum, wc.curOffset)\n\tif err := tx.metaBucket.Put(writeLocKeyName, writeRow); err != nil {\n\t\trollback()\n\t\treturn database.ConvertErr(\"failed to store write cursor\", err)\n\t}\n\n\t// Atomically update the database cache. The cache automatically\n\t// handles flushing to the underlying persistent storage database.\n\treturn tx.db.cache.commitTx(tx)\n}", "func (tp *TransactionProcessor) ApplyTransactions(layer LayerID, transactions Transactions) (uint32, error) {\n\t//todo: need to seed the mersenne twister with random beacon seed\n\tif len(transactions) == 0 {\n\t\treturn 0, nil\n\t}\n\n\ttxs := tp.mergeDoubles(transactions)\n\ttp.mu.Lock()\n\tdefer tp.mu.Unlock()\n\tfailed := tp.Process(tp.randomSort(txs), tp.coalesceTransactionsBySender(txs))\n\tnewHash, err := tp.globalState.Commit(false)\n\n\tif err != nil {\n\t\ttp.Log.Error(\"db write error %v\", err)\n\t\treturn failed, err\n\t}\n\n\ttp.Log.Info(\"new state root for layer %v is %x\", layer, newHash)\n\ttp.Log.With().Info(\"new state\", log.Uint32(\"layer_id\", uint32(layer)), log.String(\"root_hash\", newHash.String()))\n\n\ttp.stateQueue.PushBack(newHash)\n\tif tp.stateQueue.Len() > maxPastStates {\n\t\thash := tp.stateQueue.Remove(tp.stateQueue.Back())\n\t\ttp.db.Commit(hash.(common.Hash), false)\n\t}\n\ttp.prevStates[layer] = newHash\n\ttp.db.Reference(newHash, common.Hash{})\n\n\treturn failed, nil\n}", "func (mr *MockDynamoDBAPIMockRecorder) TransactWriteItems(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"TransactWriteItems\", reflect.TypeOf((*MockDynamoDBAPI)(nil).TransactWriteItems), varargs...)\n}", "func (repo *trepo) SaveTransaction(id uint64, data string) {\n\trepo.transactions[id] = data\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigCallerSession) Transactions(arg0 *big.Int) (struct {\n\tDestination common.Address\n\tValue *big.Int\n\tData []byte\n\tExecuted bool\n}, error) {\n\treturn _ReserveSpenderMultiSig.Contract.Transactions(&_ReserveSpenderMultiSig.CallOpts, arg0)\n}", "func sendTransaction(t *Transaction) {\n\ttransactionToSend := &Message{}\n\ttransactionToSend.Transaction = t\n\tfor _, conn := range connections{\n\t\tgo send(transactionToSend, conn)\n\t}\n\ttransactionIsUsed[t.Id] = true\n}", "func writeTxContract(w io.Writer, tc *TxContract) error {\n\treturn serialization.WriteUint32(w, tc.GasLimit)\n}", "func (c *changeTrackerDB) WriteTxn(idx uint64) *txn {\n\tt := &txn{\n\t\tTxn: c.memdb.Txn(true),\n\t\tIndex: idx,\n\t\tpublish: c.publish,\n\t\tmsgType: structs.IgnoreUnknownTypeFlag, // The zero value of structs.MessageType is noderegistration.\n\t}\n\tt.Txn.TrackChanges()\n\treturn t\n}", "func (suite *MainIntegrationSuite) TestWriteMultipleTXs() {\n\t// Create a controller to write to the DB using the test tables.\n\tvar testDBClient dbclient.Controller\n\ttestDBClient, err := dbclient.New(\n\t\tdbclient.DBPort(injector.PostgresPort()),\n\t\tdbclient.DBName(injector.PostgresDBName()),\n\t\tdbclient.DBUser(injector.PostgresUserName()),\n\t\tdbclient.DBHost(injector.PostgresDomain()),\n\t\tdbclient.DBPassword(injector.PostgresPassword()),\n\t\tdbclient.PostgresClient(),\n\t\tdbclient.Test())\n\n\t// Connect to the DB.\n\terr = testDBClient.Connect()\n\tdefer testDBClient.Close()\n\tsuite.NoError(err, \"There should be no error connecting to the DB\")\n\n\t// Create a node Controller to communicate with a Blockchain Node.\n\tvar nodeClient nodeclient.Controller\n\tnodeClient = nodeclient.New(\n\t\tinjector.DefaultHTTPClient(),\n\t\tinjector.BTCDomain(),\n\t\tinjector.BTCUsername(),\n\t\tinjector.BTCPassword())\n\n\t// Retrieve a Block\n\tblock := testutils.Block506664\n\ttxs := block.TX\n\n\t// Write the Block to the db\n\terr = testDBClient.WriteBlock(block)\n\tsuite.NoError(err, \"Should be able to write block to the db\")\n\n\t// Write 10 transactions to the DB.\n\tfor i, hash := range txs {\n\t\t// Break early, this block has +1000 plus txs.\n\t\tif i == 10 {\n\t\t\tbreak\n\t\t}\n\n\t\t// Request GetTransaction from the node.\n\t\ttx, err := nodeClient.GetTransaction(hash)\n\t\tsuite.NoError(err, \"There should be no error when connecting to the Test DB.\")\n\n\t\t// Add blockhash to transaction.\n\t\ttx.Blockhash = block.Hash\n\n\t\t// Write the retrieved transaction to the transaction table.\n\t\terr = testDBClient.WriteTransaction(tx)\n\t\tsuite.NoError(err, \"There should be no error writing transaction\")\n\n\t\t// Loop over each input in the transaction.\n\t\tfor _, input := range tx.Vin {\n\t\t\t// Write the transaction inputs to the inputs table.\n\t\t\terr = testDBClient.WriteInput(tx.Hash, input)\n\t\t\tsuite.NoError(err, \"There should be no error writing inputs to the db.\")\n\t\t}\n\n\t\t// Loop over each output in the transaction.\n\t\tfor _, output := range tx.Vout {\n\t\t\t// Write the transaction outputs to the outputs table.\n\t\t\terr = testDBClient.WriteOutput(tx.Hash, output)\n\t\t\tsuite.NoError(err, \"There should be no error writing outputs to the db.\")\n\t\t}\n\t}\n}", "func (dao *PagesDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {\n\treturn dao.Ctx(ctx).Transaction(ctx, f)\n}", "func (bi *Blockchainidentifier) SaveTransaction(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r.RemoteAddr + \" POST /transactions/new\")\n\n\tvar t transaction\n\n\terr := json.NewDecoder(r.Body).Decode(&t)\n\tif err != nil {\n\t\thttp.Error(w, \"ERROR: \"+err.Error(), 500)\n\t\treturn\n\t}\n\n\tif bi.isValid(t) == false {\n\t\thttp.Error(w, \"ERROR: Missing values in transaction\", 400)\n\t\treturn\n\t}\n\n\tt.Timestamp = time.Now().UTC().Format(\"2006-01-02 15:04:05\")\n\n\tnewblockindex := bi.newTransaction(t)\n\n\tresponseMessage := map[string]string{\n\t\t\"message\": \"Transaction will be added in Block#\" + strconv.Itoa(newblockindex),\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.WriteHeader(http.StatusCreated)\n\tjson.NewEncoder(w).Encode(responseMessage)\n}", "func (ds *DiskSyncer) ScheduleTxStoreWrite(a *Account) {\n\tds.scheduleTxStore <- a\n}", "func Transaction(rt *Runtime, c chan goengage.Fundraise) (err error) {\n\trt.Log.Println(\"Transaction: start\")\n\tfor true {\n\t\tr, ok := <-c\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\n\t\trt.Log.Printf(\"%v Transaction\\n\", r.ActivityID)\n\t\tif rt.GoodYear(r.ActivityDate) {\n\t\t\tif len(r.Transactions) != 0 {\n\t\t\t\tfor _, c := range r.Transactions {\n\t\t\t\t\tc.ActivityID = r.ActivityID\n\t\t\t\t\trt.DB.Create(&c)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\trt.Log.Println(\"Transaction: end\")\n\treturn nil\n}", "func (s *PollStore) Transaction(callback func(*PollStore) error) error {\n\tif callback == nil {\n\t\treturn kallax.ErrInvalidTxCallback\n\t}\n\n\treturn s.Store.Transaction(func(store *kallax.Store) error {\n\t\treturn callback(&PollStore{store})\n\t})\n}", "func (db *stateDB) WriteTxn() WriteTransaction {\n\ttxn := db.memDB.Txn(true)\n\ttxn.TrackChanges()\n\treturn &transaction{\n\t\tdb: db,\n\t\ttxn: txn,\n\t\t// Assign a revision to the transaction. Protected by\n\t\t// the memDB writer lock that we acquired with Txn(true).\n\t\trevision: db.revision + 1,\n\t}\n}", "func (account *Account) updateOutgoingTransactions(tipHeight uint64) {\n\tdefer account.Synchronizer.IncRequestsCounter()()\n\n\tdbTx, err := account.db.Begin()\n\tif err != nil {\n\t\taccount.log.WithError(err).Error(\"could not open db\")\n\t\treturn\n\t}\n\tdefer dbTx.Rollback()\n\n\t// Get our stored outgoing transactions.\n\toutgoingTransactions, err := dbTx.OutgoingTransactions()\n\tif err != nil {\n\t\taccount.log.WithError(err).Error(\"could not get outgoing transactions\")\n\t\treturn\n\t}\n\n\t// Update the stored txs' metadata if up to 12 confirmations.\n\tfor idx, tx := range outgoingTransactions {\n\t\ttxLog := account.log.WithField(\"idx\", idx)\n\t\tremoteTx, err := account.coin.client.TransactionReceiptWithBlockNumber(context.TODO(), tx.Transaction.Hash())\n\t\tif remoteTx == nil || err != nil {\n\t\t\t// Transaction not found. This usually happens for pending transactions.\n\t\t\t// In this case, check if the node actually knows about the transaction, and if not, re-broadcast.\n\t\t\t// We do this because it seems that sometimes, a transaction that was broadcast without error still ends up lost.\n\t\t\t_, _, err := account.coin.client.TransactionByHash(context.TODO(), tx.Transaction.Hash())\n\t\t\tif err != nil {\n\t\t\t\ttx.BroadcastAttempts++\n\t\t\t\ttxLog.WithError(err).Errorf(\"could not fetch transaction - rebroadcasting, attempt %d\", tx.BroadcastAttempts)\n\t\t\t\tif err := dbTx.PutOutgoingTransaction(tx); err != nil {\n\t\t\t\t\ttxLog.WithError(err).Error(\"could not update outgoing tx\")\n\t\t\t\t\t// Do not abort here, we want to attempt broadcastng the tx in any case.\n\t\t\t\t}\n\t\t\t\tif err := account.coin.client.SendTransaction(context.TODO(), tx.Transaction); err != nil {\n\t\t\t\t\ttxLog.WithError(err).Error(\"failed to broadcast\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\ttxLog.Info(\"Broadcasting did not return an error\")\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tsuccess := remoteTx.Status == types.ReceiptStatusSuccessful\n\t\tif tx.Height == 0 || (tipHeight-remoteTx.BlockNumber) < ethtypes.NumConfirmationsComplete || tx.Success != success {\n\t\t\ttx.Height = remoteTx.BlockNumber\n\t\t\ttx.GasUsed = remoteTx.GasUsed\n\t\t\ttx.Success = success\n\t\t\tif err := dbTx.PutOutgoingTransaction(tx); err != nil {\n\t\t\t\ttxLog.WithError(err).Error(\"could not update outgoing tx\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\tif err := dbTx.Commit(); err != nil {\n\t\taccount.log.WithError(err).Error(\"could not commit db tx\")\n\t\treturn\n\t}\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigCaller) Transactions(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tDestination common.Address\n\tValue *big.Int\n\tData []byte\n\tExecuted bool\n}, error) {\n\tret := new(struct {\n\t\tDestination common.Address\n\t\tValue *big.Int\n\t\tData []byte\n\t\tExecuted bool\n\t})\n\tout := ret\n\terr := _ReserveSpenderMultiSig.contract.Call(opts, out, \"transactions\", arg0)\n\treturn *ret, err\n}", "func (s *SessionStore) Transaction(callback func(*SessionStore) error) error {\n\tif callback == nil {\n\t\treturn kallax.ErrInvalidTxCallback\n\t}\n\n\treturn s.Store.Transaction(func(store *kallax.Store) error {\n\t\treturn callback(&SessionStore{store})\n\t})\n}", "func (o *LoyaltySubLedger) SetTransactions(v []LoyaltyLedgerEntry) {\n\to.Transactions = &v\n}", "func (db *database) Transact(txHandler func(tx *sqlx.Tx) error) (err error) {\n\t// Start the transaction and receive a transaction handle.\n\ttx, err := db.Beginx()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to begin transaction\")\n\t}\n\n\t// Add deferred handler to clean up this transaction.\n\tdefer func() { err = db.cleanupTransaction(tx, err) }()\n\n\t// Call the transaction handler.\n\terr = txHandler(tx)\n\n\t// Remember, deferred cleanup ALWAYS runs after this.\n\treturn\n}", "func (t *TaskStore) applyTransaction(transaction []updateDiff) error {\n\tif err := t.journalAppend(transaction); err != nil {\n\t\treturn err\n\t}\n\tt.playTransaction(transaction, t.snapshotting)\n\treturn nil\n}", "func (db *DB) WriteTx() *WriteTx {\n\treturn &WriteTx{\n\t\tdb: db,\n\t}\n}", "func (db *database) Transact(txHandler func(tx *sqlx.Tx) error) (err error) {\n\ttx, err := db.Beginx()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to begin transaction\")\n\t}\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\t_ = tx.Rollback()\n\t\t\tpanic(r)\n\t\t}\n\n\t\tif err != nil {\n\t\t\t_ = tx.Rollback()\n\t\t\treturn\n\t\t}\n\n\t\ttx.Commit()\n\t}()\n\n\terr = txHandler(tx)\n\treturn\n}", "func (s *transactionStore) Close(ctx context.Context) error {\n\terr := s.transactions.Close(ctx)\n\tif err != nil {\n\t\treturn errors.FromAtomix(err)\n\t}\n\treturn nil\n}", "func (s *PollVoteStore) Transaction(callback func(*PollVoteStore) error) error {\n\tif callback == nil {\n\t\treturn kallax.ErrInvalidTxCallback\n\t}\n\n\treturn s.Store.Transaction(func(store *kallax.Store) error {\n\t\treturn callback(&PollVoteStore{store})\n\t})\n}", "func (txn *levelDBTxn) commit() error {\n\t// Check context first to make sure transaction is not cancelled.\n\tselect {\n\tdefault:\n\tcase <-txn.ctx.Done():\n\t\treturn txn.ctx.Err()\n\t}\n\n\ttxn.mu.Lock()\n\tdefer txn.mu.Unlock()\n\n\treturn txn.kv.Write(txn.batch, nil)\n}", "func (s *PetStore) Transaction(callback func(*PetStore) error) error {\n\tif callback == nil {\n\t\treturn kallax.ErrInvalidTxCallback\n\t}\n\n\treturn s.Store.Transaction(func(store *kallax.Store) error {\n\t\treturn callback(&PetStore{store})\n\t})\n}", "func (c *Conn) Transaction(t TransactionType, f func(c *Conn) error) error {\n\tvar err error\n\tif c.nTransaction == 0 {\n\t\terr = c.BeginTransaction(t)\n\t} else {\n\t\terr = c.Savepoint(strconv.Itoa(int(c.nTransaction)))\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.nTransaction++\n\tdefer func() {\n\t\tc.nTransaction--\n\t\tif err != nil {\n\t\t\t_, ko := err.(*ConnError)\n\t\t\tif c.nTransaction == 0 || ko {\n\t\t\t\t_ = c.Rollback()\n\t\t\t} else {\n\t\t\t\tif rerr := c.RollbackSavepoint(strconv.Itoa(int(c.nTransaction))); rerr != nil {\n\t\t\t\t\tLog(-1, rerr.Error())\n\t\t\t\t} else if rerr := c.ReleaseSavepoint(strconv.Itoa(int(c.nTransaction))); rerr != nil {\n\t\t\t\t\tLog(-1, rerr.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif c.nTransaction == 0 {\n\t\t\t\terr = c.Commit()\n\t\t\t} else {\n\t\t\t\terr = c.ReleaseSavepoint(strconv.Itoa(int(c.nTransaction)))\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\t_ = c.Rollback()\n\t\t\t}\n\t\t}\n\t}()\n\terr = f(c)\n\treturn err\n}", "func (cdt *SqlDBTx) TxEnd(txFunc func() error) error {\n\treturn nil\n}", "func (s *UserStore) Transaction(callback func(*UserStore) error) error {\n\tif callback == nil {\n\t\treturn kallax.ErrInvalidTxCallback\n\t}\n\n\treturn s.Store.Transaction(func(store *kallax.Store) error {\n\t\treturn callback(&UserStore{store})\n\t})\n}", "func (s *PollOptionStore) Transaction(callback func(*PollOptionStore) error) error {\n\tif callback == nil {\n\t\treturn kallax.ErrInvalidTxCallback\n\t}\n\n\treturn s.Store.Transaction(func(store *kallax.Store) error {\n\t\treturn callback(&PollOptionStore{store})\n\t})\n}", "func Transaction(db *sql.DB, fns ...func(DB) error) error {\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, fn := range fns {\n\t\terr := fn(tx)\n\t\tif err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = tx.Commit()\n\terr = interpretScanError(err)\n\treturn err\n}", "func (tx *Tx) commit() {\n\tfor v, val := range tx.writes {\n\t\tv.mu.Lock()\n\t\tv.val = val\n\t\tv.version++\n\t\tv.mu.Unlock()\n\t}\n}", "func (b *BootstrapClient) writeTransitPolicy() error {\n\treturn b.usingVaultRootToken(func() error {\n\t\tfor i := range b.config.transitData {\n\t\t\tif err := b.writeWritePolicy(b.config.transitData[i].EncryptPath); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := b.writeWritePolicy(b.config.transitData[i].DecryptPath); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := b.writeReadPolicy(b.config.transitData[i].OutputPath); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}", "func spendTransaction(utxoView *blockchain.UtxoViewpoint, tx *dcrutil.Tx,\n\theight int64, isTreasuryEnabled bool) {\n\n\tfor _, txIn := range tx.MsgTx().TxIn {\n\t\tentry := utxoView.LookupEntry(txIn.PreviousOutPoint)\n\t\tif entry != nil {\n\t\t\tentry.Spend()\n\t\t}\n\t}\n\n\tutxoView.AddTxOuts(tx, height, wire.NullBlockIndex, isTreasuryEnabled)\n}", "func connectTransactions(txStore TxStore, block *massutil.Block) error {\n\tfor _, tx := range block.Transactions() {\n\t\tmsgTx := tx.MsgTx()\n\t\tif txD, exists := txStore[*tx.Hash()]; exists {\n\t\t\ttxD.Tx = tx\n\t\t\ttxD.BlockHeight = block.Height()\n\t\t\ttxD.Spent = make([]bool, len(msgTx.TxOut))\n\t\t\ttxD.Err = nil\n\t\t}\n\n\t\tif IsCoinBaseTx(msgTx) {\n\t\t\tcontinue\n\t\t} else {\n\t\t\tfor _, txIn := range msgTx.TxIn {\n\t\t\t\toriginHash := &txIn.PreviousOutPoint.Hash\n\t\t\t\toriginIndex := txIn.PreviousOutPoint.Index\n\t\t\t\tif originTx, exists := txStore[*originHash]; exists {\n\t\t\t\t\tif originIndex > uint32(len(originTx.Spent)) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\toriginTx.Spent[originIndex] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func (s *Store) StoreTransaction(t Transaction) error {\n\treturn s.db.Update(func(tx *bolt.Tx) error {\n\t\t// Retrieve buckets\n\t\tbTRN := tx.Bucket([]byte(\"TRANSACTIONS\"))\n\t\tbCAN := tx.Bucket([]byte(\"CANDIDATES\"))\n\t\tbVOT := tx.Bucket([]byte(\"VOTES\"))\n\n\t\t// Increase the total vote count for each candidate voted for\n\t\tfor candidate, voteCount := range t.Votes {\n\t\t\t// Confirm that the candidate exists and is active\n\t\t\tcandidateStatus := bCAN.Get([]byte(candidate))\n\t\t\tif candidateStatus == nil {\n\t\t\t\treturn fmt.Errorf(\"Transaction contains invalid candidate name: %s\", candidate)\n\t\t\t}\n\t\t\tif !bytetobool(candidateStatus) {\n\t\t\t\treturn fmt.Errorf(\"Cannot vote for eliminated candidate %s\", candidate)\n\t\t\t}\n\n\t\t\tv := bVOT.Get([]byte(candidate))\n\t\t\tif v == nil {\n\t\t\t\treturn fmt.Errorf(\"Transaction contains invalid candidate name: %s\", candidate)\n\t\t\t}\n\n\t\t\tbVOT.Put([]byte(candidate), itob(voteCount+btoi(v)))\n\t\t}\n\n\t\t// Generate ID for this trasaction\n\t\t// This returns an error only if the Tx is closed or not writeable.\n\t\t// That can't happen in an Update() call so I ignore the error check.\n\t\tid, _ := bTRN.NextSequence()\n\n\t\t// Marshal transaction into bytes.\n\t\tbuf, err := json.Marshal(t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t//fmt.Printf(\"Storing transaction: %s\\n\", string(buf))\n\n\t\t// Persist bytes to bucket\n\t\treturn bTRN.Put(itob(int(id)), buf)\n\t})\n}", "func CreateTransactions(\n\trouter *mux.Router,\n\tpk cryptography.PrivateKey,\n\tuser users.User,\n\tserverSDK sdks.Servers,\n\troutePrefix string,\n\tsignedTrsBufferSize int,\n\tatomicTrsBufferSize int,\n\taggregatedTrsBufferSize int,\n\ttrsAggregationDelay time.Duration,\n) *Transactions {\n\n\t//channels:\n\tnewSignedTrs := make(chan signed_transactions.Transaction, signedTrsBufferSize)\n\tnewAtomicSignedTrs := make(chan signed_transactions.AtomicTransaction, atomicTrsBufferSize)\n\tnewAggregatedTrs := make(chan aggregated_transactions.Transactions, aggregatedTrsBufferSize)\n\n\t//factories:\n\tmetaDataBuilderFactory := concrete_metadata.CreateBuilderFactory()\n\thtBuilderFactory := concrete_hashtrees.CreateHashTreeBuilderFactory()\n\tpublicKeyBuilderFactory := concrete_cryptography.CreatePublicKeyBuilderFactory()\n\tsigBuilderFactory := concrete_cryptography.CreateSignatureBuilderFactory(publicKeyBuilderFactory)\n\tuserSigBuilderFactory := concrete_users.CreateSignatureBuilderFactory(sigBuilderFactory, htBuilderFactory, metaDataBuilderFactory)\n\n\t//transactions and blocks factories:\n\tblockChainMetaDataBuilderFactory := concrete_blockchain_metadata.CreateBuilderFactory()\n\tsignedTrsBuilderFactory := concrete_signed_transactions.CreateTransactionBuilderFactory(htBuilderFactory, blockChainMetaDataBuilderFactory)\n\tsignedTransBuilderFactory := concrete_signed_transactions.CreateTransactionsBuilderFactory(htBuilderFactory, blockChainMetaDataBuilderFactory)\n\tsignedAtomicTransBuilderFactory := concrete_signed_transactions.CreateAtomicTransactionsBuilderFactory(htBuilderFactory, blockChainMetaDataBuilderFactory)\n\tatomicSignedTrsBuilderFactory := concrete_signed_transactions.CreateAtomicTransactionBuilderFactory(htBuilderFactory, blockChainMetaDataBuilderFactory)\n\tsignedAggregatedTrsBuilderFactory := concrete_aggregated_transactions.CreateTransactionsBuilderFactory(htBuilderFactory, blockChainMetaDataBuilderFactory)\n\n\t//create the leader SDK:\n\tleadSDK := concrete_sdks.CreateLeaders(userSigBuilderFactory, routePrefix, pk, user)\n\n\t//create the transaction API:\n\ttransactionsAPI := apis.CreateTransactions(\n\t\troutePrefix,\n\t\trouter,\n\t\tsignedTrsBuilderFactory,\n\t\tatomicSignedTrsBuilderFactory,\n\t\tnewSignedTrs,\n\t\tnewAtomicSignedTrs,\n\t)\n\n\t//create the transaction agent:\n\ttrsAgent := agents.CreatePushTransactionsToLeaders(\n\t\tsignedAggregatedTrsBuilderFactory,\n\t\tsignedTransBuilderFactory,\n\t\tsignedAtomicTransBuilderFactory,\n\t\ttrsAggregationDelay,\n\t\tnewSignedTrs,\n\t\tnewAtomicSignedTrs,\n\t\tnewAggregatedTrs,\n\t)\n\n\tout := Transactions{\n\t\tapi: transactionsAPI,\n\t\tagent: trsAgent,\n\t\tleadSDK: leadSDK,\n\t\tservSDK: serverSDK,\n\t\tnewAggregatedTrs: newAggregatedTrs,\n\t}\n\n\treturn &out\n}", "func TransactionIndex(c *gin.Context) {\n\trelatedObjectID := c.Query(\"relatedObjectId\")\n\trelatedObjectType := c.Query(\"relatedObjectType\")\n\tisSettledQuery := c.Query(\"isSettled\")\n\tstatusQuery := c.Query(\"status\")\n\tcurUserID := c.Keys[\"CurrentUserID\"]\n\n\tvar transactions []models.Transaction\n\n\tquery := database.DBCon\n\n\tisSettled, err := strconv.ParseBool(isSettledQuery)\n\tif isSettledQuery != \"\" && err == nil {\n\t\tquery = query.Where(\"is_settled = ?\", isSettled)\n\t}\n\n\t// TODO: Check that statusQuery is a valid status\n\tif statusQuery != \"\" {\n\t\tquery = query.Where(\"status = ?\", statusQuery)\n\t}\n\n\tif relatedObjectID != \"\" && relatedObjectType != \"\" {\n\t\tquery.\n\t\t\tWhere(\"related_object_id = ? AND related_object_type = ?\", relatedObjectID, relatedObjectType).\n\t\t\tOrder(\"created_at desc\").\n\t\t\tFind(&transactions)\n\t} else {\n\t\tquery.\n\t\t\tWhere(\"creator_id = ?\", curUserID).\n\t\t\tFind(&transactions)\n\t}\n\n\t// Get creator and relatedUser\n\t// TODO: n + 1 query problem here, so we'll figure this out later\n\tfor i := range transactions {\n\t\tdatabase.DBCon.First(&transactions[i].Recipient, transactions[i].RecipientID)\n\t\tdatabase.DBCon.First(&transactions[i].Sender, transactions[i].SenderID)\n\t\tdatabase.DBCon.First(&transactions[i].Creator, transactions[i].CreatorID)\n\t}\n\n\tdata, err := jsonapi.Marshal(transactions)\n\n\tif err != nil {\n\t\tc.AbortWithError(http.StatusInternalServerError, err).\n\t\t\tSetMeta(appError.JSONParseFailure)\n\t\treturn\n\t}\n\n\tc.Data(http.StatusOK, \"application/vnd.api+json\", data)\n}", "func txlogzHandler(w http.ResponseWriter, req *http.Request) {\n\tif err := acl.CheckAccessHTTP(req, acl.DEBUGGING); err != nil {\n\t\tacl.SendError(w, err)\n\t\treturn\n\t}\n\n\tif streamlog.GetRedactDebugUIQueries() {\n\t\tio.WriteString(w, `\n<!DOCTYPE html>\n<html>\n<body>\n<h1>Redacted</h1>\n<p>/txlogz has been redacted for your protection</p>\n</body>\n</html>\n`)\n\t\treturn\n\t}\n\n\ttimeout, limit := parseTimeoutLimitParams(req)\n\tch := tabletenv.TxLogger.Subscribe(\"txlogz\")\n\tdefer tabletenv.TxLogger.Unsubscribe(ch)\n\tlogz.StartHTMLTable(w)\n\tdefer logz.EndHTMLTable(w)\n\tw.Write(txlogzHeader)\n\n\ttmr := time.NewTimer(timeout)\n\tdefer tmr.Stop()\n\tfor i := 0; i < limit; i++ {\n\t\tselect {\n\t\tcase out := <-ch:\n\t\t\ttxc, ok := out.(*StatefulConnection)\n\t\t\tif !ok {\n\t\t\t\terr := fmt.Errorf(\"unexpected value in %s: %#v (expecting value of type %T)\", tabletenv.TxLogger.Name(), out, &StatefulConnection{})\n\t\t\t\tio.WriteString(w, `<tr class=\"error\">`)\n\t\t\t\tio.WriteString(w, err.Error())\n\t\t\t\tio.WriteString(w, \"</tr>\")\n\t\t\t\tlog.Error(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// not all StatefulConnections contain transactions\n\t\t\tif txc.txProps != nil {\n\t\t\t\twriteTransactionData(w, txc)\n\t\t\t}\n\t\tcase <-tmr.C:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (c *changeTrackerDB) WriteTxnRestore() *txn {\n\treturn &txn{\n\t\tTxn: c.memdb.Txn(true),\n\t\tIndex: 0,\n\t}\n}", "func (this *UTXOSet) CountTransactions() int {\n\tdb := this.BlockChain.db\n\tcounter := 0\n\n\terr := db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(utxoBucket))\n\t\tc := b.Cursor()\n\n\t\tfor k, _ := c.First(); k != nil; k, _ = c.Next() {\n\t\t\tcounter++\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn counter\n}", "func (h *Reports) Transactions(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {\n\n\tvar data = make(map[string]interface{})\n\tvar total float64\n\n\tclaims, err := auth.ClaimsFromContext(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfields := []datatable.DisplayField{\n\t\t{Field: \"id\", Title: \"ID\", Visible: false, Searchable: true, Orderable: true, Filterable: false},\n\t\t{Field: \"amount\", Title: \"Amount\", Visible: true, Searchable: false, Orderable: true, Filterable: true, FilterPlaceholder: \"filter Quantity\"},\n\t\t{Field: \"created_at\", Title: \"Date\", Visible: true, Searchable: true, Orderable: true, Filterable: true, FilterPlaceholder: \"filter Date\"},\n\t\t{Field: \"customer_name\", Title: \"Customer\", Visible: true, Searchable: true, Orderable: true, Filterable: true, FilterPlaceholder: \"filter Account\"},\n\t\t{Field: \"account\", Title: \"Account Number\", Visible: true, Searchable: true, Orderable: true, Filterable: true, FilterPlaceholder: \"filter Account\"},\n\t\t{Field: \"sales_rep_id\", Title: \"Recorded By\", Visible: true, Searchable: true, Orderable: false, Filterable: true, FilterPlaceholder: \"filter Recorder\"},\n\t}\n\n\tmapFunc := func(q transaction.TxReportResponse, cols []datatable.DisplayField) (resp []datatable.ColumnValue, err error) {\n\t\tfor i := 0; i < len(cols); i++ {\n\t\t\tcol := cols[i]\n\t\t\tvar v datatable.ColumnValue\n\t\t\tswitch col.Field {\n\t\t\tcase \"id\":\n\t\t\t\tv.Value = fmt.Sprintf(\"%s\", q.ID)\n\t\t\tcase \"amount\":\n\t\t\t\tv.Value = fmt.Sprintf(\"%f\", q.Amount)\n\t\t\t\tp := message.NewPrinter(language.English)\n\t\t\t\tv.Formatted = p.Sprintf(\"<a href='%s'>%.2f</a>\", urlCustomersTransactionsView(q.CustomerID, q.AccountID, q.ID), q.Amount)\n\t\t\tcase \"created_at\":\n\t\t\t\tdate := web.NewTimeResponse(ctx, time.Unix(q.CreatedAt, 0))\n\t\t\t\tv.Value = date.LocalDate\n\t\t\t\tv.Formatted = date.LocalDate\n\t\t\tcase \"narration\":\n\t\t\t\tvalues := strings.Split(q.Narration, \":\")\n\t\t\t\tif len(values) > 1 {\n\t\t\t\t\tif values[0] == \"sale\" {\n\t\t\t\t\t\tv.Value = values[1]\n\t\t\t\t\t\tv.Formatted = fmt.Sprintf(\"<a href='%s'>%s</a>\", urlSalesView(values[2]), v.Value)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tv.Value = q.Narration\n\t\t\t\t\tv.Formatted = q.Narration\n\t\t\t\t}\n\t\t\tcase \"payment_method\":\n\t\t\t\tv.Value = q.PaymentMethod\n\t\t\t\tv.Formatted = q.PaymentMethod\n\t\t\tcase \"customer_name\":\n\t\t\t\tv.Value = q.CustomerName\n\t\t\t\tv.Formatted = fmt.Sprintf(\"<a href='%s'>%s</a>\", urlCustomersView(q.CustomerID), v.Value)\n\t\t\tcase \"account\":\n\t\t\t\tv.Value = q.AccountNumber\n\t\t\t\tv.Formatted = fmt.Sprintf(\"<a href='%s'>%s</a>\", urlCustomersAccountsView(q.CustomerID, q.AccountID), v.Value)\n\t\t\tcase \"sales_rep_id\":\n\t\t\t\tv.Value = q.SalesRepID\n\t\t\t\tv.Formatted = fmt.Sprintf(\"<a href='%s'>%s</a>\", urlUsersView(q.SalesRepID), q.SalesRep)\n\t\t\tdefault:\n\t\t\t\treturn resp, errors.Errorf(\"Failed to map value for %s.\", col.Field)\n\t\t\t}\n\t\t\tresp = append(resp, v)\n\t\t}\n\n\t\treturn resp, nil\n\t}\n\n\tvar txWhere = []string{\"tx_type = 'deposit'\"}\n\tvar txArgs []interface{}\n\t// todo sales rep filtering\n\tif v := r.URL.Query().Get(\"sales_rep_id\"); v != \"\" {\n\t\ttxWhere = append(txWhere, \"sales_rep_id = $1\")\n\t\ttxArgs = append(txArgs, v)\n\t\tdata[\"salesRepID\"] = v\n\t}\n\n\tif v := r.URL.Query().Get(\"payment_method\"); v != \"\" {\n\t\ttxWhere = append(txWhere, fmt.Sprintf(\"payment_method = $%d\", len(txArgs)+1))\n\t\ttxArgs = append(txArgs, v)\n\t\tdata[\"paymentMethod\"] = v\n\t}\n\n\tvar date = time.Now()\n\tif v := r.URL.Query().Get(\"start_date\"); v != \"\" {\n\t\tdate, err = time.Parse(\"01/02/2006\", v)\n\t\tif err != nil {\n\t\t\tdate = time.Now()\n\t\t\treturn err\n\t\t}\n\t}\n\tdate = date.Truncate(time.Millisecond)\n\tdate = now.New(date).BeginningOfDay().Add(-1 * time.Hour)\n\ttxWhere = append(txWhere, fmt.Sprintf(\"created_at >= $%d\", len(txArgs)+1))\n\ttxArgs = append(txArgs, date.UTC().Unix())\n\tdata[\"startDate\"] = date.Format(\"01/02/2006\")\n\n\tdate = time.Now()\n\tif v := r.URL.Query().Get(\"end_date\"); v != \"\" {\n\t\tdate, err = time.Parse(\"01/02/2006\", v)\n\t\tif err != nil {\n\t\t\tdate = time.Now()\n\t\t\treturn err\n\t\t}\n\n\t}\n\tdate = date.Truncate(time.Millisecond)\n\tdate = now.New(date).EndOfDay().Add(-1 * time.Hour)\n\ttxWhere = append(txWhere, fmt.Sprintf(\"created_at <= $%d\", len(txArgs)+1))\n\ttxArgs = append(txArgs, date.Unix())\n\tdata[\"endDate\"] = date.Format(\"01/02/2006\")\n\n\tloadFunc := func(ctx context.Context, sorting string, fields []datatable.DisplayField) (resp [][]datatable.ColumnValue, err error) {\n\n\t\tvar order []string\n\t\tif len(sorting) > 0 {\n\t\t\torder = strings.Split(sorting, \",\")\n\t\t}\n\n\t\tfor i := range txWhere {\n\t\t\ttxWhere[i] = \"tx.\" + txWhere[i]\n\t\t}\n\t\tres, err := h.TransactionRepo.TxReport(ctx, claims, transaction.FindRequest{\n\t\t\tOrder: order, Where: strings.Join(txWhere, \" AND \"), Args: txArgs,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn resp, err\n\t\t}\n\n\t\tfor _, a := range res {\n\t\t\tl, err := mapFunc(a, fields)\n\t\t\tif err != nil {\n\t\t\t\treturn resp, errors.Wrapf(err, \"Failed to map brand for display.\")\n\t\t\t}\n\n\t\t\tresp = append(resp, l)\n\t\t}\n\n\t\treturn resp, nil\n\t}\n\n\tdt, err := datatable.New(ctx, w, r, h.Redis, fields, loadFunc)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif dt.HasCache() {\n\t\treturn nil\n\t}\n\n\tif ok, err := dt.Render(); ok {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\tusers, err := h.UserRepos.Find(ctx, claims, user.UserFindRequest{\n\t\tOrder: []string{\"first_name\", \"last_name\"},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttotal, err = h.TransactionRepo.DepositAmountByWhere(ctx, strings.Join(txWhere, \" and \"), txArgs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdata[\"paymentMethods\"] = transaction.PaymentMethods\n\tdata[\"users\"] = users\n\tdata[\"total\"] = total\n\tdata[\"datatable\"] = dt.Response()\n\n\treturn h.Renderer.Render(ctx, w, r, TmplLayoutBase, \"report-transactions.gohtml\", web.MIMETextHTMLCharsetUTF8, http.StatusOK, data)\n}", "func (wg *WalletGUI) RecentTransactions(n int, listName string) l.Widget {\n\twg.txMx.Lock()\n\tdefer wg.txMx.Unlock()\n\t// wg.ready.Store(false)\n\tvar out []l.Widget\n\tfirst := true\n\t// out = append(out)\n\tvar wga []btcjson.ListTransactionsResult\n\tswitch listName {\n\tcase \"history\":\n\t\twga = wg.txHistoryList\n\tcase \"recent\":\n\t\twga = wg.txRecentList\n\t}\n\tif len(wga) == 0 {\n\t\treturn func(gtx l.Context) l.Dimensions {\n\t\t\treturn l.Dimensions{Size: gtx.Constraints.Max}\n\t\t}\n\t}\n\tDebug(\">>>>>>>>>>>>>>>> iterating transactions\", n, listName)\n\tfor x := range wga {\n\t\tif x > n && n > 0 {\n\t\t\tbreak\n\t\t}\n\t\t\n\t\ti := x\n\t\ttxs := wga[i]\n\t\t// spacer\n\t\tif !first {\n\t\t\tout = append(out,\n\t\t\t\twg.Inset(0.25, gui.EmptyMaxWidth()).Fn,\n\t\t\t)\n\t\t} else {\n\t\t\tfirst = false\n\t\t}\n\t\tout = append(out,\n\t\t\twg.Fill(\"DocBg\", l.W, 0, 0,\n\t\t\t\twg.Inset(0.25,\n\t\t\t\t\twg.Flex().\n\t\t\t\t\t\tRigid(\n\t\t\t\t\t\t\twg.Body1(fmt.Sprintf(\"%-6.8f DUO\", txs.Amount)).Color(\"PanelText\").Fn,\n\t\t\t\t\t\t).\n\t\t\t\t\t\tFlexed(1,\n\t\t\t\t\t\t\twg.Inset(0.25,\n\t\t\t\t\t\t\t\twg.Caption(txs.Address).\n\t\t\t\t\t\t\t\t\tFont(\"go regular\").\n\t\t\t\t\t\t\t\t\tColor(\"PanelText\").\n\t\t\t\t\t\t\t\t\tTextScale(0.66).\n\t\t\t\t\t\t\t\t\tAlignment(text.End).\n\t\t\t\t\t\t\t\t\tFn,\n\t\t\t\t\t\t\t).Fn,\n\t\t\t\t\t\t).Fn,\n\t\t\t\t).Fn,\n\t\t\t).Fn,\n\t\t)\n\t\t// out = append(out,\n\t\t// \twg.Caption(txs.TxID).\n\t\t// \t\tFont(\"go regular\").\n\t\t// \t\tColor(\"PanelText\").\n\t\t// \t\tTextScale(0.5).Fn,\n\t\t// )\n\t\tout = append(out,\n\t\t\twg.Fill(\"DocBg\", l.W, 0, 0,\n\t\t\t\twg.Inset(0.25,\n\t\t\t\t\twg.Flex().Flexed(1,\n\t\t\t\t\t\twg.Flex().\n\t\t\t\t\t\t\tRigid(\n\t\t\t\t\t\t\t\twg.Flex().\n\t\t\t\t\t\t\t\t\tRigid(\n\t\t\t\t\t\t\t\t\t\twg.Icon().Color(\"PanelText\").Scale(1).Src(&icons2.DeviceWidgets).Fn,\n\t\t\t\t\t\t\t\t\t).\n\t\t\t\t\t\t\t\t\t// Rigid(\n\t\t\t\t\t\t\t\t\t// \twg.Caption(fmt.Sprint(*txs.BlockIndex)).Fn,\n\t\t\t\t\t\t\t\t\t// \t// wg.buttonIconText(txs.clickBlock,\n\t\t\t\t\t\t\t\t\t// \t// \tfmt.Sprint(*txs.BlockIndex),\n\t\t\t\t\t\t\t\t\t// \t// \t&icons2.DeviceWidgets,\n\t\t\t\t\t\t\t\t\t// \t// \twg.blockPage(*txs.BlockIndex)),\n\t\t\t\t\t\t\t\t\t// ).\n\t\t\t\t\t\t\t\t\tRigid(\n\t\t\t\t\t\t\t\t\t\twg.Caption(fmt.Sprintf(\"%d \", txs.BlockIndex)).Fn,\n\t\t\t\t\t\t\t\t\t).\n\t\t\t\t\t\t\t\t\tFn,\n\t\t\t\t\t\t\t).\n\t\t\t\t\t\t\tRigid(\n\t\t\t\t\t\t\t\twg.Flex().\n\t\t\t\t\t\t\t\t\tRigid(\n\t\t\t\t\t\t\t\t\t\twg.Icon().Color(\"PanelText\").Scale(1).Src(&icons2.ActionCheckCircle).Fn,\n\t\t\t\t\t\t\t\t\t).\n\t\t\t\t\t\t\t\t\tRigid(\n\t\t\t\t\t\t\t\t\t\twg.Caption(fmt.Sprintf(\"%d \", txs.Confirmations)).Fn,\n\t\t\t\t\t\t\t\t\t).\n\t\t\t\t\t\t\t\t\tFn,\n\t\t\t\t\t\t\t).\n\t\t\t\t\t\t\tRigid(\n\t\t\t\t\t\t\t\twg.Flex().\n\t\t\t\t\t\t\t\t\tRigid(\n\t\t\t\t\t\t\t\t\t\tfunc(gtx l.Context) l.Dimensions {\n\t\t\t\t\t\t\t\t\t\t\tswitch txs.Category {\n\t\t\t\t\t\t\t\t\t\t\tcase \"generate\":\n\t\t\t\t\t\t\t\t\t\t\t\treturn wg.Icon().Color(\"PanelText\").Scale(1).Src(&icons2.ActionStars).Fn(gtx)\n\t\t\t\t\t\t\t\t\t\t\tcase \"immature\":\n\t\t\t\t\t\t\t\t\t\t\t\treturn wg.Icon().Color(\"PanelText\").Scale(1).Src(&icons2.ImageTimeLapse).Fn(gtx)\n\t\t\t\t\t\t\t\t\t\t\tcase \"receive\":\n\t\t\t\t\t\t\t\t\t\t\t\treturn wg.Icon().Color(\"PanelText\").Scale(1).Src(&icons2.ActionPlayForWork).Fn(gtx)\n\t\t\t\t\t\t\t\t\t\t\tcase \"unknown\":\n\t\t\t\t\t\t\t\t\t\t\t\treturn wg.Icon().Color(\"PanelText\").Scale(1).Src(&icons2.AVNewReleases).Fn(gtx)\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\treturn l.Dimensions{}\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t).\n\t\t\t\t\t\t\t\t\tRigid(\n\t\t\t\t\t\t\t\t\t\twg.Caption(txs.Category+\" \").Fn,\n\t\t\t\t\t\t\t\t\t).\n\t\t\t\t\t\t\t\t\tFn,\n\t\t\t\t\t\t\t).\n\t\t\t\t\t\t\tRigid(\n\t\t\t\t\t\t\t\twg.Flex().\n\t\t\t\t\t\t\t\t\tRigid(\n\t\t\t\t\t\t\t\t\t\twg.Icon().Color(\"PanelText\").Scale(1).Src(&icons2.DeviceAccessTime).Fn,\n\t\t\t\t\t\t\t\t\t).\n\t\t\t\t\t\t\t\t\tRigid(\n\t\t\t\t\t\t\t\t\t\twg.Caption(\n\t\t\t\t\t\t\t\t\t\t\ttime.Unix(txs.Time,\n\t\t\t\t\t\t\t\t\t\t\t\t0).Format(\"02 Jan 06 15:04:05 MST\"),\n\t\t\t\t\t\t\t\t\t\t).Color(\"PanelText\").Fn,\n\t\t\t\t\t\t\t\t\t).\n\t\t\t\t\t\t\t\t\tFn,\n\t\t\t\t\t\t\t).Fn,\n\t\t\t\t\t).Fn,\n\t\t\t\t).Fn,\n\t\t\t).Fn,\n\t\t)\n\t}\n\tle := func(gtx l.Context, index int) l.Dimensions {\n\t\treturn out[index](gtx)\n\t}\n\two := func(gtx l.Context) l.Dimensions {\n\t\treturn wg.lists[listName].\n\t\t\tVertical().\n\t\t\tLength(len(out)).\n\t\t\tListElement(le).\n\t\t\tFn(gtx)\n\t}\n\tDebug(\">>>>>>>>>>>>>>>> history widget completed\", n, listName)\n\tswitch listName {\n\tcase \"history\":\n\t\twg.HistoryWidget = wo\n\t\tif !wg.ready.Load() {\n\t\t\twg.ready.Store(true)\n\t\t}\n\tcase \"recent\":\n\t\twg.RecentTransactionsWidget = wo\n\t}\n\treturn func(gtx l.Context) l.Dimensions {\n\t\treturn wo(gtx)\n\t}\n}", "func SaveAccountTransaction(validators []*schema.Validator, transactions []*schema.Transaction) {\n\n\tfor _, tx := range transactions {\n\t\tvar listAccountAddress = getListAccountAddres(tx.Messages)\n\t\tfor _, address := range listAccountAddress {\n\t\t\torm.Save(document.CollectionAccountTransaction, &document.AccountTransaction{\n\t\t\t\tHeight: tx.Height,\n\t\t\t\tAccountAddr: address,\n\t\t\t\tTxHash: tx.TxHash,\n\t\t\t})\n\t\t}\n\t}\n}", "func Transactions(exec boil.Executor, mods ...qm.QueryMod) transactionQuery {\n\tmods = append(mods, qm.From(\"`transaction`\"))\n\treturn transactionQuery{NewQuery(exec, mods...)}\n}", "func writeTxIn(w io.Writer, pver uint32, ti *TxIn) error {\n\terr := writeOutPoint(w, pver, &ti.PreviousOutPoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar buf [1]byte\n\n\tbuf[0] = ti.sighash\n\n\t_, err = w.Write(buf[:])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func ProcessTransactions(db *sql.DB, blockNumber *big.Int) error {\n\n\tb, err := blockchain.GetBlock(ethClient, blockNumber)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttransactions := b.Transactions()\n\ttimestamp := strconv.FormatUint(b.Time(), 10)\n\n\tfor _, tx := range transactions {\n\t\tgasReceipt := blockchain.GetGasReceipt(ethClient, tx.Hash())\n\t\tprocessTransaction(db, blockNumber, timestamp, tx, gasReceipt)\n\t}\n\n\treturn nil\n\n}", "func (u UTXOSet) CountTransactions() int {\n\treturn storage.CountTransactions(u.Blockchain.db)\n}", "func (l *EventLogger) CommitTransaction() (lastErr error) {\n\tdefer l.Unlock()\n\tl.endTransaction()\n\treturn l.close()\n}", "func commitDBTx(t *testing.T, store *Store, db walletdb.DB,\n\tf func(walletdb.ReadWriteBucket)) {\n\n\tt.Helper()\n\n\tdbTx, err := db.BeginReadWriteTx()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer dbTx.Commit()\n\n\tns := dbTx.ReadWriteBucket(namespaceKey)\n\n\tf(ns)\n}", "func (_EthCrossChain *EthCrossChainSession) Transactions(arg0 *big.Int) ([32]byte, error) {\n\treturn _EthCrossChain.Contract.Transactions(&_EthCrossChain.CallOpts, arg0)\n}", "func (_Validator *ValidatorSession) ExecuteTransactions(data [][]byte, destination []common.Address, amount []*big.Int) (*types.Transaction, error) {\n\treturn _Validator.Contract.ExecuteTransactions(&_Validator.TransactOpts, data, destination, amount)\n}", "func (c *Connection) Transaction(fn func(*Connection) error) error {\n\td := c.C.Begin()\n\tif err := fn(&Connection{C: d, log: c.log}); err != nil {\n\t\td.Rollback()\n\t\treturn err\n\t}\n\td.Commit()\n\treturn nil\n}", "func writeTxIn(w io.Writer, pver uint32, ti *TxIn) error {\n\terr := writeOutPoint(w, &ti.PreviousOutPoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = serialization.WriteVarBytes(w, pver, ti.SignatureScript)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = serialization.WriteUint32(w, ti.Sequence)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn nil\n}", "func (c *Conn) Transaction(fn func(*Conn) error) error {\r\n\tvar (\r\n\t\ttx = c.Begin()\r\n\t\tconn = &Conn{}\r\n\t)\r\n\tcopier.Copy(conn, c)\r\n\tconn.DB = tx\r\n\tif err := fn(conn); err != nil {\r\n\t\ttx.Rollback()\r\n\t\treturn err\r\n\t}\r\n\ttx.Commit()\r\n\treturn nil\r\n}", "func (s *PersonStore) Transaction(callback func(*PersonStore) error) error {\n\tif callback == nil {\n\t\treturn kallax.ErrInvalidTxCallback\n\t}\n\n\treturn s.Store.Transaction(func(store *kallax.Store) error {\n\t\treturn callback(&PersonStore{store})\n\t})\n}", "func (_EthCrossChain *EthCrossChainCallerSession) Transactions(arg0 *big.Int) ([32]byte, error) {\n\treturn _EthCrossChain.Contract.Transactions(&_EthCrossChain.CallOpts, arg0)\n}", "func (c *Client) Transaction() <-chan *interfaces.TxWithBlock {\n\treturn c.transactions\n}", "func disconnectTransactions(txStore TxStore, block *massutil.Block) error {\n\tfor _, tx := range block.Transactions() {\n\t\tif txD, exists := txStore[*tx.Hash()]; exists {\n\t\t\ttxD.Tx = nil\n\t\t\ttxD.BlockHeight = 0\n\t\t\ttxD.Spent = nil\n\t\t\ttxD.Err = database.ErrTxShaMissing\n\t\t}\n\n\t\tfor _, txIn := range tx.MsgTx().TxIn {\n\t\t\toriginHash := &txIn.PreviousOutPoint.Hash\n\t\t\toriginIndex := txIn.PreviousOutPoint.Index\n\t\t\toriginTx, exists := txStore[*originHash]\n\t\t\tif exists && originTx.Tx != nil && originTx.Err == nil {\n\t\t\t\tif originIndex > uint32(len(originTx.Spent)) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\toriginTx.Spent[originIndex] = false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (api API) WalletTransactions(charID int64, accountKey int64, fromID int64, rowCount int64) (*WalletTransactionsResult, error) {\n\toutput := WalletTransactionsResult{}\n\targs := url.Values{}\n\n args.Add(\"characterID\", strconv.FormatInt(charID,10))\n args.Add(\"accountKey\", strconv.FormatInt(accountKey,10))\n if fromID != 0 {\n args.Add(\"fromID\", strconv.FormatInt(fromID,10))\n }\n args.Add(\"rowCount\", strconv.FormatInt(rowCount,10))\n\n\terr := api.Call(WalletTransactionsURL, args, &output)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif output.Error != nil {\n\t\treturn nil, output.Error\n\t}\n\treturn &output, nil\n}", "func (tx *transaction) Commit() error {\n\tif tx.terminated {\n\t\treturn errors.Wrap(engine.ErrTransactionDiscarded)\n\t}\n\n\tif !tx.writable {\n\t\treturn errors.Wrap(engine.ErrTransactionReadOnly)\n\t}\n\n\tselect {\n\tcase <-tx.ctx.Done():\n\t\treturn tx.Rollback()\n\tdefault:\n\t}\n\n\ttx.terminated = true\n\n\tfor _, fn := range tx.onCommit {\n\t\tfn()\n\t}\n\n\treturn nil\n}", "func (s *PostgresWalletStorage) StoreTransaction(transaction *types.Transaction) (*types.Transaction, error) {\n\tvar existingTransaction *types.Transaction\n\tvar err error\n\n\ttxIsNew := true\n\n\tif transaction.ID != uuid.Nil {\n\t\texistingTransaction, err = s.GetTransactionByID(transaction.ID)\n\t\tswitch err {\n\t\tcase nil: // tx already in database\n\t\t\ttxIsNew = false\n\t\tcase sql.ErrNoRows: // new tx\n\t\tdefault:\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif txIsNew && transaction.Hash != \"\" {\n\t\texistingTransaction, err = s.GetTransactionByHashDirectionAndAddress(transaction)\n\t\tswitch err {\n\t\tcase nil: // tx already in database\n\t\t\ttxIsNew = false\n\t\tcase sql.ErrNoRows: // new tx\n\t\tdefault:\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif !txIsNew {\n\t\t_, err := s.db.Exec(`UPDATE transactions SET hash = $1, block_hash = $2,\n\t\t\tconfirmations = $3, status = $4 WHERE id = $5`,\n\t\t\ttransaction.Hash,\n\t\t\ttransaction.BlockHash,\n\t\t\ttransaction.Confirmations,\n\t\t\ttransaction.Status.String(),\n\t\t\texistingTransaction.ID,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Update of tx data in DB failed: %s. Tx %#v\",\n\t\t\t\terr, transaction)\n\t\t}\n\t\texistingTransaction.Update(transaction)\n\t\treturn existingTransaction, nil\n\t}\n\n\tif transaction.ID == uuid.Nil {\n\t\tif transaction.Direction == types.OutgoingDirection {\n\t\t\tlog.Printf(\n\t\t\t\t\"Warning: generating new id for new unseen outgoing tx. \"+\n\t\t\t\t\t\"This should not happen because outgoing transactions are\"+\n\t\t\t\t\t\" generated by us. Tx: %v\",\n\t\t\t\ttransaction,\n\t\t\t)\n\t\t\tdebug.PrintStack()\n\t\t}\n\t\ttransaction.ID = uuid.Must(uuid.NewV4())\n\t}\n\tmetainfoJSON, err := json.Marshal(transaction.Metainfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tquery := fmt.Sprintf(`INSERT INTO transactions (%s)\n\t\t\tVALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)`,\n\t\ttransactionFields,\n\t)\n\t_, err = s.db.Exec(\n\t\tquery,\n\t\ttransaction.ID,\n\t\ttransaction.Hash,\n\t\ttransaction.BlockHash,\n\t\ttransaction.Confirmations,\n\t\ttransaction.Address,\n\t\ttransaction.Direction.String(),\n\t\ttransaction.Status.String(),\n\t\ttransaction.Amount,\n\t\tstring(metainfoJSON),\n\t\ttransaction.Fee,\n\t\ttransaction.FeeType.String(),\n\t\ttransaction.ColdStorage,\n\t\ttransaction.ReportedConfirmations,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to insert new tx into DB: %s. Tx %#v\",\n\t\t\terr, transaction)\n\t}\n\treturn transaction, nil\n}", "func writeBlocks(ctx context.Context, t *text.Text, connectionSignal <-chan string) {\n\n\tport := *givenPort\n\tsocket := gowebsocket.New(\"ws://localhost:\" + port + \"/websocket\")\n\n\tsocket.OnTextMessage = func(message string, socket gowebsocket.Socket) {\n\t\tcurrentBlock := gjson.Get(message, \"result.data.value.block.header.height\")\n\t\tif currentBlock.String() != \"\" {\n\t\t\tif err := t.Write(fmt.Sprintf(\"%s\\n\", \"Latest block height \"+currentBlock.String())); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\n\t}\n\n\tsocket.Connect()\n\n\tsocket.SendText(\"{ \\\"jsonrpc\\\": \\\"2.0\\\", \\\"method\\\": \\\"subscribe\\\", \\\"params\\\": [\\\"tm.event='NewBlock'\\\"], \\\"id\\\": 1 }\")\n\n\tfor {\n\t\tselect {\n\t\tcase s := <-connectionSignal:\n\t\t\tif s == \"no_connection\" {\n\t\t\t\tsocket.Close()\n\t\t\t}\n\t\t\tif s == \"reconnect\" {\n\t\t\t\twriteBlocks(ctx, t, connectionSignal)\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\tlog.Println(\"interrupt\")\n\t\t\tsocket.Close()\n\t\t\treturn\n\t\t}\n\t}\n}", "func (_Validator *ValidatorTransactorSession) ExecuteTransactions(data [][]byte, destination []common.Address, amount []*big.Int) (*types.Transaction, error) {\n\treturn _Validator.Contract.ExecuteTransactions(&_Validator.TransactOpts, data, destination, amount)\n}", "func (w *worker) fillTransactions(interrupt *int32, env *environment) error {\n\t// Split the pending transactions into locals and remotes\n\t// Fill the block with all available pending transactions.\n\tpending := w.entropy.TxPool().Pending(true)\n\tlocalTxs, remoteTxs := make(map[common.Address]model.Transactions), pending\n\tfor _, account := range w.entropy.TxPool().Locals() {\n\t\tif txs := remoteTxs[account]; len(txs) > 0 {\n\t\t\tdelete(remoteTxs, account)\n\t\t\tlocalTxs[account] = txs\n\t\t}\n\t}\n\tif len(localTxs) > 0 {\n\t\ttxs := model.NewTransactionsByPriceAndNonce(env.signer, localTxs, env.header.BaseFee)\n\t\tif err := w.commitTransactions(env, txs, interrupt); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif len(remoteTxs) > 0 {\n\t\ttxs := model.NewTransactionsByPriceAndNonce(env.signer, remoteTxs, env.header.BaseFee)\n\t\tif err := w.commitTransactions(env, txs, interrupt); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func Example_transactions() {\n\tdb, _ := dbx.Open(\"mysql\", \"user:pass@/example\")\n\n\tdb.Transactional(func(tx *dbx.Tx) error {\n\t\t_, err := tx.Insert(\"user\", dbx.Params{\n\t\t\t\"name\": \"user1\",\n\t\t}).Execute()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = tx.Insert(\"user\", dbx.Params{\n\t\t\t\"name\": \"user2\",\n\t\t}).Execute()\n\t\treturn err\n\t})\n}", "func finishTransaction(ctx context.Context, exec sqlexec.SQLExecutor, err error) error {\n\tif err == nil {\n\t\t_, err = exec.ExecuteInternal(ctx, \"commit\")\n\t} else {\n\t\t_, err1 := exec.ExecuteInternal(ctx, \"rollback\")\n\t\tterror.Log(errors.Trace(err1))\n\t}\n\treturn errors.Trace(err)\n}", "func (o *WalletTransactionsListResponse) SetTransactions(v []WalletTransaction) {\n\to.Transactions = v\n}", "func (msh *Mesh) StoreTransactionsFromPool(blk *types.Block) error {\n\t// Store transactions (doesn't have to be rolled back if other writes fail)\n\tif len(blk.TxIDs) == 0 {\n\t\treturn nil\n\t}\n\ttxs := make([]*types.Transaction, 0, len(blk.TxIDs))\n\tfor _, txID := range blk.TxIDs {\n\t\ttx, err := msh.txPool.Get(txID)\n\t\tif err != nil {\n\t\t\t// if the transaction is not in the pool it could have been\n\t\t\t// invalidated by another block\n\t\t\tif has, err := msh.transactions.Has(txID.Bytes()); !has {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif err = tx.CalcAndSetOrigin(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttxs = append(txs, tx)\n\t}\n\tif err := msh.writeTransactions(blk, txs...); err != nil {\n\t\treturn fmt.Errorf(\"could not write transactions of block %v database: %v\", blk.ID(), err)\n\t}\n\n\tif err := msh.addToUnappliedTxs(txs, blk.LayerIndex); err != nil {\n\t\treturn fmt.Errorf(\"failed to add to unappliedTxs: %v\", err)\n\t}\n\n\t// remove txs from pool\n\tmsh.invalidateFromPools(&blk.MiniBlock)\n\n\treturn nil\n}", "func (s *Scheduler) consumeTransactions() {\n\tdefer s.wg.Done()\n\tfor {\n\t\ttxn, canceled := s.dequeueTxn()\n\t\tif canceled {\n\t\t\treturn\n\t\t}\n\t\ts.processTransaction(txn)\n\t}\n}", "func (s *Spammer) PostTransaction(tx *devnetvm.Transaction, clt evilwallet.Client) {\n\tif tx == nil {\n\t\ts.log.Debug(ErrTransactionIsNil)\n\t\ts.ErrCounter.CountError(ErrTransactionIsNil)\n\t}\n\tallSolid := s.handleSolidityForReuseOutputs(clt, tx)\n\tif !allSolid {\n\t\ts.log.Debug(ErrInputsNotSolid)\n\t\ts.ErrCounter.CountError(errors.WithMessagef(ErrInputsNotSolid, \"txID: %s\", tx.ID().Base58()))\n\t\treturn\n\t}\n\n\tif err := evilwallet.RateSetterSleep(clt, s.UseRateSetter); err != nil {\n\t\treturn\n\t}\n\ttxID, blockID, err := clt.PostTransaction(tx)\n\tif err != nil {\n\t\ts.log.Debug(ErrFailPostTransaction)\n\t\ts.ErrCounter.CountError(errors.WithMessage(ErrFailPostTransaction, err.Error()))\n\t\treturn\n\t}\n\tif s.EvilScenario.OutputWallet.Type() == evilwallet.Reuse {\n\t\ts.EvilWallet.SetTxOutputsSolid(tx.Essence().Outputs(), clt.URL())\n\t}\n\n\tcount := s.State.txSent.Add(1)\n\ts.log.Debugf(\"%s: Last transaction sent, ID: %s, txCount: %d\", blockID.Base58(), txID.Base58(), count)\n}", "func createTransaction(\n\tctx context.Context,\n\tdb storage.Database,\n\tappserviceID string,\n) (\n\ttransactionJSON []byte,\n\ttxnID, maxID int,\n\teventsRemaining bool,\n\terr error,\n) {\n\t// Retrieve the latest events from the DB (will return old events if they weren't successfully sent)\n\ttxnID, maxID, events, eventsRemaining, err := db.GetEventsWithAppServiceID(ctx, appserviceID, transactionBatchSize)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"appservice\": appserviceID,\n\t\t}).WithError(err).Fatalf(\"appservice worker unable to read queued events from DB\")\n\n\t\treturn\n\t}\n\n\t// Check if these events do not already have a transaction ID\n\tif txnID == -1 {\n\t\t// If not, grab next available ID from the DB\n\t\ttxnID, err = db.GetLatestTxnID(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, 0, 0, false, err\n\t\t}\n\n\t\t// Mark new events with current transactionID\n\t\tif err = db.UpdateTxnIDForEvents(ctx, appserviceID, maxID, txnID); err != nil {\n\t\t\treturn nil, 0, 0, false, err\n\t\t}\n\t}\n\n\tvar ev []*gomatrixserverlib.HeaderedEvent\n\tfor i := range events {\n\t\tev = append(ev, &events[i])\n\t}\n\n\t// Create a transaction and store the events inside\n\ttransaction := gomatrixserverlib.ApplicationServiceTransaction{\n\t\tEvents: gomatrixserverlib.HeaderedToClientEvents(ev, gomatrixserverlib.FormatAll),\n\t}\n\n\ttransactionJSON, err = json.Marshal(transaction)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func Transaction(fn func (tx *sql.Tx) (interface{}, *sql.Stmt, error)) (interface{}, error) {\n\n\tdefer func(){\n\t\tstr := recover()\n\t\tif str != nil{\n\t\t\tlog.Println(\"panic occur: \", str)\n\t\t}\n\t}()\n\n\tlog.Println(\"opening connection database\")\n\n\tdb, err := GetConnection()\n\tif err != nil {\n\t\tlog.Println(\"could not open connection\", err)\n\t\treturn nil, err\n\t}\n\tdefer func(){\n\t\tlog.Println(\"m=Transaction,msg=closing connection\")\n\t\tdb.Close()\n\t}()\n\n\tlog.Println(\"begin transaction\")\n\ttx,err := db.Begin()\n\tif err != nil {\n\t\tlog.Println(\"could not open transaction\", err)\n\t\treturn nil, err\n\t}\n\n\tlog.Println(\"calling callback\")\n\tit, stm, err := fn(tx)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\tlog.Println(\"could not run stm\", err)\n\t\treturn nil, err\n\t}\n\tdefer func(){\n\t\tlog.Println(\"closed stm\")\n\t\tstm.Close()\n\t}()\n\tlog.Println(\"callback successfull called, commiting\")\n\terr = tx.Commit()\n\tlog.Println(\"transaction commited\")\n\tif err != nil {\n\t\tlog.Println(\"could not commit transaction\", err)\n\t\treturn nil, err\n\t}\n\n\treturn it, err\n}", "func (_m *Repository) CommitTransaction(ctx context.Context) {\n\t_m.Called(ctx)\n}", "func Transactions(exec boil.Executor, mods ...qm.QueryMod) transactionQuery {\n\tmods = append(mods, qm.From(\"`transactions`\"))\n\treturn transactionQuery{NewQuery(exec, mods...)}\n}", "func SyncTransactions(\n\tctx context.Context,\n\tcompany *Company,\n\tsubscription *braintree.Subscription,\n) error {\n\n\tcompanyKey := company.Key(ctx)\n\n\t// TODO: Add 6-month cutoff.\n\tfor _, btTransaction := range subscription.Transactions.Transaction {\n\t\tvar transaction Transaction\n\n\t\tkey := datastore.NewKey(ctx, transactionKind, btTransaction.Id, 0, companyKey)\n\t\tif err := nds.Get(ctx, key, &transaction); err == datastore.ErrNoSuchEntity {\n\t\t\ttransaction.Company = companyKey\n\t\t\ttransaction.SubscriptionID = subscription.Id\n\t\t\ttransaction.SubscriptionPlanID = subscription.PlanId\n\t\t\ttransaction.SubscriptionCountry = company.SubscriptionCountry\n\t\t\ttransaction.SubscriptionVATID = company.SubscriptionVATID\n\t\t\tif company.SubscriptionVATID == \"\" {\n\t\t\t\ttransaction.SubscriptionVATPercent = utils.LookupVAT(company.SubscriptionCountry)\n\t\t\t}\n\t\t}\n\n\t\ttransaction.TransactionID = btTransaction.Id\n\t\ttransaction.TransactionType = btTransaction.Type\n\t\ttransaction.TransactionStatus = btTransaction.Status\n\t\ttransaction.TransactionAmount = btTransaction.Amount.Unscaled\n\n\t\ttransaction.CreatedAt = *btTransaction.CreatedAt\n\t\ttransaction.UpdatedAt = *btTransaction.UpdatedAt\n\t\tif _, err := nds.Put(ctx, key, &transaction); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m Middleware) Tx(db *sql.DB) TxFunc {\n\treturn func(f func(tx daos.Transaction, w http.ResponseWriter, r *http.Request) error) http.HandlerFunc {\n\t\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\t\tt, err := db.Begin()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tdefer func() {\n\t\t\t\tl := m.log.WithRequest(r)\n\t\t\t\tif p := recover(); p != nil {\n\t\t\t\t\tt.Rollback()\n\t\t\t\t\tl.Info(\"transaction rollbacked\")\n\t\t\t\t\tpanic(p)\n\t\t\t\t} else if err != nil {\n\t\t\t\t\tt.Rollback()\n\t\t\t\t\tl.Info(\"transaction rollbacked\")\n\t\t\t\t\tpanic(err)\n\t\t\t\t} else {\n\t\t\t\t\terr = t.Commit()\n\t\t\t\t\tl.Info(\"transaction commited\")\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\terr = f(t, w, r)\n\t\t}\n\t}\n}", "func (app *builder) WithTransactions(trx []hash.Hash) Builder {\n\tapp.trx = trx\n\treturn app\n}", "func (m *MockDynamoDBAPI) TransactWriteItems(arg0 context.Context, arg1 *dynamodb.TransactWriteItemsInput, arg2 ...func(*dynamodb.Options)) (*dynamodb.TransactWriteItemsOutput, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"TransactWriteItems\", varargs...)\n\tret0, _ := ret[0].(*dynamodb.TransactWriteItemsOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (s *State) Persist() error {\n\tmempool := make([]Transaction, len(s.txMempool))\n\tcopy(mempool, s.txMempool)\n\n\tfor i := 0; i < len(mempool); i++ {\n\t\ttxJson, err := json.Marshal(mempool[i])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif _, err = s.dbFile.Write(append(txJson, '\\n')); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Remove the Transaction written to a file from the mempool\n\t\ts.txMempool = s.txMempool[1:]\n\t}\n\n\treturn nil\n}", "func CommitTxn(txn *types.Transaction) error {\n\tbodyBuff := bytes.NewBuffer(nil)\n\tif err := json.NewEncoder(bodyBuff).Encode(txn); err != nil {\n\t\treturn err\n\t}\n\tresp, err := RivineRequest(\"POST\", \"/transactionpool/transactions\", bodyBuff)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn errors.New(\"Failed to commit txn: \" + string(body))\n\t}\n\treturn nil\n}", "func (_Validator *ValidatorTransactor) ExecuteTransactions(opts *bind.TransactOpts, data [][]byte, destination []common.Address, amount []*big.Int) (*types.Transaction, error) {\n\treturn _Validator.contract.Transact(opts, \"executeTransactions\", data, destination, amount)\n}", "func (dao *SysConfigDao) Transaction(ctx context.Context, f func(ctx context.Context, tx gdb.TX) error) (err error) {\n\treturn dao.Ctx(ctx).Transaction(ctx, f)\n}", "func (b *Block) Transactions() tx.Transactions {\n\treturn append(tx.Transactions(nil), b.txs...)\n}", "func (c *context) write(data []byte) error {\n\tdefer c.close()\n\t_, err := c.conn.Write(data)\n\n\treturn err\n}" ]
[ "0.57876074", "0.55413955", "0.540568", "0.5267858", "0.516664", "0.5153982", "0.5146749", "0.50884444", "0.508247", "0.50363714", "0.502477", "0.5023313", "0.5020898", "0.5010816", "0.49901876", "0.49889544", "0.49859205", "0.49845076", "0.49823585", "0.49817055", "0.49813595", "0.49777612", "0.49645364", "0.49084464", "0.49084234", "0.490646", "0.48998088", "0.48684686", "0.4866245", "0.4862941", "0.48588505", "0.48480457", "0.48471388", "0.4832108", "0.48279768", "0.4799404", "0.4766341", "0.47617063", "0.475154", "0.47467247", "0.47450584", "0.47320017", "0.47260416", "0.4717182", "0.47144875", "0.47035575", "0.470323", "0.4700259", "0.46905562", "0.4689779", "0.46595365", "0.46476734", "0.46316242", "0.46286097", "0.46242332", "0.4622971", "0.4620798", "0.46193275", "0.46188542", "0.46164554", "0.4613569", "0.46129766", "0.46040514", "0.4600382", "0.45844522", "0.45808673", "0.45741662", "0.45669505", "0.45665884", "0.4564807", "0.45476946", "0.45452672", "0.45442885", "0.4540564", "0.45394343", "0.4538602", "0.45383602", "0.453761", "0.45352715", "0.4531022", "0.45274612", "0.452594", "0.45240027", "0.45159015", "0.45155227", "0.45113882", "0.45105398", "0.45093995", "0.45089585", "0.4505649", "0.44971377", "0.44970417", "0.44903", "0.44856623", "0.4485454", "0.44829085", "0.44762203", "0.44711652", "0.447102", "0.4468899" ]
0.6411364
0
writeBlocks writes the latest Block to the blocksWidget. Exits when the context expires.
func writeBlocks(ctx context.Context, t *text.Text, connectionSignal <-chan string) { port := *givenPort socket := gowebsocket.New("ws://localhost:" + port + "/websocket") socket.OnTextMessage = func(message string, socket gowebsocket.Socket) { currentBlock := gjson.Get(message, "result.data.value.block.header.height") if currentBlock.String() != "" { if err := t.Write(fmt.Sprintf("%s\n", "Latest block height "+currentBlock.String())); err != nil { panic(err) } } } socket.Connect() socket.SendText("{ \"jsonrpc\": \"2.0\", \"method\": \"subscribe\", \"params\": [\"tm.event='NewBlock'\"], \"id\": 1 }") for { select { case s := <-connectionSignal: if s == "no_connection" { socket.Close() } if s == "reconnect" { writeBlocks(ctx, t, connectionSignal) } case <-ctx.Done(): log.Println("interrupt") socket.Close() return } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (d *Data) writeBlocks(v dvid.VersionID, b storage.TKeyValues, wg1, wg2 *sync.WaitGroup) error {\n\tbatcher, err := datastore.GetKeyValueBatcher(d)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpreCompress, postCompress := 0, 0\n\n\tctx := datastore.NewVersionedCtx(d, v)\n\tevt := datastore.SyncEvent{d.DataUUID(), IngestBlockEvent}\n\n\tserver.CheckChunkThrottling()\n\tgo func() {\n\t\tdefer func() {\n\t\t\twg1.Done()\n\t\t\twg2.Done()\n\t\t\tdvid.Debugf(\"Wrote voxel blocks. Before %s: %d bytes. After: %d bytes\\n\", d.Compression(), preCompress, postCompress)\n\t\t\tserver.HandlerToken <- 1\n\t\t}()\n\n\t\tmutID := d.NewMutationID()\n\t\tbatch := batcher.NewBatch(ctx)\n\t\tfor i, block := range b {\n\t\t\tserialization, err := dvid.SerializeData(block.V, d.Compression(), d.Checksum())\n\t\t\tpreCompress += len(block.V)\n\t\t\tpostCompress += len(serialization)\n\t\t\tif err != nil {\n\t\t\t\tdvid.Errorf(\"Unable to serialize block: %v\\n\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tbatch.Put(block.K, serialization)\n\n\t\t\tindexZYX, err := DecodeTKey(block.K)\n\t\t\tif err != nil {\n\t\t\t\tdvid.Errorf(\"Unable to recover index from block key: %v\\n\", block.K)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tmsg := datastore.SyncMessage{IngestBlockEvent, v, Block{indexZYX, block.V, mutID}}\n\t\t\tif err := datastore.NotifySubscribers(evt, msg); err != nil {\n\t\t\t\tdvid.Errorf(\"Unable to notify subscribers of ChangeBlockEvent in %s\\n\", d.DataName())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Check if we should commit\n\t\t\tif i%KVWriteSize == KVWriteSize-1 {\n\t\t\t\tif err := batch.Commit(); err != nil {\n\t\t\t\t\tdvid.Errorf(\"Error on trying to write batch: %v\\n\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tbatch = batcher.NewBatch(ctx)\n\t\t\t}\n\t\t}\n\t\tif err := batch.Commit(); err != nil {\n\t\t\tdvid.Errorf(\"Error on trying to write batch: %v\\n\", err)\n\t\t\treturn\n\t\t}\n\t}()\n\treturn nil\n}", "func BlockWrite(w io.Writer, l Level, text string) error {\n\treturn NewBlockWriter(l, w).QR(text)\n}", "func writeBlock(w io.Writer, pver uint32, b *MicroBlock) error {\n\tsec := uint32(bh.Timestamp.Unix())\n\treturn writeElements(w, b.Version, &b.PrevBlock, &b.MerkleRoot,\n\t\tsec, b.Bits)\n}", "func (b *Block) Write() error {\n\tdata := []byte(b.String())\n\tfname := \"blocks/\" + strconv.Itoa(b.Number) + \".block\"\n\n\tif err := ioutil.WriteFile(fname, data, 0600); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func WriteBlock(chain uint64, data []byte) error {\n\tkey := runtime.GetHash(data)\n\texist := runtime.DbExist(dbBlockData{}, chain, key)\n\tif exist {\n\t\treturn nil\n\t}\n\n\treturn runtime.AdminDbSet(dbBlockData{}, chain, key, data, 2<<50)\n}", "func writeBlock(file *os.File, index int64, data *dataBlock) {\n\tfile.Seek(index, 0)\n\t//Empezamos el proceso de guardar en binario la data en memoria del struct\n\tvar binaryDisc bytes.Buffer\n\tbinary.Write(&binaryDisc, binary.BigEndian, data)\n\twriteNextBytes(file, binaryDisc.Bytes())\n}", "func BlockWriteFile(filename string, l Level, text string) error {\n\treturn NewBlockWriter(l, nil).QRFile(filename, text)\n}", "func (h *NeutrinoDBStore) WriteBlockHeaders(tx walletdb.ReadWriteTx, hdrs ...BlockHeader) er.R {\n\theaderLocs := make([]headerEntryWithHeight, len(hdrs))\n\tfor i, header := range hdrs {\n\t\theaderLocs[i].Header = header.toIndexEntry()\n\t\theaderLocs[i].Height = header.Height\n\t}\n\treturn h.addBlockHeaders(tx, headerLocs, false)\n}", "func (hlr *HandlerEnv) GetBlockWrites(c *gin.Context) {\n\tvar err error\n\tvar blkWrts []mdl.BlockWrite\n\tvar rsp = make(map[string]interface{})\n\n\t// Fetch the block writes from the database\n\topts := options.Find().SetSort(bson.D{{\"manifest.timestamp\", -1}})\n\tcsr, err := hlr.CollBlockWrites.Find(context.TODO(), bson.M{\"deleted\": bson.M{\"$ne\": true}}, opts)\n\tif err != nil {\n\t\t// error fetching blockwrites from the database\n\t\tlog.Printf(\"ERROR: %v - error fetching blockwrites from the database. See: %v\\n\",\n\t\t\tutils.FileLine(),\n\t\t\terr)\n\t\trsp[\"msg\"] = \"an error occurred, please try again\"\n\t\tc.JSON(http.StatusInternalServerError, rsp)\n\t\treturn\n\t}\n\n\t// Grab all blockwrites from the query\n\terr = csr.All(context.TODO(), &blkWrts)\n\tif err != nil {\n\t\t// error accessing blockwrite data\n\t\tlog.Printf(\"ERROR: %v - error accessing blockwrite data. See: %v\\n\",\n\t\t\tutils.FileLine(),\n\t\t\terr)\n\t\trsp[\"msg\"] = \"an error occurred, please try again\"\n\t\tc.JSON(http.StatusInternalServerError, rsp)\n\t\treturn\n\t}\n\n\t// Iterate through the query results and construct a response\n\tvar tmpCntArr []map[string]interface{}\n\tfor _, elm := range blkWrts {\n\t\tvar tmpCnt = make(map[string]interface{})\n\n\t\t// Construct a response array element\n\t\ttmpCnt[\"docid\"] = elm.RequestID\n\t\ttmpCnt[\"source\"] = elm.Source\n\t\ttmpCnt[\"event\"] = elm.Event\n\t\ttmpCnt[\"network\"] = elm.ChainNetwork\n\t\ttmpCnt[\"timestamp\"] = fmt.Sprintf(\"%v CST\", elm.Manifest.TimeStamp[:19])\n\t\ttmpCnt[\"block\"] = elm.BlockNumber\n\t\ttmpCnt[\"explorer_link\"] = fmt.Sprintf(\"%vblock/%v\",\n\t\t\tconfig.Consts[\"gochain_testnet_explorer\"],\n\t\t\telm.BlockNumber)\n\n\t\ttmpCnt[\"alert\"] = \"none\"\n\t\t// Set \"alert\" to highlight rows in the client\n\t\tif strings.Contains(strings.ToLower(elm.Event), \"alert\") {\n\t\t\ttmpCnt[\"alert\"] = \"alert\"\n\t\t}\n\n\t\t// Add element to the response\n\t\ttmpCntArr = append(tmpCntArr, tmpCnt)\n\t}\n\n\t// Construct the final response\n\trsp[\"msg\"] = \"blockwrites\"\n\trsp[\"content\"] = tmpCntArr\n\n\tc.JSON(http.StatusOK, rsp)\n}", "func flushBlocks(w *os.File, data []*batch.Batch, meta *metadata.Segment) error {\n\tvar metaBuf bytes.Buffer\n\theader := make([]byte, 32)\n\tcopy(header, encoding.EncodeUint64(Version))\n\terr := binary.Write(&metaBuf, binary.BigEndian, header)\n\tif err != nil {\n\t\treturn err\n\t}\n\treserved := make([]byte, 64)\n\terr = binary.Write(&metaBuf, binary.BigEndian, reserved)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = binary.Write(&metaBuf, binary.BigEndian, uint8(compress.Lz4))\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = binary.Write(&metaBuf, binary.BigEndian, uint32(len(data)))\n\tif err != nil {\n\t\treturn err\n\t}\n\tcolDefs := meta.Table.Schema.ColDefs\n\tcolCnt := len(colDefs)\n\tif err = binary.Write(&metaBuf, binary.BigEndian, uint32(colCnt)); err != nil {\n\t\treturn err\n\t}\n\tfor _, blk := range meta.BlockSet {\n\t\tif err = binary.Write(&metaBuf, binary.BigEndian, blk.Count); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trangeBuf, _ := meta.CommitInfo.LogRange.Marshal()\n\t\tif err = binary.Write(&metaBuf, binary.BigEndian, rangeBuf); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar preIdx []byte\n\t\tif blk.CommitInfo.PrevIndex != nil {\n\t\t\tpreIdx, err = blk.CommitInfo.PrevIndex.Marshal()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tpreIdx = make([]byte, blkIdxSize)\n\t\t}\n\t\tif err = binary.Write(&metaBuf, binary.BigEndian, preIdx); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar idx []byte\n\t\tif blk.CommitInfo.LogIndex != nil {\n\t\t\tidx, err = blk.CommitInfo.LogIndex.Marshal()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tidx = make([]byte, blkIdxSize)\n\t\t}\n\t\tif err = binary.Write(&metaBuf, binary.BigEndian, idx); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvar dataBuf bytes.Buffer\n\tcolSizes := make([]int, colCnt)\n\tfor i := 0; i < colCnt; i++ {\n\t\tcolSz := 0\n\t\tfor _, bat := range data {\n\t\t\tcolBuf, err := bat.Vecs[i].Show()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcolSize := len(colBuf)\n\t\t\tcbuf := make([]byte, lz4.CompressBlockBound(colSize))\n\t\t\tif cbuf, err = compress.Compress(colBuf, cbuf, compress.Lz4); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err = binary.Write(&metaBuf, binary.BigEndian, uint64(len(cbuf))); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err = binary.Write(&metaBuf, binary.BigEndian, uint64(colSize)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err = binary.Write(&dataBuf, binary.BigEndian, cbuf); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcolSz += len(cbuf)\n\t\t}\n\t\tcolSizes[i] = colSz\n\t}\n\n\tmetaSize := headerSize +\n\t\treservedSize +\n\t\talgoSize +\n\t\tblkCntSize +\n\t\tcolCntSize +\n\t\tstartPosSize +\n\t\tendPosSize +\n\t\tlen(data)*(blkCountSize+2*blkIdxSize+blkRangeSize) +\n\t\tlen(data)*colCnt*(colSizeSize*2) +\n\t\tcolCnt*colPosSize\n\n\tstartPos := int64(metaSize)\n\tcurPos := startPos\n\tcolPoses := make([]int64, colCnt)\n\tfor i, colSz := range colSizes {\n\t\tcolPoses[i] = curPos\n\t\tcurPos += int64(colSz)\n\t}\n\tendPos := curPos\n\tif err = binary.Write(&metaBuf, binary.BigEndian, startPos); err != nil {\n\t\treturn err\n\t}\n\tif err = binary.Write(&metaBuf, binary.BigEndian, endPos); err != nil {\n\t\treturn err\n\t}\n\tfor _, colPos := range colPoses {\n\t\tif err = binary.Write(&metaBuf, binary.BigEndian, colPos); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif _, err = w.Write(metaBuf.Bytes()); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err = w.Write(dataBuf.Bytes()); err != nil {\n\t\treturn err\n\n\t}\n\n\treturn nil\n}", "func (v *Voxels) WriteBlock(block *storage.TKeyValue, blockSize dvid.Point) error {\n\treturn v.writeBlock(block, blockSize)\n}", "func (d *Data) PutBlocks(v dvid.VersionID, mutID uint64, start dvid.ChunkPoint3d, span int, data io.ReadCloser, mutate bool) error {\n\tbatcher, err := datastore.GetKeyValueBatcher(d)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx := datastore.NewVersionedCtx(d, v)\n\tbatch := batcher.NewBatch(ctx)\n\n\t// Read blocks from the stream until we can output a batch put.\n\tconst BatchSize = 1000\n\tvar readBlocks int\n\tnumBlockBytes := d.BlockSize().Prod()\n\tchunkPt := start\n\tbuf := make([]byte, numBlockBytes)\n\tfor {\n\t\t// Read a block's worth of data\n\t\treadBytes := int64(0)\n\t\tfor {\n\t\t\tn, err := data.Read(buf[readBytes:])\n\t\t\treadBytes += int64(n)\n\t\t\tif readBytes == numBlockBytes {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif err == io.EOF {\n\t\t\t\treturn fmt.Errorf(\"block data ceased before all block data read\")\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error reading blocks: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\tif readBytes != numBlockBytes {\n\t\t\treturn fmt.Errorf(\"expected %d bytes in block read, got %d instead, aborting\", numBlockBytes, readBytes)\n\t\t}\n\n\t\tserialization, err := dvid.SerializeData(buf, d.Compression(), d.Checksum())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tzyx := dvid.IndexZYX(chunkPt)\n\t\ttk := NewTKey(&zyx)\n\n\t\t// If we are mutating, get the previous block of data.\n\t\tvar oldBlock []byte\n\t\tif mutate {\n\t\t\toldBlock, err = d.GetBlock(v, tk)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to load previous block in %q, key %v: %v\", d.DataName(), tk, err)\n\t\t\t}\n\t\t}\n\n\t\t// Write the new block\n\t\tbatch.Put(tk, serialization)\n\n\t\t// Notify any subscribers that you've changed block.\n\t\tvar event string\n\t\tvar delta interface{}\n\t\tif mutate {\n\t\t\tevent = MutateBlockEvent\n\t\t\tdelta = MutatedBlock{&zyx, oldBlock, buf, mutID}\n\t\t} else {\n\t\t\tevent = IngestBlockEvent\n\t\t\tdelta = Block{&zyx, buf, mutID}\n\t\t}\n\t\tevt := datastore.SyncEvent{d.DataUUID(), event}\n\t\tmsg := datastore.SyncMessage{event, v, delta}\n\t\tif err := datastore.NotifySubscribers(evt, msg); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Advance to next block\n\t\tchunkPt[0]++\n\t\treadBlocks++\n\t\tfinish := (readBlocks == span)\n\t\tif finish || readBlocks%BatchSize == 0 {\n\t\t\tif err := batch.Commit(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"error on batch commit, block %d: %v\", readBlocks, err)\n\t\t\t}\n\t\t\tif finish {\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tbatch = batcher.NewBatch(ctx)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func handleWriteBlock(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tvar m model.Message\n\n\t// Decode http request into message struct\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&m); err != nil {\n\t\trespondWithJSON(w, r, http.StatusBadRequest, r.Body)\n\t\treturn\n\t}\n\n\t// checks if the password is correct\n\t// if !authenticate(m.Password) {\n\t// \trespondWithJSON(w, r, http.StatusUnauthorized, r.Body)\n\t// }\n\n\tdefer r.Body.Close()\n\n\t//ensure atomicity when creating new block\n\tvar mutex = &sync.Mutex{}\n\tmutex.Lock()\n\tnewBlock := blockchainhelpers.GenerateBlock(model.Blockchain[len(model.Blockchain)-1], m.BPM)\n\tmutex.Unlock()\n\n\tif blockchainhelpers.IsBlockValid(newBlock, model.Blockchain[len(model.Blockchain)-1]) {\n\t\tmodel.Blockchain = append(model.Blockchain, newBlock)\n\t\tspew.Dump(model.Blockchain)\n\t}\n\n\trespondWithJSON(w, r, http.StatusCreated, newBlock)\n\n}", "func (ctx *DefaultContext) BlockFinalize() error {\n\tif len(ctx.logs) != 0 {\n\t\tlogs, err := json.Marshal(ctx.logs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tctx.wb.Put([]byte(fmt.Sprintf(\"block_log_%s_%d\", ctx.channelID, ctx.block.GetNumber())), logs)\n\t}\n\n\tfor addr, acc := range ctx.accounts {\n\t\t// sync account\n\t\tif acc.updated {\n\t\t\tif err := ctx.wb.SetAccount(acc.account.CommonAccount()); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tcommonAddr := bytesToCommonAddress([]byte(addr))\n\t\tif acc.account.HasSuicide() {\n\t\t\t// remove suicide account's storage\n\t\t\tctx.wb.RemoveAccountStorage(commonAddr)\n\t\t\tcontinue\n\t\t}\n\t\t// sync storage\n\t\tfor key, v := range acc.storage {\n\t\t\tif v.updated {\n\t\t\t\tif err := ctx.wb.SetStorage(commonAddr, bytesToCommomWord256([]byte(key)), bytesToCommomWord256(v.value)); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (w *writer) WriteBlock(pieceIndex, pieceOffset uint32, p []byte) (int, error) {\n\treturn w.WriteAt(p, w.info.PieceOffset(pieceIndex, pieceOffset))\n}", "func (dbv DiskBlockDevice) WriteBlock(index uint16, data Block) error {\n\tif index >= dbv.blocks {\n\t\treturn fmt.Errorf(\"device has %d blocks; tried to read block %d (index=%d)\", dbv.blocks, index+1, index)\n\t}\n\ti := int(index) * 2\n\tsectors := int(dbv.lsd.Sectors())\n\n\ttrack0 := i / sectors\n\tsector0 := i % sectors\n\tsector1 := sector0 + 1\n\ttrack1 := track0\n\tif sector1 == sectors {\n\t\tsector1 = 0\n\t\ttrack1++\n\t}\n\n\tif err := dbv.lsd.WriteLogicalSector(byte(track0), byte(sector0), data[:256]); err != nil {\n\t\treturn fmt.Errorf(\"error writing first half of block %d (t:%d s:%d): %v\", index, track0, sector0, err)\n\t}\n\tif err := dbv.lsd.WriteLogicalSector(byte(track1), byte(sector1), data[256:]); err != nil {\n\t\treturn fmt.Errorf(\"error writing second half of block %d (t:%d s:%d): %v\", index, track1, sector1, err)\n\t}\n\n\treturn nil\n}", "func (this *Block) WriteBlock(value int) {\n\tif this.Val != 0 {\n\t\tpanic(fmt.Sprintf(\"Cant Write to Block value %v\", value))\n\t}\n\tthis.Val = value\n}", "func (s *BlockStore) Write(b *block.Block) error {\n\terr := os.MkdirAll(s.RootDir, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfilename := s.filename(b.Hash)\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tdata, err := json.Marshal(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = f.Write(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (manager *SyncManager) SyncBlocks(latestHeight int64) error {\n\tmaybeLastIndexedHeight, err := manager.eventHandler.GetLastHandledEventHeight()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error running GetLastIndexedBlockHeight %v\", err)\n\t}\n\n\t// if none of the block has been indexed before, start with 0\n\tcurrentIndexingHeight := int64(0)\n\tif maybeLastIndexedHeight != nil {\n\t\tcurrentIndexingHeight = *maybeLastIndexedHeight + 1\n\t}\n\n\tmanager.logger.Infof(\"going to synchronized blocks from %d to %d\", currentIndexingHeight, latestHeight)\n\tfor currentIndexingHeight < latestHeight {\n\t\tblocksCommands, syncedHeight, err := manager.windowSyncStrategy.Sync(\n\t\t\tcurrentIndexingHeight, latestHeight, manager.syncBlockWorker,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error when synchronizing block with window strategy: %v\", err)\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error beginning transaction: %v\", err)\n\t\t}\n\t\tfor i, commands := range blocksCommands {\n\t\t\tblockHeight := currentIndexingHeight + int64(i)\n\n\t\t\tevents := make([]event.Event, 0, len(commands))\n\t\t\tfor _, command := range commands {\n\t\t\t\tevent, err := command.Exec()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"error generating event: %v\", err)\n\t\t\t\t}\n\t\t\t\tevents = append(events, event)\n\t\t\t}\n\n\t\t\terr := manager.eventHandler.HandleEvents(blockHeight, events)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error handling events: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\t// If there is any error before, short-circuit return in the error handling\n\t\t// while the local currentIndexingHeight won't be incremented and will be retried later\n\t\tmanager.logger.Infof(\"successfully synced to block height %d\", syncedHeight)\n\t\tcurrentIndexingHeight = syncedHeight + 1\n\t}\n\treturn nil\n}", "func (w *writer) flushBlock() error {\n\ttryTime := 2\n\tfor i := 0; i < len(w.blocks); i++ {\n\t\tif len(w.blocks[i].data) == blockSize && w.blocks[i].finished == false {\n\t\t\t// Try 3 time to upload the block if failed\n\t\t\ttryTime = 2\n\t\t\tfor ;tryTime >= 0 ; tryTime-- {\n\t\t\t\terr := w.uploadBlock(w.blocks[i])\n\t\t\t\tif err == nil {\n\t\t\t\t\tw.ctxs = append(w.ctxs, []byte(w.blocks[i].lastCtx))\n\t\t\t\t\tw.blocks[i].finished = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn errors.New(\"Up to max failur times\")\n\t\t}\n\t}\n\t// Remove uploaded block from blocks\n\tfor i:=0; i < len(w.blocks); i++ {\n\t\tif w.blocks[i].finished == false {\n\t\t\tw.blocks = w.blocks[i:]\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (w *Writer) finishBlock() (blockHandle, error) {\n\t// Write the restart points to the buffer.\n\tif w.nEntries == 0 {\n\t\t// Every block must have at least one restart point.\n\t\tw.restarts = w.restarts[:1]\n\t\tw.restarts[0] = 0\n\t}\n\ttmp4 := w.tmp[:4]\n\tfor _, x := range w.restarts {\n\t\tbinary.LittleEndian.PutUint32(tmp4, x)\n\t\tw.buf.Write(tmp4)\n\t}\n\tbinary.LittleEndian.PutUint32(tmp4, uint32(len(w.restarts)))\n\tw.buf.Write(tmp4)\n\n\t// Compress the buffer, discarding the result if the improvement\n\t// isn't at least 12.5%.\n\tb := w.buf.Bytes()\n\tw.tmp[0] = noCompressionBlockType\n\tif w.compression == db.SnappyCompression {\n\t\tcompressed, err := snappy.Encode(w.compressedBuf, b)\n\t\tif err != nil {\n\t\t\treturn blockHandle{}, err\n\t\t}\n\t\tw.compressedBuf = compressed[:cap(compressed)]\n\t\tif len(compressed) < len(b)-len(b)/8 {\n\t\t\tw.tmp[0] = snappyCompressionBlockType\n\t\t\tb = compressed\n\t\t}\n\t}\n\n\t// Calculate the checksum.\n\tchecksum := crc.New(b).Update(w.tmp[:1]).Value()\n\tbinary.LittleEndian.PutUint32(w.tmp[1:5], checksum)\n\n\t// Write the bytes to the file.\n\tif _, err := w.writer.Write(b); err != nil {\n\t\treturn blockHandle{}, err\n\t}\n\tif _, err := w.writer.Write(w.tmp[:5]); err != nil {\n\t\treturn blockHandle{}, err\n\t}\n\tbh := blockHandle{w.offset, uint64(len(b))}\n\tw.offset += uint64(len(b)) + blockTrailerLen\n\n\t// Reset the per-block state.\n\tw.buf.Reset()\n\tw.nEntries = 0\n\tw.restarts = w.restarts[:0]\n\treturn bh, nil\n}", "func (b *buffer) WriteBlock() safemem.Block {\n\treturn safemem.BlockFromSafeSlice(b.WriteSlice())\n}", "func (b *blockListV1) WriteBlockData(blockData interface{}) error {\n\tdataBytes, err := b.SerializeBlockData(blockData)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = b.writeBlockDataBytes(dataBytes)\n\treturn err\n}", "func (dao *blockDAO) putBlock(blk *block.Block) error {\n\tbatch := db.NewBatch()\n\n\theight := byteutil.Uint64ToBytes(blk.Height())\n\thash := blk.HashBlock()\n\tserHeader, err := blk.Header.Serialize()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to serialize block header\")\n\t}\n\tserBody, err := blk.Body.Serialize()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to serialize block body\")\n\t}\n\tserFooter, err := blk.Footer.Serialize()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to serialize block footer\")\n\t}\n\tif dao.compressBlock {\n\t\ttimer := dao.timerFactory.NewTimer(\"compress_header\")\n\t\tserHeader, err = compress.Compress(serHeader)\n\t\ttimer.End()\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"error when compressing a block header\")\n\t\t}\n\t\ttimer = dao.timerFactory.NewTimer(\"compress_body\")\n\t\tserBody, err = compress.Compress(serBody)\n\t\ttimer.End()\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"error when compressing a block body\")\n\t\t}\n\t\ttimer = dao.timerFactory.NewTimer(\"compress_footer\")\n\t\tserFooter, err = compress.Compress(serFooter)\n\t\ttimer.End()\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"error when compressing a block footer\")\n\t\t}\n\t}\n\tbatch.Put(blockHeaderNS, hash[:], serHeader, \"failed to put block header\")\n\tbatch.Put(blockBodyNS, hash[:], serBody, \"failed to put block body\")\n\tbatch.Put(blockFooterNS, hash[:], serFooter, \"failed to put block footer\")\n\n\thashKey := append(hashPrefix, hash[:]...)\n\tbatch.Put(blockHashHeightMappingNS, hashKey, height, \"failed to put hash -> height mapping\")\n\n\theightKey := append(heightPrefix, height...)\n\tbatch.Put(blockHashHeightMappingNS, heightKey, hash[:], \"failed to put height -> hash mapping\")\n\n\tvalue, err := dao.kvstore.Get(blockNS, topHeightKey)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to get top height\")\n\t}\n\ttopHeight := enc.MachineEndian.Uint64(value)\n\tif blk.Height() > topHeight {\n\t\tbatch.Put(blockNS, topHeightKey, height, \"failed to put top height\")\n\t}\n\n\tvalue, err = dao.kvstore.Get(blockNS, totalActionsKey)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to get total actions\")\n\t}\n\ttotalActions := enc.MachineEndian.Uint64(value)\n\ttotalActions += uint64(len(blk.Actions))\n\ttotalActionsBytes := byteutil.Uint64ToBytes(totalActions)\n\tbatch.Put(blockNS, totalActionsKey, totalActionsBytes, \"failed to put total actions\")\n\n\tif !dao.writeIndex {\n\t\treturn dao.kvstore.Commit(batch)\n\t}\n\tif err := indexBlock(dao.kvstore, blk, batch); err != nil {\n\t\treturn err\n\t}\n\treturn dao.kvstore.Commit(batch)\n}", "func writeFragmentBlocks(fileList []*finalizeFileInfo, f util.File, ws string, blocksize int, options FinalizeOptions, location int64) ([]fragmentBlock, int64, error) {\n\tcompressor := options.Compression\n\tif options.NoCompressFragments {\n\t\tcompressor = nil\n\t}\n\tfragmentData := make([]byte, 0)\n\tvar (\n\t\tallWritten int64\n\t\tfragmentBlockIndex uint32\n\t\tfragmentBlocks []fragmentBlock\n\t)\n\tfileCloseList := make([]*os.File, 0)\n\tdefer func() {\n\t\tfor _, f := range fileCloseList {\n\t\t\tf.Close()\n\t\t}\n\t}()\n\tfor _, e := range fileList {\n\t\t// only copy data for regular files\n\t\tif e.fileType != fileRegular {\n\t\t\tcontinue\n\t\t}\n\t\tvar (\n\t\t\twritten int64\n\t\t\terr error\n\t\t)\n\n\t\t// how much is there to put in a fragment?\n\t\tremainder := e.Size() % int64(blocksize)\n\t\tif remainder == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\t// would adding this data cause us to write?\n\t\tif len(fragmentData)+int(remainder) > blocksize {\n\t\t\twritten, compressed, err := finalizeFragment(fragmentData, f, location, compressor)\n\t\t\tif err != nil {\n\t\t\t\treturn fragmentBlocks, 0, fmt.Errorf(\"error writing fragment block %d: %v\", fragmentBlockIndex, err)\n\t\t\t}\n\t\t\tfragmentBlocks = append(fragmentBlocks, fragmentBlock{\n\t\t\t\tsize: uint32(written),\n\t\t\t\tcompressed: compressed,\n\t\t\t\tlocation: location,\n\t\t\t})\n\t\t\t// increment as all writes will be to next block block\n\t\t\tfragmentBlockIndex++\n\t\t\tfragmentData = fragmentData[:blocksize]\n\t\t}\n\n\t\te.fragment = &fragmentRef{\n\t\t\tblock: fragmentBlockIndex,\n\t\t\toffset: uint32(len(fragmentData)),\n\t\t}\n\t\t// save the fragment data from the file\n\n\t\tfrom, err := os.Open(path.Join(ws, e.path))\n\t\tif err != nil {\n\t\t\treturn fragmentBlocks, 0, fmt.Errorf(\"failed to open file for reading %s: %v\", e.path, err)\n\t\t}\n\t\tfileCloseList = append(fileCloseList, from)\n\t\tbuf := make([]byte, remainder)\n\t\tn, err := from.ReadAt(buf, e.Size()-remainder)\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn fragmentBlocks, 0, fmt.Errorf(\"error reading final %d bytes from file %s: %v\", remainder, e.Name(), err)\n\t\t}\n\t\tif n != len(buf) {\n\t\t\treturn fragmentBlocks, 0, fmt.Errorf(\"failed reading final %d bytes from file %s, only read %d\", remainder, e.Name(), n)\n\t\t}\n\t\tfrom.Close()\n\t\tfragmentData = append(fragmentData, buf...)\n\n\t\tallWritten += written\n\t\tif written > 0 {\n\t\t\tfragmentBlockIndex++\n\t\t}\n\t}\n\n\t// write remaining fragment data\n\tif len(fragmentData) > 0 {\n\t\twritten, compressed, err := finalizeFragment(fragmentData, f, location, compressor)\n\t\tif err != nil {\n\t\t\treturn fragmentBlocks, 0, fmt.Errorf(\"error writing fragment block %d: %v\", fragmentBlockIndex, err)\n\t\t}\n\t\tfragmentBlocks = append(fragmentBlocks, fragmentBlock{\n\t\t\tsize: uint32(written),\n\t\t\tcompressed: compressed,\n\t\t\tlocation: location,\n\t\t})\n\t\t// increment as all writes will be to next block block\n\t\tallWritten += int64(written)\n\t}\n\treturn fragmentBlocks, allWritten, nil\n}", "func (di *dataIndexer) SaveBlock(args *indexer.ArgsSaveBlockData) {\n\twi := workItems.NewItemBlock(\n\t\tdi.elasticProcessor,\n\t\tdi.marshalizer,\n\t\targs,\n\t)\n\tdi.dispatcher.Add(wi)\n}", "func generateBlock(oldBlock Block, Key int) Block {\n\n\tvar newBlock Block\n\n\tt := time.Now()\n\n\tnewBlock.Index = oldBlock.Index + 1\n\tnewBlock.Timestamp = t.String()\n\tnewBlock.Key = Key\n\tnewBlock.PrevHash = oldBlock.Hash\n\tnewBlock.Hash = calculateHash(newBlock)\n\n\tf, err := os.OpenFile(\"blocks.txt\",\n\t\tos.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tb, err := json.Marshal(newBlock)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer f.Close()\n\tif _, err := f.WriteString(string(b)); err != nil {\n\t\tlog.Println(err)\n\t}\n\n\treturn newBlock\n}", "func (v *View) WriteFromBlocks(srcs safemem.BlockSeq) (uint64, error) {\n\treturn v.WriteFromSafememReader(&safemem.BlockSeqReader{srcs}, srcs.NumBytes())\n}", "func WritersBlock(run Runtime, w writer.Output, fn func() error) (err error) {\n\twas := run.SetWriter(w)\n\te := fn()\n\trun.SetWriter(was)\n\tif e != nil {\n\t\terr = e\n\t} else {\n\t\terr = writer.Close(w)\n\t}\n\treturn\n}", "func ExportBlock(conn *dbus.Conn, path dbus.ObjectPath, v Blocker) error {\n\treturn conn.ExportSubtreeMethodTable(map[string]interface{}{\n\t\t\"AddConfigurationItem\": v.AddConfigurationItem,\n\t\t\"RemoveConfigurationItem\": v.RemoveConfigurationItem,\n\t\t\"UpdateConfigurationItem\": v.UpdateConfigurationItem,\n\t\t\"GetSecretConfiguration\": v.GetSecretConfiguration,\n\t\t\"Format\": v.Format,\n\t\t\"OpenForBackup\": v.OpenForBackup,\n\t\t\"OpenForRestore\": v.OpenForRestore,\n\t\t\"OpenForBenchmark\": v.OpenForBenchmark,\n\t\t\"OpenDevice\": v.OpenDevice,\n\t\t\"Rescan\": v.Rescan,\n\t}, path, InterfaceBlock)\n}", "func HalfBlockWrite(w io.Writer, l Level, text string) error {\n\treturn NewHalfBlockWriter(l, w).QR(text)\n}", "func (suite *MainIntegrationSuite) TestWriteBlock() {\n\t// Create a controller to write to the DB using the test tables.\n\tvar testDBClient dbclient.Controller\n\ttestDBClient, err := dbclient.New(\n\t\tdbclient.DBPort(injector.PostgresPort()),\n\t\tdbclient.DBName(injector.PostgresDBName()),\n\t\tdbclient.DBUser(injector.PostgresUserName()),\n\t\tdbclient.DBHost(injector.PostgresDomain()),\n\t\tdbclient.DBPassword(injector.PostgresPassword()),\n\t\tdbclient.PostgresClient(),\n\t\tdbclient.Test())\n\tsuite.NoError(err, \"There should be no error when init testDBClient\")\n\n\t// Create connection to the DB.\n\terr = testDBClient.Connect()\n\tdefer testDBClient.Close()\n\tsuite.NoError(err, \"There should be no error connecting to the DB\")\n\n\t// Retrieve blocks and transactions.\n\tblock := testutils.Block506664\n\t// txs := block.TX\n\n\t// Write the Block to the db.\n\terr = testDBClient.WriteBlock(block)\n\tsuite.NoError(err, \"Should be able to write block to the db\")\n}", "func (bc *Blockchain) SendBlocks() {\n for true {\n i := <-bc.BlockIndexChannel\n if i < len(bc.Chain) && i >= 0 {\n bc.GetBlockChannel <-bc.Chain[i]\n } else {\n // make an \"error\" block\n respBlock := Block {\n Index: -1,\n }\n bc.GetBlockChannel <-respBlock\n }\n }\n}", "func (w *streamedBlockWriter) Close() error {\n\tif w.finalized {\n\t\treturn nil\n\t}\n\tw.finalized = true\n\n\tmerr := tsdberrors.MultiError{}\n\n\tif w.ignoreFinalize {\n\t\t// Close open file descriptors anyway.\n\t\tfor _, cl := range w.closers {\n\t\t\tmerr.Add(cl.Close())\n\t\t}\n\t\treturn merr.Err()\n\t}\n\n\t// Finalize saves prepared index and metadata to corresponding files.\n\n\tif err := w.writeLabelSets(); err != nil {\n\t\treturn errors.Wrap(err, \"write label sets\")\n\t}\n\n\tif err := w.writeMemPostings(); err != nil {\n\t\treturn errors.Wrap(err, \"write mem postings\")\n\t}\n\n\tfor _, cl := range w.closers {\n\t\tmerr.Add(cl.Close())\n\t}\n\n\tif err := block.WriteIndexCache(\n\t\tw.logger,\n\t\tfilepath.Join(w.blockDir, block.IndexFilename),\n\t\tfilepath.Join(w.blockDir, block.IndexCacheFilename),\n\t); err != nil {\n\t\treturn errors.Wrap(err, \"write index cache\")\n\t}\n\n\tif err := w.writeMetaFile(); err != nil {\n\t\treturn errors.Wrap(err, \"write meta meta\")\n\t}\n\n\tif err := w.syncDir(); err != nil {\n\t\treturn errors.Wrap(err, \"sync blockDir\")\n\t}\n\n\tif err := merr.Err(); err != nil {\n\t\treturn errors.Wrap(err, \"finalize\")\n\t}\n\n\t// No error, claim success.\n\n\tlevel.Info(w.logger).Log(\n\t\t\"msg\", \"finalized downsampled block\",\n\t\t\"mint\", w.meta.MinTime,\n\t\t\"maxt\", w.meta.MaxTime,\n\t\t\"ulid\", w.meta.ULID,\n\t\t\"resolution\", w.meta.Thanos.Downsample.Resolution,\n\t)\n\treturn nil\n}", "func (lsm *lsm) Write(blocks, index []byte, bloom *bloom, keyRange *keyRange) error {\n\tlevel := lsm.levels[0]\n\tfileID := level.getUniqueID()\n\tfilename := filepath.Join(level.directory, fileID+\".sst\")\n\n\tkeyRangeEntry := createkeyRangeEntry(keyRange)\n\theader := createHeader(len(blocks), len(index), len(bloom.bits), len(keyRangeEntry))\n\tdata := append(header, append(append(append(blocks, index...), bloom.bits...), keyRangeEntry...)...)\n\n\terr := lsm.fm.Write(filename, data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlevel.NewSSTFile(fileID, keyRange, bloom)\n\n\treturn nil\n}", "func GetBlocks(w http.ResponseWriter, r *http.Request) {\n\t// Send a copy of this node's blockchain\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(b.blockchain)\n}", "func HalfBlockWriteFile(filename string, l Level, text string) error {\n\treturn NewHalfBlockWriter(l, nil).QRFile(filename, text)\n}", "func (c *RPCClient) FilterBlocks(\n\treq *FilterBlocksRequest) (*FilterBlocksResponse, er.R) {\n\n\tblockFilterer := NewBlockFilterer(c.chainParams, req)\n\n\t// Construct the watchlist using the addresses and outpoints contained\n\t// in the filter blocks request.\n\twatchList, err := buildFilterBlocksWatchList(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Iterate over the requested blocks, fetching the compact filter for\n\t// each one, and matching it against the watchlist generated above. If\n\t// the filter returns a positive match, the full block is then requested\n\t// and scanned for addresses using the block filterer.\n\tfor i, blk := range req.Blocks {\n\t\trawFilter, err := c.GetCFilter(&blk.Hash, wire.GCSFilterRegular)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Ensure the filter is large enough to be deserialized.\n\t\tif len(rawFilter.Data) < 4 {\n\t\t\tcontinue\n\t\t}\n\n\t\tfilter, err := gcs.FromNBytes(\n\t\t\tbuilder.DefaultP, builder.DefaultM, rawFilter.Data,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Skip any empty filters.\n\t\tif filter.N() == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tkey := builder.DeriveKey(&blk.Hash)\n\t\tmatched, err := filter.MatchAny(key, watchList)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t} else if !matched {\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Infof(\"Fetching block height=%d hash=%v\",\n\t\t\tblk.Height, blk.Hash)\n\n\t\trawBlock, err := c.GetBlock(&blk.Hash)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif !blockFilterer.FilterBlock(rawBlock) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// If any external or internal addresses were detected in this\n\t\t// block, we return them to the caller so that the rescan\n\t\t// windows can widened with subsequent addresses. The\n\t\t// `BatchIndex` is returned so that the caller can compute the\n\t\t// *next* block from which to begin again.\n\t\tresp := &FilterBlocksResponse{\n\t\t\tBatchIndex: uint32(i),\n\t\t\tBlockMeta: blk,\n\t\t\tFoundExternalAddrs: blockFilterer.FoundExternal,\n\t\t\tFoundInternalAddrs: blockFilterer.FoundInternal,\n\t\t\tFoundOutPoints: blockFilterer.FoundOutPoints,\n\t\t\tRelevantTxns: blockFilterer.RelevantTxns,\n\t\t}\n\n\t\treturn resp, nil\n\t}\n\n\t// No addresses were found for this range.\n\treturn nil, nil\n}", "func (b *Builder) writeBlockOffsets(builder *fbs.Builder) ([]fbs.UOffsetT, uint32) {\n\tvar startOffset uint32\n\tvar uoffs []fbs.UOffsetT\n\tfor _, bl := range b.blockList {\n\t\tuoff := b.writeBlockOffset(builder, bl, startOffset)\n\t\tuoffs = append(uoffs, uoff)\n\t\tstartOffset += uint32(bl.end)\n\t}\n\treturn uoffs, startOffset\n}", "func sendBlock(block *Block, ws *WrappedStream) error {\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tfmt.Println(\"recovered error in send block\", r)\n\t\t}\n\t}()\n\n\terr := ws.enc.Encode(block)\n\tif err != nil {\n\t\tlog.Printf(\"block encoding error:\\n\\n%v\\n\\n\", block)\n\t\treturn err\n\t}\n\t// Because output is buffered with bufio, we need to flush!\n\tws.w.Flush()\n\treturn err\n}", "func (b *Backend) CommitBlock() {\n\tblock, results, err := b.emulator.ExecuteAndCommitBlock()\n\tif err != nil {\n\t\tb.logger.WithError(err).Error(\"Failed to commit block\")\n\t\treturn\n\t}\n\n\tfor _, result := range results {\n\t\tprintTransactionResult(b.logger, result)\n\t}\n\n\tblockID := block.ID()\n\n\tb.logger.WithFields(logrus.Fields{\n\t\t\"blockHeight\": block.Header.Height,\n\t\t\"blockID\": hex.EncodeToString(blockID[:]),\n\t}).Debugf(\"📦 Block #%d committed\", block.Header.Height)\n}", "func (w *Writer) newBlockWriter(typ byte) *blockWriter {\n\tblock := w.block\n\n\tvar blockStart uint32\n\tif w.next == 0 {\n\t\thb := w.headerBytes()\n\t\tblockStart = uint32(copy(block, hb))\n\t}\n\n\tbw := newBlockWriter(typ, block, blockStart)\n\tbw.restartInterval = w.opts.RestartInterval\n\treturn bw\n}", "func saveBlockRaw(w kv.Putter, id polo.Bytes32, raw block.Raw) error {\n\treturn w.Put(append(blockPrefix, id[:]...), raw)\n}", "func (bw *BlockWriter) writeBlockWriteRequest(w io.Writer) error {\n\ttargets := bw.currentPipeline()[1:]\n\n\top := &hdfs.OpWriteBlockProto{\n\t\tHeader: &hdfs.ClientOperationHeaderProto{\n\t\t\tBaseHeader: &hdfs.BaseHeaderProto{\n\t\t\t\tBlock: bw.Block.GetB(),\n\t\t\t\tToken: bw.Block.GetBlockToken(),\n\t\t\t},\n\t\t\tClientName: proto.String(bw.ClientName),\n\t\t},\n\t\tTargets: targets,\n\t\tStage: bw.currentStage().Enum(),\n\t\tPipelineSize: proto.Uint32(uint32(len(targets))),\n\t\tMinBytesRcvd: proto.Uint64(bw.Block.GetB().GetNumBytes()),\n\t\tMaxBytesRcvd: proto.Uint64(uint64(bw.Offset)),\n\t\tLatestGenerationStamp: proto.Uint64(uint64(bw.generationTimestamp())),\n\t\tRequestedChecksum: &hdfs.ChecksumProto{\n\t\t\tType: hdfs.ChecksumTypeProto_CHECKSUM_CRC32C.Enum(),\n\t\t\tBytesPerChecksum: proto.Uint32(outboundChunkSize),\n\t\t},\n\t}\n\n\treturn writeBlockOpRequest(w, writeBlockOp, op)\n}", "func (client *Client) setBlock(b *types.Block) error {\n\tplog.Info(\"setBlock\", \"height\", b.Height, \"txCount\", len(b.Txs), \"hash\", common.ToHex(b.Hash(client.GetAPI().GetConfig())))\n\tlastBlock, err := client.RequestBlock(b.Height - 1)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = client.WriteBlock(lastBlock.StateHash, b)\n\tif err != nil {\n\t\tplog.Error(\"writeBlock error\", \"err\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (dcr *ExchangeWallet) monitorBlocks(ctx context.Context) {\n\tticker := time.NewTicker(blockTicker)\n\tdefer ticker.Stop()\n\n\tvar walletBlock <-chan *block\n\tif notifier, isNotifier := dcr.wallet.(tipNotifier); isNotifier {\n\t\twalletBlock = notifier.tipFeed()\n\t}\n\n\t// A polledBlock is a block found during polling, but whose broadcast has\n\t// been queued in anticipation of a wallet notification.\n\ttype polledBlock struct {\n\t\t*block\n\t\tqueue *time.Timer\n\t}\n\n\t// queuedBlock is the currently queued, polling-discovered block that will\n\t// be broadcast after a timeout if the wallet doesn't send the matching\n\t// notification.\n\tvar queuedBlock *polledBlock\n\n\t// checkTip captures queuedBlock and walletBlock.\n\tcheckTip := func() {\n\t\tctx, cancel := context.WithTimeout(dcr.ctx, 4*time.Second)\n\t\tdefer cancel()\n\n\t\tnewTip, err := dcr.getBestBlock(ctx)\n\t\tif err != nil {\n\t\t\tdcr.handleTipChange(nil, 0, fmt.Errorf(\"failed to get best block: %w\", err))\n\t\t\treturn\n\t\t}\n\n\t\tdcr.tipMtx.RLock()\n\t\tsameTip := dcr.currentTip.hash.IsEqual(newTip.hash)\n\t\tdcr.tipMtx.RUnlock()\n\n\t\tif sameTip {\n\t\t\treturn\n\t\t}\n\n\t\tif walletBlock == nil {\n\t\t\tdcr.handleTipChange(newTip.hash, newTip.height, nil)\n\t\t\treturn\n\t\t}\n\n\t\t// Queue it for reporting, but don't send it right away. Give the wallet\n\t\t// a chance to provide their block update. SPV wallet may need more time\n\t\t// after storing the block header to fetch and scan filters and issue\n\t\t// the FilteredBlockConnected report.\n\t\tif queuedBlock != nil {\n\t\t\tqueuedBlock.queue.Stop()\n\t\t}\n\t\tblockAllowance := walletBlockAllowance\n\t\tctx, cancel = context.WithTimeout(dcr.ctx, 4*time.Second)\n\t\tsynced, _, err := dcr.wallet.SyncStatus(ctx)\n\t\tcancel()\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"Error retrieving sync status before queuing polled block: %v\", err)\n\t\t} else if !synced {\n\t\t\tblockAllowance *= 10\n\t\t}\n\t\tqueuedBlock = &polledBlock{\n\t\t\tblock: newTip,\n\t\t\tqueue: time.AfterFunc(blockAllowance, func() {\n\t\t\t\tdcr.log.Warnf(\"Reporting a block found in polling that the wallet apparently \"+\n\t\t\t\t\t\"never reported: %s (%d). If you see this message repeatedly, it may indicate \"+\n\t\t\t\t\t\"an issue with the wallet.\", newTip.hash, newTip.height)\n\t\t\t\tdcr.handleTipChange(newTip.hash, newTip.height, nil)\n\t\t\t}),\n\t\t}\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tcheckTip()\n\n\t\tcase walletTip := <-walletBlock:\n\t\t\tif queuedBlock != nil && walletTip.height >= queuedBlock.height {\n\t\t\t\tif !queuedBlock.queue.Stop() && walletTip.hash == queuedBlock.hash {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tqueuedBlock = nil\n\t\t\t}\n\t\t\tdcr.handleTipChange(walletTip.hash, walletTip.height, nil)\n\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func (dcr *ExchangeWallet) monitorBlocks(ctx context.Context) {\n\tticker := time.NewTicker(blockTicker)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tdcr.checkForNewBlocks()\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func NewBlockWriter(block *hdfs.LocatedBlockProto, namenode *NamenodeConnection, blockSize int64) *BlockWriter {\n\tpm := newPipelineManager(namenode, block)\n\n\ts := &BlockWriter{\n\t\tpm: pm,\n\t\tblock: block,\n\t\tblockSize: blockSize,\n\t}\n\n\treturn s\n}", "func (self *StateStore) SaveCurrentBlock(height uint64, blockHash common.Hash) error {\n\tkey := self.getCurrentBlockKey()\n\tvalue := bytes.NewBuffer(nil)\n\tblockHash.Serialize(value)\n\tserialization.WriteUint64(value, height)\n\tself.store.BatchPut(key, value.Bytes())\n\treturn nil\n}", "func (b *blocksProviderImpl) DeliverBlocks() {\n\terrorStatusCounter := 0\n\tvar statusCounter uint64 = 0\n\tvar verErrCounter uint64 = 0\n\tvar delay time.Duration\n\n\tdefer b.client.CloseSend()\n\tfor !b.isDone() {\n\t\tmsg, err := b.client.Recv()\n\t\tif err != nil {\n\t\t\tlogger.Warningf(\"[%s] Receive error: %s\", b.chainID, err.Error())\n\t\t\treturn\n\t\t}\n\t\tswitch t := msg.Type.(type) {\n\t\tcase *orderer.DeliverResponse_Status:\n\t\t\tverErrCounter = 0\n\n\t\t\tif t.Status == common.Status_SUCCESS {\n\t\t\t\tlogger.Warningf(\"[%s] ERROR! Received success for a seek that should never complete\", b.chainID)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif t.Status == common.Status_BAD_REQUEST || t.Status == common.Status_FORBIDDEN {\n\t\t\t\tlogger.Errorf(\"[%s] Got error %v\", b.chainID, t)\n\t\t\t\terrorStatusCounter++\n\t\t\t\tif errorStatusCounter > b.wrongStatusThreshold {\n\t\t\t\t\tlogger.Criticalf(\"[%s] Wrong statuses threshold passed, stopping block provider\", b.chainID)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terrorStatusCounter = 0\n\t\t\t\tlogger.Warningf(\"[%s] Got error %v\", b.chainID, t)\n\t\t\t}\n\n\t\t\tdelay, statusCounter = computeBackOffDelay(statusCounter)\n\t\t\ttime.Sleep(delay)\n\t\t\tb.client.Disconnect()\n\t\t\tcontinue\n\t\tcase *orderer.DeliverResponse_Block:\n\t\t\terrorStatusCounter = 0\n\t\t\tstatusCounter = 0\n\t\t\tblockNum := t.Block.Header.Number\n\n\t\t\tmarshaledBlock, err := proto.Marshal(t.Block)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(\"[%s] Error serializing block with sequence number %d, due to %s; Disconnecting client from orderer.\", b.chainID, blockNum, err)\n\t\t\t\tdelay, verErrCounter = computeBackOffDelay(verErrCounter)\n\t\t\t\ttime.Sleep(delay)\n\t\t\t\tb.client.Disconnect()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif err := b.mcs.VerifyBlock(gossipcommon.ChannelID(b.chainID), blockNum, t.Block); err != nil {\n\t\t\t\tlogger.Errorf(\"[%s] Error verifying block with sequence number %d, due to %s; Disconnecting client from orderer.\", b.chainID, blockNum, err)\n\t\t\t\tdelay, verErrCounter = computeBackOffDelay(verErrCounter)\n\t\t\t\ttime.Sleep(delay)\n\t\t\t\tb.client.Disconnect()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tverErrCounter = 0 // On a good block\n\n\t\t\tnumberOfPeers := len(b.gossip.PeersOfChannel(gossipcommon.ChannelID(b.chainID)))\n\t\t\t// Create payload with a block received\n\t\t\tpayload := createPayload(blockNum, marshaledBlock)\n\t\t\t// Use payload to create gossip message\n\t\t\tgossipMsg := createGossipMsg(b.chainID, payload)\n\n\t\t\tlogger.Debugf(\"[%s] Adding payload to local buffer, blockNum = [%d]\", b.chainID, blockNum)\n\t\t\t// Add payload to local state payloads buffer\n\t\t\tif err := b.gossip.AddPayload(b.chainID, payload); err != nil {\n\t\t\t\tlogger.Warningf(\"Block [%d] received from ordering service wasn't added to payload buffer: %v\", blockNum, err)\n\t\t\t}\n\n\t\t\t// Gossip messages with other nodes\n\t\t\tlogger.Debugf(\"[%s] Gossiping block [%d], peers number [%d]\", b.chainID, blockNum, numberOfPeers)\n\t\t\tif !b.isDone() {\n\t\t\t\tb.gossip.Gossip(gossipMsg)\n\t\t\t}\n\n\t\t\tb.client.UpdateReceived(blockNum)\n\n\t\tdefault:\n\t\t\tlogger.Warningf(\"[%s] Received unknown: %v\", b.chainID, t)\n\t\t\treturn\n\t\t}\n\t}\n}", "func (b *blockWriter) Close() error {\n\tif b.err != nil {\n\t\treturn b.err\n\t}\n\n\t// precondition: b.buf[0] != 255\n\tn := int(b.buf[0])\n\tif n == 0 {\n\t\tn++ // no short block needed, just terminate\n\t} else {\n\t\tb.buf[n+1] = 0 // append terminator\n\t\tn += 2\n\t}\n\n\tn2, err := b.w.Write(b.buf[0:n])\n\tif n2 < n && err == nil {\n\t\terr = io.ErrShortWrite\n\t}\n\tb.buf[0] = 0\n\tb.err = alreadyClosed\n\treturn err\n}", "func (coord *Coordinator) CommitBlock(chains ...*TestChain) {\n\tfor _, chain := range chains {\n\t\tchain.App.Commit()\n\t\tchain.NextBlock()\n\t}\n\tcoord.IncrementTime()\n}", "func (bw *BusWrapper) WriteByteBlock(sid devices.DeviceID, reg byte, list []byte) (err error) {\n\ts, err := bw.getSensor(sid)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = bw.switchMuxIfPresent(s.muxAddr, s.muxPort)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn bw.bus.WriteByteBlock(byte(s.i2cAddress), reg, list)\n}", "func (app *App) EndBlock(req abci.RequestEndBlock) abci.ResponseEndBlock {\n\tres := app.BandApp.EndBlock(req)\n\tfor _, event := range res.Events {\n\t\tapp.handleBeginBlockEndBlockEvent(event)\n\t}\n\t// Update balances of all affected accounts on this block.\n\t// Index 0 is message NEW_BLOCK, we insert SET_ACCOUNT messages right after it.\n\tmodifiedMsgs := []Message{app.msgs[0]}\n\tfor accStr, _ := range app.accsInBlock {\n\t\tacc, _ := sdk.AccAddressFromBech32(accStr)\n\t\tmodifiedMsgs = append(modifiedMsgs, Message{\n\t\t\tKey: \"SET_ACCOUNT\",\n\t\t\tValue: JsDict{\n\t\t\t\t\"address\": acc,\n\t\t\t\t\"balance\": app.BankKeeper.GetCoins(app.DeliverContext, acc).String(),\n\t\t\t}})\n\t}\n\tapp.msgs = append(modifiedMsgs, app.msgs[1:]...)\n\tapp.Write(\"COMMIT\", JsDict{\"height\": req.Height})\n\treturn res\n}", "func SetBlockHeight(height int64) {\n\tBlockHeight = height\n}", "func NewStreamedBlockWriter(\n\tblockDir string,\n\tindexReader tsdb.IndexReader,\n\tlogger log.Logger,\n\toriginMeta metadata.Meta,\n) (w *streamedBlockWriter, err error) {\n\tclosers := make([]io.Closer, 0, 2)\n\n\t// We should close any opened Closer up to an error.\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tvar merr tsdberrors.MultiError\n\t\t\tmerr.Add(err)\n\t\t\tfor _, cl := range closers {\n\t\t\t\tmerr.Add(cl.Close())\n\t\t\t}\n\t\t\terr = merr.Err()\n\t\t}\n\t}()\n\n\tchunkWriter, err := chunks.NewWriter(filepath.Join(blockDir, block.ChunksDirname))\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"create chunk writer in streamedBlockWriter\")\n\t}\n\tclosers = append(closers, chunkWriter)\n\n\tindexWriter, err := index.NewWriter(filepath.Join(blockDir, block.IndexFilename))\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"open index writer in streamedBlockWriter\")\n\t}\n\tclosers = append(closers, indexWriter)\n\n\tsymbols, err := indexReader.Symbols()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"read symbols\")\n\t}\n\n\terr = indexWriter.AddSymbols(symbols)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"add symbols\")\n\t}\n\n\treturn &streamedBlockWriter{\n\t\tlogger: logger,\n\t\tblockDir: blockDir,\n\t\tindexReader: indexReader,\n\t\tindexWriter: indexWriter,\n\t\tchunkWriter: chunkWriter,\n\t\tmeta: originMeta,\n\t\tclosers: closers,\n\t\tlabelsValues: make(labelsValues, 1024),\n\t\tmemPostings: index.NewUnorderedMemPostings(),\n\t}, nil\n}", "func (bcb *BlockCreateBulk) Save(ctx context.Context) ([]*Block, error) {\n\tspecs := make([]*sqlgraph.CreateSpec, len(bcb.builders))\n\tnodes := make([]*Block, len(bcb.builders))\n\tmutators := make([]Mutator, len(bcb.builders))\n\tfor i := range bcb.builders {\n\t\tfunc(i int, root context.Context) {\n\t\t\tbuilder := bcb.builders[i]\n\t\t\tbuilder.defaults()\n\t\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\t\tmutation, ok := m.(*BlockMutation)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t\t}\n\t\t\t\tif err := builder.check(); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tbuilder.mutation = mutation\n\t\t\t\tnodes[i], specs[i] = builder.createSpec()\n\t\t\t\tvar err error\n\t\t\t\tif i < len(mutators)-1 {\n\t\t\t\t\t_, err = mutators[i+1].Mutate(root, bcb.builders[i+1].mutation)\n\t\t\t\t} else {\n\t\t\t\t\t// Invoke the actual operation on the latest mutation in the chain.\n\t\t\t\t\tif err = sqlgraph.BatchCreate(ctx, bcb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil {\n\t\t\t\t\t\tif cerr, ok := isSQLConstraintError(err); ok {\n\t\t\t\t\t\t\terr = cerr\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmutation.done = true\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tid := specs[i].ID.Value.(int64)\n\t\t\t\tnodes[i].ID = int(id)\n\t\t\t\treturn nodes[i], nil\n\t\t\t})\n\t\t\tfor i := len(builder.hooks) - 1; i >= 0; i-- {\n\t\t\t\tmut = builder.hooks[i](mut)\n\t\t\t}\n\t\t\tmutators[i] = mut\n\t\t}(i, ctx)\n\t}\n\tif len(mutators) > 0 {\n\t\tif _, err := mutators[0].Mutate(ctx, bcb.builders[0].mutation); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn nodes, nil\n}", "func (blockchain *Blockchain) SaveNewBlockToBlockchain(newBlock *Block) {\n\tDBName := fmt.Sprintf(DBName, os.Getenv(\"NODE_ID\"))\n\tdb, err := bolt.Open(DBName, 0600, nil)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tdefer db.Close()\n\n\terr = db.Update(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(BlockBucketName))\n\t\tif b != nil {\n\t\t\tb.Put(newBlock.BlockHash, gobEncode(newBlock))\n\t\t\tb.Put([]byte(\"l\"), newBlock.BlockHash)\n\t\t\tblockchain.Tip = newBlock.BlockHash\n\t\t}\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n}", "func storeBlocksAsync(test *testing.T, db database.DB, blocks []*block.Block, timeoutDuration time.Duration) error {\n\n\troutinesCount := runtime.NumCPU()\n\tblocksCount := len(blocks)\n\tvar wg sync.WaitGroup\n\t// For each slice of N blocks build a batch to be performed concurrently\n\tfor batchIndex := 0; batchIndex <= blocksCount/routinesCount; batchIndex++ {\n\n\t\t// get a slice of all blocks\n\t\tfrom := routinesCount * batchIndex\n\t\tto := from + routinesCount\n\n\t\tif to > blocksCount {\n\t\t\t// half-open interval reslicing\n\t\t\tto = blocksCount\n\t\t}\n\n\t\t// Start a separate unit to perform a DB tx with multiple StoreBlock\n\t\t// calls\n\t\twg.Add(1)\n\t\tgo func(blocks []*block.Block, wg *sync.WaitGroup) {\n\n\t\t\tdefer wg.Done()\n\t\t\t_ = db.Update(func(t database.Transaction) error {\n\n\t\t\t\tfor _, block := range blocks {\n\t\t\t\t\terr := t.StoreBlock(block)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Print(err.Error())\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t})\n\n\t\t}(blocks[from:to], &wg)\n\t}\n\n\t// Wait here for all updates to complete or just timeout in case of a\n\t// deadlock.\n\ttimeouted := waitTimeout(&wg, timeoutDuration)\n\n\tif timeouted {\n\t\t// Also it might be due to too slow write call\n\t\treturn errors.New(\"Seems like we've got a deadlock situation on storing blocks in concurrent way\")\n\t}\n\n\treturn nil\n}", "func (b *Builder) FinishBlock() {\n\tb.append(y.U32SliceToBytes(b.entryOffsets))\n\tb.append(y.U32ToBytes(uint32(len(b.entryOffsets))))\n\tchecksum := utils.NewCRC(b.currentBlock.Data[:b.sz]).Value()\n\tb.append(y.U32ToBytes(checksum))\n\n\txlog.Logger.Debugf(\"real block size is %d, len of entries is %d\\n\", b.sz, len(b.entryOffsets))\n\t//truncate block to b.sz\n\tb.currentBlock.Data = b.currentBlock.Data[:b.sz]\n\tb.writeCh <- writeBlock{\n\t\tbaseKey: y.Copy(b.baseKey),\n\t\tb: b.currentBlock,\n\t}\n\treturn\n}", "func (suite *MainIntegrationSuite) TestWriteBlockToTestDB() {\n\t// Create a DBClient that will be using the test tables.\n\ttestDBClient, err := dbclient.New(\n\t\tdbclient.DBPort(injector.PostgresPort()),\n\t\tdbclient.DBName(injector.PostgresDBName()),\n\t\tdbclient.DBUser(injector.PostgresUserName()),\n\t\tdbclient.DBHost(injector.PostgresDomain()),\n\t\tdbclient.DBPassword(injector.PostgresPassword()),\n\t\tdbclient.PostgresClient(),\n\t\tdbclient.Test())\n\n\t// Connect to the DB.\n\terr = testDBClient.Connect()\n\tdefer testDBClient.Close()\n\tsuite.NoError(err, \"There should be no error when connecting to the Test DB.\")\n\n\t// Write a block to the DB.\n\tblock := testutils.Block506664\n\terr = testDBClient.WriteBlock(block)\n\tsuite.NoError(err, \"There should be no error writing block to db\")\n}", "func (bw *BlockWriter) Close() error {\n\tbw.closed = true\n\tif bw.conn != nil {\n\t\tdefer bw.conn.Close()\n\t}\n\n\tif bw.stream != nil {\n\t\t// TODO: handle failures, set up recovery pipeline\n\t\terr := bw.stream.finish()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// We need to tell the namenode what the final block length is.\n\t\terr = bw.pm.finalizeBlock(bw.offset)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (a *API) WriteBlockProfile(file string) error {\n\ta.logger.Debug(\"debug_writeBlockProfile\", \"file\", file)\n\treturn writeProfile(\"block\", file, a.logger)\n}", "func (c *digisparkI2cConnection) WriteBlockData(reg uint8, data []byte) error {\n\tc.mtx.Lock()\n\tdefer c.mtx.Unlock()\n\n\tif len(data) > 32 {\n\t\tdata = data[:32]\n\t}\n\n\tbuf := make([]byte, len(data)+1)\n\tcopy(buf[1:], data)\n\tbuf[0] = reg\n\treturn c.writeAndCheckCount(buf, true)\n}", "func (f *Builder) AppendManyBlocksOnBlocks(ctx context.Context, height int, parents ...*types.BlockHeader) *types.BlockHeader {\n\tvar tip *types.TipSet\n\tif len(parents) > 0 {\n\t\ttip = testhelpers.RequireNewTipSet(f.t, parents...)\n\t}\n\treturn f.BuildManyOn(ctx, height, tip, nil).At(0)\n}", "func (m *dbManager) SaveBlockMetadata(hash []byte, blockMetadata *BlockMetadata) error {\n\n\tm.db.Update(func(tx *bolt.Tx) error {\n\t\tblockBucket, err := tx.CreateBucketIfNotExists([]byte(blockBucketName))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlastHashBucket, err := tx.CreateBucketIfNotExists([]byte(lastHashBucketName))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tencoded, err := json.Marshal(blockMetadata)\n\t\tvar metadata BlockMetadata\n\t\tjson.Unmarshal(encoded, &metadata)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = blockBucket.Put(hash, encoded)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn lastHashBucket.Put([]byte(\"lastUsedHash\"), hash)\n\t})\n\treturn nil\n}", "func (s *Server) UploadBlocks(stream service.DirSync_UploadBlocksServer) error {\n\tmeta, err := extractUploadMeta(stream.Context())\n\tif err != nil {\n\t\treturn err\n\t}\n\tpath := meta.Path\n\tblockSize := meta.BlockSize\n\n\ttmpfile, err := ioutil.TempFile(\"\", \"dirsync\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer tmpfile.Close()\n\n\tabsPath := filepath.Join(s.absDir, fsutil.CleanPath(path))\n\n\terr = os.MkdirAll(filepath.Dir(absPath), 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfile, err := os.OpenFile(absPath, os.O_CREATE, 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tfileHash := sha256.New()\n\tstartTime := time.Now()\n\tfor {\n\t\tblock, err := stream.Recv()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\t// Atomically move tmp file to directory.\n\t\t\t\terr := os.Rename(tmpfile.Name(), absPath)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfileChecksum := hex.EncodeToString(fileHash.Sum(nil))\n\t\t\t\ts.updateChecksumMapping(absPath, fileChecksum)\n\t\t\t\tlog.Printf(\"uploading file %s, elapsed: %s\\n\", path, time.Since(startTime))\n\t\t\t\treturn stream.SendAndClose(&service.UploadResponse{})\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tif block.GetReference() {\n\t\t\t_, err := file.Seek(int64(block.GetNumber())*int64(blockSize), 0)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbuf := make([]byte, blockSize)\n\t\t\tn, _ := io.ReadFull(file, buf)\n\t\t\t_, err = tmpfile.Write(buf[:n])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t_, err = fileHash.Write(buf[:n])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\t_, err := tmpfile.Write(block.GetPayload())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t_, err = fileHash.Write(block.GetPayload())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n}", "func GetBlocks(hostURL string, hostPort int, height int) *bytes.Buffer {\n\tparams := make(map[string]interface{})\n\tparams[\"height\"] = height\n\treturn makePostRequest(hostURL, hostPort, \"f_blocks_list_json\", params)\n}", "func (b *blockListV1) writeBlockDataBytes(data []byte) (Block, error) {\n\tblock := &blockV1{0, uint32(len(data)), data}\n\n\tif b.GetCurBlock() != nil {\n\t\tblock.id = b.GetCurBlock().GetID() + 1\n\t}\n\n\terr := b.writeBlock(block)\n\treturn block, err\n}", "func writeBlockHeader(w io.Writer, bh *BlockHeader) error {\n\treturn bh.Serialize(w)\n}", "func (bc *Blockchain) replaceBlocks(blocks []*block.Block) {\n\tbc.blocks = blocks\n}", "func WALGenerateNBlocks(t *testing.T, wr io.Writer, numBlocks int) (err error) {\n\tconfig := getConfig(t)\n\n\tapp := kvstore.NewPersistentKVStoreApplication(filepath.Join(config.DBDir(), \"wal_generator\"))\n\tdefer app.Close()\n\n\tlogger := log.TestingLogger().With(\"wal_generator\", \"wal_generator\")\n\tlogger.Info(\"generating WAL (last height msg excluded)\", \"numBlocks\", numBlocks)\n\n\t/////////////////////////////////////////////////////////////////////////////\n\t// COPY PASTE FROM node.go WITH A FEW MODIFICATIONS\n\t// NOTE: we can't import node package because of circular dependency.\n\t// NOTE: we don't do handshake so need to set state.Version.Consensus.App directly.\n\tprivValidatorKeyFile := config.PrivValidatorKeyFile()\n\tprivValidatorStateFile := config.PrivValidatorStateFile()\n\tprivValidator := privval.LoadOrGenFilePV(privValidatorKeyFile, privValidatorStateFile)\n\tgenDoc, err := types.GenesisDocFromFile(config.GenesisFile())\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to read genesis file\")\n\t}\n\tblockStoreDB := db.NewMemDB()\n\tstateDB := blockStoreDB\n\tstate, err := sm.MakeGenesisState(genDoc)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to make genesis state\")\n\t}\n\tstate.AppVersion = kvstore.AppVersion\n\tsm.SaveState(stateDB, state)\n\tblockStore := store.NewBlockStore(blockStoreDB)\n\n\tproxyApp := proxy.NewAppConns(proxy.NewLocalClientCreator(app))\n\tproxyApp.SetLogger(logger.With(\"module\", \"proxy\"))\n\tif err := proxyApp.Start(); err != nil {\n\t\treturn errors.Wrap(err, \"failed to start proxy app connections\")\n\t}\n\tdefer proxyApp.Stop()\n\n\tevsw := events.NewEventSwitch()\n\tevsw.SetLogger(logger.With(\"module\", \"events\"))\n\tif err := evsw.Start(); err != nil {\n\t\treturn errors.Wrap(err, \"failed to start event bus\")\n\t}\n\tdefer evsw.Stop()\n\tmempool := mock.Mempool{}\n\tblockExec := sm.NewBlockExecutor(stateDB, log.TestingLogger(), proxyApp.Consensus(), mempool)\n\tconsensusState := NewConsensusState(config.Consensus, state.Copy(), blockExec, blockStore, mempool)\n\tconsensusState.SetLogger(logger)\n\tconsensusState.SetEventSwitch(evsw)\n\tif privValidator != nil {\n\t\tconsensusState.SetPrivValidator(privValidator)\n\t}\n\t// END OF COPY PASTE\n\t/////////////////////////////////////////////////////////////////////////////\n\n\t// set consensus wal to buffered WAL, which will write all incoming msgs to buffer\n\tnumBlocksWritten := make(chan struct{})\n\twal := newHeightStopWAL(logger, walm.NewWALWriter(wr, maxMsgSize), int64(numBlocks)+1, numBlocksWritten)\n\t// See wal.go OnStart().\n\t// Since we separate the WALWriter from the WAL, we need to\n\t// initialize ourself.\n\twal.WriteMetaSync(walm.MetaMessage{Height: 1})\n\tconsensusState.wal = wal\n\n\tif err := consensusState.Start(); err != nil {\n\t\treturn errors.Wrap(err, \"failed to start consensus state\")\n\t}\n\n\tselect {\n\tcase <-numBlocksWritten:\n\t\tconsensusState.Stop()\n\t\treturn nil\n\tcase <-time.After(2 * time.Minute):\n\t\tconsensusState.Stop()\n\t\treturn fmt.Errorf(\"waited too long for tendermint to produce %d blocks (grep logs for `wal_generator`)\", numBlocks)\n\t}\n}", "func (builder *Builder) RenderBlock(block *BlockInfo) (string, error) {\n\tfor i, renderer := range builder.BlockCompilers {\n\t\tnewVal, err := renderer(block)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"error in block renderer %d: \\n%s\", i, err.Error())\n\t\t}\n\n\t\tblock.Value = newVal\n\t}\n\n\treturn block.Value, nil\n}", "func (s *BlockStorage) Save() error {\n\t// Create storage directory\n\tif err := s.createStorageDir(); err != nil {\n\t\treturn err\n\t}\n\t// Serialize each block and write it to the directory\n\tvar err error\n\ts.blockstore.AccountBlocks(func(sequence int, b *tradeblocks.AccountBlock) bool {\n\t\terr = s.SaveAccountBlock(b)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t})\n\ts.blockstore.SwapBlocks(func(sequence int, b *tradeblocks.SwapBlock) bool {\n\t\terr = s.SaveSwapBlock(b)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t})\n\ts.blockstore.OrderBlocks(func(sequence int, b *tradeblocks.OrderBlock) bool {\n\t\terr = s.SaveOrderBlock(b)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t})\n\treturn err\n}", "func (bc *Blockchain) ReplaceBlocks(blocks []Block, genesis Block) error {\n\terr := CheckBlocks(blocks, genesis)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(blocks) <= len(bc.chain) {\n\t\treturn errors.New(\"new blocks length must be longer than current\")\n\t}\n\n\tbc.chain = blocks\n\treturn nil\n}", "func (f Frame) compressBlocks() ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\n\ttmpBuf := new(bytes.Buffer)\n\tfor _, b := range f.Blocks {\n\t\terr := b.Encode(tmpBuf)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tzlibWriter := zlib.NewWriter(buf)\n\t_, err := tmpBuf.WriteTo(zlibWriter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tzlibWriter.Close()\n\n\treturn buf.Bytes(), nil\n}", "func (color *Color) writeBlockLength(w io.Writer) (err error) {\n\tblockLength, err := color.calculateBlockLength()\n\tif err != nil {\n\t\treturn\n\t}\n\tif err = binary.Write(w, binary.BigEndian, blockLength); err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func (f *Builder) AppendBlockOnBlocks(ctx context.Context, parents ...*types.BlockHeader) *types.BlockHeader {\n\tvar tip *types.TipSet\n\tif len(parents) > 0 {\n\t\ttip = testhelpers.RequireNewTipSet(f.t, parents...)\n\t}\n\treturn f.AppendBlockOn(ctx, tip)\n}", "func (b Block) Encode(w io.Writer) error {\n\tcorrectLength := b.CorrectLength()\n\tif (correctLength < 32 && b.Type == 3) || correctLength < 16 {\n\t\t// Error should never happen\n\t\treturn errors.New(\"Block length is too small\")\n\t}\n\theaderLength := 16\n\tbuf := make([]byte, correctLength)\n\tbinary.LittleEndian.PutUint32(buf[0:4], correctLength)\n\tbinary.LittleEndian.PutUint32(buf[4:8], b.SubjectID)\n\tbinary.LittleEndian.PutUint32(buf[8:12], b.CurrentID)\n\tbinary.LittleEndian.PutUint16(buf[12:14], b.Type)\n\tbinary.LittleEndian.PutUint16(buf[14:16], b.Pad1)\n\tif b.Type == 3 {\n\t\theaderLength = 32\n\t\tbinary.LittleEndian.PutUint16(buf[16:18], b.Reserved)\n\t\tbinary.LittleEndian.PutUint16(buf[18:20], b.Opcode)\n\t\tbinary.LittleEndian.PutUint16(buf[20:22], b.Pad2)\n\t\tbinary.LittleEndian.PutUint16(buf[22:24], b.ServerID)\n\t\ttime := uint32(b.Time.Unix())\n\t\tbinary.LittleEndian.PutUint32(buf[24:28], time)\n\t\tbinary.LittleEndian.PutUint32(buf[28:32], b.Pad3)\n\t}\n\n\tvar blockData []byte\n\tvar err error\n\tswitch v := b.Data.(type) {\n\tcase *GenericBlockData:\n\t\tblockData, err = v.MarshalBytes()\n\tdefault:\n\t\tblockData, err = MarshalBlockBytes(v)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tcopy(buf[headerLength:correctLength], blockData)\n\n\t_, err = w.Write(buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (w *Writer) Close() (err error) {\n\tdefer func() {\n\t\tif w.closer == nil {\n\t\t\treturn\n\t\t}\n\t\terr1 := w.closer.Close()\n\t\tif err == nil {\n\t\t\terr = err1\n\t\t}\n\t\tw.closer = nil\n\t}()\n\tif w.err != nil {\n\t\treturn w.err\n\t}\n\n\t// Finish the last data block, or force an empty data block if there\n\t// aren't any data blocks at all.\n\tif w.nEntries > 0 || len(w.indexEntries) == 0 {\n\t\tbh, err := w.finishBlock()\n\t\tif err != nil {\n\t\t\tw.err = err\n\t\t\treturn w.err\n\t\t}\n\t\tw.pendingBH = bh\n\t\tw.flushPendingBH(nil)\n\t}\n\n\t// Write the (empty) metaindex block.\n\tmetaindexBlockHandle, err := w.finishBlock()\n\tif err != nil {\n\t\tw.err = err\n\t\treturn w.err\n\t}\n\n\t// Write the index block.\n\t// writer.append uses w.tmp[:3*binary.MaxVarintLen64].\n\ti0, tmp := 0, w.tmp[3*binary.MaxVarintLen64:5*binary.MaxVarintLen64]\n\tfor _, ie := range w.indexEntries {\n\t\tn := encodeBlockHandle(tmp, ie.bh)\n\t\ti1 := i0 + ie.keyLen\n\t\tw.append(w.indexKeys[i0:i1], tmp[:n], true)\n\t\ti0 = i1\n\t}\n\tindexBlockHandle, err := w.finishBlock()\n\tif err != nil {\n\t\tw.err = err\n\t\treturn w.err\n\t}\n\n\t// Write the table footer.\n\tfooter := w.tmp[:footerLen]\n\tfor i := range footer {\n\t\tfooter[i] = 0\n\t}\n\tn := encodeBlockHandle(footer, metaindexBlockHandle)\n\tencodeBlockHandle(footer[n:], indexBlockHandle)\n\tcopy(footer[footerLen-len(magic):], magic)\n\tif _, err := w.writer.Write(footer); err != nil {\n\t\tw.err = err\n\t\treturn w.err\n\t}\n\n\t// Flush the buffer.\n\tif w.bufWriter != nil {\n\t\tif err := w.bufWriter.Flush(); err != nil {\n\t\t\tw.err = err\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Make any future calls to Set or Close return an error.\n\tw.err = errors.New(\"leveldb/table: writer is closed\")\n\treturn nil\n}", "func (tx *transaction) writePendingAndCommit() error {\n\t// Save the current block store write position for potential rollback.\n\t// These variables are only updated here in this function and there can\n\t// only be one write transaction active at a time, so it's safe to store\n\t// them for potential rollback.\n\twc := tx.db.store.writeCursor\n\twc.RLock()\n\toldBlkFileNum := wc.curFileNum\n\toldBlkOffset := wc.curOffset\n\twc.RUnlock()\n\n\t// rollback is a closure that is used to rollback all writes to the\n\t// block files.\n\trollback := func() {\n\t\t// Rollback any modifications made to the block files if needed.\n\t\ttx.db.store.handleRollback(oldBlkFileNum, oldBlkOffset)\n\t}\n\n\t// Loop through all of the pending blocks to store and write them.\n\tfor _, blockData := range tx.pendingBlockData {\n\t\tlog.Tracef(\"Storing block %v\", *blockData.key)\n\t\tlocation, err := tx.db.store.writeBlock(blockData.bytes)\n\t\tif err != nil {\n\t\t\trollback()\n\t\t\treturn err\n\t\t}\n\n\t\t// Add a record in the block index for the block. The record\n\t\t// includes the location information needed to locate the block\n\t\t// on the filesystem as well as the block header since they are\n\t\t// so commonly needed.\n\t\tblockRow := serializeBlockLoc(location)\n\t\terr = tx.blockIdxBucket.Put(blockData.key[:], blockRow)\n\t\tif err != nil {\n\t\t\trollback()\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Update the metadata for the current write file and offset.\n\twriteRow := serializeWriteRow(wc.curFileNum, wc.curOffset)\n\tif err := tx.metaBucket.Put(writeLocKeyName, writeRow); err != nil {\n\t\trollback()\n\t\treturn database.ConvertErr(\"failed to store write cursor\", err)\n\t}\n\n\t// Atomically update the database cache. The cache automatically\n\t// handles flushing to the underlying persistent storage database.\n\treturn tx.db.cache.commitTx(tx)\n}", "func (ob *Observer) updateBlock(curHeight, nextHeight int64, curBlockHash string) error {\n\tblock, err := ob.deps.Recorder.Block(nextHeight)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"[Observer.updateBlock]: failed to get block info, height=%d\", nextHeight)\n\t}\n\n\tif curHeight != 0 && block.ParentBlockHash != curBlockHash {\n\t\tif err := ob.DeleteBlock(curHeight); err != nil {\n\t\t\treturn errors.Wrap(err, \"[Observer.updateBlock]: failed to delete a forked block\")\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tif err := ob.RecordBlockAndTxs(block); err != nil {\n\t\treturn errors.Wrap(err, \"[Observer.updateBlock]: failed to save and process block\")\n\t}\n\n\treturn nil\n}", "func (db *StakeDatabase) DisconnectBlocks(count int64) error {\n\tdb.nodeMtx.Lock()\n\tdefer db.nodeMtx.Unlock()\n\n\tfor i := int64(0); i < count; i++ {\n\t\tif err := db.disconnectBlock(false); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (d *Data) storeBlockElements(ctx *datastore.VersionedCtx, batch storage.Batch, be blockElements) error {\n\tfor izyxStr, elems := range be {\n\t\tblockCoord, err := izyxStr.ToChunkPoint3d()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Modify the block annotations\n\t\ttk := NewBlockTKey(blockCoord)\n\t\tif err := d.modifyElements(ctx, batch, tk, elems); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func getLatestBlocks(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tblockCount := blockdata.GetBlockCount() // get the latest blocks\n\n\tvar blocks []*btcjson.GetBlockVerboseResult\n\n\t// blockheight - 1 in the loop. Get the blockhash from the height\n\tfor i := 0; i < 10; i++ {\n\t\tprevBlock := blockCount - int64(i)\n\t\thash, _ := blockdata.GetBlockHash(prevBlock)\n\n\t\tblock, err := blockdata.GetBlock(hash)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tblocks = append(blocks, block)\n\t}\n\tjson.NewEncoder(w).Encode(blocks)\n}", "func (b *BlockCreator) SolveBlocks() {\n\tfor {\n\n\t\t// Bail if 'Stop' has been called.\n\t\tselect {\n\t\tcase <-b.tg.StopChan():\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\t// This is mainly here to avoid the creation of useless blocks during IBD and when a node comes back online\n\t\t// after some downtime\n\t\tif !b.csSynced {\n\t\t\tif !b.cs.Synced() {\n\t\t\t\tb.log.Debugln(\"Consensus set is not synced, don't create blocks yet\")\n\t\t\t\ttime.Sleep(8 * time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tb.csSynced = true\n\t\t}\n\n\t\t// Try to solve a block for blocktimes of the next 10 seconds\n\t\tnow := time.Now().Unix()\n\t\tb.log.Debugln(\"[BC] Attempting to solve blocks\")\n\t\tblock := b.solveBlock(uint64(now), 10)\n\t\tif block != nil {\n\t\t\tbjson, err := json.Marshal(block)\n\t\t\tif err != nil {\n\t\t\t\tb.log.Println(\"Solved block but failed to JSON-marshal it for logging purposes:\", err)\n\t\t\t} else {\n\t\t\t\tb.log.Println(\"Solved block:\", string(bjson))\n\t\t\t}\n\n\t\t\terr = b.submitBlock(*block)\n\t\t\tif err != nil {\n\t\t\t\tb.log.Println(\"ERROR: An error occurred while submitting a solved block:\", err)\n\t\t\t}\n\t\t}\n\t\t//sleep a while before recalculating\n\t\ttime.Sleep(8 * time.Second)\n\t}\n}", "func (g *gcm) updateBlocks(y *gcmFieldElement, blocks []byte) {\n\tfor len(blocks) > 0 {\n\t\ty.low ^= binary.BigEndian.Uint64(blocks)\n\t\ty.high ^= binary.BigEndian.Uint64(blocks[8:])\n\t\tg.mul(y)\n\t\tblocks = blocks[gcmBlockSize:]\n\t}\n}", "func (ts *Tipset) Block(miner Miner, winCount int64, msgs ...*ApplicableMessage) {\n\tblock := Block{\n\t\tMinerAddr: miner.MinerActorAddr.ID,\n\t\tWinCount: winCount,\n\t}\n\tfor _, am := range msgs {\n\t\tblock.Messages = append(block.Messages, MustSerialize(am.Message))\n\n\t\t// if we see this message for the first time, add it to the `msgIdx` map and to the `orderMsgs` slice.\n\t\tif _, ok := ts.tss.msgIdx[am.Message.Cid()]; !ok {\n\t\t\tts.tss.msgIdx[am.Message.Cid()] = am\n\t\t\tts.tss.orderedMsgs = append(ts.tss.orderedMsgs, am)\n\t\t}\n\t}\n\n\tts.Blocks = append(ts.Blocks, block)\n}", "func NewBlockWriter(rand io.Reader, orgId, streamId uuid.UUID, salt crypto.Salt, pass []byte, cipher crypto.Cipher) BlockWriter {\n\tidx, key := 0, salt.Apply(pass, cipher.KeySize())\n\treturn BlockWriterFn(func(data []byte) (next secret.Block, err error) {\n\t\tdefer func() {\n\t\t\tidx++\n\t\t}()\n\n\t\tct, err := cipher.Apply(rand, key, data)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tnext = secret.Block{orgId, streamId, idx, ct}\n\t\treturn\n\t})\n}", "func dbStoreBlock(dbTx database.Tx, block *asiutil.Block) error {\n\tblockKey := database.NewNormalBlockKey(block.Hash())\n\thasBlock, err := dbTx.HasBlock(blockKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif hasBlock {\n\t\treturn nil\n\t}\n\n\tblockBytes, err := block.Bytes()\n\tif err != nil {\n\t\tstr := fmt.Sprintf(\"failed to get serialized bytes for block %s\",\n\t\t\tblock.Hash())\n\t\treturn ruleError(ErrFailedSerializedBlock, str)\n\t}\n\tlog.Infof(\"save block, height=%d, hash=%s\", block.Height(), block.Hash())\n\treturn dbTx.StoreBlock(blockKey, blockBytes)\n}", "func (chain *Blockchain) AddBlock(transactions []*Transaction) (err error) {\n\tblock := NewBlock(transactions, chain.Tail)\n\tbytes, err := json.Marshal(block)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = chain.Database.Update(func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket([]byte(BucketName))\n\t\terr := bucket.Put(block.Hash, bytes)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = bucket.Put([]byte(LastBlockKey), block.Hash)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn\n\t}\n\tchain.Tail = block.Hash\n\treturn\n}", "func (itr *blocksItr) Close() {\n\titr.mgr.blkfilesInfoCond.L.Lock()\n\tdefer itr.mgr.blkfilesInfoCond.L.Unlock()\n\titr.closeMarkerLock.Lock()\n\tdefer itr.closeMarkerLock.Unlock()\n\titr.closeMarker = true\n\titr.mgr.blkfilesInfoCond.Broadcast()\n\tif itr.stream != nil {\n\t\titr.stream.close()\n\t}\n}", "func (c *BlockCache) Add(height int, block *walletrpc.CompactBlock) error {\n\t// Invariant: m[firstBlock..nextBlock) are valid.\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\n\tif height > c.nextBlock {\n\t\t// Cache has been reset (for example, checksum error)\n\t\treturn nil\n\t}\n\tif height < c.firstBlock {\n\t\t// Should never try to add a block before Sapling activation height\n\t\tLog.Fatal(\"cache.Add height below Sapling: \", height)\n\t\treturn nil\n\t}\n\tif height < c.nextBlock {\n\t\t// Should never try to \"backup\" (call Reorg() instead).\n\t\tLog.Fatal(\"cache.Add height going backwards: \", height)\n\t\treturn nil\n\t}\n\tbheight := int(block.Height)\n\n\tif bheight != height {\n\t\t// This could only happen if zcashd returned the wrong\n\t\t// block (not the height we requested).\n\t\tLog.Fatal(\"cache.Add wrong height: \", bheight, \" expecting: \", height)\n\t\treturn nil\n\t}\n\n\t// Add the new block and its length to the db files.\n\tdata, err := proto.Marshal(block)\n\tif err != nil {\n\t\treturn err\n\t}\n\tb := append(checksum(height, data), data...)\n\tn, err := c.blocksFile.Write(b)\n\tif err != nil {\n\t\tLog.Fatal(\"blocks write failed: \", err)\n\t}\n\tif n != len(b) {\n\t\tLog.Fatal(\"blocks write incorrect length: expected: \", len(b), \"written: \", n)\n\t}\n\tb = make([]byte, 4)\n\tbinary.LittleEndian.PutUint32(b, uint32(len(data)))\n\tn, err = c.lengthsFile.Write(b)\n\tif err != nil {\n\t\tLog.Fatal(\"lengths write failed: \", err)\n\t}\n\tif n != len(b) {\n\t\tLog.Fatal(\"lengths write incorrect length: expected: \", len(b), \"written: \", n)\n\t}\n\n\t// update the in-memory variables\n\toffset := c.starts[len(c.starts)-1]\n\tc.starts = append(c.starts, offset+int64(len(data)+8))\n\n\tif c.latestHash == nil {\n\t\tc.latestHash = make([]byte, len(block.Hash))\n\t}\n\tcopy(c.latestHash, block.Hash)\n\tc.nextBlock++\n\t// Invariant: m[firstBlock..nextBlock) are valid.\n\treturn nil\n}", "func (color *Color) writeBlockType(w io.Writer) (err error) {\n\treturn binary.Write(w, binary.BigEndian, colorEntry)\n}", "func (soc *SocketServer) Store(blockData *blockdata.BlockData, msgBlock *wire.MsgBlock) error {\n\tapiLog.Debugf(\"Sending new websocket block %s\", blockData.Header.Hash)\n\tsoc.BroadcastToRoom(\"\", \"inv\", \"block\", blockData.Header.Hash)\n\n\t// Since the coinbase transaction is generated by the miner, it will never\n\t// hit mempool. It must be processed now, with the new block.\n\treturn soc.sendNewMsgTx(msgBlock.Transactions[0])\n}", "func CreateBlock(series []storage.Series, dir string, chunkRange int64, logger log.Logger) (string, error) {\n\tif chunkRange == 0 {\n\t\tchunkRange = DefaultBlockDuration\n\t}\n\tif chunkRange < 0 {\n\t\treturn \"\", ErrInvalidTimes\n\t}\n\n\tw, err := NewBlockWriter(logger, dir, chunkRange)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer func() {\n\t\tif err := w.Close(); err != nil {\n\t\t\tlogger.Log(\"err closing blockwriter\", err.Error())\n\t\t}\n\t}()\n\n\tsampleCount := 0\n\tconst commitAfter = 10000\n\tctx := context.Background()\n\tapp := w.Appender(ctx)\n\tvar it chunkenc.Iterator\n\n\tfor _, s := range series {\n\t\tref := storage.SeriesRef(0)\n\t\tit = s.Iterator(it)\n\t\tlset := s.Labels()\n\t\ttyp := it.Next()\n\t\tlastTyp := typ\n\t\tfor ; typ != chunkenc.ValNone; typ = it.Next() {\n\t\t\tif lastTyp != typ {\n\t\t\t\t// The behaviour of appender is undefined if samples of different types\n\t\t\t\t// are appended to the same series in a single Commit().\n\t\t\t\tif err = app.Commit(); err != nil {\n\t\t\t\t\treturn \"\", err\n\t\t\t\t}\n\t\t\t\tapp = w.Appender(ctx)\n\t\t\t\tsampleCount = 0\n\t\t\t}\n\n\t\t\tswitch typ {\n\t\t\tcase chunkenc.ValFloat:\n\t\t\t\tt, v := it.At()\n\t\t\t\tref, err = app.Append(ref, lset, t, v)\n\t\t\tcase chunkenc.ValHistogram:\n\t\t\t\tt, h := it.AtHistogram()\n\t\t\t\tref, err = app.AppendHistogram(ref, lset, t, h, nil)\n\t\t\tcase chunkenc.ValFloatHistogram:\n\t\t\t\tt, fh := it.AtFloatHistogram()\n\t\t\t\tref, err = app.AppendHistogram(ref, lset, t, nil, fh)\n\t\t\tdefault:\n\t\t\t\treturn \"\", fmt.Errorf(\"unknown sample type %s\", typ.String())\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\tsampleCount++\n\t\t\tlastTyp = typ\n\t\t}\n\t\tif it.Err() != nil {\n\t\t\treturn \"\", it.Err()\n\t\t}\n\t\t// Commit and make a new appender periodically, to avoid building up data in memory.\n\t\tif sampleCount > commitAfter {\n\t\t\tif err = app.Commit(); err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\tapp = w.Appender(ctx)\n\t\t\tsampleCount = 0\n\t\t}\n\t}\n\n\tif err = app.Commit(); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tulid, err := w.Flush(ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn filepath.Join(dir, ulid.String()), nil\n}", "func (xc *AChainCore) SyncBlocks() {\n\thd := &global.XContext{Timer: global.NewXTimer()}\n\tfor i := 0; i < MaxSyncTimes; i++ {\n\t\txc.log.Trace(\"sync blocks\", \"blockname\", xc.bcname, \"try times\", i)\n\t\tbc, confirm := xc.syncForOnce()\n\t\txc.log.Trace(\"sync blocks\", \"bc\", bc, \"confirm\", confirm)\n\t\tif bc == nil || bc.GetBlock() == nil {\n\t\t\ttime.Sleep(time.Duration(rand.Intn(MaxSleepMilSecond)) * time.Millisecond)\n\t\t\tcontinue\n\t\t}\n\t\tif !confirm && i < MaxSyncTimes-1 {\n\t\t\ttime.Sleep(time.Duration(rand.Intn(MaxSleepMilSecond)) * time.Millisecond)\n\t\t\tcontinue\n\t\t}\n\t\terr := xc.SendBlock(\n\t\t\t&pb.Block{\n\t\t\t\tHeader: global.GHeader(),\n\t\t\t\tBcname: xc.bcname,\n\t\t\t\tBlockid: bc.Block.Blockid,\n\t\t\t\tBlock: bc.Block}, hd)\n\t\tif err == nil || err.Error() == ErrBlockExist.Error() {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (p *socketAppProxyClient) commitBlock(block ledger.Block) ([]byte, error) {\n\tvar stateHash ledger.StateHash\n\n\tconn, err := net.DialTimeout(\"tcp\", p.clientAddr, p.timeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trpcConn := jsonrpc.NewClient(conn)\n\n\terr = rpcConn.Call(\"State.CommitBlock\", block, &stateHash)\n\n\tp.logger.Log(\"debug\", \"AppProxyClient.commitBlock\", LogFields{\"block\": block.Index, \"state_hash\": stateHash.Hash})\n\n\treturn stateHash.Hash, err\n}", "func Block(b models.Block) *genModels.BlocksRow {\n\tts := b.Timestamp.Unix()\n\n\tgenBlock := genModels.BlocksRow{\n\t\tLevel: b.Level.Ptr(),\n\t\tProto: b.Proto.Ptr(),\n\t\tBlockTime: b.BlockTime,\n\t\tPredecessor: b.Predecessor.Ptr(),\n\t\tTimestamp: &ts,\n\t\tValidationPass: b.ValidationPass.Ptr(),\n\t\tFitness: b.Fitness.Ptr(),\n\t\tContext: b.Context,\n\t\tSignature: b.Signature,\n\t\tProtocol: b.Protocol.Ptr(),\n\t\tPriority: b.Priority.Ptr(),\n\t\tChainID: b.ChainID,\n\t\tHash: b.Hash.Ptr(),\n\t\tReward: &b.Reward,\n\t\tDeposit: b.Deposit,\n\t\tOperationsHash: b.OperationsHash,\n\t\tPeriodKind: b.PeriodKind,\n\t\tCurrentExpectedQuorum: b.CurrentExpectedQuorum,\n\t\tActiveProposal: b.ActiveProposal,\n\t\tBaker: b.Baker,\n\t\tBakerName: b.BakerName,\n\t\tNonceHash: b.NonceHash,\n\t\tConsumedGas: b.ConsumedGas,\n\t\tMetaLevel: b.MetaLevel,\n\t\tMetaLevelPosition: b.MetaLevelPosition,\n\t\tMetaCycle: b.MetaCycle,\n\t\tMetaCyclePosition: b.MetaCyclePosition,\n\t\tMetaVotingPeriod: b.MetaVotingPeriod,\n\t\tMetaVotingPeriodPosition: b.MetaVotingPeriodPosition,\n\t\tExpectedCommitment: b.ExpectedCommitment,\n\t}\n\n\tif b.BlockAggregation != nil {\n\t\tgenBlock.Volume = b.BlockAggregation.Volume\n\t\tgenBlock.Fees = b.BlockAggregation.Fees\n\t\tgenBlock.Endorsements = b.BlockAggregation.Endorsements\n\t\tgenBlock.Proposals = b.BlockAggregation.Proposals\n\t\tgenBlock.SeedNonceRevelations = b.BlockAggregation.SeedNonceRevelations\n\t\tgenBlock.Delegations = b.BlockAggregation.Delegations\n\t\tgenBlock.Transactions = b.BlockAggregation.Transactions\n\t\tgenBlock.ActivateAccounts = b.BlockAggregation.ActivateAccounts\n\t\tgenBlock.Ballots = b.BlockAggregation.Ballots\n\t\tgenBlock.Originations = b.BlockAggregation.Originations\n\t\tgenBlock.Reveals = b.BlockAggregation.Reveals\n\t\tgenBlock.DoubleBakingEvidence = b.BlockAggregation.DoubleBakingEvidences\n\t\tgenBlock.DoubleEndorsementEvidence = b.BlockAggregation.DoubleEndorsementEvidences\n\t\tgenBlock.NumberOfOperations = b.BlockAggregation.NumberOfOperations\n\t}\n\n\treturn &genBlock\n}", "func (a *BlocksApplier) Apply(blocks []*proto.Block) error {\n\tlocked := a.state.Mutex().Lock()\n\tdefer locked.Unlock()\n\n\tlastBlock, _, err := a.inner.apply(blocks)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := maybeEnableExtendedApi(a.state, lastBlock, proto.NewTimestampFromTime(a.tm.Now())); err != nil {\n\t\tpanic(fmt.Sprintf(\"[*] BlockDownloader: MaybeEnableExtendedApi(): %v. Failed to persist address transactions for API after successfully applying valid blocks.\", err))\n\t}\n\treturn nil\n}" ]
[ "0.67294586", "0.6327706", "0.60434544", "0.6032351", "0.600879", "0.598723", "0.59501386", "0.58701485", "0.5869605", "0.5795803", "0.57213795", "0.5720991", "0.5705852", "0.5687761", "0.5684173", "0.5661786", "0.5650782", "0.56272984", "0.5619659", "0.56156945", "0.5522049", "0.55167025", "0.55160666", "0.54893976", "0.5445317", "0.5402958", "0.5400216", "0.5395947", "0.5395016", "0.5382917", "0.53719866", "0.53443", "0.5328188", "0.5321512", "0.5315584", "0.52682865", "0.5257979", "0.52464527", "0.52243394", "0.5182478", "0.51760906", "0.5169583", "0.51561165", "0.5149604", "0.5149475", "0.5142157", "0.51358426", "0.5127753", "0.5106879", "0.50971305", "0.5083104", "0.5080869", "0.5079227", "0.50777876", "0.50711393", "0.50692934", "0.50671434", "0.5049952", "0.5047184", "0.50433785", "0.5039685", "0.50301826", "0.5024939", "0.5024682", "0.50130296", "0.49895853", "0.4973475", "0.49661013", "0.4932554", "0.4925669", "0.4924872", "0.4916521", "0.4914837", "0.49080846", "0.48982438", "0.4895944", "0.48948023", "0.4884853", "0.4883682", "0.4883387", "0.48801073", "0.4874358", "0.487098", "0.48709488", "0.486836", "0.4867403", "0.48636657", "0.4857022", "0.48475596", "0.4845556", "0.482989", "0.48297825", "0.48286137", "0.4821715", "0.4807884", "0.48057887", "0.48004094", "0.4799351", "0.4798741", "0.47980854" ]
0.70504236
0
writeValidators writes the current validator set to the validatoWidget Exits when the context expires.
func writeValidators(ctx context.Context, t *text.Text, connectionSignal <-chan string) { port := *givenPort socket := gowebsocket.New("ws://localhost:" + port + "/websocket") socket.OnConnected = func(socket gowebsocket.Socket) { validators := gjson.Get(getFromRPC("validators"), "result.validators") t.Reset() i := 1 validators.ForEach(func(key, validator gjson.Result) bool { ta := table.NewWriter() ta.AppendRow([]interface{}{fmt.Sprintf("%d", i), validator.Get("address").String(), validator.Get("voting_power").String()}) if err := t.Write(fmt.Sprintf("%s\n", ta.Render())); err != nil { panic(err) } i++ return true // keep iterating }) } socket.OnTextMessage = func(message string, socket gowebsocket.Socket) { validators := gjson.Get(getFromRPC("validators"), "result.validators") t.Reset() i := 1 validators.ForEach(func(key, validator gjson.Result) bool { ta := table.NewWriter() ta.AppendRow([]interface{}{fmt.Sprintf("%d", i), validator.Get("address").String(), validator.Get("voting_power").String()}) if err := t.Write(fmt.Sprintf("%s\n", ta.Render())); err != nil { panic(err) } i++ return true // keep iterating }) } socket.Connect() socket.SendText("{ \"jsonrpc\": \"2.0\", \"method\": \"subscribe\", \"params\": [\"tm.event='ValidatorSetUpdates'\"], \"id\": 3 }") for { select { case s := <-connectionSignal: if s == "no_connection" { socket.Close() } if s == "reconnect" { writeValidators(ctx, t, connectionSignal) } case <-ctx.Done(): log.Println("interrupt") socket.Close() return } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func WriteValidators(ctx sdk.Context, keeper *keeper.Keeper) (vals []cmttypes.GenesisValidator, returnErr error) {\n\terr := keeper.LastValidatorPower.Walk(ctx, nil, func(key []byte, _ gogotypes.Int64Value) (bool, error) {\n\t\tvalidator, err := keeper.GetValidator(ctx, key)\n\t\tif err != nil {\n\t\t\treturn true, err\n\t\t}\n\n\t\tpk, err := validator.ConsPubKey()\n\t\tif err != nil {\n\t\t\treturnErr = err\n\t\t\treturn true, err\n\t\t}\n\t\tcmtPk, err := cryptocodec.ToCmtPubKeyInterface(pk)\n\t\tif err != nil {\n\t\t\treturnErr = err\n\t\t\treturn true, err\n\t\t}\n\n\t\tvals = append(vals, cmttypes.GenesisValidator{\n\t\t\tAddress: sdk.ConsAddress(cmtPk.Address()).Bytes(),\n\t\t\tPubKey: cmtPk,\n\t\t\tPower: validator.GetConsensusPower(keeper.PowerReduction(ctx)),\n\t\t\tName: validator.GetMoniker(),\n\t\t})\n\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn vals, returnErr\n}", "func saveValidatorsInfo(db dbm.DB, nextHeight, changeHeight uint64, valSet *types.ValidatorSet) {\n\tvalInfo := &ValidatorsInfo{\n\t\tLastHeightChanged: changeHeight,\n\t}\n\tif changeHeight == nextHeight {\n\t\tvalInfo.ValidatorSet = valSet\n\t}\n\tdb.SetSync(calcValidatorsKey(nextHeight), valInfo.Bytes())\n}", "func (mapper GovMapper) saveValidatorSet(ctx context.Context, proposalID uint64) {\n\tvalidators := ecomapper.GetValidatorMapper(ctx).GetActiveValidatorSet(false)\n\tif validators != nil {\n\t\tmapper.Set(KeyVotingPeriodValidators(proposalID), validators)\n\t}\n}", "func (m *GovernanceManager) UpdateValidators(ctx context.Context, v *Validator) bool {\n\tif m.validatorWatcher != nil {\n\t\tvar validatorFile string\n\t\tselect {\n\t\tcase event := <-m.validatorWatcher.Events:\n\t\t\tif event.Op&fsnotify.Write == fsnotify.Write {\n\t\t\t\tvalidatorFile = event.Name\n\t\t\t}\n\t\tcase err := <-m.validatorWatcher.Errors:\n\t\t\tlog.Warnf(\"Validator file watcher error caught: %s\", err)\n\t\tdefault:\n\t\t\tbreak\n\t\t}\n\t\tif validatorFile != \"\" {\n\t\t\tgo func() {\n\t\t\t\tif m.loadValidatorsFromFile(ctx) == nil {\n\t\t\t\t\tm.sendValidators()\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t}\n\tselect {\n\tcase validator := <-m.validatorChan:\n\t\t*v = validator\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (di *dataIndexer) SaveValidatorsRating(indexID string, validatorsRatingInfo []*indexer.ValidatorRatingInfo) {\n\tvalRatingInfo := make([]*data.ValidatorRatingInfo, 0)\n\tfor _, info := range validatorsRatingInfo {\n\t\tvalRatingInfo = append(valRatingInfo, &data.ValidatorRatingInfo{\n\t\t\tPublicKey: info.PublicKey,\n\t\t\tRating: info.Rating,\n\t\t})\n\t}\n\n\twi := workItems.NewItemRating(\n\t\tdi.elasticProcessor,\n\t\tindexID,\n\t\tvalRatingInfo,\n\t)\n\tdi.dispatcher.Add(wi)\n}", "func (s AlwaysPanicStakingMock) IterateValidators(sdk.Context, func(index int64, validator stakingtypes.ValidatorI) (stop bool)) {\n\tpanic(\"unexpected call\")\n}", "func (k Keeper) IterateValidators(ctx sdk.Context, fn func(index int64, validator exported.ValidatorI) (stop bool)) {\n\tstore := ctx.KVStore(k.storeKey)\n\titerator := sdk.KVStorePrefixIterator(store, types.ValidatorsKey)\n\tdefer iterator.Close()\n\ti := int64(0)\n\tfor ; iterator.Valid(); iterator.Next() {\n\t\tvalidator := types.MustUnmarshalValidator(k.cdc, iterator.Value())\n\t\tstop := fn(i, validator) // XXX is this safe will the validator unexposed fields be able to get written to?\n\t\tif stop {\n\t\t\tbreak\n\t\t}\n\t\ti++\n\t}\n}", "func (k Keeper) IterateValidators(ctx context.Context, fn func(index int64, validator types.ValidatorI) (stop bool)) error {\n\tstore := k.storeService.OpenKVStore(ctx)\n\titerator, err := store.Iterator(types.ValidatorsKey, storetypes.PrefixEndBytes(types.ValidatorsKey))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer iterator.Close()\n\n\ti := int64(0)\n\n\tfor ; iterator.Valid(); iterator.Next() {\n\t\tvalidator, err := types.UnmarshalValidator(k.cdc, iterator.Value())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tstop := fn(i, validator) // XXX is this safe will the validator unexposed fields be able to get written to?\n\n\t\tif stop {\n\t\t\tbreak\n\t\t}\n\t\ti++\n\t}\n\n\treturn nil\n}", "func (di *dataIndexer) SaveValidatorsPubKeys(validatorsPubKeys map[uint32][][]byte, epoch uint32) {\n\twi := workItems.NewItemValidators(\n\t\tdi.elasticProcessor,\n\t\tepoch,\n\t\tvalidatorsPubKeys,\n\t)\n\tdi.dispatcher.Add(wi)\n}", "func (k Keeper) AddValidators(ctx sdk.Context, vals []abci.Validator) {\n\tfor i := 0; i < len(vals); i++ {\n\t\tval := vals[i]\n\t\tpubkey, err := tmtypes.PB2TM.PubKey(val.PubKey)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tk.addPubkey(ctx, pubkey)\n\t}\n}", "func (s *StakingKeeperMock) IterateValidators(ctx sdk.Context, cb func(index int64, validator stakingtypes.ValidatorI) (stop bool)) {\n\tfor i, val := range s.BondedValidators {\n\t\tstop := cb(int64(i), val)\n\t\tif stop {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (m *ValidatorSet) MarshalToWriter(writer jspb.Writer) {\n\tif m == nil {\n\t\treturn\n\t}\n\n\tfor _, msg := range m.ValidatorPublicKeys {\n\t\twriter.WriteMessage(1, func() {\n\t\t\tmsg.MarshalToWriter(writer)\n\t\t})\n\t}\n\n\treturn\n}", "func (status NewStatus) GetValidators() (last *types.ValidatorSet, current *types.ValidatorSet) {\n\treturn status.LastValidators, status.Validators\n}", "func (vlog *valueLog) validateWrites(reqs []*request) error {\n\tvlogOffset := uint64(vlog.woffset())\n\tfor _, req := range reqs {\n\t\t// calculate size of the request.\n\t\tsize := estimateRequestSize(req)\n\t\testimatedVlogOffset := vlogOffset + size\n\t\tif estimatedVlogOffset > uint64(maxVlogFileSize) {\n\t\t\treturn errors.Errorf(\"Request size offset %d is bigger than maximum offset %d\",\n\t\t\t\testimatedVlogOffset, maxVlogFileSize)\n\t\t}\n\n\t\tif estimatedVlogOffset >= uint64(vlog.opt.ValueLogFileSize) {\n\t\t\t// We'll create a new vlog file if the estimated offset is greater or equal to\n\t\t\t// max vlog size. So, resetting the vlogOffset.\n\t\t\tvlogOffset = 0\n\t\t\tcontinue\n\t\t}\n\t\t// Estimated vlog offset will become current vlog offset if the vlog is not rotated.\n\t\tvlogOffset = estimatedVlogOffset\n\t}\n\treturn nil\n}", "func (k Keeper) IterateLastValidators(ctx sdk.Context,\n\tfn func(index int64, validator exported.ValidatorI) (stop bool)) {\n\titerator := k.LastValidatorsIterator(ctx)\n\tdefer iterator.Close()\n\ti := int64(0)\n\tfor ; iterator.Valid(); iterator.Next() {\n\t\taddress := types.AddressFromLastValidatorPowerKey(iterator.Key())\n\t\tvalidator, found := k.GetValidator(ctx, address)\n\t\tif !found {\n\t\t\tpanic(fmt.Sprintf(\"validator record not found for address: %v\\n\", address))\n\t\t}\n\n\t\tstop := fn(i, validator) // XXX is this safe will the validator unexposed fields be able to get written to?\n\t\tif stop {\n\t\t\tbreak\n\t\t}\n\t\ti++\n\t}\n}", "func (s AlwaysPanicStakingMock) IterateLastValidators(sdk.Context, func(index int64, validator stakingtypes.ValidatorI) (stop bool)) {\n\tpanic(\"unexpected call\")\n}", "func AddValidators(m map[string]any) {\n\tfor name, checkFunc := range m {\n\t\tAddValidator(name, checkFunc)\n\t}\n}", "func (m Mapper) getValidators(maxVal uint16) (validators []Validator) {\n\n\titerator := m.store.Iterator(subspace(ValidatorKeyPrefix)) //smallest to largest\n\n\tvalidators = make([]Validator, maxVal)\n\tfor i := 0; ; i++ {\n\t\tif !iterator.Valid() || i > int(maxVal) {\n\t\t\titerator.Close()\n\t\t\tbreak\n\t\t}\n\t\tvalBytes := iterator.Value()\n\t\tvar val Validator\n\t\terr := m.cdc.UnmarshalJSON(valBytes, &val)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tvalidators[i] = val\n\t\titerator.Next()\n\t}\n\n\treturn\n}", "func (s *Service) refreshValidators(ctx context.Context) error {\n\taccountPubKeys := make([]phase0.BLSPubKey, 0, len(s.accounts))\n\tfor pubKey := range s.accounts {\n\t\taccountPubKeys = append(accountPubKeys, pubKey)\n\t}\n\tif err := s.validatorsManager.RefreshValidatorsFromBeaconNode(ctx, accountPubKeys); err != nil {\n\t\treturn errors.Wrap(err, \"failed to refresh validators\")\n\t}\n\treturn nil\n}", "func (plugin *testPlugin) TransactionValidators() []modules.PluginTransactionValidationFunction {\n\treturn nil\n}", "func (h MultiStakingHooks) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) {\n\tfor i := range h {\n\t\th[i].AfterValidatorCreated(ctx, valAddr)\n\t}\n}", "func setupValidators(sdk pb.Sdk, filepath string) *[]validators.Validator {\n\tvar val *[]validators.Validator\n\tswitch sdk {\n\tcase pb.Sdk_SDK_JAVA:\n\t\tval = validators.GetJavaValidators(filepath)\n\t}\n\treturn val\n}", "func setupTestValidators(pool Pool, keeper Keeper, ctx sdk.Context, validatorTokens []int64, maxValidators uint16) ([]Validator, Keeper, Pool) {\n\tparams := DefaultParams()\n\tparams.MaxValidators = maxValidators\n\tkeeper.setParams(ctx, params)\n\tnumValidators := len(validatorTokens)\n\tvalidators := make([]Validator, numValidators)\n\n\tfor i := 0; i < numValidators; i++ {\n\t\tvalidators[i] = NewValidator(addrs[i], pks[i], Description{})\n\t\tvalidators[i], pool, _ = validators[i].addTokensFromDel(pool, sdk.NewInt(validatorTokens[i]))\n\t\tkeeper.setPool(ctx, pool)\n\t\tvalidators[i] = keeper.updateValidator(ctx, validators[i]) //will kick out lower power validators. Keep this in mind when setting up the test validators order\n\t\tpool = keeper.GetPool(ctx)\n\t}\n\n\treturn validators, keeper, pool\n}", "func (s *StakingKeeperMock) IterateLastValidators(ctx sdk.Context, cb func(index int64, validator stakingtypes.ValidatorI) (stop bool)) {\n\tfor i, val := range s.BondedValidators {\n\t\tstop := cb(int64(i), val)\n\t\tif stop {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func getValidators(store types.KVStore, maxVal int) (validators []Validator) {\n\n\titerator := store.Iterator(subspace(ValidatorKeyPrefix)) //smallest to largest\n\n\tvalidators = make([]Validator, maxVal)\n\tfor i := 0; ; i++ {\n\t\tif !iterator.Valid() || i > maxVal {\n\t\t\titerator.Close()\n\t\t\tbreak\n\t\t}\n\t\tvalBytes := iterator.Value()\n\t\tvar val Validator\n\t\terr := cdc.UnmarshalJSON(valBytes, &val)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tvalidators[i] = val\n\t\titerator.Next()\n\t}\n\n\treturn\n}", "func (h MultiStakingHooks) AfterValidatorDestroyed(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) {\n\tfor i := range h {\n\t\th[i].AfterValidatorDestroyed(ctx, consAddr, valAddr)\n\t}\n}", "func (s *TXPoolServer) registerValidator(v *types.RegisterValidator) {\n\ts.validators.Lock()\n\tdefer s.validators.Unlock()\n\n\t_, ok := s.validators.entries[v.Type]\n\n\tif !ok {\n\t\ts.validators.entries[v.Type] = make([]*types.RegisterValidator, 0, 1)\n\t}\n\ts.validators.entries[v.Type] = append(s.validators.entries[v.Type], v)\n}", "func (f FormField) SetValidators(validators *ValidatorsList) FormField {\n\tf.Validators = validators\n\treturn f\n}", "func (k Keeper) MaxValidators(ctx sdk.Context) (res uint32) {\n\tk.paramspace.Get(ctx, types.KeyMaxValidators, &res)\n\treturn\n}", "func (consensus *Consensus) DebugPrintValidators() {\n\tcount := 0\n\tconsensus.validators.Range(func(k, v interface{}) bool {\n\t\tif p, ok := v.(p2p.Peer); ok {\n\t\t\tstr2 := fmt.Sprintf(\"%s\", p.PubKey)\n\t\t\tutils.GetLogInstance().Debug(\"validator:\", \"IP\", p.IP, \"Port\", p.Port, \"VID\", p.ValidatorID, \"Key\", str2)\n\t\t\tcount++\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t})\n\tutils.GetLogInstance().Debug(\"Validators\", \"#\", count)\n}", "func SetWriters(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"INFO\\tSet Writers\")\n\tfmt.Println(\"INFO\\tSet Writers\")\n\n\t/*\n\t\tvars := mux.Vars(r)\n\t\tip := vars[\"ip\"]\n\n\t\tips := strings.Split(ip, DELIM)\n\n\t\tfor i := range ips {\n\t\t\tdata.writers[ips[i]] = true\n\t\t}\n\n\t\tif data.processType == 3 {\n\t\t\tvar clients map[string]bool = data.writers\n\t\t\tserverListStr := create_server_list_string()\n\t\t\tj := 0\n\t\t\tfor ipaddr := range clients {\n\t\t\t\tsend_command_to_process(ipaddr, \"SetServers\", serverListStr)\n\t\t\t\tname := \"writer_\" + fmt.Sprintf(\"%d\", j)\n\t\t\t\tsend_command_to_process(ipaddr, \"SetName\", name)\n\t\t\t\tj = j + 1\n\t\t\t}\n\t\t}\n\t*/\n}", "func (svcs *Services) ProcessValidatorSet(state *State, log types.Log) error {\n\n\teth := svcs.eth\n\tc := eth.Contracts()\n\n\tupdatedState := state\n\n\tevent, err := c.Ethdkg.ParseValidatorSet(log)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tepoch := uint32(event.Epoch.Int64())\n\n\tvs := state.ValidatorSets[epoch]\n\tvs.NotBeforeMadNetHeight = event.MadHeight\n\tvs.ValidatorCount = event.ValidatorCount\n\tvs.GroupKey[0] = *event.GroupKey0\n\tvs.GroupKey[1] = *event.GroupKey1\n\tvs.GroupKey[2] = *event.GroupKey2\n\tvs.GroupKey[3] = *event.GroupKey3\n\n\tupdatedState.ValidatorSets[epoch] = vs\n\n\terr = svcs.checkValidatorSet(updatedState, epoch)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (h *Handler) validationHandler() {\n\ttxs := []tx{}\n\tfor {\n\t\tselect {\n\t\tcase tx := <-h.validations:\n\t\t\tpossibleCollisions := filterTxs(txs, tx.gtc)\n\t\t\tif !detectCollisions(possibleCollisions, tx) {\n\t\t\t\th.stateHandler.Write(tx.changeSet)\n\t\t\t}\n\t\t}\n\t}\n}", "func (monitor *Monitor) connectToValidators() error {\n\n\tif monitor.Validators == nil || len(monitor.Validators) == 0 {\n\t\treturn fmt.Errorf(\"error: no validators given\")\n\t}\n\n\t// resolve validator addresses given and connect to them\n\tfor _, val := range monitor.Validators {\n\t\tconn, err := connection.Connect(val)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error while connecting to one of the validators given: %s\", err)\n\t\t}\n\n\t\t// start goroutines to send message and wait for reply from each validator\n\t\tgo monitor.receiveHvsFromValidator(conn)\n\t}\n\n\treturn nil\n}", "func (vs *ValidatorSet) RemoveValidator(addr sdk.AccAddress) {\n\tpos := -1\n\tfor i, val := range vs.Validators {\n\t\tif bytes.Equal(val.Address, addr) {\n\t\t\tpos = i\n\t\t\tbreak\n\t\t}\n\t}\n\tif pos == -1 {\n\t\treturn\n\t}\n\tvs.Validators = append(vs.Validators[:pos], vs.Validators[pos+1:]...)\n}", "func (m Mapper) clearValidatorUpdates(maxVal int) {\n\titerator := m.store.Iterator(subspace(ValidatorUpdatesKeyPrefix))\n\tfor ; iterator.Valid(); iterator.Next() {\n\t\tm.store.Delete(iterator.Key()) // XXX write test for this, may need to be in a second loop\n\t}\n\titerator.Close()\n}", "func (vs *ValidatorSet) AddValidator(val Validator) {\n\tvs.Validators = append(vs.Validators, val)\n}", "func (s *Module) SetUpdateValidatorsCallback(f func(uint32, keys.PublicKeys)) {\n\ts.mtx.Lock()\n\tdefer s.mtx.Unlock()\n\ts.updateValidatorsCb = f\n}", "func WritersBlock(run Runtime, w writer.Output, fn func() error) (err error) {\n\twas := run.SetWriter(w)\n\te := fn()\n\trun.SetWriter(was)\n\tif e != nil {\n\t\terr = e\n\t} else {\n\t\terr = writer.Close(w)\n\t}\n\treturn\n}", "func (cs *ConsensusState) GetValidators() (int64, []*ttypes.Validator) {\n\tcs.mtx.Lock()\n\tdefer cs.mtx.Unlock()\n\treturn cs.state.LastBlockHeight, cs.state.Validators.Copy().Validators\n}", "func (ruleset *DnsForwardingRuleset) deleteValidations() []func() (admission.Warnings, error) {\n\treturn nil\n}", "func (s *Simulator) GetAllValidators() SimValidators {\n\tvalidators := make(SimValidators, 0)\n\tfor _, acc := range s.accounts {\n\t\tif !acc.IsValOperator() {\n\t\t\tcontinue\n\t\t}\n\t\tvalidators = append(validators, acc.OperatedValidator)\n\t}\n\n\treturn validators\n}", "func (e *Errors) Validate(validators ...Validator) {\n\t// declare WaitGroup\n\twg := &sync.WaitGroup{}\n\n\t// loop-over supplied validators\n\tfor i := range validators {\n\t\t// new goroutine busy count\n\t\twg.Add(1)\n\n\t\tgo func(wg *sync.WaitGroup, i int) {\n\t\t\t// release goroutines busy count on exit\n\t\t\tdefer wg.Done()\n\n\t\t\t// get current validator object\n\t\t\tvalidator := validators[i]\n\n\t\t\t// run validation method\n\t\t\tvalidator.Validate(e)\n\t\t}(wg, i)\n\t}\n\n\t// wait for all concurrent goroutines to finish\n\twg.Wait()\n}", "func Validators() map[string]int8 {\n\treturn validators\n}", "func (policy *ServersConnectionPolicy) deleteValidations() []func() (admission.Warnings, error) {\n\treturn nil\n}", "func (s AlwaysPanicStakingMock) IterateBondedValidatorsByPower(sdk.Context, func(index int64, validator stakingtypes.ValidatorI) (stop bool)) {\n\tpanic(\"unexpected call\")\n}", "func (machine *VirtualMachine) deleteValidations() []func() (admission.Warnings, error) {\n\treturn nil\n}", "func (v Validators) ToSDKValidators() (validators []exported.ValidatorI) {\n\tfor _, val := range v {\n\t\tvalidators = append(validators, val)\n\t}\n\treturn validators\n}", "func (f *StringSetFilter) AddValidator(validator StringSetValidator) *StringSetFilter {\r\n\tf.validators = append(f.validators, validator)\r\n\treturn f\r\n}", "func (c *Config) AddValidator(v Validator) {}", "func (p *proxy) ValidatorsCount() (uint64, error) {\n\treturn p.rpc.ValidatorsCount()\n}", "func All(validators ...Validator) []error {\n\tvar output []error\n\tvar err error\n\tfor _, validator := range validators {\n\t\tif err = validator(); err != nil {\n\t\t\toutput = append(output, err)\n\t\t}\n\t}\n\treturn output\n}", "func validateWriteOptions(opts *cli.Options) error {\n\treturn nil\n}", "func (setting *MongodbDatabaseCollectionThroughputSetting) deleteValidations() []func() (admission.Warnings, error) {\n\treturn nil\n}", "func (store *ConfigurationStore) deleteValidations() []func() (admission.Warnings, error) {\n\treturn nil\n}", "func (machine *VirtualMachine) updateValidations() []func(old runtime.Object) (admission.Warnings, error) {\n\treturn []func(old runtime.Object) (admission.Warnings, error){\n\t\tfunc(old runtime.Object) (admission.Warnings, error) {\n\t\t\treturn machine.validateResourceReferences()\n\t\t},\n\t\tmachine.validateWriteOnceProperties}\n}", "func encodeValidator(w io.Writer, v schema.FieldValidator) (err error) {\n\tif v == nil {\n\t\treturn nil\n\t}\n\tswitch t := v.(type) {\n\tcase *schema.String:\n\t\terr = encodeString(w, t)\n\tcase *schema.Integer:\n\t\terr = encodeInteger(w, t)\n\tcase *schema.Float:\n\t\terr = encodeFloat(w, t)\n\tcase *schema.Array:\n\t\terr = encodeArray(w, t)\n\tcase *schema.Object:\n\t\t// FIXME: May break the JSON encoding atm. if t.Schema is nil.\n\t\terr = encodeObject(w, t)\n\tcase *schema.Time:\n\t\terr = encodeTime(w, t)\n\tcase *schema.Bool:\n\t\terr = encodeBool(w, t)\n\tdefault:\n\t\treturn ErrNotImplemented\n\t}\n\treturn err\n}", "func LoadValidators(db dbm.DB, height uint64) (*types.ValidatorSet, uint64, error) {\n\tvalInfo := loadValidatorsInfo(db, height)\n\tif valInfo == nil {\n\t\treturn nil, 0, ErrNoValSetForHeight{height}\n\t}\n\tlastHeightChanged := valInfo.LastHeightChanged\n\tif valInfo.ValidatorSet == nil {\n\t\tvalInfo2 := loadValidatorsInfo(db, lastHeightChanged)\n\t\tif valInfo2 == nil {\n\t\t\tcmn.PanicSanity(fmt.Sprintf(`Couldn't find validators at height %d as\n last changed from height %d`, valInfo.LastHeightChanged, height))\n\t\t}\n\t\tvalInfo = valInfo2\n\t}\n\n\treturn valInfo.ValidatorSet, lastHeightChanged, nil\n}", "func clearValidatorUpdates(store types.KVStore, maxVal int) {\n\titerator := store.Iterator(subspace(ValidatorUpdatesKeyPrefix))\n\tfor ; iterator.Valid(); iterator.Next() {\n\t\tstore.Delete(iterator.Key()) // XXX write test for this, may need to be in a second loop\n\t}\n\titerator.Close()\n}", "func (k Querier) Validators(ctx context.Context, req *types.QueryValidatorsRequest) (*types.QueryValidatorsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\t// validate the provided status, return all the validators if the status is empty\n\tif req.Status != \"\" && !(req.Status == types.Bonded.String() || req.Status == types.Unbonded.String() || req.Status == types.Unbonding.String()) {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"invalid validator status %s\", req.Status)\n\t}\n\n\tstore := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))\n\tvalStore := prefix.NewStore(store, types.ValidatorsKey)\n\n\tvalidators, pageRes, err := query.GenericFilteredPaginate(k.cdc, valStore, req.Pagination, func(key []byte, val *types.Validator) (*types.Validator, error) {\n\t\tif req.Status != \"\" && !strings.EqualFold(val.GetStatus().String(), req.Status) {\n\t\t\treturn nil, nil\n\t\t}\n\n\t\treturn val, nil\n\t}, func() *types.Validator {\n\t\treturn &types.Validator{}\n\t})\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tvals := types.Validators{}\n\tfor _, val := range validators {\n\t\tvals.Validators = append(vals.Validators, *val)\n\t}\n\n\treturn &types.QueryValidatorsResponse{Validators: vals.Validators, Pagination: pageRes}, nil\n}", "func (self *testSystemBackend) Validators(proposal istanbul.Proposal) istanbul.ValidatorSet {\n\treturn self.peers\n}", "func (s *Simulator) GetValidators(bonded, unbonding, unbonded bool) SimValidators {\n\tvalidators := make(SimValidators, 0)\n\tfor _, acc := range s.accounts {\n\t\tif acc.OperatedValidator != nil {\n\t\t\tadd := false\n\t\t\tswitch acc.OperatedValidator.GetStatus() {\n\t\t\tcase sdk.Bonded:\n\t\t\t\tif bonded {\n\t\t\t\t\tadd = true\n\t\t\t\t}\n\t\t\tcase sdk.Unbonding:\n\t\t\t\tif unbonding {\n\t\t\t\t\tadd = true\n\t\t\t\t}\n\t\t\tcase sdk.Unbonded:\n\t\t\t\tif unbonded {\n\t\t\t\t\tadd = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif add {\n\t\t\t\tvalidators = append(validators, acc.OperatedValidator)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn validators\n}", "func (setting *MongodbDatabaseCollectionThroughputSetting) updateValidations() []func(old runtime.Object) (admission.Warnings, error) {\n\treturn []func(old runtime.Object) (admission.Warnings, error){\n\t\tfunc(old runtime.Object) (admission.Warnings, error) {\n\t\t\treturn setting.validateResourceReferences()\n\t\t},\n\t\tsetting.validateWriteOnceProperties}\n}", "func (setting *MongodbDatabaseCollectionThroughputSetting) createValidations() []func() (admission.Warnings, error) {\n\treturn []func() (admission.Warnings, error){setting.validateResourceReferences}\n}", "func (store *ConfigurationStore) createValidations() []func() (admission.Warnings, error) {\n\treturn []func() (admission.Warnings, error){store.validateResourceReferences, store.validateSecretDestinations}\n}", "func (k Keeper) GetActiveValidators(ctx sdk.Context) ([]types.Validator, error) {\n\tvar result []types.Validator\n\tstore := ctx.KVStore(k.dataStoreKey)\n\tproposed := k.GetBlocksProposedByAll(ctx)\n\n\tit := store.Iterator(nil, nil)\n\tdefer it.Close()\n\tfor ; it.Valid(); it.Next() {\n\t\tvar value types.Info\n\t\tif err := proto.Unmarshal(it.Value(), &value); err != nil {\n\t\t\tpanic(errors.Wrap(err, \"cannot unmarshal info\"))\n\t\t}\n\t\tif !value.IsActive() {\n\t\t\tcontinue\n\t\t}\n\t\taddr := sdk.AccAddress(it.Key())\n\t\tresult = append(result, types.GenesisValidatorFromD(addr, value, proposed[addr.String()]))\n\t}\n\n\treturn result, nil\n}", "func (db *Database) QueryValidators() ([]*schema.Validator, error) {\n\tvals := make([]*schema.Validator, 0)\n\n\terr := db.Model(&vals).\n\t\tOrder(\"tokens DESC\").\n\t\tSelect()\n\n\tif err == pg.ErrNoRows {\n\t\treturn vals, fmt.Errorf(\"no rows in block table: %s\", err)\n\t}\n\n\tif err != nil {\n\t\treturn vals, fmt.Errorf(\"unexpected database error: %s\", err)\n\t}\n\n\treturn vals, nil\n}", "func (m *FederatedTokenValidationPolicy) SetValidatingDomains(value ValidatingDomainsable)() {\n err := m.GetBackingStore().Set(\"validatingDomains\", value)\n if err != nil {\n panic(err)\n }\n}", "func (k Keeper) AddValidator(ctx sdk.Context, address sdk.AccAddress, ethAddress string) error {\n\tk.modulePerms.AutoCheck(types.PermWrite)\n\n\treturn k.addValidator(ctx, address, ethAddress, true)\n}", "func (s *ControllerPool) NewControllerValidators(controllerType string, validator ...Validator) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\ts.controllerValidators[controllerType] = validator\n}", "func (store *ConfigurationStore) updateValidations() []func(old runtime.Object) (admission.Warnings, error) {\n\treturn []func(old runtime.Object) (admission.Warnings, error){\n\t\tfunc(old runtime.Object) (admission.Warnings, error) {\n\t\t\treturn store.validateResourceReferences()\n\t\t},\n\t\tstore.validateWriteOnceProperties,\n\t\tfunc(old runtime.Object) (admission.Warnings, error) {\n\t\t\treturn store.validateSecretDestinations()\n\t\t},\n\t}\n}", "func (s *SPService) getValidators(round uint32, verbose bool) ([]*common.Address, map[common.Address]uint16, error) {\n\tvalidators, weightMap, err := s.config.Chain.GetValidators(round)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to get validators %v\", err.Error())\n\t}\n\tif int64(len(validators)) != s.context.RoundSize {\n\t\treturn nil, nil, fmt.Errorf(\"getValidators error: can not get validators %d for round = %d\",\n\t\t\tlen(validators), round)\n\t}\n\n\tif verbose {\n\t\tfor i := 0; i < len(validators); i++ {\n\t\t\tlog.Infof(\"validators[%d]=%v\", i, validators[i].String())\n\t\t}\n\t}\n\treturn validators, weightMap, nil\n}", "func (rule *NamespacesEventhubsAuthorizationRule) deleteValidations() []func() (admission.Warnings, error) {\n\treturn nil\n}", "func GetScioValidators(filePath string) *[]Validator {\n\tvalidatorArgs := make([]interface{}, 2)\n\tvalidatorArgs[0] = filePath\n\tvalidatorArgs[1] = scalaExtension\n\tpathCheckerValidator := Validator{\n\t\tValidator: fs_tool.CheckPathIsValid,\n\t\tArgs: validatorArgs,\n\t\tName: \"Valid path\",\n\t}\n\tunitTestValidator := Validator{\n\t\tValidator: checkIsUnitTestScio,\n\t\tArgs: validatorArgs,\n\t\tName: UnitTestValidatorName,\n\t}\n\tvalidators := []Validator{pathCheckerValidator, unitTestValidator}\n\treturn &validators\n}", "func (validatorObj *ValidatorStruct) AddValidator() string {\n\tvalidatorObj.Index = NewIndex()\n\tif validatorObj.validationAdd() {\n\t\tif validatorObj.ValidatorIP == CurrentValidator.ValidatorIP {\n\t\t\tValidatorsLstObj = append(ValidatorsLstObj, *validatorObj) //add the current validator pivate key only in validator list\n\t\t\tvalidatorObj.ECCPublicKey = *new(ecdsa.PublicKey) //delete both keys from validator to store in db\n\t\t\tvalidatorObj.ECCPrivateKey = new(ecdsa.PrivateKey)\n\t\t} else {\n\t\t\tvalidatorObj.ECCPrivateKey = new(ecdsa.PrivateKey) //delete private key first\n\t\t\tValidatorsLstObj = append(ValidatorsLstObj, *validatorObj) //add the other node validator with public key only to the list\n\t\t\tvalidatorObj.ECCPublicKey = *new(ecdsa.PublicKey) // then delete the public key from validatore before saving it to the db\n\t\t}\n\t\tCreateValidator(validatorObj)\n\t\treturn \"\"\n\t}\n\treturn errorpk.AddError(\"Add Validator validator package\", \"enter correct validator object not exist before\", \"hack error\")\n}", "func (rv *ResumeValidator) RegisterValidatorAPI() {\n\thttp.HandleFunc(\"/\", rv.homePage())\n\thttp.HandleFunc(\"/validateFile\", rv.validateFile())\n}", "func (validatorObj *ValidatorStruct) UpdateValidator() string {\n\tfor index, validatorExistsObj := range ValidatorsLstObj {\n\t\tif validatorExistsObj.ValidatorIP == validatorObj.ValidatorIP {\n\t\t\tdecryptedValidatorList := GetAllValidatorsDecrypted()\n\t\t\tfor _, myValidator := range decryptedValidatorList {\n\t\t\t\tif validatorObj.ValidatorIP == myValidator.ValidatorIP {\n\t\t\t\t\tif validatorObj.ValidatorIP == CurrentValidator.ValidatorIP {\n\t\t\t\t\t\tvalidatorObj.ECCPublicKey = myValidator.ECCPublicKey\n\t\t\t\t\t\tvalidatorObj.ECCPrivateKey = myValidator.ECCPrivateKey\n\t\t\t\t\t\tvalidatorObj.EncECCPriv = myValidator.EncECCPriv\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvalidatorObj.ECCPublicKey = myValidator.ECCPublicKey\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tValidatorsLstObj[index] = *validatorObj\n\t\t\tvalidatorObj.ECCPublicKey = *new(ecdsa.PublicKey)\n\t\t\tvalidatorObj.ECCPrivateKey = new(ecdsa.PrivateKey)\n\t\t\tCreateValidator(validatorObj)\n\t\t\treturn \"\"\n\t\t}\n\t}\n\treturn errorpk.AddError(\"Update Validator validator package\", \"Can't find the validator object \"+validatorObj.ValidatorIP, \"hack error\")\n}", "func (policy *ServersConnectionPolicy) updateValidations() []func(old runtime.Object) (admission.Warnings, error) {\n\treturn []func(old runtime.Object) (admission.Warnings, error){\n\t\tfunc(old runtime.Object) (admission.Warnings, error) {\n\t\t\treturn policy.validateResourceReferences()\n\t\t},\n\t\tpolicy.validateWriteOnceProperties}\n}", "func (w *writer) WriteAll() {\n\tvar wg = sync.WaitGroup{}\n\n\tfor _, application := range w.project.Applications {\n\t\twg.Add(1)\n\t\tgo func(application *config.Application) {\n\t\t\tdefer wg.Done()\n\t\t\tw.Write(application)\n\t\t}(application)\n\t}\n\n\twg.Wait()\n}", "func (k Keeper) IterateBondedValidatorsByPower(ctx context.Context, fn func(index int64, validator types.ValidatorI) (stop bool)) error {\n\tstore := k.storeService.OpenKVStore(ctx)\n\tmaxValidators, err := k.MaxValidators(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\titerator, err := store.ReverseIterator(types.ValidatorsByPowerIndexKey, storetypes.PrefixEndBytes(types.ValidatorsByPowerIndexKey))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer iterator.Close()\n\n\ti := int64(0)\n\tfor ; iterator.Valid() && i < int64(maxValidators); iterator.Next() {\n\t\taddress := iterator.Value()\n\t\tvalidator := k.mustGetValidator(ctx, address)\n\n\t\tif validator.IsBonded() {\n\t\t\tstop := fn(i, validator) // XXX is this safe will the validator unexposed fields be able to get written to?\n\t\t\tif stop {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ti++\n\t\t}\n\t}\n\n\treturn nil\n}", "func (s AlwaysPanicStakingMock) GetBondedValidatorsByPower(ctx sdk.Context) []stakingtypes.Validator {\n\tpanic(\"unexpected call\")\n}", "func (self *Bgmchain) SetValidator(validator bgmcommon.Address) {\n\tself.lock.Lock()\n\tself.validator = validator\n\tself.lock.Unlock()\n}", "func (p *http) ValidatorSet(height int64) (*types.ValidatorSet, error) {\n\th, err := validateHeight(height)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconst maxPerPage = 100\n\tres, err := p.client.Validators(h, 0, maxPerPage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar (\n\t\tvals = res.Validators\n\t\tpage = 1\n\t)\n\n\t// Check if there are more validators.\n\tfor len(res.Validators) == maxPerPage {\n\t\tres, err = p.client.Validators(h, page, maxPerPage)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(res.Validators) > 0 {\n\t\t\tvals = append(vals, res.Validators...)\n\t\t}\n\t\tpage++\n\t}\n\n\treturn types.NewValidatorSet(vals), nil\n}", "func (s *StakingKeeperMock) IterateBondedValidatorsByPower(ctx sdk.Context, cb func(index int64, validator stakingtypes.ValidatorI) (stop bool)) {\n\tfor i, val := range s.BondedValidators {\n\t\tstop := cb(int64(i), val)\n\t\tif stop {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (h MultiStakingHooks) AfterValidatorBonded(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) {\n\tfor i := range h {\n\t\th[i].AfterValidatorBonded(ctx, consAddr, valAddr)\n\t}\n}", "func (api *API) GetValidators(number *rpc.BlockNumber) ([]common.Address, error) {\n\t// Retrieve the requested block number (or current if none requested)\n\tvar header *types.Header\n\tif number == nil || *number == rpc.LatestBlockNumber {\n\t\theader = api.chain.CurrentHeader()\n\t} else {\n\t\theader = api.chain.GetHeaderByNumber(uint64(number.Int64()))\n\t}\n\t// Ensure we have an actually valid block and return the validators from its snapshot\n\tif header == nil {\n\t\treturn nil, istanbulcommon.ErrUnknownBlock\n\t}\n\tsnap, err := api.backend.snapshot(api.chain, header.Number.Uint64(), header.Hash(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn snap.validators(), nil\n}", "func (ruleset *DnsForwardingRuleset) updateValidations() []func(old runtime.Object) (admission.Warnings, error) {\n\treturn []func(old runtime.Object) (admission.Warnings, error){\n\t\tfunc(old runtime.Object) (admission.Warnings, error) {\n\t\t\treturn ruleset.validateResourceReferences()\n\t\t},\n\t\truleset.validateWriteOnceProperties}\n}", "func (app *ArteryApp) ExportAppStateAndValidators(\n\tforZeroHeight bool, jailWhiteList []string,\n) (appState json.RawMessage, validators []tmtypes.GenesisValidator, err error) {\n\n\t// as if they could withdraw from the start of the next block\n\tctx := app.NewContext(true, abci.Header{Height: app.LastBlockHeight()})\n\n\tif forZeroHeight {\n\t\tapp.prepForZeroHeightGenesis(ctx, jailWhiteList)\n\t}\n\n\tgenState := app.mm.ExportGenesis(ctx)\n\tappState, err = codec.MarshalJSONIndent(app.cdc, genState)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// We should never have genesis validators per se.\n\t// All validators should be added via noding module instead.\n\treturn appState, nil, nil\n}", "func (r *mutationResolver) WriteTenants(ctx context.Context, in []*graphql.BusinessTenantMappingInput) ([]string, error) {\n\treturn r.tenant.Write(ctx, in)\n}", "func (it *ERC721ValidatorAddedIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func RegisterValidations() {\n\tif v, ok := binding.Validator.Engine().(*validator.Validate); ok {\n\t\tv.RegisterValidation(\"validpin\", validPincode)\n\t\tv.RegisterValidation(\"validtransportmode\", validTransportMode)\n\t}\n}", "func (p *proxy) DownValidators() ([]types.OfflineValidator, error) {\n\ttopID, err := p.LastValidatorId()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlist := make([]types.OfflineValidator, 0)\n\tfor i := uint64(0); i < topID; i++ {\n\t\tot, ob, err := p.ValidatorDowntime((*hexutil.Big)(big.NewInt(int64(i))))\n\t\tif err != nil {\n\t\t\tp.log.Errorf(\"could not get downtime of #%d; %s\", i, err.Error())\n\t\t\tcontinue\n\t\t}\n\n\t\tif ot > 0 {\n\t\t\tadr, err := p.rpc.ValidatorAddress(big.NewInt(int64(i)))\n\t\t\tif err != nil {\n\t\t\t\tp.log.Errorf(\"could not get address of #%d; %s\", i, err.Error())\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlist = append(list, types.OfflineValidator{\n\t\t\t\tID: i,\n\t\t\t\tAddress: *adr,\n\t\t\t\tDownTime: types.Downtime(ot),\n\t\t\t\tDownBlocks: ob,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn list, nil\n}", "func ValidateOutputs(outputs serializer.Serializables, funcs ...OutputsValidatorFunc) error {\n\tfor i, output := range outputs {\n\t\tif _, isOutput := output.(Output); !isOutput {\n\t\t\treturn fmt.Errorf(\"%w: can only validate outputs but got %T instead\", ErrUnknownOutputType, output)\n\t\t}\n\t\tfor _, f := range funcs {\n\t\t\tif err := f(i, output.(Output)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (k Keeper) IterateBondedValidatorsByPower(ctx sdk.Context,\n\tfn func(index int64, validator exported.ValidatorI) (stop bool)) {\n\tstore := ctx.KVStore(k.storeKey)\n\tmaxValidators := k.MaxValidators(ctx)\n\n\titerator := sdk.KVStoreReversePrefixIterator(store, types.ValidatorsByPowerIndexKey)\n\tdefer iterator.Close()\n\n\ti := int64(0)\n\tfor ; iterator.Valid() && i < int64(maxValidators); iterator.Next() {\n\t\taddress := iterator.Value()\n\t\tvalidator := k.mustGetValidator(ctx, address)\n\n\t\tif validator.IsBonded() {\n\t\t\tstop := fn(i, validator) // XXX is this safe will the validator unexposed fields be able to get written to?\n\t\t\tif stop {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ti++\n\t\t}\n\t}\n}", "func (m *FederatedTokenValidationPolicy) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.DirectoryObject.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteObjectValue(\"validatingDomains\", m.GetValidatingDomains())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (k Querier) DelegatorValidators(ctx context.Context, req *types.QueryDelegatorValidatorsRequest) (*types.QueryDelegatorValidatorsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\tvar validators types.Validators\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, pageRes, err := query.CollectionPaginate(ctx, k.Delegations, req.Pagination,\n\t\tfunc(_ collections.Pair[sdk.AccAddress, sdk.ValAddress], delegation types.Delegation) (types.Delegation, error) {\n\t\t\tvalAddr, err := k.validatorAddressCodec.StringToBytes(delegation.GetValidatorAddr())\n\t\t\tif err != nil {\n\t\t\t\treturn types.Delegation{}, err\n\t\t\t}\n\t\t\tvalidator, err := k.GetValidator(ctx, valAddr)\n\t\t\tif err != nil {\n\t\t\t\treturn types.Delegation{}, err\n\t\t\t}\n\n\t\t\tvalidators.Validators = append(validators.Validators, validator)\n\t\t\treturn types.Delegation{}, nil\n\t\t}, query.WithCollectionPaginationPairPrefix[sdk.AccAddress, sdk.ValAddress](delAddr),\n\t)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryDelegatorValidatorsResponse{Validators: validators.Validators, Pagination: pageRes}, nil\n}", "func SetValidate(v *validator.Validate) {\n\tvalidate = v\n}", "func (k Keeper) MinValidators(ctx sdk.Context) (res uint32) {\n\tk.paramspace.Get(ctx, types.KeyMinValidators, &res)\n\treturn\n}", "func (o *CmdObservations) ApplyWrites(p *memory.Pool) {\n\tif o != nil {\n\t\tfor _, w := range o.Writes {\n\t\t\tp.Write(w.Range.Base, memory.Resource(w.ID, w.Range.Size))\n\t\t}\n\t}\n}", "func (k Keeper) IterateBondedValidatorsByPower(ctx sdk.Context,\n\tfn func(index int64, validator exported.ValidatorI) (stop bool)) {\n\tk.stakingKeeper.IterateBondedValidatorsByPower(ctx, fn)\n}" ]
[ "0.72786766", "0.5906981", "0.5879324", "0.58167946", "0.56755745", "0.5671124", "0.5660429", "0.5636795", "0.55855256", "0.557589", "0.5555675", "0.5398646", "0.5363388", "0.5340318", "0.51216114", "0.5061059", "0.5057237", "0.5056569", "0.5046799", "0.50461566", "0.4970463", "0.49370685", "0.49213904", "0.4911109", "0.49065548", "0.4904036", "0.48905665", "0.48824805", "0.48245895", "0.48109308", "0.4770376", "0.4734084", "0.4716458", "0.47017032", "0.46975136", "0.4672824", "0.46673232", "0.46487635", "0.4627127", "0.4623807", "0.4620503", "0.4605442", "0.4585084", "0.4581568", "0.45793813", "0.45722675", "0.4548816", "0.45427403", "0.4538444", "0.45313728", "0.45193106", "0.45151603", "0.45033985", "0.44926667", "0.44909823", "0.44816118", "0.44773722", "0.4476679", "0.4472791", "0.4471498", "0.4462662", "0.44426224", "0.4427915", "0.44097027", "0.44043964", "0.43943205", "0.43902242", "0.43859947", "0.43766472", "0.43755692", "0.43722695", "0.43575972", "0.43574336", "0.43574244", "0.4357035", "0.4355246", "0.43533367", "0.43423685", "0.43418512", "0.43418345", "0.43347812", "0.43261963", "0.432555", "0.43242127", "0.43233165", "0.43225804", "0.43138474", "0.42960757", "0.42941305", "0.42901355", "0.42829803", "0.42827246", "0.42790407", "0.4278429", "0.42754316", "0.42569876", "0.42556182", "0.42534572", "0.42526117", "0.4250108" ]
0.6655839
1
syncGauge displays the syncing status in the syncWidget Exits when the context expires.
func syncGauge(ctx context.Context, g *gauge.Gauge, blockHeight int64) { var progress int64 = 0 ticker := time.NewTicker(1000 * time.Millisecond) defer ticker.Stop() for { select { case <-ticker.C: maxHeight := gjson.Get(getTendermintRPC("consensus_state"), "result.round_state.height/round/step").String() maxHeightOnly := strings.Split(maxHeight, "/")[0] n, err := strconv.ParseInt(maxHeightOnly, 10, 64) if err != nil { panic(err) } progress = (blockHeight / n) * 100 if err := g.Absolute(int(progress), 100); err != nil { panic(err) } case <-ctx.Done(): return } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func PrintSync() {\n\tklog.Infof(\"** stats collected **\")\n\tif GlobalStats != nil {\n\t\tPrint(PodList)\n\t\tPrint(IDList)\n\t\tPrint(BindingList)\n\t\tPrint(AssignedIDList)\n\t\tPrint(System)\n\t\tPrint(CacheSync)\n\n\t\tPrint(CloudGet)\n\t\tPrint(CloudUpdate)\n\t\tPrint(AssignedIDAdd)\n\t\tPrint(AssignedIDDel)\n\n\t\tPrintCount(TotalUpdateCalls)\n\t\tPrintCount(TotalGetCalls)\n\n\t\tPrintCount(TotalAssignedIDsCreated)\n\t\tPrintCount(TotalAssignedIDsUpdated)\n\t\tPrintCount(TotalAssignedIDsDeleted)\n\n\t\tPrint(FindAssignedIDCreate)\n\t\tPrint(FindAssignedIDDel)\n\n\t\tPrint(TotalCreateOrUpdate)\n\n\t\tPrint(Total)\n\t}\n\tklog.Infof(\"*********************\")\n}", "func (s *syncRatio) ReportSyncEvent() {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\ts.syncEvents++\n}", "func (d *specialDevice) sync() error {\n\tif d.toLimb != nil {\n\t\tif err := d.toLimb(d.instance); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif d.mqttClient != nil {\n\t\tif err := d.mqttClient.Publish(mqtt.PublishMessage{Payload: d.instance.Status}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\td.log.V(1).Info(\"Synced\")\n\treturn nil\n}", "func (g *Grabber) Sync(notify chan int) {\n\tgrowing := 1\n\tfor {\n\t\tselect {\n\t\tcase <-g.done:\n\t\t\treturn\n\t\tcase <-time.After(time.Duration(growing) * time.Hour):\n\t\t}\n\n\t\tsame, err := g.loadMetaMetrics()\n\t\tif !same {\n\t\t\tnotify <- g.index // send index to scheduler\n\t\t}\n\t\tif err != nil {\n\t\t\tgl.Log.Errorf(\"loadMetaMetrics error. err=%s grabber=%s\", err, g.Name)\n\t\t\tcontinue\n\t\t}\n\t\tif growing < 16 {\n\t\t\tgrowing = growing * 2\n\t\t}\n\t}\n}", "func (m *monitor) sync() error {\n\tnames, _, err := m.harvest(\"\")\n\tif len(names) > 0 {\n\t\tm.tip = names\n\t} else {\n\t\tm.tip = defaultTip\n\t}\n\treturn err\n}", "func PrintSync() {\n\tklog.Infof(\"** stats collected **\")\n\tif globalStats != nil {\n\t\tPrint(PodList)\n\t\tPrint(AzureIdentityList)\n\t\tPrint(AzureIdentityBindingList)\n\t\tPrint(AzureAssignedIdentityList)\n\t\tPrint(System)\n\t\tPrint(CacheSync)\n\n\t\tPrint(CloudGet)\n\t\tPrint(CloudPatch)\n\t\tPrint(CreateAzureAssignedIdentity)\n\t\tPrint(UpdateAzureAssignedIdentity)\n\t\tPrint(DeleteAzureAssignedIdentity)\n\n\t\tPrintCount(TotalPatchCalls)\n\t\tPrintCount(TotalGetCalls)\n\n\t\tPrintCount(TotalAzureAssignedIdentitiesCreated)\n\t\tPrintCount(TotalAzureAssignedIdentitiesUpdated)\n\t\tPrintCount(TotalAzureAssignedIdentitiesDeleted)\n\n\t\tPrint(FindAzureAssignedIdentitiesToCreate)\n\t\tPrint(FindAzureAssignedIdentitiesToDelete)\n\n\t\tPrint(TotalAzureAssignedIdentitiesCreateOrUpdate)\n\n\t\tPrint(Total)\n\t}\n\tklog.Infof(\"*********************\")\n}", "func (gc *GelfCore) Sync() error {\n\treturn nil\n}", "func (cbo *CBO) statusProgressing() error {\n desiredVersions := os.Getenv(\"OPERATOR_VERSION\")\n\n\t// TODO Making an assumption here that the Cluster Operator already exists\n\t// Check to see if we need to check if the ClusterOperator already exists\n\t// and create one if it doesn't\n currentVersions, err := cbo.getCurrentVersions()\n\n if err != nil {\n glog.Errorf(\"Error getting operator current versions: %v\", err)\n return err\n }\n var isProgressing osconfigv1.ConditionStatus\n\t\n co, err := cbo.getOrCreateClusterOperator()\n if err != nil {\n \tglog.Errorf(\"Failed to get or create Cluster Operator: %v\", err)\n \treturn err\n }\n\n var message string\n if !reflect.DeepEqual(desiredVersions, currentVersions) {\n glog.V(2).Info(\"Syncing status: progressing\")\n\t\t// TODO Use K8s event recorder to report this state\n isProgressing = osconfigv1.ConditionTrue\n } else {\n glog.V(2).Info(\"Syncing status: re-syncing\")\n\t\t// TODO Use K8s event recorder to report this state\n isProgressing = osconfigv1.ConditionFalse\n }\n\n conds := []osconfigv1.ClusterOperatorStatusCondition{\n newClusterOperatorStatusCondition(osconfigv1.OperatorProgressing, isProgressing, string(ReasonSyncing), message),\n operatorUpgradeable,\n }\n\n return cbo.updateStatus(co, conds)\n\treturn nil\n}", "func TestDaemon_SyncStatus(t *testing.T) {\n\td, start, clean, _, _, _ := mockDaemon(t)\n\tstart()\n\tdefer clean()\n\tw := newWait(t)\n\n\tctx := context.Background()\n\t// Perform a release\n\tid := updateImage(ctx, d, t)\n\n\t// Get the commit id\n\tstat := w.ForJobSucceeded(d, id)\n\n\t// Note: I can't test for an expected number of commits > 0\n\t// because I can't control how fast the sync loop updates the cluster\n\n\t// Once sync'ed to the cluster, it should empty\n\tw.ForSyncStatus(d, stat.Result.Revision, 0)\n}", "func (o *WlDisplay) Sync(callback *WlCallback) error {\n\tmsg, err := wire.NewMessage(o.ID(), 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = msg.Write(callback.ID()); err != nil {\n\t\treturn err\n\t}\n\n\tif err = o.Base.Conn.Write(msg); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (w *StatsWriter) FlushSync() error {\n\tif !w.syncMode {\n\t\treturn errors.New(\"not flushing; sync mode not enabled\")\n\t}\n\n\tdefer w.report()\n\tnotify := make(chan struct{}, 1)\n\tw.flushChan <- notify\n\t<-notify\n\treturn nil\n}", "func Sync(syncName string) {\n\ts := SyncServiceStatus(syncName)\n\tif s == \"running\" {\n\t\tfmt.Println(syncRunningErr)\n\t\treturn\n\t}\n\n\tfmt.Println()\n\tconsole.Println(\"⚡ Syncing files between your system and the Tokaido environment\", \"\")\n\tutils.StdoutStreamCmdDebug(\"unison\", syncName, \"-watch=false\")\n}", "func (c *Core) watchSyncFinished(onSyncFin <-chan golegs.SyncFinished) {\n\tfor syncFin := range onSyncFin {\n\t\tif _, err := c.PS.Get(context.Background(), syncFin.Cid); err != nil {\n\t\t\t// skip if data is not stored\n\t\t\tcontinue\n\t\t}\n\n\t\texist, _ := c.checkCidCached(syncFin.Cid)\n\t\tif exist {\n\t\t\t// seen cid before, skip\n\t\t\tcontinue\n\t\t}\n\n\t\tmetrics.Counter(context.Background(), metrics.ProviderNotificationCount, syncFin.PeerID.String(), 1)()\n\n\t\t// Persist the latest sync\n\t\terr := c.DS.Put(context.Background(), datastore.NewKey(SyncPrefix+syncFin.PeerID.String()), syncFin.Cid.Bytes())\n\t\tif err != nil {\n\t\t\tlogger.Errorw(\"Error persisting latest sync\", \"err\", err, \"peer\", syncFin.PeerID)\n\t\t\tcontinue\n\t\t}\n\t\tlogger.Debugw(\"Persisted latest sync\", \"peer\", syncFin.PeerID, \"cid\", syncFin.Cid)\n\t}\n\tclose(c.watchDone)\n}", "func (o ApplicationStatusOutput) Sync() ApplicationStatusSyncPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatus) *ApplicationStatusSync { return v.Sync }).(ApplicationStatusSyncPtrOutput)\n}", "func (c *Client) Gauge(stat string, value int, rate float64) error {\n\treturn c.send(stat, rate, \"%d|g\", value)\n}", "func (dcr *ExchangeWallet) SyncStatus() (bool, float32, error) {\n\treturn dcr.wallet.SyncStatus(dcr.ctx)\n}", "func (o ApplicationStatusPtrOutput) Sync() ApplicationStatusSyncPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationStatus) *ApplicationStatusSync {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Sync\n\t}).(ApplicationStatusSyncPtrOutput)\n}", "func (m *Mgr) Sync(ctx context.Context) error {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\treturn m.sync(ctx)\n}", "func Sync() {\n\tLogger.Sync()\n}", "func (g *GPIOControllerPCF8574T) sync() {\n\terr := g.bus.WriteByte(g.address, g.valuePinMask)\n\tif err != nil {\n\t\tfmt.Printf(\"Error syncing gpio controller: %v\\n\", err)\n\t}\n}", "func printSyncWith(sender string) {\n\tfmt.Println(\"IN SYNC WITH \" + sender)\n}", "func (p *blockPrefetcher) OverallSyncStatus() PrefetchProgress {\n\tp.overallSyncStatusLock.RLock()\n\tdefer p.overallSyncStatusLock.RUnlock()\n\treturn p.overallSyncStatus\n}", "func (api *PublicHostManagerDebugAPI) Syncing() bool {\n\treturn api.shm.b.Syncing()\n}", "func (m *MetaNode) Sync() {\n\tm.wg.Wait()\n}", "func BeginSync(st o.SyncType) {\n\n\tdbName := c.DBConfig.DBName.StockD1\n\tnames, _ := h.GetCollectionNames(dbName)\n\tcCount := len(names)\n\tvar start, end time.Time\n\tstart = time.Now()\n\tfmt.Println(\"Sync stock base information from database StockD1. SyncType is \", st.ToString())\n\tfmt.Println(\"Begin time: \", start.Format(\"2006-01-02 15:04:05\"))\n\tfor i, name := range names {\n\t\tIncrementSync(name, st)\n\t\tfmt.Printf(\"Stock code: %s (%d/%d) \\r\", name, i+1, cCount)\n\t}\n\tend = time.Now()\n\tfmt.Println(\"Synchronization Completed at \", end.Format(\"2006-01-02 15:04:05\"))\n\tfmt.Println(\"Duration: \", end.Sub(start).String())\n\tfmt.Println()\n}", "func (lb *Elb) Sync() {\n\tlb.syncCh <- 1\n}", "func (client *TcpBridgeClient) SyncStatistic(meta *SyncStatisticMeta) (*SyncStatisticResponseMeta, error) {\n frame, e := client.sendReceive(FRAME_OPERATION_SYNC_STATISTIC, STATE_VALIDATED, meta, 0, nil)\n if e != nil {\n return nil, e\n }\n var res = &SyncStatisticResponseMeta{}\n e1 := json.Unmarshal(frame.FrameMeta, res)\n if e1 != nil {\n return nil, e1\n }\n return res, nil\n}", "func (l *Logger) Sync() {\n\t_ = l.SugaredLogger.Sync()\n}", "func (o ApplicationStatusOperationStateOperationOutput) Sync() ApplicationStatusOperationStateOperationSyncPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatusOperationStateOperation) *ApplicationStatusOperationStateOperationSync {\n\t\treturn v.Sync\n\t}).(ApplicationStatusOperationStateOperationSyncPtrOutput)\n}", "func (dc *DatadogCollector) UpdateConcurrencyInUse(concurrencyInUse float64) {\n\t_ = dc.client.Gauge(dmConcurrencyInUse, 100*concurrencyInUse, dc.tags, 1.0)\n}", "func (h *HTTP) Gauge(stat string, value int64) error {\n\th.Lock()\n\th.json.SetP(value, stat)\n\th.Unlock()\n\treturn nil\n}", "func (s *Syncer) Sync() error {\n\treturn nil\n}", "func TaskSyncStatisticInfo(tracker *TrackerInstance) (bool, error) {\n\tclient := *tracker.client\n\tmeta := &bridgev2.SyncStatisticMeta{}\n\tresMeta, err := client.SyncStatistic(meta)\n\tif err != nil {\n\t\treturn true, err\n\t}\n\tif resMeta != nil {\n\t\tupdateStatistic(tracker.ConnStr, resMeta.FileCount, resMeta.Statistic)\n\t\treturn false, nil\n\t} else {\n\t\treturn true, errors.New(\"receive empty response from server\")\n\t}\n}", "func synchronize(kvsync kvs.Sync) {\n\tc := context.Background()\n\n\t// This is the object to be synchronized\n\tdb := Data{}\n\n\t// Creating a sync object from the provided lower-level kv sync.\n\ts := sync.Sync{\n\t\tSync: kvsync,\n\t}\n\n\t// Registering callback for given object with given format\n\ts.SyncObject(sync.SyncObject{\n\t\tCallback: SyncCallback,\n\t\tObject: &db,\n\t\tFormat: \"/db/stored/here/\",\n\t})\n\n\t// Time wheel to trigger callback notification for successive events\n\tfor {\n\t\te := s.Next(c)\n\t\tif e != nil {\n\t\t\tpanic(e)\n\t\t}\n\t\tif stopTimeWheel {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfmt.Printf(\"Final DB state %v\\n\\n\", &db)\n}", "func (dcr *ExchangeWallet) SyncStatus() (bool, float32, error) {\n\tchainInfo, err := dcr.node.GetBlockChainInfo(dcr.ctx)\n\tif err != nil {\n\t\treturn false, 0, fmt.Errorf(\"getblockchaininfo error: %w\", translateRPCCancelErr(err))\n\t}\n\ttoGo := chainInfo.Headers - chainInfo.Blocks\n\tif chainInfo.InitialBlockDownload || toGo > 1 {\n\t\togTip := atomic.LoadInt64(&dcr.tipAtConnect)\n\t\ttotalToSync := chainInfo.Headers - ogTip\n\t\tvar progress float32 = 1\n\t\tif totalToSync > 0 {\n\t\t\tprogress = 1 - (float32(toGo) / float32(totalToSync))\n\t\t}\n\t\treturn false, progress, nil\n\t}\n\treturn true, 1, nil\n}", "func (g *GardenerAPI) Status(w http.ResponseWriter) {\n\tfmt.Fprintf(w, \"Gardener API: %s\\n\", g.trackerBase.String())\n}", "func GetSync() Sync {\n\treturn Configurations.Sync\n}", "func (s *CheckpointManager) Sync() {\n\t_, _, err := s.flushCtrl.Flush(s.indexID, FlushModeForceLocal)\n\tif err != nil {\n\t\tlogutil.BgLogger().Warn(\"flush local engine failed\", zap.String(\"category\", \"ddl-ingest\"), zap.Error(err))\n\t}\n\ts.mu.Lock()\n\ts.progressLocalSyncMinKey()\n\ts.mu.Unlock()\n\twg := sync.WaitGroup{}\n\twg.Add(1)\n\ts.updaterCh <- &wg\n\twg.Wait()\n}", "func (c *PumpsClient) syncLocalPumpStatus(_ context.Context) {\n\tnodeStatus := &node.Status{\n\t\tNodeID: localPump,\n\t\tAddr: c.binlogSocket,\n\t\tIsAlive: true,\n\t\tState: node.Online,\n\t}\n\tc.addPump(NewPumpStatus(nodeStatus, c.Security), true)\n}", "func (ec *Client) SyncProgress(ctx context.Context) (*siotchain.SyncProgress, error) {\n\tvar raw json.RawMessage\n\tif err := ec.c.CallContext(ctx, &raw, \"siot_syncing\"); err != nil {\n\t\treturn nil, err\n\t}\n\t// Handle the possible response types\n\tvar syncing bool\n\tif err := json.Unmarshal(raw, &syncing); err == nil {\n\t\treturn nil, nil // Not syncing (always false)\n\t}\n\tvar progress *rpcProgress\n\tif err := json.Unmarshal(raw, &progress); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &siotchain.SyncProgress{\n\t\tStartingBlock: progress.StartingBlock.Uint64(),\n\t\tCurrentBlock: progress.CurrentBlock.Uint64(),\n\t\tHighestBlock: progress.HighestBlock.Uint64(),\n\t\tPulledStates: progress.PulledStates.Uint64(),\n\t\tKnownStates: progress.KnownStates.Uint64(),\n\t}, nil\n}", "func (m *KubedgeBaseManager) BaseSync(ctx context.Context) error {\n\tm.DeployedSubResourceList = av1.NewSubResourceList(m.PhaseNamespace, m.PhaseName)\n\n\trendered, alreadyDeployed, err := m.internalSync(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm.DeployedSubResourceList = alreadyDeployed\n\tif len(rendered.GetDependentResources()) != len(alreadyDeployed.GetDependentResources()) {\n\t\tm.IsInstalledFlag = false\n\t\tm.IsUpdateRequiredFlag = false\n\t} else {\n\t\tm.IsInstalledFlag = true\n\t\tm.IsUpdateRequiredFlag = false\n\t}\n\n\treturn nil\n}", "func Sync() error {\n\treturn GetZapLogger().Sync()\n}", "func (s *Syncer) Sync() error {\n\ts.called = true\n\treturn s.err\n}", "func (h *Hub) Status(ctx context.Context, _ *pb.HubStatusRequest) (*pb.HubStatusReply, error) {\n\th.mu.Lock()\n\tminersCount := len(h.miners)\n\th.mu.Unlock()\n\n\tuptime := time.Now().Unix() - h.startTime.Unix()\n\n\treply := &pb.HubStatusReply{\n\t\tMinerCount: uint64(minersCount),\n\t\tUptime: uint64(uptime),\n\t\tPlatform: util.GetPlatformName(),\n\t\tVersion: h.version,\n\t\tEthAddr: hex.EncodeToString(crypto.FromECDSA(h.ethKey)),\n\t}\n\n\treturn reply, nil\n}", "func (s *Synchronizer) HealthCheck() bool {\n\ts.l.Lock()\n\tdefer s.l.Unlock()\n\n\tsyncHearthbeat := s.syncHeartbeat\n\tif syncHearthbeat.IsZero() {\n\t\tsyncHearthbeat = s.startedAt\n\t}\n\n\tif s.now().Before(s.disabledUntil) {\n\t\t// synchronization is still disabled, don't check syncHearthbeat\n\t\treturn true\n\t}\n\n\tif s.now().Sub(syncHearthbeat) > time.Hour {\n\t\tlogger.Printf(\"Bleemeo API communication didn't run since %s. This should be a Glouton bug\", syncHearthbeat.Format(time.RFC3339))\n\n\t\tif s.now().Sub(syncHearthbeat) > 6*time.Hour {\n\t\t\ts.heartbeatConsecutiveError++\n\n\t\t\tif s.heartbeatConsecutiveError >= 3 {\n\t\t\t\tlogger.Printf(\"Bleemeo API communication is broken. Glouton seems unhealthy, killing myself\")\n\n\t\t\t\t// We don't know how big the buffer needs to be to collect\n\t\t\t\t// all the goroutines. Use 2MB buffer which hopefully is enough\n\t\t\t\tbuffer := make([]byte, 1<<21)\n\n\t\t\t\truntime.Stack(buffer, true)\n\t\t\t\tlogger.Printf(\"%s\", string(buffer))\n\t\t\t\tpanic(\"Glouton seems unhealthy (last API request too old), killing myself\")\n\t\t\t}\n\t\t}\n\t} else {\n\t\ts.heartbeatConsecutiveError = 0\n\t}\n\n\treturn true\n}", "func (c *LoggerClient) Gauge(name string, value float64) {\n\tc.print(\"Gauge\", name, value, value)\n}", "func Sync() {\n\tlog.RLock()\n\tdefer log.RUnlock()\n\tlog.active.Sync()\n}", "func Refresh() {\n\tgo func() {\n\t\tif e := SyncedRefresh(); e != nil {\n\t\t\tlog.Println(e.Error())\n\t\t}\n\t}()\n}", "func (s GetServiceInstanceSyncStatusOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (ec *Client) SyncProgress(ctx context.Context) (*ethereum.SyncProgress, error) {\n\tec.Send(generalCost)\n\treturn ec.c.SyncProgress(ctx)\n}", "func isComponentStatusSynced(componentStatus string) bool {\n\treturn componentStatus == \"Synced\"\n}", "func (s *syncRatio) ReportFailedSync() {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\ts.failedSyncs++\n}", "func (o ApplicationStatusSyncPtrOutput) Status() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationStatusSync) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Status\n\t}).(pulumi.StringPtrOutput)\n}", "func (s Broker) Gauge(name string, value int) {\n\ts.Send(&gauge{Name: name, Value: value})\n}", "func (c *managedClusterLeaseController) sync(ctx context.Context, syncCtx factory.SyncContext) error {\n\tcluster, err := c.hubClusterLister.Get(c.clusterName)\n\t// unable to get managed cluster, make sure there is no lease update routine.\n\tif err != nil {\n\t\tc.leaseUpdater.stop()\n\t\treturn fmt.Errorf(\"unable to get managed cluster %q from hub: %w\", c.clusterName, err)\n\t}\n\n\t// the managed cluster is not accepted, make sure there is no lease update routine.\n\tif !meta.IsStatusConditionTrue(cluster.Status.Conditions, clusterv1.ManagedClusterConditionHubAccepted) {\n\t\tc.leaseUpdater.stop()\n\t\treturn nil\n\t}\n\n\tobservedLeaseDurationSeconds := cluster.Spec.LeaseDurationSeconds\n\t// for backward compatible, release-2.1 has mutating admission webhook to mutate this field,\n\t// but release-2.0 does not have the mutating admission webhook\n\tif observedLeaseDurationSeconds == 0 {\n\t\tobservedLeaseDurationSeconds = 60\n\t}\n\n\t// if lease duration is changed, start a new lease update routine.\n\tif c.lastLeaseDurationSeconds != observedLeaseDurationSeconds {\n\t\tc.lastLeaseDurationSeconds = observedLeaseDurationSeconds\n\t\tc.leaseUpdater.stop()\n\t\tc.leaseUpdater.start(ctx, time.Duration(c.lastLeaseDurationSeconds)*time.Second)\n\t}\n\n\treturn nil\n}", "func (_OracleMgr *OracleMgrCallerSession) SyncFrequency() (*big.Int, error) {\n\treturn _OracleMgr.Contract.SyncFrequency(&_OracleMgr.CallOpts)\n}", "func (o ApplicationStatusOperationStateOperationPtrOutput) Sync() ApplicationStatusOperationStateOperationSyncPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationStatusOperationStateOperation) *ApplicationStatusOperationStateOperationSync {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Sync\n\t}).(ApplicationStatusOperationStateOperationSyncPtrOutput)\n}", "func (a *Agent) StartSync() {\n\tgo a.sync.Run()\n\ta.logger.Printf(\"[INFO] agent: started state syncer\")\n}", "func (_OracleMgr *OracleMgrSession) SyncFrequency() (*big.Int, error) {\n\treturn _OracleMgr.Contract.SyncFrequency(&_OracleMgr.CallOpts)\n}", "func (vs *ViewServer) tick(){\n\t// Your code here.\n\tvs.mu.Lock()\n\tnow := time.Now()\n\ttimeWindow := DeadPings * PingInterval\n\n\t// check if we can get the primary server\n\tif now.Sub(vs.pingTime[vs.currentView.Primary]) >= timeWindow && vs.primaryACK == true{\n\t\t// primary already ACK currentView -> update view using backup\n\t\tupdate(vs, vs.currentView.Backup, vs.idleServer)\n\t}\n\n\t// check recent pings from backup server\n\tif now.Sub(vs.pingTime[vs.currentView.Backup]) >= timeWindow && vs.backupACK == true{\n\t\t// check if there's an idle server\n\t\tif vs.idleServer != \"\"{\n\t\t\t// use idle server as backup\n\t\t\tupdate(vs, vs.currentView.Primary, vs.idleServer)\n\t\t}\n\t}\n\n\t// check pings from idle server\n\tif now.Sub(vs.pingTime[vs.idleServer]) >= timeWindow{\n\t\tvs.idleServer = \"\"\n\t} else {\n\t\tif vs.primaryACK == true && vs.idleServer != \"\" && vs.currentView.Backup == \"\"{\n\t\t\t// no backup -> use idle server\n\t\t\tupdate(vs, vs.currentView.Primary, vs.idleServer)\n\t\t}\n\t}\n\n\tvs.mu.Unlock()\n}", "func casgstatus(gp *g, oldval, newval uint32) {\n\tif (oldval&_Gscan != 0) || (newval&_Gscan != 0) || oldval == newval {\n\t\tsystemstack(func() {\n\t\t\tprint(\"runtime: casgstatus: oldval=\", hex(oldval), \" newval=\", hex(newval), \"\\n\")\n\t\t\tthrow(\"casgstatus: bad incoming values\")\n\t\t})\n\t}\n\n\tif oldval == _Grunning && gp.gcscanvalid {\n\t\t// If oldvall == _Grunning, then the actual status must be\n\t\t// _Grunning or _Grunning|_Gscan; either way,\n\t\t// we own gp.gcscanvalid, so it's safe to read.\n\t\t// gp.gcscanvalid must not be true when we are running.\n\t\tsystemstack(func() {\n\t\t\tprint(\"runtime: casgstatus \", hex(oldval), \"->\", hex(newval), \" gp.status=\", hex(gp.atomicstatus), \" gp.gcscanvalid=true\\n\")\n\t\t\tthrow(\"casgstatus\")\n\t\t})\n\t}\n\n\t// See https://golang.org/cl/21503 for justification of the yield delay.\n\tconst yieldDelay = 5 * 1000\n\tvar nextYield int64\n\n\t// loop if gp->atomicstatus is in a scan state giving\n\t// GC time to finish and change the state to oldval.\n\tfor i := 0; !atomic.Cas(&gp.atomicstatus, oldval, newval); i++ {\n\t\tif oldval == _Gwaiting && gp.atomicstatus == _Grunnable {\n\t\t\tthrow(\"casgstatus: waiting for Gwaiting but is Grunnable\")\n\t\t}\n\t\t// Help GC if needed.\n\t\t// if gp.preemptscan && !gp.gcworkdone && (oldval == _Grunning || oldval == _Gsyscall) {\n\t\t// \tgp.preemptscan = false\n\t\t// \tsystemstack(func() {\n\t\t// \t\tgcphasework(gp)\n\t\t// \t})\n\t\t// }\n\t\t// But meanwhile just yield.\n\t\tif i == 0 {\n\t\t\tnextYield = nanotime() + yieldDelay\n\t\t}\n\t\tif nanotime() < nextYield {\n\t\t\tfor x := 0; x < 10 && gp.atomicstatus != oldval; x++ {\n\t\t\t\tprocyield(1)\n\t\t\t}\n\t\t} else {\n\t\t\tosyield()\n\t\t\tnextYield = nanotime() + yieldDelay/2\n\t\t}\n\t}\n\tif newval == _Grunning {\n\t\tgp.gcscanvalid = false\n\t}\n}", "func Sync() error {\n\treturn logger.Sync()\n}", "func (s *DataNode) Sync() {\n\ts.control.Sync()\n}", "func (m *RdmaDevPlugin) NotifyRegistrationStatus(ctx context.Context, regstat *registerapi.RegistrationStatus) (*registerapi.RegistrationStatusResponse, error) {\n\tif regstat.PluginRegistered {\n\t\tlog.Printf(\"%s gets registered successfully at Kubelet \\n\", m.socketName)\n\t} else {\n\t\tlog.Printf(\"%s failed to be registered at Kubelet: %v; restarting.\\n\", m.socketName, regstat.Error)\n\t\tm.server.Stop()\n\t}\n\treturn &registerapi.RegistrationStatusResponse{}, nil\n}", "func (vs *ViewServer) tick() {\n\n\t// Your code here.\n\n\tvs.mu.Lock()\n\tif vs.currentView.Primary != \"\" {\n\t\tvs.primaryPingout++\n\t}\n\tif vs.currentView.Backup != \"\" {\n\t\tvs.backupPingout++\n\t}\n\tvs.mu.Unlock()\n\n\tif vs.primaryPingout >= DeadPings {\n\t\t//log.Printf(\"Set primaryCrash\\n\")\n\t\tvs.primaryCrash = true\n\t} else if vs.backupPingout >= DeadPings {\n\t\t//log.Printf(\"Set Backup Crash\\n\")\n\t\tvs.backupCrash = true\n\t}\n}", "func (l *SentryLogger) Sync() error {\n\tif l.sentry != nil {\n\t\tl.sentry.Wait()\n\t}\n\n\treturn l.SugaredLogger.Sync()\n}", "func (o ApplicationStatusSyncOutput) Status() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ApplicationStatusSync) string { return v.Status }).(pulumi.StringOutput)\n}", "func (c *DeploymentController) SyncStatus(cd *flaggerv1.Canary, status flaggerv1.CanaryStatus) error {\n\tdep, err := c.kubeClient.AppsV1().Deployments(cd.Namespace).Get(cd.Spec.TargetRef.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn fmt.Errorf(\"deployment %s.%s not found\", cd.Spec.TargetRef.Name, cd.Namespace)\n\t\t}\n\t\treturn ex.Wrap(err, \"SyncStatus deployment query error\")\n\t}\n\n\tconfigs, err := c.configTracker.GetConfigRefs(cd)\n\tif err != nil {\n\t\treturn ex.Wrap(err, \"SyncStatus configs query error\")\n\t}\n\n\treturn syncCanaryStatus(c.flaggerClient, cd, status, dep.Spec.Template, func(cdCopy *flaggerv1.Canary) {\n\t\tcdCopy.Status.TrackedConfigs = configs\n\t})\n}", "func (core *coreService) SyncingProgress() (uint64, uint64, uint64) {\n\tstartingHeight, currentHeight, targetHeight, _ := core.bs.SyncStatus()\n\treturn startingHeight, currentHeight, targetHeight\n}", "func (c *Eventer) sync() {\n\tc.syncc <- struct{}{}\n\t<-c.syncDonec\n}", "func (_OracleMgr *OracleMgrCaller) SyncFrequency(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _OracleMgr.contract.Call(opts, out, \"syncFrequency\")\n\treturn *ret0, err\n}", "func FetchSyncing(conn *grpc.ClientConn) (bool, error) {\n\tif conn == nil {\n\t\treturn false, errors.New(\"no connection to beacon node\")\n\t}\n\tclient := ethpb.NewNodeClient(conn)\n\tctx, cancel := context.WithTimeout(context.Background(), viper.GetDuration(\"timeout\"))\n\tdefer cancel()\n\tsyncStatus, err := client.GetSyncStatus(ctx, &types.Empty{})\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn syncStatus.Syncing, nil\n}", "func (c *CmdHandle) CmdHealthMonitor(){\n// log.Println(\"CmdHealthMonitor: Start\")\n\n //Check if any of the commands have been running for ever avg timout time 20s\n// log.Println(\"Monitored Cmd Processing Health\")\n\n // Check the system load if less send more commands for processing\n c.CmdProcessPendingCommands()\n\n// log.Println(\"CmdHealthMonitor: Complete\")\n}", "func (pb *PBServer) tick() {\n view, ok := pb.vs.Get()\n now := time.Now()\n if !ok {\n if now.Sub(pb.lastGetViewTime) > viewservice.PingInterval * viewservice.DeadPings / 2 {\n pb.staleView = true\n }\n return\n } else {\n pb.lastGetViewTime = now\n pb.staleView = false\n }\n\n // fmt.Printf(\"viewnum: %d, me: %s, p: %s, b: %s\\n\", view.Viewnum, pb.me, view.Primary, view.Backup)\n pb.mu.Lock()\n defer pb.mu.Unlock()\n update_view := true\n if view.Primary == pb.me {\n if view.Backup == \"\" {\n update_view = true\n } else if view.Backup != pb.view.Backup {\n snapshot := SnapshotArgs{pb.values}\n var reply SnapshotReply\n ok := call(view.Backup, \"PBServer.SendSnapshot\", &snapshot, &reply)\n if !ok {\n fmt.Printf(\"Failed to call PBServer.SendSnapshot on backup: '%s'\\n\", view.Backup)\n update_view = false\n } else if reply.Err == OK {\n fmt.Printf(\"Successfully send snapshot to backup: '%s'\\n\", view.Backup)\n update_view = true\n } else {\n fmt.Printf(\"Failed to send snapshot to backup '%s': %s\\n\", view.Backup, reply.Err)\n update_view = false\n }\n }\n }\n // if view.Backup == pb.Me {\n // if pb.view.Backup != pb.Me {\n // \n // }\n // }\n if update_view {\n pb.view = view\n }\n pb.vs.Ping(pb.view.Viewnum)\n}", "func Sync(ctx context.Context, config *tsbridge.Config, metrics *tsbridge.Metrics) error {\n\tstore, err := LoadStorageEngine(ctx, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer store.Close()\n\n\tmetricCfg, err := tsbridge.NewMetricConfig(ctx, config, store)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif errs := metrics.UpdateAll(ctx, metricCfg, config.Options.UpdateParallelism); errs != nil {\n\t\tmsg := strings.Join(errs, \"; \")\n\t\treturn errors.New(msg)\n\t}\n\treturn nil\n}", "func (mp *MockProducer) HandleSync(context.Context, *pkg.Job) {\n\tmp.SyncSignal <- struct{}{}\n}", "func (l *Logger) Sync() {\n\tl.zap.Sync()\n}", "func (lp *ChargerHandler) SyncEnabled() {\n\tenabled, err := lp.charger.Enabled()\n\tif err == nil && enabled != lp.enabled {\n\t\tlp.log.DEBUG.Printf(\"sync enabled state to %s\", status[lp.enabled])\n\t\terr = lp.charger.Enable(lp.enabled)\n\t}\n\n\tif err != nil {\n\t\tlp.log.ERROR.Printf(\"charge controller error: %v\", err)\n\t}\n}", "func (w *rpcWallet) SyncStatus(ctx context.Context) (bool, float32, error) {\n\tsyncStatus := new(walletjson.SyncStatusResult)\n\terr := w.rpcClientRawRequest(ctx, methodSyncStatus, nil, syncStatus)\n\tif err != nil {\n\t\treturn false, 0, fmt.Errorf(\"rawrequest error: %w\", err)\n\t}\n\tready := syncStatus.Synced && !syncStatus.InitialBlockDownload\n\tif !ready {\n\t\treturn false, syncStatus.HeadersFetchProgress, nil\n\t}\n\t// It looks like we are ready based on syncstatus, but that may just be\n\t// comparing wallet height to known chain height. Now check peers.\n\tnumPeers, err := w.PeerCount(ctx)\n\tif err != nil {\n\t\treturn false, 0, err\n\t}\n\treturn numPeers > 0, syncStatus.HeadersFetchProgress, nil\n}", "func Sync(ctx context.Context, config *tsbridge.Config) error {\n\tstore, err := LoadStorageEngine(ctx, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer store.Close()\n\n\tmetrics, err := tsbridge.NewMetricConfig(ctx, config, store)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar errSync []error\n\n\tsdClientOnce.Do(func() {\n\t\tsdClient, err = stackdriver.NewAdapter(ctx, config.Options.SDLookBackInterval)\n\t\tif err != nil {\n\t\t\terrSync = append(errSync, fmt.Errorf(\"unable to initialize stackdriver adapter: %v\", err))\n\t\t}\n\t})\n\n\tstatsCollectorOnce.Do(func() {\n\t\tstatsCollector, err = tsbridge.NewCollector(ctx, config.Options.SDInternalMetricsProject, config.Options.MonitoringBackends)\n\t\tif err != nil {\n\t\t\terrSync = append(errSync, fmt.Errorf(\"unable to initialize stats collector: %v\", err))\n\t\t}\n\t})\n\n\t// Process errors from Once.Do blocks since we cannot return in those\n\tif len(errSync) > 0 {\n\t\treturn fmt.Errorf(\"errors occured during sync init: %v\", errSync)\n\t}\n\n\tif errs := tsbridge.UpdateAllMetrics(ctx, metrics, sdClient, config.Options.UpdateParallelism, statsCollector); errs != nil {\n\t\tmsg := strings.Join(errs, \"; \")\n\t\treturn errors.New(msg)\n\t}\n\treturn nil\n}", "func displayDownloadProgress(resp *grab.Response) {\n\n\tprinter := message.NewPrinter(message.MatchLanguage(\"en\"))\n\t// Begin UI loop\n\ttimer := time.NewTicker(5 * time.Second)\n\tdefer timer.Stop()\n\tpercentageDownloaded := 0\n\tfor {\n\t\tselect {\n\t\tcase <-timer.C:\n\t\t\tcurrentPercentageDownloaded := int(100 * resp.Progress())\n\t\t\tif currentPercentageDownloaded > percentageDownloaded {\n\t\t\t\tpercentageDownloaded = currentPercentageDownloaded\n\t\t\t\tlog.Info(printer.Sprintf(\"FastSync: Downloaded %.0fMB of %.0fMB (%d%%)\",\n\t\t\t\t\tfloat64(resp.BytesComplete())*0.000001,\n\t\t\t\t\tfloat64(resp.Size)*0.000001,\n\t\t\t\t\tpercentageDownloaded))\n\t\t\t}\n\n\t\tcase <-resp.Done:\n\t\t\t// Download is complete\n\t\t\treturn\n\t\t}\n\t}\n}", "func (l *LogWriter) Sync() (err error) {\n\treturn\n}", "func (rm *ResourceQuotaManager) syncResourceQuota(quota api.ResourceQuota) (err error) {\n\n\t// dirty tracks if the usage status differs from the previous sync,\n\t// if so, we send a new usage with latest status\n\t// if this is our first sync, it will be dirty by default, since we need track usage\n\tdirty := quota.Status.Hard == nil || quota.Status.Used == nil\n\n\t// Create a usage object that is based on the quota resource version\n\tusage := api.ResourceQuotaUsage{\n\t\tObjectMeta: api.ObjectMeta{\n\t\t\tName: quota.Name,\n\t\t\tNamespace: quota.Namespace,\n\t\t\tResourceVersion: quota.ResourceVersion},\n\t\tStatus: api.ResourceQuotaStatus{\n\t\t\tHard: api.ResourceList{},\n\t\t\tUsed: api.ResourceList{},\n\t\t},\n\t}\n\t// populate the usage with the current observed hard/used limits\n\tusage.Status.Hard = quota.Spec.Hard\n\tusage.Status.Used = quota.Status.Used\n\n\tset := map[api.ResourceName]bool{}\n\tfor k := range usage.Status.Hard {\n\t\tset[k] = true\n\t}\n\n\tpods := &api.PodList{}\n\tif set[api.ResourcePods] || set[api.ResourceMemory] || set[api.ResourceCPU] {\n\t\tpods, err = rm.kubeClient.Pods(usage.Namespace).List(labels.Everything())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// iterate over each resource, and update observation\n\tfor k := range usage.Status.Hard {\n\n\t\t// look if there is a used value, if none, we are definitely dirty\n\t\tprevQuantity, found := usage.Status.Used[k]\n\t\tif !found {\n\t\t\tdirty = true\n\t\t}\n\n\t\tvar value *resource.Quantity\n\n\t\tswitch k {\n\t\tcase api.ResourcePods:\n\t\t\tvalue = resource.NewQuantity(int64(len(pods.Items)), resource.DecimalSI)\n\t\tcase api.ResourceMemory:\n\t\t\tval := int64(0)\n\t\t\tfor i := range pods.Items {\n\t\t\t\tval = val + PodMemory(&pods.Items[i]).Value()\n\t\t\t}\n\t\t\tvalue = resource.NewQuantity(int64(val), resource.DecimalSI)\n\t\tcase api.ResourceCPU:\n\t\t\tval := int64(0)\n\t\t\tfor i := range pods.Items {\n\t\t\t\tval = val + PodCPU(&pods.Items[i]).MilliValue()\n\t\t\t}\n\t\t\tvalue = resource.NewMilliQuantity(int64(val), resource.DecimalSI)\n\t\tcase api.ResourceServices:\n\t\t\titems, err := rm.kubeClient.Services(usage.Namespace).List(labels.Everything())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tvalue = resource.NewQuantity(int64(len(items.Items)), resource.DecimalSI)\n\t\tcase api.ResourceReplicationControllers:\n\t\t\titems, err := rm.kubeClient.ReplicationControllers(usage.Namespace).List(labels.Everything())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tvalue = resource.NewQuantity(int64(len(items.Items)), resource.DecimalSI)\n\t\tcase api.ResourceQuotas:\n\t\t\titems, err := rm.kubeClient.ResourceQuotas(usage.Namespace).List(labels.Everything())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tvalue = resource.NewQuantity(int64(len(items.Items)), resource.DecimalSI)\n\t\t}\n\n\t\t// ignore fields we do not understand (assume another controller is tracking it)\n\t\tif value != nil {\n\t\t\t// see if the value has changed\n\t\t\tdirty = dirty || (value.Value() != prevQuantity.Value())\n\t\t\t// just update the value\n\t\t\tusage.Status.Used[k] = *value\n\t\t}\n\t}\n\n\t// update the usage only if it changed\n\tif dirty {\n\t\treturn rm.kubeClient.ResourceQuotaUsages(usage.Namespace).Create(&usage)\n\t}\n\treturn nil\n}", "func MONITOR() { ctx.MONITOR() }", "func (g *Gateway) Sync() {\n\tg.lock.RLock()\n\tdefer g.lock.RUnlock()\n\n\tif g.server == nil || g.info.Role != db.RaftVoter {\n\t\treturn\n\t}\n\n\tclient, err := g.getClient()\n\tif err != nil {\n\t\tlogger.Warnf(\"Failed to get client: %v\", err)\n\t\treturn\n\t}\n\n\tdefer func() { _ = client.Close() }()\n\n\tfiles, err := client.Dump(context.Background(), \"db.bin\")\n\tif err != nil {\n\t\t// Just log a warning, since this is not fatal.\n\t\tlogger.Warnf(\"Failed get database dump: %v\", err)\n\t\treturn\n\t}\n\n\tdir := filepath.Join(g.db.Dir(), \"global\")\n\tfor _, file := range files {\n\t\tpath := filepath.Join(dir, file.Name)\n\t\terr := os.WriteFile(path, file.Data, 0600)\n\t\tif err != nil {\n\t\t\tlogger.Warnf(\"Failed to dump database file %s: %v\", file.Name, err)\n\t\t}\n\t}\n}", "func Sync() error {\n\treturn conf.Sync()\n}", "func (mb *MetricsBuilder) RecordActiveDirectoryDsReplicationSyncObjectPendingDataPoint(ts pcommon.Timestamp, val int64) {\n\tmb.metricActiveDirectoryDsReplicationSyncObjectPending.recordDataPoint(mb.startTime, ts, val)\n}", "func (c *sentryCore) Sync() error {\n\tc.client.Flush(c.flushTimeout)\n\treturn nil\n}", "func (d *Daemon) doSync(logger log.Logger) (retErr error) {\n\tstarted := time.Now().UTC()\n\tdefer func() {\n\t\tsyncDuration.With(\n\t\t\tfluxmetrics.LabelSuccess, fmt.Sprint(retErr == nil),\n\t\t).Observe(time.Since(started).Seconds())\n\t}()\n\t// We don't care how long this takes overall, only about not\n\t// getting bogged down in certain operations, so use an\n\t// undeadlined context in general.\n\tctx := context.Background()\n\n\t// checkout a working clone so we can mess around with tags later\n\tvar working *git.Checkout\n\t{\n\t\tvar err error\n\t\tctx, cancel := context.WithTimeout(ctx, gitOpTimeout)\n\t\tdefer cancel()\n\t\tworking, err = d.Checkout.WorkingClone(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer working.Clean()\n\t}\n\n\t// TODO logging, metrics?\n\t// Get a map of all resources defined in the repo\n\tallResources, err := d.Manifests.LoadManifests(working.ManifestDir())\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"loading resources from repo\")\n\t}\n\n\t// TODO supply deletes argument from somewhere (command-line?)\n\tif err := fluxsync.Sync(d.Manifests, allResources, d.Cluster, false, logger); err != nil {\n\t\tlogger.Log(\"err\", err)\n\t\t// TODO(michael): we should distinguish between \"fully mostly\n\t\t// succeeded\" and \"failed utterly\", since we want to abandon\n\t\t// this and not move the tag (and send a SyncFail event\n\t\t// upstream?), if the latter. For now, it's presumed that any\n\t\t// error returned is at worst a minor, partial failure (e.g.,\n\t\t// a small number of resources failed to sync, for unimportant\n\t\t// reasons)\n\t}\n\n\t// update notes and emit events for applied commits\n\n\tvar initialSync bool\n\tvar commits []git.Commit\n\t{\n\t\tvar err error\n\t\tctx, cancel := context.WithTimeout(ctx, gitOpTimeout)\n\t\tcommits, err = working.CommitsBetween(ctx, working.SyncTag, \"HEAD\")\n\t\tif isUnknownRevision(err) {\n\t\t\t// No sync tag, grab all revisions\n\t\t\tinitialSync = true\n\t\t\tcommits, err = working.CommitsBefore(ctx, \"HEAD\")\n\t\t}\n\t\tcancel()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Figure out which service IDs changed in this release\n\tchangedResources := map[string]resource.Resource{}\n\n\tif initialSync {\n\t\t// no synctag, We are syncing everything from scratch\n\t\tchangedResources = allResources\n\t} else {\n\t\tctx, cancel := context.WithTimeout(ctx, gitOpTimeout)\n\t\tchangedFiles, err := working.ChangedFiles(ctx, working.SyncTag)\n\t\tif err == nil {\n\t\t\t// We had some changed files, we're syncing a diff\n\t\t\tchangedResources, err = d.Manifests.LoadManifests(changedFiles...)\n\t\t}\n\t\tcancel()\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"loading resources from repo\")\n\t\t}\n\t}\n\n\tserviceIDs := flux.ServiceIDSet{}\n\tfor _, r := range changedResources {\n\t\tserviceIDs.Add([]flux.ResourceID{r.ResourceID()})\n\t}\n\n\tvar notes map[string]struct{}\n\t{\n\t\tctx, cancel := context.WithTimeout(ctx, gitOpTimeout)\n\t\tnotes, err = working.NoteRevList(ctx)\n\t\tcancel()\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"loading notes from repo\")\n\t\t}\n\t}\n\n\t// Collect any events that come from notes attached to the commits\n\t// we just synced. While we're doing this, keep track of what\n\t// other things this sync includes e.g., releases and\n\t// autoreleases, that we're already posting as events, so upstream\n\t// can skip the sync event if it wants to.\n\tincludes := make(map[string]bool)\n\tif len(commits) > 0 {\n\t\tvar noteEvents []history.Event\n\n\t\t// Find notes in revisions.\n\t\tfor i := len(commits) - 1; i >= 0; i-- {\n\t\t\tif _, ok := notes[commits[i].Revision]; !ok {\n\t\t\t\tincludes[history.NoneOfTheAbove] = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tctx, cancel := context.WithTimeout(ctx, gitOpTimeout)\n\t\t\tn, err := working.GetNote(ctx, commits[i].Revision)\n\t\t\tcancel()\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"loading notes from repo\")\n\t\t\t}\n\t\t\tif n == nil {\n\t\t\t\tincludes[history.NoneOfTheAbove] = true\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// If this is the first sync, we should expect no notes,\n\t\t\t// since this is supposedly the first time we're seeing\n\t\t\t// the repo. But there are circumstances in which we can\n\t\t\t// nonetheless see notes -- if the tag was deleted from\n\t\t\t// the upstream repo, or if this accidentally has the same\n\t\t\t// notes ref as another daemon using the same repo (but a\n\t\t\t// different tag). Either way, we don't want to report any\n\t\t\t// notes on an initial sync, since they (most likely)\n\t\t\t// don't belong to us.\n\t\t\tif initialSync {\n\t\t\t\tlogger.Log(\"warning\", \"no notes expected on initial sync; this repo may be in use by another fluxd\")\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// Interpret some notes as events to send to the upstream\n\t\t\tswitch n.Spec.Type {\n\t\t\tcase update.Images:\n\t\t\t\tspec := n.Spec.Spec.(update.ReleaseSpec)\n\t\t\t\tnoteEvents = append(noteEvents, history.Event{\n\t\t\t\t\tServiceIDs: serviceIDs.ToSlice(),\n\t\t\t\t\tType: history.EventRelease,\n\t\t\t\t\tStartedAt: started,\n\t\t\t\t\tEndedAt: time.Now().UTC(),\n\t\t\t\t\tLogLevel: history.LogLevelInfo,\n\t\t\t\t\tMetadata: &history.ReleaseEventMetadata{\n\t\t\t\t\t\tReleaseEventCommon: history.ReleaseEventCommon{\n\t\t\t\t\t\t\tRevision: commits[i].Revision,\n\t\t\t\t\t\t\tResult: n.Result,\n\t\t\t\t\t\t\tError: n.Result.Error(),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tSpec: spec,\n\t\t\t\t\t\tCause: n.Spec.Cause,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\tincludes[history.EventRelease] = true\n\t\t\tcase update.Auto:\n\t\t\t\tspec := n.Spec.Spec.(update.Automated)\n\t\t\t\tnoteEvents = append(noteEvents, history.Event{\n\t\t\t\t\tServiceIDs: serviceIDs.ToSlice(),\n\t\t\t\t\tType: history.EventAutoRelease,\n\t\t\t\t\tStartedAt: started,\n\t\t\t\t\tEndedAt: time.Now().UTC(),\n\t\t\t\t\tLogLevel: history.LogLevelInfo,\n\t\t\t\t\tMetadata: &history.AutoReleaseEventMetadata{\n\t\t\t\t\t\tReleaseEventCommon: history.ReleaseEventCommon{\n\t\t\t\t\t\t\tRevision: commits[i].Revision,\n\t\t\t\t\t\t\tResult: n.Result,\n\t\t\t\t\t\t\tError: n.Result.Error(),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tSpec: spec,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\tincludes[history.EventAutoRelease] = true\n\t\t\tcase update.Policy:\n\t\t\t\t// Use this to mean any change to policy\n\t\t\t\tincludes[history.EventUpdatePolicy] = true\n\t\t\tdefault:\n\t\t\t\t// Presume it's not something we're otherwise sending\n\t\t\t\t// as an event\n\t\t\t\tincludes[history.NoneOfTheAbove] = true\n\t\t\t}\n\t\t}\n\n\t\tcs := make([]history.Commit, len(commits))\n\t\tfor i, c := range commits {\n\t\t\tcs[i].Revision = c.Revision\n\t\t\tcs[i].Message = c.Message\n\t\t}\n\t\tif err = d.LogEvent(history.Event{\n\t\t\tServiceIDs: serviceIDs.ToSlice(),\n\t\t\tType: history.EventSync,\n\t\t\tStartedAt: started,\n\t\t\tEndedAt: started,\n\t\t\tLogLevel: history.LogLevelInfo,\n\t\t\tMetadata: &history.SyncEventMetadata{\n\t\t\t\tCommits: cs,\n\t\t\t\tInitialSync: initialSync,\n\t\t\t\tIncludes: includes,\n\t\t\t},\n\t\t}); err != nil {\n\t\t\tlogger.Log(\"err\", err)\n\t\t}\n\n\t\tfor _, event := range noteEvents {\n\t\t\tif err = d.LogEvent(event); err != nil {\n\t\t\t\tlogger.Log(\"err\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Move the tag and push it so we know how far we've gotten.\n\t{\n\t\tctx, cancel := context.WithTimeout(ctx, gitOpTimeout)\n\t\terr := working.MoveTagAndPush(ctx, \"HEAD\", \"Sync pointer\")\n\t\tcancel()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Pull the tag if it has changed\n\t{\n\t\tctx, cancel := context.WithTimeout(ctx, gitOpTimeout)\n\t\tif err := d.pullIfTagMoved(ctx, working, logger); err != nil {\n\t\t\tlogger.Log(\"err\", errors.Wrap(err, \"updating tag\"))\n\t\t}\n\t\tcancel()\n\t}\n\n\treturn nil\n}", "func (core *SysLogCore) Sync() error {\n\treturn nil\n}", "func (t *tracer) flushSync() {\n\tdone := make(chan struct{})\n\tt.flush <- done\n\t<-done\n}", "func (o ConnectedRegistryOutput) SyncMessageTtl() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ConnectedRegistry) pulumi.StringPtrOutput { return v.SyncMessageTtl }).(pulumi.StringPtrOutput)\n}", "func (s *NodeService) Syncing(ctx context.Context) (*GetNodeSyncing, *http.Response, error) {\n\tvar responseStruct *GetNodeSyncing\n\tresp, err := s.client.SendRequest(ctx, \"GET\", \"node/syncing\", nil, nil, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func (ct *Cointop) setRefreshStatus() {\n\tct.debuglog(\"setRefreshStatus()\")\n\tgo func() {\n\t\tct.loadingTicks(\"refreshing\", 900)\n\t\tct.RowChanged()\n\t}()\n}", "func syncRepo(c *gin.Context) {\n\tr := c.Param(\"repo\")\n\tif strings.Contains(r, \"not-found\") {\n\t\tmsg := fmt.Sprintf(\"Repo %s does not exist\", r)\n\n\t\tc.AbortWithStatusJSON(http.StatusNotFound, types.Error{Message: &msg})\n\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, fmt.Sprintf(\"Repo %s has been synced\", r))\n}", "func Heartbeat(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"Still\": \"Alive\",\n\t})\n}", "func Heartbeat(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"Still\": \"Alive\",\n\t})\n}", "func (pb *PBServer) tick() {\n\n newview, err := pb.vs.Ping(pb.view.Viewnum)\n if err != nil {\n fmt.Printf(\"view serivice unreachable!, error %s\\n\", err)\n return;\n }\n\n if pb.view.Viewnum != newview.Viewnum {\n fmt.Printf(\"view changed from \\n%s ==>\\n%s\\n\",pb.view, newview)\n if (pb.view.Primary == pb.me &&\n newview.Primary == pb.me &&\n pb.view.Backup != newview.Backup &&\n newview.Backup != \"\") {\n // backup changes and I'm still primary \n pb.view = newview\n fmt.Printf(\"new backup is %s\\n\", newview.Backup)\n pb.syncWithBackup()\n }\n }\n // only when pb is in the view, proceed to new view\n if pb.me == newview.Primary || pb.me == newview.Backup {\n pb.view = newview\n } else {\n fmt.Printf(\"I'm not in the view, keep trying\\n\")\n }\n}", "func Monitor(ctx *context.Context) {\n\tctx.Data[\"Title\"] = ctx.Tr(\"admin.monitor\")\n\tctx.Data[\"PageIsAdmin\"] = true\n\tctx.Data[\"PageIsAdminMonitor\"] = true\n\tctx.Data[\"Processes\"], ctx.Data[\"ProcessCount\"] = process.GetManager().Processes(false, true)\n\tctx.Data[\"Entries\"] = cron.ListTasks()\n\tctx.Data[\"Queues\"] = queue.GetManager().ManagedQueues()\n\n\tctx.HTML(http.StatusOK, tplMonitor)\n}", "func (gdb *Gdb) syncHisData() error {\n\tt := time.NewTicker(gdb.hisTimeDuration)\n\tfor {\n\t\tselect {\n\t\tcase st := <-t.C:\n\t\t\tif !gdb.isReloading {\n\t\t\t\tif err := gdb.innerSync(st); err != nil {\n\t\t\t\t\tfmt.Println(\"fatal error occurred while synchronizing history data:\" + err.Error())\n\t\t\t\t\ttime.Sleep(time.Minute)\n\t\t\t\t\tos.Exit(-1)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}" ]
[ "0.55687135", "0.5557459", "0.54056567", "0.5397949", "0.5235747", "0.5140872", "0.50922406", "0.5001546", "0.4993071", "0.4979371", "0.4961334", "0.49594572", "0.49523577", "0.49466237", "0.48886985", "0.48702312", "0.48170477", "0.4773439", "0.47626206", "0.47622085", "0.4761971", "0.47487074", "0.47304702", "0.47179028", "0.47160274", "0.47154614", "0.470912", "0.46950114", "0.46806884", "0.4655829", "0.46554616", "0.46544918", "0.46541747", "0.4651982", "0.46486393", "0.46482384", "0.46382847", "0.46369842", "0.462378", "0.46209836", "0.46190038", "0.46183807", "0.46133235", "0.46116325", "0.46027693", "0.46005753", "0.45947728", "0.45880693", "0.45868516", "0.45788455", "0.45695928", "0.45634302", "0.4553694", "0.45439744", "0.45425704", "0.45326096", "0.45306963", "0.4513237", "0.4512229", "0.4510467", "0.45093092", "0.45074847", "0.44973716", "0.44971734", "0.4493291", "0.44927412", "0.44923988", "0.4486517", "0.4484421", "0.4478308", "0.4476872", "0.44718087", "0.4470691", "0.44703797", "0.44618028", "0.4451817", "0.4451391", "0.44504404", "0.44451973", "0.44443724", "0.444148", "0.44362044", "0.44358894", "0.44296", "0.44288424", "0.44282547", "0.44279313", "0.44248074", "0.44183365", "0.44179282", "0.440624", "0.43895507", "0.43874583", "0.4381584", "0.43792808", "0.43779132", "0.43779132", "0.43775463", "0.43771774", "0.43769887" ]
0.6046038
0
byteCountDecimal calculates bytes integer to a human readable decimal number
func byteCountDecimal(b int64) string { const unit = 1000 if b < unit { return fmt.Sprintf("%d B", b) } div, exp := int64(unit), 0 for n := b / unit; n >= unit; n /= unit { div *= unit exp++ } return fmt.Sprintf("%.1f %cB", float64(b)/float64(div), "kMGTPE"[exp]) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func calcBytesLengthForDecimal(m int) int {\n\treturn (m / 9 * 4) + ((m%9)+1)/2\n}", "func ByteCount(b int64) string {\n\tconst unit = 1000\n\tif b < unit {\n\t\treturn fmt.Sprintf(\"%d B\", b)\n\t}\n\tdiv, exp := int64(unit), 0\n\tfor n := b / unit; n >= unit; n /= unit {\n\t\tdiv *= unit\n\t\texp++\n\t}\n\treturn fmt.Sprintf(\"%.1f %cB\",\n\t\tfloat64(b)/float64(div), \"kMGTPE\"[exp])\n}", "func decimalBinSize(precision, frac int) int {\n\ttrace_util_0.Count(_mydecimal_00000, 375)\n\tdigitsInt := precision - frac\n\twordsInt := digitsInt / digitsPerWord\n\twordsFrac := frac / digitsPerWord\n\txInt := digitsInt - wordsInt*digitsPerWord\n\txFrac := frac - wordsFrac*digitsPerWord\n\treturn wordsInt*wordSize + dig2bytes[xInt] + wordsFrac*wordSize + dig2bytes[xFrac]\n}", "func UINT64ByteCountDecimal(b uint64) string {\n\tconst unit = 1024\n\tif b < unit {\n\t\treturn fmt.Sprintf(\"%d B\", b)\n\t}\n\tdiv, exp := uint64(unit), 0\n\tfor n := b / unit; n >= unit; n /= unit {\n\t\tdiv *= unit\n\t\texp++\n\t}\n\treturn fmt.Sprintf(\"%.1f %cB\", float64(b)/float64(div), \"kMGTPE\"[exp])\n}", "func UINT32ByteCountDecimal(b uint32) string {\n\tconst unit = 1024\n\tif b < unit {\n\t\treturn fmt.Sprintf(\"%d B\", b)\n\t}\n\tdiv, exp := uint32(unit), 0\n\tfor n := b / unit; n >= unit; n /= unit {\n\t\tdiv *= unit\n\t\texp++\n\t}\n\treturn fmt.Sprintf(\"%.1f %cB\", float32(b)/float32(div), \"kMGTPE\"[exp])\n}", "func DecimalBinSize(precision, frac int) (int, error) {\n\tdigitsInt := precision - frac\n\twordsInt := digitsInt / digitsPerWord\n\twordsFrac := frac / digitsPerWord\n\txInt := digitsInt - wordsInt*digitsPerWord\n\txFrac := frac - wordsFrac*digitsPerWord\n\tif xInt < 0 || xInt >= len(dig2bytes) || xFrac < 0 || xFrac >= len(dig2bytes) {\n\t\treturn 0, ErrBadNumber\n\t}\n\treturn wordsInt*wordSize + dig2bytes[xInt] + wordsFrac*wordSize + dig2bytes[xFrac], nil\n}", "func ByteSize(bytes int) string {\n\tconst (\n\t\tBYTE = 1 << (10 * iota)\n\t\tKB\n\t\tMB\n\t\tGB\n\t\tTB\n\t\tPB\n\t\tEB\n\t)\n\tvar (\n\t\tu = \"\"\n\t\tv = float64(bytes)\n\t\tresult string\n\t)\n\tswitch {\n\tcase bytes >= EB:\n\t\tu = \"E\"\n\t\tv = v / EB\n\tcase bytes >= PB:\n\t\tu = \"P\"\n\t\tv = v / PB\n\tcase bytes >= TB:\n\t\tu = \"T\"\n\t\tv = v / TB\n\tcase bytes >= GB:\n\t\tu = \"G\"\n\t\tv = v / GB\n\tcase bytes >= MB:\n\t\tu = \"M\"\n\t\tv = v / MB\n\tcase bytes >= KB:\n\t\tu = \"K\"\n\t\tv = v / KB\n\tcase bytes >= BYTE:\n\t\tu = \"B\"\n\tcase bytes == 0:\n\t\treturn \"0B\"\n\t}\n\tresult = strconv.FormatFloat(v, 'f', 1, 64)\n\tresult = strings.TrimSuffix(result, \".0\")\n\treturn result + u\n}", "func BytesSize(bytes float64, format string, prec int) string {\n\n\tif bytes <= 0 {\n\t\treturn \"0\"\n\t}\n\n\t// Default format is decimal: MB, GB\n\tvalue := 1000.0\n\tresFormat := \"\"\n\n\t// Binary format: MiB, GiB\n\tif format == \"binary\" {\n\t\tvalue = 1024.0\n\t\tresFormat = \"i\"\n\t}\n\n\tif bytes < value {\n\t\tstrRes := strconv.FormatFloat(bytes, 'f', prec, 64)\n\t\treturn strings.TrimSuffix(strRes, \".0\") + \"B\"\n\t}\n\n\tdivider, exp := value, 0\n\tfor n := bytes / value; n >= value; n /= value {\n\t\tdivider *= value\n\t\texp++\n\t}\n\n\tstrRes := strconv.FormatFloat(bytes/divider, 'f', prec, 64)\n\tif prec == 0 {\n\t\t\tstrRes = strings.TrimSuffix(strRes, \".0\")\n\t}\n\n\treturn strRes + fmt.Sprintf(\"%c%sB\", \"KMGTPE\"[exp], resFormat)\n}", "func byteCountSI(b int64) string {\n\tconst unit = 1000\n\tif b < unit {\n\t\treturn fmt.Sprintf(\"%d B\", b)\n\t}\n\tdiv, exp := int64(unit), 0\n\tfor n := b / unit; n >= unit; n /= unit {\n\t\tdiv *= unit\n\t\texp++\n\t}\n\treturn fmt.Sprintf(\"%.1f %cB\",\n\t\tfloat64(b)/float64(div), \"kMGTPE\"[exp])\n}", "func byteCountIEC(b int64) string {\n\tconst unit = 1024\n\tif b < unit {\n\t\treturn fmt.Sprintf(\"%d B\", b)\n\t}\n\tdiv, exp := int64(unit), 0\n\tfor n := b / unit; n >= unit; n /= unit {\n\t\tdiv *= unit\n\t\texp++\n\t}\n\treturn fmt.Sprintf(\"%.1f %ciB\",\n\t\tfloat64(b)/float64(div), \"KMGTPE\"[exp])\n}", "func byteCountIEC(b int64) string {\n\tconst unit = 1024\n\tif b < unit {\n\t\treturn fmt.Sprintf(\"%d B\", b)\n\t}\n\tdiv, exp := int64(unit), 0\n\tfor n := b / unit; n >= unit; n /= unit {\n\t\tdiv *= unit\n\t\texp++\n\t}\n\treturn fmt.Sprintf(\"%.1f %ciB\",\n\t\tfloat64(b)/float64(div), \"KMGTPE\"[exp])\n}", "func CountBytes(b []byte) (int, error) {\n\tvar count int\n\tfor len(b) >= 8 {\n\t\tv := binary.BigEndian.Uint64(b[:8])\n\t\tb = b[8:]\n\n\t\tsel := v >> 60\n\t\tif sel >= 16 {\n\t\t\treturn 0, fmt.Errorf(\"invalid selector value: %v\", sel)\n\t\t}\n\t\tcount += selector[sel].n\n\t}\n\n\tif len(b) > 0 {\n\t\treturn 0, fmt.Errorf(\"invalid slice len remaining: %v\", len(b))\n\t}\n\treturn count, nil\n}", "func ByteSize(bytes uint64) string {\n\tunit := \"\"\n\tvalue := float32(bytes)\n\n\tswitch {\n\tcase bytes >= TERABYTE:\n\t\tunit = \"T\"\n\t\tvalue = value / TERABYTE\n\tcase bytes >= GIGABYTE:\n\t\tunit = \"G\"\n\t\tvalue = value / GIGABYTE\n\tcase bytes >= MEGABYTE:\n\t\tunit = \"M\"\n\t\tvalue = value / MEGABYTE\n\tcase bytes >= KILOBYTE:\n\t\tunit = \"K\"\n\t\tvalue = value / KILOBYTE\n\tcase bytes >= BYTE:\n\t\tunit = \"B\"\n\tcase bytes == 0:\n\t\treturn \"0\"\n\t}\n\n\tstringValue := fmt.Sprintf(\"%.1f\", value)\n\tstringValue = strings.TrimSuffix(stringValue, \".0\")\n\treturn fmt.Sprintf(\"%s%s\", stringValue, unit)\n}", "func ByteSize(bytes uint64) string {\n\tunit := \"\"\n\tvalue := float32(bytes)\n\n\tswitch {\n\tcase bytes >= TERABYTE:\n\t\tunit = \"T\"\n\t\tvalue = value / TERABYTE\n\tcase bytes >= GIGABYTE:\n\t\tunit = \"G\"\n\t\tvalue = value / GIGABYTE\n\tcase bytes >= MEGABYTE:\n\t\tunit = \"M\"\n\t\tvalue = value / MEGABYTE\n\tcase bytes >= KILOBYTE:\n\t\tunit = \"K\"\n\t\tvalue = value / KILOBYTE\n\tcase bytes >= BYTE:\n\t\tunit = \"B\"\n\tcase bytes == 0:\n\t\treturn \"0\"\n\t}\n\n\tstringValue := fmt.Sprintf(\"%.1f\", value)\n\tstringValue = strings.TrimSuffix(stringValue, \".0\")\n\treturn fmt.Sprintf(\"%s%s\", stringValue, unit)\n}", "func ByteSize(b float64) string {\n\tvar (\n\t\tunit string\n\t\tdel float64 = 1\n\t)\n\n\tswitch {\n\tcase b >= YB:\n\t\tunit = \"Y\"\n\t\tdel = YB\n\tcase b >= ZB:\n\t\tunit = \"Z\"\n\t\tdel = ZB\n\tcase b >= EB:\n\t\tunit = \"E\"\n\t\tdel = EB\n\tcase b >= PB:\n\t\tunit = \"P\"\n\t\tdel = PB\n\tcase b >= TB:\n\t\tunit = \"T\"\n\t\tdel = TB\n\tcase b >= GB:\n\t\tunit = \"G\"\n\t\tdel = GB\n\tcase b >= MB:\n\t\tunit = \"M\"\n\t\tdel = MB\n\tcase b >= KB:\n\t\tunit = \"K\"\n\t\tdel = KB\n\tcase b == 0:\n\t\treturn \"0\"\n\tdefault:\n\t\tunit = \"B\"\n\t}\n\treturn strings.TrimSuffix(\n\t\tstrconv.FormatFloat(b/del, 'f', 1, 32),\n\t\t\".0\",\n\t) + unit\n}", "func DecimalPeak(b []byte) (int, error) {\n\tif len(b) < 3 {\n\t\treturn 0, ErrBadNumber\n\t}\n\tprecision := int(b[0])\n\tfrac := int(b[1])\n\tbinSize, err := DecimalBinSize(precision, frac)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn binSize + 2, nil\n}", "func (f *CommitNotice) ByteCount() int {\n\treturn 4 + 8\n}", "func BytesToBinarySize(bytes float64) string {\n\n\tif bytes <= 0 {\n\t\treturn \"0\"\n\t}\n\n\tvar\tunit string\n\tvar res float64\n\n\tswitch {\n\tcase bytes >= EiB:\n\t\tunit = \"EiB\"\n\t\tres = bytes / EiB\n\tcase bytes >= PiB:\n\t\tunit = \"PiB\"\n\t\tres = bytes / PiB\n\tcase bytes >= TiB:\n\t\tunit = \"TiB\"\n\t\tres = bytes / TiB\n\tcase bytes >= GiB:\n\t\tunit = \"GiB\"\n\t\tres = bytes / GiB\n\tcase bytes >= MiB:\n\t\tunit = \"MiB\"\n\t\tres = bytes / MiB\n\tcase bytes >= KiB:\n\t\tunit = \"KiB\"\n\t\tres = bytes / KiB\n\tcase bytes >= BYTE:\n\t\tunit = \"B\"\n\t\tres = bytes\n\t}\n\n\tstrRes := strconv.FormatFloat(res, 'f', 1, 64)\n\tstrRes = strings.TrimSuffix(strRes, \".0\")\n\n\treturn strRes + unit\n}", "func ComputeLengthBytes(s []byte) (n int) {\n\t// From utf16 package.\n\tvar i int\n\tfor i < len(s) {\n\t\tv, size := utf8.DecodeRune(s[i:])\n\t\ti += size\n\t\tn += utf16RuneLen(v)\n\t}\n\treturn n\n}", "func byteCountToHuman(b int64) string {\n\tconst unit = 1000\n\tif b < unit {\n\t\treturn fmt.Sprintf(\"%dB\", b)\n\t}\n\tdiv, exp := int64(unit), 0\n\tfor n := b / unit; n >= unit; n /= unit {\n\t\tdiv *= unit\n\t\texp++\n\t}\n\treturn fmt.Sprintf(\"%.1f%cB\", float64(b)/float64(div), \"kMGTPE\"[exp])\n}", "func (f *ProgressNotice) ByteCount() int {\n\treturn 8 + f.User.ByteCount()\n}", "func humanBytes(byteCount uint64) string {\n\tconst unit = 1024\n\tif byteCount < unit {\n\t\treturn fmt.Sprintf(\"%d B\", byteCount)\n\t}\n\n\tdiv, exp := int64(unit), 0\n\tfor n := byteCount / unit; n >= unit; n /= unit {\n\t\tdiv *= unit\n\t\texp++\n\t}\n\n\treturn fmt.Sprintf(\"%.1f %ciB\", float64(byteCount)/float64(div), \"KMGTPE\"[exp])\n}", "func ByteCountSI(input string) string {\n\n\tb, err := strconv.Atoi(input)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn ByteCountSIInt(b)\n}", "func numUvarintBytes(x uint64) (n int) {\n\tfor x >= 0x80 {\n\t\tx >>= 7\n\t\tn++\n\t}\n\treturn n + 1\n}", "func prettyNumBytes(n int64) string {\n\tconst (\n\t\t_ = 1 << (10 * iota)\n\t\tKB\n\t\tMB\n\t\tGB\n\t\tTB\n\t\tPB\n\t)\n\n\ttable := []struct {\n\t\tv int64\n\t\tn string\n\t}{\n\t\t{PB, \"PB\"},\n\t\t{TB, \"TB\"},\n\t\t{GB, \"GB\"},\n\t\t{MB, \"MB\"},\n\t\t{KB, \"KB\"},\n\t}\n\n\tfor _, t := range table {\n\t\tif n > t.v {\n\t\t\treturn fmt.Sprintf(\"%.2f%s\", float64(n)/float64(t.v), t.n)\n\t\t}\n\t}\n\n\t// Less than 1KB\n\treturn fmt.Sprintf(\"%dB\", n)\n}", "func DecimalPeak(b []byte) (int, error) {\n\ttrace_util_0.Count(_mydecimal_00000, 627)\n\tif len(b) < 3 {\n\t\ttrace_util_0.Count(_mydecimal_00000, 629)\n\t\treturn 0, ErrBadNumber\n\t}\n\ttrace_util_0.Count(_mydecimal_00000, 628)\n\tprecision := int(b[0])\n\tfrac := int(b[1])\n\treturn decimalBinSize(precision, frac) + 2, nil\n}", "func (f *PushNotice) ByteCount() int {\n\treturn 1 + len(f.Data)\n}", "func Bytes(n int64, decimals int, long bool) string {\n\tpadding := \" \"\n\tlevels := []string{\n\t\t\"B\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", /* \"ZB\", \"YB\" will overflow int64 */\n\t}\n\tif long {\n\t\tlevels = []string{\n\t\t\t\"bytes\", \"kilobyte\", \"megabyte\", \"gigabyte\", \"terabyte\", \"petabyte\", \"exabyte\",\n\t\t}\n\t}\n\n\treturn human(n, levels, 1024, decimals, padding)\n}", "func ByteCountSIInt(input int) string {\n\n\tconst unit = 1000\n\tif input < unit {\n\t\treturn fmt.Sprintf(\"%d B\", input)\n\t}\n\tdiv, exp := int64(unit), 0\n\tfor n := input / unit; n >= unit; n /= unit {\n\t\tdiv *= unit\n\t\texp++\n\t}\n\treturn fmt.Sprintf(\"%.1f %cB\",\n\t\tfloat64(input)/float64(div), \"kMGTPE\"[exp])\n}", "func humanReadableCountSI(bytes int64) string {\n\tif -1000 < bytes && bytes < 1000 {\n\t\treturn fmt.Sprintf(\"%d \", bytes)\n\t}\n\tci := \"kMGTPE\"\n\tidx := 0\n\tfor bytes <= -999950 || bytes >= 999950 {\n\t\tbytes /= 1000\n\t\tidx++\n\t}\n\treturn fmt.Sprintf(\"%.1f %c\", float64(bytes)/1000.0, ci[idx])\n}", "func decimals(dec int64) int {\n\tif dec < 1 {\n\t\treturn 0\n\t}\n\treturn int(math.Floor(math.Log10(float64(dec))))\n}", "func (f *CloseNotice) ByteCount() int {\n\treturn 0\n}", "func (bs *endecBytes) calc(fields ...interface{}) int {\n\ttotal := 0\n\tfor _, val := range fields {\n\t\tswitch val.(type) {\n\t\tcase byte:\n\t\t\ttotal++\n\t\tcase uint16:\n\t\t\ttotal += 2\n\t\tcase uint32: // remaingLength\n\t\t\tremlen := val.(uint32)\n\t\t\tif remlen <= 127 {\n\t\t\t\ttotal++\n\t\t\t} else if remlen <= 16383 {\n\t\t\t\ttotal += 2\n\t\t\t} else if remlen <= 2097151 {\n\t\t\t\ttotal += 3\n\t\t\t} else if remlen <= 268435455 {\n\t\t\t\ttotal += 4\n\t\t\t}\n\t\tcase string:\n\t\t\ttotal += (2 + len([]byte(val.(string))))\n\t\tcase []string:\n\t\t\tfor _, s := range val.([]string) {\n\t\t\t\ttotal += (2 + len([]byte(s)))\n\t\t\t}\n\t\tcase []byte:\n\t\t\ttotal += len(val.([]byte))\n\t\tdefault: // unknown type\n\t\t\treturn -total\n\t\t}\n\t}\n\treturn total\n}", "func (p *Esc) expectedByteCount() int {\n\tswitch p.trice.Type {\n\tcase \"TRICE0\":\n\t\treturn 0\n\tcase \"TRICE8_1\":\n\t\treturn 1\n\tcase \"TRICE8_2\", \"TRICE16_1\":\n\t\treturn 2\n\tcase \"TRICE8_3\", \"TRICE8_4\", \"TRICE16_2\", \"TRICE32_1\":\n\t\treturn 4\n\tcase \"TRICE8_5\", \"TRICE8_6\", \"TRICE16_3\", \"TRICE8_7\", \"TRICE8_8\", \"TRICE16_4\", \"TRICE32_2\", \"TRICE64_1\":\n\t\treturn 8\n\tcase \"TRICE32_3\", \"TRICE32_4\", \"TRICE64_2\":\n\t\treturn 16\n\tcase \"TRICE_S\":\n\t\treturn p.bc\n\tdefault:\n\t\treturn -1 // unknown trice type\n\t}\n}", "func (m *logMeasurement) bytes() int {\n\tvar b int\n\tb += len(m.name)\n\tfor k, v := range m.tagSet {\n\t\tb += len(k)\n\t\tb += v.bytes()\n\t}\n\tb += (int(m.cardinality()) * 8)\n\tb += int(unsafe.Sizeof(*m))\n\treturn b\n}", "func convertBinaryToDecimal(binary string) int {\n\tvar (\n\t\tdecimal int = 0\n\t\tcounter int = 0\n\t\tsize = len(binary)\n\t)\n\tfor i := size - 1; i >= 0; i-- {\n\t\tif binary[i] == '1' {\n\t\t\tdecimal += int(math.Pow(2, float64(counter)))\n\t\t}\n\t\tcounter++\n\t}\n\treturn decimal\n}", "func (f *ReadRequest) ByteCount() int {\n\treturn 1 + 8 + 8\n}", "func ConvertBytesToSizeString(b int64) string {\n\tconst unit = 1000\n\n\tif b < unit {\n\t\treturn fmt.Sprintf(\"%d B\", b)\n\t}\n\n\tdiv, exp := int64(unit), 0\n\tfor n := b / unit; n >= unit; n /= unit {\n\t\tdiv *= unit\n\t\texp++\n\t}\n\n\treturn fmt.Sprintf(\"%.1f %cB\",\n\t\tfloat64(b)/float64(div), \"kMGTPE\"[exp])\n}", "func (c *Control) ByteCount() *bytes.Bytes {\n\treturn c.byteCount\n}", "func totalUvarintBytes(a, b, c, d, e uint64, more []uint64) (n int) {\n\tn = numUvarintBytes(a)\n\tn += numUvarintBytes(b)\n\tn += numUvarintBytes(c)\n\tn += numUvarintBytes(d)\n\tn += numUvarintBytes(e)\n\tfor _, v := range more {\n\t\tn += numUvarintBytes(v)\n\t}\n\treturn n\n}", "func (b Datasize) Pebibytes() float64 {\n\treturn float64(b / Pebibyte)\n}", "func decimalPlaces(v string) int {\n\ts := strings.Split(v, \".\")\n\tif len(s) < 2 {\n\t\treturn 0\n\t}\n\treturn len(s[1])\n}", "func ByteFormat(bytes float64) string {\n\tif bytes >= 1024*1024 {\n\t\treturn fmt.Sprintf(\"%.f MB\", bytes/1024/1024)\n\t}\n\treturn fmt.Sprintf(\"%.f KB\", bytes/1024)\n}", "func (dt DataType) ByteLen() int {\n\tswitch dt {\n\tcase DSA:\n\t\treturn ByteLenShort\n\tcase DFA:\n\t\treturn ByteLenFloat\n\tcase DDA:\n\t\treturn ByteLenDouble\n\tcase DSB:\n\t\treturn ByteLenShort\n\tcase DFB:\n\t\treturn ByteLenFloat\n\tcase DDB:\n\t\treturn ByteLenDouble\n\tdefault:\n\t\treturn -1 // unreachable code\n\t}\n}", "func Bytes(s int64) string {\n\tsizes := []string{\"B\", \"K\", \"M\", \"G\", \"T\", \"P\", \"E\"}\n\treturn humanateBytes(s, 1000, sizes)\n}", "func formatBytes(i int64) (result string) {\n\tswitch {\n\tcase i > (1024 * 1024 * 1024 * 1024):\n\t\tresult = fmt.Sprintf(\"%.02f TB\", float64(i)/1024/1024/1024/1024)\n\tcase i > (1024 * 1024 * 1024):\n\t\tresult = fmt.Sprintf(\"%.02f GB\", float64(i)/1024/1024/1024)\n\tcase i > (1024 * 1024):\n\t\tresult = fmt.Sprintf(\"%.02f MB\", float64(i)/1024/1024)\n\tcase i > 1024:\n\t\tresult = fmt.Sprintf(\"%.02f KB\", float64(i)/1024)\n\tdefault:\n\t\tresult = fmt.Sprintf(\"%d B\", i)\n\t}\n\tresult = strings.Trim(result, \" \")\n\treturn\n}", "func formatBytes(i int64) (result string) {\n\tswitch {\n\tcase i > (1024 * 1024 * 1024 * 1024):\n\t\tresult = fmt.Sprintf(\"%.02f TB\", float64(i)/1024/1024/1024/1024)\n\tcase i > (1024 * 1024 * 1024):\n\t\tresult = fmt.Sprintf(\"%.02f GB\", float64(i)/1024/1024/1024)\n\tcase i > (1024 * 1024):\n\t\tresult = fmt.Sprintf(\"%.02f MB\", float64(i)/1024/1024)\n\tcase i > 1024:\n\t\tresult = fmt.Sprintf(\"%.02f KB\", float64(i)/1024)\n\tdefault:\n\t\tresult = fmt.Sprintf(\"%d B\", i)\n\t}\n\tresult = strings.Trim(result, \" \")\n\treturn\n}", "func (s Size) Pebibytes() float64 { return float64(s) / float64(Pebibyte) }", "func countCurrSrvBytes(msmtInfoRep *shared.DataObj) uint {\n\tvar currSrvByte uint\n\n\tfor _, dataElement := range msmtInfoRep.Data.DataElements {\n\t\tbytes, err := strconv.ParseUint(dataElement.Received_bytes, 10, 0)\n\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Could not parse bytes: %s\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tcurrSrvByte += uint(bytes)\n\t}\n\treturn currSrvByte\n}", "func (b Datasize) Petabytes() float64 {\n\treturn float64(b / Petabyte)\n}", "func DataTypeBytes(dataType DataType) int {\n\treturn (DataTypeBits(dataType) + 7) / 8\n}", "func (m NumSeriesDistribution) ByteSize() int {\n\treturn 24 + len(m)*numSeriesDistributionBaseSize\n}", "func (o BackupOutput) SizeBytes() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Backup) pulumi.StringOutput { return v.SizeBytes }).(pulumi.StringOutput)\n}", "func BytesSize(size float64) string {\n\treturn units.CustomSize(\"%.2f%s\", size, 1024.0, binaryAbbrs)\n}", "func countBytes(data []byte) map[byte]int {\n\tvar frequencies map[byte]int = make(map[byte]int)\n\tfor _, character := range data {\n\t\t//increase the count of this character\n\t\tfrequencies[character]++\n\t}\n\treturn frequencies\n}", "func (s Size) Kibibytes() float64 { return float64(s) / float64(Kibibyte) }", "func (b Datasize) Zebibytes() float64 {\n\treturn float64(b / Zebibyte)\n}", "func (tv *logTagValue) bytes() int {\n\tvar b int\n\tb += len(tv.name)\n\tb += int(unsafe.Sizeof(*tv))\n\tb += (int(tv.cardinality()) * 8)\n\treturn b\n}", "func (b Datasize) Bytes() float64 {\n\treturn float64(b / Byte)\n}", "func DecimalNumberInDiffFormats(x int) {\n\n\t// %b is for binary format\n\t// %x is for hexa decimal format\n\t// %d is for decimal format\n\tfmt.Printf(\"%d \\t %b \\t %x\", x, x, x)\n}", "func mysqlDecimalToCHDecimalBin(ft *types.FieldType, d *types.MyDecimal) ([]byte, error) {\n\tconst (\n\t\tten0 = 1\n\t\tten1 = 10\n\t\tten2 = 100\n\t\tten3 = 1000\n\t\tten4 = 10000\n\t\tten5 = 100000\n\t\tten6 = 1000000\n\t\tten7 = 10000000\n\t\tten8 = 100000000\n\t\tten9 = 1000000000\n\n\t\tdigitsPerWord = 9 // A word holds 9 digits.\n\t\twordSize = 4 // A word is 4 bytes int32.\n\t\twordBase = ten9\n\t)\n\n\tvar (\n\t\tpowers10 = [10]int64{ten0, ten1, ten2, ten3, ten4, ten5, ten6, ten7, ten8, ten9}\n\t\tdig2bytes = [10]int{0, 1, 1, 2, 2, 3, 3, 4, 4, 4}\n\t)\n\n\tprecision, frac, intdigits := ft.Flen, ft.Decimal, ft.Flen-ft.Decimal\n\tmyBytes, err := d.ToBin(precision, frac)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\t// Calculate offsets.\n\tleadingBytes := dig2bytes[intdigits%digitsPerWord]\n\talignedFrom, alignedTo := leadingBytes, leadingBytes+intdigits/digitsPerWord*wordSize+frac/digitsPerWord*wordSize\n\ttrailingDigits := frac % digitsPerWord\n\ttrailingBytes := dig2bytes[trailingDigits]\n\n\t// Get mask.\n\tmask := int32(-1)\n\tif myBytes[0]&0x80 > 0 {\n\t\tmask = 0\n\t}\n\n\t// Flip the very first bit.\n\tmyBytes[0] ^= 0x80\n\n\t// Accumulate the word value into big.Int.\n\tvar digitsGoInt, baseGoInt = big.NewInt(0), big.NewInt(wordBase)\n\tif leadingBytes > 0 {\n\t\tleadingInt := int64(0)\n\t\tfor i := 0; i < leadingBytes; i++ {\n\t\t\tleadingInt = leadingInt<<8 + int64(myBytes[i]^byte(mask))\n\t\t}\n\t\tdigitsGoInt.Add(digitsGoInt, big.NewInt(leadingInt))\n\t}\n\tfor i := alignedFrom; i < alignedTo; i += wordSize {\n\t\tword := int32(myBytes[i])<<24 + int32(myBytes[i+1])<<16 + int32(myBytes[i+2])<<8 + int32(myBytes[i+3])\n\t\tword ^= mask\n\t\tdigitsGoInt.Mul(digitsGoInt, baseGoInt)\n\t\tdigitsGoInt.Add(digitsGoInt, big.NewInt(int64(word)))\n\t}\n\tif trailingBytes > 0 {\n\t\ttrailingFrac := int64(0)\n\t\tfor i := 0; i < trailingBytes; i++ {\n\t\t\ttrailingFrac = trailingFrac<<8 + int64(myBytes[alignedTo+i]^byte(mask))\n\t\t}\n\t\tdigitsGoInt.Mul(digitsGoInt, big.NewInt(powers10[trailingDigits]))\n\t\tdigitsGoInt.Add(digitsGoInt, big.NewInt(trailingFrac))\n\t}\n\n\t// Get bytes and swap to little-endian.\n\tbin := digitsGoInt.Bytes()\n\tfor i := 0; i < len(bin)/2; i++ {\n\t\tbin[i], bin[len(bin)-1-i] = bin[len(bin)-1-i], bin[i]\n\t}\n\n\t// Pack 32-byte value part for CH Decimal.\n\tif len(bin) > 32 {\n\t\treturn nil, errors.Errorf(\"Decimal out of range.\")\n\t}\n\tchBin := append(bin, make([]byte, 32-len(bin))...)\n\n\t// Append limbs.\n\tlimbs := int16(math.Ceil(float64(len(bin)) / 8.0))\n\tchBin = append(chBin, byte(limbs), byte(limbs>>8))\n\n\t// Append sign.\n\tif d.IsNegative() {\n\t\tchBin = append(chBin, byte(1))\n\t} else {\n\t\tchBin = append(chBin, byte(0))\n\t}\n\tchBin = append(chBin, byte(0))\n\n\t// Padding to 48 bytes.\n\tchBin = append(chBin, make([]byte, 12)...)\n\n\t// Append precision.\n\tchBin = append(chBin, byte(precision), byte(precision>>8))\n\n\t// Append scale.\n\tchBin = append(chBin, byte(frac), byte(frac>>8))\n\n\t// Padding to 64 bytes.\n\tchBin = append(chBin, make([]byte, 12)...)\n\n\treturn chBin, nil\n}", "func humanizeBytes(s uint64) string {\n\tif s < 10 {\n\t\treturn fmt.Sprintf(\"%dB\", s)\n\t}\n\tconst base = 1000\n\tsizes := []string{\"B\", \"kB\", \"MB\", \"GB\", \"TB\"}\n\te := math.Floor(math.Log(float64(s)) / math.Log(base))\n\tsuffix := sizes[int(e)]\n\tval := math.Floor(float64(s)/math.Pow(base, e)*10+0.5) / 10\n\tf := \"%.0f%s\"\n\tif val < 10 {\n\t\tf = \"%.1f%s\"\n\t}\n\treturn fmt.Sprintf(f, val, suffix)\n}", "func (b Datasize) Exabytes() float64 {\n\treturn float64(b / Exabyte)\n}", "func StrBytes(s string) int64 {\n\tidx := len(s) - 1\n\tnum, _ := strconv.ParseInt(s[:idx], 10, 64)\n\n\tunit := string(s[idx])\n\tswitch unit {\n\tcase \"c\", \"C\":\n\t\treturn num\n\tcase \"k\", \"K\":\n\t\treturn num * KiB\n\tcase \"m\", \"M\":\n\t\treturn num * MiB\n\tcase \"g\", \"G\":\n\t\treturn num * GiB\n\tcase \"t\", \"T\":\n\t\treturn num * TiB\n\t}\n\treturn 0\n}", "func (b Datasize) Kibibytes() float64 {\n\treturn float64(b / Kibibyte)\n}", "func (field EnvChangePackageField) ByteLength() int {\n\t// type byte\n\t// + new value length byte + new value length\n\t// + old value length byte + old value length\n\treturn 3 + len(field.NewValue) + len(field.OldValue)\n}", "func (n *Uint256) toDecimal() []byte {\n\tif n.IsZero() {\n\t\treturn []byte(\"0\")\n\t}\n\n\t// Create space for the max possible number of output digits.\n\t//\n\t// Note that the actual total number of output digits is usually calculated\n\t// as:\n\t// floor(log2(n) / log2(base)) + 1\n\t//\n\t// However, in order to avoid more expensive calculation of the full log2 of\n\t// the value, the code below instead calculates a value that might overcount\n\t// by a max of one digit and trims the result as needed via the following\n\t// slightly modified version of the formula:\n\t// floor(bitlen(n) / log2(base)) + 1\n\t//\n\t// The modified formula is guaranteed to be large enough because:\n\t// (a) floor(log2(x)) ≤ log2(x) ≤ floor(log2(x)) + 1\n\t// (b) bitlen(x) = floor(log2(x)) + 1\n\t//\n\t// Which implies:\n\t// (c) floor(log2(n) / log2(base)) ≤ floor(floor(log2(n))+1) / log2(base))\n\t// (d) floor(log2(n) / log2(base)) ≤ floor(bitlen(n)) / log2(base))\n\t//\n\t// Note that (c) holds since the left hand side of the inequality has a\n\t// dividend that is ≤ the right hand side dividend due to (a) while the\n\t// divisor is = the right hand side divisor, and then (d) is equal to (c)\n\t// per (b). Adding 1 to both sides of (d) yields an inequality where the\n\t// left hand side is the typical formula and the right hand side is the\n\t// modified formula thereby proving it will never under count.\n\tconst log2Of10 = 3.321928094887362\n\tmaxOutDigits := uint8(float64(n.BitLen())/log2Of10) + 1\n\tresult := make([]byte, maxOutDigits)\n\n\t// Convert each internal base 2^64 word to base 10 from least to most\n\t// significant. Since the value is guaranteed to be non-zero per a previous\n\t// check, there will always be a nonzero most-significant word. Also, note\n\t// that partial digit handling is needed in this case because the shift\n\t// amount does not evenly divide the bits per internal word.\n\tconst outputDigitsPerDiv = 19\n\tvar remainingDigitsPerDiv uint8\n\tvar quo, rem, t Uint256\n\tvar r uint64\n\toutputIdx := maxOutDigits - 1\n\tquo = *n\n\tfor !quo.IsZero() {\n\t\tfor i := uint8(0); i < remainingDigitsPerDiv; i++ {\n\t\t\tresult[outputIdx] = '0'\n\t\t\toutputIdx--\n\t\t}\n\t\tremainingDigitsPerDiv = outputDigitsPerDiv\n\n\t\trem.Set(&quo)\n\t\tquo.Div(maxPow10ForInternalWord)\n\t\tt.Mul2(&quo, maxPow10ForInternalWord)\n\t\tinputWord := rem.Sub(&t).Uint64()\n\t\tfor inputWord != 0 {\n\t\t\tinputWord, r = inputWord/10, inputWord%10\n\t\t\tresult[outputIdx] = '0' + byte(r)\n\t\t\toutputIdx--\n\t\t\tremainingDigitsPerDiv--\n\t\t}\n\t}\n\n\treturn result[outputIdx+1:]\n}", "func Bytes(s uint64) string {\n\tsizes := []string{\"B\", \"kB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\"}\n\treturn humanateBytes(s, 1024, sizes)\n}", "func (bm BitMap) BitCountByte(ctx context.Context, start, end int64) (int64, error) {\n\treq := newRequest(\"*4\\r\\n$8\\r\\nBITCOUNT\\r\\n$\")\n\treq.addStringInt2String(bm.name, start, end, \"BYTE\")\n\treturn bm.c.cmdInt(ctx, req)\n}", "func FormatBytes(i int64) (result string) {\n\tswitch {\n\tcase i > (1024 * 1024 * 1024 * 1024):\n\t\tresult = fmt.Sprintf(\"%#.02f TB\", float64(i)/1024/1024/1024/1024)\n\tcase i > (1024 * 1024 * 1024):\n\t\tresult = fmt.Sprintf(\"%#.02f GB\", float64(i)/1024/1024/1024)\n\tcase i > (1024 * 1024):\n\t\tresult = fmt.Sprintf(\"%#.02f MB\", float64(i)/1024/1024)\n\tcase i > 1024:\n\t\tresult = fmt.Sprintf(\"%#.02f KB\", float64(i)/1024)\n\tdefault:\n\t\tresult = fmt.Sprintf(\"%d B\", i)\n\t}\n\tresult = strings.Trim(result, \" \")\n\treturn\n}", "func FormatBytes(i int64) (result string) {\n\tswitch {\n\tcase i > (1024 * 1024 * 1024 * 1024):\n\t\tresult = fmt.Sprintf(\"%#.02f TB\", float64(i)/1024/1024/1024/1024)\n\tcase i > (1024 * 1024 * 1024):\n\t\tresult = fmt.Sprintf(\"%#.02f GB\", float64(i)/1024/1024/1024)\n\tcase i > (1024 * 1024):\n\t\tresult = fmt.Sprintf(\"%#.02f MB\", float64(i)/1024/1024)\n\tcase i > 1024:\n\t\tresult = fmt.Sprintf(\"%#.02f KB\", float64(i)/1024)\n\tdefault:\n\t\tresult = fmt.Sprintf(\"%d B\", i)\n\t}\n\tresult = strings.Trim(result, \" \")\n\treturn\n}", "func (d Dense) SizeBytes() int {\n\treturn BytesFor(d.len)\n}", "func (entry *LogEntry) SizeBytes() uint32 {\n\tvar len uint32\n\t// sizes of fields on disk\n\t// 16 - 128 bit LSN\n\t// 8 - 64 bit sym Id\n\t// 8 - 64 bit timestamp\n\t// 4 - 32 bit length of value data\n\t// value-data\n\theaderLen := unsafe.Sizeof(entry.logID) +\n\t\tunsafe.Sizeof(entry.symbolID) +\n\t\tunsafe.Sizeof(entry.timeStamp) +\n\t\tunsafe.Sizeof(len)\n\treturn uint32(headerLen) + sizeOfValues(entry.valueList)\n}", "func (s Size) Petabytes() float64 { return float64(s) / float64(Petabyte) }", "func HumanizeBytes(bytes float32) string {\n\tif bytes < 1000000 { //if we have less than 1MB in bytes convert to KB\n\t\tpBytes := fmt.Sprintf(\"%.2f\", bytes/1024)\n\t\tpBytes = pBytes + \" KB\"\n\t\treturn pBytes\n\t}\n\tbytes = bytes / 1024 / 1024 //Converting bytes to a useful measure\n\tif bytes > 1024 {\n\t\tpBytes := fmt.Sprintf(\"%.2f\", bytes/1024)\n\t\tpBytes = pBytes + \" GB\"\n\t\treturn pBytes\n\t}\n\tpBytes := fmt.Sprintf(\"%.2f\", bytes) //If not too big or too small leave it as MB\n\tpBytes = pBytes + \" MB\"\n\treturn pBytes\n}", "func (b Datasize) Zettabytes() float64 {\n\treturn float64(b / Zettabyte)\n}", "func byteDiff(a, b uint8) int {\n\tcount := 0\n\tfor i := uint(0); i < 8; i++ {\n\t\tif a&(1<<i) != b&(1<<i) {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count\n}", "func Byte() byte {\n\treturn 109\n}", "func ByteSized(size int64, precision int, sep string) string {\n\tf := float64(size)\n\ttpl := \"%.\" + strconv.Itoa(precision) + \"f\" + sep\n\n\tswitch {\n\tcase f >= yb:\n\t\treturn fmt.Sprintf(tpl+\"YB\", f/yb)\n\tcase f >= zb:\n\t\treturn fmt.Sprintf(tpl+\"ZB\", f/zb)\n\tcase f >= eb:\n\t\treturn fmt.Sprintf(tpl+\"EB\", f/eb)\n\tcase f >= pb:\n\t\treturn fmt.Sprintf(tpl+\"PB\", f/pb)\n\tcase f >= tb:\n\t\treturn fmt.Sprintf(tpl+\"TB\", f/tb)\n\tcase f >= gb:\n\t\treturn fmt.Sprintf(tpl+\"GB\", f/gb)\n\tcase f >= mb:\n\t\treturn fmt.Sprintf(tpl+\"MB\", f/mb)\n\tcase f >= kb:\n\t\treturn fmt.Sprintf(tpl+\"KB\", f/kb)\n\t}\n\treturn fmt.Sprintf(tpl+\"B\", f)\n}", "func BytesCounter(r io.Reader) (int64, error) {\n\tvar readSizeTmp int\n\tvar err error\n\tbuf := make([]byte, 1024)\n\tvar total int64\n\tfor {\n\t\treadSizeTmp, err = r.Read(buf)\n\t\ttotal = total + int64(readSizeTmp)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif err == io.EOF {\n\t\t\treturn total, nil\n\t\t}\n\t}\n\treturn total, err\n}", "func (mms *logMeasurements) bytes() int {\n\tvar b int\n\tfor k, v := range *mms {\n\t\tb += len(k)\n\t\tb += v.bytes()\n\t}\n\tb += int(unsafe.Sizeof(*mms))\n\treturn b\n}", "func (b *block) uncompressedSizeBytes() uint64 {\n\trowsCount := uint64(b.Len())\n\n\t// Take into account timestamps\n\tn := rowsCount * uint64(len(time.RFC3339Nano))\n\n\t// Take into account columns\n\tcs := b.columns\n\tfor i := range cs {\n\t\tc := &cs[i]\n\t\tnameLen := uint64(len(c.name))\n\t\tif nameLen == 0 {\n\t\t\tnameLen = uint64(len(\"_msg\"))\n\t\t}\n\t\tfor _, v := range c.values {\n\t\t\tif len(v) > 0 {\n\t\t\t\tn += nameLen + 2 + uint64(len(v))\n\t\t\t}\n\t\t}\n\t}\n\n\t// Take into account constColumns\n\tccs := b.constColumns\n\tfor i := range ccs {\n\t\tcc := &ccs[i]\n\t\tnameLen := uint64(len(cc.Name))\n\t\tif nameLen == 0 {\n\t\t\tnameLen = uint64(len(\"_msg\"))\n\t\t}\n\t\tn += rowsCount * (2 + nameLen + uint64(len(cc.Value)))\n\t}\n\n\treturn n\n}", "func (this *Dcmp0_Chunk_ExtendedBody_RepeatBody) ByteCount() (v int, err error) {\n\tif (this._f_byteCount) {\n\t\treturn this.byteCount, nil\n\t}\n\tvar tmp47 int8;\n\tif (this.Tag == 2) {\n\t\ttmp47 = 1\n\t} else {\n\t\tvar tmp48 int8;\n\t\tif (this.Tag == 3) {\n\t\t\ttmp48 = 2\n\t\t} else {\n\t\t\ttmp48 = -1\n\t\t}\n\t\ttmp47 = tmp48\n\t}\n\tthis.byteCount = int(tmp47)\n\tthis._f_byteCount = true\n\treturn this.byteCount, nil\n}", "func IntABytes(n int) []byte {\n\tx := int32(n)\n\tbufferBytes := bytes.NewBuffer([]byte{})\n\tbinary.Write(bufferBytes, binary.BigEndian, x)\n\treturn bufferBytes.Bytes()\n}", "func (f *OpenStreamReply) ByteCount() int {\n\treturn 4\n}", "func ByteSizeString(sizeInBytes int64, useSI bool) string {\n\tn := int64(1024)\n\tif useSI {\n\t\tn = 1000\n\t}\n\tif sizeInBytes > -n && sizeInBytes < n {\n\t\treturn fmt.Sprintf(\"%d B\", sizeInBytes)\n\t}\n\tif !useSI && sizeInBytes == math.MinInt64 {\n\t\treturn \"-7.9 EiB\"\n\t}\n\tneg := sizeInBytes < 0\n\tvar ret string\n\tif neg {\n\t\tsizeInBytes = -sizeInBytes\n\t\tret = \"-\"\n\t}\n\tfor _, group := range []struct {\n\t\tunit string\n\t\tscale int64\n\t}{ // binary: SI:\n\t\t{\"E\", n * n * n * n * n * n}, // exabyte exbibyte\n\t\t{\"P\", n * n * n * n * n}, // petabyte pebibyte\n\t\t{\"T\", n * n * n * n}, // terabyte tebibyte\n\t\t{\"G\", n * n * n}, // gigabyte gibibyte\n\t\t{\"M\", n * n}, // megabyte mebibyte\n\t\t{\"K\", n}, // kilobyte kibibyte\n\t} {\n\t\tif sizeInBytes < group.scale {\n\t\t\tcontinue\n\t\t}\n\t\t// because Sprintf() rounds numbers up, cut at 1dp before calling it\n\t\t// (use either regular arithmetic or math.BigInt if size is very large)\n\t\tvar cut float64\n\t\tif sizeInBytes < math.MaxInt64/1024 {\n\t\t\tcut = float64(sizeInBytes) / float64(group.scale)\n\t\t\tcut = float64(int64(cut*10)) / 10\n\t\t} else {\n\t\t\tsz := big.NewInt(sizeInBytes)\n\t\t\tsz.Mul(sz, big.NewInt(10))\n\t\t\tsz.Div(sz, big.NewInt(group.scale))\n\t\t\tcut = float64(sz.Int64()) / 10\n\t\t}\n\t\tret += fmt.Sprintf(\"%0.1f\", cut)\n\t\t//\n\t\t// remove trailing zero decimal\n\t\tif strings.HasSuffix(ret, \".0\") {\n\t\t\tret = ret[:len(ret)-2]\n\t\t}\n\t\t// append SI or binary units\n\t\tret += \" \" + group.unit\n\t\tif useSI {\n\t\t\tret += \"B\"\n\t\t} else {\n\t\t\tret += \"iB\"\n\t\t}\n\t\tbreak\n\t}\n\treturn ret\n}", "func Bytes(b0, b1 []byte) int {\n\td := 0\n\tfor i, x := range b0 {\n\t\td += Byte(x, b1[i])\n\t}\n\treturn d\n}", "func Bytes(s uint64) string {\n\treturn humanateBytes(s, 1000, nameSizes, 1, nil)\n}", "func (f *CreateBundleReply) ByteCount() int {\n\treturn 4\n}", "func IntBytes(x *big.Int,) []byte", "func (o LocalDiskResponseOutput) DiskCount() pulumi.IntOutput {\n\treturn o.ApplyT(func(v LocalDiskResponse) int { return v.DiskCount }).(pulumi.IntOutput)\n}", "func (b *BundleIdent) ByteCount() int {\n\treturn len(b.App) + 1 + len(b.Name) + 1 + len(b.Incarnation) + 1 + b.User.ByteCount()\n}", "func (lf *ListFile) NumBytes() int64 {\n\t// NOTE: here we don't use IsClosed() because\n\t// it uses the mutex; Size() is used in noMutexIterateLines\n\t// which is called after another mutex is locked,\n\t// making IsClosed() wait forever for the mutex unlock.\n\tif lf.isClosed {\n\t\treturn 0\n\t}\n\n\terr := lf.file.Sync()\n\tif err != nil {\n\t\t// TODO: not panic??\n\t\tpanic(err)\n\t}\n\n\tinfo, err := lf.file.Stat()\n\tif err != nil {\n\t\t// TODO: not panic??\n\t\tpanic(err)\n\t}\n\n\treturn info.Size()\n}", "func (b Datasize) Tebibytes() float64 {\n\treturn float64(b / Tebibyte)\n}", "func (tk *logTagKey) bytes() int {\n\tvar b int\n\tb += len(tk.name)\n\tfor k, v := range tk.tagValues {\n\t\tb += len(k)\n\t\tb += v.bytes()\n\t}\n\tb += int(unsafe.Sizeof(*tk))\n\treturn b\n}", "func FormatBytes(i int64) string {\n\tconst (\n\t\tKiB = 1024\n\t\tMiB = 1048576\n\t\tGiB = 1073741824\n\t\tTiB = 1099511627776\n\t)\n\tswitch {\n\tcase i >= TiB:\n\t\treturn fmt.Sprintf(\"%.02fTiB\", float64(i)/TiB)\n\tcase i >= GiB:\n\t\treturn fmt.Sprintf(\"%.02fGiB\", float64(i)/GiB)\n\tcase i >= MiB:\n\t\treturn fmt.Sprintf(\"%.02fMiB\", float64(i)/MiB)\n\tcase i >= KiB:\n\t\treturn fmt.Sprintf(\"%.02fKiB\", float64(i)/KiB)\n\tdefault:\n\t\treturn fmt.Sprintf(\"%dB\", i)\n\t}\n}", "func (d *Download) TotalBytes() int {\r\n\treturn d.max\r\n}", "func (n *Uint256) numDigits() int {\n\tfor i := 3; i >= 0; i-- {\n\t\tif n.n[i] != 0 {\n\t\t\treturn i + 1\n\t\t}\n\t}\n\treturn 0\n}", "func Bytes(z *big.Int) []byte {\n\treturn z.Bytes()\n}", "func (m *memStats) fmtBytes(b uint64) string {\n\tvar (\n\t\tkb uint64 = 1024\n\t\tmb uint64 = kb * 1024\n\t\tgb uint64 = mb * 1024\n\t)\n\tif b < kb {\n\t\treturn fmt.Sprintf(\"%dB\", b)\n\t}\n\tif b < mb {\n\t\treturn fmt.Sprintf(\"%dKB\", b/kb)\n\t}\n\tif b < gb {\n\t\treturn fmt.Sprintf(\"%dMB\", b/mb)\n\t}\n\treturn fmt.Sprintf(\"%dGB\", b/gb)\n}" ]
[ "0.75545055", "0.73857147", "0.7362746", "0.73176783", "0.7284079", "0.7272819", "0.6667764", "0.6593917", "0.6580991", "0.65651476", "0.65651476", "0.65460676", "0.65441024", "0.65441024", "0.65439713", "0.6459058", "0.64501345", "0.6334746", "0.62716866", "0.6255239", "0.62354463", "0.6219879", "0.620204", "0.61118215", "0.61109316", "0.61109304", "0.6098435", "0.6077235", "0.6046948", "0.6037001", "0.6020628", "0.6014499", "0.60021853", "0.59487724", "0.583728", "0.58324385", "0.5826465", "0.5825069", "0.57914996", "0.57664305", "0.57647884", "0.5760054", "0.57561827", "0.5753117", "0.5733838", "0.57115716", "0.5710425", "0.5709539", "0.57049286", "0.57041323", "0.57011247", "0.569884", "0.5681662", "0.5676158", "0.5670238", "0.5670073", "0.56609416", "0.5645615", "0.564262", "0.56236035", "0.5584829", "0.55632627", "0.5561132", "0.5547603", "0.5530288", "0.55263907", "0.5526006", "0.55166596", "0.5514363", "0.5506146", "0.5506146", "0.54997605", "0.54853", "0.5484878", "0.5478412", "0.5470146", "0.5468009", "0.5447566", "0.5442912", "0.5438347", "0.54353064", "0.5430389", "0.5426158", "0.5410646", "0.54102695", "0.54089415", "0.53959286", "0.5391732", "0.53900486", "0.5389505", "0.5385353", "0.5381717", "0.53771305", "0.5374858", "0.5368223", "0.53630793", "0.5361511", "0.5361193", "0.5360569", "0.5353253" ]
0.8371103
0
CmdCreateIAMRole is an entrypoint to createiam role command
func CmdCreateIAMRole(c *cli.Context) error { ctx := c.Context sess := edgegrid.GetSession(ctx) client := iam.Client(sess) // tfWorkPath is a target directory for generated terraform resources var tfWorkPath = "./" if c.IsSet("tfworkpath") { tfWorkPath = c.String("tfworkpath") } tfWorkPath = filepath.FromSlash(tfWorkPath) groupPath := filepath.Join(tfWorkPath, "groups.tf") importPath := filepath.Join(tfWorkPath, "import.sh") rolesPath := filepath.Join(tfWorkPath, "role.tf") userPath := filepath.Join(tfWorkPath, "users.tf") variablesPath := filepath.Join(tfWorkPath, "variables.tf") err := tools.CheckFiles(userPath, groupPath, rolesPath, variablesPath, importPath) if err != nil { return cli.Exit(color.RedString(err.Error()), 1) } templateToFile := map[string]string{ "groups.tmpl": groupPath, "imports.tmpl": importPath, "roles.tmpl": rolesPath, "users.tmpl": userPath, "variables.tmpl": variablesPath, } processor := templates.FSTemplateProcessor{ TemplatesFS: templateFiles, TemplateTargets: templateToFile, } section := edgegrid.GetEdgercSection(c) roleID, err := strconv.ParseInt(c.Args().First(), 10, 64) if err != nil { return cli.Exit(color.RedString(fmt.Sprintf("Wrong format of role id %v must be a number: %s", roleID, err)), 1) } if err = createIAMRoleByID(ctx, roleID, section, client, processor); err != nil { return cli.Exit(color.RedString(fmt.Sprintf("Error exporting HCL for IAM: %s", err)), 1) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func createRole(namespace string, role string, roleTemplateFile string) (bool, string) {\n\tvar resource []byte\n\tvar e error\n\n\tif roleTemplateFile != \"\" {\n\t\t// load file from path of TillerRoleTemplateFile\n\t\tresource, e = ioutil.ReadFile(roleTemplateFile)\n\t} else {\n\t\t// load static resource\n\t\tresource, e = Asset(\"data/role.yaml\")\n\t}\n\tif e != nil {\n\t\tlogError(e.Error())\n\t}\n\treplaceStringInFile(resource, \"temp-modified-role.yaml\", map[string]string{\"<<namespace>>\": namespace, \"<<role-name>>\": role})\n\n\tcmd := command{\n\t\tCmd: \"bash\",\n\t\tArgs: []string{\"-c\", \"kubectl apply -f temp-modified-role.yaml \"},\n\t\tDescription: \"creating role [\" + role + \"] in namespace [ \" + namespace + \" ]\",\n\t}\n\n\texitCode, err := cmd.exec(debug, verbose)\n\n\tif exitCode != 0 {\n\t\treturn false, err\n\t}\n\n\tdeleteFile(\"temp-modified-role.yaml\")\n\n\treturn true, \"\"\n}", "func CreateIAMRolesDiagnostic() diagnostics.Diagnostic {\n\treturn diagnostics.Diagnostic{\n\t\tName: \"iam-roles\",\n\t\tTags: diagnostics.Tags{\"iam\"},\n\t\tSkip: func(tstCtx diagnostics.TestContext) (bool, string, error) {\n\t\t\tisV2, err := tstCtx.IsIAMV2()\n\t\t\tif err != nil {\n\t\t\t\treturn false, \"\", err\n\t\t\t}\n\n\t\t\t// the Skip function is run before each step: Generate, Verify, and Cleanup\n\t\t\tloaded := generatedRoleData{}\n\t\t\terr = tstCtx.GetValue(\"iam-roles\", &loaded)\n\t\t\tif err != nil {\n\t\t\t\t// this is the first time running this diagnostic,\n\t\t\t\t// so we save whether or not we're skipping it\n\t\t\t\ttstCtx.SetValue(\"iam-roles\", &generatedRoleData{\n\t\t\t\t\tSkipped: !isV2,\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\t// the diagnostic has been run before, so we keep track of its saved values\n\t\t\t\ttstCtx.SetValue(\"iam-roles\", &generatedRoleData{\n\t\t\t\t\tID: loaded.ID,\n\t\t\t\t\tActions: loaded.Actions,\n\t\t\t\t\tSkipped: loaded.Skipped,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\treturn !isV2, \"requires IAM v2\", nil\n\t\t},\n\t\tGenerate: func(tstCtx diagnostics.TestContext) error {\n\t\t\troleInfo, err := CreateRole(tstCtx,\n\t\t\t\tfmt.Sprintf(\"iam-roles-%s\", TimestampName()), \"system:serviceVersion:get\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tloaded := generatedRoleData{}\n\t\t\terr = tstCtx.GetValue(\"iam-roles\", &loaded)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"could not find generated context\")\n\t\t\t}\n\n\t\t\ttstCtx.SetValue(\"iam-roles\", &generatedRoleData{\n\t\t\t\tID: roleInfo.Role.ID,\n\t\t\t\tActions: roleInfo.Role.Actions,\n\t\t\t\tSkipped: loaded.Skipped,\n\t\t\t})\n\t\t\treturn nil\n\t\t},\n\t\tVerify: func(tstCtx diagnostics.VerificationTestContext) {\n\t\t\tloaded := generatedRoleData{}\n\t\t\terr := tstCtx.GetValue(\"iam-roles\", &loaded)\n\t\t\trequire.NoError(tstCtx, err, \"Could not find generated context\")\n\t\t\tif loaded.Skipped {\n\t\t\t\t// this happens in the v1->v2 force upgrade scenario:\n\t\t\t\t// when we run generate diagnostic data while on v1\n\t\t\t\t// then force-upgrade to v2\n\t\t\t\t// then run verify and cleanup on that data\n\t\t\t\t// for roles, since the Generate step was skipped\n\t\t\t\t// there is nothing to verify on v2\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\troleInfo, err := GetRole(tstCtx, loaded.ID)\n\t\t\trequire.NoError(tstCtx, err)\n\n\t\t\tassert.Equal(tstCtx, loaded.ID, roleInfo.Role.ID)\n\t\t\tassert.Equal(tstCtx, loaded.Actions, roleInfo.Role.Actions)\n\t\t},\n\t\tCleanup: func(tstCtx diagnostics.TestContext) error {\n\t\t\tloaded := generatedRoleData{}\n\t\t\terr := tstCtx.GetValue(\"iam-roles\", &loaded)\n\t\t\tif loaded.Skipped {\n\t\t\t\t// if diagnostic was run on v1, generating roles was skipped\n\t\t\t\t// so nothing to clean up here\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"Could not find generated context\")\n\t\t\t}\n\n\t\t\treturn DeleteRole(tstCtx, loaded.ID)\n\t\t},\n\t}\n}", "func CreateRole(tstCtx diagnostics.TestContext, id string, action string) (*RoleInfo, error) {\n\troleInfo := RoleInfo{}\n\terr := MustJSONDecodeSuccess(\n\t\ttstCtx.DoLBRequest(\n\t\t\t\"/apis/iam/v2/roles\",\n\t\t\tlbrequest.WithMethod(\"POST\"),\n\t\t\tlbrequest.WithJSONStringTemplateBody(createRoleTemplate, struct {\n\t\t\t\tID string\n\t\t\t\tAction string\n\t\t\t}{\n\t\t\t\tID: id,\n\t\t\t\tAction: action,\n\t\t\t}),\n\t\t)).WithValue(&roleInfo)\n\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Could not create role\")\n\t}\n\n\treturn &roleInfo, nil\n}", "func createIAMLambdaRole(ctx *pulumi.Context, name string) (*iam.Role, error) {\n\troleName := fmt.Sprintf(\"%s-task-exec-role\", name)\n\n\trole, err := iam.NewRole(ctx, roleName, &iam.RoleArgs{\n\t\tAssumeRolePolicy: pulumi.String(`{\n\t\t\t\"Version\": \"2012-10-17\",\n\t\t\t\"Statement\": [{\n\t\t\t\t\"Sid\": \"\",\n\t\t\t\t\"Effect\": \"Allow\",\n\t\t\t\t\"Principal\": {\n\t\t\t\t\t\"Service\": \"lambda.amazonaws.com\"\n\t\t\t\t},\n\t\t\t\t\"Action\": \"sts:AssumeRole\"\n\t\t\t}]\n\t\t}`),\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error create IAM role for %s: %v\", name, err)\n\t}\n\n\treturn role, nil\n}", "func createRole(ctx context.Context, cli client.Client, role *rbacv1.Role) (*rbacv1.Role, error) {\n\tif err := cli.Create(ctx, role); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create role %s/%s: %w\", role.Namespace, role.Name, err)\n\t}\n\treturn role, nil\n}", "func (s *Server) CreateRole(ctx context.Context, params *authorization.Role) (*authorization.Role, error) {\n\treturn &authorization.Role{}, nil\n}", "func (ts *tester) createRole() error {\n\tfmt.Print(ts.cfg.EKSConfig.Colorize(\"\\n\\n[yellow]*********************************\\n\"))\n\tfmt.Printf(ts.cfg.EKSConfig.Colorize(\"[light_green]createRole [default](%q)\\n\"), ts.cfg.EKSConfig.ConfigPath)\n\n\tif !ts.cfg.EKSConfig.Role.Create {\n\t\tts.cfg.Logger.Info(\"Role.Create false; skipping creation\")\n\t\treturn aws_iam.ValidateV2(\n\t\t\tts.cfg.Logger,\n\t\t\tts.cfg.IAMAPIV2,\n\t\t\tts.cfg.EKSConfig.Role.Name,\n\t\t\t[]string{\"eks.amazonaws.com\"},\n\t\t\t[]string{\n\t\t\t\t// Prior to April 16, 2020, AmazonEKSServicePolicy was also required and the suggested name was eksServiceRole. With the AWSServiceRoleForAmazonEKS service-linked role, that policy is no longer required for clusters created on or after April 16, 2020.\n\t\t\t\t// ref. https://docs.aws.amazon.com/eks/latest/userguide/service_IAM_role.html\n\t\t\t\t\"arn:aws:iam::aws:policy/AmazonEKSClusterPolicy\",\n\t\t\t},\n\t\t)\n\t}\n\tif ts.cfg.EKSConfig.Role.ARN != \"\" {\n\t\tts.cfg.Logger.Info(\"role already created; no need to create a new one\")\n\t\treturn nil\n\t}\n\tif ts.cfg.EKSConfig.Role.Name == \"\" {\n\t\treturn errors.New(\"cannot create a cluster role with an empty Role.Name\")\n\t}\n\n\tif err := ts._createRole(); err != nil {\n\t\treturn err\n\t}\n\tif err := ts.createPolicy(); err != nil {\n\t\treturn err\n\t}\n\tif err := ts.attachPolicy(); err != nil {\n\t\treturn err\n\t}\n\n\tts.cfg.Logger.Info(\"created a new role and attached policy\",\n\t\tzap.String(\"role-arn\", ts.cfg.EKSConfig.Role.ARN),\n\t\tzap.String(\"role-name\", ts.cfg.EKSConfig.Role.Name),\n\t)\n\treturn nil\n}", "func CmdCreateIAMUser(c *cli.Context) error {\n\tctx := c.Context\n\tsess := edgegrid.GetSession(ctx)\n\tclient := iam.Client(sess)\n\t// tfWorkPath is a target directory for generated terraform resources\n\tvar tfWorkPath = \"./\"\n\tif c.IsSet(\"tfworkpath\") {\n\t\ttfWorkPath = c.String(\"tfworkpath\")\n\t}\n\ttfWorkPath = filepath.FromSlash(tfWorkPath)\n\n\tgroupPath := filepath.Join(tfWorkPath, \"groups.tf\")\n\timportPath := filepath.Join(tfWorkPath, \"import.sh\")\n\trolesPath := filepath.Join(tfWorkPath, \"roles.tf\")\n\tuserPath := filepath.Join(tfWorkPath, \"user.tf\")\n\tvariablesPath := filepath.Join(tfWorkPath, \"variables.tf\")\n\n\terr := tools.CheckFiles(userPath, groupPath, rolesPath, variablesPath, importPath)\n\tif err != nil {\n\t\treturn cli.Exit(color.RedString(err.Error()), 1)\n\t}\n\n\ttemplateToFile := map[string]string{\n\t\t\"groups.tmpl\": groupPath,\n\t\t\"imports.tmpl\": importPath,\n\t\t\"roles.tmpl\": rolesPath,\n\t\t\"users.tmpl\": userPath,\n\t\t\"variables.tmpl\": variablesPath,\n\t}\n\n\tprocessor := templates.FSTemplateProcessor{\n\t\tTemplatesFS: templateFiles,\n\t\tTemplateTargets: templateToFile,\n\t}\n\n\tsection := edgegrid.GetEdgercSection(c)\n\temail := c.Args().First()\n\tif err = createIAMUserByEmail(ctx, email, section, client, processor); err != nil {\n\t\treturn cli.Exit(color.RedString(fmt.Sprintf(\"Error exporting HCL for IAM: %s\", err)), 1)\n\t}\n\treturn nil\n}", "func createRoleBinding(role string, saName string, namespace string) (bool, string) {\n\tclusterRole := false\n\tresource := \"rolebinding\"\n\n\tif role == \"cluster-admin\" {\n\t\tclusterRole = true\n\t\tresource = \"clusterrolebinding\"\n\t}\n\n\tbindingName := saName + \"-binding\"\n\tbindingOption := \"--role=\" + role\n\tif clusterRole {\n\t\tbindingOption = \"--clusterrole=\" + role\n\t\tbindingName = namespace + \":\" + saName + \"-binding\"\n\t}\n\n\tlog.Println(\"INFO: creating \" + resource + \" for service account [ \" + saName + \" ] in namespace [ \" + namespace + \" ] with role: \" + role + \".\")\n\tcmd := command{\n\t\tCmd: \"bash\",\n\t\tArgs: []string{\"-c\", \"kubectl create \" + resource + \" \" + bindingName + \" \" + bindingOption + \" --serviceaccount \" + namespace + \":\" + saName + \" -n \" + namespace},\n\t\tDescription: \"creating \" + resource + \" for service account [ \" + saName + \" ] in namespace [ \" + namespace + \" ] with role: \" + role,\n\t}\n\n\texitCode, err := cmd.exec(debug, verbose)\n\n\tif exitCode != 0 {\n\t\treturn false, err\n\t}\n\n\treturn true, \"\"\n}", "func (a *IamProjectRoleApiService) IamProjectRoleCreateExecute(r ApiIamProjectRoleCreateRequest) (*Role, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tformFiles []formFile\n\t\tlocalVarReturnValue *Role\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"IamProjectRoleApiService.IamProjectRoleCreate\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/iam/project/{projectId}/role\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"projectId\"+\"}\", url.PathEscape(parameterToString(r.projectId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\tif r.iamProjectRoleCreate == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"iamProjectRoleCreate is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.xIdempotencyKey != nil {\n\t\tlocalVarHeaderParams[\"x-idempotency-key\"] = parameterToString(*r.xIdempotencyKey, \"\")\n\t}\n\tif r.xDryRun != nil {\n\t\tlocalVarHeaderParams[\"x-dry-run\"] = parameterToString(*r.xDryRun, \"\")\n\t}\n\t// body params\n\tlocalVarPostBody = r.iamProjectRoleCreate\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\t\tvar v InlineResponseDefault\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func CreateRole(c *gin.Context) {\n\tnewRole := model.Role{}\n\tc.BindJSON(&newRole)\n\n\terr := service.CreateRole(newRole)\n\n\tif err != nil {\n\t\terror := service.GetGormErrorCode(err.Error())\n\t\tc.JSON(500, error)\n\t} else {\n\t\tc.String(200, \"ok\")\n\t}\n}", "func (rc *ResourceCommand) createRole(ctx context.Context, client auth.ClientI, raw services.UnknownResource) error {\n\trole, err := services.UnmarshalRole(raw.Raw)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\terr = role.CheckAndSetDefaults()\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\tif err := services.ValidateAccessPredicates(role); err != nil {\n\t\t// check for syntax errors in predicates\n\t\treturn trace.Wrap(err)\n\t}\n\n\twarnAboutKubernetesResources(rc.config.Log, role)\n\troleName := role.GetName()\n\t_, err = client.GetRole(ctx, roleName)\n\tif err != nil && !trace.IsNotFound(err) {\n\t\treturn trace.Wrap(err)\n\t}\n\troleExists := (err == nil)\n\tif roleExists && !rc.IsForced() {\n\t\treturn trace.AlreadyExists(\"role '%s' already exists\", roleName)\n\t}\n\tif err := client.UpsertRole(ctx, role); err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\tfmt.Printf(\"role '%s' has been %s\\n\", roleName, UpsertVerb(roleExists, rc.IsForced()))\n\treturn nil\n}", "func (a *IamProjectRoleApiService) IamProjectRoleCreate(ctx context.Context, projectId string) ApiIamProjectRoleCreateRequest {\n\treturn ApiIamProjectRoleCreateRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tprojectId: projectId,\n\t}\n}", "func CreateUserRole(w http.ResponseWriter, r *http.Request) {\n\tfLog := userMgmtLogger.WithField(\"func\", \"CreateUserRole\").WithField(\"RequestID\", r.Context().Value(constants.RequestID)).WithField(\"path\", r.URL.Path).WithField(\"method\", r.Method)\n\n\tiauthctx := r.Context().Value(constants.HansipAuthentication)\n\tif iauthctx == nil {\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusUnauthorized, \"You are not authorized to access this resource\", nil, nil)\n\t\treturn\n\t}\n\n\tparams, err := helper.ParsePathParams(fmt.Sprintf(\"%s/management/user/{userRecId}/role/{roleRecId}\", apiPrefix), r.URL.Path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\trole, err := RoleRepo.GetRoleByRecID(r.Context(), params[\"roleRecId\"])\n\tif err != nil {\n\t\tfLog.Errorf(\"RoleRepo.GetRoleByRecID got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tif role == nil {\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusNotFound, fmt.Sprintf(\"Role recid %s not found\", params[\"roleRecId\"]), nil, nil)\n\t\treturn\n\t}\n\n\tauthCtx := iauthctx.(*hansipcontext.AuthenticationContext)\n\tif !authCtx.IsAdminOfDomain(role.RoleDomain) {\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusForbidden, \"You don't have the right to access role with the specified domain\", nil, nil)\n\t\treturn\n\t}\n\n\tuser, err := UserRepo.GetUserByRecID(r.Context(), params[\"userRecId\"])\n\tif err != nil {\n\t\tfLog.Errorf(\"UserRepo.GetUserByRecID got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tif user == nil {\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusNotFound, fmt.Sprintf(\"User recid %s not found\", params[\"userRecId\"]), nil, nil)\n\t\treturn\n\t}\n\n\t_, err = UserRoleRepo.CreateUserRole(r.Context(), user, role)\n\tif err != nil {\n\t\tfLog.Errorf(\"UserRoleRepo.CreateUserRole got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tRevocationRepo.Revoke(r.Context(), user.Email)\n\thelper.WriteHTTPResponse(r.Context(), w, http.StatusOK, \"User-Role created\", nil, nil)\n}", "func (a *Client) CreateRole(params *CreateRoleParams) error {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewCreateRoleParams()\n\t}\n\n\t_, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"createRole\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/roles\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &CreateRoleReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n\n}", "func NewCmdCreateClusterRoleBinding(f cmdutil.Factory, ioStreams genericiooptions.IOStreams) *cobra.Command {\n\to := NewClusterRoleBindingOptions(ioStreams)\n\n\tcmd := &cobra.Command{\n\t\tUse: \"clusterrolebinding NAME --clusterrole=NAME [--user=username] [--group=groupname] [--serviceaccount=namespace:serviceaccountname] [--dry-run=server|client|none]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Create a cluster role binding for a particular cluster role\"),\n\t\tLong: clusterRoleBindingLong,\n\t\tExample: clusterRoleBindingExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmd.Flags().StringVar(&o.ClusterRole, \"clusterrole\", \"\", i18n.T(\"ClusterRole this ClusterRoleBinding should reference\"))\n\tcmd.MarkFlagRequired(\"clusterrole\")\n\tcmd.Flags().StringArrayVar(&o.Users, \"user\", o.Users, \"Usernames to bind to the clusterrole. The flag can be repeated to add multiple users.\")\n\tcmd.Flags().StringArrayVar(&o.Groups, \"group\", o.Groups, \"Groups to bind to the clusterrole. The flag can be repeated to add multiple groups.\")\n\tcmd.Flags().StringArrayVar(&o.ServiceAccounts, \"serviceaccount\", o.ServiceAccounts, \"Service accounts to bind to the clusterrole, in the format <namespace>:<name>. The flag can be repeated to add multiple service accounts.\")\n\tcmdutil.AddFieldManagerFlagVar(cmd, &o.FieldManager, \"kubectl-create\")\n\n\t// Completion for relevant flags\n\tcmdutil.CheckErr(cmd.RegisterFlagCompletionFunc(\n\t\t\"clusterrole\",\n\t\tfunc(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\t\t\treturn completion.CompGetResource(f, \"clusterrole\", toComplete), cobra.ShellCompDirectiveNoFileComp\n\t\t}))\n\n\treturn cmd\n}", "func NewCreate(f func(string, string, []string) (proto.Message, error)) *cobra.Command {\n\tvar (\n\t\tdisplayName string\n\t\tpermissionIDs []string\n\t)\n\n\tcmd := template.NewArg1Proto(\"create ROLE_ID\", \"Create a new role\", func(cmd *cobra.Command, arg string) (proto.Message, error) {\n\t\tvar names []string\n\t\tfor _, p := range permissionIDs {\n\t\t\tnames = append(names, fmt.Sprintf(\"permissions/%s\", p))\n\t\t}\n\t\treturn f(arg, displayName, names)\n\t})\n\n\tcmd.Flags().StringVar(&displayName, \"display-name\", \"\", \"display name\")\n\tcmd.Flags().StringSliceVar(&permissionIDs, \"permission-ids\", nil, \"permission ids\")\n\n\treturn cmd\n}", "func RoleCreate(user_id int64, level_id uint8) (sql.Result, error) {\n\tres, err := database.DB.Exec(\"INSERT INTO role (user_id, level_id) VALUES (?,?)\", user_id, level_id)\n\treturn res, err\n}", "func NewRole(ctx *pulumi.Context,\n\tname string, args *RoleArgs, opts ...pulumi.ResourceOption) (*Role, error) {\n\tif args == nil {\n\t\targs = &RoleArgs{}\n\t}\n\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Role\n\terr := ctx.RegisterResource(\"alicloud:ram/role:Role\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (r *mutationResolver) CreateRole(ctx context.Context, input *models.CreateRoleInput) (*user.Role, error) {\n\tpanic(\"not implemented\")\n}", "func RoleCreate(r *models.Role) error {\n\tif r == nil {\n\t\tlog.Error(r)\n\t}\n\n\tif r.Name != \"\" {\n\t\t// Check if role already exists\n\t\tvar count uint\n\t\tbootstrap.Db().Where(\"name = ?\", r.Name).Find(&models.Role{}).Count(&count)\n\n\t\tif count == 0 {\n\t\t\terr := bootstrap.Db().Create(&r).Error\n\t\t\tif err != nil {\n\t\t\t\treturn errors.New(err.Error())\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn errors.New(\"role with empty name if forbidden\")\n\t}\n\treturn nil\n}", "func createIstioCARole(clientset kubernetes.Interface, namespace string) error {\n\trole := rbac.Role{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"rbac.authorization.k8s.io/v1beta1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"istio-ca-role\",\n\t\t\tNamespace: namespace,\n\t\t},\n\t\tRules: []rbac.PolicyRule{\n\t\t\t{\n\t\t\t\tVerbs: []string{\"create\", \"get\", \"watch\", \"list\", \"update\"},\n\t\t\t\tAPIGroups: []string{\"\"},\n\t\t\t\tResources: []string{\"secrets\"},\n\t\t\t},\n\t\t\t{\n\t\t\t\tVerbs: []string{\"get\", \"watch\", \"list\"},\n\t\t\t\tAPIGroups: []string{\"\"},\n\t\t\t\tResources: []string{\"serviceaccounts\", \"services\", \"pods\"},\n\t\t\t},\n\t\t},\n\t}\n\tif _, err := clientset.RbacV1beta1().Roles(namespace).Create(&role); err != nil {\n\t\treturn fmt.Errorf(\"failed to create role (error: %v)\", err)\n\t}\n\treturn nil\n}", "func (c *Client) CreateChannelRole(params ...string) error {\n\treturn nil\n\n}", "func CreateRole(name string) *rbacv1.Role {\n\treturn &rbacv1.Role{\n\t\tTypeMeta: genTypeMeta(gvk.Role),\n\t\tObjectMeta: genObjectMeta(name, true),\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\t{\n\t\t\t\tAPIGroups: []string{\n\t\t\t\t\t\"\",\n\t\t\t\t},\n\t\t\t\tResources: []string{\n\t\t\t\t\t\"pods\",\n\t\t\t\t},\n\t\t\t\tVerbs: []string{\n\t\t\t\t\t\"get\",\n\t\t\t\t\t\"watch\",\n\t\t\t\t\t\"list\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func (p *planner) CreateRole(ctx context.Context, n *tree.CreateRole) (planNode, error) {\n\treturn p.CreateRoleNode(ctx, n.Name, n.IfNotExists, n.IsRole,\n\t\t\"CREATE ROLE\", n.KVOptions)\n}", "func NewOperatorIAMRole() *OperatorIAMRoleBuilder {\n\treturn &OperatorIAMRoleBuilder{}\n}", "func (a *IamProjectRoleApiService) IamProjectRoleTagCreate(ctx context.Context, projectId string, roleId string) ApiIamProjectRoleTagCreateRequest {\n\treturn ApiIamProjectRoleTagCreateRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tprojectId: projectId,\n\t\troleId: roleId,\n\t}\n}", "func (cli *Service) CreateRolePri(req *restful.Request, resp *restful.Response) {\n\n\tlanguage := util.GetActionLanguage(req)\n\townerID := util.GetOwnerID(req.Request.Header)\n\tdefErr := cli.Core.CCErr.CreateDefaultCCErrorIf(language)\n\tctx := util.GetDBContext(context.Background(), req.Request.Header)\n\tdb := cli.Instance.Clone()\n\n\tpathParams := req.PathParameters()\n\tobjID := pathParams[\"bk_obj_id\"]\n\tpropertyID := pathParams[\"bk_property_id\"]\n\tvalue, err := ioutil.ReadAll(req.Request.Body)\n\tif err != nil {\n\t\tblog.Error(\"read json data error :%v\", err)\n\t\tresp.WriteError(http.StatusBadRequest, &meta.RespError{Msg: defErr.New(common.CCErrCommHTTPReadBodyFailed, err.Error())})\n\t\treturn\n\t}\n\tvar roleJSON []string\n\terr = json.Unmarshal([]byte(value), &roleJSON)\n\tif err != nil {\n\t\tblog.Error(\"read json data error :%v\", err)\n\t\tresp.WriteError(http.StatusBadRequest, &meta.RespError{Msg: defErr.New(common.CCErrCommJSONUnmarshalFailed, err.Error())})\n\t\treturn\n\t}\n\tinput := make(map[string]interface{})\n\tinput[common.BKOwnerIDField] = ownerID\n\tinput[common.BKObjIDField] = objID\n\tinput[common.BKPropertyIDField] = propertyID\n\tinput[common.BKPrivilegeField] = roleJSON\n\tinput = util.SetModOwner(input, ownerID)\n\n\terr = db.Table(common.BKTableNamePrivilege).Insert(ctx, input)\n\tif nil != err {\n\t\tblog.Error(\"create role privilege error :%v\", err)\n\t\tresp.WriteError(http.StatusBadRequest, &meta.RespError{Msg: defErr.New(common.CCErrObjectDBOpErrno, err.Error())})\n\t\treturn\n\t}\n\n\tresp.WriteEntity(meta.Response{BaseResp: meta.SuccessBaseResp})\n}", "func (client *Client) CreateRole(role *graylog.Role) (*ErrorInfo, error) {\n\treturn client.CreateRoleContext(context.Background(), role)\n}", "func createIAMPolicyAndRoleOrDie(iamSvc *iam.IAM, policyDocument, policyName, roleName, account, issuer, serviceAccountName, serviceAccountNamespace string) (clean func()) {\n\taction := fmt.Sprintf(\"Creating IAM policy %v\", policyName)\n\tginkgo.By(action)\n\tframework.Logf(\"PolicyDocument:\\n %v\", policyDocument)\n\tcreatePolicyOut, err := iamSvc.CreatePolicy(&iam.CreatePolicyInput{\n\t\tPolicyDocument: aws.String(policyDocument),\n\t\tPolicyName: aws.String(policyName),\n\t})\n\tframework.ExpectNoError(err, action)\n\tpolicyArn := *createPolicyOut.Policy.Arn\n\n\taction = fmt.Sprintf(\"Creating IAM role %v\", roleName)\n\tginkgo.By(action)\n\ttrustDocument := strings.ReplaceAll(trustDocumentTemplate, \"${AWS_ACCOUNT_ID}\", account)\n\ttrustDocument = strings.ReplaceAll(trustDocument, \"${OIDC_PROVIDER}\", strings.ReplaceAll(issuer, \"https://\", \"\"))\n\ttrustDocument = strings.ReplaceAll(trustDocument, \"${SERVICE_ACCOUNT_NAMESPACE}\", serviceAccountNamespace)\n\ttrustDocument = strings.ReplaceAll(trustDocument, \"${SERVICE_ACCOUNT_NAME}\", serviceAccountName)\n\tframework.Logf(\"AssumeRolePolicyDocument:\\n %v\", trustDocument)\n\t_, err = iamSvc.CreateRole(&iam.CreateRoleInput{\n\t\tAssumeRolePolicyDocument: aws.String(trustDocument),\n\t\tRoleName: aws.String(roleName),\n\t})\n\tframework.ExpectNoError(err, action)\n\n\taction = fmt.Sprintf(\"Attaching IAM policy %v to IAM role %v\", policyArn, roleName)\n\tginkgo.By(action)\n\t_, err = iamSvc.AttachRolePolicy(&iam.AttachRolePolicyInput{\n\t\tPolicyArn: aws.String(policyArn),\n\t\tRoleName: aws.String(roleName),\n\t})\n\tframework.ExpectNoError(err, action)\n\n\treturn func() {\n\t\tginkgo.By(fmt.Sprintf(\"Detaching IAM policy %v from IAM role %v\", policyArn, roleName))\n\t\t_, err := iamSvc.DetachRolePolicy(&iam.DetachRolePolicyInput{\n\t\t\tPolicyArn: aws.String(policyArn),\n\t\t\tRoleName: aws.String(roleName),\n\t\t})\n\t\tif err != nil {\n\t\t\tframework.Logf(\"Error detaching IAM policy: %v\", err)\n\t\t}\n\n\t\tginkgo.By(fmt.Sprintf(\"Deleting IAM role %v\", roleName))\n\t\t_, err = iamSvc.DeleteRole(&iam.DeleteRoleInput{\n\t\t\tRoleName: aws.String(roleName),\n\t\t})\n\t\tif err != nil {\n\t\t\tframework.Logf(\"Error deleting IAM role: %v\", err)\n\t\t}\n\n\t\tginkgo.By(fmt.Sprintf(\"Deleting IAM policy %v\", policyArn))\n\t\t_, err = iamSvc.DeletePolicy(&iam.DeletePolicyInput{\n\t\t\tPolicyArn: aws.String(policyArn),\n\t\t})\n\t\tif err != nil {\n\t\t\tframework.Logf(\"Error deleting IAM policy: %v\", err)\n\t\t}\n\t}\n}", "func (aaa *RolesService) CreateRole(input *roles.CreateRoleParams) (*iamclientmodels.AccountcommonRole, error) {\n\ttoken, err := aaa.TokenRepository.GetToken()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcreated, badRequest, unauthorized, forbidden, err := aaa.Client.Roles.CreateRole(input, client.BearerToken(*token.AccessToken))\n\tif badRequest != nil {\n\t\treturn nil, badRequest\n\t}\n\tif unauthorized != nil {\n\t\treturn nil, unauthorized\n\t}\n\tif forbidden != nil {\n\t\treturn nil, forbidden\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn created.GetPayload(), nil\n}", "func (client *Client) CreateRoleContext(\n\tctx context.Context, role *graylog.Role,\n) (*ErrorInfo, error) {\n\tif role == nil {\n\t\treturn nil, fmt.Errorf(\"role is nil\")\n\t}\n\treturn client.callPost(ctx, client.Endpoints().Roles(), role, role)\n}", "func (a *IamProjectRoleApiService) IamProjectRolePermissionCreateExecute(r ApiIamProjectRolePermissionCreateRequest) (*IamPermission, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tformFiles []formFile\n\t\tlocalVarReturnValue *IamPermission\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"IamProjectRoleApiService.IamProjectRolePermissionCreate\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/iam/project/{projectId}/role/{roleId}/permission\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"projectId\"+\"}\", url.PathEscape(parameterToString(r.projectId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"roleId\"+\"}\", url.PathEscape(parameterToString(r.roleId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\tif r.iamPermission == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"iamPermission is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.iamPermission\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\t\tvar v InlineResponseDefault\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (a *IamProjectRoleApiService) IamProjectRolePermissionCreate(ctx context.Context, projectId string, roleId string) ApiIamProjectRolePermissionCreateRequest {\n\treturn ApiIamProjectRolePermissionCreateRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tprojectId: projectId,\n\t\troleId: roleId,\n\t}\n}", "func createDatabaseRoles(ctx context.Context, client kubernetes.Interface, f flags) error {\n\tif err := createServiceAccount(ctx, client, appdbServiceAccount, f.memberClusterNamespace); err != nil {\n\t\treturn err\n\t}\n\tif err := createServiceAccount(ctx, client, databasePodsServiceAccount, f.memberClusterNamespace); err != nil {\n\t\treturn err\n\t}\n\tif err := createServiceAccount(ctx, client, opsManagerServiceAccount, f.memberClusterNamespace); err != nil {\n\t\treturn err\n\t}\n\tif err := createDatabaseRole(ctx, client, appdbRole, f.memberClusterNamespace); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (db *MySQLDB) CreateRole(ctx context.Context, roleName, roleDomain, description string) (*Role, error) {\n\tfLog := mysqlLog.WithField(\"func\", \"CreateRole\").WithField(\"RequestID\", ctx.Value(constants.RequestID))\n\tr := &Role{\n\t\tRecID: helper.MakeRandomString(10, true, true, true, false),\n\t\tRoleName: roleName,\n\t\tRoleDomain: roleDomain,\n\t\tDescription: description,\n\t}\n\tq := \"INSERT INTO HANSIP_ROLE(REC_ID, ROLE_NAME,ROLE_DOMAIN, DESCRIPTION) VALUES (?,?,?,?)\"\n\t_, err := db.instance.ExecContext(ctx, q, r.RecID, roleName, roleDomain, description)\n\tif err != nil {\n\t\tfLog.Errorf(\"db.instance.ExecContext got %s. SQL = %s\", err.Error(), q)\n\t\treturn nil, &ErrDBExecuteError{\n\t\t\tWrapped: err,\n\t\t\tMessage: \"Error CreateRole\",\n\t\t\tSQL: q,\n\t\t}\n\t}\n\treturn r, nil\n}", "func (c Client) Create(input *CreateRoleInput) (*CreateRoleResponse, error) {\n\treturn c.CreateWithContext(context.Background(), input)\n}", "func GenerateRoleName(serviceAccountName string) string {\n\treturn fmt.Sprintf(\"karmada-controller-manager:%s\", serviceAccountName)\n}", "func newAssign() *cobra.Command {\n\tvar cluster []string\n\tvar timeout time.Duration\n\n\troles := map[string]int{\n\t\tclient.Voter.String(): int(Voter),\n\t\tclient.Spare.String(): int(Spare),\n\t\tclient.StandBy.String(): int(Standby),\n\t}\n\tchoices := &FlagChoice{choices: mapKeys(roles), chosen: client.Voter.String()}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"assign <id>\",\n\t\tShort: \"assign a role to a node (voter, spare, or standby).\",\n\t\tArgs: cobra.MinimumNArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tr, err := nodeRole(choices.chosen)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\t\t\tdefer cancel()\n\n\t\t\tfor _, arg := range args {\n\t\t\t\tid, err := strconv.ParseUint(arg, 10, 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalln(err)\n\t\t\t\t}\n\t\t\t\tif err := Assign(ctx, &globalKeys, uint64(id), client.NodeRole(r), cluster); err != nil {\n\t\t\t\t\tlog.Fatalln(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\tflags := cmd.Flags()\n\tflags.StringSliceVarP(&cluster, \"cluster\", \"c\", clusterList(), \"addresses of existing cluster nodes\")\n\tflags.DurationVarP(&timeout, \"timeout\", \"t\", time.Second*60, \"time to wait for transfer to complete\")\n\tflags.VarP(choices, \"role\", \"r\", \"server role\")\n\treturn cmd\n}", "func (a *IamProjectRoleApiService) IamProjectRoleTagCreateExecute(r ApiIamProjectRoleTagCreateRequest) (*Tag, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tformFiles []formFile\n\t\tlocalVarReturnValue *Tag\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"IamProjectRoleApiService.IamProjectRoleTagCreate\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/iam/project/{projectId}/role/{roleId}/tag\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"projectId\"+\"}\", url.PathEscape(parameterToString(r.projectId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"roleId\"+\"}\", url.PathEscape(parameterToString(r.roleId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\tif r.tag == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"tag is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.tag\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\t\tvar v InlineResponseDefault\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func NewCreateOIDCIssuerCmd() *cobra.Command {\n\tcreateOIDCIssuerCmd := &cobra.Command{\n\t\tUse: \"create-oidc-issuer --name NAME --region REGION --subscription-id SUBSCRIPTION_ID --tenant-id TENANT_ID --public-key-file PUBLIC_KEY_FILE\",\n\t\tShort: \"Create OIDC Issuer\",\n\t\tRun: createOIDCIssuerCmd,\n\t\tPersistentPreRun: initEnvForCreateOIDCIssuerCmd,\n\t}\n\n\t// Required parameters\n\tcreateOIDCIssuerCmd.PersistentFlags().StringVar(\n\t\t&CreateOIDCIssuerOpts.Name,\n\t\t\"name\",\n\t\t\"\",\n\t\t\"User-defined name for all created Azure resources. This user-defined name can be separate from the cluster's infra-id. \"+\n\t\t\tfmt.Sprintf(\"Azure resources created by ccoctl will be tagged with '%s_NAME = %s'\", ownedAzureResourceTagKeyPrefix, ownedAzureResourceTagValue),\n\t)\n\tcreateOIDCIssuerCmd.MarkPersistentFlagRequired(\"name\")\n\tcreateOIDCIssuerCmd.PersistentFlags().StringVar(&CreateOIDCIssuerOpts.Region, \"region\", \"\", \"Azure region in which to create identity provider infrastructure\")\n\tcreateOIDCIssuerCmd.MarkPersistentFlagRequired(\"region\")\n\tcreateOIDCIssuerCmd.PersistentFlags().StringVar(&CreateOIDCIssuerOpts.SubscriptionID, \"subscription-id\", \"\", \"Azure Subscription ID within which to create identity provider infrastructure\")\n\tcreateOIDCIssuerCmd.MarkPersistentFlagRequired(\"subscription-id\")\n\tcreateOIDCIssuerCmd.PersistentFlags().StringVar(&CreateOIDCIssuerOpts.TenantID, \"tenant-id\", \"\", \"Azure Tenant ID in which identity provider infrastructure will be created\")\n\tcreateOIDCIssuerCmd.MarkPersistentFlagRequired(\"tenant-id\")\n\tcreateOIDCIssuerCmd.PersistentFlags().StringVar(&CreateOIDCIssuerOpts.PublicKeyPath, \"public-key-file\", \"\", \"Path to public ServiceAccount signing key\")\n\tcreateOIDCIssuerCmd.MarkPersistentFlagRequired(\"public-key-file\")\n\n\t// Optional parameters\n\tcreateOIDCIssuerCmd.PersistentFlags().StringVar(\n\t\t&CreateOIDCIssuerOpts.OIDCResourceGroupName,\n\t\t\"oidc-resource-group-name\",\n\t\t\"\",\n\t\t// FIXME: Say what the default is gonna be, ie -oidc appended to the --name.\n\t\t\"The Azure resource group in which to create OIDC infrastructure including a storage account, blob storage container and user-assigned managed identities. \"+\n\t\t\t\"A resource group will be created with a name derived from the --name parameter if an --oidc-resource-group-name parameter was not provided.\",\n\t)\n\tcreateOIDCIssuerCmd.PersistentFlags().StringVar(\n\t\t&CreateOIDCIssuerOpts.StorageAccountName,\n\t\t\"storage-account-name\",\n\t\t\"\",\n\t\t\"The name of the Azure storage account in which to create OIDC issuer infrastructure. \"+\n\t\t\t\"A storage account will be created with a name derived from the --name parameter if a --storage-account-name parameter was not provided. \"+\n\t\t\t\"The storage account will be created within the OIDC resource group identified by the --oidc-resource-group-name parameter. \"+\n\t\t\t\"If pre-existing, the storage account must exist within the OIDC resource group identified by the --oidc-resource-group-name parameter. \"+\n\t\t\t\"Azure storage account names must be between 3 and 24 characters in length and may contain numbers and lowercase letters only.\",\n\t)\n\tcreateOIDCIssuerCmd.PersistentFlags().StringVar(\n\t\t&CreateOIDCIssuerOpts.BlobContainerName,\n\t\t\"blob-container-name\",\n\t\t\"\",\n\t\t\"The name of the Azure blob container in which to upload OIDC discovery documents. \"+\n\t\t\t\"A blob container will be created with a name derived from the --name parameter if a --blob-container-name parameter was not provided. \"+\n\t\t\t\"The blob container will be created within the OIDC resource group identified by the --oidc-resource-group-name parameter \"+\n\t\t\t\"and storage account identified by --storage-account-name.\",\n\t)\n\tcreateOIDCIssuerCmd.PersistentFlags().BoolVar(&CreateOIDCIssuerOpts.DryRun, \"dry-run\", false, \"Skip creating objects, and just save what would have been created into files\")\n\tcreateOIDCIssuerCmd.PersistentFlags().StringVar(&CreateOIDCIssuerOpts.OutputDir, \"output-dir\", \"\", \"Directory to place generated manifest files. Defaults to the current directory.\")\n\tcreateOIDCIssuerCmd.PersistentFlags().StringToStringVar(&CreateOIDCIssuerOpts.UserTags, \"user-tags\", map[string]string{}, \"User tags to be applied to Azure resources, multiple tags may be specified comma-separated for example: --user-tags key1=value1,key2=value2\")\n\n\treturn createOIDCIssuerCmd\n}", "func NewRole() *Role {\n\treturn &Role{}\n}", "func newAWSCommand() *cobra.Command {\n\tvar (\n\t\tclusterName string\n\t\troleARN string\n\t)\n\tvar command = &cobra.Command{\n\t\tUse: \"aws\",\n\t\tRun: func(c *cobra.Command, args []string) {\n\t\t\tctx := c.Context()\n\n\t\t\tpresignedURLString, err := getSignedRequestWithRetry(ctx, time.Minute, 5*time.Second, clusterName, roleARN, getSignedRequest)\n\t\t\terrors.CheckError(err)\n\t\t\ttoken := v1Prefix + base64.RawURLEncoding.EncodeToString([]byte(presignedURLString))\n\t\t\t// Set token expiration to 1 minute before the presigned URL expires for some cushion\n\t\t\ttokenExpiration := time.Now().Local().Add(presignedURLExpiration - 1*time.Minute)\n\t\t\t_, _ = fmt.Fprint(os.Stdout, formatJSON(token, tokenExpiration))\n\t\t},\n\t}\n\tcommand.Flags().StringVar(&clusterName, \"cluster-name\", \"\", \"AWS Cluster name\")\n\tcommand.Flags().StringVar(&roleARN, \"role-arn\", \"\", \"AWS Role ARN\")\n\treturn command\n}", "func main() {\n\tcode_generator.Generate(\"./\", \"github.com/jimersylee/iris-seed\", code_generator.GetGenerateStruct(&models.Role{}))\n}", "func (*CreateRoleNode) Next(runParams) (bool, error) { return false, nil }", "func desiredRole(name string, contour *operatorv1alpha1.Contour) *rbacv1.Role {\n\trole := &rbacv1.Role{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"Role\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: contour.Spec.Namespace.Name,\n\t\t\tName: name,\n\t\t},\n\t}\n\tgroupAll := []string{\"\"}\n\tverbCU := []string{\"create\", \"update\"}\n\tsecret := rbacv1.PolicyRule{\n\t\tVerbs: verbCU,\n\t\tAPIGroups: groupAll,\n\t\tResources: []string{\"secrets\"},\n\t}\n\trole.Rules = []rbacv1.PolicyRule{secret}\n\trole.Labels = map[string]string{\n\t\toperatorv1alpha1.OwningContourNameLabel: contour.Name,\n\t\toperatorv1alpha1.OwningContourNsLabel: contour.Namespace,\n\t}\n\treturn role\n}", "func NewRole(client client.Client, role rbacv1.Role) (Role, error) {\n\tcreatedRole, err := client.Kubernetes.\n\t\tRbacV1().\n\t\tRoles(role.Namespace).\n\t\tCreate(client.Ctx, &role, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn Role{}, fmt.Errorf(\"failed to create role %s in namespace %s: %w\", role.Name, role.Namespace, err)\n\t}\n\n\treturn Role{\n\t\tRole: *createdRole,\n\t\tclient: client,\n\t}, nil\n}", "func ensureIAMRoleForCustomResource(awsPrincipalName string,\n\tsourceArn *gocf.StringExpr,\n\ttemplate *gocf.Template,\n\tlogger *logrus.Logger) (string, error) {\n\n\tvar principalActions []string\n\tswitch awsPrincipalName {\n\tcase cloudformationresources.SNSLambdaEventSource:\n\t\tprincipalActions = PushSourceConfigurationActions.SNSLambdaEventSource\n\tcase cloudformationresources.S3LambdaEventSource:\n\t\tprincipalActions = PushSourceConfigurationActions.S3LambdaEventSource\n\tcase cloudformationresources.SESLambdaEventSource:\n\t\tprincipalActions = PushSourceConfigurationActions.SESLambdaEventSource\n\tcase cloudformationresources.CloudWatchLogsLambdaEventSource:\n\t\tprincipalActions = PushSourceConfigurationActions.CloudWatchLogsLambdaEventSource\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"Unsupported principal for IAM role creation: %s\", awsPrincipalName)\n\t}\n\n\t// What's the stable IAMRoleName?\n\tresourceBaseName := fmt.Sprintf(\"CustomResource%sIAMRole\", awsPrincipalToService(awsPrincipalName))\n\tstableRoleName := CloudFormationResourceName(resourceBaseName, awsPrincipalName)\n\n\t// Ensure it exists, then check to see if this Source ARN is already specified...\n\t// Checking equality with Stringable?\n\n\t// Create a new Role\n\tvar existingIAMRole *gocf.IAMRole\n\texistingResource, exists := template.Resources[stableRoleName]\n\tlogger.WithFields(logrus.Fields{\n\t\t\"PrincipalActions\": principalActions,\n\t\t\"SourceArn\": sourceArn,\n\t}).Debug(\"Ensuring IAM Role results\")\n\n\tif !exists {\n\t\t// Insert the IAM role here. We'll walk the policies data in the next section\n\t\t// to make sure that the sourceARN we have is in the list\n\t\tstatements := CommonIAMStatements.Core\n\n\t\tiamPolicyList := gocf.IAMRolePolicyList{}\n\t\tiamPolicyList = append(iamPolicyList,\n\t\t\tgocf.IAMRolePolicy{\n\t\t\t\tPolicyDocument: ArbitraryJSONObject{\n\t\t\t\t\t\"Version\": \"2012-10-17\",\n\t\t\t\t\t\"Statement\": statements,\n\t\t\t\t},\n\t\t\t\tPolicyName: gocf.String(fmt.Sprintf(\"%sPolicy\", stableRoleName)),\n\t\t\t},\n\t\t)\n\n\t\texistingIAMRole = &gocf.IAMRole{\n\t\t\tAssumeRolePolicyDocument: AssumePolicyDocument,\n\t\t\tPolicies: &iamPolicyList,\n\t\t}\n\t\ttemplate.AddResource(stableRoleName, existingIAMRole)\n\n\t\t// Create a new IAM Role resource\n\t\tlogger.WithFields(logrus.Fields{\n\t\t\t\"RoleName\": stableRoleName,\n\t\t}).Debug(\"Inserting IAM Role\")\n\t} else {\n\t\texistingIAMRole = existingResource.Properties.(*gocf.IAMRole)\n\t}\n\n\t// Walk the existing statements\n\tif nil != existingIAMRole.Policies {\n\t\tfor _, eachPolicy := range *existingIAMRole.Policies {\n\t\t\tpolicyDoc := eachPolicy.PolicyDocument.(ArbitraryJSONObject)\n\t\t\tstatements := policyDoc[\"Statement\"]\n\t\t\tfor _, eachStatement := range statements.([]spartaIAM.PolicyStatement) {\n\t\t\t\tif sourceArn.String() == eachStatement.Resource.String() {\n\n\t\t\t\t\tlogger.WithFields(logrus.Fields{\n\t\t\t\t\t\t\"RoleName\": stableRoleName,\n\t\t\t\t\t\t\"SourceArn\": sourceArn.String(),\n\t\t\t\t\t}).Debug(\"SourceArn already exists for IAM Policy\")\n\t\t\t\t\treturn stableRoleName, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlogger.WithFields(logrus.Fields{\n\t\t\t\"RoleName\": stableRoleName,\n\t\t\t\"Action\": principalActions,\n\t\t\t\"Resource\": sourceArn,\n\t\t}).Debug(\"Inserting Actions for configuration ARN\")\n\n\t\t// Add this statement to the first policy, iff the actions are non-empty\n\t\tif len(principalActions) > 0 {\n\t\t\trootPolicy := (*existingIAMRole.Policies)[0]\n\t\t\trootPolicyDoc := rootPolicy.PolicyDocument.(ArbitraryJSONObject)\n\t\t\trootPolicyStatements := rootPolicyDoc[\"Statement\"].([]spartaIAM.PolicyStatement)\n\t\t\trootPolicyDoc[\"Statement\"] = append(rootPolicyStatements, spartaIAM.PolicyStatement{\n\t\t\t\tEffect: \"Allow\",\n\t\t\t\tAction: principalActions,\n\t\t\t\tResource: sourceArn,\n\t\t\t})\n\t\t}\n\n\t\treturn stableRoleName, nil\n\t}\n\n\treturn \"\", fmt.Errorf(\"Unable to find Policies entry for IAM role: %s\", stableRoleName)\n}", "func (client *RestClient) CreateRole(role *corev2.Role) error {\n\treturn client.Post(RolesPath(role.Namespace), role)\n}", "func createIstioCARoleBinding(clientset kubernetes.Interface, namespace string) error {\n\trolebinding := rbac.RoleBinding{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"rbac.authorization.k8s.io/v1beta1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"istio-ca-role-binding\",\n\t\t\tNamespace: namespace,\n\t\t},\n\t\tSubjects: []rbac.Subject{\n\t\t\t{\n\t\t\t\tKind: \"ServiceAccount\",\n\t\t\t\tName: \"default\",\n\t\t\t\tNamespace: namespace,\n\t\t\t},\n\t\t},\n\t\tRoleRef: rbac.RoleRef{\n\t\t\tKind: \"Role\",\n\t\t\tName: \"istio-ca-role\",\n\t\t\tAPIGroup: \"rbac.authorization.k8s.io\",\n\t\t},\n\t}\n\t_, err := clientset.RbacV1beta1().RoleBindings(namespace).Create(&rolebinding)\n\treturn err\n}", "func newRole(name, desc string) *Role {\n\tvar r = &Role{Name: name, Desc: oneline(desc)}\n\troles[name] = r\n\treturn r\n}", "func newCreateIdentityCmd(f cmdutil.Factory, out io.Writer, errOut io.Writer) *cobra.Command {\n\tnewOptions := func() *createIdentityOptions {\n\t\treturn &createIdentityOptions{\n\t\t\tedgeOptions: edgeOptions{\n\t\t\t\tCommonOptions: common.CommonOptions{Factory: f, Out: out, Err: errOut},\n\t\t\t},\n\t\t}\n\t}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"identity\",\n\t\tShort: \"creates a new identity managed by the Ziti Edge Controller\",\n\t\tLong: \"creates a new identity managed by the Ziti Edge Controller\",\n\t}\n\n\tcmd.AddCommand(newCreateIdentityOfTypeCmd(\"device\", newOptions()))\n\tcmd.AddCommand(newCreateIdentityOfTypeCmd(\"user\", newOptions()))\n\tcmd.AddCommand(newCreateIdentityOfTypeCmd(\"service\", newOptions()))\n\n\treturn cmd\n}", "func NewEnsureIAMRoleAction(creationContext *EksClusterCreateUpdateContext, roleName string) *EnsureIAMRoleAction {\n\treturn &EnsureIAMRoleAction{\n\t\tcontext: creationContext,\n\t\troleName: roleName,\n\t\trolesToAttach: []string{\n\t\t\t\"arn:aws:iam::aws:policy/AmazonEKSClusterPolicy\",\n\t\t\t\"arn:aws:iam::aws:policy/AmazonEKSServicePolicy\",\n\t\t},\n\t\tsuccessfullyAttachedRoles: []string{},\n\t}\n}", "func createRBAC(sa string, namespace string, role string, roleTemplateFile string) (bool, string) {\n\tvar ok bool\n\tvar err string\n\tif role == \"\" {\n\t\tif namespace == \"kube-system\" {\n\t\t\trole = \"cluster-admin\"\n\t\t} else {\n\t\t\trole = \"helmsman-tiller\"\n\t\t}\n\t}\n\tif ok, err = createServiceAccount(sa, namespace); ok {\n\t\tif role == \"cluster-admin\" || (role == \"\" && namespace == \"kube-system\") {\n\t\t\tif ok, err = createRoleBinding(role, sa, namespace); ok {\n\t\t\t\treturn true, \"\"\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\t\tif ok, err = createRole(namespace, role, roleTemplateFile); ok {\n\t\t\tif ok, err = createRoleBinding(role, sa, namespace); ok {\n\t\t\t\treturn true, \"\"\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\n\t\treturn false, err\n\t}\n\treturn false, err\n}", "func NewRole(id string) Role {\n\trole := &StdRole{\n\t\tIdStr: id,\n\t\tpermissions: make(Permissions),\n\t\tparents: make(Roles),\n\t}\n\treturn role\n}", "func CreateRole(c RoleCreated) (int, error) {\n\tq := `INSERT INTO roles(name, parent_id) \n\t\t VALUES($1, $2) RETURNING id`\n\tdb := GetConnection()\n\n\tdefer db.Close()\n\tvar id int = 0\n\terr := db.QueryRow(q, c.Name, c.ParentId).Scan(&id)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn id, nil\n}", "func GenerateNewLambdaRoleName(region, name *string) string {\n\treturn fmt.Sprintf(\"%s-%s-%s\", constants.CommonNamePrefix, *name, *region)\n}", "func NewRoleAttribute(value interface{}) (*Attribute, error) {\n\treturn NewNamedAttribute(AttrRole, value)\n}", "func CreateRBACRoleBindingOp(apiserver *cke.Node) cke.Operator {\n\treturn &createRBACRoleBindingOp{\n\t\tapiserver: apiserver,\n\t}\n}", "func (s *projService) CreateProjectRoleType(ctx context.Context, req *pb.CreateProjectRoleTypeRequest) (*pb.CreateProjectRoleTypeResponse, error) {\n\tresp := &pb.CreateProjectRoleTypeResponse{}\n\tif !nameValidator.MatchString(req.GetRoleName()) {\n\t\tresp.ErrorCode = 510\n\t\tresp.ErrorMessage = \"name invalid format\"\n\t\treturn resp, nil\n\t}\n\n\tdesc := strings.TrimSpace(req.GetDescription())\n\tif desc == \"\" {\n\t\tresp.ErrorCode = 510\n\t\tresp.ErrorMessage = \"description missing\"\n\t\treturn resp, nil\n\t}\n\n\tsqlstring := `INSERT INTO tb_ProjectRoleType\n\t(intProjectRoleId, dtmCreated, dtmModified, dtmDeleted, bitIsDeleted, intVersion, inbMserviceId, chvRoleName, chvDescription)\n\tVALUES(?, NOW(), NOW(), NOW(), 0, 1, ?, ?, ?)`\n\n\tstmt, err := s.db.Prepare(sqlstring)\n\tif err != nil {\n\t\tlevel.Error(s.logger).Log(\"what\", \"Prepare\", \"error\", err)\n\t\tresp.ErrorCode = 500\n\t\tresp.ErrorMessage = \"db.Prepare failed\"\n\t\treturn resp, nil\n\t}\n\n\tdefer stmt.Close()\n\n\t_, err = stmt.Exec(req.GetProjectRoleId(), req.GetMserviceId(), req.GetRoleName(), desc)\n\tif err == nil {\n\t\tresp.Version = 1\n\t} else {\n\t\tresp.ErrorCode = 501\n\t\tresp.ErrorMessage = err.Error()\n\t\tlevel.Error(s.logger).Log(\"what\", \"Exec\", \"error\", err)\n\t\terr = nil\n\t}\n\n\treturn resp, err\n}", "func verifyIAMRoles(ctx *workflowContext) (workflowStep, error) {\n\t// The map is either a literal Arn from a pre-existing role name\n\t// or a ArbitraryJSONObject{\n\t// \t\"Fn::GetAtt\": []string{iamRoleDefinitionName, \"Arn\"},\n\t// }\n\n\t// Don't verify them, just create them...\n\tctx.logger.Info(\"Verifying IAM Lambda execution roles\")\n\tctx.lambdaIAMRoleNameMap = make(map[string]interface{}, 0)\n\tsvc := iam.New(ctx.awsSession)\n\n\tfor _, eachLambda := range ctx.lambdaAWSInfos {\n\t\tif \"\" != eachLambda.RoleName && nil != eachLambda.RoleDefinition {\n\t\t\treturn nil, fmt.Errorf(\"Both RoleName and RoleDefinition defined for lambda: %s\", eachLambda.lambdaFnName)\n\t\t}\n\n\t\t// Get the IAM role name\n\t\tif \"\" != eachLambda.RoleName {\n\t\t\t_, exists := ctx.lambdaIAMRoleNameMap[eachLambda.RoleName]\n\t\t\tif !exists {\n\t\t\t\t// Check the role\n\t\t\t\tparams := &iam.GetRoleInput{\n\t\t\t\t\tRoleName: aws.String(eachLambda.RoleName),\n\t\t\t\t}\n\t\t\t\tctx.logger.Debug(\"Checking IAM RoleName: \", eachLambda.RoleName)\n\t\t\t\tresp, err := svc.GetRole(params)\n\t\t\t\tif err != nil {\n\t\t\t\t\tctx.logger.Error(err.Error())\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\t// Cache it - we'll need it later when we create the\n\t\t\t\t// CloudFormation template which needs the execution Arn (not role)\n\t\t\t\tctx.lambdaIAMRoleNameMap[eachLambda.RoleName] = *resp.Role.Arn\n\t\t\t}\n\t\t} else {\n\t\t\tlogicalName := eachLambda.RoleDefinition.logicalName()\n\t\t\t_, exists := ctx.lambdaIAMRoleNameMap[logicalName]\n\t\t\tif !exists {\n\t\t\t\t// Insert it into the resource creation map and add\n\t\t\t\t// the \"Ref\" entry to the hashmap\n\t\t\t\tctx.cloudformationResources[logicalName] = eachLambda.RoleDefinition.rolePolicy(eachLambda.EventSourceMappings, ctx.logger)\n\n\t\t\t\tctx.lambdaIAMRoleNameMap[logicalName] = ArbitraryJSONObject{\n\t\t\t\t\t\"Fn::GetAtt\": []string{logicalName, \"Arn\"},\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tctx.logger.Info(\"IAM roles verified. Count: \", len(ctx.lambdaIAMRoleNameMap))\n\treturn createPackageStep(), nil\n}", "func NewRole() *Role {\n\tt := &Role{\n\t\tPermissions: []string{},\n\t}\n\treturn t\n}", "func New() *Role {\n\treturn &Role{}\n}", "func NewAdd(f func(string, string) (proto.Message, error)) *cobra.Command {\n\tvar (\n\t\trole string\n\t\tuser string\n\t)\n\n\tcmd := template.NewArg0Proto(\"add\", \"Add a new role binding\", func(cmd *cobra.Command) (proto.Message, error) {\n\t\treturn f(role, user)\n\t})\n\n\tcmd.Flags().StringVar(&role, \"role\", \"\", \"role name\")\n\tcmd.Flags().StringVar(&user, \"user\", \"\", \"user name\")\n\n\treturn cmd\n}", "func NewRole(id string, name string, typeVal Type, actions []string, projects []string) (*Role, error) {\n\trole := &Role{\n\t\tID: id,\n\t\tName: name,\n\t\tType: typeVal,\n\t\tActions: actions,\n\t\tProjects: projects,\n\t}\n\n\treturn role, nil\n}", "func (s *Store) CreateRole(ctx context.Context, role *Role) (*Role, error) {\n\terr := role.Validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult, err := sqlx.NamedExecContext(\n\t\tctx,\n\t\ts.db,\n\t\t\"INSERT INTO roles (name) VALUES (:name)\",\n\t\t&role)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, errors.ErrorUnknown, \"\")\n\t}\n\n\tid, err := result.LastInsertId()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, errors.ErrorUnknown, \"\")\n\t}\n\treturn s.FindRoleByID(ctx, id)\n}", "func createCommand() cli.Command {\n\treturn cli.Command{\n\t\tName: \"create\",\n\t\tBefore: survey.RequireGlobalFlagsFunc(requiredFlags...),\n\t\tAction: create(),\n\t}\n}", "func NewRole(f *RolePostForm, t time.Time) *Role {\n\trole := Role{\n\t\tID: f.ID,\n\t\tName: f.Name,\n\t\tPassword: f.Password,\n\t\tRegDate: t}\n\n\treturn &role\n}", "func (handler httpRole) New() httphandler.HandlerFunc {\n\ttype Req struct {\n\t\tName string `binding:\"required\"`\n\t\tDescription string `binding:\"required\"`\n\t\tIcon string `binding:\"required\"`\n\t}\n\tresp := jsont.F{\n\t\t\"ID\": nil,\n\t\t\"UpdatedAt\": nil,\n\t\t\"Status\": nil,\n\t\t\"RecordActions\": nil,\n\t}\n\treturn func(c *httphandler.Context) {\n\t\treq := Req{}\n\t\tif c.BindJSON(&req) {\n\t\t\treturn\n\t\t}\n\n\t\trec := coremodel.Role{\n\t\t\tName: req.Name,\n\t\t\tDescription: req.Description,\n\t\t\tIcon: req.Icon,\n\t\t}\n\t\tbiz := corebiz.NewBizRole()\n\t\ttx := c.BeginTx(handler.DB)\n\t\terr := biz.New(c, tx.Tx, &rec)\n\t\tif c.HandleError(err) {\n\t\t\ttx.Rollback(c)\n\t\t\treturn\n\t\t}\n\t\ttx.Commit(c)\n\t\tc.JSONWithFields(rec, resp)\n\t}\n}", "func NewValidateIAMRoleActivity(awsSessionFactory *awsworkflow.AWSSessionFactory) *ValidateIAMRoleActivity {\n\treturn &ValidateIAMRoleActivity{\n\t\tawsSessionFactory: awsSessionFactory,\n\t}\n}", "func newRoleBinding(cr *argoprojv1a1.ArgoCD) *v1.RoleBinding {\n\treturn &v1.RoleBinding{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cr.Name,\n\t\t\tLabels: argoutil.LabelsForCluster(cr),\n\t\t\tAnnotations: argoutil.AnnotationsForCluster(cr),\n\t\t\tNamespace: cr.Namespace,\n\t\t},\n\t}\n}", "func (p *ProjectRoleService) Create(ctx context.Context, name, description string) (result *ProjectRoleScheme, response *Response, err error) {\n\n\tif len(name) == 0 {\n\t\treturn nil, nil, fmt.Errorf(\"error, please provide a valid projectKeyOrID value\")\n\t}\n\n\tpayload := struct {\n\t\tName string `json:\"name,omitempty\"`\n\t\tDescription string `json:\"description,omitempty\"`\n\t}{\n\t\tName: name,\n\t\tDescription: description,\n\t}\n\n\tvar endpoint = \"rest/api/3/role\"\n\n\trequest, err := p.client.newRequest(ctx, http.MethodPost, endpoint, &payload)\n\tif err != nil {\n\t\treturn\n\t}\n\n\trequest.Header.Set(\"Accept\", \"application/json\")\n\trequest.Header.Set(\"Content-Type\", \"application/json\")\n\n\tresponse, err = p.client.Do(request)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tresult = new(ProjectRoleScheme)\n\tif err = json.Unmarshal(response.BodyAsBytes, &result); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func SetupRole(mgr ctrl.Manager, o controller.Options) error {\n\tname := managed.ControllerName(v1beta1.RoleGroupKind)\n\n\tcps := []managed.ConnectionPublisher{managed.NewAPISecretPublisher(mgr.GetClient(), mgr.GetScheme())}\n\tif o.Features.Enabled(features.EnableAlphaExternalSecretStores) {\n\t\tcps = append(cps, connection.NewDetailsManager(mgr.GetClient(), v1alpha1.StoreConfigGroupVersionKind))\n\t}\n\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\tNamed(name).\n\t\tWithOptions(o.ForControllerRuntime()).\n\t\tFor(&v1beta1.Role{}).\n\t\tComplete(managed.NewReconciler(mgr,\n\t\t\tresource.ManagedKind(v1beta1.RoleGroupVersionKind),\n\t\t\tmanaged.WithExternalConnecter(&connector{kube: mgr.GetClient(), newClientFn: iam.NewRoleClient}),\n\t\t\tmanaged.WithReferenceResolver(managed.NewAPISimpleReferenceResolver(mgr.GetClient())),\n\t\t\tmanaged.WithConnectionPublishers(),\n\t\t\tmanaged.WithPollInterval(o.PollInterval),\n\t\t\tmanaged.WithLogger(o.Logger.WithValues(\"controller\", name)),\n\t\t\tmanaged.WithInitializers(managed.NewNameAsExternalName(mgr.GetClient()), &tagger{kube: mgr.GetClient()}),\n\t\t\tmanaged.WithRecorder(event.NewAPIRecorder(mgr.GetEventRecorderFor(name))),\n\t\t\tmanaged.WithConnectionPublishers(cps...)))\n}", "func createCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"create\",\n\t\tShort: \"Create a Windows instance on the same provider as the existing OpenShift Cluster.\",\n\t\tLong: \"creates a Windows instance under the same virtual network (AWS-VCP, Azure-Vnet, \" +\n\t\t\t\"and etc.) used by a given OpenShift cluster running on the selected provider. \" +\n\t\t\t\"The created instance would be ready to join the OpenShift Cluster as a worker node.\",\n\t\tPreRunE: func(cmd *cobra.Command, _ []string) error {\n\t\t\treturn validateCreateFlags(cmd)\n\t\t},\n\t\tRunE: func(_ *cobra.Command, _ []string) error {\n\t\t\tcloud, err := cloudprovider.CloudProviderFactory(rootInfo.kubeconfigPath, rootInfo.credentialPath,\n\t\t\t\trootInfo.credentialAccountID, rootInfo.resourceTrackerDir)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error creating cloud provider clients, %v\", err)\n\t\t\t}\n\t\t\terr = cloud.CreateWindowsVM(createFlagInfo.imageID, createFlagInfo.instanceType, createFlagInfo.sshKey)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error creating Windows Instance, %v\", err)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tcmd.PersistentFlags().StringVar(&createFlagInfo.imageID, \"image-id\", \"\",\n\t\t\"ami ID of a base image for the instance (i.e.\"+\n\t\t\t\": ami-06a4e829b8bbad61e for Microsoft Windows Server 2019 Base image on AWS). (required)\")\n\tcmd.PersistentFlags().StringVar(&createFlagInfo.instanceType, \"instance-type\", \"\",\n\t\t\"name of a type of instance (i.e.: m4.large for AWS, etc). (required)\")\n\tcmd.PersistentFlags().StringVar(&createFlagInfo.sshKey, \"ssh-key\", \"\",\n\t\t\"name of existing ssh key on cloud provider for accessing the instance after it is created. (required)\")\n\treturn cmd\n}", "func (gb *CurrentGrantBuilder) Role(n string) GrantExecutable {\n\treturn &CurrentGrantExecutable{\n\t\tgrantName: gb.qualifiedName,\n\t\tgrantType: gb.grantType,\n\t\tgranteeName: n,\n\t\tgranteeType: roleType,\n\t}\n}", "func (action *EnsureIAMRoleAction) ExecuteAction(input interface{}) (output interface{}, err error) {\n\tlog.Infoln(\"EXECUTE EnsureIAMRoleAction, role name:\", action.roleName)\n\n\tiamSvc := iam.New(action.context.Session)\n\tassumeRolePolicy := `{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"Service\": \"eks.amazonaws.com\"\n },\n \"Action\": \"sts:AssumeRole\"\n }\n ]\n}`\n\n\troleinput := &iam.CreateRoleInput{\n\t\tAssumeRolePolicyDocument: &assumeRolePolicy,\n\t\tRoleName: aws.String(action.roleName),\n\t\tDescription: aws.String(\"EKS Creation Role created by Pipeline\"),\n\t\tPath: aws.String(\"/\"),\n\t\tMaxSessionDuration: aws.Int64(3600),\n\t}\n\t//irName := \"\"\n\toutInstanceRole, err := iamSvc.CreateRole(roleinput)\n\n\tif err != nil {\n\t\tlog.Errorln(\"CreateRole error:\", err.Error())\n\t\treturn nil, err\n\t}\n\n\tfor _, roleName := range action.rolesToAttach {\n\t\tattachRoleInput := &iam.AttachRolePolicyInput{\n\t\t\tRoleName: outInstanceRole.Role.RoleName,\n\t\t\tPolicyArn: aws.String(roleName),\n\t\t}\n\t\t_, err = iamSvc.AttachRolePolicy(attachRoleInput)\n\t\tif err != nil {\n\t\t\tlog.Errorln(\"AttachRole error:\", err.Error())\n\t\t\treturn nil, err\n\t\t}\n\t\taction.successfullyAttachedRoles = append(action.successfullyAttachedRoles, roleName)\n\t}\n\taction.context.Role = outInstanceRole.Role\n\n\treturn outInstanceRole.Role, nil\n}", "func (m *GormIdentityRoleRepository) Create(ctx context.Context, u *IdentityRole) error {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"identity_role\", \"create\"}, time.Now())\n\tif u.IdentityRoleID == uuid.Nil {\n\t\tu.IdentityRoleID = uuid.NewV4()\n\t}\n\terr := m.db.Create(u).Error\n\tif err != nil {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"identity_role_id\": u.IdentityRoleID,\n\t\t\t\"err\": err,\n\t\t}, \"unable to create the identity role\")\n\t\tif gormsupport.IsUniqueViolation(err, \"uq_identity_role_identity_role_resource\") {\n\t\t\treturn errs.WithStack(errors.NewDataConflictError(err.Error()))\n\t\t}\n\t\tif gormsupport.IsForeignKeyViolation(err, \"identity_role_identity_id_fkey\") {\n\t\t\treturn errs.WithStack(errors.NewNotFoundError(\"identity\", u.IdentityID.String()))\n\t\t}\n\t\tif gormsupport.IsForeignKeyViolation(err, \"identity_role_resource_id_fkey\") {\n\t\t\treturn errs.WithStack(errors.NewNotFoundError(\"resource\", u.ResourceID))\n\t\t}\n\t\tif gormsupport.IsForeignKeyViolation(err, \"identity_role_role_id_fkey\") {\n\t\t\treturn errs.WithStack(errors.NewNotFoundError(\"role\", u.RoleID.String()))\n\t\t}\n\t\treturn errs.WithStack(err)\n\t}\n\tlog.Debug(ctx, map[string]interface{}{\n\t\t\"identity_role_id\": u.IdentityRoleID,\n\t}, \"Identity Role created!\")\n\treturn nil\n}", "func NewRBACRole(name string, kind RBACRoleKind, authRole model.AuthRole, settings ExportSettings) (helm.Node, error) {\n\trules := helm.NewList()\n\tfor _, ruleSpec := range authRole {\n\t\trule := helm.NewMapping()\n\t\trule.Add(\"apiGroups\", helm.NewNode(ruleSpec.APIGroups))\n\t\trule.Add(\"resources\", helm.NewNode(ruleSpec.Resources))\n\t\trule.Add(\"verbs\", helm.NewNode(ruleSpec.Verbs))\n\t\tif len(ruleSpec.ResourceNames) > 0 {\n\t\t\tresourceNames := helm.NewList()\n\t\t\tfor _, resourceName := range ruleSpec.ResourceNames {\n\t\t\t\tif settings.CreateHelmChart && ruleSpec.IsPodSecurityPolicyRule() {\n\t\t\t\t\t// When creating helm charts for PSPs, let the user override it\n\t\t\t\t\tresourceNames.Add(fmt.Sprintf(\n\t\t\t\t\t\t`{{ if .Values.kube.psp.%[1]s }}{{ .Values.kube.psp.%[1]s }}{{ else }}`+\n\t\t\t\t\t\t\t`{{ template \"fissile.SanitizeName\" (printf \"%%s-psp-%[1]s\" .Release.Namespace) }}{{ end }}`, resourceName))\n\t\t\t\t} else {\n\t\t\t\t\tresourceNames.Add(resourceName)\n\t\t\t\t}\n\t\t\t}\n\t\t\trule.Add(\"resourceNames\", resourceNames)\n\t\t}\n\t\trules.Add(rule.Sort())\n\t}\n\n\tcb := NewConfigBuilder().\n\t\tSetSettings(&settings).\n\t\tSetAPIVersion(\"rbac.authorization.k8s.io/v1\").\n\t\tSetKind(string(kind)).\n\t\tAddModifier(authModeRBAC(settings))\n\tif kind == RBACRoleKindClusterRole && settings.CreateHelmChart {\n\t\tcb.SetNameHelmExpression(fmt.Sprintf(`{{ template \"fissile.SanitizeName\" (printf \"%%s-cluster-role-%s\" .Release.Namespace) }}`, name))\n\t} else {\n\t\tcb.SetName(name)\n\t}\n\trole, err := cb.Build()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to build a new kube config: %v\", err)\n\t}\n\trole.Add(\"rules\", rules)\n\n\treturn role.Sort(), nil\n}", "func (m *MockRoleClient) CreateRoleRequest(input *iam.CreateRoleInput) iam.CreateRoleRequest {\n\treturn m.MockCreateRoleRequest(input)\n}", "func (p *planner) CreateRoleNode(\n\tctx context.Context,\n\tnameE tree.Expr,\n\tifNotExists bool,\n\tisRole bool,\n\topName string,\n\tkvOptions tree.KVOptions,\n) (*CreateRoleNode, error) {\n\tif err := p.CheckRoleOption(ctx, roleoption.CREATEROLE); err != nil {\n\t\treturn nil, err\n\t}\n\n\tasStringOrNull := func(e tree.Expr, op string) (func() (bool, string, error), error) {\n\t\treturn p.TypeAsStringOrNull(ctx, e, op)\n\t}\n\troleOptions, err := kvOptions.ToRoleOptions(asStringOrNull, opName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := roleOptions.CheckRoleOptionConflicts(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Using CREATE ROLE syntax enables NOLOGIN by default.\n\tif isRole && !roleOptions.Contains(roleoption.LOGIN) && !roleOptions.Contains(roleoption.NOLOGIN) {\n\t\troleOptions = append(roleOptions,\n\t\t\troleoption.RoleOption{Option: roleoption.NOLOGIN, HasValue: false})\n\t}\n\n\t// Check that the requested combination of password options is\n\t// compatible with the user's own CREATELOGIN privilege.\n\tif err := p.checkPasswordOptionConstraints(ctx, roleOptions, true /* newUser */); err != nil {\n\t\treturn nil, err\n\t}\n\n\tua, err := p.getUserAuthInfo(ctx, nameE, opName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &CreateRoleNode{\n\t\tuserNameInfo: ua,\n\t\tifNotExists: ifNotExists,\n\t\tisRole: isRole,\n\t\troleOptions: roleOptions,\n\t}, nil\n}", "func (svc *roleService) Add(ctx context.Context, in *permissionpb.RoleRequest, out *commons.Status) error {\n\treturn xbasiswrapper.ContextToAuthorize(ctx, out, func(auth *xbasiswrapper.WrapperUser) *commons.State {\n\t\trepo := svc.GetRepo()\n\t\tdefer repo.Close()\n\n\t\t_, err := repo.FindByName(in.Name, in.AppId)\n\t\tif err != nil && err == mgo.ErrNotFound {\n\t\t\terr = repo.Save(in.Name, in.AppId, auth.User)\n\t\t\tif err != nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn errstate.Success\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn errstate.ErrRoleAlreadyExists\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func NewRoleServer() *RoleServer {\n\tvar s = &RoleServer{\n\t\tServeMux: http.NewServeMux(),\n\t}\n\ts.HandleFunc(\"/create\", s.HandleCreate)\n\ts.HandleFunc(\"/get\", s.HandleGetByID)\n\ts.HandleFunc(\"/update\", s.HandleUpdateByID)\n\ts.HandleFunc(\"/mark_delete\", s.HandleMarkDelete)\n\ts.HandleFunc(\"/get_all\", s.HandleAllRole)\n\treturn s\n}", "func CmdCreateIBMCos() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"ibm-cos <namespace-store-name>\",\n\t\tShort: \"Create ibm-cos namespace store\",\n\t\tRun: RunCreateIBMCos,\n\t}\n\tcmd.Flags().String(\n\t\t\"target-bucket\", \"\",\n\t\t\"The target bucket name on the cloud\",\n\t)\n\tcmd.Flags().String(\n\t\t\"access-key\", \"\",\n\t\t`Access key for authentication - the best practice is to **omit this flag**, in that case the CLI will prompt to prompt and read it securely from the terminal to avoid leaking secrets in the shell history`,\n\t)\n\tcmd.Flags().String(\n\t\t\"secret-key\", \"\",\n\t\t`Secret key for authentication - the best practice is to **omit this flag**, in that case the CLI will prompt to prompt and read it securely from the terminal to avoid leaking secrets in the shell history`,\n\t)\n\tcmd.Flags().String(\n\t\t\"secret-name\", \"\",\n\t\t`The name of a secret for authentication - should have IBM_COS_ACCESS_KEY_ID and IBM_COS_SECRET_ACCESS_KEY properties`,\n\t)\n\tcmd.Flags().String(\n\t\t\"endpoint\", \"\",\n\t\t\"The target IBM Cos endpoint\",\n\t)\n\tcmd.Flags().String(\n\t\t\"access-mode\", \"read-write\",\n\t\t`The resource access privileges read-write|read-only`,\n\t)\n\treturn cmd\n}", "func createServiceAccountAndRoles(ctx context.Context, c kubernetes.Interface, serviceAccountName, namespace string, clusterScoped bool, clusterType clusterType) error {\n\tsa := corev1.ServiceAccount{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: serviceAccountName,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: multiClusterLabels(),\n\t\t},\n\t\tImagePullSecrets: []corev1.LocalObjectReference{\n\t\t\t{Name: \"image-registries-secret\"},\n\t\t},\n\t}\n\n\t_, err := c.CoreV1().ServiceAccounts(sa.Namespace).Create(ctx, &sa, metav1.CreateOptions{})\n\tif !errors.IsAlreadyExists(err) && err != nil {\n\t\treturn xerrors.Errorf(\"error creating service account: %w\", err)\n\t}\n\n\tif !clusterScoped {\n\t\tvar role rbacv1.Role\n\t\tif clusterType == centralCluster {\n\t\t\trole = buildCentralEntityRole(sa.Namespace)\n\t\t} else {\n\t\t\trole = buildMemberEntityRole(sa.Namespace)\n\t\t}\n\n\t\t_, err = c.RbacV1().Roles(sa.Namespace).Create(ctx, &role, metav1.CreateOptions{})\n\t\tif !errors.IsAlreadyExists(err) && err != nil {\n\t\t\treturn xerrors.Errorf(\"error creating role: %w\", err)\n\t\t}\n\n\t\troleBinding := buildRoleBinding(role, sa.Name)\n\t\t_, err = c.RbacV1().RoleBindings(sa.Namespace).Create(ctx, &roleBinding, metav1.CreateOptions{})\n\t\tif !errors.IsAlreadyExists(err) && err != nil {\n\t\t\treturn xerrors.Errorf(\"error creating role binding: %w\", err)\n\t\t}\n\t\treturn nil\n\t}\n\n\tvar clusterRole rbacv1.ClusterRole\n\tif clusterType == centralCluster {\n\t\tclusterRole = buildCentralEntityClusterRole()\n\t} else {\n\t\tclusterRole = buildMemberEntityClusterRole()\n\t}\n\n\t_, err = c.RbacV1().ClusterRoles().Create(ctx, &clusterRole, metav1.CreateOptions{})\n\tif !errors.IsAlreadyExists(err) && err != nil {\n\t\treturn xerrors.Errorf(\"error creating cluster role: %w\", err)\n\t}\n\tfmt.Printf(\"created clusterrole: %s\\n\", clusterRole.Name)\n\n\tclusterRoleBinding := buildClusterRoleBinding(clusterRole, sa)\n\t_, err = c.RbacV1().ClusterRoleBindings().Create(ctx, &clusterRoleBinding, metav1.CreateOptions{})\n\tif !errors.IsAlreadyExists(err) && err != nil {\n\t\treturn xerrors.Errorf(\"error creating cluster role binding: %w\", err)\n\t}\n\tfmt.Printf(\"created clusterrolebinding: %s\\n\", clusterRoleBinding.Name)\n\treturn nil\n}", "func createPrivilegedServiceAccount(ctx context.Context, log *logrus.Entry, name, cluster, usersAccount string, kubeActions adminactions.KubeActions) (func() error, error, error) {\n\tserviceAcc := newServiceAccount(name, cluster)\n\tclusterRole := newClusterRole(usersAccount, cluster)\n\tcrb := newClusterRoleBinding(name, cluster)\n\tscc := newSecurityContextConstraint(name, cluster, usersAccount)\n\n\t// cleanup is created here incase an error occurs while creating permissions\n\tcleanup := func() error {\n\t\tlog.Infof(\"Deleting service account %s now\", serviceAcc.GetName())\n\t\terr := kubeActions.KubeDelete(ctx, serviceAcc.GetKind(), serviceAcc.GetNamespace(), serviceAcc.GetName(), true, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.Infof(\"Deleting security context contstraint %s now\", scc.GetName())\n\t\terr = kubeActions.KubeDelete(ctx, scc.GetKind(), scc.GetNamespace(), scc.GetName(), true, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.Infof(\"Deleting cluster role %s now\", clusterRole.GetName())\n\t\terr = kubeActions.KubeDelete(ctx, clusterRole.GetKind(), clusterRole.GetNamespace(), clusterRole.GetName(), true, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.Infof(\"Deleting cluster role binding %s now\", crb.GetName())\n\t\terr = kubeActions.KubeDelete(ctx, crb.GetKind(), crb.GetNamespace(), crb.GetName(), true, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tlog.Infof(\"Creating Service Account %s now\", serviceAcc.GetName())\n\terr := kubeActions.KubeCreateOrUpdate(ctx, serviceAcc)\n\tif err != nil {\n\t\treturn nil, err, cleanup()\n\t}\n\n\tlog.Infof(\"Creating Cluster Role %s now\", clusterRole.GetName())\n\terr = kubeActions.KubeCreateOrUpdate(ctx, clusterRole)\n\tif err != nil {\n\t\treturn nil, err, cleanup()\n\t}\n\n\tlog.Infof(\"Creating Cluster Role Binding %s now\", crb.GetName())\n\terr = kubeActions.KubeCreateOrUpdate(ctx, crb)\n\tif err != nil {\n\t\treturn nil, err, cleanup()\n\t}\n\n\tlog.Infof(\"Creating Security Context Constraint %s now\", name)\n\terr = kubeActions.KubeCreateOrUpdate(ctx, scc)\n\tif err != nil {\n\t\treturn nil, err, cleanup()\n\t}\n\n\treturn cleanup, nil, nil\n}", "func createNamespace(ns string) {\n\tcmd := command{\n\t\tCmd: \"bash\",\n\t\tArgs: []string{\"-c\", \"kubectl create namespace \" + ns},\n\t\tDescription: \"creating namespace \" + ns,\n\t}\n\n\tif exitCode, _ := cmd.exec(debug, verbose); exitCode != 0 {\n\t\tlog.Println(\"WARN: I could not create namespace [ \" +\n\t\t\tns + \" ]. It already exists. I am skipping this.\")\n\t}\n}", "func newRoleForCR(cr *storagev1.CSIPowerMaxRevProxy) *rbacv1.Role {\n\treturn &rbacv1.Role{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: ReverseProxyName,\n\t\t\tNamespace: cr.Namespace,\n\t\t\tOwnerReferences: getOwnerReferences(cr),\n\t\t},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\t{\n\t\t\t\tAPIGroups: []string{\"\"},\n\t\t\t\tResources: []string{\"secrets\"},\n\t\t\t\tVerbs: []string{\"list\", \"watch\", \"get\"},\n\t\t\t},\n\t\t},\n\t}\n}", "func (bot *DiscordBot) CreateCommand(ctx context.Context, command *discordgo.ApplicationCommand) error {\n\tbot.logger.Info(\"Create command\", \"command\", command)\n\n\t// TODO: store the output somewhere\n\t// _, err := session.ApplicationCommandCreate(session.State.User.ID, \"\", applicationCommand)\n\t// if err != nil {\n\t// \treturn fmt.Errorf(\"create command '%s': %w\", name, err)\n\t// }\n\n\treturn nil\n}", "func CreateRoleTable(db *sql.DB) error {\n\t_, err := db.Exec(roleSQLString[mysqlRoleCreateTable])\n\treturn err\n}", "func (v *Client) GenerateNewAppRoleSecret(secretID, appRoleName string) (string, error) {\n\tappRolePath := v.getAppRolePath(appRoleName)\n\tsecretIDData, err := v.lookupSecretID(secretID, appRolePath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treqPath := sanitizePath(path.Join(appRolePath, \"/secret-id\"))\n\n\t// we preserve metadata which was attached to the secret-id\n\tjson, err := json.Marshal(secretIDData[\"metadata\"])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tsecret, err := v.lClient.Write(reqPath, map[string]interface{}{\n\t\t\"metadata\": string(json),\n\t})\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif secret == nil || secret.Data == nil {\n\t\treturn \"\", fmt.Errorf(\"Could not generate new approle secret-id for approle path %s\", reqPath)\n\t}\n\n\tsecretIDRaw, ok := secret.Data[\"secret_id\"]\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"Vault response for path %s did not contain a new secret-id\", reqPath)\n\t}\n\n\tnewSecretID, ok := secretIDRaw.(string)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"New secret-id from approle path %s has an unexpected type %T expected 'string'\", reqPath, secretIDRaw)\n\t}\n\n\treturn newSecretID, nil\n}", "func CreateClusterRole(cr, namespace, name, app, description string, rules []rbacv1.PolicyRule) *rbacv1.ClusterRole {\n\tlabels := map[string]string{\n\t\t\"app\": app,\n\t\t\"deployedby\": \"aqua-operator\",\n\t\t\"aquasecoperator_cr\": cr,\n\t}\n\tannotations := map[string]string{\n\t\t\"description\": description,\n\t\t\"openshift.io/description\": \"A user who can search and scan images from an OpenShift integrated registry.\",\n\t}\n\tcrole := &rbacv1.ClusterRole{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"rbac.authorization.k8s.io/v1\",\n\t\t\tKind: \"ClusterRole\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t\tAnnotations: annotations,\n\t\t},\n\t\tRules: rules,\n\t}\n\n\treturn crole\n}", "func Create(c *client.Client, cr *Instance) error {\n\n\trole := &rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cr.Name,\n\t\t\tLabels: map[string]string{\n\t\t\t\tcr.LabelKey: cr.LabelValue,\n\t\t\t},\n\t\t},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\t{\n\t\t\t\tAPIGroups: cr.APIGroups,\n\t\t\t\tResources: cr.Resources,\n\t\t\t\tVerbs: cr.Verbs,\n\t\t\t\tResourceNames: cr.ResourcesNames,\n\t\t\t},\n\t\t},\n\t}\n\n\t_, err := c.Clientset.RbacV1().ClusterRoles().Create(\n\t\tcontext.TODO(),\n\t\trole,\n\t\tmetav1.CreateOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func CreateClusterRole(\n\tk8sClient *kubernetes.Clientset,\n\tappName string,\n\tclusterRoleName string,\n\trules []PolicyRule,\n) error {\n\n\tlabels := map[string]string{\n\t\t\"app\": appName,\n\t}\n\n\trbacRules, err := generateRbacRules(rules)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%v\", err)\n\t}\n\n\tclusterRole := rbacv1.ClusterRole{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"rbac.authorization.k8s.io/v1\",\n\t\t\tKind: \"ClusterRole\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: clusterRoleName,\n\t\t\tLabels: labels,\n\t\t},\n\t\tRules: rbacRules,\n\t}\n\n\tclient := k8sClient.RbacV1().ClusterRoles()\n\t_, err = client.Create(&clusterRole)\n\tif err != nil {\n\t\tif !apierr.IsAlreadyExists(err) {\n\t\t\treturn fmt.Errorf(\"Failed to create ClusterRole %q: %v\", clusterRoleName, err)\n\t\t}\n\t\t_, err = client.Update(&clusterRole)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to update ClusterRole %q: %v\", clusterRoleName, err)\n\t\t}\n\t\tfmt.Printf(\"ClusterRole %q updated\\n\", clusterRoleName)\n\t} else {\n\t\tfmt.Printf(\"ClusterRole %q created\\n\", clusterRoleName)\n\t}\n\treturn nil\n}", "func createOrUpdateAegisRole() string {\n\t// Default aegis IAM role name: aegis_lambda_role\n\taegisLambdaRoleName := aws.String(\"aegis_lambda_role\")\n\troleArn := \"\"\n\n\tsvc := iam.New(getAWSSession())\n\n\t// First see if the role exists\n\tparams := &iam.GetRoleInput{\n\t\tRoleName: aegisLambdaRoleName,\n\t}\n\t// Don't worry about errors just yet, there'll be more errors below if things aren't configured properly or can't connect.\n\tresp, err := svc.GetRole(params)\n\tif err == nil {\n\t\tif resp.Role.Arn != nil {\n\t\t\troleArn = *resp.Role.Arn\n\t\t\tfmt.Printf(\"%v %v\\n\", \"Using existing execution role for Lambda:\", color.GreenString(roleArn))\n\t\t}\n\t}\n\n\t// Assume role policy document\n\tvar iamAssumeRolePolicy = `{\n\t\t\"Version\": \"2012-10-17\",\n\t\t\"Statement\": [\n\t\t {\n\t\t\t\"Effect\": \"Allow\",\n\t\t\t\"Principal\": {\n\t\t\t \"Service\": \"lambda.amazonaws.com\"\n\t\t\t},\n\t\t\t\"Action\": \"sts:AssumeRole\"\n\t\t },\n\t\t {\n\t\t\t\"Effect\": \"Allow\",\n\t\t\t\"Principal\": {\n\t\t\t \"Service\": \"events.amazonaws.com\"\n\t\t\t},\n\t\t\t \"Action\": \"sts:AssumeRole\"\n\t\t },\n\t\t {\n\t\t\t\"Effect\": \"Allow\",\n\t\t\t\"Principal\": {\n\t\t\t \"Service\": \"xray.amazonaws.com\"\n\t\t\t},\n\t\t\t\"Action\": \"sts:AssumeRole\"\n\t\t }\n\t\t]\n\t }`\n\n\t// Create the Lambda execution role, if necessary\n\tif roleArn == \"\" || err != nil {\n\t\trole, err := svc.CreateRole(&iam.CreateRoleInput{\n\t\t\tRoleName: aegisLambdaRoleName,\n\t\t\tAssumeRolePolicyDocument: aws.String(iamAssumeRolePolicy),\n\t\t})\n\t\tif err != nil {\n\t\t\tfmt.Println(\"There was a problem creating a default IAM role for Lambda. Check your configuration.\")\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(-1)\n\t\t}\n\t\troleArn = *role.Role.Arn\n\t\tfmt.Printf(\"%v %v\\n\", \"Created a new execution role for Lambda:\", color.GreenString(roleArn))\n\t}\n\n\t// Update assume role policy\n\t_, err = svc.UpdateAssumeRolePolicy(&iam.UpdateAssumeRolePolicyInput{\n\t\tPolicyDocument: aws.String(iamAssumeRolePolicy),\n\t\tRoleName: aegisLambdaRoleName,\n\t})\n\n\t// Attach managed policies.\n\t// First, AWSLambdaFullAccess\n\t_, err = svc.AttachRolePolicy(&iam.AttachRolePolicyInput{\n\t\tPolicyArn: aws.String(\"arn:aws:iam::aws:policy/AWSLambdaFullAccess\"),\n\t\tRoleName: aegisLambdaRoleName,\n\t})\n\tif err != nil {\n\t\tfmt.Println(\"There was a problem attaching AWSLambdaFullAccess managed policy to the IAM role for Lambda.\")\n\t\tfmt.Println(err)\n\t}\n\n\t// Then AmazonCognitoReadOnly\n\t_, err = svc.AttachRolePolicy(&iam.AttachRolePolicyInput{\n\t\tPolicyArn: aws.String(\"arn:aws:iam::aws:policy/AmazonCognitoReadOnly\"),\n\t\tRoleName: aegisLambdaRoleName,\n\t})\n\tif err != nil {\n\t\tfmt.Println(\"There was a problem attaching AmazonCognitoReadOnly managed policy to the IAM role for Lambda.\")\n\t\tfmt.Println(err)\n\t}\n\n\t// Then AWSXrayFullAccess\n\t_, err = svc.AttachRolePolicy(&iam.AttachRolePolicyInput{\n\t\tPolicyArn: aws.String(\"arn:aws:iam::aws:policy/AWSXrayFullAccess\"),\n\t\tRoleName: aegisLambdaRoleName,\n\t})\n\tif err != nil {\n\t\tfmt.Println(\"There was a problem attaching AWSXrayFullAccess managed policy to the IAM role for Lambda.\")\n\t\tfmt.Println(err)\n\t}\n\n\t// Then AmazonVPCFullAccess\n\t_, err = svc.AttachRolePolicy(&iam.AttachRolePolicyInput{\n\t\tPolicyArn: aws.String(\"arn:aws:iam::aws:policy/AmazonVPCFullAccess\"),\n\t\tRoleName: aegisLambdaRoleName,\n\t})\n\tif err != nil {\n\t\tfmt.Println(\"There was a problem attaching AmazonVPCFullAccess managed policy to the IAM role for Lambda.\")\n\t\tfmt.Println(err)\n\t}\n\n\t// Then AWSLambdaSQSQueueExecutionRole\n\t_, err = svc.AttachRolePolicy(&iam.AttachRolePolicyInput{\n\t\tPolicyArn: aws.String(\"arn:aws:iam::aws:policy/service-role/AWSLambdaSQSQueueExecutionRole\"),\n\t\tRoleName: aegisLambdaRoleName,\n\t})\n\tif err != nil {\n\t\tfmt.Println(\"There was a problem attaching AWSLambdaSQSQueueExecutionRole managed policy to the IAM role for Lambda.\")\n\t\tfmt.Println(err)\n\t}\n\n\treturn roleArn\n}", "func (a *IamProjectRoleApiService) IamProjectRoleDeleteExecute(r ApiIamProjectRoleDeleteRequest) (*Role, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodDelete\n\t\tlocalVarPostBody interface{}\n\t\tformFiles []formFile\n\t\tlocalVarReturnValue *Role\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"IamProjectRoleApiService.IamProjectRoleDelete\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/iam/project/{projectId}/role/{roleId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"projectId\"+\"}\", url.PathEscape(parameterToString(r.projectId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"roleId\"+\"}\", url.PathEscape(parameterToString(r.roleId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\t\tvar v InlineResponseDefault\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r *OrganizationsRolesService) Create(parent string, createrolerequest *CreateRoleRequest) *OrganizationsRolesCreateCall {\n\tc := &OrganizationsRolesCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.parent = parent\n\tc.createrolerequest = createrolerequest\n\treturn c\n}", "func (role *Role) Create() error {\n\tvar funcIDs []string\n\tfor _, fun := range role.Func {\n\t\tfuncIDs = append(funcIDs, fun.FuncID)\n\t}\n\tfuncs := []Func{}\n\tif errFunc := db.Where(\"func_id in (?)\", funcIDs).Find(&funcs).Error; errFunc != nil {\n\t\tlogger.Error(\"Failed to find role related system functions\", errFunc)\n\t\treturn errFunc\n\t}\n\trole.RoleID = util.GUID()\n\trole.Func = funcs\n\tif err := db.Create(&role).Association(\"Func\").Append(funcs).Error; err != nil {\n\t\tlogger.Error(\"Failed to create new role\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func modifyImageIamPolicy(c *cli.Context, w io.Writer, action string) error {\n\terr := checkArgCount(c, 1)\n\tif err != nil {\n\t\treturn err\n\t}\n\timageID := c.Args()[0]\n\tprincipal := c.String(\"principal\")\n\trole := c.String(\"role\")\n\n\tif !c.GlobalIsSet(\"non-interactive\") {\n\t\tvar err error\n\t\tprincipal, err = askForInput(\"Principal: \", principal)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(principal) == 0 {\n\t\treturn fmt.Errorf(\"Please provide principal\")\n\t}\n\n\tif !c.GlobalIsSet(\"non-interactive\") {\n\t\tvar err error\n\t\trole, err = askForInput(\"Role: \", role)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(role) == 0 {\n\t\treturn fmt.Errorf(\"Please provide role\")\n\t}\n\n\tclient.Photonclient, err = client.GetClient(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar delta photon.PolicyDelta\n\tdelta = photon.PolicyDelta{Principal: principal, Action: action, Role: role}\n\ttask, err := client.Photonclient.Images.ModifyIam(imageID, &delta)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = waitOnTaskOperation(task.ID, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif utils.NeedsFormatting(c) {\n\t\tpolicy, err := client.Photonclient.Images.GetIam(imageID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tutils.FormatObject(policy, w, c)\n\t}\n\n\treturn nil\n}", "func (mr *MockClientInterfaceMockRecorder) CreateRole(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateRole\", reflect.TypeOf((*MockClientInterface)(nil).CreateRole), arg0)\n}", "func (r *ProjectsRolesService) Create(parent string, createrolerequest *CreateRoleRequest) *ProjectsRolesCreateCall {\n\tc := &ProjectsRolesCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.parent = parent\n\tc.createrolerequest = createrolerequest\n\treturn c\n}" ]
[ "0.64185333", "0.6343696", "0.63033944", "0.62764794", "0.6259748", "0.607277", "0.6022307", "0.601651", "0.6010092", "0.5993361", "0.59221154", "0.58515495", "0.5795519", "0.57180107", "0.56589943", "0.5650192", "0.563629", "0.5621326", "0.5602486", "0.5566102", "0.55211556", "0.55164266", "0.5484281", "0.5482953", "0.54698724", "0.54487634", "0.54355055", "0.5421807", "0.5409124", "0.5396241", "0.5385047", "0.53606075", "0.5347476", "0.5339146", "0.53052396", "0.5285041", "0.5251478", "0.5195321", "0.5194486", "0.51846087", "0.5178337", "0.5174793", "0.5168737", "0.5168228", "0.51607823", "0.51595527", "0.5152117", "0.51415086", "0.5124823", "0.51228154", "0.51217306", "0.5111157", "0.51033026", "0.5098866", "0.50983864", "0.5078836", "0.50720155", "0.50596035", "0.50484085", "0.50223976", "0.5018795", "0.5013708", "0.5008189", "0.49964428", "0.49767008", "0.49717262", "0.49527818", "0.49524194", "0.4951005", "0.4928913", "0.49271512", "0.49269596", "0.49172166", "0.49154907", "0.49102825", "0.49055168", "0.49045005", "0.49027142", "0.4901457", "0.48791426", "0.48754528", "0.48687634", "0.4860252", "0.48599115", "0.4858601", "0.48555413", "0.48342496", "0.48312277", "0.48259914", "0.47994295", "0.47971997", "0.4792421", "0.47874087", "0.47869337", "0.4775411", "0.47655195", "0.47650468", "0.4760556", "0.47526678", "0.47458884" ]
0.7840388
0
scalar kernel that ignores (assumed allnull inputs) and returns null
func NullToNullExec(_ *exec.KernelCtx, _ *exec.ExecSpan, _ *exec.ExecResult) error { return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (e *Engine) NeScalar(a tensor.Tensor, b interface{}, leftTensor bool, opts ...tensor.FuncOpt) (retVal tensor.Tensor, err error) {\n\tname := constructName1(a, leftTensor, \"ne\")\n\tif !e.HasFunc(name) {\n\t\treturn nil, errors.Errorf(\"Unable to perform NeScalar(). The tensor engine does not have the function %q\", name)\n\t}\n\n\tvar bMem tensor.Memory\n\tvar ok bool\n\tif bMem, ok = b.(tensor.Memory); !ok {\n\t\treturn nil, errors.Errorf(\"b has to be a tensor.Memory. Got %T instead\", b)\n\t}\n\n\tif err = unaryCheck(a); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Basic checks failed for NeScalar\")\n\t}\n\n\tvar reuse tensor.DenseTensor\n\tvar safe, toReuse bool\n\tif reuse, safe, toReuse, _, _, err = handleFuncOpts(a.Shape(), a.Dtype(), a.DataOrder(), true, opts...); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Unable to handle funcOpts\")\n\t}\n\n\tvar mem, memB cu.DevicePtr\n\tvar size int64\n\n\tswitch {\n\tcase toReuse:\n\t\tmem = cu.DevicePtr(reuse.Uintptr())\n\t\tmemA := cu.DevicePtr(a.Uintptr())\n\t\tmemSize := int64(a.MemSize())\n\t\te.memcpy(mem, memA, memSize)\n\n\t\tsize = int64(logicalSize(reuse.Shape()))\n\t\tretVal = reuse\n\tcase !safe:\n\t\tmem = cu.DevicePtr(a.Uintptr())\n\t\tretVal = a\n\t\tsize = int64(logicalSize(a.Shape()))\n\tdefault:\n\t\treturn nil, errors.New(\"Impossible state: A reuse tensor must be passed in, or the operation must be unsafe. Incr and safe operations are not supported\")\n\t}\n\n\tmemB = cu.DevicePtr(bMem.Uintptr())\n\tif !leftTensor {\n\t\tmem, memB = memB, mem\n\t}\n\n\tfn := e.f[name]\n\tgridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ := e.ElemGridSize(int(size))\n\targs := []unsafe.Pointer{\n\t\tunsafe.Pointer(&mem),\n\t\tunsafe.Pointer(&memB),\n\t\tunsafe.Pointer(&size),\n\t}\n\tlogf(\"gx %d, gy %d, gz %d | bx %d by %d, bz %d\", gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ)\n\tlogf(\"CUDADO %q, Mem: %v size %v, args %v\", name, mem, size, args)\n\tlogf(\"LaunchKernel Params. mem: %v. Size %v\", mem, size)\n\te.c.LaunchAndSync(fn, gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ, 0, cu.NoStream, args)\n\treturn\n}", "func (o *PerCPU) Kernel() float64 {\n\ts := o.System.ComputeRate()\n\tt := o.Total.ComputeRate()\n\tif s != math.NaN() && t != math.NaN() && t > 0 {\n\t\treturn (s / t)\n\t}\n\treturn math.NaN()\n}", "func (n null) Mul(v Val) Val {\n\tpanic(ErrInvalidOpMulOnNil)\n}", "func rcNoop(ctx context.Context, in Params) (out Params, err error) {\n\treturn in, nil\n}", "func (e *Engine) GteScalar(a tensor.Tensor, b interface{}, leftTensor bool, opts ...tensor.FuncOpt) (retVal tensor.Tensor, err error) {\n\tname := constructName1(a, leftTensor, \"gte\")\n\tif !e.HasFunc(name) {\n\t\treturn nil, errors.Errorf(\"Unable to perform GteScalar(). The tensor engine does not have the function %q\", name)\n\t}\n\n\tvar bMem tensor.Memory\n\tvar ok bool\n\tif bMem, ok = b.(tensor.Memory); !ok {\n\t\treturn nil, errors.Errorf(\"b has to be a tensor.Memory. Got %T instead\", b)\n\t}\n\n\tif err = unaryCheck(a); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Basic checks failed for GteScalar\")\n\t}\n\n\tvar reuse tensor.DenseTensor\n\tvar safe, toReuse bool\n\tif reuse, safe, toReuse, _, _, err = handleFuncOpts(a.Shape(), a.Dtype(), a.DataOrder(), true, opts...); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Unable to handle funcOpts\")\n\t}\n\n\tvar mem, memB cu.DevicePtr\n\tvar size int64\n\n\tswitch {\n\tcase toReuse:\n\t\tmem = cu.DevicePtr(reuse.Uintptr())\n\t\tmemA := cu.DevicePtr(a.Uintptr())\n\t\tmemSize := int64(a.MemSize())\n\t\te.memcpy(mem, memA, memSize)\n\n\t\tsize = int64(logicalSize(reuse.Shape()))\n\t\tretVal = reuse\n\tcase !safe:\n\t\tmem = cu.DevicePtr(a.Uintptr())\n\t\tretVal = a\n\t\tsize = int64(logicalSize(a.Shape()))\n\tdefault:\n\t\treturn nil, errors.New(\"Impossible state: A reuse tensor must be passed in, or the operation must be unsafe. Incr and safe operations are not supported\")\n\t}\n\n\tmemB = cu.DevicePtr(bMem.Uintptr())\n\tif !leftTensor {\n\t\tmem, memB = memB, mem\n\t}\n\n\tfn := e.f[name]\n\tgridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ := e.ElemGridSize(int(size))\n\targs := []unsafe.Pointer{\n\t\tunsafe.Pointer(&mem),\n\t\tunsafe.Pointer(&memB),\n\t\tunsafe.Pointer(&size),\n\t}\n\tlogf(\"gx %d, gy %d, gz %d | bx %d by %d, bz %d\", gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ)\n\tlogf(\"CUDADO %q, Mem: %v size %v, args %v\", name, mem, size, args)\n\tlogf(\"LaunchKernel Params. mem: %v. Size %v\", mem, size)\n\te.c.LaunchAndSync(fn, gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ, 0, cu.NoStream, args)\n\treturn\n}", "func scalarIsZero(scalar []uint64) int {\r\n\treturn uint64IsZero(scalar[0] | scalar[1] | scalar[2] | scalar[3])\r\n}", "func scalarIsZero(scalar []uint64) int {\n\treturn uint64IsZero(scalar[0] | scalar[1] | scalar[2] | scalar[3])\n}", "func NaN() float32 { return Float32frombits(uvnan) }", "func funcScalar(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\tv := vals[0].(Vector)\n\tif len(v) != 1 {\n\t\treturn append(enh.Out, Sample{F: math.NaN()})\n\t}\n\treturn append(enh.Out, Sample{F: v[0].F})\n}", "func MulNoNan(scope *Scope, x tf.Output, y tf.Output) (z tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"MulNoNan\",\n\t\tInput: []tf.Input{\n\t\t\tx, y,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func (e *Engine) GtScalar(a tensor.Tensor, b interface{}, leftTensor bool, opts ...tensor.FuncOpt) (retVal tensor.Tensor, err error) {\n\tname := constructName1(a, leftTensor, \"gt\")\n\tif !e.HasFunc(name) {\n\t\treturn nil, errors.Errorf(\"Unable to perform GtScalar(). The tensor engine does not have the function %q\", name)\n\t}\n\n\tvar bMem tensor.Memory\n\tvar ok bool\n\tif bMem, ok = b.(tensor.Memory); !ok {\n\t\treturn nil, errors.Errorf(\"b has to be a tensor.Memory. Got %T instead\", b)\n\t}\n\n\tif err = unaryCheck(a); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Basic checks failed for GtScalar\")\n\t}\n\n\tvar reuse tensor.DenseTensor\n\tvar safe, toReuse bool\n\tif reuse, safe, toReuse, _, _, err = handleFuncOpts(a.Shape(), a.Dtype(), a.DataOrder(), true, opts...); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Unable to handle funcOpts\")\n\t}\n\n\tvar mem, memB cu.DevicePtr\n\tvar size int64\n\n\tswitch {\n\tcase toReuse:\n\t\tmem = cu.DevicePtr(reuse.Uintptr())\n\t\tmemA := cu.DevicePtr(a.Uintptr())\n\t\tmemSize := int64(a.MemSize())\n\t\te.memcpy(mem, memA, memSize)\n\n\t\tsize = int64(logicalSize(reuse.Shape()))\n\t\tretVal = reuse\n\tcase !safe:\n\t\tmem = cu.DevicePtr(a.Uintptr())\n\t\tretVal = a\n\t\tsize = int64(logicalSize(a.Shape()))\n\tdefault:\n\t\treturn nil, errors.New(\"Impossible state: A reuse tensor must be passed in, or the operation must be unsafe. Incr and safe operations are not supported\")\n\t}\n\n\tmemB = cu.DevicePtr(bMem.Uintptr())\n\tif !leftTensor {\n\t\tmem, memB = memB, mem\n\t}\n\n\tfn := e.f[name]\n\tgridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ := e.ElemGridSize(int(size))\n\targs := []unsafe.Pointer{\n\t\tunsafe.Pointer(&mem),\n\t\tunsafe.Pointer(&memB),\n\t\tunsafe.Pointer(&size),\n\t}\n\tlogf(\"gx %d, gy %d, gz %d | bx %d by %d, bz %d\", gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ)\n\tlogf(\"CUDADO %q, Mem: %v size %v, args %v\", name, mem, size, args)\n\tlogf(\"LaunchKernel Params. mem: %v. Size %v\", mem, size)\n\te.c.LaunchAndSync(fn, gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ, 0, cu.NoStream, args)\n\treturn\n}", "func (*Secp256k1) Scalar() kyber.Scalar { return newScalar(big.NewInt(0)) }", "func INCL(mr operand.Op) { ctx.INCL(mr) }", "func DivNoNan(scope *Scope, x tf.Output, y tf.Output) (z tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"DivNoNan\",\n\t\tInput: []tf.Input{\n\t\t\tx, y,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func Null() Val { return Val{t: bsontype.Null} }", "func TestExprIsNeverNull(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\n\tdatadriven.Walk(t, \"testdata/expr\", func(t *testing.T, path string) {\n\t\tcatalog := testcat.New()\n\n\t\tdatadriven.RunTest(t, path, func(t *testing.T, d *datadriven.TestData) string {\n\t\t\ttester := opttester.New(catalog, d.Input)\n\t\t\tswitch d.Cmd {\n\t\t\tcase \"scalar-is-not-nullable\":\n\t\t\t\tctx := context.Background()\n\t\t\t\tsemaCtx := tree.MakeSemaContext()\n\t\t\t\tevalCtx := tree.MakeTestingEvalContext(cluster.MakeTestingClusterSettings())\n\n\t\t\t\tvar o xform.Optimizer\n\t\t\t\to.Init(&evalCtx, catalog)\n\n\t\t\t\tvar sv testutils.ScalarVars\n\n\t\t\t\tfor _, arg := range d.CmdArgs {\n\t\t\t\t\tkey, vals := arg.Key, arg.Vals\n\t\t\t\t\tswitch key {\n\t\t\t\t\tcase \"vars\":\n\t\t\t\t\t\terr := sv.Init(o.Memo().Metadata(), vals)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\td.Fatalf(t, \"%v\", err)\n\t\t\t\t\t\t}\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tif err := tester.Flags.Set(arg); err != nil {\n\t\t\t\t\t\t\td.Fatalf(t, \"%s\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\texpr, err := parser.ParseExpr(d.Input)\n\t\t\t\tif err != nil {\n\t\t\t\t\td.Fatalf(t, \"%v\", err)\n\t\t\t\t}\n\n\t\t\t\tb := optbuilder.NewScalar(ctx, &semaCtx, &evalCtx, o.Factory())\n\t\t\t\terr = b.Build(expr)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Sprintf(\"error: %s\\n\", strings.TrimSpace(err.Error()))\n\t\t\t\t}\n\t\t\t\tresult := memo.ExprIsNeverNull(o.Memo().RootExpr().(opt.ScalarExpr), sv.NotNullCols())\n\t\t\t\treturn fmt.Sprintf(\"%t\\n\", result)\n\n\t\t\tdefault:\n\t\t\t\treturn tester.RunCommand(t, d)\n\t\t\t}\n\t\t})\n\t})\n}", "func (*Base) LiteralNull(p ASTPass, node *ast.LiteralNull, ctx Context) {\n}", "func KXNORW(k, k1, k2 operand.Op) { ctx.KXNORW(k, k1, k2) }", "func (e *Engine) EqScalar(a tensor.Tensor, b interface{}, leftTensor bool, opts ...tensor.FuncOpt) (retVal tensor.Tensor, err error) {\n\tname := constructName1(a, leftTensor, \"eq\")\n\tif !e.HasFunc(name) {\n\t\treturn nil, errors.Errorf(\"Unable to perform EqScalar(). The tensor engine does not have the function %q\", name)\n\t}\n\n\tvar bMem tensor.Memory\n\tvar ok bool\n\tif bMem, ok = b.(tensor.Memory); !ok {\n\t\treturn nil, errors.Errorf(\"b has to be a tensor.Memory. Got %T instead\", b)\n\t}\n\n\tif err = unaryCheck(a); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Basic checks failed for EqScalar\")\n\t}\n\n\tvar reuse tensor.DenseTensor\n\tvar safe, toReuse bool\n\tif reuse, safe, toReuse, _, _, err = handleFuncOpts(a.Shape(), a.Dtype(), a.DataOrder(), true, opts...); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Unable to handle funcOpts\")\n\t}\n\n\tvar mem, memB cu.DevicePtr\n\tvar size int64\n\n\tswitch {\n\tcase toReuse:\n\t\tmem = cu.DevicePtr(reuse.Uintptr())\n\t\tmemA := cu.DevicePtr(a.Uintptr())\n\t\tmemSize := int64(a.MemSize())\n\t\te.memcpy(mem, memA, memSize)\n\n\t\tsize = int64(logicalSize(reuse.Shape()))\n\t\tretVal = reuse\n\tcase !safe:\n\t\tmem = cu.DevicePtr(a.Uintptr())\n\t\tretVal = a\n\t\tsize = int64(logicalSize(a.Shape()))\n\tdefault:\n\t\treturn nil, errors.New(\"Impossible state: A reuse tensor must be passed in, or the operation must be unsafe. Incr and safe operations are not supported\")\n\t}\n\n\tmemB = cu.DevicePtr(bMem.Uintptr())\n\tif !leftTensor {\n\t\tmem, memB = memB, mem\n\t}\n\n\tfn := e.f[name]\n\tgridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ := e.ElemGridSize(int(size))\n\targs := []unsafe.Pointer{\n\t\tunsafe.Pointer(&mem),\n\t\tunsafe.Pointer(&memB),\n\t\tunsafe.Pointer(&size),\n\t}\n\tlogf(\"gx %d, gy %d, gz %d | bx %d by %d, bz %d\", gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ)\n\tlogf(\"CUDADO %q, Mem: %v size %v, args %v\", name, mem, size, args)\n\tlogf(\"LaunchKernel Params. mem: %v. Size %v\", mem, size)\n\te.c.LaunchAndSync(fn, gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ, 0, cu.NoStream, args)\n\treturn\n}", "func (e *Engine) LteScalar(a tensor.Tensor, b interface{}, leftTensor bool, opts ...tensor.FuncOpt) (retVal tensor.Tensor, err error) {\n\tname := constructName1(a, leftTensor, \"lte\")\n\tif !e.HasFunc(name) {\n\t\treturn nil, errors.Errorf(\"Unable to perform LteScalar(). The tensor engine does not have the function %q\", name)\n\t}\n\n\tvar bMem tensor.Memory\n\tvar ok bool\n\tif bMem, ok = b.(tensor.Memory); !ok {\n\t\treturn nil, errors.Errorf(\"b has to be a tensor.Memory. Got %T instead\", b)\n\t}\n\n\tif err = unaryCheck(a); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Basic checks failed for LteScalar\")\n\t}\n\n\tvar reuse tensor.DenseTensor\n\tvar safe, toReuse bool\n\tif reuse, safe, toReuse, _, _, err = handleFuncOpts(a.Shape(), a.Dtype(), a.DataOrder(), true, opts...); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Unable to handle funcOpts\")\n\t}\n\n\tvar mem, memB cu.DevicePtr\n\tvar size int64\n\n\tswitch {\n\tcase toReuse:\n\t\tmem = cu.DevicePtr(reuse.Uintptr())\n\t\tmemA := cu.DevicePtr(a.Uintptr())\n\t\tmemSize := int64(a.MemSize())\n\t\te.memcpy(mem, memA, memSize)\n\n\t\tsize = int64(logicalSize(reuse.Shape()))\n\t\tretVal = reuse\n\tcase !safe:\n\t\tmem = cu.DevicePtr(a.Uintptr())\n\t\tretVal = a\n\t\tsize = int64(logicalSize(a.Shape()))\n\tdefault:\n\t\treturn nil, errors.New(\"Impossible state: A reuse tensor must be passed in, or the operation must be unsafe. Incr and safe operations are not supported\")\n\t}\n\n\tmemB = cu.DevicePtr(bMem.Uintptr())\n\tif !leftTensor {\n\t\tmem, memB = memB, mem\n\t}\n\n\tfn := e.f[name]\n\tgridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ := e.ElemGridSize(int(size))\n\targs := []unsafe.Pointer{\n\t\tunsafe.Pointer(&mem),\n\t\tunsafe.Pointer(&memB),\n\t\tunsafe.Pointer(&size),\n\t}\n\tlogf(\"gx %d, gy %d, gz %d | bx %d by %d, bz %d\", gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ)\n\tlogf(\"CUDADO %q, Mem: %v size %v, args %v\", name, mem, size, args)\n\tlogf(\"LaunchKernel Params. mem: %v. Size %v\", mem, size)\n\te.c.LaunchAndSync(fn, gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ, 0, cu.NoStream, args)\n\treturn\n}", "func (c *Compiler) null(is IniSection, sc *StateControllerBase, _ int8) (StateController, error) {\n\treturn nullStateController, nil\n}", "func (e *Engine) LtScalar(a tensor.Tensor, b interface{}, leftTensor bool, opts ...tensor.FuncOpt) (retVal tensor.Tensor, err error) {\n\tname := constructName1(a, leftTensor, \"lt\")\n\tif !e.HasFunc(name) {\n\t\treturn nil, errors.Errorf(\"Unable to perform LtScalar(). The tensor engine does not have the function %q\", name)\n\t}\n\n\tvar bMem tensor.Memory\n\tvar ok bool\n\tif bMem, ok = b.(tensor.Memory); !ok {\n\t\treturn nil, errors.Errorf(\"b has to be a tensor.Memory. Got %T instead\", b)\n\t}\n\n\tif err = unaryCheck(a); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Basic checks failed for LtScalar\")\n\t}\n\n\tvar reuse tensor.DenseTensor\n\tvar safe, toReuse bool\n\tif reuse, safe, toReuse, _, _, err = handleFuncOpts(a.Shape(), a.Dtype(), a.DataOrder(), true, opts...); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Unable to handle funcOpts\")\n\t}\n\n\tvar mem, memB cu.DevicePtr\n\tvar size int64\n\n\tswitch {\n\tcase toReuse:\n\t\tmem = cu.DevicePtr(reuse.Uintptr())\n\t\tmemA := cu.DevicePtr(a.Uintptr())\n\t\tmemSize := int64(a.MemSize())\n\t\te.memcpy(mem, memA, memSize)\n\n\t\tsize = int64(logicalSize(reuse.Shape()))\n\t\tretVal = reuse\n\tcase !safe:\n\t\tmem = cu.DevicePtr(a.Uintptr())\n\t\tretVal = a\n\t\tsize = int64(logicalSize(a.Shape()))\n\tdefault:\n\t\treturn nil, errors.New(\"Impossible state: A reuse tensor must be passed in, or the operation must be unsafe. Incr and safe operations are not supported\")\n\t}\n\n\tmemB = cu.DevicePtr(bMem.Uintptr())\n\tif !leftTensor {\n\t\tmem, memB = memB, mem\n\t}\n\n\tfn := e.f[name]\n\tgridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ := e.ElemGridSize(int(size))\n\targs := []unsafe.Pointer{\n\t\tunsafe.Pointer(&mem),\n\t\tunsafe.Pointer(&memB),\n\t\tunsafe.Pointer(&size),\n\t}\n\tlogf(\"gx %d, gy %d, gz %d | bx %d by %d, bz %d\", gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ)\n\tlogf(\"CUDADO %q, Mem: %v size %v, args %v\", name, mem, size, args)\n\tlogf(\"LaunchKernel Params. mem: %v. Size %v\", mem, size)\n\te.c.LaunchAndSync(fn, gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ, 0, cu.NoStream, args)\n\treturn\n}", "func nilSparseRealVector(length int) *SparseRealVector {\n return &SparseRealVector{values: make(map[int]*Real), n: length}\n}", "func NullSparseRealVector(length int) *SparseRealVector {\n v := nilSparseRealVector(length)\n return v\n}", "func KXNORQ(k, k1, k2 operand.Op) { ctx.KXNORQ(k, k1, k2) }", "func nonnilptr(b *Block) *Value {\n\tif len(b.Preds) == 1 {\n\t\tbp := b.Preds[0].b\n\t\tif bp.Kind == BlockCheck {\n\t\t\treturn bp.Control.Args[0]\n\t\t}\n\t\tif bp.Kind == BlockIf && bp.Control.Op == OpIsNonNil && bp.Succs[0].b == b {\n\t\t\treturn bp.Control.Args[0]\n\t\t}\n\t}\n\treturn nil\n}", "func (n null) Float() float64 {\n\tpanic(ErrInvalidConvNilToFloat)\n}", "func NullModifier(i interface{}) (interface{}, error) {\n\treturn i, nil\n}", "func Div(a, b interface{}, opts ...FuncOpt) (retVal Tensor, err error) {\n\tad, adok := a.(*Dense)\n\tbd, bdok := b.(*Dense)\n\n\tswitch {\n\tcase adok && bdok:\n\t\treturn ad.Div(bd, opts...)\n\tcase adok && !bdok:\n\t\treturn ad.ScaleInv(b, opts...)\n\tcase !adok && bdok:\n\t\treturn bd.ScaleInvR(a, opts...)\n\t}\n\tpanic(\"Unreachable\")\n}", "func Nop(c *CPU) {\n}", "func BlobIsNil() predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.IsNull(s.C(FieldBlob)))\n\t})\n}", "func nilcheckelim(f *Func) {\n\t// A nil check is redundant if the same nil check was successful in a\n\t// dominating block. The efficacy of this pass depends heavily on the\n\t// efficacy of the cse pass.\n\tidom := f.idom\n\tdomTree := make([][]*Block, f.NumBlocks())\n\n\t// Create a block ID -> [dominees] mapping\n\tfor _, b := range f.Blocks {\n\t\tif dom := idom[b.ID]; dom != nil {\n\t\t\tdomTree[dom.ID] = append(domTree[dom.ID], b)\n\t\t}\n\t}\n\n\t// TODO: Eliminate more nil checks.\n\t// We can recursively remove any chain of fixed offset calculations,\n\t// i.e. struct fields and array elements, even with non-constant\n\t// indices: x is non-nil iff x.a.b[i].c is.\n\n\ttype walkState int\n\tconst (\n\t\tWork walkState = iota // clear nil check if we should and traverse to dominees regardless\n\t\tRecPtr // record the pointer as being nil checked\n\t\tClearPtr\n\t)\n\n\ttype bp struct {\n\t\tblock *Block // block, or nil in RecPtr/ClearPtr state\n\t\tptr *Value // if non-nil, ptr that is to be set/cleared in RecPtr/ClearPtr state\n\t\top walkState\n\t}\n\n\twork := make([]bp, 0, 256)\n\twork = append(work, bp{block: f.Entry})\n\n\t// map from value ID to bool indicating if value is known to be non-nil\n\t// in the current dominator path being walked. This slice is updated by\n\t// walkStates to maintain the known non-nil values.\n\tnonNilValues := make([]bool, f.NumValues())\n\n\t// make an initial pass identifying any non-nil values\n\tfor _, b := range f.Blocks {\n\t\t// a value resulting from taking the address of a\n\t\t// value, or a value constructed from an offset of a\n\t\t// non-nil ptr (OpAddPtr) implies it is non-nil\n\t\tfor _, v := range b.Values {\n\t\t\tif v.Op == OpAddr || v.Op == OpAddPtr {\n\t\t\t\tnonNilValues[v.ID] = true\n\t\t\t} else if v.Op == OpPhi {\n\t\t\t\t// phis whose arguments are all non-nil\n\t\t\t\t// are non-nil\n\t\t\t\targsNonNil := true\n\t\t\t\tfor _, a := range v.Args {\n\t\t\t\t\tif !nonNilValues[a.ID] {\n\t\t\t\t\t\targsNonNil = false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif argsNonNil {\n\t\t\t\t\tnonNilValues[v.ID] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// perform a depth first walk of the dominee tree\n\tfor len(work) > 0 {\n\t\tnode := work[len(work)-1]\n\t\twork = work[:len(work)-1]\n\n\t\tswitch node.op {\n\t\tcase Work:\n\t\t\tchecked := checkedptr(node.block) // ptr being checked for nil/non-nil\n\t\t\tnonnil := nonnilptr(node.block) // ptr that is non-nil due to this blocks pred\n\n\t\t\tif checked != nil {\n\t\t\t\t// already have a nilcheck in the dominator path, or this block is a success\n\t\t\t\t// block for the same value it is checking\n\t\t\t\tif nonNilValues[checked.ID] || checked == nonnil {\n\t\t\t\t\t// Eliminate the nil check.\n\t\t\t\t\t// The deadcode pass will remove vestigial values,\n\t\t\t\t\t// and the fuse pass will join this block with its successor.\n\n\t\t\t\t\t// Logging in the style of the former compiler -- and omit line 1,\n\t\t\t\t\t// which is usually in generated code.\n\t\t\t\t\tif f.Config.Debug_checknil() && node.block.Control.Line > 1 {\n\t\t\t\t\t\tf.Config.Warnl(node.block.Control.Line, \"removed nil check\")\n\t\t\t\t\t}\n\n\t\t\t\t\tswitch node.block.Kind {\n\t\t\t\t\tcase BlockIf:\n\t\t\t\t\t\tnode.block.Kind = BlockFirst\n\t\t\t\t\t\tnode.block.SetControl(nil)\n\t\t\t\t\tcase BlockCheck:\n\t\t\t\t\t\tnode.block.Kind = BlockPlain\n\t\t\t\t\t\tnode.block.SetControl(nil)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tf.Fatalf(\"bad block kind in nilcheck %s\", node.block.Kind)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif nonnil != nil && !nonNilValues[nonnil.ID] {\n\t\t\t\t// this is a new nilcheck so add a ClearPtr node to clear the\n\t\t\t\t// ptr from the map of nil checks once we traverse\n\t\t\t\t// back up the tree\n\t\t\t\twork = append(work, bp{op: ClearPtr, ptr: nonnil})\n\t\t\t}\n\n\t\t\t// add all dominated blocks to the work list\n\t\t\tfor _, w := range domTree[node.block.ID] {\n\t\t\t\twork = append(work, bp{block: w})\n\t\t\t}\n\n\t\t\tif nonnil != nil && !nonNilValues[nonnil.ID] {\n\t\t\t\twork = append(work, bp{op: RecPtr, ptr: nonnil})\n\t\t\t}\n\t\tcase RecPtr:\n\t\t\tnonNilValues[node.ptr.ID] = true\n\t\t\tcontinue\n\t\tcase ClearPtr:\n\t\t\tnonNilValues[node.ptr.ID] = false\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func BlobIsNil() predicate.User {\n\treturn predicate.User(sql.FieldIsNull(FieldBlob))\n}", "func (e ReduceTensorOp) C() C.cudnnReduceTensorOp_t { return C.cudnnReduceTensorOp_t(e) }", "func (n null) Div(v Val) Val {\n\tpanic(ErrInvalidOpDivOnNil)\n}", "func VREDUCESS(ops ...operand.Op) { ctx.VREDUCESS(ops...) }", "func VUCOMISS(mx, x operand.Op) { ctx.VUCOMISS(mx, x) }", "func (t *Dense) ModScalar(other interface{}, leftTensor bool, opts ...FuncOpt) (retVal *Dense, err error) {\n\tvar ret Tensor\n\tif t.oe != nil {\n\t\tif ret, err = t.oe.ModScalar(t, other, leftTensor, opts...); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"Unable to do ModScalar()\")\n\t\t}\n\t\tif retVal, err = assertDense(ret); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, opFail, \"ModScalar\")\n\t\t}\n\t\treturn\n\t}\n\n\tif moder, ok := t.e.(Moder); ok {\n\t\tif ret, err = moder.ModScalar(t, other, leftTensor, opts...); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"Unable to do ModScalar()\")\n\t\t}\n\t\tif retVal, err = assertDense(ret); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, opFail, \"ModScalar\")\n\t\t}\n\t\treturn\n\t}\n\treturn nil, errors.Errorf(\"Engine does not support ModScalar()\")\n}", "func KXNORB(k, k1, k2 operand.Op) { ctx.KXNORB(k, k1, k2) }", "func (f Float64) Filter(c func(float64) bool) Float64 {\n\tif c == nil || !f.IsPresent() || !c(f.value) {\n\t\treturn Float64{}\n\t}\n\treturn f\n}", "func (e NanPropagation) C() C.cudnnNanPropagation_t { return C.cudnnNanPropagation_t(e) }", "func (tbl DbCompoundTable) QueryOneNullFloat64(req require.Requirement, query string, args ...interface{}) (result sql.NullFloat64, err error) {\n\terr = support.QueryOneNullThing(tbl, req, &result, query, args...)\n\treturn result, err\n}", "func NullValue() Value { return Value{Typ: '$', Null: true} }", "func COMISS(mx, x operand.Op) { ctx.COMISS(mx, x) }", "func (a *Array64) Nonzero(axis ...int) *Array64 {\n\tif a.valAxis(&axis, \"Nonzero\") {\n\t\treturn a\n\t}\n\n\treturn a.Map(func(d float64) float64 {\n\t\tif d == 0 {\n\t\t\treturn 0\n\t\t}\n\t\treturn 1\n\t}).Sum(axis...)\n}", "func UCOMISS(mx, x operand.Op) { ctx.UCOMISS(mx, x) }", "func KNOTW(k, k1 operand.Op) { ctx.KNOTW(k, k1) }", "func (np *vpoint) zeroOut() {\n\tnp.elems = nil\n}", "func BufferIsNil() predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.IsNull(s.C(FieldBuffer)))\n\t})\n}", "func UCOMISD(mx, x operand.Op) { ctx.UCOMISD(mx, x) }", "func NoopFilter(index string, data []byte) ([]byte, error) {\n\treturn data, nil\n}", "func Coalesce[T any](vs ...T) T {\n\tfor _, v := range vs {\n\t\tif !isZero(v) {\n\t\t\treturn v\n\t\t}\n\t}\n\treturn *new(T)\n}", "func Any(scope *Scope, input tf.Output, axis tf.Output, optional ...AnyAttr) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{}\n\tfor _, a := range optional {\n\t\ta(attrs)\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"Any\",\n\t\tInput: []tf.Input{\n\t\t\tinput, axis,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func (s *CPUStat) Kernel() float64 {\n\treturn s.All.Kernel() * float64(len(s.cpus))\n}", "func BufferIsNil() predicate.User {\n\treturn predicate.User(sql.FieldIsNull(FieldBuffer))\n}", "func TestCheckBinaryExprFloatXorNil(t *testing.T) {\n\tenv := MakeSimpleEnv()\n\n\texpectCheckError(t, `2.0 ^ nil`, env,\n\t\t`cannot convert nil to type float64`,\n\t\t`invalid operation: 2 ^ nil (mismatched types float64 and <T>)`,\n\t)\n\n}", "func NaN32() float32 { return Float32frombits(uvnan32) }", "func NEGL(mr operand.Op) { ctx.NEGL(mr) }", "func Empty(scope *Scope, shape tf.Output, dtype tf.DataType, optional ...EmptyAttr) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{\"dtype\": dtype}\n\tfor _, a := range optional {\n\t\ta(attrs)\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"Empty\",\n\t\tInput: []tf.Input{\n\t\t\tshape,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func BenchmarkModNScalarIsZero(b *testing.B) {\n\tvar s1 ModNScalar\n\ts1.SetByteSlice(benchmarkVals()[0])\n\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = s1.IsZero()\n\t}\n}", "func ReturnTensor(t Tensor) {\n\tif !usePool {\n\t\treturn\n\t}\n\tswitch tt := t.(type) {\n\tcase *Dense:\n\t\ttt.AP.zero()\n\n\t\tif tt.transposeWith != nil {\n\t\t\tReturnInts(tt.transposeWith)\n\t\t\ttt.transposeWith = nil\n\t\t}\n\n\t\t// array reset\n\t\ttt.t = Dtype{}\n\t\ttt.array.Header.Raw = nil\n\n\t\t// engine and flag reset\n\t\ttt.e = StdEng{}\n\t\ttt.oe = nil\n\t\ttt.flag = 0\n\n\t\t// other reset\n\t\ttt.old.zero()\n\t\ttt.viewOf = 0\n\t\ttt.transposeWith = nil\n\n\t\t// mask related stuff - TODO: deprecate\n\t\ttt.mask = nil\n\t\ttt.maskIsSoft = false\n\n\t\t// densePool.Put(tt)\n\t\tif len(densePool) < cap(densePool) {\n\t\t\tdensePool <- tt\n\t\t}\n\t}\n}", "func (e OpTensorOp) C() C.cudnnOpTensorOp_t { return C.cudnnOpTensorOp_t(e) }", "func (ServerConfig) elemValueOrNil(v interface{}) interface{} {\n\tif t := reflect.TypeOf(v); t.Kind() == reflect.Ptr {\n\t\tif reflect.ValueOf(v).IsNil() {\n\t\t\treturn reflect.Zero(t.Elem()).Interface()\n\t\t} else {\n\t\t\treturn reflect.ValueOf(v).Interface()\n\t\t}\n\t} else if v == nil {\n\t\treturn reflect.Zero(t).Interface()\n\t}\n\n\treturn v\n}", "func BenchmarkModNScalarZero(b *testing.B) {\n\tvar s1 ModNScalar\n\ts1.SetByteSlice(benchmarkVals()[0])\n\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\ts1.Zero()\n\t}\n}", "func VUCOMISD(mx, x operand.Op) { ctx.VUCOMISD(mx, x) }", "func TestCheckBinaryExprNilXorFloat(t *testing.T) {\n\tenv := MakeSimpleEnv()\n\n\texpectCheckError(t, `nil ^ 2.0`, env,\n\t\t`cannot convert nil to type float64`,\n\t\t`invalid operation: nil ^ 2 (mismatched types <T> and float64)`,\n\t)\n\n}", "func JNO(r operand.Op) { ctx.JNO(r) }", "func JOS(r operand.Op) { ctx.JOS(r) }", "func Null() Value {\n\tpanic(message)\n}", "func zeroFunc(time.Duration) float64 { return 0 }", "func FuncRetEmptyFunc() func()", "func NOTW(mr operand.Op) { ctx.NOTW(mr) }", "func BlobNotNil() predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.NotNull(s.C(FieldBlob)))\n\t})\n}", "func NULL_VECTOR(length int) VECTOR_TYPE {\n v := NIL_VECTOR(length)\n return v\n}", "func EvaluateExprWithNull(ctx sessionctx.Context, schema *Schema, expr Expression) Expression {\n\tswitch x := expr.(type) {\n\tcase *ScalarFunction:\n\t\targs := make([]Expression, len(x.GetArgs()))\n\t\tfor i, arg := range x.GetArgs() {\n\t\t\targs[i] = EvaluateExprWithNull(ctx, schema, arg)\n\t\t}\n\t\treturn NewFunctionInternal(ctx, x.FuncName.L, x.RetType, args...)\n\tcase *Column:\n\t\tif !schema.Contains(x) {\n\t\t\treturn x\n\t\t}\n\t\treturn &Constant{Value: types.Datum{}, RetType: types.NewFieldType(mysql.TypeNull)}\n\tcase *Constant:\n\t\tif x.DeferredExpr != nil {\n\t\t\treturn FoldConstant(x)\n\t\t}\n\t}\n\treturn expr\n}", "func (e *Engine) ElNe(a tensor.Tensor, b tensor.Tensor, opts ...tensor.FuncOpt) (retVal tensor.Tensor, err error) {\n\tname := constructName2(a, b, \"ne\")\n\n\tif !e.HasFunc(name) {\n\t\treturn nil, errors.Errorf(\"Unable to perform ElNe(). The tensor engine does not have the function %q\", name)\n\t}\n\n\tif err = binaryCheck(a, b); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Basic checks failed for ElNe\")\n\t}\n\n\tvar reuse tensor.DenseTensor\n\tvar safe, toReuse bool\n\tif reuse, safe, toReuse, _, _, err = handleFuncOpts(a.Shape(), a.Dtype(), a.DataOrder(), true, opts...); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Unable to handle funcOpts\")\n\t}\n\n\tvar mem, memB cu.DevicePtr\n\tvar size int64\n\n\tswitch {\n\tcase toReuse:\n\t\tmem = cu.DevicePtr(reuse.Uintptr())\n\t\tmemA := cu.DevicePtr(a.Uintptr())\n\t\tmemSize := int64(a.MemSize())\n\t\te.memcpy(mem, memA, memSize)\n\n\t\tsize = int64(logicalSize(reuse.Shape()))\n\t\tretVal = reuse\n\tcase !safe:\n\t\tmem = cu.DevicePtr(a.Uintptr())\n\t\tretVal = a\n\t\tsize = int64(logicalSize(a.Shape()))\n\tdefault:\n\t\treturn nil, errors.New(\"Impossible state: A reuse tensor must be passed in, or the operation must be unsafe. Incr and safe operations are not supported\")\n\t}\n\n\tmemB = cu.DevicePtr(b.Uintptr())\n\tfn := e.f[name]\n\tgridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ := e.ElemGridSize(int(size))\n\targs := []unsafe.Pointer{\n\t\tunsafe.Pointer(&mem),\n\t\tunsafe.Pointer(&memB),\n\t\tunsafe.Pointer(&size),\n\t}\n\tlogf(\"gx %d, gy %d, gz %d | bx %d by %d, bz %d\", gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ)\n\tlogf(\"CUDADO %q, Mem: %v MemB: %v size %v, args %v\", name, mem, memB, size, args)\n\tlogf(\"LaunchKernel Params. mem: %v. Size %v\", mem, size)\n\te.c.LaunchAndSync(fn, gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ, 0, cu.NoStream, args)\n\treturn\n}", "func nullCtor() (core.Aggregator, error) {\n\treturn nil, nil\n}", "func OptionalNone(scope *Scope) (optional tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"OptionalNone\",\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func ValueIsNil() predicate.Blob {\n\treturn predicate.Blob(\n\t\tfunc(s *sql.Selector) {\n\t\t\ts.Where(sql.IsNull(s.C(FieldValue)))\n\t\t},\n\t)\n}", "func TestCheckBinaryExprFloatRhlNil(t *testing.T) {\n\tenv := MakeSimpleEnv()\n\n\texpectCheckError(t, `2.0 >> nil`, env,\n\t\t`cannot convert nil to type uint`,\n\t)\n\n}", "func IDIVW(mr operand.Op) { ctx.IDIVW(mr) }", "func VCOMISS(mx, x operand.Op) { ctx.VCOMISS(mx, x) }", "func NOP() { ctx.NOP() }", "func (t *Dense) Zero() {\n\tif t.IsMaterializable() {\n\t\tif err := t.zeroIter(); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tif t.IsMasked() {\n\t\tt.ResetMask()\n\t}\n\tswitch t.t.Kind() {\n\tcase reflect.Bool:\n\t\tdata := t.bools()\n\t\tfor i := range data {\n\t\t\tdata[i] = false\n\n\t\t}\n\tcase reflect.Int:\n\t\tdata := t.ints()\n\t\tfor i := range data {\n\t\t\tdata[i] = 0\n\t\t}\n\tcase reflect.Int8:\n\t\tdata := t.int8s()\n\t\tfor i := range data {\n\t\t\tdata[i] = 0\n\t\t}\n\tcase reflect.Int16:\n\t\tdata := t.int16s()\n\t\tfor i := range data {\n\t\t\tdata[i] = 0\n\t\t}\n\tcase reflect.Int32:\n\t\tdata := t.int32s()\n\t\tfor i := range data {\n\t\t\tdata[i] = 0\n\t\t}\n\tcase reflect.Int64:\n\t\tdata := t.int64s()\n\t\tfor i := range data {\n\t\t\tdata[i] = 0\n\t\t}\n\tcase reflect.Uint:\n\t\tdata := t.uints()\n\t\tfor i := range data {\n\t\t\tdata[i] = 0\n\t\t}\n\tcase reflect.Uint8:\n\t\tdata := t.uint8s()\n\t\tfor i := range data {\n\t\t\tdata[i] = 0\n\t\t}\n\tcase reflect.Uint16:\n\t\tdata := t.uint16s()\n\t\tfor i := range data {\n\t\t\tdata[i] = 0\n\t\t}\n\tcase reflect.Uint32:\n\t\tdata := t.uint32s()\n\t\tfor i := range data {\n\t\t\tdata[i] = 0\n\t\t}\n\tcase reflect.Uint64:\n\t\tdata := t.uint64s()\n\t\tfor i := range data {\n\t\t\tdata[i] = 0\n\t\t}\n\tcase reflect.Uintptr:\n\t\tdata := t.uintptrs()\n\t\tfor i := range data {\n\t\t\tdata[i] = 0\n\t\t}\n\tcase reflect.Float32:\n\t\tdata := t.float32s()\n\t\tfor i := range data {\n\t\t\tdata[i] = 0\n\t\t}\n\tcase reflect.Float64:\n\t\tdata := t.float64s()\n\t\tfor i := range data {\n\t\t\tdata[i] = 0\n\t\t}\n\tcase reflect.Complex64:\n\t\tdata := t.complex64s()\n\t\tfor i := range data {\n\t\t\tdata[i] = 0\n\t\t}\n\tcase reflect.Complex128:\n\t\tdata := t.complex128s()\n\t\tfor i := range data {\n\t\t\tdata[i] = 0\n\t\t}\n\tcase reflect.String:\n\t\tdata := t.strings()\n\t\tfor i := range data {\n\t\t\tdata[i] = \"\"\n\n\t\t}\n\tcase reflect.UnsafePointer:\n\t\tdata := t.unsafePointers()\n\t\tfor i := range data {\n\t\t\tdata[i] = nil\n\n\t\t}\n\tdefault:\n\t\tptr := uintptr(t.data)\n\t\tfor i := 0; i < t.hdr.Len; i++ {\n\t\t\twant := ptr + uintptr(i)*t.t.Size()\n\t\t\tval := reflect.NewAt(t.t, unsafe.Pointer(want))\n\t\t\tval = reflect.Indirect(val)\n\t\t\tval.Set(reflect.Zero(t.t))\n\t\t}\n\t}\n}", "func ScalarProduct(v1, v2 []float64) (product float64) {\n\tfor i := range v1 {\n\t\tproduct += v1[i] * v2[i]\n\t}\n\treturn\n}", "func (o OceanFiltersPtrOutput) MinGpu() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *OceanFilters) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.MinGpu\n\t}).(pulumi.IntPtrOutput)\n}", "func Null() Value {\n\treturn Value{v: reflect.ValueOf((*byte)(nil))}\n}", "func BlobNotNil() predicate.User {\n\treturn predicate.User(sql.FieldNotNull(FieldBlob))\n}", "func TestCheckBinaryExprFloatRemNil(t *testing.T) {\n\tenv := MakeSimpleEnv()\n\n\texpectCheckError(t, `2.0 % nil`, env,\n\t\t`cannot convert nil to type float64`,\n\t\t`invalid operation: 2 % nil (mismatched types float64 and <T>)`,\n\t)\n\n}", "func BenchmarkModNScalarNegate(b *testing.B) {\n\tvar s1 ModNScalar\n\ts1.SetByteSlice(benchmarkVals()[0])\n\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = new(ModNScalar).NegateVal(&s1)\n\t}\n}", "func Zero() Vect { return Vect{} }", "func (c *CSR) DoNonZero(fn func(i, j int, v float64)) {\n\tfor i := 0; i < len(c.matrix.Indptr)-1; i++ {\n\t\tc.DoRowNonZero(i, fn)\n\t}\n}", "func Null(fieldPtr interface{}) Filter {\n\treturn &NullFilter{fieldPtr}\n}", "func (e *Engine) Gte(a tensor.Tensor, b tensor.Tensor, opts ...tensor.FuncOpt) (retVal tensor.Tensor, err error) {\n\tname := constructName2(a, b, \"gte\")\n\n\tif !e.HasFunc(name) {\n\t\treturn nil, errors.Errorf(\"Unable to perform Gte(). The tensor engine does not have the function %q\", name)\n\t}\n\n\tif err = binaryCheck(a, b); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Basic checks failed for Gte\")\n\t}\n\n\tvar reuse tensor.DenseTensor\n\tvar safe, toReuse bool\n\tif reuse, safe, toReuse, _, _, err = handleFuncOpts(a.Shape(), a.Dtype(), a.DataOrder(), true, opts...); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Unable to handle funcOpts\")\n\t}\n\n\tvar mem, memB cu.DevicePtr\n\tvar size int64\n\n\tswitch {\n\tcase toReuse:\n\t\tmem = cu.DevicePtr(reuse.Uintptr())\n\t\tmemA := cu.DevicePtr(a.Uintptr())\n\t\tmemSize := int64(a.MemSize())\n\t\te.memcpy(mem, memA, memSize)\n\n\t\tsize = int64(logicalSize(reuse.Shape()))\n\t\tretVal = reuse\n\tcase !safe:\n\t\tmem = cu.DevicePtr(a.Uintptr())\n\t\tretVal = a\n\t\tsize = int64(logicalSize(a.Shape()))\n\tdefault:\n\t\treturn nil, errors.New(\"Impossible state: A reuse tensor must be passed in, or the operation must be unsafe. Incr and safe operations are not supported\")\n\t}\n\n\tmemB = cu.DevicePtr(b.Uintptr())\n\tfn := e.f[name]\n\tgridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ := e.ElemGridSize(int(size))\n\targs := []unsafe.Pointer{\n\t\tunsafe.Pointer(&mem),\n\t\tunsafe.Pointer(&memB),\n\t\tunsafe.Pointer(&size),\n\t}\n\tlogf(\"gx %d, gy %d, gz %d | bx %d by %d, bz %d\", gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ)\n\tlogf(\"CUDADO %q, Mem: %v MemB: %v size %v, args %v\", name, mem, memB, size, args)\n\tlogf(\"LaunchKernel Params. mem: %v. Size %v\", mem, size)\n\te.c.LaunchAndSync(fn, gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ, 0, cu.NoStream, args)\n\treturn\n}", "func getZero[T any]() T {\n\tvar result T\n\treturn result\n}", "func NilFloat() Float {\n\treturn Float{0, false}\n}", "func TestCheckBinaryExprFloatEqlNil(t *testing.T) {\n\tenv := MakeSimpleEnv()\n\n\texpectCheckError(t, `2.0 == nil`, env,\n\t\t`cannot convert nil to type float64`,\n\t\t`invalid operation: 2 == nil (mismatched types float64 and <T>)`,\n\t)\n\n}", "func builtinCoalesce(args []types.Datum, ctx context.Context) (d types.Datum, err error) {\n\tfor _, d = range args {\n\t\tif !d.IsNull() {\n\t\t\treturn d, nil\n\t\t}\n\t}\n\treturn d, nil\n}", "func Vneg(input []float32, inputStride int, output []float32, outputStride int) {\n\tC.vDSP_vneg((*C.float)(&input[0]), C.vDSP_Stride(inputStride), (*C.float)(&output[0]), C.vDSP_Stride(outputStride), C.vDSP_Length(len(output)/outputStride))\n}", "func NoOp(scope *Scope) (o *tf.Operation) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"NoOp\",\n\t}\n\treturn scope.AddOperation(opspec)\n}", "func planIsNullProjectionOp(\n\tctx context.Context,\n\tevalCtx *tree.EvalContext,\n\toutputType *types.T,\n\texpr tree.TypedExpr,\n\tcolumnTypes []*types.T,\n\tinput colexecop.Operator,\n\tacc *mon.BoundAccount,\n\tnegate bool,\n\tfactory coldata.ColumnFactory,\n) (op colexecop.Operator, resultIdx int, typs []*types.T, err error) {\n\top, resultIdx, typs, err = planProjectionOperators(\n\t\tctx, evalCtx, expr, columnTypes, input, acc, factory,\n\t)\n\tif err != nil {\n\t\treturn op, resultIdx, typs, err\n\t}\n\toutputIdx := len(typs)\n\tisTupleNull := typs[resultIdx].Family() == types.TupleFamily\n\top = colexec.NewIsNullProjOp(\n\t\tcolmem.NewAllocator(ctx, acc, factory), op, resultIdx, outputIdx, negate, isTupleNull,\n\t)\n\ttyps = appendOneType(typs, outputType)\n\treturn op, outputIdx, typs, nil\n}" ]
[ "0.5379526", "0.52734643", "0.52604604", "0.52080774", "0.5170007", "0.51522714", "0.5124176", "0.5061064", "0.50365657", "0.5023953", "0.49725294", "0.49276504", "0.49113187", "0.4908961", "0.49065426", "0.4877512", "0.4804168", "0.48031953", "0.4780407", "0.4766727", "0.47437528", "0.47426972", "0.47336316", "0.4732954", "0.47316995", "0.4702485", "0.46901512", "0.46564898", "0.46562305", "0.46553203", "0.4635744", "0.46350023", "0.46190464", "0.4608857", "0.46045902", "0.45894697", "0.45879167", "0.45874915", "0.45831046", "0.45786437", "0.4576132", "0.45741543", "0.45732895", "0.45693016", "0.45685175", "0.4564152", "0.4552512", "0.45498207", "0.4544598", "0.4540831", "0.4529088", "0.45282167", "0.45133477", "0.45120114", "0.450786", "0.44947106", "0.4493988", "0.4487556", "0.44836053", "0.4478584", "0.44778913", "0.44667774", "0.44653377", "0.4462664", "0.4460176", "0.4451146", "0.44501522", "0.44413763", "0.44383365", "0.44361526", "0.4435706", "0.44353318", "0.44240335", "0.44194457", "0.44183964", "0.44130656", "0.44000852", "0.43914372", "0.43843758", "0.43749967", "0.43655452", "0.43646845", "0.4362698", "0.4362229", "0.43595168", "0.4357234", "0.43529516", "0.43525815", "0.43477413", "0.4343997", "0.43420753", "0.43411475", "0.43381172", "0.4333317", "0.43311673", "0.43242112", "0.43200943", "0.43190217", "0.4315338", "0.43150595", "0.43142498" ]
0.0
-1
PossiblePurgeStateValues returns an array of possible values for the PurgeState const type.
func PossiblePurgeStateValues() []PurgeState { return []PurgeState{Completed, Pending} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func PossibleGeoBackupPolicyStateValues() []GeoBackupPolicyState {\n\treturn []GeoBackupPolicyState{GeoBackupPolicyStateDisabled, GeoBackupPolicyStateEnabled}\n}", "func PossibleStateValues() []State {\n\treturn []State{Active, Deleted}\n}", "func PossibleStateValues() []State {\n\treturn []State{StateDeprovisioning, StateFailed, StateNetworkSourceDeleted, StateProvisioning, StateSucceeded}\n}", "func PossibleProvisionStateValues() []ProvisionState {\n\treturn []ProvisionState{\n\t\tProvisionStateAccepted,\n\t\tProvisionStateCanceled,\n\t\tProvisionStateCreating,\n\t\tProvisionStateDeleted,\n\t\tProvisionStateDeleting,\n\t\tProvisionStateFailed,\n\t\tProvisionStateNotSpecified,\n\t\tProvisionStateSucceeded,\n\t\tProvisionStateUpdating,\n\t}\n}", "func PossibleDigestConfigStateValues() []DigestConfigState {\n\treturn []DigestConfigState{\n\t\tDigestConfigStateActive,\n\t\tDigestConfigStateDisabled,\n\t}\n}", "func PossiblePackageStateValues() []PackageState {\n\treturn []PackageState{PackageStateActive, PackageStatePending}\n}", "func PurchasingOption_Values() []string {\n\treturn []string{\n\t\tPurchasingOptionAllUpfront,\n\t\tPurchasingOptionPartialUpfront,\n\t\tPurchasingOptionNoUpfront,\n\t}\n}", "func (VpnState) Values() []VpnState {\n\treturn []VpnState{\n\t\t\"pending\",\n\t\t\"available\",\n\t\t\"deleting\",\n\t\t\"deleted\",\n\t}\n}", "func PossibleStateValues() []State {\n\treturn []State{StateCreating, StateDeleted, StateDeleting, StateRunning, StateStarting, StateStopped, StateStopping, StateUnavailable}\n}", "func (CarrierGatewayState) Values() []CarrierGatewayState {\n\treturn []CarrierGatewayState{\n\t\t\"pending\",\n\t\t\"available\",\n\t\t\"deleting\",\n\t\t\"deleted\",\n\t}\n}", "func PossibleStateValues() []State {\n\treturn []State{StateCreating, StateDeleted, StateDeleting, StateRunning, StateStarting, StateStopped, StateStopping, StateUnavailable, StateUpdating}\n}", "func PossibleStateValues() []State {\n\treturn []State{StateApproved, StateClaimed, StateCompleted, StateCreated, StateExecuting, StateInvalid, StatePreparing, StateRestoring}\n}", "func PossibleProjectProvisioningStateValues() []ProjectProvisioningState {\n\treturn []ProjectProvisioningState{Deleting, Succeeded}\n}", "func PossibleStateValues() []State {\n\treturn []State{StateDisabled, StateEnabled}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{Creating, Deleting, Failed, Succeeded}\n}", "func (TransitGatewayState) Values() []TransitGatewayState {\n\treturn []TransitGatewayState{\n\t\t\"pending\",\n\t\t\"available\",\n\t\t\"modifying\",\n\t\t\"deleting\",\n\t\t\"deleted\",\n\t}\n}", "func (State) Values() []State {\n\treturn []State{\n\t\t\"PendingAcceptance\",\n\t\t\"Pending\",\n\t\t\"Available\",\n\t\t\"Deleting\",\n\t\t\"Deleted\",\n\t\t\"Rejected\",\n\t\t\"Failed\",\n\t\t\"Expired\",\n\t}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{Creating, Deleting, Failed, Succeeded, Updating}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{Creating, Deleting, Failed, Moving, Running, Succeeded}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{Creating, Deleting, Failed, Running, Succeeded}\n}", "func PossibleRepairTaskHealthCheckStateValues() []RepairTaskHealthCheckState {\n\treturn []RepairTaskHealthCheckState{InProgress, NotStarted, Skipped, Succeeded, TimedOut}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{\n\t\tProvisioningStateCanceled,\n\t\tProvisioningStateCreating,\n\t\tProvisioningStateDeleting,\n\t\tProvisioningStateFailed,\n\t\tProvisioningStateMoving,\n\t\tProvisioningStateRunning,\n\t\tProvisioningStateSucceeded,\n\t\tProvisioningStateUnknown,\n\t\tProvisioningStateUpdating,\n\t}\n}", "func PossiblePoolProvisioningStateValues() []PoolProvisioningState {\n\treturn []PoolProvisioningState{PoolProvisioningStateDeleting, PoolProvisioningStateSucceeded}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{Canceled, Creating, Deleting, Failed, Succeeded, Updating}\n}", "func PossibleTopicSpaceProvisioningStateValues() []TopicSpaceProvisioningState {\n\treturn []TopicSpaceProvisioningState{\n\t\tTopicSpaceProvisioningStateCanceled,\n\t\tTopicSpaceProvisioningStateCreating,\n\t\tTopicSpaceProvisioningStateDeleted,\n\t\tTopicSpaceProvisioningStateDeleting,\n\t\tTopicSpaceProvisioningStateFailed,\n\t\tTopicSpaceProvisioningStateSucceeded,\n\t\tTopicSpaceProvisioningStateUpdating,\n\t}\n}", "func PossibleBackupStateValues() []BackupState {\n\treturn []BackupState{BackupStateAccepted, BackupStateBackupInProgress, BackupStateFailure, BackupStateInvalid, BackupStateSuccess, BackupStateTimeout}\n}", "func (NatGatewayState) Values() []NatGatewayState {\n\treturn []NatGatewayState{\n\t\t\"pending\",\n\t\t\"failed\",\n\t\t\"available\",\n\t\t\"deleting\",\n\t\t\"deleted\",\n\t}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{\n\t\tProvisioningStateAccepted,\n\t\tProvisioningStateCreating,\n\t\tProvisioningStateDeleting,\n\t\tProvisioningStateFailed,\n\t\tProvisioningStateSucceeded,\n\t\tProvisioningStateUpdating,\n\t}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{\n\t\tProvisioningStateCanceled,\n\t\tProvisioningStateCreating,\n\t\tProvisioningStateDeleting,\n\t\tProvisioningStateFailed,\n\t\tProvisioningStateSucceeded,\n\t\tProvisioningStateUpdating,\n\t}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{\n\t\tProvisioningStateAccepted,\n\t\tProvisioningStateCanceled,\n\t\tProvisioningStateCreating,\n\t\tProvisioningStateDeleted,\n\t\tProvisioningStateDeleting,\n\t\tProvisioningStateFailed,\n\t\tProvisioningStateNotSpecified,\n\t\tProvisioningStateSucceeded,\n\t\tProvisioningStateUpdating,\n\t}\n}", "func PossibleSiteAvailabilityStateValues() []SiteAvailabilityState {\n\treturn []SiteAvailabilityState{DisasterRecoveryMode, Limited, Normal}\n}", "func State_Values() []string {\n\treturn []string{\n\t\tStateCreating,\n\t\tStateUpdating,\n\t\tStateDeleting,\n\t\tStateActive,\n\t\tStateError,\n\t}\n}", "func PossibleWorkloadNetworkDhcpProvisioningStateValues() []WorkloadNetworkDhcpProvisioningState {\n\treturn []WorkloadNetworkDhcpProvisioningState{WorkloadNetworkDhcpProvisioningStateBuilding, WorkloadNetworkDhcpProvisioningStateDeleting, WorkloadNetworkDhcpProvisioningStateFailed, WorkloadNetworkDhcpProvisioningStateSucceeded, WorkloadNetworkDhcpProvisioningStateUpdating}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{\n\t\tProvisioningStateCreating,\n\t\tProvisioningStateUpdating,\n\t\tProvisioningStateSucceeded,\n\t\tProvisioningStateFailed,\n\t\tProvisioningStateDeleting,\n\t\tProvisioningStateCanceled,\n\t}\n}", "func PossibleProvisioningStatesValues() []ProvisioningStates {\n\treturn []ProvisioningStates{\n\t\tProvisioningStatesCanceled,\n\t\tProvisioningStatesCreating,\n\t\tProvisioningStatesDeleting,\n\t\tProvisioningStatesFailed,\n\t\tProvisioningStatesInvalid,\n\t\tProvisioningStatesPending,\n\t\tProvisioningStatesSucceeded,\n\t\tProvisioningStatesUpdating,\n\t}\n}", "func PossibleProvisioningStatesValues() []ProvisioningStates {\n\treturn []ProvisioningStates{\n\t\tProvisioningStatesDeleting,\n\t\tProvisioningStatesExpiring,\n\t\tProvisioningStatesFailed,\n\t\tProvisioningStatesHumanIntervention,\n\t\tProvisioningStatesProvisioning,\n\t\tProvisioningStatesSucceeded,\n\t}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{\n\t\tProvisioningStateAccepted,\n\t\tProvisioningStateCanceled,\n\t\tProvisioningStateCreating,\n\t\tProvisioningStateDeleted,\n\t\tProvisioningStateFailed,\n\t\tProvisioningStateSucceeded,\n\t}\n}", "func PossibleStateValues() []State {\n\treturn []State{Active, ResolvedByPositiveResult, ResolvedByStateChange, ResolvedByTimer, ResolvedManually}\n}", "func PossibleDomainsProvisioningStateValues() []DomainsProvisioningState {\n\treturn []DomainsProvisioningState{\n\t\tDomainsProvisioningStateCanceled,\n\t\tDomainsProvisioningStateCreating,\n\t\tDomainsProvisioningStateDeleting,\n\t\tDomainsProvisioningStateFailed,\n\t\tDomainsProvisioningStateMoving,\n\t\tDomainsProvisioningStateRunning,\n\t\tDomainsProvisioningStateSucceeded,\n\t\tDomainsProvisioningStateUnknown,\n\t\tDomainsProvisioningStateUpdating,\n\t}\n}", "func PossibleReadinessStateValues() []ReadinessState {\n\treturn []ReadinessState{\n\t\tReadinessStateActivated,\n\t\tReadinessStateNeverActivated,\n\t}\n}", "func PossibleUpgradeDomainStateValues() []UpgradeDomainState {\n\treturn []UpgradeDomainState{UpgradeDomainStateCompleted, UpgradeDomainStateInProgress, UpgradeDomainStateInvalid, UpgradeDomainStatePending}\n}", "func PossibleDomainProvisioningStateValues() []DomainProvisioningState {\n\treturn []DomainProvisioningState{Canceled, Creating, Deleting, Failed, Succeeded, Updating}\n}", "func (PlacementGroupState) Values() []PlacementGroupState {\n\treturn []PlacementGroupState{\n\t\t\"pending\",\n\t\t\"available\",\n\t\t\"deleting\",\n\t\t\"deleted\",\n\t}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{Accepted, Canceled, Deleting, Failed, Provisioning, Succeeded, Updating}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{ProvisioningStateDeleteError, ProvisioningStateDeleting, ProvisioningStateFailed, ProvisioningStateProvisioning, ProvisioningStateSucceeded}\n}", "func (ApprovalState) Values() []ApprovalState {\n\treturn []ApprovalState{\n\t\t\"APPROVE\",\n\t\t\"REVOKE\",\n\t}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{\n\t\tProvisioningStateAccepted,\n\t\tProvisioningStateCanceled,\n\t\tProvisioningStateCreated,\n\t\tProvisioningStateCreating,\n\t\tProvisioningStateDeleted,\n\t\tProvisioningStateDeleting,\n\t\tProvisioningStateFailed,\n\t\tProvisioningStateMovingResources,\n\t\tProvisioningStateNotSpecified,\n\t\tProvisioningStateRolloutInProgress,\n\t\tProvisioningStateRunning,\n\t\tProvisioningStateSucceeded,\n\t\tProvisioningStateTransientFailure,\n\t}\n}", "func PossibleAllocationStateValues() []AllocationState {\n\treturn []AllocationState{AllocationStateResizing, AllocationStateSteady, AllocationStateStopping}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{Creating, Succeeded}\n}", "func PossibleQuotaRequestStateValues() []QuotaRequestState {\n\treturn []QuotaRequestState{QuotaRequestStateAccepted, QuotaRequestStateFailed, QuotaRequestStateInProgress, QuotaRequestStateInvalid, QuotaRequestStateSucceeded}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{ProvisioningStateCanceled, ProvisioningStateDeleting, ProvisioningStateFailed, ProvisioningStateInProgress, ProvisioningStateSucceeded}\n}", "func PossibleDomainProvisioningStateValues() []DomainProvisioningState {\n\treturn []DomainProvisioningState{\n\t\tDomainProvisioningStateCanceled,\n\t\tDomainProvisioningStateCreating,\n\t\tDomainProvisioningStateDeleting,\n\t\tDomainProvisioningStateFailed,\n\t\tDomainProvisioningStateSucceeded,\n\t\tDomainProvisioningStateUpdating,\n\t}\n}", "func PossibleWorkloadNetworkSegmentProvisioningStateValues() []WorkloadNetworkSegmentProvisioningState {\n\treturn []WorkloadNetworkSegmentProvisioningState{WorkloadNetworkSegmentProvisioningStateBuilding, WorkloadNetworkSegmentProvisioningStateDeleting, WorkloadNetworkSegmentProvisioningStateFailed, WorkloadNetworkSegmentProvisioningStateSucceeded, WorkloadNetworkSegmentProvisioningStateUpdating}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{BillingFailed, Cancelled, ConfirmedBilling, ConfirmedResourceHold, Created, Creating, Expired, Failed, Merged, PendingBilling, PendingResourceHold, Split, Succeeded}\n}", "func PossibleEmailServicesProvisioningStateValues() []EmailServicesProvisioningState {\n\treturn []EmailServicesProvisioningState{\n\t\tEmailServicesProvisioningStateCanceled,\n\t\tEmailServicesProvisioningStateCreating,\n\t\tEmailServicesProvisioningStateDeleting,\n\t\tEmailServicesProvisioningStateFailed,\n\t\tEmailServicesProvisioningStateMoving,\n\t\tEmailServicesProvisioningStateRunning,\n\t\tEmailServicesProvisioningStateSucceeded,\n\t\tEmailServicesProvisioningStateUnknown,\n\t\tEmailServicesProvisioningStateUpdating,\n\t}\n}", "func (MonitoringState) Values() []MonitoringState {\n\treturn []MonitoringState{\n\t\t\"disabled\",\n\t\t\"disabling\",\n\t\t\"enabled\",\n\t\t\"pending\",\n\t}\n}", "func (ReservationState) Values() []ReservationState {\n\treturn []ReservationState{\n\t\t\"payment-pending\",\n\t\t\"payment-failed\",\n\t\t\"active\",\n\t\t\"retired\",\n\t}\n}", "func PossibleServerStateValues() []ServerState {\n return []ServerState{ServerStateDisabled,ServerStateDropping,ServerStateReady,ServerStateStarting,ServerStateStopped,ServerStateStopping,ServerStateUpdating}\n }", "func PossibleServerStateValues() []ServerState {\n return []ServerState{ServerStateDisabled,ServerStateDropping,ServerStateReady,ServerStateStarting,ServerStateStopped,ServerStateStopping,ServerStateUpdating}\n }", "func State_Values() []string {\n\treturn []string{\n\t\tStateWaiting,\n\t\tStateInProgress,\n\t\tStateError,\n\t\tStateCompleted,\n\t\tStateCancelled,\n\t\tStateTimedOut,\n\t}\n}", "func PossibleVMBootOptimizationStateValues() []VMBootOptimizationState {\n\treturn []VMBootOptimizationState{\n\t\tVMBootOptimizationStateEnabled,\n\t\tVMBootOptimizationStateDisabled,\n\t}\n}", "func (ArchiveState) Values() []ArchiveState {\n\treturn []ArchiveState{\n\t\t\"ENABLED\",\n\t\t\"DISABLED\",\n\t\t\"CREATING\",\n\t\t\"UPDATING\",\n\t\t\"CREATE_FAILED\",\n\t\t\"UPDATE_FAILED\",\n\t}\n}", "func PossibleResourceProvisioningStateValues() []ResourceProvisioningState {\n\treturn []ResourceProvisioningState{\n\t\tResourceProvisioningStateCanceled,\n\t\tResourceProvisioningStateCreating,\n\t\tResourceProvisioningStateDeleting,\n\t\tResourceProvisioningStateFailed,\n\t\tResourceProvisioningStateSucceeded,\n\t\tResourceProvisioningStateUpdating,\n\t}\n}", "func IngestionState_Values() []string {\n\treturn []string{\n\t\tIngestionStateEnabled,\n\t\tIngestionStateDisabled,\n\t}\n}", "func PossibleExportStateValues() []ExportState {\n\treturn []ExportState{ExportStateFailed, ExportStateQueued, ExportStateStarted, ExportStateSucceeded}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{\n\t\tProvisioningStateCreating,\n\t\tProvisioningStateFailed,\n\t\tProvisioningStateSucceeded,\n\t}\n}", "func PossibleSubscriptionStateValues() []SubscriptionState {\n\treturn []SubscriptionState{\n\t\tSubscriptionStateDeleted,\n\t\tSubscriptionStateDisabled,\n\t\tSubscriptionStateEnabled,\n\t\tSubscriptionStateNotDefined,\n\t\tSubscriptionStatePastDue,\n\t\tSubscriptionStateWarned,\n\t}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{ProvisioningStateCanceled, ProvisioningStateCreating, ProvisioningStateDeleting, ProvisioningStateFailed, ProvisioningStateSucceeded, ProvisioningStateUpdating}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{ProvisioningStateCanceled, ProvisioningStateCreating, ProvisioningStateDeleting, ProvisioningStateFailed, ProvisioningStateSucceeded, ProvisioningStateUpdating}\n}", "func (CapacityReservationState) Values() []CapacityReservationState {\n\treturn []CapacityReservationState{\n\t\t\"active\",\n\t\t\"expired\",\n\t\t\"cancelled\",\n\t\t\"pending\",\n\t\t\"failed\",\n\t}\n}", "func PossibleProvisioningStatesValues() []ProvisioningStates {\n\treturn []ProvisioningStates{Creating, Succeeded}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{Accepted, Canceled, Created, Creating, Deleted, Deleting, Failed, NotSpecified, Ready, Running, Succeeded, Updating}\n}", "func PossibleDomainTopicProvisioningStateValues() []DomainTopicProvisioningState {\n\treturn []DomainTopicProvisioningState{\n\t\tDomainTopicProvisioningStateCanceled,\n\t\tDomainTopicProvisioningStateCreating,\n\t\tDomainTopicProvisioningStateDeleting,\n\t\tDomainTopicProvisioningStateFailed,\n\t\tDomainTopicProvisioningStateSucceeded,\n\t\tDomainTopicProvisioningStateUpdating,\n\t}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{ProvisioningStateCompleted, ProvisioningStateFailed, ProvisioningStateRunning}\n}", "func PossibleWarmStoragePropertiesStateValues() []WarmStoragePropertiesState {\n\treturn []WarmStoragePropertiesState{\n\t\tWarmStoragePropertiesStateError,\n\t\tWarmStoragePropertiesStateOk,\n\t\tWarmStoragePropertiesStateUnknown,\n\t}\n}", "func PossibleUsageStateValues() []UsageState {\n\treturn []UsageState{UsageStateExceeded, UsageStateNormal}\n}", "func (TransitGatewayPolicyTableState) Values() []TransitGatewayPolicyTableState {\n\treturn []TransitGatewayPolicyTableState{\n\t\t\"pending\",\n\t\t\"available\",\n\t\t\"deleting\",\n\t\t\"deleted\",\n\t}\n}", "func PossibleReplicationStateValues() []ReplicationState {\n\treturn []ReplicationState{CATCHUP, PENDING, SEEDING, SUSPENDED}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{ProvisioningStateCancelled, ProvisioningStateCreating, ProvisioningStateDeleting, ProvisioningStateFailed, ProvisioningStateInvalid, ProvisioningStateSucceeded}\n}", "func PossibleResourceStateValues() []ResourceState {\n\treturn []ResourceState{ResourceStateCreating, ResourceStateDeleting, ResourceStateDisabled, ResourceStateDisabling, ResourceStateEnabled, ResourceStateEnabling}\n}", "func PossibleResourceProvisioningStateValues() []ResourceProvisioningState {\n\treturn []ResourceProvisioningState{ResourceProvisioningStateCanceled, ResourceProvisioningStateCreating, ResourceProvisioningStateDeleting, ResourceProvisioningStateFailed, ResourceProvisioningStateSucceeded, ResourceProvisioningStateUpdating}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{\n\t\tProvisioningStateSucceeded,\n\t\tProvisioningStateProvisioning,\n\t\tProvisioningStateFailed,\n\t}\n}", "func PossibleSubscriptionStateValues() []SubscriptionState {\n\treturn []SubscriptionState{SubscriptionStateDeleted, SubscriptionStateRegistered, SubscriptionStateSuspended, SubscriptionStateUnregistered, SubscriptionStateWarned}\n}", "func (TransitGatewayAttachmentState) Values() []TransitGatewayAttachmentState {\n\treturn []TransitGatewayAttachmentState{\n\t\t\"initiating\",\n\t\t\"initiatingRequest\",\n\t\t\"pendingAcceptance\",\n\t\t\"rollingBack\",\n\t\t\"pending\",\n\t\t\"available\",\n\t\t\"modifying\",\n\t\t\"deleting\",\n\t\t\"deleted\",\n\t\t\"failed\",\n\t\t\"rejected\",\n\t\t\"rejecting\",\n\t\t\"failing\",\n\t}\n}", "func PossibleClientGroupProvisioningStateValues() []ClientGroupProvisioningState {\n\treturn []ClientGroupProvisioningState{\n\t\tClientGroupProvisioningStateCanceled,\n\t\tClientGroupProvisioningStateCreating,\n\t\tClientGroupProvisioningStateDeleted,\n\t\tClientGroupProvisioningStateDeleting,\n\t\tClientGroupProvisioningStateFailed,\n\t\tClientGroupProvisioningStateSucceeded,\n\t\tClientGroupProvisioningStateUpdating,\n\t}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{Creating, ResolvingDNS, Succeeded}\n}", "func PossibleTopicTypeProvisioningStateValues() []TopicTypeProvisioningState {\n\treturn []TopicTypeProvisioningState{\n\t\tTopicTypeProvisioningStateCanceled,\n\t\tTopicTypeProvisioningStateCreating,\n\t\tTopicTypeProvisioningStateDeleting,\n\t\tTopicTypeProvisioningStateFailed,\n\t\tTopicTypeProvisioningStateSucceeded,\n\t\tTopicTypeProvisioningStateUpdating,\n\t}\n}", "func PossibleGroupIDProvisioningStateValues() []GroupIDProvisioningState {\n\treturn []GroupIDProvisioningState{\n\t\tGroupIDProvisioningStateCanceled,\n\t\tGroupIDProvisioningStateFailed,\n\t\tGroupIDProvisioningStateSucceeded,\n\t}\n}", "func (GatewayAssociationState) Values() []GatewayAssociationState {\n\treturn []GatewayAssociationState{\n\t\t\"associated\",\n\t\t\"not-associated\",\n\t\t\"associating\",\n\t\t\"disassociating\",\n\t}\n}", "func PossibleJobStateValues() []JobState {\n\treturn []JobState{\n\t\tJobStateCreated,\n\t\tJobStateDegraded,\n\t\tJobStateDeleting,\n\t\tJobStateFailed,\n\t\tJobStateRestarting,\n\t\tJobStateRunning,\n\t\tJobStateScaling,\n\t\tJobStateStarting,\n\t\tJobStateStopped,\n\t\tJobStateStopping,\n\t}\n}", "func (ReservedInstanceState) Values() []ReservedInstanceState {\n\treturn []ReservedInstanceState{\n\t\t\"payment-pending\",\n\t\t\"active\",\n\t\t\"payment-failed\",\n\t\t\"retired\",\n\t\t\"queued\",\n\t\t\"queued-deleted\",\n\t}\n}", "func (VpcState) Values() []VpcState {\n\treturn []VpcState{\n\t\t\"pending\",\n\t\t\"available\",\n\t}\n}", "func PossibleAppStateValues() []AppState {\n\treturn []AppState{AppStateCreated, AppStateSuspended}\n}", "func PossibleNamespaceProvisioningStateValues() []NamespaceProvisioningState {\n\treturn []NamespaceProvisioningState{\n\t\tNamespaceProvisioningStateCanceled,\n\t\tNamespaceProvisioningStateCreateFailed,\n\t\tNamespaceProvisioningStateCreating,\n\t\tNamespaceProvisioningStateDeleteFailed,\n\t\tNamespaceProvisioningStateDeleted,\n\t\tNamespaceProvisioningStateDeleting,\n\t\tNamespaceProvisioningStateFailed,\n\t\tNamespaceProvisioningStateSucceeded,\n\t\tNamespaceProvisioningStateUpdatedFailed,\n\t\tNamespaceProvisioningStateUpdating,\n\t}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{ProvisioningStateCanceled, ProvisioningStateDeleted, ProvisioningStateDeleting, ProvisioningStateFailed, ProvisioningStateMoving, ProvisioningStateProvisioning, ProvisioningStateRestoring, ProvisioningStateSucceeded, ProvisioningStateSuspending, ProvisioningStateWarning}\n}", "func (CEState) Values() []CEState {\n\treturn []CEState{\n\t\t\"ENABLED\",\n\t\t\"DISABLED\",\n\t}\n}", "func PossibleDeliveryModeValues() []DeliveryMode {\n\treturn []DeliveryMode{\n\t\tDeliveryModeQueue,\n\t}\n}", "func PossibleBackendEnabledStateValues() []BackendEnabledState {\n\treturn []BackendEnabledState{BackendEnabledStateDisabled, BackendEnabledStateEnabled}\n}", "func PossibleUpgradeStateValues() []UpgradeState {\n\treturn []UpgradeState{UpgradeStateFailed, UpgradeStateInvalid, UpgradeStateRollingBackCompleted, UpgradeStateRollingBackInProgress, UpgradeStateRollingForwardCompleted, UpgradeStateRollingForwardInProgress, UpgradeStateRollingForwardPending}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{ProvisioningStateBillingFailed, ProvisioningStateCancelled, ProvisioningStateConfirmedBilling, ProvisioningStateConfirmedResourceHold, ProvisioningStateCreated, ProvisioningStateCreating, ProvisioningStateExpired, ProvisioningStateFailed, ProvisioningStateMerged, ProvisioningStatePendingBilling, ProvisioningStatePendingResourceHold, ProvisioningStateSplit, ProvisioningStateSucceeded}\n}" ]
[ "0.6727513", "0.66168475", "0.652589", "0.6481542", "0.6430128", "0.63950294", "0.6366211", "0.6349712", "0.6288205", "0.6282557", "0.6277112", "0.627455", "0.62271947", "0.6215656", "0.62119126", "0.6211626", "0.6204943", "0.61992425", "0.6180284", "0.6174474", "0.6157859", "0.6154967", "0.6152828", "0.61506623", "0.61391807", "0.61358327", "0.6134767", "0.61346287", "0.61302656", "0.6116076", "0.6110211", "0.6103969", "0.60985243", "0.6096825", "0.6090615", "0.6083144", "0.60723275", "0.6071521", "0.60696155", "0.6065352", "0.60622466", "0.6051227", "0.60442144", "0.6041343", "0.6038872", "0.6037377", "0.60217565", "0.6017753", "0.6013354", "0.6012459", "0.60106117", "0.60082537", "0.5994948", "0.59944665", "0.59923166", "0.5991763", "0.5987809", "0.5984294", "0.5984294", "0.5983841", "0.5982499", "0.59809345", "0.5979013", "0.59764874", "0.5969697", "0.5966559", "0.596274", "0.5962578", "0.5962578", "0.59612864", "0.5958845", "0.5956335", "0.5954152", "0.59405804", "0.5940315", "0.59306926", "0.59298456", "0.59274715", "0.5918045", "0.5912121", "0.5903519", "0.590224", "0.5895317", "0.5887864", "0.5884361", "0.5873489", "0.5872076", "0.58716244", "0.5869442", "0.5868233", "0.58579254", "0.5857866", "0.5853691", "0.5853294", "0.5846065", "0.584581", "0.58411247", "0.58388466", "0.5833874", "0.5832797" ]
0.85856366
0
PossibleSearchSortEnumValues returns an array of possible values for the SearchSortEnum const type.
func PossibleSearchSortEnumValues() []SearchSortEnum { return []SearchSortEnum{Asc, Desc} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetJreSortByEnumValues() []JreSortByEnum {\n\tvalues := make([]JreSortByEnum, 0)\n\tfor _, v := range mappingJreSortBy {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func SearchSortOrder_Values() []string {\n\treturn []string{\n\t\tSearchSortOrderAscending,\n\t\tSearchSortOrderDescending,\n\t}\n}", "func (SortByEnum) Values() []SortByEnum {\n\treturn []SortByEnum{\n\t\t\"repositoryName\",\n\t\t\"lastModifiedDate\",\n\t}\n}", "func GetSearchSoftwareSourceModulesDetailsSortOrderEnumValues() []SearchSoftwareSourceModulesDetailsSortOrderEnum {\n\tvalues := make([]SearchSoftwareSourceModulesDetailsSortOrderEnum, 0)\n\tfor _, v := range mappingSearchSoftwareSourceModulesDetailsSortOrderEnum {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func GetHostEndpointProtectionScanResultSortByEnumValues() []HostEndpointProtectionScanResultSortByEnum {\n\tvalues := make([]HostEndpointProtectionScanResultSortByEnum, 0)\n\tfor _, v := range mappingHostEndpointProtectionScanResultSortBy {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func GetSearchSoftwareSourceModulesDetailsSortByEnumValues() []SearchSoftwareSourceModulesDetailsSortByEnum {\n\tvalues := make([]SearchSoftwareSourceModulesDetailsSortByEnum, 0)\n\tfor _, v := range mappingSearchSoftwareSourceModulesDetailsSortByEnum {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func (SearchSortOrder) Values() []SearchSortOrder {\n\treturn []SearchSortOrder{\n\t\t\"Ascending\",\n\t\t\"Descending\",\n\t}\n}", "func GetListFsuDiscoveriesSortOrderEnumValues() []ListFsuDiscoveriesSortOrderEnum {\n\tvalues := make([]ListFsuDiscoveriesSortOrderEnum, 0)\n\tfor _, v := range mappingListFsuDiscoveriesSortOrderEnum {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func SearchOrder_Values() []string {\n\treturn []string{\n\t\tSearchOrderAscending,\n\t\tSearchOrderDescending,\n\t}\n}", "func GetSummarizeInstallationsSortOrderEnumValues() []SummarizeInstallationsSortOrderEnum {\n\tvalues := make([]SummarizeInstallationsSortOrderEnum, 0)\n\tfor _, v := range mappingSummarizeInstallationsSortOrder {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func GetListFsuDiscoveriesSortByEnumValues() []ListFsuDiscoveriesSortByEnum {\n\tvalues := make([]ListFsuDiscoveriesSortByEnum, 0)\n\tfor _, v := range mappingListFsuDiscoveriesSortByEnum {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func GetListCaptureFiltersSortOrderEnumValues() []ListCaptureFiltersSortOrderEnum {\n\tvalues := make([]ListCaptureFiltersSortOrderEnum, 0)\n\tfor _, v := range mappingListCaptureFiltersSortOrderEnum {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func (OrderEnum) Values() []OrderEnum {\n\treturn []OrderEnum{\n\t\t\"ascending\",\n\t\t\"descending\",\n\t}\n}", "func GetListFsuDiscoveriesSortOrderEnumStringValues() []string {\n\treturn []string{\n\t\t\"ASC\",\n\t\t\"DESC\",\n\t}\n}", "func GetSearchSoftwareSourceModulesDetailsSortOrderEnumStringValues() []string {\n\treturn []string{\n\t\t\"ASC\",\n\t\t\"DESC\",\n\t}\n}", "func (v *QuerySortOrder) GetAllowedValues() []QuerySortOrder {\n\treturn allowedQuerySortOrderEnumValues\n}", "func GetSearchSoftwareSourceModulesDetailsSortByEnumStringValues() []string {\n\treturn []string{\n\t\t\"NAME\",\n\t}\n}", "func GetSummarizeInstallationsSortByEnumValues() []SummarizeInstallationsSortByEnum {\n\tvalues := make([]SummarizeInstallationsSortByEnum, 0)\n\tfor _, v := range mappingSummarizeInstallationsSortBy {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func GetListCaptureFiltersSortByEnumValues() []ListCaptureFiltersSortByEnum {\n\tvalues := make([]ListCaptureFiltersSortByEnum, 0)\n\tfor _, v := range mappingListCaptureFiltersSortByEnum {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func GetListEntitlementsSortByEnumValues() []ListEntitlementsSortByEnum {\n\tvalues := make([]ListEntitlementsSortByEnum, 0)\n\tfor _, v := range mappingListEntitlementsSortByEnum {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func GetListEntitlementsSortOrderEnumValues() []ListEntitlementsSortOrderEnum {\n\tvalues := make([]ListEntitlementsSortOrderEnum, 0)\n\tfor _, v := range mappingListEntitlementsSortOrderEnum {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func GetListEntitlementsSortByEnumStringValues() []string {\n\treturn []string{\n\t\t\"csi\",\n\t\t\"vendorName\",\n\t}\n}", "func ModelCardExportJobSortOrder_Values() []string {\n\treturn []string{\n\t\tModelCardExportJobSortOrderAscending,\n\t\tModelCardExportJobSortOrderDescending,\n\t}\n}", "func ModelCardSortOrder_Values() []string {\n\treturn []string{\n\t\tModelCardSortOrderAscending,\n\t\tModelCardSortOrderDescending,\n\t}\n}", "func GetListCaptureFiltersSortOrderEnumStringValues() []string {\n\treturn []string{\n\t\t\"ASC\",\n\t\t\"DESC\",\n\t}\n}", "func (SortOrder) Values() []SortOrder {\n\treturn []SortOrder{\n\t\t\"ASCENDING\",\n\t\t\"DESCENDING\",\n\t}\n}", "func (SortOrder) Values() []SortOrder {\n\treturn []SortOrder{\n\t\t\"ASCENDING\",\n\t\t\"DESCENDING\",\n\t}\n}", "func GetListEntitlementsSortOrderEnumStringValues() []string {\n\treturn []string{\n\t\t\"ASC\",\n\t\t\"DESC\",\n\t}\n}", "func SortOrder_Values() []string {\n\treturn []string{\n\t\tSortOrderAscending,\n\t\tSortOrderDescending,\n\t}\n}", "func SortOrder_Values() []string {\n\treturn []string{\n\t\tSortOrderAscending,\n\t\tSortOrderDescending,\n\t}\n}", "func SortOrder_Values() []string {\n\treturn []string{\n\t\tSortOrderAscending,\n\t\tSortOrderDescending,\n\t}\n}", "func SortOrder_Values() []string {\n\treturn []string{\n\t\tSortOrderAscending,\n\t\tSortOrderDescending,\n\t}\n}", "func SortOrder_Values() []string {\n\treturn []string{\n\t\tSortOrderAscending,\n\t\tSortOrderDescending,\n\t}\n}", "func SortOrder_Values() []string {\n\treturn []string{\n\t\tSortOrderAscending,\n\t\tSortOrderDescending,\n\t}\n}", "func (ImageSortOrder) Values() []ImageSortOrder {\n\treturn []ImageSortOrder{\n\t\t\"ASCENDING\",\n\t\t\"DESCENDING\",\n\t}\n}", "func (SortOrder) Values() []SortOrder {\n\treturn []SortOrder{\n\t\t\"Ascending\",\n\t\t\"Descending\",\n\t}\n}", "func PossibleHAEnabledEnumValues() []HAEnabledEnum {\n return []HAEnabledEnum{Disabled,Enabled}\n }", "func ResourceCatalogSortOrder_Values() []string {\n\treturn []string{\n\t\tResourceCatalogSortOrderAscending,\n\t\tResourceCatalogSortOrderDescending,\n\t}\n}", "func GetListBatchInstancesSortOrderEnumValues() []ListBatchInstancesSortOrderEnum {\n\tvalues := make([]ListBatchInstancesSortOrderEnum, 0)\n\tfor _, v := range mappingListBatchInstancesSortOrder {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func SortOrder_Values() []string {\n\treturn []string{\n\t\tSortOrderAsc,\n\t\tSortOrderDesc,\n\t}\n}", "func (ModelCardExportJobSortOrder) Values() []ModelCardExportJobSortOrder {\n\treturn []ModelCardExportJobSortOrder{\n\t\t\"Ascending\",\n\t\t\"Descending\",\n\t}\n}", "func GetListFunctionsSortByEnumValues() []ListFunctionsSortByEnum {\n\tvalues := make([]ListFunctionsSortByEnum, 0)\n\tfor _, v := range mappingListFunctionsSortByEnum {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func ProjectSortOrder_Values() []string {\n\treturn []string{\n\t\tProjectSortOrderAscending,\n\t\tProjectSortOrderDescending,\n\t}\n}", "func (ModelCardSortOrder) Values() []ModelCardSortOrder {\n\treturn []ModelCardSortOrder{\n\t\t\"Ascending\",\n\t\t\"Descending\",\n\t}\n}", "func PossiblePublicNetworkAccessEnumValues() []PublicNetworkAccessEnum {\n return []PublicNetworkAccessEnum{PublicNetworkAccessEnumDisabled,PublicNetworkAccessEnumEnabled}\n }", "func GetListFunctionsSortByEnumStringValues() []string {\n\treturn []string{\n\t\t\"timeCreated\",\n\t\t\"id\",\n\t\t\"displayName\",\n\t}\n}", "func AnalyticsSortOrder_Values() []string {\n\treturn []string{\n\t\tAnalyticsSortOrderAscending,\n\t\tAnalyticsSortOrderDescending,\n\t}\n}", "func GetListFunctionsSortOrderEnumStringValues() []string {\n\treturn []string{\n\t\t\"ASC\",\n\t\t\"DESC\",\n\t}\n}", "func GetListFsuDiscoveriesSortByEnumStringValues() []string {\n\treturn []string{\n\t\t\"timeCreated\",\n\t\t\"displayName\",\n\t}\n}", "func (ProjectSortOrder) Values() []ProjectSortOrder {\n\treturn []ProjectSortOrder{\n\t\t\"Ascending\",\n\t\t\"Descending\",\n\t}\n}", "func (CodeRepositorySortOrder) Values() []CodeRepositorySortOrder {\n\treturn []CodeRepositorySortOrder{\n\t\t\"Ascending\",\n\t\t\"Descending\",\n\t}\n}", "func (CommonFileSearchRequest_SortField) EnumDescriptor() ([]byte, []int) {\n\treturn file_box_search_proto_rawDescGZIP(), []int{20, 1}\n}", "func CodeRepositorySortOrder_Values() []string {\n\treturn []string{\n\t\tCodeRepositorySortOrderAscending,\n\t\tCodeRepositorySortOrderDescending,\n\t}\n}", "func (v *TableWidgetHasSearchBar) GetAllowedValues() []TableWidgetHasSearchBar {\n\treturn allowedTableWidgetHasSearchBarEnumValues\n}", "func GetListFunctionsSortOrderEnumValues() []ListFunctionsSortOrderEnum {\n\tvalues := make([]ListFunctionsSortOrderEnum, 0)\n\tfor _, v := range mappingListFunctionsSortOrderEnum {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func PossibleSegmentStatusEnumValues() []SegmentStatusEnum {\n\treturn []SegmentStatusEnum{SegmentStatusEnumSUCCESSFAILURE}\n}", "func PossibleVMTypeEnumValues() []VMTypeEnum {\n\treturn []VMTypeEnum{REGULAREDGESERVICE}\n}", "func (ImageVersionSortOrder) Values() []ImageVersionSortOrder {\n\treturn []ImageVersionSortOrder{\n\t\t\"ASCENDING\",\n\t\t\"DESCENDING\",\n\t}\n}", "func FeatureGroupSortOrder_Values() []string {\n\treturn []string{\n\t\tFeatureGroupSortOrderAscending,\n\t\tFeatureGroupSortOrderDescending,\n\t}\n}", "func GetListBatchInstancesSortByEnumValues() []ListBatchInstancesSortByEnum {\n\tvalues := make([]ListBatchInstancesSortByEnum, 0)\n\tfor _, v := range mappingListBatchInstancesSortBy {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func GetBucketVersioningEnumValues() []BucketVersioningEnum {\n\tvalues := make([]BucketVersioningEnum, 0)\n\tfor _, v := range mappingBucketVersioning {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func GetOperationTypeEnumValues() []OperationTypeEnum {\n\tvalues := make([]OperationTypeEnum, 0)\n\tfor _, v := range mappingOperationType {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func (FeatureGroupSortOrder) Values() []FeatureGroupSortOrder {\n\treturn []FeatureGroupSortOrder{\n\t\t\"Ascending\",\n\t\t\"Descending\",\n\t}\n}", "func (ObjectTypeEnum) Values() []ObjectTypeEnum {\n\treturn []ObjectTypeEnum{\n\t\t\"FILE\",\n\t\t\"DIRECTORY\",\n\t\t\"GIT_LINK\",\n\t\t\"SYMBOLIC_LINK\",\n\t}\n}", "func (ResourceCatalogSortOrder) Values() []ResourceCatalogSortOrder {\n\treturn []ResourceCatalogSortOrder{\n\t\t\"Ascending\",\n\t\t\"Descending\",\n\t}\n}", "func PossibleEntitySearchTypeValues() []EntitySearchType {\n\treturn []EntitySearchType{\n\t\tEntitySearchTypeAllowedChildren,\n\t\tEntitySearchTypeAllowedParents,\n\t\tEntitySearchTypeChildrenOnly,\n\t\tEntitySearchTypeParentAndFirstLevelChildren,\n\t\tEntitySearchTypeParentOnly,\n\t}\n}", "func (PackageVersionSortType) Values() []PackageVersionSortType {\n\treturn []PackageVersionSortType{\n\t\t\"PUBLISHED_TIME\",\n\t}\n}", "func PossibleProvisioningStateEnumValues() []ProvisioningStateEnum {\n\treturn []ProvisioningStateEnum{Created, Deleted, Failed, Succeeded, Unknown, Updating}\n}", "func PossibleSearchServiceStatusValues() []SearchServiceStatus {\n\treturn []SearchServiceStatus{\n\t\tSearchServiceStatusRunning,\n\t\tSearchServiceStatusProvisioning,\n\t\tSearchServiceStatusDeleting,\n\t\tSearchServiceStatusDegraded,\n\t\tSearchServiceStatusDisabled,\n\t\tSearchServiceStatusError,\n\t}\n}", "func GetListZonesSortOrderEnumValues() []ListZonesSortOrderEnum {\n\tvalues := make([]ListZonesSortOrderEnum, 0)\n\tfor _, v := range mappingListZonesSortOrder {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func PossibleThreatIntelligenceSortingOrderValues() []ThreatIntelligenceSortingOrder {\n\treturn []ThreatIntelligenceSortingOrder{\n\t\tThreatIntelligenceSortingOrderAscending,\n\t\tThreatIntelligenceSortingOrderDescending,\n\t\tThreatIntelligenceSortingOrderUnsorted,\n\t}\n}", "func (e *EnumDescriptor) GetValues() []*EnumValueDescriptor { return e.Values }", "func GetGiResourceIdFilterEntityTypeEnumValues() []GiResourceIdFilterEntityTypeEnum {\n\tvalues := make([]GiResourceIdFilterEntityTypeEnum, 0)\n\tfor _, v := range mappingGiResourceIdFilterEntityTypeEnum {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func (TagAnalyticsRequest_SortDirection) EnumDescriptor() ([]byte, []int) {\n\treturn file_contents_v1_tag_proto_rawDescGZIP(), []int{13, 0}\n}", "func ImageSortOrder_Values() []string {\n\treturn []string{\n\t\tImageSortOrderAscending,\n\t\tImageSortOrderDescending,\n\t}\n}", "func PossibleInfrastructureEncryptionEnumValues() []InfrastructureEncryptionEnum {\n return []InfrastructureEncryptionEnum{Disabled,Enabled}\n }", "func GetListZonesSortByEnumValues() []ListZonesSortByEnum {\n\tvalues := make([]ListZonesSortByEnum, 0)\n\tfor _, v := range mappingListZonesSortBy {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func InputService8TestShapeEnumType_Values() []string {\n\treturn []string{\n\t\tEnumTypeFoo,\n\t\tEnumTypeBar,\n\t}\n}", "func GetListPipelinesSortOrderEnumValues() []ListPipelinesSortOrderEnum {\n\tvalues := make([]ListPipelinesSortOrderEnum, 0)\n\tfor _, v := range mappingListPipelinesSortOrder {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func (TagGetMultipleRequest_SortDirection) EnumDescriptor() ([]byte, []int) {\n\treturn file_contents_v1_tag_proto_rawDescGZIP(), []int{5, 0}\n}", "func (ConflictResolutionStrategyTypeEnum) Values() []ConflictResolutionStrategyTypeEnum {\n\treturn []ConflictResolutionStrategyTypeEnum{\n\t\t\"NONE\",\n\t\t\"ACCEPT_SOURCE\",\n\t\t\"ACCEPT_DESTINATION\",\n\t\t\"AUTOMERGE\",\n\t}\n}", "func PossibleInternetEnumValues() []InternetEnum {\n\treturn []InternetEnum{Disabled, Enabled}\n}", "func PossibleInternetEnumValues() []InternetEnum {\n\treturn []InternetEnum{Disabled, Enabled}\n}", "func GetStorageTierEnumValues() []StorageTierEnum {\n\tvalues := make([]StorageTierEnum, 0)\n\tfor _, v := range mappingStorageTier {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func (ReplacementTypeEnum) Values() []ReplacementTypeEnum {\n\treturn []ReplacementTypeEnum{\n\t\t\"KEEP_BASE\",\n\t\t\"KEEP_SOURCE\",\n\t\t\"KEEP_DESTINATION\",\n\t\t\"USE_NEW_CONTENT\",\n\t}\n}", "func (ActionTypeEnum) Values() []ActionTypeEnum {\n\treturn []ActionTypeEnum{\n\t\t\"forward\",\n\t\t\"authenticate-oidc\",\n\t\t\"authenticate-cognito\",\n\t\t\"redirect\",\n\t\t\"fixed-response\",\n\t}\n}", "func (RelativeFileVersionEnum) Values() []RelativeFileVersionEnum {\n\treturn []RelativeFileVersionEnum{\n\t\t\"BEFORE\",\n\t\t\"AFTER\",\n\t}\n}", "func GetOperationTypesEnumValues() []OperationTypesEnum {\n\tvalues := make([]OperationTypesEnum, 0)\n\tfor _, v := range mappingOperationTypesEnum {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func ImageVersionSortOrder_Values() []string {\n\treturn []string{\n\t\tImageVersionSortOrderAscending,\n\t\tImageVersionSortOrderDescending,\n\t}\n}", "func GetListManagedInstanceUpdatablePackagesSortOrderEnumValues() []ListManagedInstanceUpdatablePackagesSortOrderEnum {\n\tvalues := make([]ListManagedInstanceUpdatablePackagesSortOrderEnum, 0)\n\tfor _, v := range mappingListManagedInstanceUpdatablePackagesSortOrderEnum {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func PossibleJobDetailsTypeEnumValues() []JobDetailsTypeEnum {\n\treturn []JobDetailsTypeEnum{JobDetailsTypeDataBox, JobDetailsTypeDataBoxDisk, JobDetailsTypeDataBoxHeavy, JobDetailsTypeJobDetails}\n}", "func PossibleNsxtAdminRotateEnumValues() []NsxtAdminRotateEnum {\n\treturn []NsxtAdminRotateEnum{OnetimeRotate}\n}", "func Order_Values() []string {\n\treturn []string{\n\t\tOrderAscending,\n\t\tOrderDescending,\n\t}\n}", "func BuiltInSlotTypeSortAttribute_Values() []string {\n\treturn []string{\n\t\tBuiltInSlotTypeSortAttributeSlotTypeSignature,\n\t}\n}", "func (ChangeTypeEnum) Values() []ChangeTypeEnum {\n\treturn []ChangeTypeEnum{\n\t\t\"A\",\n\t\t\"M\",\n\t\t\"D\",\n\t}\n}", "func GetWorkRequestStatusEnumValues() []WorkRequestStatusEnum {\n\tvalues := make([]WorkRequestStatusEnum, 0)\n\tfor _, v := range mappingWorkRequestStatusEnum {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func GetWorkRequestStatusEnumValues() []WorkRequestStatusEnum {\n\tvalues := make([]WorkRequestStatusEnum, 0)\n\tfor _, v := range mappingWorkRequestStatus {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}", "func GetListCaptureFiltersSortByEnumStringValues() []string {\n\treturn []string{\n\t\t\"TIMECREATED\",\n\t\t\"DISPLAYNAME\",\n\t}\n}", "func SortActionsBy_Values() []string {\n\treturn []string{\n\t\tSortActionsByName,\n\t\tSortActionsByCreationTime,\n\t}\n}", "func StringComparisonType_Values() []string {\n\treturn []string{\n\t\tStringComparisonTypeStartsWith,\n\t\tStringComparisonTypeContains,\n\t\tStringComparisonTypeExact,\n\t}\n}" ]
[ "0.7325511", "0.71536255", "0.7051821", "0.69074374", "0.68921673", "0.68232894", "0.6820254", "0.6725558", "0.6699984", "0.6673019", "0.6573578", "0.656557", "0.6559185", "0.6547756", "0.65249574", "0.6443032", "0.6439072", "0.6411762", "0.6403628", "0.6390762", "0.6379967", "0.6374816", "0.6344577", "0.63403875", "0.63326496", "0.6318351", "0.6318351", "0.63137174", "0.6272406", "0.6272406", "0.6272406", "0.6272406", "0.6272406", "0.6272406", "0.62509716", "0.6249215", "0.62355775", "0.62277454", "0.62258667", "0.6225262", "0.6219313", "0.6196896", "0.6188865", "0.61879516", "0.6186806", "0.6182125", "0.61709446", "0.6161927", "0.6141821", "0.614145", "0.6135456", "0.61292017", "0.6102805", "0.60990286", "0.6093376", "0.6091459", "0.6087789", "0.6085524", "0.60649973", "0.605808", "0.6030177", "0.60141075", "0.6011913", "0.600801", "0.6007243", "0.5992025", "0.59701014", "0.5966786", "0.5966377", "0.5951306", "0.59479874", "0.593934", "0.59367007", "0.59312576", "0.59293383", "0.5922926", "0.59201086", "0.5919981", "0.591314", "0.59022677", "0.5896484", "0.58938843", "0.58938843", "0.5880951", "0.5875269", "0.5865676", "0.58603555", "0.58517796", "0.5851224", "0.5847107", "0.5833117", "0.5832787", "0.5812901", "0.58016026", "0.58014846", "0.5791436", "0.5785051", "0.5782833", "0.5773659", "0.5765465" ]
0.8448999
0
PossibleStorageInsightStateValues returns an array of possible values for the StorageInsightState const type.
func PossibleStorageInsightStateValues() []StorageInsightState { return []StorageInsightState{ERROR, OK} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func PossibleWarmStoragePropertiesStateValues() []WarmStoragePropertiesState {\n\treturn []WarmStoragePropertiesState{\n\t\tWarmStoragePropertiesStateError,\n\t\tWarmStoragePropertiesStateOk,\n\t\tWarmStoragePropertiesStateUnknown,\n\t}\n}", "func IngestionState_Values() []string {\n\treturn []string{\n\t\tIngestionStateEnabled,\n\t\tIngestionStateDisabled,\n\t}\n}", "func PossibleWorkloadNetworkSegmentProvisioningStateValues() []WorkloadNetworkSegmentProvisioningState {\n\treturn []WorkloadNetworkSegmentProvisioningState{WorkloadNetworkSegmentProvisioningStateBuilding, WorkloadNetworkSegmentProvisioningStateDeleting, WorkloadNetworkSegmentProvisioningStateFailed, WorkloadNetworkSegmentProvisioningStateSucceeded, WorkloadNetworkSegmentProvisioningStateUpdating}\n}", "func State_Values() []string {\n\treturn []string{\n\t\tStateCreating,\n\t\tStateUpdating,\n\t\tStateDeleting,\n\t\tStateActive,\n\t\tStateError,\n\t}\n}", "func PossibleStateValues() []State {\n\treturn []State{Active, Deleted}\n}", "func PossibleStorageWorkloadTypeValues() []StorageWorkloadType {\n\treturn []StorageWorkloadType{\n\t\tStorageWorkloadTypeDW,\n\t\tStorageWorkloadTypeGENERAL,\n\t\tStorageWorkloadTypeOLTP,\n\t}\n}", "func State_Values() []string {\n\treturn []string{\n\t\tStateWaiting,\n\t\tStateInProgress,\n\t\tStateError,\n\t\tStateCompleted,\n\t\tStateCancelled,\n\t\tStateTimedOut,\n\t}\n}", "func PossibleStateValues() []State {\n\treturn []State{StateDeprovisioning, StateFailed, StateNetworkSourceDeleted, StateProvisioning, StateSucceeded}\n}", "func PossibleStateValues() []State {\n\treturn []State{StateApproved, StateClaimed, StateCompleted, StateCreated, StateExecuting, StateInvalid, StatePreparing, StateRestoring}\n}", "func PossibleProvisionStateValues() []ProvisionState {\n\treturn []ProvisionState{\n\t\tProvisionStateAccepted,\n\t\tProvisionStateCanceled,\n\t\tProvisionStateCreating,\n\t\tProvisionStateDeleted,\n\t\tProvisionStateDeleting,\n\t\tProvisionStateFailed,\n\t\tProvisionStateNotSpecified,\n\t\tProvisionStateSucceeded,\n\t\tProvisionStateUpdating,\n\t}\n}", "func PossibleStateValues() []State {\n\treturn []State{StateCreating, StateDeleted, StateDeleting, StateRunning, StateStarting, StateStopped, StateStopping, StateUnavailable}\n}", "func PossibleStateValues() []State {\n\treturn []State{StateCreating, StateDeleted, StateDeleting, StateRunning, StateStarting, StateStopped, StateStopping, StateUnavailable, StateUpdating}\n}", "func PossibleEncryptionScopeStateValues() []EncryptionScopeState {\n\treturn []EncryptionScopeState{Disabled, Enabled}\n}", "func PossibleProfileResourceStateValues() []ProfileResourceState {\n\treturn []ProfileResourceState{\n\t\tProfileResourceStateActive,\n\t\tProfileResourceStateCreating,\n\t\tProfileResourceStateDeleting,\n\t\tProfileResourceStateDisabled,\n\t}\n}", "func PossibleStateValues() []State {\n\treturn []State{Active, ResolvedByPositiveResult, ResolvedByStateChange, ResolvedByTimer, ResolvedManually}\n}", "func PossibleNamespaceStateValues() []NamespaceState {\n\treturn []NamespaceState{NamespaceStateActivating, NamespaceStateActive, NamespaceStateCreated, NamespaceStateCreating, NamespaceStateDisabled, NamespaceStateDisabling, NamespaceStateEnabling, NamespaceStateFailed, NamespaceStateRemoved, NamespaceStateRemoving, NamespaceStateSoftDeleted, NamespaceStateSoftDeleting, NamespaceStateUnknown}\n}", "func PossibleGeoBackupPolicyStateValues() []GeoBackupPolicyState {\n\treturn []GeoBackupPolicyState{GeoBackupPolicyStateDisabled, GeoBackupPolicyStateEnabled}\n}", "func PossibleDatabaseStateValues() []DatabaseState {\n\treturn []DatabaseState{Copying, Emergency, Offline, OfflineSecondary, Online, Recovering, RecoveryPending, Restoring, Suspect}\n}", "func PossibleBlobAuditingPolicyStateValues() []BlobAuditingPolicyState {\n\treturn []BlobAuditingPolicyState{BlobAuditingPolicyStateDisabled, BlobAuditingPolicyStateEnabled}\n}", "func SyncJobState_Values() []string {\n\treturn []string{\n\t\tSyncJobStateCreating,\n\t\tSyncJobStateInitializing,\n\t\tSyncJobStateActive,\n\t\tSyncJobStateDeleting,\n\t\tSyncJobStateError,\n\t}\n}", "func (ImageState) Values() []ImageState {\n\treturn []ImageState{\n\t\t\"pending\",\n\t\t\"available\",\n\t\t\"invalid\",\n\t\t\"deregistered\",\n\t\t\"transient\",\n\t\t\"failed\",\n\t\t\"error\",\n\t}\n}", "func PossibleReplicationStateValues() []ReplicationState {\n\treturn []ReplicationState{CATCHUP, PENDING, SEEDING, SUSPENDED}\n}", "func PossibleOperationStateValues() []OperationState {\n\treturn []OperationState{OperationStateCancelled, OperationStateCompleted, OperationStateFaulted, OperationStateForceCancelled, OperationStateInvalid, OperationStateRollingBack, OperationStateRunning}\n}", "func PossibleIntegrationRuntimeStateValues() []IntegrationRuntimeState {\n\treturn []IntegrationRuntimeState{\n\t\tIntegrationRuntimeStateAccessDenied,\n\t\tIntegrationRuntimeStateInitial,\n\t\tIntegrationRuntimeStateLimited,\n\t\tIntegrationRuntimeStateNeedRegistration,\n\t\tIntegrationRuntimeStateOffline,\n\t\tIntegrationRuntimeStateOnline,\n\t\tIntegrationRuntimeStateStarted,\n\t\tIntegrationRuntimeStateStarting,\n\t\tIntegrationRuntimeStateStopped,\n\t\tIntegrationRuntimeStateStopping,\n\t}\n}", "func (State) Values() []State {\n\treturn []State{\n\t\t\"PendingAcceptance\",\n\t\t\"Pending\",\n\t\t\"Available\",\n\t\t\"Deleting\",\n\t\t\"Deleted\",\n\t\t\"Rejected\",\n\t\t\"Failed\",\n\t\t\"Expired\",\n\t}\n}", "func PossibleIngressStateValues() []IngressState {\n\treturn []IngressState{\n\t\tIngressStateDisabled,\n\t\tIngressStatePaused,\n\t\tIngressStateReady,\n\t\tIngressStateRunning,\n\t\tIngressStateUnknown,\n\t}\n}", "func PossibleWorkflowStateValues() []WorkflowState {\n\treturn []WorkflowState{\n\t\tWorkflowStateCompleted,\n\t\tWorkflowStateDeleted,\n\t\tWorkflowStateDisabled,\n\t\tWorkflowStateEnabled,\n\t\tWorkflowStateNotSpecified,\n\t\tWorkflowStateSuspended,\n\t}\n}", "func PossibleTopicSpaceProvisioningStateValues() []TopicSpaceProvisioningState {\n\treturn []TopicSpaceProvisioningState{\n\t\tTopicSpaceProvisioningStateCanceled,\n\t\tTopicSpaceProvisioningStateCreating,\n\t\tTopicSpaceProvisioningStateDeleted,\n\t\tTopicSpaceProvisioningStateDeleting,\n\t\tTopicSpaceProvisioningStateFailed,\n\t\tTopicSpaceProvisioningStateSucceeded,\n\t\tTopicSpaceProvisioningStateUpdating,\n\t}\n}", "func PossibleManagementOperationStateValues() []ManagementOperationState {\n\treturn []ManagementOperationState{CancelInProgress, Cancelled, Failed, InProgress, Pending, Succeeded}\n}", "func PossibleJobStateValues() []JobState {\n\treturn []JobState{\n\t\tJobStateCreated,\n\t\tJobStateDegraded,\n\t\tJobStateDeleting,\n\t\tJobStateFailed,\n\t\tJobStateRestarting,\n\t\tJobStateRunning,\n\t\tJobStateScaling,\n\t\tJobStateStarting,\n\t\tJobStateStopped,\n\t\tJobStateStopping,\n\t}\n}", "func PossibleStateValues() []State {\n\treturn []State{StateDisabled, StateEnabled}\n}", "func PossibleIntegrationRuntimeStateValues() []IntegrationRuntimeState {\n\treturn []IntegrationRuntimeState{AccessDenied, Initial, Limited, NeedRegistration, Offline, Online, Started, Starting, Stopped, Stopping}\n}", "func (MonitoringState) Values() []MonitoringState {\n\treturn []MonitoringState{\n\t\t\"disabled\",\n\t\t\"disabling\",\n\t\t\"enabled\",\n\t\t\"pending\",\n\t}\n}", "func VocabularyState_Values() []string {\n\treturn []string{\n\t\tVocabularyStateCreationInProgress,\n\t\tVocabularyStateActive,\n\t\tVocabularyStateCreationFailed,\n\t\tVocabularyStateDeleteInProgress,\n\t}\n}", "func PossibleNetworkExperimentResourceStateValues() []NetworkExperimentResourceState {\n\treturn []NetworkExperimentResourceState{NetworkExperimentResourceStateCreating, NetworkExperimentResourceStateDeleting, NetworkExperimentResourceStateDisabled, NetworkExperimentResourceStateDisabling, NetworkExperimentResourceStateEnabled, NetworkExperimentResourceStateEnabling}\n}", "func PossibleMigrationStateValues() []MigrationState {\n\treturn []MigrationState{MigrationStateCompleted, MigrationStateFailed, MigrationStateInProgress, MigrationStateNone, MigrationStateSkipped, MigrationStateStopped, MigrationStateWarning}\n}", "func PossibleLargeFileSharesStateValues() []LargeFileSharesState {\n\treturn []LargeFileSharesState{LargeFileSharesStateDisabled, LargeFileSharesStateEnabled}\n}", "func (IpamManagementState) Values() []IpamManagementState {\n\treturn []IpamManagementState{\n\t\t\"managed\",\n\t\t\"unmanaged\",\n\t\t\"ignored\",\n\t}\n}", "func PossibleNamespaceProvisioningStateValues() []NamespaceProvisioningState {\n\treturn []NamespaceProvisioningState{\n\t\tNamespaceProvisioningStateCanceled,\n\t\tNamespaceProvisioningStateCreateFailed,\n\t\tNamespaceProvisioningStateCreating,\n\t\tNamespaceProvisioningStateDeleteFailed,\n\t\tNamespaceProvisioningStateDeleted,\n\t\tNamespaceProvisioningStateDeleting,\n\t\tNamespaceProvisioningStateFailed,\n\t\tNamespaceProvisioningStateSucceeded,\n\t\tNamespaceProvisioningStateUpdatedFailed,\n\t\tNamespaceProvisioningStateUpdating,\n\t}\n}", "func PossibleUsageStateValues() []UsageState {\n\treturn []UsageState{UsageStateExceeded, UsageStateNormal}\n}", "func PossiblePartnerNamespaceProvisioningStateValues() []PartnerNamespaceProvisioningState {\n\treturn []PartnerNamespaceProvisioningState{\n\t\tPartnerNamespaceProvisioningStateCanceled,\n\t\tPartnerNamespaceProvisioningStateCreating,\n\t\tPartnerNamespaceProvisioningStateDeleting,\n\t\tPartnerNamespaceProvisioningStateFailed,\n\t\tPartnerNamespaceProvisioningStateSucceeded,\n\t\tPartnerNamespaceProvisioningStateUpdating,\n\t}\n}", "func PossibleServerStateValues() []ServerState {\n return []ServerState{ServerStateDisabled,ServerStateDropping,ServerStateReady,ServerStateStarting,ServerStateStopped,ServerStateStopping,ServerStateUpdating}\n }", "func PossibleServerStateValues() []ServerState {\n return []ServerState{ServerStateDisabled,ServerStateDropping,ServerStateReady,ServerStateStarting,ServerStateStopped,ServerStateStopping,ServerStateUpdating}\n }", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{\n\t\tProvisioningStateCanceled,\n\t\tProvisioningStateCreating,\n\t\tProvisioningStateDeleting,\n\t\tProvisioningStateFailed,\n\t\tProvisioningStateMoving,\n\t\tProvisioningStateRunning,\n\t\tProvisioningStateSucceeded,\n\t\tProvisioningStateUnknown,\n\t\tProvisioningStateUpdating,\n\t}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{\n\t\tProvisioningStateAccepted,\n\t\tProvisioningStateCanceled,\n\t\tProvisioningStateCreating,\n\t\tProvisioningStateDeleted,\n\t\tProvisioningStateDeleting,\n\t\tProvisioningStateFailed,\n\t\tProvisioningStateNotSpecified,\n\t\tProvisioningStateSucceeded,\n\t\tProvisioningStateUpdating,\n\t}\n}", "func PossibleDataLakeAnalyticsAccountStateValues() []DataLakeAnalyticsAccountState {\n\treturn []DataLakeAnalyticsAccountState{Active, Suspended}\n}", "func PossibleDataLakeAnalyticsAccountStateValues() []DataLakeAnalyticsAccountState {\n\treturn []DataLakeAnalyticsAccountState{Active, Suspended}\n}", "func SyncResourceState_Values() []string {\n\treturn []string{\n\t\tSyncResourceStateInitializing,\n\t\tSyncResourceStateProcessing,\n\t\tSyncResourceStateDeleted,\n\t\tSyncResourceStateInSync,\n\t\tSyncResourceStateError,\n\t}\n}", "func PossibleDataTypeStateValues() []DataTypeState {\n\treturn []DataTypeState{\n\t\tDataTypeStateDisabled,\n\t\tDataTypeStateEnabled,\n\t}\n}", "func PossibleBackupStateValues() []BackupState {\n\treturn []BackupState{BackupStateAccepted, BackupStateBackupInProgress, BackupStateFailure, BackupStateInvalid, BackupStateSuccess, BackupStateTimeout}\n}", "func PossibleFirewallStateValues() []FirewallState {\n\treturn []FirewallState{FirewallStateDisabled, FirewallStateEnabled}\n}", "func PossibleWorkflowProvisioningStateValues() []WorkflowProvisioningState {\n\treturn []WorkflowProvisioningState{\n\t\tWorkflowProvisioningStateAccepted,\n\t\tWorkflowProvisioningStateCanceled,\n\t\tWorkflowProvisioningStateCompleted,\n\t\tWorkflowProvisioningStateCreated,\n\t\tWorkflowProvisioningStateCreating,\n\t\tWorkflowProvisioningStateDeleted,\n\t\tWorkflowProvisioningStateDeleting,\n\t\tWorkflowProvisioningStateFailed,\n\t\tWorkflowProvisioningStateInProgress,\n\t\tWorkflowProvisioningStateMoving,\n\t\tWorkflowProvisioningStateNotSpecified,\n\t\tWorkflowProvisioningStatePending,\n\t\tWorkflowProvisioningStateReady,\n\t\tWorkflowProvisioningStateRegistered,\n\t\tWorkflowProvisioningStateRegistering,\n\t\tWorkflowProvisioningStateRenewing,\n\t\tWorkflowProvisioningStateRunning,\n\t\tWorkflowProvisioningStateSucceeded,\n\t\tWorkflowProvisioningStateUnregistered,\n\t\tWorkflowProvisioningStateUnregistering,\n\t\tWorkflowProvisioningStateUpdating,\n\t\tWorkflowProvisioningStateWaiting,\n\t}\n}", "func PossibleExportStateValues() []ExportState {\n\treturn []ExportState{ExportStateFailed, ExportStateQueued, ExportStateStarted, ExportStateSucceeded}\n}", "func PossibleServerHAStateValues() []ServerHAState {\n return []ServerHAState{CreatingStandby,FailingOver,Healthy,NotEnabled,RemovingStandby,ReplicatingData}\n }", "func PossibleServerHAStateValues() []ServerHAState {\n return []ServerHAState{CreatingStandby,FailingOver,Healthy,NotEnabled,RemovingStandby,ReplicatingData}\n }", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{\n\t\tProvisioningStateCanceled,\n\t\tProvisioningStateCreating,\n\t\tProvisioningStateDeleting,\n\t\tProvisioningStateFailed,\n\t\tProvisioningStateSucceeded,\n\t\tProvisioningStateUpdating,\n\t}\n}", "func IndexState_Values() []string {\n\treturn []string{\n\t\tIndexStateCreating,\n\t\tIndexStateActive,\n\t\tIndexStateDeleting,\n\t\tIndexStateDeleted,\n\t\tIndexStateUpdating,\n\t}\n}", "func PossibleResourceStateValues() []ResourceState {\n\treturn []ResourceState{ResourceStateCreating, ResourceStateDeleting, ResourceStateDisabled, ResourceStateDisabling, ResourceStateEnabled, ResourceStateEnabling}\n}", "func PossibleRestoreStateValues() []RestoreState {\n\treturn []RestoreState{RestoreStateAccepted, RestoreStateFailure, RestoreStateInvalid, RestoreStateRestoreInProgress, RestoreStateSuccess, RestoreStateTimeout}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{\n\t\tProvisioningStateAccepted,\n\t\tProvisioningStateCreating,\n\t\tProvisioningStateDeleting,\n\t\tProvisioningStateFailed,\n\t\tProvisioningStateSucceeded,\n\t\tProvisioningStateUpdating,\n\t}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{\n\t\tProvisioningStateCreating,\n\t\tProvisioningStateUpdating,\n\t\tProvisioningStateSucceeded,\n\t\tProvisioningStateFailed,\n\t\tProvisioningStateDeleting,\n\t\tProvisioningStateCanceled,\n\t}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{\n\t\tProvisioningStateAccepted,\n\t\tProvisioningStateCanceled,\n\t\tProvisioningStateCreated,\n\t\tProvisioningStateCreating,\n\t\tProvisioningStateDeleted,\n\t\tProvisioningStateDeleting,\n\t\tProvisioningStateFailed,\n\t\tProvisioningStateMovingResources,\n\t\tProvisioningStateNotSpecified,\n\t\tProvisioningStateRolloutInProgress,\n\t\tProvisioningStateRunning,\n\t\tProvisioningStateSucceeded,\n\t\tProvisioningStateTransientFailure,\n\t}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{\n\t\tProvisioningStateAccepted,\n\t\tProvisioningStateCanceled,\n\t\tProvisioningStateCreating,\n\t\tProvisioningStateDeleted,\n\t\tProvisioningStateFailed,\n\t\tProvisioningStateSucceeded,\n\t}\n}", "func PossibleFirewallAllowAzureIpsStateValues() []FirewallAllowAzureIpsState {\n\treturn []FirewallAllowAzureIpsState{Disabled, Enabled}\n}", "func PossibleBackendEnabledStateValues() []BackendEnabledState {\n\treturn []BackendEnabledState{BackendEnabledStateDisabled, BackendEnabledStateEnabled}\n}", "func PossibleQuotaRequestStateValues() []QuotaRequestState {\n\treturn []QuotaRequestState{QuotaRequestStateAccepted, QuotaRequestStateFailed, QuotaRequestStateInProgress, QuotaRequestStateInvalid, QuotaRequestStateSucceeded}\n}", "func PossibleDigestConfigStateValues() []DigestConfigState {\n\treturn []DigestConfigState{\n\t\tDigestConfigStateActive,\n\t\tDigestConfigStateDisabled,\n\t}\n}", "func PossibleWorkloadNetworkVMGroupProvisioningStateValues() []WorkloadNetworkVMGroupProvisioningState {\n\treturn []WorkloadNetworkVMGroupProvisioningState{WorkloadNetworkVMGroupProvisioningStateBuilding, WorkloadNetworkVMGroupProvisioningStateDeleting, WorkloadNetworkVMGroupProvisioningStateFailed, WorkloadNetworkVMGroupProvisioningStateSucceeded, WorkloadNetworkVMGroupProvisioningStateUpdating}\n}", "func PossiblePurgeStateValues() []PurgeState {\n\treturn []PurgeState{Completed, Pending}\n}", "func StorageType_Values() []string {\n\treturn []string{\n\t\tStorageTypeS3,\n\t\tStorageTypeKinesisVideoStream,\n\t\tStorageTypeKinesisStream,\n\t\tStorageTypeKinesisFirehose,\n\t}\n}", "func PossibleWorkloadNetworkDhcpProvisioningStateValues() []WorkloadNetworkDhcpProvisioningState {\n\treturn []WorkloadNetworkDhcpProvisioningState{WorkloadNetworkDhcpProvisioningStateBuilding, WorkloadNetworkDhcpProvisioningStateDeleting, WorkloadNetworkDhcpProvisioningStateFailed, WorkloadNetworkDhcpProvisioningStateSucceeded, WorkloadNetworkDhcpProvisioningStateUpdating}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{Creating, Deleting, Failed, Succeeded, Updating}\n}", "func PossibleProvisioningStatesValues() []ProvisioningStates {\n\treturn []ProvisioningStates{\n\t\tProvisioningStatesCanceled,\n\t\tProvisioningStatesCreating,\n\t\tProvisioningStatesDeleting,\n\t\tProvisioningStatesFailed,\n\t\tProvisioningStatesInvalid,\n\t\tProvisioningStatesPending,\n\t\tProvisioningStatesSucceeded,\n\t\tProvisioningStatesUpdating,\n\t}\n}", "func StateValues() []State {\n\treturn _StateValues\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{Creating, Deleting, Failed, Succeeded}\n}", "func PossibleReadinessStateValues() []ReadinessState {\n\treturn []ReadinessState{\n\t\tReadinessStateActivated,\n\t\tReadinessStateNeverActivated,\n\t}\n}", "func (IpamResourceDiscoveryState) Values() []IpamResourceDiscoveryState {\n\treturn []IpamResourceDiscoveryState{\n\t\t\"create-in-progress\",\n\t\t\"create-complete\",\n\t\t\"create-failed\",\n\t\t\"modify-in-progress\",\n\t\t\"modify-complete\",\n\t\t\"modify-failed\",\n\t\t\"delete-in-progress\",\n\t\t\"delete-complete\",\n\t\t\"delete-failed\",\n\t\t\"isolate-in-progress\",\n\t\t\"isolate-complete\",\n\t\t\"restore-in-progress\",\n\t}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{Creating, Deleting, Failed, Moving, Running, Succeeded}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{Creating, Deleting, Failed, Running, Succeeded}\n}", "func PossibleAllocationStateValues() []AllocationState {\n\treturn []AllocationState{AllocationStateResizing, AllocationStateSteady, AllocationStateStopping}\n}", "func PossibleResourceProvisioningStateValues() []ResourceProvisioningState {\n\treturn []ResourceProvisioningState{\n\t\tResourceProvisioningStateCanceled,\n\t\tResourceProvisioningStateCreating,\n\t\tResourceProvisioningStateDeleting,\n\t\tResourceProvisioningStateFailed,\n\t\tResourceProvisioningStateSucceeded,\n\t\tResourceProvisioningStateUpdating,\n\t}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{Canceled, Creating, Deleting, Failed, Succeeded, Updating}\n}", "func (IpamScopeState) Values() []IpamScopeState {\n\treturn []IpamScopeState{\n\t\t\"create-in-progress\",\n\t\t\"create-complete\",\n\t\t\"create-failed\",\n\t\t\"modify-in-progress\",\n\t\t\"modify-complete\",\n\t\t\"modify-failed\",\n\t\t\"delete-in-progress\",\n\t\t\"delete-complete\",\n\t\t\"delete-failed\",\n\t\t\"isolate-in-progress\",\n\t\t\"isolate-complete\",\n\t\t\"restore-in-progress\",\n\t}\n}", "func PossibleOriginResourceStateValues() []OriginResourceState {\n\treturn []OriginResourceState{\n\t\tOriginResourceStateActive,\n\t\tOriginResourceStateCreating,\n\t\tOriginResourceStateDeleting,\n\t}\n}", "func PossibleJobStatesValues() []JobStates {\n\treturn []JobStates{JobStatesFailed, JobStatesQueued, JobStatesStarted, JobStatesSucceeded}\n}", "func VocabularyState_Values() []string {\n\treturn []string{\n\t\tVocabularyStatePending,\n\t\tVocabularyStateReady,\n\t\tVocabularyStateFailed,\n\t}\n}", "func PossibleTopicSpacesConfigurationStateValues() []TopicSpacesConfigurationState {\n\treturn []TopicSpacesConfigurationState{\n\t\tTopicSpacesConfigurationStateDisabled,\n\t\tTopicSpacesConfigurationStateEnabled,\n\t}\n}", "func PossibleStorageAutogrowValues() []StorageAutogrow {\n return []StorageAutogrow{StorageAutogrowDisabled,StorageAutogrowEnabled}\n }", "func PossibleAccountStateValues() []AccountState {\n\treturn []AccountState{AccountStateOk, AccountStateSuspended, AccountStateUnavailable}\n}", "func PossibleSiteAvailabilityStateValues() []SiteAvailabilityState {\n\treturn []SiteAvailabilityState{DisasterRecoveryMode, Limited, Normal}\n}", "func (LocalStorageType) Values() []LocalStorageType {\n\treturn []LocalStorageType{\n\t\t\"hdd\",\n\t\t\"ssd\",\n\t}\n}", "func PossibleHealthStateValues() []HealthState {\n\treturn []HealthState{HealthStateError, HealthStateInvalid, HealthStateOk, HealthStateUnknown, HealthStateWarning}\n}", "func PossiblePolicyResourceStateValues() []PolicyResourceState {\n\treturn []PolicyResourceState{\n\t\tPolicyResourceStateCreating,\n\t\tPolicyResourceStateDeleting,\n\t\tPolicyResourceStateDisabled,\n\t\tPolicyResourceStateDisabling,\n\t\tPolicyResourceStateEnabled,\n\t\tPolicyResourceStateEnabling,\n\t}\n}", "func (v *SecurityMonitoringSignalState) GetAllowedValues() []SecurityMonitoringSignalState {\n\treturn allowedSecurityMonitoringSignalStateEnumValues\n}", "func PossibleDomainTopicProvisioningStateValues() []DomainTopicProvisioningState {\n\treturn []DomainTopicProvisioningState{\n\t\tDomainTopicProvisioningStateCanceled,\n\t\tDomainTopicProvisioningStateCreating,\n\t\tDomainTopicProvisioningStateDeleting,\n\t\tDomainTopicProvisioningStateFailed,\n\t\tDomainTopicProvisioningStateSucceeded,\n\t\tDomainTopicProvisioningStateUpdating,\n\t}\n}", "func (IpamState) Values() []IpamState {\n\treturn []IpamState{\n\t\t\"create-in-progress\",\n\t\t\"create-complete\",\n\t\t\"create-failed\",\n\t\t\"modify-in-progress\",\n\t\t\"modify-complete\",\n\t\t\"modify-failed\",\n\t\t\"delete-in-progress\",\n\t\t\"delete-complete\",\n\t\t\"delete-failed\",\n\t\t\"isolate-in-progress\",\n\t\t\"isolate-complete\",\n\t\t\"restore-in-progress\",\n\t}\n}", "func PossibleEndpointResourceStateValues() []EndpointResourceState {\n\treturn []EndpointResourceState{\n\t\tEndpointResourceStateCreating,\n\t\tEndpointResourceStateDeleting,\n\t\tEndpointResourceStateRunning,\n\t\tEndpointResourceStateStarting,\n\t\tEndpointResourceStateStopped,\n\t\tEndpointResourceStateStopping,\n\t}\n}", "func (InstanceMetadataOptionsState) Values() []InstanceMetadataOptionsState {\n\treturn []InstanceMetadataOptionsState{\n\t\t\"pending\",\n\t\t\"applied\",\n\t}\n}", "func PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{ProvisioningStateCanceled, ProvisioningStateDeleting, ProvisioningStateFailed, ProvisioningStateInProgress, ProvisioningStateSucceeded}\n}", "func InstanceHealthCheckState_Values() []string {\n\treturn []string{\n\t\tInstanceHealthCheckStateOk,\n\t\tInstanceHealthCheckStateImpaired,\n\t\tInstanceHealthCheckStateInsufficientData,\n\t\tInstanceHealthCheckStateInitializing,\n\t}\n}" ]
[ "0.682293", "0.6605254", "0.6553771", "0.6548761", "0.6496183", "0.64893043", "0.64096045", "0.63897544", "0.6389178", "0.6358125", "0.6339661", "0.63313603", "0.6326768", "0.62572414", "0.6227403", "0.61806184", "0.6177829", "0.6176427", "0.6174233", "0.61690754", "0.61680454", "0.61574185", "0.61458075", "0.6144595", "0.6144224", "0.61366844", "0.61355764", "0.61290556", "0.61264473", "0.61245394", "0.61208814", "0.61142844", "0.61062324", "0.61039597", "0.6098614", "0.6098476", "0.60917664", "0.6091255", "0.6082127", "0.6069496", "0.60661954", "0.60635215", "0.60635215", "0.6059573", "0.60541594", "0.60538113", "0.60538113", "0.6051661", "0.6047436", "0.60465324", "0.60414094", "0.60385317", "0.6037676", "0.60355246", "0.60355246", "0.6032248", "0.6021031", "0.6013234", "0.6011769", "0.60082173", "0.59994966", "0.599385", "0.5992424", "0.5988144", "0.5985205", "0.59817827", "0.5979709", "0.5972384", "0.5967691", "0.59603155", "0.59533435", "0.5952237", "0.5951526", "0.5951299", "0.595112", "0.59490585", "0.59372", "0.59313875", "0.59298843", "0.5929327", "0.5925351", "0.59174746", "0.5916785", "0.59165543", "0.59108263", "0.5909971", "0.5901087", "0.58985597", "0.589804", "0.5896836", "0.5889265", "0.588455", "0.5882387", "0.58787763", "0.5877598", "0.58775777", "0.58749074", "0.5871187", "0.58678603", "0.5867065" ]
0.82418233
0
MarshalJSON is the custom marshaler for ProxyResource.
func (pr ProxyResource) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if pr.ID != nil { objectMap["id"] = pr.ID } if pr.Name != nil { objectMap["name"] = pr.Name } if pr.Type != nil { objectMap["type"] = pr.Type } if pr.Tags != nil { objectMap["tags"] = pr.Tags } return json.Marshal(objectMap) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p ProxyResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", p.ID)\n\tpopulate(objectMap, \"name\", p.Name)\n\tpopulate(objectMap, \"systemData\", p.SystemData)\n\tpopulate(objectMap, \"type\", p.Type)\n\treturn json.Marshal(objectMap)\n}", "func (p ProxyResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", p.ID)\n\tpopulate(objectMap, \"name\", p.Name)\n\tpopulate(objectMap, \"systemData\", p.SystemData)\n\tpopulate(objectMap, \"type\", p.Type)\n\treturn json.Marshal(objectMap)\n}", "func (p ProxyResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", p.ID)\n\tpopulate(objectMap, \"name\", p.Name)\n\tpopulate(objectMap, \"type\", p.Type)\n\treturn json.Marshal(objectMap)\n}", "func (p ProxyResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", p.ID)\n\tpopulate(objectMap, \"name\", p.Name)\n\tpopulate(objectMap, \"type\", p.Type)\n\treturn json.Marshal(objectMap)\n}", "func (p ProxyResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", p.ID)\n\tpopulate(objectMap, \"name\", p.Name)\n\tpopulate(objectMap, \"type\", p.Type)\n\treturn json.Marshal(objectMap)\n}", "func (p ProxyResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", p.ID)\n\tpopulate(objectMap, \"name\", p.Name)\n\tpopulate(objectMap, \"type\", p.Type)\n\treturn json.Marshal(objectMap)\n}", "func (p ProxyResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", p.ID)\n\tpopulate(objectMap, \"name\", p.Name)\n\tpopulate(objectMap, \"type\", p.Type)\n\treturn json.Marshal(objectMap)\n}", "func (m ManagedProxyResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"expiresOn\", m.ExpiresOn)\n\tpopulate(objectMap, \"proxy\", m.Proxy)\n\treturn json.Marshal(objectMap)\n}", "func (pr ProxyResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\treturn json.Marshal(objectMap)\n}", "func (pi *proxyItem) Marshal() ([]byte, error) {\n\tif pi == nil || pi.obj == nil {\n\t\treturn nil, nil\n\t}\n\n\tswitch m := pi.obj.(type) {\n\tcase encoding.BinaryMarshaler:\n\t\treturn m.MarshalBinary()\n\tcase storage.Marshaler:\n\t\treturn m.Marshal()\n\t}\n\treturn json.Marshal(pi.obj)\n}", "func (e EndpointAccessResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"relay\", e.Relay)\n\treturn json.Marshal(objectMap)\n}", "func (m *JSONMarshaller) Marshal(message proto.Message) ([]byte, error) {\n\treturn m.marshaller.MarshalResource(message)\n}", "func (p PartnerManagedResourceProperties) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", p.ID)\n\tpopulate(objectMap, \"internalLoadBalancerId\", p.InternalLoadBalancerID)\n\tpopulate(objectMap, \"standardLoadBalancerId\", p.StandardLoadBalancerID)\n\treturn json.Marshal(objectMap)\n}", "func (r *HybridResource) MarshalJSON() ([]byte, error) {\n\tif r.Many != nil {\n\t\treturn json.Marshal(r.Many)\n\t}\n\n\treturn json.Marshal(r.One)\n}", "func (s SwapResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", s.ID)\n\tpopulate(objectMap, \"name\", s.Name)\n\tpopulate(objectMap, \"properties\", s.Properties)\n\tpopulate(objectMap, \"type\", s.Type)\n\treturn json.Marshal(objectMap)\n}", "func (e EndpointResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", e.ID)\n\tpopulate(objectMap, \"name\", e.Name)\n\tpopulate(objectMap, \"properties\", e.Properties)\n\tpopulate(objectMap, \"systemData\", e.SystemData)\n\tpopulate(objectMap, \"type\", e.Type)\n\treturn json.Marshal(objectMap)\n}", "func (i IotConnectorPatchResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"identity\", i.Identity)\n\tpopulate(objectMap, \"tags\", i.Tags)\n\treturn json.Marshal(objectMap)\n}", "func (e EndpointResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", e.ID)\n\tpopulate(objectMap, \"name\", e.Name)\n\tpopulate(objectMap, \"properties\", e.Properties)\n\tpopulate(objectMap, \"systemData\", e.SystemData)\n\tpopulate(objectMap, \"type\", e.Type)\n\treturn json.Marshal(objectMap)\n}", "func (m ManagedProxyRequest) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"hostname\", m.Hostname)\n\tpopulate(objectMap, \"service\", m.Service)\n\treturn json.Marshal(objectMap)\n}", "func (tr TrackedResource)MarshalJSON() ([]byte, error){\n objectMap := make(map[string]interface{})\n if(tr.Tags != nil) {\n objectMap[\"tags\"] = tr.Tags\n }\n if(tr.Location != nil) {\n objectMap[\"location\"] = tr.Location\n }\n return json.Marshal(objectMap)\n }", "func (f FhirServicePatchResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"identity\", f.Identity)\n\tpopulate(objectMap, \"tags\", f.Tags)\n\treturn json.Marshal(objectMap)\n}", "func (j *JSON) Marshal(target interface{}) (output interface{}, err error) {\n\treturn jsonEncoding.Marshal(target)\n}", "func (d DicomServicePatchResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"identity\", d.Identity)\n\tpopulate(objectMap, \"tags\", d.Tags)\n\treturn json.Marshal(objectMap)\n}", "func (mr MonitorResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif mr.Properties != nil {\n\t\tobjectMap[\"properties\"] = mr.Properties\n\t}\n\tif mr.Identity != nil {\n\t\tobjectMap[\"identity\"] = mr.Identity\n\t}\n\tif mr.Tags != nil {\n\t\tobjectMap[\"tags\"] = mr.Tags\n\t}\n\tif mr.Location != nil {\n\t\tobjectMap[\"location\"] = mr.Location\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (i IngressGatewayResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"ingress\", i.Ingress)\n\tpopulate(objectMap, \"relay\", i.Relay)\n\treturn json.Marshal(objectMap)\n}", "func (m MonitorResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", m.ID)\n\tpopulate(objectMap, \"identity\", m.Identity)\n\tpopulate(objectMap, \"location\", m.Location)\n\tpopulate(objectMap, \"name\", m.Name)\n\tpopulate(objectMap, \"properties\", m.Properties)\n\tpopulate(objectMap, \"systemData\", m.SystemData)\n\tpopulate(objectMap, \"tags\", m.Tags)\n\tpopulate(objectMap, \"type\", m.Type)\n\treturn json.Marshal(objectMap)\n}", "func (j *qProxyClient) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (o OrchestratorResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", o.ID)\n\tpopulate(objectMap, \"identity\", o.Identity)\n\tpopulate(objectMap, \"kind\", o.Kind)\n\tpopulate(objectMap, \"location\", o.Location)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"tags\", o.Tags)\n\tpopulate(objectMap, \"type\", o.Type)\n\treturn json.Marshal(objectMap)\n}", "func (v SearchInResourceReturns) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage17(w, v)\n}", "func (ssor SingleSignOnResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif ssor.SystemData != nil {\n\t\tobjectMap[\"systemData\"] = ssor.SystemData\n\t}\n\tif ssor.Properties != nil {\n\t\tobjectMap[\"properties\"] = ssor.Properties\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"identity\", r.Identity)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"sku\", r.SKU)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\treturn json.Marshal(objectMap)\n}", "func (p PrivateLinkResourceBase) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", p.ID)\n\tpopulate(objectMap, \"name\", p.Name)\n\tpopulate(objectMap, \"type\", p.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"sku\", r.SKU)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (c ChildResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"etag\", c.Etag)\n\tpopulate(objectMap, \"id\", c.ID)\n\tpopulate(objectMap, \"name\", c.Name)\n\tpopulate(objectMap, \"type\", c.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\ttmpResource := struct {\n\t\tID ID `json:\"id\"`\n\t\tStatus Status `json:\"status\"`\n\t\tSince time.Time `json:\"since\"`\n\t}{\n\t\tr.ID,\n\t\tr.Status,\n\t\tr.Since,\n\t}\n\treturn json.Marshal(tmpResource)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"systemData\", t.SystemData)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"systemData\", t.SystemData)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"systemData\", r.SystemData)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"systemData\", r.SystemData)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (ri *rawItem) Marshal() ([]byte, error) {\n\tif ri == nil || ri.proxyItem == nil || ri.proxyItem.obj == nil {\n\t\treturn nil, nil\n\t}\n\n\tif buf, ok := ri.proxyItem.obj.([]byte); ok {\n\t\treturn buf, nil\n\t}\n\n\treturn ri.proxyItem.Marshal()\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\tpopulate(objectMap, \"type\", r.Type)\n\tpopulate(objectMap, \"zones\", r.Zones)\n\treturn json.Marshal(objectMap)\n}", "func (s ServicesResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"etag\", s.Etag)\n\tpopulate(objectMap, \"id\", s.ID)\n\tpopulate(objectMap, \"identity\", s.Identity)\n\tpopulate(objectMap, \"kind\", s.Kind)\n\tpopulate(objectMap, \"location\", s.Location)\n\tpopulate(objectMap, \"name\", s.Name)\n\tpopulate(objectMap, \"tags\", s.Tags)\n\tpopulate(objectMap, \"type\", s.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif r.Location != nil {\n\t\tobjectMap[\"location\"] = r.Location\n\t}\n\tif r.Tags != nil {\n\t\tobjectMap[\"tags\"] = r.Tags\n\t}\n\tif r.Sku != nil {\n\t\tobjectMap[\"sku\"] = r.Sku\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"identity\", r.Identity)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"systemData\", r.SystemData)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"systemData\", t.SystemData)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r *ComputeFirewallRuleResource) Marshal() ([]byte, error) {\n\treturn json.Marshal(&r.f)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func Marshal(v interface{}) ([]byte, error) {\n\tif ImplementsPreJSONMarshaler(v) {\n\t\terr := v.(PreJSONMarshaler).PreMarshalJSON()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn json.Marshal(v)\n}", "func (j *JsonlMarshaler) Marshal(v interface{}) ([]byte, error) {\n\treturn json.Marshal(v)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif r.Location != nil {\n\t\tobjectMap[\"location\"] = r.Location\n\t}\n\tif r.Tags != nil {\n\t\tobjectMap[\"tags\"] = r.Tags\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (s SwapResourceProperties) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"slotType\", s.SlotType)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"etag\", r.Etag)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"kind\", r.Kind)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"sku\", r.SKU)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\tpopulate(objectMap, \"type\", r.Type)\n\tpopulate(objectMap, \"zones\", r.Zones)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif r.Tags != nil {\n\t\tobjectMap[\"tags\"] = r.Tags\n\t}\n\tif r.Location != nil {\n\t\tobjectMap[\"location\"] = r.Location\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif r.ID != nil {\n\t\tobjectMap[\"id\"] = r.ID\n\t}\n\tif r.Name != nil {\n\t\tobjectMap[\"name\"] = r.Name\n\t}\n\tif r.Type != nil {\n\t\tobjectMap[\"type\"] = r.Type\n\t}\n\tif r.Location != nil {\n\t\tobjectMap[\"location\"] = r.Location\n\t}\n\tif r.Tags != nil {\n\t\tobjectMap[\"tags\"] = r.Tags\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif r.ID != nil {\n\t\tobjectMap[\"id\"] = r.ID\n\t}\n\tif r.Name != nil {\n\t\tobjectMap[\"name\"] = r.Name\n\t}\n\tif r.Type != nil {\n\t\tobjectMap[\"type\"] = r.Type\n\t}\n\tif r.Location != nil {\n\t\tobjectMap[\"location\"] = r.Location\n\t}\n\tif r.Tags != nil {\n\t\tobjectMap[\"tags\"] = r.Tags\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif r.ID != nil {\n\t\tobjectMap[\"id\"] = r.ID\n\t}\n\tif r.Name != nil {\n\t\tobjectMap[\"name\"] = r.Name\n\t}\n\tif r.Type != nil {\n\t\tobjectMap[\"type\"] = r.Type\n\t}\n\tif r.Location != nil {\n\t\tobjectMap[\"location\"] = r.Location\n\t}\n\tif r.Tags != nil {\n\t\tobjectMap[\"tags\"] = r.Tags\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (tr TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif tr.Location != nil {\n\t\tobjectMap[\"location\"] = tr.Location\n\t}\n\tif tr.Tags != nil {\n\t\tobjectMap[\"tags\"] = tr.Tags\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (tr TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif tr.Location != nil {\n\t\tobjectMap[\"location\"] = tr.Location\n\t}\n\tif tr.Tags != nil {\n\t\tobjectMap[\"tags\"] = tr.Tags\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (tr TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif tr.Location != nil {\n\t\tobjectMap[\"location\"] = tr.Location\n\t}\n\tif tr.Tags != nil {\n\t\tobjectMap[\"tags\"] = tr.Tags\n\t}\n\treturn json.Marshal(objectMap)\n}", "func Marshal(v Marshaler) ([]byte, error) {\n\tw := jwriter.Writer{}\n\tv.MarshalEasyJSON(&w)\n\treturn w.BuildBytes()\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (d DdosCustomPolicyPropertiesFormat) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"provisioningState\", d.ProvisioningState)\n\tpopulate(objectMap, \"resourceGuid\", d.ResourceGUID)\n\treturn json.Marshal(objectMap)\n}", "func (aer AzureEntityResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\treturn json.Marshal(objectMap)\n}", "func (v SearchInResourceReturns) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage17(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (tr TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif tr.Tags != nil {\n\t\tobjectMap[\"tags\"] = tr.Tags\n\t}\n\tif tr.Location != nil {\n\t\tobjectMap[\"location\"] = tr.Location\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (tr TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif tr.Tags != nil {\n\t\tobjectMap[\"tags\"] = tr.Tags\n\t}\n\tif tr.Location != nil {\n\t\tobjectMap[\"location\"] = tr.Location\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (tr TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif tr.Tags != nil {\n\t\tobjectMap[\"tags\"] = tr.Tags\n\t}\n\tif tr.Location != nil {\n\t\tobjectMap[\"location\"] = tr.Location\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (w WebhookPartnerDestinationProperties) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"clientAuthentication\", w.ClientAuthentication)\n\tpopulate(objectMap, \"endpointBaseUrl\", w.EndpointBaseURL)\n\tpopulate(objectMap, \"endpointUrl\", w.EndpointURL)\n\treturn json.Marshal(objectMap)\n}", "func (v GetResourceContentReturns) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage40(w, v)\n}", "func (m MachinePoolProperties) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"resources\", m.Resources)\n\treturn json.Marshal(objectMap)\n}", "func (s SyncIdentityProviderProperties) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"resources\", s.Resources)\n\treturn json.Marshal(objectMap)\n}", "func (p PrivateLinkResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", p.ID)\n\tpopulate(objectMap, \"name\", p.Name)\n\tpopulate(objectMap, \"properties\", p.Properties)\n\tpopulate(objectMap, \"type\", p.Type)\n\treturn json.Marshal(objectMap)\n}", "func (p PrivateLinkResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", p.ID)\n\tpopulate(objectMap, \"name\", p.Name)\n\tpopulate(objectMap, \"properties\", p.Properties)\n\tpopulate(objectMap, \"type\", p.Type)\n\treturn json.Marshal(objectMap)\n}", "func (p PrivateLinkResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", p.ID)\n\tpopulate(objectMap, \"name\", p.Name)\n\tpopulate(objectMap, \"properties\", p.Properties)\n\tpopulate(objectMap, \"type\", p.Type)\n\treturn json.Marshal(objectMap)\n}", "func (s SwapResourceListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"value\", s.Value)\n\treturn json.Marshal(objectMap)\n}", "func (a *SearchInResourceArgs) MarshalJSON() ([]byte, error) {\n\ttype Copy SearchInResourceArgs\n\tc := &Copy{}\n\t*c = Copy(*a)\n\treturn json.Marshal(&c)\n}", "func (a ApplicationGatewayPrivateLinkResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"etag\", a.Etag)\n\tpopulate(objectMap, \"id\", a.ID)\n\tpopulate(objectMap, \"name\", a.Name)\n\tpopulate(objectMap, \"properties\", a.Properties)\n\tpopulate(objectMap, \"type\", a.Type)\n\treturn json.Marshal(objectMap)\n}" ]
[ "0.78600556", "0.78600556", "0.784037", "0.784037", "0.784037", "0.784037", "0.784037", "0.7778434", "0.7720367", "0.6736437", "0.6510341", "0.6497555", "0.64737177", "0.64454365", "0.63258666", "0.6287661", "0.625608", "0.6255603", "0.6235596", "0.6209794", "0.61868066", "0.61771095", "0.61756223", "0.6115451", "0.6095755", "0.6090933", "0.60482866", "0.60417926", "0.60412383", "0.60396636", "0.6036548", "0.6026553", "0.6026384", "0.6025528", "0.6019472", "0.6019472", "0.6019472", "0.6019472", "0.6019472", "0.6019472", "0.6019472", "0.6018369", "0.6017917", "0.6017917", "0.60168993", "0.60168993", "0.60168993", "0.6013243", "0.6013243", "0.60046846", "0.59991664", "0.59991664", "0.59991664", "0.59991664", "0.59921545", "0.5988925", "0.5987352", "0.5987352", "0.5987158", "0.5975346", "0.5966645", "0.59656405", "0.59593594", "0.59593594", "0.59593594", "0.59593594", "0.59593594", "0.59593594", "0.59593594", "0.59581167", "0.5956687", "0.5955142", "0.5950901", "0.59441614", "0.59430575", "0.5941958", "0.5941958", "0.5941958", "0.59267324", "0.59267324", "0.59267324", "0.5924603", "0.5918076", "0.5918076", "0.5916885", "0.59144956", "0.5913425", "0.59074956", "0.59074956", "0.59074956", "0.59045273", "0.5900366", "0.58998173", "0.58992314", "0.589462", "0.589462", "0.589462", "0.58878607", "0.5873778", "0.5872339" ]
0.77710354
8
MarshalJSON is the custom marshaler for Resource.
func (r Resource) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if r.ID != nil { objectMap["id"] = r.ID } if r.Name != nil { objectMap["name"] = r.Name } if r.Type != nil { objectMap["type"] = r.Type } if r.Location != nil { objectMap["location"] = r.Location } if r.Tags != nil { objectMap["tags"] = r.Tags } return json.Marshal(objectMap) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"systemData\", r.SystemData)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"systemData\", r.SystemData)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"sku\", r.SKU)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"identity\", r.Identity)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"systemData\", r.SystemData)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"identity\", r.Identity)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"sku\", r.SKU)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"etag\", r.Etag)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"kind\", r.Kind)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"sku\", r.SKU)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\tpopulate(objectMap, \"type\", r.Type)\n\tpopulate(objectMap, \"zones\", r.Zones)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"eTag\", r.ETag)\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"sku\", r.SKU)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\treturn json.Marshal(objectMap)\n}", "func (p ProxyResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", p.ID)\n\tpopulate(objectMap, \"name\", p.Name)\n\tpopulate(objectMap, \"systemData\", p.SystemData)\n\tpopulate(objectMap, \"type\", p.Type)\n\treturn json.Marshal(objectMap)\n}", "func (p ProxyResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", p.ID)\n\tpopulate(objectMap, \"name\", p.Name)\n\tpopulate(objectMap, \"systemData\", p.SystemData)\n\tpopulate(objectMap, \"type\", p.Type)\n\treturn json.Marshal(objectMap)\n}", "func (p ProxyResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", p.ID)\n\tpopulate(objectMap, \"name\", p.Name)\n\tpopulate(objectMap, \"type\", p.Type)\n\treturn json.Marshal(objectMap)\n}", "func (p ProxyResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", p.ID)\n\tpopulate(objectMap, \"name\", p.Name)\n\tpopulate(objectMap, \"type\", p.Type)\n\treturn json.Marshal(objectMap)\n}", "func (p ProxyResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", p.ID)\n\tpopulate(objectMap, \"name\", p.Name)\n\tpopulate(objectMap, \"type\", p.Type)\n\treturn json.Marshal(objectMap)\n}", "func (p ProxyResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", p.ID)\n\tpopulate(objectMap, \"name\", p.Name)\n\tpopulate(objectMap, \"type\", p.Type)\n\treturn json.Marshal(objectMap)\n}", "func (p ProxyResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", p.ID)\n\tpopulate(objectMap, \"name\", p.Name)\n\tpopulate(objectMap, \"type\", p.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\tpopulate(objectMap, \"type\", r.Type)\n\tpopulate(objectMap, \"zones\", r.Zones)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\ttmpResource := struct {\n\t\tID ID `json:\"id\"`\n\t\tStatus Status `json:\"status\"`\n\t\tSince time.Time `json:\"since\"`\n\t}{\n\t\tr.ID,\n\t\tr.Status,\n\t\tr.Since,\n\t}\n\treturn json.Marshal(tmpResource)\n}", "func (c ChildResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"etag\", c.Etag)\n\tpopulate(objectMap, \"id\", c.ID)\n\tpopulate(objectMap, \"name\", c.Name)\n\tpopulate(objectMap, \"type\", c.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r *HybridResource) MarshalJSON() ([]byte, error) {\n\tif r.Many != nil {\n\t\treturn json.Marshal(r.Many)\n\t}\n\n\treturn json.Marshal(r.One)\n}", "func (m *JSONMarshaller) Marshal(message proto.Message) ([]byte, error) {\n\treturn m.marshaller.MarshalResource(message)\n}", "func (m MonitorResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", m.ID)\n\tpopulate(objectMap, \"identity\", m.Identity)\n\tpopulate(objectMap, \"location\", m.Location)\n\tpopulate(objectMap, \"name\", m.Name)\n\tpopulate(objectMap, \"properties\", m.Properties)\n\tpopulate(objectMap, \"systemData\", m.SystemData)\n\tpopulate(objectMap, \"tags\", m.Tags)\n\tpopulate(objectMap, \"type\", m.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif r.Location != nil {\n\t\tobjectMap[\"location\"] = r.Location\n\t}\n\tif r.Tags != nil {\n\t\tobjectMap[\"tags\"] = r.Tags\n\t}\n\tif r.Sku != nil {\n\t\tobjectMap[\"sku\"] = r.Sku\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (e EndpointResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", e.ID)\n\tpopulate(objectMap, \"name\", e.Name)\n\tpopulate(objectMap, \"properties\", e.Properties)\n\tpopulate(objectMap, \"systemData\", e.SystemData)\n\tpopulate(objectMap, \"type\", e.Type)\n\treturn json.Marshal(objectMap)\n}", "func (f FhirServicePatchResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"identity\", f.Identity)\n\tpopulate(objectMap, \"tags\", f.Tags)\n\treturn json.Marshal(objectMap)\n}", "func (s SwapResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", s.ID)\n\tpopulate(objectMap, \"name\", s.Name)\n\tpopulate(objectMap, \"properties\", s.Properties)\n\tpopulate(objectMap, \"type\", s.Type)\n\treturn json.Marshal(objectMap)\n}", "func (o OrchestratorResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", o.ID)\n\tpopulate(objectMap, \"identity\", o.Identity)\n\tpopulate(objectMap, \"kind\", o.Kind)\n\tpopulate(objectMap, \"location\", o.Location)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"tags\", o.Tags)\n\tpopulate(objectMap, \"type\", o.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif r.Tags != nil {\n\t\tobjectMap[\"tags\"] = r.Tags\n\t}\n\tif r.Location != nil {\n\t\tobjectMap[\"location\"] = r.Location\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (e EndpointResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", e.ID)\n\tpopulate(objectMap, \"name\", e.Name)\n\tpopulate(objectMap, \"properties\", e.Properties)\n\tpopulate(objectMap, \"systemData\", e.SystemData)\n\tpopulate(objectMap, \"type\", e.Type)\n\treturn json.Marshal(objectMap)\n}", "func (pr ProxyResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif pr.ID != nil {\n\t\tobjectMap[\"id\"] = pr.ID\n\t}\n\tif pr.Name != nil {\n\t\tobjectMap[\"name\"] = pr.Name\n\t}\n\tif pr.Type != nil {\n\t\tobjectMap[\"type\"] = pr.Type\n\t}\n\tif pr.Tags != nil {\n\t\tobjectMap[\"tags\"] = pr.Tags\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (r Resource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif r.Location != nil {\n\t\tobjectMap[\"location\"] = r.Location\n\t}\n\tif r.Tags != nil {\n\t\tobjectMap[\"tags\"] = r.Tags\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (t TaggedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"etag\", t.Etag)\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (ssor SingleSignOnResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif ssor.SystemData != nil {\n\t\tobjectMap[\"systemData\"] = ssor.SystemData\n\t}\n\tif ssor.Properties != nil {\n\t\tobjectMap[\"properties\"] = ssor.Properties\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (mr MonitorResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif mr.Properties != nil {\n\t\tobjectMap[\"properties\"] = mr.Properties\n\t}\n\tif mr.Identity != nil {\n\t\tobjectMap[\"identity\"] = mr.Identity\n\t}\n\tif mr.Tags != nil {\n\t\tobjectMap[\"tags\"] = mr.Tags\n\t}\n\tif mr.Location != nil {\n\t\tobjectMap[\"location\"] = mr.Location\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"systemData\", t.SystemData)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"systemData\", t.SystemData)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (s ServicesResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"etag\", s.Etag)\n\tpopulate(objectMap, \"id\", s.ID)\n\tpopulate(objectMap, \"identity\", s.Identity)\n\tpopulate(objectMap, \"kind\", s.Kind)\n\tpopulate(objectMap, \"location\", s.Location)\n\tpopulate(objectMap, \"name\", s.Name)\n\tpopulate(objectMap, \"tags\", s.Tags)\n\tpopulate(objectMap, \"type\", s.Type)\n\treturn json.Marshal(objectMap)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (pr ProxyResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\treturn json.Marshal(objectMap)\n}", "func (s SubResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", s.ID)\n\tpopulate(objectMap, \"name\", s.Name)\n\tpopulate(objectMap, \"type\", s.Type)\n\treturn json.Marshal(objectMap)\n}", "func (s SubResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", s.ID)\n\treturn json.Marshal(objectMap)\n}", "func (s SubResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", s.ID)\n\treturn json.Marshal(objectMap)\n}", "func (s SubResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", s.ID)\n\treturn json.Marshal(objectMap)\n}", "func (c ControllerResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", c.ID)\n\tpopulate(objectMap, \"location\", c.Location)\n\tpopulate(objectMap, \"name\", c.Name)\n\tpopulate(objectMap, \"tags\", c.Tags)\n\tpopulate(objectMap, \"type\", c.Type)\n\treturn json.Marshal(objectMap)\n}", "func (d DicomServicePatchResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"identity\", d.Identity)\n\tpopulate(objectMap, \"tags\", d.Tags)\n\treturn json.Marshal(objectMap)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"systemData\", t.SystemData)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (m ManagedProxyResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"expiresOn\", m.ExpiresOn)\n\tpopulate(objectMap, \"proxy\", m.Proxy)\n\treturn json.Marshal(objectMap)\n}", "func (tr TrackedResource)MarshalJSON() ([]byte, error){\n objectMap := make(map[string]interface{})\n if(tr.Tags != nil) {\n objectMap[\"tags\"] = tr.Tags\n }\n if(tr.Location != nil) {\n objectMap[\"location\"] = tr.Location\n }\n return json.Marshal(objectMap)\n }", "func (i IotConnectorPatchResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"identity\", i.Identity)\n\tpopulate(objectMap, \"tags\", i.Tags)\n\treturn json.Marshal(objectMap)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (t TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\tpopulate(objectMap, \"type\", t.Type)\n\treturn json.Marshal(objectMap)\n}", "func (t TagsResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"tags\", t.Tags)\n\treturn json.Marshal(objectMap)\n}", "func (t TagsResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"tags\", t.Tags)\n\treturn json.Marshal(objectMap)\n}", "func (a AzureEntityResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"etag\", a.Etag)\n\tpopulate(objectMap, \"id\", a.ID)\n\tpopulate(objectMap, \"name\", a.Name)\n\tpopulate(objectMap, \"type\", a.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r ResourceAutoGenerated) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (n NamespaceResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", n.ID)\n\tpopulate(objectMap, \"location\", n.Location)\n\tpopulate(objectMap, \"name\", n.Name)\n\tpopulate(objectMap, \"properties\", n.Properties)\n\tpopulate(objectMap, \"sku\", n.SKU)\n\tpopulate(objectMap, \"tags\", n.Tags)\n\tpopulate(objectMap, \"type\", n.Type)\n\treturn json.Marshal(objectMap)\n}", "func (u UpdateResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"tags\", u.Tags)\n\treturn json.Marshal(objectMap)\n}", "func (resource *Patient) MarshalJSON() ([]byte, error) {\n\tresource.ResourceType = \"Patient\"\n\t// Dereferencing the pointer to avoid infinite recursion.\n\t// Passing in plain old x (a pointer to Patient), would cause this same\n\t// MarshallJSON function to be called again\n\treturn json.Marshal(*resource)\n}", "func (n NotificationHubResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", n.ID)\n\tpopulate(objectMap, \"location\", n.Location)\n\tpopulate(objectMap, \"name\", n.Name)\n\tpopulate(objectMap, \"properties\", n.Properties)\n\tpopulate(objectMap, \"sku\", n.SKU)\n\tpopulate(objectMap, \"tags\", n.Tags)\n\tpopulate(objectMap, \"type\", n.Type)\n\treturn json.Marshal(objectMap)\n}", "func (ur UpdateResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif ur.Tags != nil {\n\t\tobjectMap[\"tags\"] = ur.Tags\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (j JobResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", j.ID)\n\tpopulate(objectMap, \"identity\", j.Identity)\n\tpopulate(objectMap, \"location\", j.Location)\n\tpopulate(objectMap, \"name\", j.Name)\n\tpopulate(objectMap, \"properties\", j.Properties)\n\tpopulate(objectMap, \"sku\", j.SKU)\n\tpopulate(objectMap, \"systemData\", j.SystemData)\n\tpopulate(objectMap, \"tags\", j.Tags)\n\tpopulate(objectMap, \"type\", j.Type)\n\treturn json.Marshal(objectMap)\n}", "func (aer AzureEntityResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\treturn json.Marshal(objectMap)\n}", "func (p PatchResourceTags) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"tags\", p.Tags)\n\treturn json.Marshal(objectMap)\n}", "func (r ResourceCreation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"properties\", r.Properties)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (e EndpointAccessResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"relay\", e.Relay)\n\treturn json.Marshal(objectMap)\n}", "func (resource *Claim) MarshalJSON() ([]byte, error) {\n\tresource.ResourceType = \"Claim\"\n\t// Dereferencing the pointer to avoid infinite recursion.\n\t// Passing in plain old x (a pointer to Claim), would cause this same\n\t// MarshallJSON function to be called again\n\treturn json.Marshal(*resource)\n}", "func (resource *Claim) MarshalJSON() ([]byte, error) {\n\tresource.ResourceType = \"Claim\"\n\t// Dereferencing the pointer to avoid infinite recursion.\n\t// Passing in plain old x (a pointer to Claim), would cause this same\n\t// MarshallJSON function to be called again\n\treturn json.Marshal(*resource)\n}", "func Resource(w http.ResponseWriter, status int, resource interface{}) error {\n\tw.Header().Set(\"Content-Type\", jsonapi.MediaType)\n\tw.WriteHeader(status)\n\n\treturn jsonapi.MarshalPayload(w, resource)\n}", "func (tr TagsResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif tr.Tags != nil {\n\t\tobjectMap[\"tags\"] = tr.Tags\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (t TopologyResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"associations\", t.Associations)\n\tpopulate(objectMap, \"id\", t.ID)\n\tpopulate(objectMap, \"location\", t.Location)\n\tpopulate(objectMap, \"name\", t.Name)\n\treturn json.Marshal(objectMap)\n}", "func (resource *Communication) MarshalJSON() ([]byte, error) {\n\tresource.ResourceType = \"Communication\"\n\t// Dereferencing the pointer to avoid infinite recursion.\n\t// Passing in plain old x (a pointer to Communication), would cause this same\n\t// MarshallJSON function to be called again\n\treturn json.Marshal(*resource)\n}", "func (tr TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif tr.Tags != nil {\n\t\tobjectMap[\"tags\"] = tr.Tags\n\t}\n\tif tr.Location != nil {\n\t\tobjectMap[\"location\"] = tr.Location\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (tr TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif tr.Tags != nil {\n\t\tobjectMap[\"tags\"] = tr.Tags\n\t}\n\tif tr.Location != nil {\n\t\tobjectMap[\"location\"] = tr.Location\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (tr TrackedResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif tr.Tags != nil {\n\t\tobjectMap[\"tags\"] = tr.Tags\n\t}\n\tif tr.Location != nil {\n\t\tobjectMap[\"location\"] = tr.Location\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (o MicrosoftGraphResourceAction) MarshalJSON() ([]byte, error) {\n\ttoSerialize := map[string]interface{}{}\n\tif o.AllowedResourceActions != nil {\n\t\ttoSerialize[\"allowedResourceActions\"] = o.AllowedResourceActions\n\t}\n\tif o.NotAllowedResourceActions != nil {\n\t\ttoSerialize[\"notAllowedResourceActions\"] = o.NotAllowedResourceActions\n\t}\n\treturn json.Marshal(toSerialize)\n}", "func (resource *Consent) MarshalJSON() ([]byte, error) {\n\tresource.ResourceType = \"Consent\"\n\t// Dereferencing the pointer to avoid infinite recursion.\n\t// Passing in plain old x (a pointer to Consent), would cause this same\n\t// MarshallJSON function to be called again\n\treturn json.Marshal(*resource)\n}", "func (resource *Device) MarshalJSON() ([]byte, error) {\n\tresource.ResourceType = \"Device\"\n\t// Dereferencing the pointer to avoid infinite recursion.\n\t// Passing in plain old x (a pointer to Device), would cause this same\n\t// MarshallJSON function to be called again\n\treturn json.Marshal(*resource)\n}", "func (c ChangeResourceResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", c.ID)\n\tpopulate(objectMap, \"name\", c.Name)\n\tpopulate(objectMap, \"properties\", c.Properties)\n\tpopulate(objectMap, \"type\", c.Type)\n\treturn json.Marshal(objectMap)\n}" ]
[ "0.7476091", "0.7476091", "0.7476091", "0.7476091", "0.7476091", "0.7476091", "0.7476091", "0.74696314", "0.74696314", "0.7465805", "0.741877", "0.7416342", "0.7416342", "0.7416342", "0.7416342", "0.7373975", "0.7329362", "0.7325485", "0.7325485", "0.7312305", "0.7307077", "0.7307077", "0.7276213", "0.7276213", "0.72595876", "0.72595876", "0.72595876", "0.72595876", "0.72595876", "0.7258084", "0.7247056", "0.7233845", "0.7227363", "0.7192468", "0.71912986", "0.7185286", "0.7169583", "0.7166803", "0.7164691", "0.71597344", "0.71511835", "0.7143279", "0.7137017", "0.70993346", "0.70748377", "0.70626855", "0.704521", "0.70440453", "0.70440453", "0.70299095", "0.7015401", "0.7015401", "0.7015401", "0.7014677", "0.7005273", "0.6997301", "0.6997301", "0.6997301", "0.6990923", "0.6990069", "0.6986126", "0.69804955", "0.6970928", "0.6962877", "0.6953238", "0.6953238", "0.6953238", "0.6953238", "0.6953238", "0.6953238", "0.6953238", "0.694646", "0.68797076", "0.6873912", "0.6867664", "0.6867443", "0.68580955", "0.68533576", "0.6849628", "0.6798975", "0.67935336", "0.679343", "0.67685354", "0.6747973", "0.6739145", "0.6736949", "0.6736949", "0.67151135", "0.6703415", "0.6670824", "0.6669665", "0.66653913", "0.66653913", "0.66653913", "0.66638166", "0.6658127", "0.6653054", "0.6649841" ]
0.73491335
18
MarshalJSON is the custom marshaler for SavedSearch.
func (ss SavedSearch) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if ss.ID != nil { objectMap["id"] = ss.ID } if ss.Name != nil { objectMap["name"] = ss.Name } if ss.Type != nil { objectMap["type"] = ss.Type } if ss.ETag != nil { objectMap["eTag"] = ss.ETag } if ss.SavedSearchProperties != nil { objectMap["properties"] = ss.SavedSearchProperties } return json.Marshal(objectMap) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (ss SavedSearch) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif ss.Etag != nil {\n\t\tobjectMap[\"etag\"] = ss.Etag\n\t}\n\tif ss.SavedSearchProperties != nil {\n\t\tobjectMap[\"properties\"] = ss.SavedSearchProperties\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (v Search) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson2f147938EncodeGithubComGoParkMailRu20202CodeExpressInternalModels(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v Search) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson2f147938EncodeGithubComGoParkMailRu20202CodeExpressInternalModels(w, v)\n}", "func (v SearchResult) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer7(w, v)\n}", "func (v SearchResult) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer7(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v SearchResult) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonD2b7633eEncodeGithubComIskiyRabotauaTelegramBotPkgRabotaua5(w, v)\n}", "func (v SearchRequest) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer8(w, v)\n}", "func (v SearchResult) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncodeGithubComIskiyRabotauaTelegramBotPkgRabotaua5(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v SearchRequest) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer8(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (o MonitorSearchResult) MarshalJSON() ([]byte, error) {\n\ttoSerialize := map[string]interface{}{}\n\tif o.UnparsedObject != nil {\n\t\treturn json.Marshal(o.UnparsedObject)\n\t}\n\tif o.Classification != nil {\n\t\ttoSerialize[\"classification\"] = o.Classification\n\t}\n\tif o.Creator != nil {\n\t\ttoSerialize[\"creator\"] = o.Creator\n\t}\n\tif o.Id != nil {\n\t\ttoSerialize[\"id\"] = o.Id\n\t}\n\tif o.LastTriggeredTs.IsSet() {\n\t\ttoSerialize[\"last_triggered_ts\"] = o.LastTriggeredTs.Get()\n\t}\n\tif o.Metrics != nil {\n\t\ttoSerialize[\"metrics\"] = o.Metrics\n\t}\n\tif o.Name != nil {\n\t\ttoSerialize[\"name\"] = o.Name\n\t}\n\tif o.Notifications != nil {\n\t\ttoSerialize[\"notifications\"] = o.Notifications\n\t}\n\tif o.OrgId != nil {\n\t\ttoSerialize[\"org_id\"] = o.OrgId\n\t}\n\tif o.Query != nil {\n\t\ttoSerialize[\"query\"] = o.Query\n\t}\n\tif o.Scopes != nil {\n\t\ttoSerialize[\"scopes\"] = o.Scopes\n\t}\n\tif o.Status != nil {\n\t\ttoSerialize[\"status\"] = o.Status\n\t}\n\tif o.Tags != nil {\n\t\ttoSerialize[\"tags\"] = o.Tags\n\t}\n\tif o.Type != nil {\n\t\ttoSerialize[\"type\"] = o.Type\n\t}\n\n\tfor key, value := range o.AdditionalProperties {\n\t\ttoSerialize[key] = value\n\t}\n\treturn json.Marshal(toSerialize)\n}", "func (sr SearchResponse) MarshalJSON() ([]byte, error) {\n\tsr.Type = TypeSearchResponse\n\tobjectMap := make(map[string]interface{})\n\tif sr.QueryContext != nil {\n\t\tobjectMap[\"queryContext\"] = sr.QueryContext\n\t}\n\tif sr.Entities != nil {\n\t\tobjectMap[\"entities\"] = sr.Entities\n\t}\n\tif sr.Places != nil {\n\t\tobjectMap[\"places\"] = sr.Places\n\t}\n\tif sr.ContractualRules != nil {\n\t\tobjectMap[\"contractualRules\"] = sr.ContractualRules\n\t}\n\tif sr.WebSearchURL != nil {\n\t\tobjectMap[\"webSearchUrl\"] = sr.WebSearchURL\n\t}\n\tif sr.ID != nil {\n\t\tobjectMap[\"id\"] = sr.ID\n\t}\n\tif sr.Type != \"\" {\n\t\tobjectMap[\"_type\"] = sr.Type\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (r *SearchRequest) MarshalJSON() ([]byte, error) {\n\troot := make(map[string]interface{})\n\n\troot[\"size\"] = r.Size\n\tif len(r.Sort) > 0 {\n\t\troot[\"sort\"] = r.Sort\n\t}\n\n\tfor key, value := range r.CustomProps {\n\t\troot[key] = value\n\t}\n\n\troot[\"query\"] = r.Query\n\n\tif len(r.Aggs) > 0 {\n\t\troot[\"aggs\"] = r.Aggs\n\t}\n\n\treturn json.Marshal(root)\n}", "func (v ChannelSearch) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer31(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v ChannelSearch) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer31(w, v)\n}", "func (value ObjectSearchType) MarshalJSON() ([]byte, error) {\n\tstr, err := objectSearchTypeEnumMap.String(int(value))\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"Unknown ObjectSearchType<%d>\", value)\n\t}\n\treturn []byte(fmt.Sprintf(`\"%s\"`, str)), nil\n}", "func (s SearchAssistant) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tobjectMap[\"channelName\"] = \"SearchAssistant\"\n\tpopulate(objectMap, \"etag\", s.Etag)\n\tpopulate(objectMap, \"location\", s.Location)\n\tpopulate(objectMap, \"provisioningState\", s.ProvisioningState)\n\treturn json.Marshal(objectMap)\n}", "func (v ChannelSearchResult) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer30(w, v)\n}", "func (m *SearchBucket) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"aggregationFilterToken\", m.GetAggregationFilterToken())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteInt32Value(\"count\", m.GetCount())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"key\", m.GetKey())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (v Stash) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncodeDrhyuComIndexerModels(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (m *SearchRequest) MarshalJSON() ([]byte, error) {\n\tif m == nil {\n\t\treturn json.Marshal(nil)\n\t}\n\n\tbuf := &bytes.Buffer{}\n\n\tif err := SearchRequestJSONMarshaler.Marshal(buf, m); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func (i IDPSQueryObject) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"filters\", i.Filters)\n\tpopulate(objectMap, \"orderBy\", i.OrderBy)\n\tpopulate(objectMap, \"resultsPerPage\", i.ResultsPerPage)\n\tpopulate(objectMap, \"search\", i.Search)\n\tpopulate(objectMap, \"skip\", i.Skip)\n\treturn json.Marshal(objectMap)\n}", "func (m *SearchResponse) MarshalJSON() ([]byte, error) {\n\tif m == nil {\n\t\treturn json.Marshal(nil)\n\t}\n\n\tbuf := &bytes.Buffer{}\n\n\tif err := SearchResponseJSONMarshaler.Marshal(buf, m); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func (v ChannelSearchResult) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer30(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (q QueryResults) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"matchingRecordsCount\", q.MatchingRecordsCount)\n\tpopulate(objectMap, \"signatures\", q.Signatures)\n\treturn json.Marshal(objectMap)\n}", "func (src SearchSuggestItemResponse) MarshalJSON() ([]byte, error) {\n\tif src.MoDocumentCount != nil {\n\t\treturn json.Marshal(&src.MoDocumentCount)\n\t}\n\n\tif src.SearchSuggestItemList != nil {\n\t\treturn json.Marshal(&src.SearchSuggestItemList)\n\t}\n\n\treturn nil, nil // no data in oneOf schemas\n}", "func (v SearchInResourceParams) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage18(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v matchPhraseQuery) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson390b7126EncodeGithubComChancedPicker20(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func marshalLogLogSearchToLogSearchRequestBody(v *log.LogSearch) *LogSearchRequestBody {\n\tres := &LogSearchRequestBody{\n\t\tName: v.Name,\n\t\tDescription: v.Description,\n\t}\n\n\treturn res\n}", "func (value ObjectSearchSource) MarshalJSON() ([]byte, error) {\n\tstr, err := objectSearchSourceEnumMap.String(int(value))\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"Unknown ObjectSearchSource<%d>\", value)\n\t}\n\treturn []byte(fmt.Sprintf(`\"%s\"`, str)), nil\n}", "func (f *QueryStringFilter) MarshalJSON() ([]byte, error) {\n\troot := map[string]interface{}{\n\t\t\"query_string\": map[string]interface{}{\n\t\t\t\"query\": f.Query,\n\t\t\t\"analyze_wildcard\": f.AnalyzeWildcard,\n\t\t},\n\t}\n\n\treturn json.Marshal(root)\n}", "func (v moreLikeThisQuery) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson390b7126EncodeGithubComChancedPicker18(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v matchPhrasePrefixQuery) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson390b7126EncodeGithubComChancedPicker21(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v SearchInResourceReturns) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage17(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func searchHandler(w http.ResponseWriter, r *http.Request) {\r\n\tresultJson, _ := json.Marshal(grafanaItemList)\r\n\tfmt.Fprintf(w, string(resultJson))\r\n}", "func (j *JsonMarshaler) Marshal(v interface{}) ([]byte, error) {\n\tswitch v.(type) {\n\tcase *distribute.GetResponse:\n\t\tvalue, err := protobuf.MarshalAny(v.(*distribute.GetResponse).Fields)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn json.Marshal(\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"fields\": value,\n\t\t\t},\n\t\t)\n\tcase *distribute.SearchResponse:\n\t\tvalue, err := protobuf.MarshalAny(v.(*distribute.SearchResponse).SearchResult)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn json.Marshal(\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"search_result\": value,\n\t\t\t},\n\t\t)\n\tdefault:\n\t\treturn json.Marshal(v)\n\t}\n}", "func (a *SearchInResourceArgs) MarshalJSON() ([]byte, error) {\n\ttype Copy SearchInResourceArgs\n\tc := &Copy{}\n\t*c = Copy(*a)\n\treturn json.Marshal(&c)\n}", "func (v matchPhrasePrefixQuery) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson390b7126EncodeGithubComChancedPicker21(w, v)\n}", "func marshalLogSearchRequestBodyToLogLogSearch(v *LogSearchRequestBody) *log.LogSearch {\n\tres := &log.LogSearch{\n\t\tName: v.Name,\n\t\tDescription: v.Description,\n\t}\n\n\treturn res\n}", "func (v SearchInResourceReturns) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage17(w, v)\n}", "func (s Suggester) MarshalJSON() ([]byte, error) {\n\ttype opt Suggester\n\t// We transform the struct to a map without the embedded additional properties map\n\ttmp := make(map[string]interface{}, 0)\n\n\tdata, err := json.Marshal(opt(s))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(data, &tmp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// We inline the additional fields from the underlying map\n\tfor key, value := range s.Suggesters {\n\t\ttmp[fmt.Sprintf(\"%s\", key)] = value\n\t}\n\tdelete(tmp, \"Suggesters\")\n\n\tdata, err = json.Marshal(tmp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}", "func (q QueryFilter) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"and\", q.And)\n\tpopulate(objectMap, \"dimension\", q.Dimension)\n\tpopulate(objectMap, \"not\", q.Not)\n\tpopulate(objectMap, \"or\", q.Or)\n\tpopulate(objectMap, \"tag\", q.Tag)\n\treturn json.Marshal(objectMap)\n}", "func (m *EdiscoverySearch) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Search.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetAdditionalSources() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAdditionalSources())\n err = writer.WriteCollectionOfObjectValues(\"additionalSources\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"addToReviewSetOperation\", m.GetAddToReviewSetOperation())\n if err != nil {\n return err\n }\n }\n if m.GetCustodianSources() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetCustodianSources())\n err = writer.WriteCollectionOfObjectValues(\"custodianSources\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetDataSourceScopes() != nil {\n cast := (*m.GetDataSourceScopes()).String()\n err = writer.WriteStringValue(\"dataSourceScopes\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"lastEstimateStatisticsOperation\", m.GetLastEstimateStatisticsOperation())\n if err != nil {\n return err\n }\n }\n if m.GetNoncustodialSources() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetNoncustodialSources())\n err = writer.WriteCollectionOfObjectValues(\"noncustodialSources\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (f ListFilter) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(f.Set.Values())\n}", "func (s SignatureOverridesFilterValuesQuery) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"filterName\", s.FilterName)\n\treturn json.Marshal(objectMap)\n}", "func (r RemediationFilters) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"locations\", r.Locations)\n\treturn json.Marshal(objectMap)\n}", "func (v matchPhraseQuery) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson390b7126EncodeGithubComChancedPicker20(w, v)\n}", "func (v DocumentTitleUpdate) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonDe066f3EncodeGithubComStudtoolDocumentsServiceModels2(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (s StringContainsAdvancedFilter) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"key\", s.Key)\n\tobjectMap[\"operatorType\"] = AdvancedFilterOperatorTypeStringContains\n\tpopulate(objectMap, \"values\", s.Values)\n\treturn json.Marshal(objectMap)\n}", "func (v SearchInResourceParams) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage18(w, v)\n}", "func (f CollectionFilter) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(f.Set.Values())\n}", "func (v Stash) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonD2b7633eEncodeDrhyuComIndexerModels(w, v)\n}", "func (f FilterItems) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"field\", f.Field)\n\tpopulate(objectMap, \"values\", f.Values)\n\treturn json.Marshal(objectMap)\n}", "func (m *SearchIndexResponse) MarshalJSON() ([]byte, error) {\n\tif m == nil {\n\t\treturn json.Marshal(nil)\n\t}\n\n\tbuf := &bytes.Buffer{}\n\n\tif err := SearchIndexResponseJSONMarshaler.Marshal(buf, m); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func (q QueryResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"eTag\", q.ETag)\n\tpopulate(objectMap, \"id\", q.ID)\n\tpopulate(objectMap, \"location\", q.Location)\n\tpopulate(objectMap, \"name\", q.Name)\n\tpopulate(objectMap, \"properties\", q.Properties)\n\tpopulate(objectMap, \"sku\", q.SKU)\n\tpopulate(objectMap, \"tags\", q.Tags)\n\tpopulate(objectMap, \"type\", q.Type)\n\treturn json.Marshal(objectMap)\n}", "func (m *SearchIndexRequest) MarshalJSON() ([]byte, error) {\n\tif m == nil {\n\t\treturn json.Marshal(nil)\n\t}\n\n\tbuf := &bytes.Buffer{}\n\n\tif err := SearchIndexRequestJSONMarshaler.Marshal(buf, m); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func (s ServiceLocationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", s.NextLink)\n\tpopulate(objectMap, \"value\", s.Value)\n\treturn json.Marshal(objectMap)\n}", "func (sc SegmentCriterion) MarshalJSON() ([]byte, error) {\n\tsc.Type = TypeSegment\n\tobjectMap := make(map[string]interface{})\n\tif sc.ID != nil {\n\t\tobjectMap[\"id\"] = sc.ID\n\t}\n\tif sc.Exclude != nil {\n\t\tobjectMap[\"exclude\"] = sc.Exclude\n\t}\n\tif sc.Type != \"\" {\n\t\tobjectMap[\"type\"] = sc.Type\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (o EventsScalarQuery) MarshalJSON() ([]byte, error) {\n\ttoSerialize := map[string]interface{}{}\n\tif o.UnparsedObject != nil {\n\t\treturn json.Marshal(o.UnparsedObject)\n\t}\n\ttoSerialize[\"compute\"] = o.Compute\n\ttoSerialize[\"data_source\"] = o.DataSource\n\tif o.GroupBy != nil {\n\t\ttoSerialize[\"group_by\"] = o.GroupBy\n\t}\n\tif o.Indexes != nil {\n\t\ttoSerialize[\"indexes\"] = o.Indexes\n\t}\n\tif o.Name != nil {\n\t\ttoSerialize[\"name\"] = o.Name\n\t}\n\tif o.Search != nil {\n\t\ttoSerialize[\"search\"] = o.Search\n\t}\n\n\tfor key, value := range o.AdditionalProperties {\n\t\ttoSerialize[key] = value\n\t}\n\treturn json.Marshal(toSerialize)\n}", "func (f DOIFilter) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(f.Set.Values())\n}", "func (f *FilterWrap) MarshalJSON() ([]byte, error) {\n\tvar root interface{}\n\tif len(f.filters) > 1 {\n\t\troot = map[string]interface{}{f.boolClause: f.filters}\n\t} else if len(f.filters) == 1 {\n\t\troot = f.filters[0]\n\t}\n\treturn json.Marshal(root)\n}", "func (s Salmon) MarshalJSON() ([]byte, error) {\n\ts.Fishtype = FishtypeSalmon\n\ttype Alias Salmon\n\treturn json.Marshal(&struct {\n\t\tAlias\n\t}{\n\t\tAlias: (Alias)(s),\n\t})\n}", "func (qr QueryResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif qr.QueryProperties != nil {\n\t\tobjectMap[\"properties\"] = qr.QueryProperties\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (v simpleQueryStringQuery) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson390b7126EncodeGithubComChancedPicker7(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v matchBoolPrefixQuery) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson390b7126EncodeGithubComChancedPicker22(w, v)\n}", "func (v EventNavigatedWithinDocument) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage69(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (sra SearchResultsAnswer) MarshalJSON() ([]byte, error) {\n\tsra.Type = TypeSearchResultsAnswer\n\tobjectMap := make(map[string]interface{})\n\tif sra.QueryContext != nil {\n\t\tobjectMap[\"queryContext\"] = sra.QueryContext\n\t}\n\tif sra.ContractualRules != nil {\n\t\tobjectMap[\"contractualRules\"] = sra.ContractualRules\n\t}\n\tif sra.WebSearchURL != nil {\n\t\tobjectMap[\"webSearchUrl\"] = sra.WebSearchURL\n\t}\n\tif sra.ID != nil {\n\t\tobjectMap[\"id\"] = sra.ID\n\t}\n\tif sra.Type != \"\" {\n\t\tobjectMap[\"_type\"] = sra.Type\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (s ServiceLocation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", s.ID)\n\tpopulate(objectMap, \"name\", s.Name)\n\tpopulate(objectMap, \"properties\", s.Properties)\n\tpopulate(objectMap, \"type\", s.Type)\n\treturn json.Marshal(objectMap)\n}", "func (v PostGets) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson5a72dc82EncodeGithubComTimRazumovTechnoparkDBAppModels(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func JSONEncoder() Encoder { return jsonEncoder }", "func (v matchBoolPrefixQuery) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson390b7126EncodeGithubComChancedPicker22(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v PostGets) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson5a72dc82EncodeGithubComTimRazumovTechnoparkDBAppModels(w, v)\n}", "func (g Goblinshark) MarshalJSON() ([]byte, error) {\n\tg.Fishtype = FishtypeGoblin\n\ttype Alias Goblinshark\n\treturn json.Marshal(&struct {\n\t\tAlias\n\t}{\n\t\tAlias: (Alias)(g),\n\t})\n}", "func (obj CustomObjectKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias CustomObjectKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"key-value-document\", Alias: (*Alias)(&obj)})\n}", "func (s ServiceListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", s.NextLink)\n\tpopulate(objectMap, \"value\", s.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o FindProjectsOKBody) MarshalJSON() ([]byte, error) {\n\t_parts := make([][]byte, 0, 2)\n\n\tfindProjectsOKBodyAO0, err := swag.WriteJSON(o.SearchResult)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_parts = append(_parts, findProjectsOKBodyAO0)\n\n\tvar dataFindProjectsOKBodyAO1 struct {\n\t\tData []*models.ProjectOutput `json:\"data\"`\n\t}\n\n\tdataFindProjectsOKBodyAO1.Data = o.Data\n\n\tjsonDataFindProjectsOKBodyAO1, errFindProjectsOKBodyAO1 := swag.WriteJSON(dataFindProjectsOKBodyAO1)\n\tif errFindProjectsOKBodyAO1 != nil {\n\t\treturn nil, errFindProjectsOKBodyAO1\n\t}\n\t_parts = append(_parts, jsonDataFindProjectsOKBodyAO1)\n\n\treturn swag.ConcatJSON(_parts...), nil\n}", "func (v IndexedShape) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson390b7126EncodeGithubComChancedPicker53(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v hasChildQuery) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson390b7126EncodeGithubComChancedPicker30(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (i *Index) SaveJSON() ([]byte, error) {\n\treturn json.Marshal(i.Objects)\n}", "func (l ListVirtualWANsResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", l.NextLink)\n\tpopulate(objectMap, \"value\", l.Value)\n\treturn json.Marshal(objectMap)\n}", "func (v updateByQuery) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson390b7126EncodeGithubComChancedPicker2(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v DocumentsInfo) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonDe066f3EncodeGithubComStudtoolDocumentsServiceModels1(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v RespStruct) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncodeDrhyuComIndexerModels1(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v termsSetQuery) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson390b7126EncodeGithubComChancedPicker4(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (f FilterTrackSelection) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"trackSelections\", f.TrackSelections)\n\treturn json.Marshal(objectMap)\n}", "func (this *EnvoyFilter_ProxyMatch) MarshalJSON() ([]byte, error) {\n\tstr, err := EnvoyFilterMarshaler.MarshalToString(this)\n\treturn []byte(str), err\n}", "func (v Item) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncodeDrhyuComIndexerModels2(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (e ExportListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"value\", e.Value)\n\treturn json.Marshal(objectMap)\n}", "func (v distanceFeatureQuery) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson390b7126EncodeGithubComChancedPicker37(w, v)\n}", "func (v VirtualApplianceSKUListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", v.NextLink)\n\tpopulate(objectMap, \"value\", v.Value)\n\treturn json.Marshal(objectMap)\n}", "func (s ServiceProviderListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", s.NextLink)\n\tpopulate(objectMap, \"value\", s.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o MicrosoftGraphMailSearchFolder) MarshalJSON() ([]byte, error) {\n\ttoSerialize := map[string]interface{}{}\n\tif o.Id != nil {\n\t\ttoSerialize[\"id\"] = o.Id\n\t}\n\tif o.DisplayName == nil {\n\t\tif o.isExplicitNullDisplayName {\n\t\t\ttoSerialize[\"displayName\"] = o.DisplayName\n\t\t}\n\t} else {\n\t\ttoSerialize[\"displayName\"] = o.DisplayName\n\t}\n\tif o.ParentFolderId == nil {\n\t\tif o.isExplicitNullParentFolderId {\n\t\t\ttoSerialize[\"parentFolderId\"] = o.ParentFolderId\n\t\t}\n\t} else {\n\t\ttoSerialize[\"parentFolderId\"] = o.ParentFolderId\n\t}\n\tif o.ChildFolderCount == nil {\n\t\tif o.isExplicitNullChildFolderCount {\n\t\t\ttoSerialize[\"childFolderCount\"] = o.ChildFolderCount\n\t\t}\n\t} else {\n\t\ttoSerialize[\"childFolderCount\"] = o.ChildFolderCount\n\t}\n\tif o.UnreadItemCount == nil {\n\t\tif o.isExplicitNullUnreadItemCount {\n\t\t\ttoSerialize[\"unreadItemCount\"] = o.UnreadItemCount\n\t\t}\n\t} else {\n\t\ttoSerialize[\"unreadItemCount\"] = o.UnreadItemCount\n\t}\n\tif o.TotalItemCount == nil {\n\t\tif o.isExplicitNullTotalItemCount {\n\t\t\ttoSerialize[\"totalItemCount\"] = o.TotalItemCount\n\t\t}\n\t} else {\n\t\ttoSerialize[\"totalItemCount\"] = o.TotalItemCount\n\t}\n\tif o.SingleValueExtendedProperties != nil {\n\t\ttoSerialize[\"singleValueExtendedProperties\"] = o.SingleValueExtendedProperties\n\t}\n\tif o.MultiValueExtendedProperties != nil {\n\t\ttoSerialize[\"multiValueExtendedProperties\"] = o.MultiValueExtendedProperties\n\t}\n\tif o.Messages != nil {\n\t\ttoSerialize[\"messages\"] = o.Messages\n\t}\n\tif o.MessageRules != nil {\n\t\ttoSerialize[\"messageRules\"] = o.MessageRules\n\t}\n\tif o.ChildFolders != nil {\n\t\ttoSerialize[\"childFolders\"] = o.ChildFolders\n\t}\n\tif o.IsSupported == nil {\n\t\tif o.isExplicitNullIsSupported {\n\t\t\ttoSerialize[\"isSupported\"] = o.IsSupported\n\t\t}\n\t} else {\n\t\ttoSerialize[\"isSupported\"] = o.IsSupported\n\t}\n\tif o.IncludeNestedFolders == nil {\n\t\tif o.isExplicitNullIncludeNestedFolders {\n\t\t\ttoSerialize[\"includeNestedFolders\"] = o.IncludeNestedFolders\n\t\t}\n\t} else {\n\t\ttoSerialize[\"includeNestedFolders\"] = o.IncludeNestedFolders\n\t}\n\tif o.SourceFolderIds != nil {\n\t\ttoSerialize[\"sourceFolderIds\"] = o.SourceFolderIds\n\t}\n\tif o.FilterQuery == nil {\n\t\tif o.isExplicitNullFilterQuery {\n\t\t\ttoSerialize[\"filterQuery\"] = o.FilterQuery\n\t\t}\n\t} else {\n\t\ttoSerialize[\"filterQuery\"] = o.FilterQuery\n\t}\n\treturn json.Marshal(toSerialize)\n}", "func (v DocumentsInfo) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonDe066f3EncodeGithubComStudtoolDocumentsServiceModels1(w, v)\n}", "func (v queryStringQuery) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson390b7126EncodeGithubComChancedPicker12(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (obj StoreKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias StoreKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"store\", Alias: (*Alias)(&obj)})\n}", "func (l LiveEventInputTrackSelection) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"operation\", l.Operation)\n\tpopulate(objectMap, \"property\", l.Property)\n\tpopulate(objectMap, \"value\", l.Value)\n\treturn json.Marshal(objectMap)\n}", "func (table *Table) MarshalVariantIntoJson(results []map[string]interface{}) error {\n\t// table.AfterFinds = append(table.AfterFinds, table.MarshalVariantIntoJson)\n\tfor _, m := range results {\n\t\tfor k, v := range m {\n\t\t\tfield := table.GetField(k)\n\t\t\tif field == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif field.Type != `VARIANT` {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t//now we need do it\n\t\t\t//v is type of string. marshall it into msi.M\n\t\t\t_ = v\n\t\t}\n\n\t}\n\treturn nil\n}", "func (v queryStringQuery) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson390b7126EncodeGithubComChancedPicker12(w, v)\n}", "func (v idsQuery) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson390b7126EncodeGithubComChancedPicker27(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (s SynonymTokenFilter) MarshalJSON() ([]byte, error) {\n\ttype innerSynonymTokenFilter SynonymTokenFilter\n\ttmp := innerSynonymTokenFilter{\n\t\tExpand: s.Expand,\n\t\tFormat: s.Format,\n\t\tLenient: s.Lenient,\n\t\tSynonyms: s.Synonyms,\n\t\tSynonymsPath: s.SynonymsPath,\n\t\tTokenizer: s.Tokenizer,\n\t\tType: s.Type,\n\t\tUpdateable: s.Updateable,\n\t\tVersion: s.Version,\n\t}\n\n\ttmp.Type = \"synonym\"\n\n\treturn json.Marshal(tmp)\n}", "func (b BastionShareableLinkListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", b.NextLink)\n\tpopulate(objectMap, \"value\", b.Value)\n\treturn json.Marshal(objectMap)\n}" ]
[ "0.75482726", "0.7369112", "0.71126086", "0.7048309", "0.698273", "0.6798277", "0.67543656", "0.6696488", "0.6677788", "0.6649556", "0.6633521", "0.6551491", "0.63837445", "0.6356183", "0.60920906", "0.60864776", "0.6077219", "0.60147023", "0.60008925", "0.59449065", "0.59429157", "0.5940308", "0.59348285", "0.5897633", "0.58916116", "0.5859246", "0.5845544", "0.58379036", "0.5833505", "0.58279246", "0.58193696", "0.5804417", "0.5793902", "0.5781258", "0.575481", "0.5751052", "0.5744714", "0.57296", "0.5698699", "0.56924194", "0.56860244", "0.5680042", "0.5667424", "0.56568235", "0.56490195", "0.5640926", "0.5631272", "0.5606274", "0.55988693", "0.5592304", "0.558998", "0.5584315", "0.55788624", "0.5572362", "0.5541221", "0.5531048", "0.552552", "0.5524219", "0.55075026", "0.5499894", "0.5497568", "0.5484859", "0.54608124", "0.54590833", "0.54502773", "0.544893", "0.544639", "0.5442834", "0.5427813", "0.54238564", "0.5423713", "0.5419819", "0.5410308", "0.54071474", "0.5402651", "0.5399473", "0.539944", "0.5395653", "0.53877443", "0.5386768", "0.53703815", "0.5368762", "0.5364292", "0.5359311", "0.53500706", "0.53439456", "0.5342681", "0.5342423", "0.53385353", "0.5334584", "0.5333717", "0.5326504", "0.5326278", "0.53222495", "0.53203094", "0.5316157", "0.5315122", "0.53017", "0.52967066", "0.52930725" ]
0.7696174
0
UnmarshalJSON is the custom unmarshaler for SavedSearch struct.
func (ss *SavedSearch) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } ss.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } ss.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } ss.Type = &typeVar } case "eTag": if v != nil { var eTag string err = json.Unmarshal(*v, &eTag) if err != nil { return err } ss.ETag = &eTag } case "properties": if v != nil { var savedSearchProperties SavedSearchProperties err = json.Unmarshal(*v, &savedSearchProperties) if err != nil { return err } ss.SavedSearchProperties = &savedSearchProperties } } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (ss *SavedSearch) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"etag\":\n\t\t\tif v != nil {\n\t\t\t\tvar etag string\n\t\t\t\terr = json.Unmarshal(*v, &etag)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tss.Etag = &etag\n\t\t\t}\n\t\tcase \"properties\":\n\t\t\tif v != nil {\n\t\t\t\tvar savedSearchProperties SavedSearchProperties\n\t\t\t\terr = json.Unmarshal(*v, &savedSearchProperties)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tss.SavedSearchProperties = &savedSearchProperties\n\t\t\t}\n\t\tcase \"id\":\n\t\t\tif v != nil {\n\t\t\t\tvar ID string\n\t\t\t\terr = json.Unmarshal(*v, &ID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tss.ID = &ID\n\t\t\t}\n\t\tcase \"name\":\n\t\t\tif v != nil {\n\t\t\t\tvar name string\n\t\t\t\terr = json.Unmarshal(*v, &name)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tss.Name = &name\n\t\t\t}\n\t\tcase \"type\":\n\t\t\tif v != nil {\n\t\t\t\tvar typeVar string\n\t\t\t\terr = json.Unmarshal(*v, &typeVar)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tss.Type = &typeVar\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (v *Search) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson2f147938DecodeGithubComGoParkMailRu20202CodeExpressInternalModels(&r, v)\n\treturn r.Error()\n}", "func (s *Search) UnmarshalJSON(data []byte) error {\n\tdefaults.SetDefaults(s)\n\n\ttype aliasType Search\n\talias := aliasType(*s)\n\terr := json.Unmarshal(data, &alias)\n\n\t*s = Search(alias)\n\treturn err\n}", "func (v *TableWidgetHasSearchBar) UnmarshalJSON(src []byte) error {\n\tvar value string\n\terr := json.Unmarshal(src, &value)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*v = TableWidgetHasSearchBar(value)\n\treturn nil\n}", "func (v *SearchResult) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer7(&r, v)\n\treturn r.Error()\n}", "func (v *SearchResult) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeGithubComIskiyRabotauaTelegramBotPkgRabotaua5(&r, v)\n\treturn r.Error()\n}", "func (v *SearchRequest) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer8(&r, v)\n\treturn r.Error()\n}", "func (sr *SearchResponse) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"queryContext\":\n\t\t\tif v != nil {\n\t\t\t\tvar queryContext QueryContext\n\t\t\t\terr = json.Unmarshal(*v, &queryContext)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsr.QueryContext = &queryContext\n\t\t\t}\n\t\tcase \"entities\":\n\t\t\tif v != nil {\n\t\t\t\tvar entities Entities\n\t\t\t\terr = json.Unmarshal(*v, &entities)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsr.Entities = &entities\n\t\t\t}\n\t\tcase \"places\":\n\t\t\tif v != nil {\n\t\t\t\tvar places Places\n\t\t\t\terr = json.Unmarshal(*v, &places)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsr.Places = &places\n\t\t\t}\n\t\tcase \"contractualRules\":\n\t\t\tif v != nil {\n\t\t\t\tcontractualRules, err := unmarshalBasicContractualRulesContractualRuleArray(*v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsr.ContractualRules = &contractualRules\n\t\t\t}\n\t\tcase \"webSearchUrl\":\n\t\t\tif v != nil {\n\t\t\t\tvar webSearchURL string\n\t\t\t\terr = json.Unmarshal(*v, &webSearchURL)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsr.WebSearchURL = &webSearchURL\n\t\t\t}\n\t\tcase \"id\":\n\t\t\tif v != nil {\n\t\t\t\tvar ID string\n\t\t\t\terr = json.Unmarshal(*v, &ID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsr.ID = &ID\n\t\t\t}\n\t\tcase \"_type\":\n\t\t\tif v != nil {\n\t\t\t\tvar typeVar TypeBasicResponseBase\n\t\t\t\terr = json.Unmarshal(*v, &typeVar)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsr.Type = typeVar\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (value *ObjectSearchType) UnmarshalJSON(arg []byte) error {\n\ti, err := objectSearchTypeEnumMap.UnMarshal(arg)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Failed to unmarshal ObjectSearchType\")\n\t}\n\n\t*value = ObjectSearchType(i)\n\treturn nil\n}", "func (v *ChannelSearch) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer31(&r, v)\n\treturn r.Error()\n}", "func (m *SearchResponse) UnmarshalJSON(b []byte) error {\n\treturn SearchResponseJSONUnmarshaler.Unmarshal(bytes.NewReader(b), m)\n}", "func (m *SearchRequest) UnmarshalJSON(b []byte) error {\n\treturn SearchRequestJSONUnmarshaler.Unmarshal(bytes.NewReader(b), m)\n}", "func (o *MonitorSearchResult) UnmarshalJSON(bytes []byte) (err error) {\n\traw := map[string]interface{}{}\n\tall := struct {\n\t\tClassification *string `json:\"classification,omitempty\"`\n\t\tCreator *Creator `json:\"creator,omitempty\"`\n\t\tId *int64 `json:\"id,omitempty\"`\n\t\tLastTriggeredTs NullableInt64 `json:\"last_triggered_ts,omitempty\"`\n\t\tMetrics []string `json:\"metrics,omitempty\"`\n\t\tName *string `json:\"name,omitempty\"`\n\t\tNotifications []MonitorSearchResultNotification `json:\"notifications,omitempty\"`\n\t\tOrgId *int64 `json:\"org_id,omitempty\"`\n\t\tQuery *string `json:\"query,omitempty\"`\n\t\tScopes []string `json:\"scopes,omitempty\"`\n\t\tStatus *MonitorOverallStates `json:\"status,omitempty\"`\n\t\tTags []string `json:\"tags,omitempty\"`\n\t\tType *MonitorType `json:\"type,omitempty\"`\n\t}{}\n\terr = json.Unmarshal(bytes, &all)\n\tif err != nil {\n\t\terr = json.Unmarshal(bytes, &raw)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\to.UnparsedObject = raw\n\t\treturn nil\n\t}\n\tif v := all.Status; v != nil && !v.IsValid() {\n\t\terr = json.Unmarshal(bytes, &raw)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\to.UnparsedObject = raw\n\t\treturn nil\n\t}\n\tif v := all.Type; v != nil && !v.IsValid() {\n\t\terr = json.Unmarshal(bytes, &raw)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\to.UnparsedObject = raw\n\t\treturn nil\n\t}\n\to.Classification = all.Classification\n\tif all.Creator != nil && all.Creator.UnparsedObject != nil && o.UnparsedObject == nil {\n\t\terr = json.Unmarshal(bytes, &raw)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\to.UnparsedObject = raw\n\t}\n\to.Creator = all.Creator\n\to.Id = all.Id\n\to.LastTriggeredTs = all.LastTriggeredTs\n\to.Metrics = all.Metrics\n\to.Name = all.Name\n\to.Notifications = all.Notifications\n\to.OrgId = all.OrgId\n\to.Query = all.Query\n\to.Scopes = all.Scopes\n\to.Status = all.Status\n\to.Tags = all.Tags\n\to.Type = all.Type\n\treturn nil\n}", "func (v *Stash) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeDrhyuComIndexerModels(&r, v)\n\treturn r.Error()\n}", "func (s *SearchAssistant) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"channelName\":\n\t\t\terr = unpopulate(val, \"ChannelName\", &s.ChannelName)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"etag\":\n\t\t\terr = unpopulate(val, \"Etag\", &s.Etag)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"location\":\n\t\t\terr = unpopulate(val, \"Location\", &s.Location)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provisioningState\":\n\t\t\terr = unpopulate(val, \"ProvisioningState\", &s.ProvisioningState)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (v *Search) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson2f147938DecodeGithubComGoParkMailRu20202CodeExpressInternalModels(l, v)\n}", "func (value *ObjectSearchSource) UnmarshalJSON(arg []byte) error {\n\ti, err := objectSearchSourceEnumMap.UnMarshal(arg)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Failed to unmarshal ObjectSearchSource\")\n\t}\n\n\t*value = ObjectSearchSource(i)\n\treturn nil\n}", "func (v *SearchResult) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer7(l, v)\n}", "func (v *DocumentTitleUpdate) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonDe066f3DecodeGithubComStudtoolDocumentsServiceModels2(&r, v)\n\treturn r.Error()\n}", "func (dst *SearchSuggestItemResponse) UnmarshalJSON(data []byte) error {\n\tvar err error\n\t// use discriminator value to speed up the lookup\n\tvar jsonDict map[string]interface{}\n\terr = newStrictDecoder(data).Decode(&jsonDict)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to unmarshal JSON into map for the discriminator lookup.\")\n\t}\n\n\t// check if the discriminator value is 'mo.DocumentCount'\n\tif jsonDict[\"ObjectType\"] == \"mo.DocumentCount\" {\n\t\t// try to unmarshal JSON data into MoDocumentCount\n\t\terr = json.Unmarshal(data, &dst.MoDocumentCount)\n\t\tif err == nil {\n\t\t\treturn nil // data stored in dst.MoDocumentCount, return on the first match\n\t\t} else {\n\t\t\tdst.MoDocumentCount = nil\n\t\t\treturn fmt.Errorf(\"Failed to unmarshal SearchSuggestItemResponse as MoDocumentCount: %s\", err.Error())\n\t\t}\n\t}\n\n\t// check if the discriminator value is 'search.SuggestItem.List'\n\tif jsonDict[\"ObjectType\"] == \"search.SuggestItem.List\" {\n\t\t// try to unmarshal JSON data into SearchSuggestItemList\n\t\terr = json.Unmarshal(data, &dst.SearchSuggestItemList)\n\t\tif err == nil {\n\t\t\treturn nil // data stored in dst.SearchSuggestItemList, return on the first match\n\t\t} else {\n\t\t\tdst.SearchSuggestItemList = nil\n\t\t\treturn fmt.Errorf(\"Failed to unmarshal SearchSuggestItemResponse as SearchSuggestItemList: %s\", err.Error())\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *SearchIndexResponse) UnmarshalJSON(b []byte) error {\n\treturn SearchIndexResponseJSONUnmarshaler.Unmarshal(bytes.NewReader(b), m)\n}", "func (m *SearchIndexRequest) UnmarshalJSON(b []byte) error {\n\treturn SearchIndexRequestJSONUnmarshaler.Unmarshal(bytes.NewReader(b), m)\n}", "func (v *moreLikeThisQuery) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson390b7126DecodeGithubComChancedPicker18(&r, v)\n\treturn r.Error()\n}", "func (v *QuerySortOrder) UnmarshalJSON(src []byte) error {\n\tvar value string\n\terr := json.Unmarshal(src, &value)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*v = QuerySortOrder(value)\n\treturn nil\n}", "func (v *SearchResult) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonD2b7633eDecodeGithubComIskiyRabotauaTelegramBotPkgRabotaua5(l, v)\n}", "func (w *Entry) UnmarshalJSON(bb []byte) error {\n\t<<!!YOUR_CODE!!>>\n}", "func (v *SearchRequest) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer8(l, v)\n}", "func (v *ChannelSearchResult) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer30(&r, v)\n\treturn r.Error()\n}", "func (a *SearchInResourceArgs) UnmarshalJSON(b []byte) error {\n\ttype Copy SearchInResourceArgs\n\tc := &Copy{}\n\terr := json.Unmarshal(b, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*a = SearchInResourceArgs(*c)\n\treturn nil\n}", "func (this *NamespacedName) UnmarshalJSON(b []byte) error {\n\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}", "func (v *matchPhraseQuery) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson390b7126DecodeGithubComChancedPicker20(&r, v)\n\treturn r.Error()\n}", "func (v *ShadowModelSt) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonB7ed31d3DecodeMevericcoreMccommon5(&r, v)\n\treturn r.Error()\n}", "func (j *Segment) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *EventNavigatedWithinDocument) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoPage69(&r, v)\n\treturn r.Error()\n}", "func (v *ShadowStateMetadataSt) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonB7ed31d3DecodeMevericcoreMccommon3(&r, v)\n\treturn r.Error()\n}", "func (v *SearchInResourceReturns) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoPage17(&r, v)\n\treturn r.Error()\n}", "func (v *hasChildQuery) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson390b7126DecodeGithubComChancedPicker30(&r, v)\n\treturn r.Error()\n}", "func (d *Definition) UnmarshalJSON(b []byte) error {\n\t// Aliasing Definition to avoid recursive call of this method\n\ttype definitionAlias Definition\n\tdefAlias := definitionAlias(*NewDefinition())\n\n\tif err := json.Unmarshal(b, &defAlias); err != nil {\n\t\treturn err\n\t}\n\n\t*d = Definition(defAlias)\n\treturn nil\n}", "func (v *Item) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeDrhyuComIndexerModels2(&r, v)\n\treturn r.Error()\n}", "func (s *StringContainsAdvancedFilter) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"key\":\n\t\t\terr = unpopulate(val, \"Key\", &s.Key)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operatorType\":\n\t\t\terr = unpopulate(val, \"OperatorType\", &s.OperatorType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"values\":\n\t\t\terr = unpopulate(val, \"Values\", &s.Values)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (j *ThirdParty) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *Visit) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonE564fc13DecodeGithubComLa0rgHighloadcupModel1(&r, v)\n\treturn r.Error()\n}", "func (v *EventLoadEventFired) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoPage70(&r, v)\n\treturn r.Error()\n}", "func (v *AddScriptToEvaluateOnNewDocumentReturns) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoPage105(&r, v)\n\treturn r.Error()\n}", "func (v *RespStruct) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeDrhyuComIndexerModels1(&r, v)\n\treturn r.Error()\n}", "func (v *rankFeatureQuery) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson390b7126DecodeGithubComChancedPicker11(&r, v)\n\treturn r.Error()\n}", "func (tok *Token) UnmarshalJSON(b []byte) error {\n\tvar s string\n\tif err := json.Unmarshal(b, &s); err != nil {\n\t\treturn err\n\t}\n\t*tok = Lookup(s)\n\treturn nil\n}", "func (s *SettingsUpdateResult) UnmarshalJSON(data []byte) error {\n\tres, err := unmarshalSettingClassification(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.SettingClassification = res\n\treturn nil\n}", "func (a *ActivityReportTitleUpdated) UnmarshalJSON(b []byte) error {\n\tvar helper activityReportTitleUpdatedUnmarshalHelper\n\tif err := json.Unmarshal(b, &helper); err != nil {\n\t\treturn err\n\t}\n\t*a = ActivityReportTitleUpdated(helper.Attributes)\n\treturn nil\n}", "func (v *updateByQuery) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson390b7126DecodeGithubComChancedPicker2(&r, v)\n\treturn r.Error()\n}", "func (j *Event) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *Regulations) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (self *AliasTypeDef) UnmarshalJSON(b []byte) error {\n\tvar m rawAliasTypeDef\n\terr := json.Unmarshal(b, &m)\n\tif err == nil {\n\t\to := AliasTypeDef(m)\n\t\t*self = o\n\t\terr = self.Validate()\n\t}\n\treturn err\n}", "func (lb *LocalBusiness) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"priceRange\":\n\t\t\tif v != nil {\n\t\t\t\tvar priceRange string\n\t\t\t\terr = json.Unmarshal(*v, &priceRange)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlb.PriceRange = &priceRange\n\t\t\t}\n\t\tcase \"panoramas\":\n\t\t\tif v != nil {\n\t\t\t\tvar panoramas []ImageObject\n\t\t\t\terr = json.Unmarshal(*v, &panoramas)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlb.Panoramas = &panoramas\n\t\t\t}\n\t\tcase \"isPermanentlyClosed\":\n\t\t\tif v != nil {\n\t\t\t\tvar isPermanentlyClosed bool\n\t\t\t\terr = json.Unmarshal(*v, &isPermanentlyClosed)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlb.IsPermanentlyClosed = &isPermanentlyClosed\n\t\t\t}\n\t\tcase \"tagLine\":\n\t\t\tif v != nil {\n\t\t\t\tvar tagLine string\n\t\t\t\terr = json.Unmarshal(*v, &tagLine)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlb.TagLine = &tagLine\n\t\t\t}\n\t\tcase \"address\":\n\t\t\tif v != nil {\n\t\t\t\tvar address PostalAddress\n\t\t\t\terr = json.Unmarshal(*v, &address)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlb.Address = &address\n\t\t\t}\n\t\tcase \"telephone\":\n\t\t\tif v != nil {\n\t\t\t\tvar telephone string\n\t\t\t\terr = json.Unmarshal(*v, &telephone)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlb.Telephone = &telephone\n\t\t\t}\n\t\tcase \"name\":\n\t\t\tif v != nil {\n\t\t\t\tvar name string\n\t\t\t\terr = json.Unmarshal(*v, &name)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlb.Name = &name\n\t\t\t}\n\t\tcase \"url\":\n\t\t\tif v != nil {\n\t\t\t\tvar URL string\n\t\t\t\terr = json.Unmarshal(*v, &URL)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlb.URL = &URL\n\t\t\t}\n\t\tcase \"image\":\n\t\t\tif v != nil {\n\t\t\t\tvar imageVar ImageObject\n\t\t\t\terr = json.Unmarshal(*v, &imageVar)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlb.Image = &imageVar\n\t\t\t}\n\t\tcase \"description\":\n\t\t\tif v != nil {\n\t\t\t\tvar description string\n\t\t\t\terr = json.Unmarshal(*v, &description)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlb.Description = &description\n\t\t\t}\n\t\tcase \"entityPresentationInfo\":\n\t\t\tif v != nil {\n\t\t\t\tvar entityPresentationInfo EntitiesEntityPresentationInfo\n\t\t\t\terr = json.Unmarshal(*v, &entityPresentationInfo)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlb.EntityPresentationInfo = &entityPresentationInfo\n\t\t\t}\n\t\tcase \"bingId\":\n\t\t\tif v != nil {\n\t\t\t\tvar bingID string\n\t\t\t\terr = json.Unmarshal(*v, &bingID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlb.BingID = &bingID\n\t\t\t}\n\t\tcase \"contractualRules\":\n\t\t\tif v != nil {\n\t\t\t\tcontractualRules, err := unmarshalBasicContractualRulesContractualRuleArray(*v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlb.ContractualRules = &contractualRules\n\t\t\t}\n\t\tcase \"webSearchUrl\":\n\t\t\tif v != nil {\n\t\t\t\tvar webSearchURL string\n\t\t\t\terr = json.Unmarshal(*v, &webSearchURL)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlb.WebSearchURL = &webSearchURL\n\t\t\t}\n\t\tcase \"id\":\n\t\t\tif v != nil {\n\t\t\t\tvar ID string\n\t\t\t\terr = json.Unmarshal(*v, &ID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlb.ID = &ID\n\t\t\t}\n\t\tcase \"_type\":\n\t\t\tif v != nil {\n\t\t\t\tvar typeVar TypeBasicResponseBase\n\t\t\t\terr = json.Unmarshal(*v, &typeVar)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlb.Type = typeVar\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (gbbsqd *GetBackupByStorageQueryDescription) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"StartDateTimeFilter\":\n\t\t\tif v != nil {\n\t\t\t\tvar startDateTimeFilter date.Time\n\t\t\t\terr = json.Unmarshal(*v, &startDateTimeFilter)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tgbbsqd.StartDateTimeFilter = &startDateTimeFilter\n\t\t\t}\n\t\tcase \"EndDateTimeFilter\":\n\t\t\tif v != nil {\n\t\t\t\tvar endDateTimeFilter date.Time\n\t\t\t\terr = json.Unmarshal(*v, &endDateTimeFilter)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tgbbsqd.EndDateTimeFilter = &endDateTimeFilter\n\t\t\t}\n\t\tcase \"Latest\":\n\t\t\tif v != nil {\n\t\t\t\tvar latest bool\n\t\t\t\terr = json.Unmarshal(*v, &latest)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tgbbsqd.Latest = &latest\n\t\t\t}\n\t\tcase \"Storage\":\n\t\t\tif v != nil {\n\t\t\t\tstorage, err := unmarshalBasicBackupStorageDescription(*v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tgbbsqd.Storage = storage\n\t\t\t}\n\t\tcase \"BackupEntity\":\n\t\t\tif v != nil {\n\t\t\t\tbackupEntity, err := unmarshalBasicBackupEntity(*v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tgbbsqd.BackupEntity = backupEntity\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (v *SearchInResourceParams) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoPage18(&r, v)\n\treturn r.Error()\n}", "func (v *ShadowStateSt) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonB7ed31d3DecodeMevericcoreMccommon2(&r, v)\n\treturn r.Error()\n}", "func (v *UnloadCheckResponse) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson6a975c40DecodeJsonBenchmark(&r, v)\n\treturn r.Error()\n}", "func (j *Publisher) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (o *ExportDataPartial) UnmarshalJSON(data []byte) error {\n\tkv := make(map[string]interface{})\n\tif err := json.Unmarshal(data, &kv); err != nil {\n\t\treturn err\n\t}\n\to.FromMap(kv)\n\treturn nil\n}", "func (this *ImportedReference) UnmarshalJSON(b []byte) error {\n\treturn TypesUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}", "func (v *deleteByQuery) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson390b7126DecodeGithubComChancedPicker39(&r, v)\n\treturn r.Error()\n}", "func (b *dictionaryBuilder) UnmarshalJSON([]byte) error {\n\treturn errors.New(\"unmarshal json to dictionary not yet implemented\")\n}", "func (v *PostGets) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson5a72dc82DecodeGithubComTimRazumovTechnoparkDBAppModels(&r, v)\n\treturn r.Error()\n}", "func (r *Results) UnmarshalJSON(b []byte) error {\n\tvar o struct {\n\t\tResults []Result `json:\"results,omitempty\"`\n\t\tErr string `json:\"error,omitempty\"`\n\t}\n\n\tdec := json.NewDecoder(bytes.NewBuffer(b))\n\tdec.UseNumber()\n\terr := dec.Decode(&o)\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.Results = o.Results\n\tif o.Err != \"\" {\n\t\tr.Err = errors.New(o.Err)\n\t}\n\treturn nil\n}", "func (s *Salmon) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar v *json.RawMessage\n\n\tv = m[\"location\"]\n\tif v != nil {\n\t\tvar location string\n\t\terr = json.Unmarshal(*m[\"location\"], &location)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ts.Location = &location\n\t}\n\n\tv = m[\"iswild\"]\n\tif v != nil {\n\t\tvar iswild bool\n\t\terr = json.Unmarshal(*m[\"iswild\"], &iswild)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ts.Iswild = &iswild\n\t}\n\n\tv = m[\"species\"]\n\tif v != nil {\n\t\tvar species string\n\t\terr = json.Unmarshal(*m[\"species\"], &species)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ts.Species = &species\n\t}\n\n\tv = m[\"length\"]\n\tif v != nil {\n\t\tvar length float64\n\t\terr = json.Unmarshal(*m[\"length\"], &length)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ts.Length = &length\n\t}\n\n\tv = m[\"siblings\"]\n\tif v != nil {\n\t\tsiblings, err := unmarshalFishArray(*m[\"siblings\"])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ts.Siblings = &siblings\n\t}\n\n\tv = m[\"fishtype\"]\n\tif v != nil {\n\t\tvar fishtype Fishtype\n\t\terr = json.Unmarshal(*m[\"fishtype\"], &fishtype)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ts.Fishtype = fishtype\n\t}\n\n\treturn nil\n}", "func (this *Service) UnmarshalJSON(b []byte) error {\n\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}", "func (v *ExportItem) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonB83d7b77DecodeGoplaygroundMyjson1(&r, v)\n\treturn r.Error()\n}", "func (s *ServiceLocationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &s.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &s.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (v *WidgetLiveSpan) UnmarshalJSON(src []byte) error {\n\tvar value string\n\terr := json.Unmarshal(src, &value)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*v = WidgetLiveSpan(value)\n\treturn nil\n}", "func (v *DocumentsInfo) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonDe066f3DecodeGithubComStudtoolDocumentsServiceModels1(&r, v)\n\treturn r.Error()\n}", "func (j *Json) UnmarshalJSON(data []byte) error {\n\terr := json.Unmarshal(data, &j.data)\n\n\tj.exists = (err == nil)\n\treturn err\n}", "func (j *Type) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *termsSetQuery) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson390b7126DecodeGithubComChancedPicker4(&r, v)\n\treturn r.Error()\n}", "func (s *GitEvent) UnmarshalJSON(b []byte) error {\n\tvar j string\n\terr := json.Unmarshal(b, &j)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Note that if the string cannot be found then it will be set to the zero value, 'Push' in this case.\n\t*s = toID[j]\n\treturn nil\n}", "func (op *OpRemove) UnmarshalJSON(raw []byte) error {\n\treturn json.Unmarshal(raw, &op.Field)\n}", "func (o *ExportData) UnmarshalJSON(data []byte) error {\n\tkv := make(map[string]interface{})\n\tif err := json.Unmarshal(data, &kv); err != nil {\n\t\treturn err\n\t}\n\to.FromMap(kv)\n\tif idstr, ok := kv[\"id\"].(string); ok {\n\t\to.ID = idstr\n\t}\n\treturn nil\n}", "func (t *Total) UnmarshalJSON(b []byte) error {\n\tvalue := struct {\n\t\tValue int `json:\"value\"`\n\t\tRelation string `json:\"relation\"`\n\t}{}\n\n\tif err := json.Unmarshal(b, &value); err == nil {\n\t\t*t = value\n\t\treturn nil\n\t}\n\n\t// fallback for Elasticsearch < 7\n\tif i, err := strconv.Atoi(string(b)); err == nil {\n\t\t*t = Total{Value: i, Relation: \"eq\"}\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"could not unmarshal JSON value '%s'\", string(b))\n}", "func (v *distanceFeatureQuery) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson390b7126DecodeGithubComChancedPicker37(&r, v)\n\treturn r.Error()\n}", "func (x *EBroadcastWatchLocation) UnmarshalJSON(b []byte) error {\n\tnum, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*x = EBroadcastWatchLocation(num)\n\treturn nil\n}", "func (s *Serving) UnmarshalJSON(text []byte) (err error) {\n\tvar sj servingJSON\n\terr = json.Unmarshal(text, &sj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.MealPlanID = sj.MealPlanID\n\ts.MealID = sj.MealID\n\n\ts.Date, err = time.Parse(JSONDateFormat, sj.Date)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (v *UpdateLikes) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\tdecodeUpdateLikes(&r, v)\n\treturn r.Error()\n}", "func (v *UpdateInfo) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonDe066f3DecodeGithubComStudtoolDocumentsServiceModels(&r, v)\n\treturn r.Error()\n}", "func (v *OneUpdateLike) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\tdecodeOneUpdateLike(&r, v)\n\treturn r.Error()\n}", "func (b *T) UnmarshalJSON(p []byte) error {\n\tb.BloomFilter = new(bloom.BloomFilter)\n\treturn json.Unmarshal(p, b.BloomFilter)\n}", "func (v *VisitArray) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonE564fc13DecodeGithubComLa0rgHighloadcupModel(&r, v)\n\treturn r.Error()\n}", "func (v *wildcardField) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson390b7126DecodeGithubComChancedPicker1(&r, v)\n\treturn r.Error()\n}", "func (this *Simple) UnmarshalJSON(b []byte) error {\n\treturn TypesUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}", "func (x *StockField) UnmarshalJSON(b []byte) error {\n\tnum, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*x = StockField(num)\n\treturn nil\n}", "func (v *matchBoolPrefixQuery) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson390b7126DecodeGithubComChancedPicker22(&r, v)\n\treturn r.Error()\n}", "func (this *StringMatch) UnmarshalJSON(b []byte) error {\n\treturn QuotaUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}", "func (s *SettingsGetResult) UnmarshalJSON(data []byte) error {\n\tres, err := unmarshalSettingClassification(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.SettingClassification = res\n\treturn nil\n}", "func (v *item) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeGithubComZhekabyGoGeneratorMongoRequestwrapperTests(&r, v)\n\treturn r.Error()\n}", "func (d *Document) UnmarshalJSON(bytes []byte) error {\n\t// unmarshal to map\n\tvar m Map\n\terr := json.Unmarshal(bytes, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// parse map\n\tdoc, err := Parse(m)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// validate document\n\terr = formatValidator.Validate(doc)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set document\n\t*d = doc\n\n\treturn nil\n}", "func (v *ToplistWidgetDefinitionType) UnmarshalJSON(src []byte) error {\n\tvar value string\n\terr := json.Unmarshal(src, &value)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*v = ToplistWidgetDefinitionType(value)\n\treturn nil\n}", "func (v *ScoredUser) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson6601e8cdDecodeJsongen2(&r, v)\n\treturn r.Error()\n}", "func (v *ChannelSearch) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer31(l, v)\n}", "func (v *queryStringQuery) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson390b7126DecodeGithubComChancedPicker12(&r, v)\n\treturn r.Error()\n}", "func (v *matchPhrasePrefixQuery) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson390b7126DecodeGithubComChancedPicker21(&r, v)\n\treturn r.Error()\n}", "func (q *QueryResults) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", q, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"matchingRecordsCount\":\n\t\t\terr = unpopulate(val, \"MatchingRecordsCount\", &q.MatchingRecordsCount)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"signatures\":\n\t\t\terr = unpopulate(val, \"Signatures\", &q.Signatures)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", q, err)\n\t\t}\n\t}\n\treturn nil\n}" ]
[ "0.7760415", "0.73632026", "0.73225766", "0.6934496", "0.66679347", "0.6645745", "0.6461531", "0.6358886", "0.63321537", "0.6291384", "0.62609005", "0.6259181", "0.610455", "0.60949135", "0.60774267", "0.6076495", "0.5969022", "0.58706313", "0.58498883", "0.58470803", "0.58002955", "0.57702935", "0.57283276", "0.5719314", "0.57098824", "0.56650454", "0.5651756", "0.5639091", "0.5603601", "0.55862564", "0.5572354", "0.5571582", "0.55679774", "0.5565186", "0.55576456", "0.55449396", "0.5528639", "0.5525835", "0.55228144", "0.55090004", "0.5500417", "0.54875666", "0.54642725", "0.544619", "0.5444744", "0.5444614", "0.543816", "0.543668", "0.5431027", "0.5423683", "0.5423561", "0.5416358", "0.54136", "0.5403627", "0.53996485", "0.5397623", "0.5396432", "0.5392966", "0.5390995", "0.5390704", "0.5388717", "0.5387252", "0.5382827", "0.5377383", "0.53747636", "0.53716683", "0.5364636", "0.53513557", "0.53494006", "0.5347363", "0.53401953", "0.5335396", "0.5333411", "0.5330515", "0.53234035", "0.53223586", "0.5321052", "0.5320222", "0.53199446", "0.5314347", "0.53126174", "0.53065073", "0.53064716", "0.5303826", "0.52988654", "0.5297465", "0.5288324", "0.5285809", "0.52845836", "0.5282403", "0.52795583", "0.52790445", "0.5279024", "0.5277583", "0.5263535", "0.52607757", "0.52604324", "0.5256097", "0.52547765", "0.52507526" ]
0.7819344
0
MarshalJSON is the custom marshaler for StorageInsight.
func (si StorageInsight) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if si.StorageInsightProperties != nil { objectMap["properties"] = si.StorageInsightProperties } if si.ETag != nil { objectMap["eTag"] = si.ETag } if si.ID != nil { objectMap["id"] = si.ID } if si.Name != nil { objectMap["name"] = si.Name } if si.Type != nil { objectMap["type"] = si.Type } if si.Tags != nil { objectMap["tags"] = si.Tags } return json.Marshal(objectMap) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (si StorageInsight) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif si.StorageInsightProperties != nil {\n\t\tobjectMap[\"properties\"] = si.StorageInsightProperties\n\t}\n\tif si.ETag != nil {\n\t\tobjectMap[\"eTag\"] = si.ETag\n\t}\n\tif si.Tags != nil {\n\t\tobjectMap[\"tags\"] = si.Tags\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (sip StorageInsightProperties) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif sip.Containers != nil {\n\t\tobjectMap[\"containers\"] = sip.Containers\n\t}\n\tif sip.Tables != nil {\n\t\tobjectMap[\"tables\"] = sip.Tables\n\t}\n\tif sip.StorageAccount != nil {\n\t\tobjectMap[\"storageAccount\"] = sip.StorageAccount\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (s StorageInformation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", s.ID)\n\treturn json.Marshal(objectMap)\n}", "func (u UserOwnedStorage) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"identityClientId\", u.IdentityClientID)\n\tpopulate(objectMap, \"resourceId\", u.ResourceID)\n\treturn json.Marshal(objectMap)\n}", "func (sc StorageContainer) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif sc.StorageContainerProperties != nil {\n\t\tobjectMap[\"properties\"] = sc.StorageContainerProperties\n\t}\n\tif sc.ID != nil {\n\t\tobjectMap[\"id\"] = sc.ID\n\t}\n\tif sc.Name != nil {\n\t\tobjectMap[\"name\"] = sc.Name\n\t}\n\tif sc.Type != nil {\n\t\tobjectMap[\"type\"] = sc.Type\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (s StorageProfile) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"dataDisks\", s.DataDisks)\n\tpopulate(objectMap, \"imageReference\", s.ImageReference)\n\tpopulate(objectMap, \"osDisk\", s.OSDisk)\n\treturn json.Marshal(objectMap)\n}", "func (s StorageConfiguration) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"transportFileShareConfiguration\", s.TransportFileShareConfiguration)\n\treturn json.Marshal(objectMap)\n}", "func (sai StorageAccountInformation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif sai.StorageAccountInformationProperties != nil {\n\t\tobjectMap[\"properties\"] = sai.StorageAccountInformationProperties\n\t}\n\tif sai.ID != nil {\n\t\tobjectMap[\"id\"] = sai.ID\n\t}\n\tif sai.Name != nil {\n\t\tobjectMap[\"name\"] = sai.Name\n\t}\n\tif sai.Type != nil {\n\t\tobjectMap[\"type\"] = sai.Type\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (s SyncStorageKeysInput) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", s.ID)\n\treturn json.Marshal(objectMap)\n}", "func (s StorageEndpointProperties) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"connectionString\", s.ConnectionString)\n\tpopulate(objectMap, \"containerName\", s.ContainerName)\n\tpopulate(objectMap, \"sasTtlAsIso8601\", s.SasTTLAsIso8601)\n\treturn json.Marshal(objectMap)\n}", "func (c CheckpointStorageConfig) MarshalJSON() ([]byte, error) {\n\treturn c, nil\n}", "func (s StorageAccount) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", s.ID)\n\tpopulate(objectMap, \"identity\", s.Identity)\n\tpopulate(objectMap, \"status\", s.Status)\n\tpopulate(objectMap, \"type\", s.Type)\n\treturn json.Marshal(objectMap)\n}", "func (r *StoredInfoType) marshal(c *Client) ([]byte, error) {\n\tm, err := expandStoredInfoType(c, r)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error marshalling StoredInfoType: %w\", err)\n\t}\n\tm = encodeStoredInfoTypeCreateRequest(m)\n\n\treturn json.Marshal(m)\n}", "func (p PacketCaptureStorageLocation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"filePath\", p.FilePath)\n\tpopulate(objectMap, \"storageId\", p.StorageID)\n\tpopulate(objectMap, \"storagePath\", p.StoragePath)\n\treturn json.Marshal(objectMap)\n}", "func (s SharedStorageResourceNames) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"sharedStorageAccountName\", s.SharedStorageAccountName)\n\tpopulate(objectMap, \"sharedStorageAccountPrivateEndPointName\", s.SharedStorageAccountPrivateEndPointName)\n\treturn json.Marshal(objectMap)\n}", "func Marshal(v Marshaler) ([]byte, error) {\n\tif isNilInterface(v) {\n\t\treturn nullBytes, nil\n\t}\n\n\tw := jwriter.Writer{}\n\tv.MarshalTinyJSON(&w)\n\treturn w.BuildBytes()\n}", "func Marshal(v Marshaler) ([]byte, error) {\n\tw := jwriter.Writer{}\n\tv.MarshalEasyJSON(&w)\n\treturn w.BuildBytes()\n}", "func (b *SampleFJSONBuilder) Marshal(orig *SampleF) ([]byte, error) {\n\tret, err := b.Convert(orig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn json.Marshal(ret)\n}", "func (s StorageAccountDetails) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tobjectMap[\"dataAccountType\"] = DataAccountTypeStorageAccount\n\tpopulate(objectMap, \"sharePassword\", s.SharePassword)\n\tpopulate(objectMap, \"storageAccountId\", s.StorageAccountID)\n\treturn json.Marshal(objectMap)\n}", "func Marshal(v interface{}) ([]byte, error) {\n\treturn json.Marshal(v)\n}", "func (arinpsm AddRemoveIncrementalNamedPartitionScalingMechanism) MarshalJSON() ([]byte, error) {\n\tarinpsm.Kind = KindAddRemoveIncrementalNamedPartition\n\tobjectMap := make(map[string]interface{})\n\tif arinpsm.MinPartitionCount != nil {\n\t\tobjectMap[\"MinPartitionCount\"] = arinpsm.MinPartitionCount\n\t}\n\tif arinpsm.MaxPartitionCount != nil {\n\t\tobjectMap[\"MaxPartitionCount\"] = arinpsm.MaxPartitionCount\n\t}\n\tif arinpsm.ScaleIncrement != nil {\n\t\tobjectMap[\"ScaleIncrement\"] = arinpsm.ScaleIncrement\n\t}\n\tif arinpsm.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = arinpsm.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (a ArmStreamingEndpointCurrentSKU) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"capacity\", a.Capacity)\n\tpopulate(objectMap, \"name\", a.Name)\n\treturn json.Marshal(objectMap)\n}", "func (s *StandardClaim) Marshal() ([]byte, error) {\n\tvar json = jsoniter.ConfigCompatibleWithStandardLibrary\n\treturn json.Marshal(*s)\n}", "func (p P2SVPNGateway) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"etag\", p.Etag)\n\tpopulate(objectMap, \"id\", p.ID)\n\tpopulate(objectMap, \"location\", p.Location)\n\tpopulate(objectMap, \"name\", p.Name)\n\tpopulate(objectMap, \"properties\", p.Properties)\n\tpopulate(objectMap, \"tags\", p.Tags)\n\tpopulate(objectMap, \"type\", p.Type)\n\treturn json.Marshal(objectMap)\n}", "func (tr TrackedResource)MarshalJSON() ([]byte, error){\n objectMap := make(map[string]interface{})\n if(tr.Tags != nil) {\n objectMap[\"tags\"] = tr.Tags\n }\n if(tr.Location != nil) {\n objectMap[\"location\"] = tr.Location\n }\n return json.Marshal(objectMap)\n }", "func (aslst AverageServiceLoadScalingTrigger) MarshalJSON() ([]byte, error) {\n\taslst.Kind = KindAverageServiceLoad\n\tobjectMap := make(map[string]interface{})\n\tif aslst.MetricName != nil {\n\t\tobjectMap[\"MetricName\"] = aslst.MetricName\n\t}\n\tif aslst.LowerLoadThreshold != nil {\n\t\tobjectMap[\"LowerLoadThreshold\"] = aslst.LowerLoadThreshold\n\t}\n\tif aslst.UpperLoadThreshold != nil {\n\t\tobjectMap[\"UpperLoadThreshold\"] = aslst.UpperLoadThreshold\n\t}\n\tif aslst.ScaleIntervalInSeconds != nil {\n\t\tobjectMap[\"ScaleIntervalInSeconds\"] = aslst.ScaleIntervalInSeconds\n\t}\n\tif aslst.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = aslst.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (s *Serializer) Marshal(v interface{}) ([]byte, error) {\n\treturn jsoniter.Marshal(v)\n}", "func (o Operation)MarshalJSON() ([]byte, error){\n objectMap := make(map[string]interface{})\n return json.Marshal(objectMap)\n }", "func (r *AzureMonitor) Marshal() ([]byte, error) {\n\treturn json.Marshal(r)\n}", "func (m *metadata) MarshalJSON() (result []byte, err error) {\n\tresult, err = json.Marshal(m.GetData())\n\treturn\n}", "func (f FirewallPolicyInsights) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"isEnabled\", f.IsEnabled)\n\tpopulate(objectMap, \"logAnalyticsResources\", f.LogAnalyticsResources)\n\tpopulate(objectMap, \"retentionDays\", f.RetentionDays)\n\treturn json.Marshal(objectMap)\n}", "func (m StorageCapacity) MarshalJSON() ([]byte, error) {\n\t_parts := make([][]byte, 0, 1)\n\n\tvar dataAO0 struct {\n\t\tAvailable int64 `json:\"Available,omitempty\"`\n\n\t\tFree int64 `json:\"Free,omitempty\"`\n\n\t\tTotal int64 `json:\"Total,omitempty\"`\n\n\t\tUsed int64 `json:\"Used,omitempty\"`\n\t}\n\n\tdataAO0.Available = m.Available\n\n\tdataAO0.Free = m.Free\n\n\tdataAO0.Total = m.Total\n\n\tdataAO0.Used = m.Used\n\n\tjsonDataAO0, errAO0 := swag.WriteJSON(dataAO0)\n\tif errAO0 != nil {\n\t\treturn nil, errAO0\n\t}\n\t_parts = append(_parts, jsonDataAO0)\n\n\treturn swag.ConcatJSON(_parts...), nil\n}", "func (abbsd AzureBlobBackupStorageDescription) MarshalJSON() ([]byte, error) {\n\tabbsd.StorageKind = StorageKindAzureBlobStore\n\tobjectMap := make(map[string]interface{})\n\tif abbsd.ConnectionString != nil {\n\t\tobjectMap[\"ConnectionString\"] = abbsd.ConnectionString\n\t}\n\tif abbsd.ContainerName != nil {\n\t\tobjectMap[\"ContainerName\"] = abbsd.ContainerName\n\t}\n\tif abbsd.FriendlyName != nil {\n\t\tobjectMap[\"FriendlyName\"] = abbsd.FriendlyName\n\t}\n\tif abbsd.StorageKind != \"\" {\n\t\tobjectMap[\"StorageKind\"] = abbsd.StorageKind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (v ProductShrinked) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncodeBackendInternalModels3(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v Volume) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"azureFile\", v.AzureFile)\n\tpopulate(objectMap, \"emptyDir\", &v.EmptyDir)\n\tpopulate(objectMap, \"gitRepo\", v.GitRepo)\n\tpopulate(objectMap, \"name\", v.Name)\n\tpopulate(objectMap, \"secret\", v.Secret)\n\treturn json.Marshal(objectMap)\n}", "func (pi PartitionInformation) MarshalJSON() ([]byte, error) {\n\tpi.ServicePartitionKind = ServicePartitionKindPartitionInformation\n\tobjectMap := make(map[string]interface{})\n\tif pi.ID != nil {\n\t\tobjectMap[\"Id\"] = pi.ID\n\t}\n\tif pi.ServicePartitionKind != \"\" {\n\t\tobjectMap[\"ServicePartitionKind\"] = pi.ServicePartitionKind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (v Ingredient) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonD2b7633eEncodeBackendInternalModels8(w, v)\n}", "func (pi *proxyItem) Marshal() ([]byte, error) {\n\tif pi == nil || pi.obj == nil {\n\t\treturn nil, nil\n\t}\n\n\tswitch m := pi.obj.(type) {\n\tcase encoding.BinaryMarshaler:\n\t\treturn m.MarshalBinary()\n\tcase storage.Marshaler:\n\t\treturn m.Marshal()\n\t}\n\treturn json.Marshal(pi.obj)\n}", "func (v VPNGateway) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"etag\", v.Etag)\n\tpopulate(objectMap, \"id\", v.ID)\n\tpopulate(objectMap, \"location\", v.Location)\n\tpopulate(objectMap, \"name\", v.Name)\n\tpopulate(objectMap, \"properties\", v.Properties)\n\tpopulate(objectMap, \"tags\", v.Tags)\n\tpopulate(objectMap, \"type\", v.Type)\n\treturn json.Marshal(objectMap)\n}", "func (aplst AveragePartitionLoadScalingTrigger) MarshalJSON() ([]byte, error) {\n\taplst.Kind = KindAveragePartitionLoad\n\tobjectMap := make(map[string]interface{})\n\tif aplst.MetricName != nil {\n\t\tobjectMap[\"MetricName\"] = aplst.MetricName\n\t}\n\tif aplst.LowerLoadThreshold != nil {\n\t\tobjectMap[\"LowerLoadThreshold\"] = aplst.LowerLoadThreshold\n\t}\n\tif aplst.UpperLoadThreshold != nil {\n\t\tobjectMap[\"UpperLoadThreshold\"] = aplst.UpperLoadThreshold\n\t}\n\tif aplst.ScaleIntervalInSeconds != nil {\n\t\tobjectMap[\"ScaleIntervalInSeconds\"] = aplst.ScaleIntervalInSeconds\n\t}\n\tif aplst.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = aplst.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (v Stash) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonD2b7633eEncodeDrhyuComIndexerModels(w, v)\n}", "func Marshal(v interface{}) ([]byte, error) {\n\tif ImplementsPreJSONMarshaler(v) {\n\t\terr := v.(PreJSONMarshaler).PreMarshalJSON()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn json.Marshal(v)\n}", "func (s *ServiceSecrets) MarshalJson() ([]byte, error) {\n\treturn json.Marshal(s)\n}", "func marshalJSON(i *big.Int) ([]byte, error) {\n\ttext, err := i.MarshalText()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn json.Marshal(string(text))\n}", "func (j *JsonlMarshaler) Marshal(v interface{}) ([]byte, error) {\n\treturn json.Marshal(v)\n}", "func (op *Operation) Marshal() ([]byte, error) {\n\treturn json.Marshal(op)\n}", "func (spi ServicePartitionInfo) MarshalJSON() ([]byte, error) {\n\tspi.ServiceKind = ServiceKindBasicServicePartitionInfoServiceKindServicePartitionInfo\n\tobjectMap := make(map[string]interface{})\n\tif spi.HealthState != \"\" {\n\t\tobjectMap[\"HealthState\"] = spi.HealthState\n\t}\n\tif spi.PartitionStatus != \"\" {\n\t\tobjectMap[\"PartitionStatus\"] = spi.PartitionStatus\n\t}\n\tobjectMap[\"PartitionInformation\"] = spi.PartitionInformation\n\tif spi.ServiceKind != \"\" {\n\t\tobjectMap[\"ServiceKind\"] = spi.ServiceKind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (m StorageArrayController) MarshalJSON() ([]byte, error) {\n\t_parts := make([][]byte, 0, 2)\n\n\taO0, err := swag.WriteJSON(m.EquipmentBase)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_parts = append(_parts, aO0)\n\n\tvar dataAO1 struct {\n\t\tName string `json:\"Name,omitempty\"`\n\n\t\tOperationalMode string `json:\"OperationalMode,omitempty\"`\n\n\t\tStatus string `json:\"Status,omitempty\"`\n\n\t\tStorageArray *StorageGenericArrayRef `json:\"StorageArray,omitempty\"`\n\n\t\tVersion string `json:\"Version,omitempty\"`\n\t}\n\n\tdataAO1.Name = m.Name\n\n\tdataAO1.OperationalMode = m.OperationalMode\n\n\tdataAO1.Status = m.Status\n\n\tdataAO1.StorageArray = m.StorageArray\n\n\tdataAO1.Version = m.Version\n\n\tjsonDataAO1, errAO1 := swag.WriteJSON(dataAO1)\n\tif errAO1 != nil {\n\t\treturn nil, errAO1\n\t}\n\t_parts = append(_parts, jsonDataAO1)\n\n\treturn swag.ConcatJSON(_parts...), nil\n}", "func (j *JSON) Marshal(target interface{}) (output interface{}, err error) {\n\treturn jsonEncoding.Marshal(target)\n}", "func (a ArmStreamingEndpointSKUInfo) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"capacity\", a.Capacity)\n\tpopulate(objectMap, \"resourceType\", a.ResourceType)\n\tpopulate(objectMap, \"sku\", a.SKU)\n\treturn json.Marshal(objectMap)\n}", "func Marshal(in interface{}) ([]byte, error) {\n\tres, err := jsoniter.ConfigCompatibleWithStandardLibrary.Marshal(in)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"marshaling error: %w\", err)\n\t}\n\treturn res, nil\n}", "func (u UpdateStorageAccountParameters) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"properties\", u.Properties)\n\treturn json.Marshal(objectMap)\n}", "func (i Identity)MarshalJSON() ([]byte, error){\n objectMap := make(map[string]interface{})\n if(i.Type != \"\") {\n objectMap[\"type\"] = i.Type\n }\n return json.Marshal(objectMap)\n }", "func (sc *Contract) Marshal() ([]byte, error) {\n\treturn json.Marshal(sc)\n}", "func (a AssetFileEncryptionMetadata) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"assetFileId\", a.AssetFileID)\n\tpopulate(objectMap, \"assetFileName\", a.AssetFileName)\n\tpopulate(objectMap, \"initializationVector\", a.InitializationVector)\n\treturn json.Marshal(objectMap)\n}", "func (sspi StatelessServicePartitionInfo) MarshalJSON() ([]byte, error) {\n\tsspi.ServiceKind = ServiceKindBasicServicePartitionInfoServiceKindStateless\n\tobjectMap := make(map[string]interface{})\n\tif sspi.InstanceCount != nil {\n\t\tobjectMap[\"InstanceCount\"] = sspi.InstanceCount\n\t}\n\tif sspi.HealthState != \"\" {\n\t\tobjectMap[\"HealthState\"] = sspi.HealthState\n\t}\n\tif sspi.PartitionStatus != \"\" {\n\t\tobjectMap[\"PartitionStatus\"] = sspi.PartitionStatus\n\t}\n\tobjectMap[\"PartitionInformation\"] = sspi.PartitionInformation\n\tif sspi.ServiceKind != \"\" {\n\t\tobjectMap[\"ServiceKind\"] = sspi.ServiceKind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (a ArmStreamingEndpointSKU) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"name\", a.Name)\n\treturn json.Marshal(objectMap)\n}", "func (ssor SingleSignOnResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif ssor.SystemData != nil {\n\t\tobjectMap[\"systemData\"] = ssor.SystemData\n\t}\n\tif ssor.Properties != nil {\n\t\tobjectMap[\"properties\"] = ssor.Properties\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (v Stash) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncodeDrhyuComIndexerModels(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (wi *WorkloadIdentity) MarshalJSON() ([]byte, error) {\n\tfmap := make(map[string]any, 1)\n\tfmap[config.AuthorizerTypeProperty] = WorkloadIdentityAuthorizerType\n\treturn json.Marshal(fmap)\n}", "func (spi SingletonPartitionInformation) MarshalJSON() ([]byte, error) {\n\tspi.ServicePartitionKind = ServicePartitionKindSingleton1\n\tobjectMap := make(map[string]interface{})\n\tif spi.ID != nil {\n\t\tobjectMap[\"Id\"] = spi.ID\n\t}\n\tif spi.ServicePartitionKind != \"\" {\n\t\tobjectMap[\"ServicePartitionKind\"] = spi.ServicePartitionKind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (bsd BackupStorageDescription) MarshalJSON() ([]byte, error) {\n\tbsd.StorageKind = StorageKindBackupStorageDescription\n\tobjectMap := make(map[string]interface{})\n\tif bsd.FriendlyName != nil {\n\t\tobjectMap[\"FriendlyName\"] = bsd.FriendlyName\n\t}\n\tif bsd.StorageKind != \"\" {\n\t\tobjectMap[\"StorageKind\"] = bsd.StorageKind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (j *TextMarshaler) Marshal(v interface{}) ([]byte, error) {\n\treturn json.Marshal(v)\n}", "func (d DdosCustomPolicy) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"etag\", d.Etag)\n\tpopulate(objectMap, \"id\", d.ID)\n\tpopulate(objectMap, \"location\", d.Location)\n\tpopulate(objectMap, \"name\", d.Name)\n\tpopulate(objectMap, \"properties\", d.Properties)\n\tpopulate(objectMap, \"tags\", d.Tags)\n\tpopulate(objectMap, \"type\", d.Type)\n\treturn json.Marshal(objectMap)\n}", "func (d DdosCustomPolicyPropertiesFormat) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"provisioningState\", d.ProvisioningState)\n\tpopulate(objectMap, \"resourceGuid\", d.ResourceGUID)\n\treturn json.Marshal(objectMap)\n}", "func (d DiskSKU) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"name\", d.Name)\n\treturn json.Marshal(objectMap)\n}", "func (ihsi IotHubSkuInfo) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif ihsi.Name != \"\" {\n\t\tobjectMap[\"name\"] = ihsi.Name\n\t}\n\tif ihsi.Capacity != nil {\n\t\tobjectMap[\"capacity\"] = ihsi.Capacity\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (jz JSONGzipEncoding) Marshal(v interface{}) ([]byte, error) {\n\tbuf, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// var bufSizeBefore = len(buf)\n\n\tbuf, err = GzipEncode(buf)\n\t// coloredoutput.Infof(\"gzip_json_compress_ratio=%d/%d=%.2f\",\n\t// bufSizeBefore, len(buf), float64(bufSizeBefore)/float64(len(buf)))\n\treturn buf, err\n}", "func (v PlantainerShadowMetadataSt) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson5bd79fa1EncodeMevericcoreMcplantainer9(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (dlsai DataLakeStoreAccountInformation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif dlsai.DataLakeStoreAccountInformationProperties != nil {\n\t\tobjectMap[\"properties\"] = dlsai.DataLakeStoreAccountInformationProperties\n\t}\n\tif dlsai.ID != nil {\n\t\tobjectMap[\"id\"] = dlsai.ID\n\t}\n\tif dlsai.Name != nil {\n\t\tobjectMap[\"name\"] = dlsai.Name\n\t}\n\tif dlsai.Type != nil {\n\t\tobjectMap[\"type\"] = dlsai.Type\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (o CustomDataExporter) JSON(ctx context.Context, w io.Writer, indent string) error {\n\tq := sqlutil.Select(\n\t\t\"cve_id\",\n\t\t\"cve_json\",\n\t).From(\n\t\t\"custom_data\",\n\t).Where(\n\t\to.condition(),\n\t)\n\n\tquery, args := q.String(), q.QueryArgs()\n\n\tif debug.V(1) {\n\t\tflog.Infof(\"running: %q / %#v\", query, args)\n\t}\n\n\trows, err := o.DB.QueryContext(ctx, query, args...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"cannot query vendor data\")\n\t}\n\n\tdefer rows.Close()\n\n\trecord := struct {\n\t\tCVE string\n\t\tJSON []byte\n\t}{}\n\n\tf := &cveFile{}\n\tfor rows.Next() {\n\t\tv := record\n\t\terr = rows.Scan(sqlutil.NewRecordType(&v).Values()...)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"cannot scan vendor data\")\n\t\t}\n\n\t\terr = f.Add(v.CVE, v.JSON)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif indent == \"\" {\n\t\treturn f.EncodeJSON(w)\n\t}\n\n\tconst prefix = \"\"\n\treturn f.EncodeIndentedJSON(w, prefix, indent)\n}", "func (i Interface) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"etag\", i.Etag)\n\tpopulate(objectMap, \"extendedLocation\", i.ExtendedLocation)\n\tpopulate(objectMap, \"id\", i.ID)\n\tpopulate(objectMap, \"location\", i.Location)\n\tpopulate(objectMap, \"name\", i.Name)\n\tpopulate(objectMap, \"properties\", i.Properties)\n\tpopulate(objectMap, \"tags\", i.Tags)\n\tpopulate(objectMap, \"type\", i.Type)\n\treturn json.Marshal(objectMap)\n}", "func (handler Handler) EncodeJSON(v interface{}) (b []byte, err error) {\n\n\t//if(w.Get(\"pretty\",\"false\")==\"true\"){\n\tb, err = json.MarshalIndent(v, \"\", \" \")\n\t//}else{\n\t//\tb, err = json.Marshal(v)\n\t//}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}", "func (fsbsd FileShareBackupStorageDescription) MarshalJSON() ([]byte, error) {\n\tfsbsd.StorageKind = StorageKindFileShare\n\tobjectMap := make(map[string]interface{})\n\tif fsbsd.Path != nil {\n\t\tobjectMap[\"Path\"] = fsbsd.Path\n\t}\n\tif fsbsd.PrimaryUserName != nil {\n\t\tobjectMap[\"PrimaryUserName\"] = fsbsd.PrimaryUserName\n\t}\n\tif fsbsd.PrimaryPassword != nil {\n\t\tobjectMap[\"PrimaryPassword\"] = fsbsd.PrimaryPassword\n\t}\n\tif fsbsd.SecondaryUserName != nil {\n\t\tobjectMap[\"SecondaryUserName\"] = fsbsd.SecondaryUserName\n\t}\n\tif fsbsd.SecondaryPassword != nil {\n\t\tobjectMap[\"SecondaryPassword\"] = fsbsd.SecondaryPassword\n\t}\n\tif fsbsd.FriendlyName != nil {\n\t\tobjectMap[\"FriendlyName\"] = fsbsd.FriendlyName\n\t}\n\tif fsbsd.StorageKind != \"\" {\n\t\tobjectMap[\"StorageKind\"] = fsbsd.StorageKind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (v PlantainerShadowMetadataSt) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson5bd79fa1EncodeMevericcoreMcplantainer9(w, v)\n}", "func (j *JsonMarshaler) Marshal(v interface{}) ([]byte, error) {\n\tswitch v.(type) {\n\tcase *distribute.GetResponse:\n\t\tvalue, err := protobuf.MarshalAny(v.(*distribute.GetResponse).Fields)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn json.Marshal(\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"fields\": value,\n\t\t\t},\n\t\t)\n\tcase *distribute.SearchResponse:\n\t\tvalue, err := protobuf.MarshalAny(v.(*distribute.SearchResponse).SearchResult)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn json.Marshal(\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"search_result\": value,\n\t\t\t},\n\t\t)\n\tdefault:\n\t\treturn json.Marshal(v)\n\t}\n}", "func (c *JSONCodec) Marshal(v interface{}) ([]byte, error) {\n\treturn json.Marshal(v)\n}", "func (v ShadowStateMetadataSt) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonB7ed31d3EncodeMevericcoreMccommon3(w, v)\n}", "func (v ProductShrinked) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonD2b7633eEncodeBackendInternalModels3(w, v)\n}", "func (m CloudAccountExtended) MarshalJSON() ([]byte, error) {\n\t_parts := make([][]byte, 0, 2)\n\n\taO0, err := swag.WriteJSON(m.CloudAccount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_parts = append(_parts, aO0)\n\n\tvar dataAO1 struct {\n\t\tBucket string `json:\"bucket,omitempty\"`\n\n\t\tID string `json:\"id,omitempty\"`\n\n\t\tMetadataBucket string `json:\"metadata_bucket,omitempty\"`\n\n\t\tPool string `json:\"pool,omitempty\"`\n\n\t\tState string `json:\"state,omitempty\"`\n\n\t\tStateDetails string `json:\"state_details,omitempty\"`\n\n\t\tType string `json:\"type,omitempty\"`\n\t}\n\n\tdataAO1.Bucket = m.Bucket\n\n\tdataAO1.ID = m.ID\n\n\tdataAO1.MetadataBucket = m.MetadataBucket\n\n\tdataAO1.Pool = m.Pool\n\n\tdataAO1.State = m.State\n\n\tdataAO1.StateDetails = m.StateDetails\n\n\tdataAO1.Type = m.Type\n\n\tjsonDataAO1, errAO1 := swag.WriteJSON(dataAO1)\n\tif errAO1 != nil {\n\t\treturn nil, errAO1\n\t}\n\t_parts = append(_parts, jsonDataAO1)\n\n\treturn swag.ConcatJSON(_parts...), nil\n}", "func (sbe ServiceBackupEntity) MarshalJSON() ([]byte, error) {\n\tsbe.EntityKind = EntityKindService1\n\tobjectMap := make(map[string]interface{})\n\tif sbe.ServiceName != nil {\n\t\tobjectMap[\"ServiceName\"] = sbe.ServiceName\n\t}\n\tif sbe.EntityKind != \"\" {\n\t\tobjectMap[\"EntityKind\"] = sbe.EntityKind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (si SkuInformation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif si.Sku != nil {\n\t\tobjectMap[\"sku\"] = si.Sku\n\t}\n\tif si.Enabled != nil {\n\t\tobjectMap[\"enabled\"] = si.Enabled\n\t}\n\tif si.SkuProperties != nil {\n\t\tobjectMap[\"properties\"] = si.SkuProperties\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (sg *StorageGroup) MarshalJSON() ([]byte, error) {\n\treturn (*storagegroup.StorageGroup)(sg).\n\t\tMarshalJSON()\n}", "func (s ServiceProvider) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"properties\", s.Properties)\n\treturn json.Marshal(objectMap)\n}", "func (d Dimension) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"eTag\", d.ETag)\n\tpopulate(objectMap, \"id\", d.ID)\n\tpopulate(objectMap, \"location\", d.Location)\n\tpopulate(objectMap, \"name\", d.Name)\n\tpopulate(objectMap, \"properties\", d.Properties)\n\tpopulate(objectMap, \"sku\", d.SKU)\n\tpopulate(objectMap, \"tags\", d.Tags)\n\tpopulate(objectMap, \"type\", d.Type)\n\treturn json.Marshal(objectMap)\n}", "func (q QuotaMetricInfo) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"currentValue\", q.CurrentValue)\n\tpopulate(objectMap, \"maxValue\", q.MaxValue)\n\tpopulate(objectMap, \"name\", q.Name)\n\treturn json.Marshal(objectMap)\n}", "func (ihqmi IotHubQuotaMetricInfo) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\treturn json.Marshal(objectMap)\n}", "func (ii *IndexInfo) Marshal(container *gabs.Container) (Informable, error) {\n\terr := json.Unmarshal(container.Bytes(), ii)\n\n\treturn ii, err\n}", "func (f *File) Marshal(v interface{}) error {\n\tw, err := ioutil.TempFile(filepath.Dir(f.prefix), filepath.Base(f.prefix)+\".write\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := json.NewEncoder(w).Encode(v); err != nil {\n\t\tw.Close()\n\t\treturn err\n\t}\n\tif err := w.Close(); err != nil {\n\t\treturn err\n\t}\n\tos.Remove(f.prefix + \".bak\")\n\tos.Link(f.prefix+\".json\", f.prefix+\".bak\")\n\treturn os.Rename(w.Name(), f.prefix+\".json\")\n}", "func (v BaseInstrumentInfo) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson25363b2dEncodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi128(w, v)\n}", "func (s StreamingEndpointSKUInfoListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"value\", s.Value)\n\treturn json.Marshal(objectMap)\n}", "func (f genHelperEncoder) EncJSONMarshal(iv jsonMarshaler) {\n\tbs, fnerr := iv.MarshalJSON()\n\tf.e.marshalAsis(bs, fnerr)\n}", "func (r *Anilist) Marshal() ([]byte, error) {\n\treturn json.Marshal(r)\n}", "func (pbe PartitionBackupEntity) MarshalJSON() ([]byte, error) {\n\tpbe.EntityKind = EntityKindPartition1\n\tobjectMap := make(map[string]interface{})\n\tif pbe.ServiceName != nil {\n\t\tobjectMap[\"ServiceName\"] = pbe.ServiceName\n\t}\n\tif pbe.PartitionID != nil {\n\t\tobjectMap[\"PartitionId\"] = pbe.PartitionID\n\t}\n\tif pbe.EntityKind != \"\" {\n\t\tobjectMap[\"EntityKind\"] = pbe.EntityKind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (m ServerConfigImport) MarshalJSON() ([]byte, error) {\n\t_parts := make([][]byte, 0, 2)\n\n\taO0, err := swag.WriteJSON(m.MoBaseMo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_parts = append(_parts, aO0)\n\n\tvar dataAO1 struct {\n\t\tDescription string `json:\"Description,omitempty\"`\n\n\t\tOrganization *IamAccountRef `json:\"Organization,omitempty\"`\n\n\t\tPolicyPrefix string `json:\"PolicyPrefix,omitempty\"`\n\n\t\tPolicyTypes []string `json:\"PolicyTypes\"`\n\n\t\tProfileName string `json:\"ProfileName,omitempty\"`\n\n\t\tServer *ComputeRackUnitRef `json:\"Server,omitempty\"`\n\n\t\tServerProfile *ServerProfileRef `json:\"ServerProfile,omitempty\"`\n\t}\n\n\tdataAO1.Description = m.Description\n\n\tdataAO1.Organization = m.Organization\n\n\tdataAO1.PolicyPrefix = m.PolicyPrefix\n\n\tdataAO1.PolicyTypes = m.PolicyTypes\n\n\tdataAO1.ProfileName = m.ProfileName\n\n\tdataAO1.Server = m.Server\n\n\tdataAO1.ServerProfile = m.ServerProfile\n\n\tjsonDataAO1, errAO1 := swag.WriteJSON(dataAO1)\n\tif errAO1 != nil {\n\t\treturn nil, errAO1\n\t}\n\t_parts = append(_parts, jsonDataAO1)\n\n\treturn swag.ConcatJSON(_parts...), nil\n}", "func (a Meta_HighWatermark) MarshalJSON() ([]byte, error) {\n\tvar err error\n\tobject := make(map[string]json.RawMessage)\n\n\tfor fieldName, field := range a.AdditionalProperties {\n\t\tobject[fieldName], err = json.Marshal(field)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, fmt.Sprintf(\"error marshaling '%s'\", fieldName))\n\t\t}\n\t}\n\treturn json.Marshal(object)\n}", "func (r RoutingStorageContainerProperties) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"batchFrequencyInSeconds\", r.BatchFrequencyInSeconds)\n\tpopulate(objectMap, \"connectionString\", r.ConnectionString)\n\tpopulate(objectMap, \"containerName\", r.ContainerName)\n\tpopulate(objectMap, \"encoding\", r.Encoding)\n\tpopulate(objectMap, \"fileNameFormat\", r.FileNameFormat)\n\tpopulate(objectMap, \"maxChunkSizeInBytes\", r.MaxChunkSizeInBytes)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"resourceGroup\", r.ResourceGroup)\n\tpopulate(objectMap, \"subscriptionId\", r.SubscriptionID)\n\treturn json.Marshal(objectMap)\n}", "func (aer AzureEntityResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\treturn json.Marshal(objectMap)\n}", "func (npi NamedPartitionInformation) MarshalJSON() ([]byte, error) {\n\tnpi.ServicePartitionKind = ServicePartitionKindNamed1\n\tobjectMap := make(map[string]interface{})\n\tif npi.Name != nil {\n\t\tobjectMap[\"Name\"] = npi.Name\n\t}\n\tif npi.ID != nil {\n\t\tobjectMap[\"Id\"] = npi.ID\n\t}\n\tif npi.ServicePartitionKind != \"\" {\n\t\tobjectMap[\"ServicePartitionKind\"] = npi.ServicePartitionKind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (usap UpdateStorageAccountParameters) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif usap.UpdateStorageAccountProperties != nil {\n\t\tobjectMap[\"properties\"] = usap.UpdateStorageAccountProperties\n\t}\n\treturn json.Marshal(objectMap)\n}" ]
[ "0.7438132", "0.6854708", "0.6651408", "0.6458709", "0.6369863", "0.62499017", "0.6118357", "0.6065291", "0.60439116", "0.5985736", "0.5985733", "0.5879575", "0.585946", "0.5832761", "0.57969975", "0.57697105", "0.57618684", "0.57595664", "0.5753302", "0.57477796", "0.57469225", "0.5727815", "0.5719385", "0.57067055", "0.57030636", "0.56917596", "0.56828743", "0.56603473", "0.5650743", "0.56421816", "0.56404024", "0.5635627", "0.56295323", "0.56271434", "0.56270134", "0.56164664", "0.5613196", "0.5610177", "0.5609187", "0.5605222", "0.5591597", "0.55754036", "0.5570756", "0.5567607", "0.55671513", "0.55613184", "0.55529946", "0.55518174", "0.5548502", "0.5536627", "0.5533397", "0.5529635", "0.5519411", "0.55184203", "0.55181384", "0.5507593", "0.5505581", "0.5504073", "0.55034286", "0.5497537", "0.549181", "0.54897", "0.5477763", "0.5474333", "0.5473006", "0.5468682", "0.54657185", "0.54641724", "0.54592735", "0.545901", "0.5452553", "0.5452388", "0.545001", "0.54451746", "0.54370725", "0.54349077", "0.54314816", "0.5423563", "0.542281", "0.5421515", "0.54193854", "0.54154736", "0.5415229", "0.541346", "0.5412641", "0.54020894", "0.5394932", "0.5394428", "0.5392674", "0.5392531", "0.5390613", "0.5388664", "0.5384387", "0.5383936", "0.5381217", "0.53795207", "0.53792113", "0.537776", "0.53773224", "0.53759205" ]
0.7515574
0
UnmarshalJSON is the custom unmarshaler for StorageInsight struct.
func (si *StorageInsight) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var storageInsightProperties StorageInsightProperties err = json.Unmarshal(*v, &storageInsightProperties) if err != nil { return err } si.StorageInsightProperties = &storageInsightProperties } case "eTag": if v != nil { var eTag string err = json.Unmarshal(*v, &eTag) if err != nil { return err } si.ETag = &eTag } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } si.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } si.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } si.Type = &typeVar } case "tags": if v != nil { var tags map[string]*string err = json.Unmarshal(*v, &tags) if err != nil { return err } si.Tags = tags } } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (si *StorageInsight) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"properties\":\n\t\t\tif v != nil {\n\t\t\t\tvar storageInsightProperties StorageInsightProperties\n\t\t\t\terr = json.Unmarshal(*v, &storageInsightProperties)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsi.StorageInsightProperties = &storageInsightProperties\n\t\t\t}\n\t\tcase \"eTag\":\n\t\t\tif v != nil {\n\t\t\t\tvar eTag string\n\t\t\t\terr = json.Unmarshal(*v, &eTag)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsi.ETag = &eTag\n\t\t\t}\n\t\tcase \"tags\":\n\t\t\tif v != nil {\n\t\t\t\tvar tags map[string]*string\n\t\t\t\terr = json.Unmarshal(*v, &tags)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsi.Tags = tags\n\t\t\t}\n\t\tcase \"id\":\n\t\t\tif v != nil {\n\t\t\t\tvar ID string\n\t\t\t\terr = json.Unmarshal(*v, &ID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsi.ID = &ID\n\t\t\t}\n\t\tcase \"name\":\n\t\t\tif v != nil {\n\t\t\t\tvar name string\n\t\t\t\terr = json.Unmarshal(*v, &name)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsi.Name = &name\n\t\t\t}\n\t\tcase \"type\":\n\t\t\tif v != nil {\n\t\t\t\tvar typeVar string\n\t\t\t\terr = json.Unmarshal(*v, &typeVar)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsi.Type = &typeVar\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (s *StorageInformation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &s.ID)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (u *UserOwnedStorage) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", u, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"identityClientId\":\n\t\t\terr = unpopulate(val, \"IdentityClientID\", &u.IdentityClientID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resourceId\":\n\t\t\terr = unpopulate(val, \"ResourceID\", &u.ResourceID)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", u, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (s *StorageAccount) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &s.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"identity\":\n\t\t\terr = unpopulate(val, \"Identity\", &s.Identity)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"status\":\n\t\t\terr = unpopulate(val, \"Status\", &s.Status)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"type\":\n\t\t\terr = unpopulate(val, \"Type\", &s.Type)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (sai *StorageAccountInformation) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"properties\":\n\t\t\tif v != nil {\n\t\t\t\tvar storageAccountInformationProperties StorageAccountInformationProperties\n\t\t\t\terr = json.Unmarshal(*v, &storageAccountInformationProperties)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsai.StorageAccountInformationProperties = &storageAccountInformationProperties\n\t\t\t}\n\t\tcase \"id\":\n\t\t\tif v != nil {\n\t\t\t\tvar ID string\n\t\t\t\terr = json.Unmarshal(*v, &ID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsai.ID = &ID\n\t\t\t}\n\t\tcase \"name\":\n\t\t\tif v != nil {\n\t\t\t\tvar name string\n\t\t\t\terr = json.Unmarshal(*v, &name)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsai.Name = &name\n\t\t\t}\n\t\tcase \"type\":\n\t\t\tif v != nil {\n\t\t\t\tvar typeVar string\n\t\t\t\terr = json.Unmarshal(*v, &typeVar)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsai.Type = &typeVar\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (s *StorageConfiguration) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"transportFileShareConfiguration\":\n\t\t\ts.TransportFileShareConfiguration, err = unmarshalFileShareConfigurationClassification(val)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (a *ArmStreamingEndpointCurrentSKU) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"capacity\":\n\t\t\terr = unpopulate(val, \"Capacity\", &a.Capacity)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &a.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (m *StorageCapacity) UnmarshalJSON(raw []byte) error {\n\t// AO0\n\tvar dataAO0 struct {\n\t\tAvailable int64 `json:\"Available,omitempty\"`\n\n\t\tFree int64 `json:\"Free,omitempty\"`\n\n\t\tTotal int64 `json:\"Total,omitempty\"`\n\n\t\tUsed int64 `json:\"Used,omitempty\"`\n\t}\n\tif err := swag.ReadJSON(raw, &dataAO0); err != nil {\n\t\treturn err\n\t}\n\n\tm.Available = dataAO0.Available\n\n\tm.Free = dataAO0.Free\n\n\tm.Total = dataAO0.Total\n\n\tm.Used = dataAO0.Used\n\n\treturn nil\n}", "func (f *FirewallPolicyInsights) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"isEnabled\":\n\t\t\terr = unpopulate(val, \"IsEnabled\", &f.IsEnabled)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"logAnalyticsResources\":\n\t\t\terr = unpopulate(val, \"LogAnalyticsResources\", &f.LogAnalyticsResources)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"retentionDays\":\n\t\t\terr = unpopulate(val, \"RetentionDays\", &f.RetentionDays)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (a *ArmStreamingEndpointSKUInfo) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"capacity\":\n\t\t\terr = unpopulate(val, \"Capacity\", &a.Capacity)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resourceType\":\n\t\t\terr = unpopulate(val, \"ResourceType\", &a.ResourceType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"sku\":\n\t\t\terr = unpopulate(val, \"SKU\", &a.SKU)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (a *AzureFirewallSKU) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &a.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"tier\":\n\t\t\terr = unpopulate(val, \"Tier\", &a.Tier)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (s *StorageAccountDetails) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"dataAccountType\":\n\t\t\terr = unpopulate(val, \"DataAccountType\", &s.DataAccountType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"sharePassword\":\n\t\t\terr = unpopulate(val, \"SharePassword\", &s.SharePassword)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"storageAccountId\":\n\t\t\terr = unpopulate(val, \"StorageAccountID\", &s.StorageAccountID)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (sc *StorageContainer) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"properties\":\n\t\t\tif v != nil {\n\t\t\t\tvar storageContainerProperties StorageContainerProperties\n\t\t\t\terr = json.Unmarshal(*v, &storageContainerProperties)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsc.StorageContainerProperties = &storageContainerProperties\n\t\t\t}\n\t\tcase \"id\":\n\t\t\tif v != nil {\n\t\t\t\tvar ID string\n\t\t\t\terr = json.Unmarshal(*v, &ID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsc.ID = &ID\n\t\t\t}\n\t\tcase \"name\":\n\t\t\tif v != nil {\n\t\t\t\tvar name string\n\t\t\t\terr = json.Unmarshal(*v, &name)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsc.Name = &name\n\t\t\t}\n\t\tcase \"type\":\n\t\t\tif v != nil {\n\t\t\t\tvar typeVar string\n\t\t\t\terr = json.Unmarshal(*v, &typeVar)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsc.Type = &typeVar\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (sg *StorageGroup) UnmarshalJSON(data []byte) error {\n\treturn (*storagegroup.StorageGroup)(sg).\n\t\tUnmarshalJSON(data)\n}", "func (s *SyncStorageKeysInput) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &s.ID)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (i *Interface) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", i, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"etag\":\n\t\t\terr = unpopulate(val, \"Etag\", &i.Etag)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"extendedLocation\":\n\t\t\terr = unpopulate(val, \"ExtendedLocation\", &i.ExtendedLocation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &i.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"location\":\n\t\t\terr = unpopulate(val, \"Location\", &i.Location)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &i.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &i.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"tags\":\n\t\t\terr = unpopulate(val, \"Tags\", &i.Tags)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"type\":\n\t\t\terr = unpopulate(val, \"Type\", &i.Type)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", i, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (m *StorageReplicationBlackout) UnmarshalJSON(raw []byte) error {\n\t// AO0\n\tvar dataAO0 struct {\n\t\tEnd string `json:\"End,omitempty\"`\n\n\t\tStart string `json:\"Start,omitempty\"`\n\t}\n\tif err := swag.ReadJSON(raw, &dataAO0); err != nil {\n\t\treturn err\n\t}\n\n\tm.End = dataAO0.End\n\n\tm.Start = dataAO0.Start\n\n\treturn nil\n}", "func (v *PlantainerShadowMetadataSt) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson5bd79fa1DecodeMevericcoreMcplantainer9(&r, v)\n\treturn r.Error()\n}", "func (this *Quantity) UnmarshalJSON(b []byte) error {\n\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}", "func (si *SkuInformation) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"sku\":\n\t\t\tif v != nil {\n\t\t\t\tvar sku Sku\n\t\t\t\terr = json.Unmarshal(*v, &sku)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsi.Sku = &sku\n\t\t\t}\n\t\tcase \"enabled\":\n\t\t\tif v != nil {\n\t\t\t\tvar enabled bool\n\t\t\t\terr = json.Unmarshal(*v, &enabled)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsi.Enabled = &enabled\n\t\t\t}\n\t\tcase \"properties\":\n\t\t\tif v != nil {\n\t\t\t\tvar skuProperties SkuProperties\n\t\t\t\terr = json.Unmarshal(*v, &skuProperties)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsi.SkuProperties = &skuProperties\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (bbt *BlockBlobTier) UnmarshalJSON(b []byte) error {\n\tvar s string\n\tif err := json.Unmarshal(b, &s); err != nil {\n\t\treturn err\n\t}\n\treturn bbt.Parse(s)\n}", "func (v *ShadowStateMetadataSt) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonB7ed31d3DecodeMevericcoreMccommon3(&r, v)\n\treturn r.Error()\n}", "func (pbt *PageBlobTier) UnmarshalJSON(b []byte) error {\n\tvar s string\n\tif err := json.Unmarshal(b, &s); err != nil {\n\t\treturn err\n\t}\n\treturn pbt.Parse(s)\n}", "func (s *StorageEncryptedAssetDecryptionData) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"assetFileEncryptionMetadata\":\n\t\t\terr = unpopulate(val, \"AssetFileEncryptionMetadata\", &s.AssetFileEncryptionMetadata)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"key\":\n\t\t\terr = runtime.DecodeByteArray(string(val), &s.Key, runtime.Base64StdFormat)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (rawIM *RawImageMetaJSON) UnmarshalJSON(data []byte) error {\n\t*rawIM = make(RawImageMetaJSON, len(data))\n\tcopy(*rawIM, data)\n\n\treturn nil\n}", "func (v *Stash) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeDrhyuComIndexerModels(&r, v)\n\treturn r.Error()\n}", "func (s *StorageEndpointProperties) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"connectionString\":\n\t\t\terr = unpopulate(val, \"ConnectionString\", &s.ConnectionString)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"containerName\":\n\t\t\terr = unpopulate(val, \"ContainerName\", &s.ContainerName)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"sasTtlAsIso8601\":\n\t\t\terr = unpopulate(val, \"SasTTLAsIso8601\", &s.SasTTLAsIso8601)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (s *StorageContainerProperties) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"lastModifiedTime\":\n\t\t\terr = unpopulateTimeRFC3339(val, \"LastModifiedTime\", &s.LastModifiedTime)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (v *BaseInstrumentAmount) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson25363b2dDecodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi129(&r, v)\n\treturn r.Error()\n}", "func (this *NamespacedName) UnmarshalJSON(b []byte) error {\n\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}", "func (a *AssetFileEncryptionMetadata) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"assetFileId\":\n\t\t\terr = unpopulate(val, \"AssetFileID\", &a.AssetFileID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"assetFileName\":\n\t\t\terr = unpopulate(val, \"AssetFileName\", &a.AssetFileName)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"initializationVector\":\n\t\t\terr = unpopulate(val, \"InitializationVector\", &a.InitializationVector)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (a *ArmStreamingEndpointSKU) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &a.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (v *SFMetric) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson51bca34dDecodeGithubComSkydiveProjectSkydiveSflow2(&r, v)\n\treturn r.Error()\n}", "func (s *SKUInfo) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"capacity\":\n\t\t\terr = unpopulate(val, \"Capacity\", &s.Capacity)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &s.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"tier\":\n\t\t\terr = unpopulate(val, \"Tier\", &s.Tier)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (s *Sampling) UnmarshalJSON(raw []byte) error {\n\tvar obj interface{}\n\tif err := json.Unmarshal(raw, &obj); err != nil {\n\t\treturn instrumentationError(\"failed to unmarshal Sampling value: %v\", err)\n\t}\n\tswitch v := obj.(type) {\n\tcase string:\n\t\tif err := s.Parse(v); err != nil {\n\t\t\treturn err\n\t\t}\n\tcase float64:\n\t\t*s = Sampling(v)\n\tdefault:\n\t\treturn instrumentationError(\"invalid Sampling value of type %T: %v\", obj, obj)\n\t}\n\treturn nil\n}", "func (v *MusicianFullInformation) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson62dc445bDecode20211NoskoolTeamInternalAppMusiciansModels1(&r, v)\n\treturn r.Error()\n}", "func (d *DiskSKU) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", d, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &d.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", d, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (s *SKU) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"capacity\":\n\t\t\terr = unpopulate(val, \"Capacity\", &s.Capacity)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"family\":\n\t\t\terr = unpopulate(val, \"Family\", &s.Family)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &s.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"size\":\n\t\t\terr = unpopulate(val, \"Size\", &s.Size)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"tier\":\n\t\t\terr = unpopulate(val, \"Tier\", &s.Tier)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (s *SKU) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"capacity\":\n\t\t\terr = unpopulate(val, \"Capacity\", &s.Capacity)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"family\":\n\t\t\terr = unpopulate(val, \"Family\", &s.Family)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &s.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"size\":\n\t\t\terr = unpopulate(val, \"Size\", &s.Size)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"tier\":\n\t\t\terr = unpopulate(val, \"Tier\", &s.Tier)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (t *BlockTest) UnmarshalJSON(in []byte) error {\n\treturn json.Unmarshal(in, &t.Json)\n}", "func (v *IfMetric) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson51bca34dDecodeGithubComSkydiveProjectSkydiveSflow4(&r, v)\n\treturn r.Error()\n}", "func (m *Meter) UnmarshalJSON(b []byte) error {\n\tvar j string\n\terr := json.Unmarshal(b, &j)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Note that if the string cannot be found then it will be set to the zero value, 'Created' in this case.\n\t*m = toMeterID[j]\n\treturn nil\n}", "func (l *LoadBalancerSKU) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", l, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &l.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"tier\":\n\t\t\terr = unpopulate(val, \"Tier\", &l.Tier)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", l, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (e *ExternalOptimizeForConfigV1) UnmarshalJSON(data []byte) error {\n\tunmarshal := func(v interface{}) error {\n\t\treturn json.Unmarshal(data, v)\n\t}\n\n\treturn e.unmarshalWith(unmarshal)\n}", "func (a *ArmStreamingEndpointCapacity) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"default\":\n\t\t\terr = unpopulate(val, \"Default\", &a.Default)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"maximum\":\n\t\t\terr = unpopulate(val, \"Maximum\", &a.Maximum)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"minimum\":\n\t\t\terr = unpopulate(val, \"Minimum\", &a.Minimum)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"scaleType\":\n\t\t\terr = unpopulate(val, \"ScaleType\", &a.ScaleType)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (region *Region) UnmarshalJSON(input []byte) error {\n\t// parse input value as string\n\tvar stringValue string\n\terr := json.Unmarshal(input, &stringValue)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// parse string as Region\n\t*region, err = ParseRegion(stringValue)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (v *VirtualNetworkGatewaySKU) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", v, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"capacity\":\n\t\t\terr = unpopulate(val, \"Capacity\", &v.Capacity)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &v.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"tier\":\n\t\t\terr = unpopulate(val, \"Tier\", &v.Tier)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", v, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (a *Availability) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"blobDuration\":\n\t\t\terr = unpopulate(val, \"BlobDuration\", &a.BlobDuration)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"retention\":\n\t\t\terr = unpopulate(val, \"Retention\", &a.Retention)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"timeGrain\":\n\t\t\terr = unpopulate(val, \"TimeGrain\", &a.TimeGrain)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (f *FailoverInput) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"failoverRegion\":\n\t\t\terr = unpopulate(val, \"FailoverRegion\", &f.FailoverRegion)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (v *SpotInstrument) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson25363b2dDecodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi48(&r, v)\n\treturn r.Error()\n}", "func (sspi *StatelessServicePartitionInfo) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"InstanceCount\":\n\t\t\tif v != nil {\n\t\t\t\tvar instanceCount int64\n\t\t\t\terr = json.Unmarshal(*v, &instanceCount)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsspi.InstanceCount = &instanceCount\n\t\t\t}\n\t\tcase \"HealthState\":\n\t\t\tif v != nil {\n\t\t\t\tvar healthState HealthState\n\t\t\t\terr = json.Unmarshal(*v, &healthState)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsspi.HealthState = healthState\n\t\t\t}\n\t\tcase \"PartitionStatus\":\n\t\t\tif v != nil {\n\t\t\t\tvar partitionStatus ServicePartitionStatus\n\t\t\t\terr = json.Unmarshal(*v, &partitionStatus)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsspi.PartitionStatus = partitionStatus\n\t\t\t}\n\t\tcase \"PartitionInformation\":\n\t\t\tif v != nil {\n\t\t\t\tpartitionInformation, err := unmarshalBasicPartitionInformation(*v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsspi.PartitionInformation = partitionInformation\n\t\t\t}\n\t\tcase \"ServiceKind\":\n\t\t\tif v != nil {\n\t\t\t\tvar serviceKind ServiceKindBasicServicePartitionInfo\n\t\t\t\terr = json.Unmarshal(*v, &serviceKind)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsspi.ServiceKind = serviceKind\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (jm *jsonMetric) UnmarshalJSON(data []byte) error {\n\tif jm == nil {\n\t\treturn errors.New(\"nil jsonMetric\")\n\t}\n\n\tif jm.Quantiles == nil {\n\t\tjm.Quantiles = make(QuantileMap)\n\t}\n\n\ttype Alias jsonMetric\n\taux := (*Alias)(jm)\n\tif err := json.Unmarshal(data, &aux); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (gbbsqd *GetBackupByStorageQueryDescription) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"StartDateTimeFilter\":\n\t\t\tif v != nil {\n\t\t\t\tvar startDateTimeFilter date.Time\n\t\t\t\terr = json.Unmarshal(*v, &startDateTimeFilter)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tgbbsqd.StartDateTimeFilter = &startDateTimeFilter\n\t\t\t}\n\t\tcase \"EndDateTimeFilter\":\n\t\t\tif v != nil {\n\t\t\t\tvar endDateTimeFilter date.Time\n\t\t\t\terr = json.Unmarshal(*v, &endDateTimeFilter)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tgbbsqd.EndDateTimeFilter = &endDateTimeFilter\n\t\t\t}\n\t\tcase \"Latest\":\n\t\t\tif v != nil {\n\t\t\t\tvar latest bool\n\t\t\t\terr = json.Unmarshal(*v, &latest)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tgbbsqd.Latest = &latest\n\t\t\t}\n\t\tcase \"Storage\":\n\t\t\tif v != nil {\n\t\t\t\tstorage, err := unmarshalBasicBackupStorageDescription(*v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tgbbsqd.Storage = storage\n\t\t\t}\n\t\tcase \"BackupEntity\":\n\t\t\tif v != nil {\n\t\t\t\tbackupEntity, err := unmarshalBasicBackupEntity(*v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tgbbsqd.BackupEntity = backupEntity\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (v *BaseInstrumentInfo) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson25363b2dDecodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi128(&r, v)\n\treturn r.Error()\n}", "func (spim *ServicePartitionInfoModel) UnmarshalJSON(body []byte) error {\n\tspi, err := unmarshalBasicServicePartitionInfo(body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tspim.Value = spi\n\n\treturn nil\n}", "func (o *LogsArchiveDestinationAzure) UnmarshalJSON(bytes []byte) (err error) {\n\tall := struct {\n\t\tContainer *string `json:\"container\"`\n\t\tIntegration *LogsArchiveIntegrationAzure `json:\"integration\"`\n\t\tPath *string `json:\"path,omitempty\"`\n\t\tRegion *string `json:\"region,omitempty\"`\n\t\tStorageAccount *string `json:\"storage_account\"`\n\t\tType *LogsArchiveDestinationAzureType `json:\"type\"`\n\t}{}\n\tif err = json.Unmarshal(bytes, &all); err != nil {\n\t\treturn json.Unmarshal(bytes, &o.UnparsedObject)\n\t}\n\tif all.Container == nil {\n\t\treturn fmt.Errorf(\"required field container missing\")\n\t}\n\tif all.Integration == nil {\n\t\treturn fmt.Errorf(\"required field integration missing\")\n\t}\n\tif all.StorageAccount == nil {\n\t\treturn fmt.Errorf(\"required field storage_account missing\")\n\t}\n\tif all.Type == nil {\n\t\treturn fmt.Errorf(\"required field type missing\")\n\t}\n\tadditionalProperties := make(map[string]interface{})\n\tif err = json.Unmarshal(bytes, &additionalProperties); err == nil {\n\t\tdatadog.DeleteKeys(additionalProperties, &[]string{\"container\", \"integration\", \"path\", \"region\", \"storage_account\", \"type\"})\n\t} else {\n\t\treturn err\n\t}\n\n\thasInvalidField := false\n\to.Container = *all.Container\n\tif all.Integration.UnparsedObject != nil && o.UnparsedObject == nil {\n\t\thasInvalidField = true\n\t}\n\to.Integration = *all.Integration\n\to.Path = all.Path\n\to.Region = all.Region\n\to.StorageAccount = *all.StorageAccount\n\tif !all.Type.IsValid() {\n\t\thasInvalidField = true\n\t} else {\n\t\to.Type = *all.Type\n\t}\n\n\tif len(additionalProperties) > 0 {\n\t\to.AdditionalProperties = additionalProperties\n\t}\n\n\tif hasInvalidField {\n\t\treturn json.Unmarshal(bytes, &o.UnparsedObject)\n\t}\n\n\treturn nil\n}", "func (s *SKU) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &s.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"tier\":\n\t\t\terr = unpopulate(val, \"Tier\", &s.Tier)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (i *ImageTemplateManagedImageDistributor) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn err\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"artifactTags\":\n\t\t\terr = unpopulate(val, &i.ArtifactTags)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"imageId\":\n\t\t\terr = unpopulate(val, &i.ImageID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"location\":\n\t\t\terr = unpopulate(val, &i.Location)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"runOutputName\":\n\t\t\terr = unpopulate(val, &i.RunOutputName)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"type\":\n\t\t\terr = unpopulate(val, &i.Type)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (v *LogsComputeType) UnmarshalJSON(src []byte) error {\n\tvar value string\n\terr := json.Unmarshal(src, &value)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*v = LogsComputeType(value)\n\treturn nil\n}", "func (f *FirewallPolicySKU) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"tier\":\n\t\t\terr = unpopulate(val, \"Tier\", &f.Tier)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (a *Meta_Loadavg) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]interface{})\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal interface{}\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, fmt.Sprintf(\"error unmarshaling field %s\", fieldName))\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}", "func (s *StreamingEndpointSKUInfoListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &s.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (s *SharedStorageResourceNames) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"sharedStorageAccountName\":\n\t\t\terr = unpopulate(val, \"SharedStorageAccountName\", &s.SharedStorageAccountName)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"sharedStorageAccountPrivateEndPointName\":\n\t\t\terr = unpopulate(val, \"SharedStorageAccountPrivateEndPointName\", &s.SharedStorageAccountPrivateEndPointName)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (m *MultipartState) UnmarshalJSON(bytes []byte) error {\n\ttmp := struct {\n\t\tBlkSize int `json:\"BlkSize\"`\n\t\tUploadID string `json:\"UploadId\"`\n\t}{}\n\terr := json.Unmarshal(bytes, &tmp)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.BlkSize = tmp.BlkSize\n\tm.uploadID = tmp.UploadID\n\treturn nil\n}", "func (j *CreateNhAssetOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *SpotInstrumentsListWrapper) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson25363b2dDecodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi45(&r, v)\n\treturn r.Error()\n}", "func (us *UserStorage) ImportJSON(data []byte) error {\n\treturn nil\n}", "func (u *Usage) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", u, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"currentValue\":\n\t\t\terr = unpopulate(val, \"CurrentValue\", &u.CurrentValue)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"limit\":\n\t\t\terr = unpopulate(val, \"Limit\", &u.Limit)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &u.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"nextResetTime\":\n\t\t\terr = unpopulate(val, \"NextResetTime\", &u.NextResetTime)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"quotaPeriod\":\n\t\t\terr = unpopulate(val, \"QuotaPeriod\", &u.QuotaPeriod)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"status\":\n\t\t\terr = unpopulate(val, \"Status\", &u.Status)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"unit\":\n\t\t\terr = unpopulate(val, \"Unit\", &u.Unit)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", u, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (v *FuturesInstrumentOpenInterestResult) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson25363b2dDecodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi76(&r, v)\n\treturn r.Error()\n}", "func (v *PremiumInterval) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\tdecodePremium(&r, v)\n\treturn r.Error()\n}", "func (v *ProductShrinked) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeBackendInternalModels3(&r, v)\n\treturn r.Error()\n}", "func (sspi *StatefulServicePartitionInfo) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"TargetReplicaSetSize\":\n\t\t\tif v != nil {\n\t\t\t\tvar targetReplicaSetSize int64\n\t\t\t\terr = json.Unmarshal(*v, &targetReplicaSetSize)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsspi.TargetReplicaSetSize = &targetReplicaSetSize\n\t\t\t}\n\t\tcase \"MinReplicaSetSize\":\n\t\t\tif v != nil {\n\t\t\t\tvar minReplicaSetSize int64\n\t\t\t\terr = json.Unmarshal(*v, &minReplicaSetSize)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsspi.MinReplicaSetSize = &minReplicaSetSize\n\t\t\t}\n\t\tcase \"LastQuorumLossDuration\":\n\t\t\tif v != nil {\n\t\t\t\tvar lastQuorumLossDuration string\n\t\t\t\terr = json.Unmarshal(*v, &lastQuorumLossDuration)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsspi.LastQuorumLossDuration = &lastQuorumLossDuration\n\t\t\t}\n\t\tcase \"CurrentConfigurationEpoch\":\n\t\t\tif v != nil {\n\t\t\t\tvar currentConfigurationEpoch Epoch\n\t\t\t\terr = json.Unmarshal(*v, &currentConfigurationEpoch)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsspi.CurrentConfigurationEpoch = &currentConfigurationEpoch\n\t\t\t}\n\t\tcase \"HealthState\":\n\t\t\tif v != nil {\n\t\t\t\tvar healthState HealthState\n\t\t\t\terr = json.Unmarshal(*v, &healthState)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsspi.HealthState = healthState\n\t\t\t}\n\t\tcase \"PartitionStatus\":\n\t\t\tif v != nil {\n\t\t\t\tvar partitionStatus ServicePartitionStatus\n\t\t\t\terr = json.Unmarshal(*v, &partitionStatus)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsspi.PartitionStatus = partitionStatus\n\t\t\t}\n\t\tcase \"PartitionInformation\":\n\t\t\tif v != nil {\n\t\t\t\tpartitionInformation, err := unmarshalBasicPartitionInformation(*v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsspi.PartitionInformation = partitionInformation\n\t\t\t}\n\t\tcase \"ServiceKind\":\n\t\t\tif v != nil {\n\t\t\t\tvar serviceKind ServiceKindBasicServicePartitionInfo\n\t\t\t\terr = json.Unmarshal(*v, &serviceKind)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsspi.ServiceKind = serviceKind\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (r *ResourceSKUListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", r, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &r.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &r.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", r, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (p *PacketCaptureStorageLocation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", p, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"filePath\":\n\t\t\terr = unpopulate(val, \"FilePath\", &p.FilePath)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"storageId\":\n\t\t\terr = unpopulate(val, \"StorageID\", &p.StorageID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"storagePath\":\n\t\t\terr = unpopulate(val, \"StoragePath\", &p.StoragePath)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", p, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (v *EthMetric) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson51bca34dDecodeGithubComSkydiveProjectSkydiveSflow5(&r, v)\n\treturn r.Error()\n}", "func (i *InfrastructureConfiguration) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", i, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"appResourceGroup\":\n\t\t\terr = unpopulate(val, \"AppResourceGroup\", &i.AppResourceGroup)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"deploymentType\":\n\t\t\terr = unpopulate(val, \"DeploymentType\", &i.DeploymentType)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", i, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (v *PlantainerShadowSt) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson5bd79fa1DecodeMevericcoreMcplantainer8(&r, v)\n\treturn r.Error()\n}", "func (x *CustomIndicatorField) UnmarshalJSON(b []byte) error {\n\tnum, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*x = CustomIndicatorField(num)\n\treturn nil\n}", "func (a *AccountSKUListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &a.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (c *CapabilityInformation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", c, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"accountCount\":\n\t\t\terr = unpopulate(val, \"AccountCount\", &c.AccountCount)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"maxAccountCount\":\n\t\t\terr = unpopulate(val, \"MaxAccountCount\", &c.MaxAccountCount)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"migrationState\":\n\t\t\terr = unpopulate(val, \"MigrationState\", &c.MigrationState)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"state\":\n\t\t\terr = unpopulate(val, \"State\", &c.State)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"subscriptionId\":\n\t\t\terr = unpopulate(val, \"SubscriptionID\", &c.SubscriptionID)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", c, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (i *ImageTemplateManagedImageSource) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn err\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"imageId\":\n\t\t\terr = unpopulate(val, &i.ImageID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"type\":\n\t\t\terr = unpopulate(val, &i.Type)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (x *DatabaseImageDataArchive_ImageType) UnmarshalJSON(b []byte) error {\n\tnum, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*x = DatabaseImageDataArchive_ImageType(num)\n\treturn nil\n}", "func (this *Quota) UnmarshalJSON(b []byte) error {\n\treturn QuotaUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}", "func (s *SKU) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"family\":\n\t\t\terr = unpopulate(val, \"Family\", &s.Family)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &s.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"size\":\n\t\t\terr = unpopulate(val, \"Size\", &s.Size)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"tier\":\n\t\t\terr = unpopulate(val, \"Tier\", &s.Tier)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (s *StreamingEntityScaleUnit) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"scaleUnit\":\n\t\t\terr = unpopulate(val, \"ScaleUnit\", &s.ScaleUnit)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (m *StorageArrayController) UnmarshalJSON(raw []byte) error {\n\t// AO0\n\tvar aO0 EquipmentBase\n\tif err := swag.ReadJSON(raw, &aO0); err != nil {\n\t\treturn err\n\t}\n\tm.EquipmentBase = aO0\n\n\t// AO1\n\tvar dataAO1 struct {\n\t\tName string `json:\"Name,omitempty\"`\n\n\t\tOperationalMode string `json:\"OperationalMode,omitempty\"`\n\n\t\tStatus string `json:\"Status,omitempty\"`\n\n\t\tStorageArray *StorageGenericArrayRef `json:\"StorageArray,omitempty\"`\n\n\t\tVersion string `json:\"Version,omitempty\"`\n\t}\n\tif err := swag.ReadJSON(raw, &dataAO1); err != nil {\n\t\treturn err\n\t}\n\n\tm.Name = dataAO1.Name\n\n\tm.OperationalMode = dataAO1.OperationalMode\n\n\tm.Status = dataAO1.Status\n\n\tm.StorageArray = dataAO1.StorageArray\n\n\tm.Version = dataAO1.Version\n\n\treturn nil\n}", "func (i *Int64Slice) UnmarshalJSON(data []byte) error {\n\ti.Present = true\n\n\tif bytes.Equal(data, null) {\n\t\treturn nil\n\t}\n\n\tif err := json.Unmarshal(data, &i.Value); err != nil {\n\t\treturn err\n\t}\n\n\ti.Valid = true\n\treturn nil\n}", "func (u *Usage) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", u, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"currentValue\":\n\t\t\terr = unpopulate(val, \"CurrentValue\", &u.CurrentValue)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &u.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"limit\":\n\t\t\terr = unpopulate(val, \"Limit\", &u.Limit)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &u.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"unit\":\n\t\t\terr = unpopulate(val, \"Unit\", &u.Unit)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", u, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (u *Usage) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", u, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"currentValue\":\n\t\t\terr = unpopulate(val, \"CurrentValue\", &u.CurrentValue)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &u.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"limit\":\n\t\t\terr = unpopulate(val, \"Limit\", &u.Limit)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &u.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"unit\":\n\t\t\terr = unpopulate(val, \"Unit\", &u.Unit)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", u, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (r *ResourceSKU) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", r, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"kind\":\n\t\t\terr = unpopulate(val, \"Kind\", &r.Kind)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"locations\":\n\t\t\terr = unpopulate(val, \"Locations\", &r.Locations)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &r.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resourceType\":\n\t\t\terr = unpopulate(val, \"ResourceType\", &r.ResourceType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"restrictions\":\n\t\t\terr = unpopulate(val, \"Restrictions\", &r.Restrictions)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"tier\":\n\t\t\terr = unpopulate(val, \"Tier\", &r.Tier)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", r, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (this *Probe) UnmarshalJSON(b []byte) error {\n\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}", "func (s *SKUCapability) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &s.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &s.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (c *CheckpointStorageConfig) UnmarshalJSON(data []byte) error {\n\t// Roundtrip through json.Unmarshal so that fields are updated elementwise,\n\t// which would be the behavior if CheckpointStorageConfig were a pure\n\t// struct. If we simply set *c = data, we would not preserve fields not\n\t// mentioned by data.\n\n\tm, err := c.ToModel()\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif err := json.Unmarshal(data, &m); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\treturn c.FromModel(m)\n}", "func (u *Unstructured) UnmarshalJSON(b []byte) error {\n\t_, _, err := UnstructuredJSONScheme.Decode(b, nil, u)\n\treturn err\n}", "func (v *VirtualApplianceSKU) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", v, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"etag\":\n\t\t\terr = unpopulate(val, \"Etag\", &v.Etag)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &v.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"location\":\n\t\t\terr = unpopulate(val, \"Location\", &v.Location)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &v.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &v.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"tags\":\n\t\t\terr = unpopulate(val, \"Tags\", &v.Tags)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"type\":\n\t\t\terr = unpopulate(val, \"Type\", &v.Type)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", v, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (m *ServerConfigImport) UnmarshalJSON(raw []byte) error {\n\t// AO0\n\tvar aO0 MoBaseMo\n\tif err := swag.ReadJSON(raw, &aO0); err != nil {\n\t\treturn err\n\t}\n\tm.MoBaseMo = aO0\n\n\t// AO1\n\tvar dataAO1 struct {\n\t\tDescription string `json:\"Description,omitempty\"`\n\n\t\tOrganization *IamAccountRef `json:\"Organization,omitempty\"`\n\n\t\tPolicyPrefix string `json:\"PolicyPrefix,omitempty\"`\n\n\t\tPolicyTypes []string `json:\"PolicyTypes\"`\n\n\t\tProfileName string `json:\"ProfileName,omitempty\"`\n\n\t\tServer *ComputeRackUnitRef `json:\"Server,omitempty\"`\n\n\t\tServerProfile *ServerProfileRef `json:\"ServerProfile,omitempty\"`\n\t}\n\tif err := swag.ReadJSON(raw, &dataAO1); err != nil {\n\t\treturn err\n\t}\n\n\tm.Description = dataAO1.Description\n\n\tm.Organization = dataAO1.Organization\n\n\tm.PolicyPrefix = dataAO1.PolicyPrefix\n\n\tm.PolicyTypes = dataAO1.PolicyTypes\n\n\tm.ProfileName = dataAO1.ProfileName\n\n\tm.Server = dataAO1.Server\n\n\tm.ServerProfile = dataAO1.ServerProfile\n\n\treturn nil\n}", "func (m *SDKScriptCollectorAttribute) UnmarshalJSON(raw []byte) error {\n\tvar data struct {\n\n\t\t// groovy script\n\t\t// Required: true\n\t\tGroovyScript *string `json:\"groovyScript\"`\n\n\t\t// sdk name\n\t\t// Required: true\n\t\tSdkName *string `json:\"sdkName\"`\n\n\t\t// sdk version\n\t\t// Required: true\n\t\tSdkVersion *string `json:\"sdkVersion\"`\n\t}\n\tbuf := bytes.NewBuffer(raw)\n\tdec := json.NewDecoder(buf)\n\tdec.UseNumber()\n\n\tif err := dec.Decode(&data); err != nil {\n\t\treturn err\n\t}\n\n\tvar base struct {\n\t\t/* Just the base type fields. Used for unmashalling polymorphic types.*/\n\n\t\tName string `json:\"name\"`\n\t}\n\tbuf = bytes.NewBuffer(raw)\n\tdec = json.NewDecoder(buf)\n\tdec.UseNumber()\n\n\tif err := dec.Decode(&base); err != nil {\n\t\treturn err\n\t}\n\n\tvar result SDKScriptCollectorAttribute\n\n\tif base.Name != result.Name() {\n\t\t/* Not the type we're looking for. */\n\t\treturn errors.New(422, \"invalid name value: %q\", base.Name)\n\t}\n\n\tresult.GroovyScript = data.GroovyScript\n\n\tresult.SdkName = data.SdkName\n\n\tresult.SdkVersion = data.SdkVersion\n\n\t*m = result\n\n\treturn nil\n}", "func unmarshalJSON(j extv1.JSON, output *any) error {\n\tif len(j.Raw) == 0 {\n\t\treturn nil\n\t}\n\treturn json.Unmarshal(j.Raw, output)\n}", "func (m *InventoryDeviceInfo) UnmarshalJSON(raw []byte) error {\n\t// AO0\n\tvar aO0 MoBaseMo\n\tif err := swag.ReadJSON(raw, &aO0); err != nil {\n\t\treturn err\n\t}\n\tm.MoBaseMo = aO0\n\n\t// AO1\n\tvar dataAO1 struct {\n\t\tConfigState string `json:\"ConfigState,omitempty\"`\n\n\t\tControlAction string `json:\"ControlAction,omitempty\"`\n\n\t\tErrorState string `json:\"ErrorState,omitempty\"`\n\n\t\tJobInfo []*InventoryJobInfo `json:\"JobInfo\"`\n\n\t\tOperState string `json:\"OperState,omitempty\"`\n\n\t\tProfileMoID string `json:\"ProfileMoId,omitempty\"`\n\n\t\tRegisteredDevice *AssetDeviceRegistrationRef `json:\"RegisteredDevice,omitempty\"`\n\t}\n\tif err := swag.ReadJSON(raw, &dataAO1); err != nil {\n\t\treturn err\n\t}\n\n\tm.ConfigState = dataAO1.ConfigState\n\n\tm.ControlAction = dataAO1.ControlAction\n\n\tm.ErrorState = dataAO1.ErrorState\n\n\tm.JobInfo = dataAO1.JobInfo\n\n\tm.OperState = dataAO1.OperState\n\n\tm.ProfileMoID = dataAO1.ProfileMoID\n\n\tm.RegisteredDevice = dataAO1.RegisteredDevice\n\n\treturn nil\n}", "func (x *StockField) UnmarshalJSON(b []byte) error {\n\tnum, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*x = StockField(num)\n\treturn nil\n}" ]
[ "0.77663517", "0.64480436", "0.61780083", "0.58906114", "0.58859926", "0.5874567", "0.58450717", "0.58406675", "0.58077765", "0.57999974", "0.57179284", "0.5699935", "0.5683557", "0.5669602", "0.56584376", "0.5655203", "0.56504077", "0.5629041", "0.5624216", "0.56191367", "0.56158507", "0.5610081", "0.5602211", "0.55619466", "0.55553716", "0.5551498", "0.5542753", "0.553702", "0.5535211", "0.5526098", "0.5520834", "0.55204505", "0.55167115", "0.55035096", "0.54993695", "0.5499249", "0.5495439", "0.5487262", "0.5487262", "0.5487206", "0.5478987", "0.54692435", "0.5466395", "0.5464345", "0.5442579", "0.5440723", "0.54348063", "0.5425978", "0.54238236", "0.5401403", "0.5393863", "0.5389757", "0.5385223", "0.5384305", "0.538328", "0.53770804", "0.5374643", "0.5370579", "0.53605527", "0.53515077", "0.53487766", "0.53484875", "0.5343522", "0.53408486", "0.53408", "0.53395915", "0.5337685", "0.5328806", "0.53260857", "0.5323898", "0.5321971", "0.5321787", "0.5318521", "0.5316914", "0.5316863", "0.53078127", "0.5303119", "0.5302999", "0.5299594", "0.5297377", "0.529706", "0.529454", "0.5293531", "0.5290863", "0.5285921", "0.528493", "0.52826285", "0.52780294", "0.52780294", "0.5277784", "0.52773046", "0.52666384", "0.525901", "0.52558523", "0.5255581", "0.525166", "0.5250449", "0.52493143", "0.52466846", "0.5244566" ]
0.7757473
1
NextWithContext advances to the next value. If there was an error making the request the iterator does not advance and the error is returned.
func (iter *StorageInsightListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/StorageInsightListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (iter * ConfigurationListResultIterator) NextWithContext(ctx context.Context) (err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/ConfigurationListResultIterator.NextWithContext\")\n defer func() {\n sc := -1\n if iter.Response().Response.Response != nil {\n sc = iter.Response().Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n iter.i++\n if iter.i < len(iter. page.Values()) {\n return nil\n }\n err = iter.page.NextWithContext(ctx)\n if err != nil {\n iter. i--\n return err\n }\n iter.i = 0\n return nil\n }", "func (iter * ServerListResultIterator) NextWithContext(ctx context.Context) (err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/ServerListResultIterator.NextWithContext\")\n defer func() {\n sc := -1\n if iter.Response().Response.Response != nil {\n sc = iter.Response().Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n iter.i++\n if iter.i < len(iter. page.Values()) {\n return nil\n }\n err = iter.page.NextWithContext(ctx)\n if err != nil {\n iter. i--\n return err\n }\n iter.i = 0\n return nil\n }", "func (iter *ProductResultValueIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ProductResultValueIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter * DatabaseListResultIterator) NextWithContext(ctx context.Context) (err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/DatabaseListResultIterator.NextWithContext\")\n defer func() {\n sc := -1\n if iter.Response().Response.Response != nil {\n sc = iter.Response().Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n iter.i++\n if iter.i < len(iter. page.Values()) {\n return nil\n }\n err = iter.page.NextWithContext(ctx)\n if err != nil {\n iter. i--\n return err\n }\n iter.i = 0\n return nil\n }", "func (iter *PermissionGetResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/PermissionGetResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *ListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *ListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (page *ProductResultValuePage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ProductResultValuePage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.prv)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.prv = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (iter * MaintenanceWindowListResultIterator) NextWithContext(ctx context.Context) (err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/MaintenanceWindowListResultIterator.NextWithContext\")\n defer func() {\n sc := -1\n if iter.Response().Response.Response != nil {\n sc = iter.Response().Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n iter.i++\n if iter.i < len(iter. page.Values()) {\n return nil\n }\n err = iter.page.NextWithContext(ctx)\n if err != nil {\n iter. i--\n return err\n }\n iter.i = 0\n return nil\n }", "func (iter *OperationsIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/OperationsIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *ProductResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ProductResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *ResourceSkusResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ResourceSkusResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *MonitoredResourceListResponseIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/MonitoredResourceListResponseIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *ExemptionListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ExemptionListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *OdataProductResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/OdataProductResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (page *PermissionGetResultPage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/PermissionGetResultPage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.pgr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.pgr = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (iter * FirewallRuleListResultIterator) NextWithContext(ctx context.Context) (err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/FirewallRuleListResultIterator.NextWithContext\")\n defer func() {\n sc := -1\n if iter.Response().Response.Response != nil {\n sc = iter.Response().Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n iter.i++\n if iter.i < len(iter. page.Values()) {\n return nil\n }\n err = iter.page.NextWithContext(ctx)\n if err != nil {\n iter. i--\n return err\n }\n iter.i = 0\n return nil\n }", "func (page * ConfigurationListResultPage) NextWithContext(ctx context.Context) (err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/ConfigurationListResultPage.NextWithContext\")\n defer func() {\n sc := -1\n if page.Response().Response.Response != nil {\n sc = page.Response().Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n for {\n next, err := page.fn(ctx, page.clr)\n if err != nil {\n return err\n }\n page.clr = next\n if !next.hasNextLink() || !next.IsEmpty() {\n break\n }\n }\n return nil\n }", "func (iter *MonitorResourceListResponseIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/MonitorResourceListResponseIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *ListIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ListIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *OperationListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/OperationListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *OperationListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/OperationListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *OperationListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/OperationListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *OperationListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/OperationListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *OperationListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/OperationListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *OperationListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/OperationListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *OperationListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/OperationListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *OperationListIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/OperationListIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *OperationListIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/OperationListIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *OperationListIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/OperationListIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *AvailableSkusResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/AvailableSkusResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *ServiceProviderListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ServiceProviderListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (page *MonitoredResourceListResponsePage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/MonitoredResourceListResponsePage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.mrlr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.mrlr = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (iter *DataSourceListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/DataSourceListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (page *ExemptionListResultPage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ExemptionListResultPage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.elr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.elr = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (page * MaintenanceWindowListResultPage) NextWithContext(ctx context.Context) (err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/MaintenanceWindowListResultPage.NextWithContext\")\n defer func() {\n sc := -1\n if page.Response().Response.Response != nil {\n sc = page.Response().Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n for {\n next, err := page.fn(ctx, page.mwlr)\n if err != nil {\n return err\n }\n page.mwlr = next\n if !next.hasNextLink() || !next.IsEmpty() {\n break\n }\n }\n return nil\n }", "func (iter *ListSasTokensResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ListSasTokensResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (page * ServerListResultPage) NextWithContext(ctx context.Context) (err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/ServerListResultPage.NextWithContext\")\n defer func() {\n sc := -1\n if page.Response().Response.Response != nil {\n sc = page.Response().Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n for {\n next, err := page.fn(ctx, page.slr)\n if err != nil {\n return err\n }\n page.slr = next\n if !next.hasNextLink() || !next.IsEmpty() {\n break\n }\n }\n return nil\n }", "func (iter *ClassicAdministratorListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ClassicAdministratorListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (page * DatabaseListResultPage) NextWithContext(ctx context.Context) (err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/DatabaseListResultPage.NextWithContext\")\n defer func() {\n sc := -1\n if page.Response().Response.Response != nil {\n sc = page.Response().Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n for {\n next, err := page.fn(ctx, page.dlr)\n if err != nil {\n return err\n }\n page.dlr = next\n if !next.hasNextLink() || !next.IsEmpty() {\n break\n }\n }\n return nil\n }", "func (iter *TaskListIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/TaskListIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *ServiceListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ServiceListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *ComputePolicyListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ComputePolicyListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *JobResponseListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/JobResponseListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *DataLakeAnalyticsAccountListDataLakeStoreResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/DataLakeAnalyticsAccountListDataLakeStoreResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *ClusterListIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ClusterListIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (page *ListResultPage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ListResultPage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.lr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.lr = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (page *ClassicAdministratorListResultPage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ClassicAdministratorListResultPage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.calr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.calr = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (iter *SQLServerListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/SQLServerListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (page *MonitorResourceListResponsePage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/MonitorResourceListResponsePage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.mrlr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.mrlr = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (iter *SingleSignOnResourceListResponseIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/SingleSignOnResourceListResponseIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *VMResourcesListResponseIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/VMResourcesListResponseIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *ClusterListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ClusterListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *ConsumerGroupListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ConsumerGroupListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *MachineListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/MachineListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *ServiceOperationListIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ServiceOperationListIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (page *OdataProductResultPage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/OdataProductResultPage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.opr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.opr = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (iter *SharedAccessAuthorizationRuleListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/SharedAccessAuthorizationRuleListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *MonitoringTagRulesListResponseIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/MonitoringTagRulesListResponseIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *ServiceListIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ServiceListIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (page *ListResultPage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ListResultPage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tnext, err := page.fn(ctx, page.lr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.lr = next\n\treturn nil\n}", "func (iter *OrderListIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/OrderListIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *CreatorListIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/CreatorListIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *ProviderOperationsMetadataListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ProviderOperationsMetadataListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *AccountsIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/AccountsIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *UsageAggregationListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/UsageAggregationListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (page *OperationListResultPage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/OperationListResultPage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.olr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.olr = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (page *OperationListResultPage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/OperationListResultPage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.olr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.olr = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (page *OperationListResultPage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/OperationListResultPage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.olr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.olr = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (page *OperationListResultPage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/OperationListResultPage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.olr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.olr = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (page *OperationListResultPage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/OperationListResultPage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.olr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.olr = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (iter *SharedAccessSignatureAuthorizationRuleListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/SharedAccessSignatureAuthorizationRuleListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *QuotaListIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/QuotaListIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *LocationListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/LocationListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *ResourceProviderOperationCollectionIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ResourceProviderOperationCollectionIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *EndpointHealthDataListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/EndpointHealthDataListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (page *ServiceProviderListResultPage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ServiceProviderListResultPage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.splr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.splr = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (page *VirtualMachineListResultPageClient) NextWithContext(ctx context.Context) (err error) {\n\treturn page.vmlrp.NextWithContext(ctx)\n}", "func (iter *UserRoleListResponseIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/UserRoleListResponseIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *IotHubQuotaMetricInfoListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/IotHubQuotaMetricInfoListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (page *StorageInsightListResultPage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/StorageInsightListResultPage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.silr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.silr = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (iter *ServiceLocationListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ServiceLocationListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (page * FirewallRuleListResultPage) NextWithContext(ctx context.Context) (err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/FirewallRuleListResultPage.NextWithContext\")\n defer func() {\n sc := -1\n if page.Response().Response.Response != nil {\n sc = page.Response().Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n for {\n next, err := page.fn(ctx, page.frlr)\n if err != nil {\n return err\n }\n page.frlr = next\n if !next.hasNextLink() || !next.IsEmpty() {\n break\n }\n }\n return nil\n }", "func (page *ProductResultPage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ProductResultPage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.pr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.pr = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (page *JobResponseListResultPage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/JobResponseListResultPage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.jrlr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.jrlr = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (page *DataSourceListResultPage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/DataSourceListResultPage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.dslr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.dslr = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (page *VMResourcesListResponsePage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/VMResourcesListResponsePage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.vrlr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.vrlr = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (page *OperationsPage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/OperationsPage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.o)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.o = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (iter *ProjectListIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ProjectListIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *NamespaceListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/NamespaceListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (page *ServiceListResultPage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ServiceListResultPage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.slr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.slr = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (iter *FirewallRuleListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/FirewallRuleListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *SasTokenInformationListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/SasTokenInformationListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *StorageContainerListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/StorageContainerListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (page *ProviderOperationsMetadataListResultPage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ProviderOperationsMetadataListResultPage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.pomlr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.pomlr = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (page *MachineListResultPage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/MachineListResultPage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.mlr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.mlr = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (page *SingleSignOnResourceListResponsePage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/SingleSignOnResourceListResponsePage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.ssorlr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.ssorlr = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (iter *DataPolicyManifestListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/DataPolicyManifestListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *RegistrationAssignmentListIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/RegistrationAssignmentListIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}" ]
[ "0.74208945", "0.73679584", "0.7333761", "0.7266704", "0.7236086", "0.7149819", "0.7149819", "0.71115386", "0.71107584", "0.7092523", "0.7083996", "0.7072595", "0.70320207", "0.7027248", "0.7012604", "0.7001773", "0.69785154", "0.6970891", "0.69377494", "0.6923949", "0.6913039", "0.6913039", "0.6913039", "0.6913039", "0.6913039", "0.6913039", "0.6913039", "0.69118136", "0.69118136", "0.69118136", "0.69091946", "0.6891788", "0.6883992", "0.6868561", "0.6868041", "0.685998", "0.6829655", "0.68288046", "0.6823176", "0.6822311", "0.68151474", "0.67947674", "0.6779313", "0.6763779", "0.67538446", "0.6750453", "0.6733122", "0.67315316", "0.6730835", "0.671723", "0.6716438", "0.6712911", "0.6707463", "0.670256", "0.66854084", "0.66777533", "0.6667548", "0.6663096", "0.66620606", "0.6656905", "0.66432875", "0.66391695", "0.66325194", "0.66249996", "0.6615008", "0.66124994", "0.6598677", "0.6598677", "0.6598677", "0.6598677", "0.6598677", "0.6594466", "0.657566", "0.65640235", "0.65597075", "0.65565443", "0.6539833", "0.6527531", "0.6527447", "0.6520672", "0.65090734", "0.6506867", "0.65064925", "0.64991546", "0.6484592", "0.6482736", "0.6481997", "0.64721227", "0.6463142", "0.64585733", "0.64508677", "0.64438856", "0.64430666", "0.6442828", "0.64407384", "0.6440136", "0.6439677", "0.6438589", "0.6434044" ]
0.6658886
59
Next advances to the next value. If there was an error making the request the iterator does not advance and the error is returned. Deprecated: Use NextWithContext() instead.
func (iter *StorageInsightListResultIterator) Next() error { return iter.NextWithContext(context.Background()) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (iter *ListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *ListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *ResourceListResultIterator) Next() error {\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr := iter.page.Next()\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *ServiceProviderListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *OperationListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *OperationListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *OperationListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *OperationListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *OperationListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *OperationListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *OperationListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *MonitoredResourceListResponseIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *OperationListIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *OperationListIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *OperationListIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *ProductResultValueIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *ResourceSkusResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *ServiceOperationListIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *ServiceListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *VaultListResultIterator) Next() error {\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr := iter.page.Next()\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *DevicesQueryResultIterator) Next() error {\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr := iter.page.Next()\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *OperationsIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *ServiceListIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *ListIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *PermissionGetResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *AppListResultIterator) Next() error {\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr := iter.page.Next()\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter * ConfigurationListResultIterator) Next() error {\n return iter.NextWithContext(context.Background())\n }", "func (iter *ResourceProviderOperationCollectionIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *ProviderOperationsMetadataListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter * ServerListResultIterator) NextWithContext(ctx context.Context) (err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/ServerListResultIterator.NextWithContext\")\n defer func() {\n sc := -1\n if iter.Response().Response.Response != nil {\n sc = iter.Response().Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n iter.i++\n if iter.i < len(iter. page.Values()) {\n return nil\n }\n err = iter.page.NextWithContext(ctx)\n if err != nil {\n iter. i--\n return err\n }\n iter.i = 0\n return nil\n }", "func (page *ListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (page *ListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (iter *AppCollectionListResultIterator) Next() error {\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr := iter.page.Next()\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *AvailableSkusResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter * DatabaseListResultIterator) NextWithContext(ctx context.Context) (err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/DatabaseListResultIterator.NextWithContext\")\n defer func() {\n sc := -1\n if iter.Response().Response.Response != nil {\n sc = iter.Response().Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n iter.i++\n if iter.i < len(iter. page.Values()) {\n return nil\n }\n err = iter.page.NextWithContext(ctx)\n if err != nil {\n iter. i--\n return err\n }\n iter.i = 0\n return nil\n }", "func (c *Context) Next() {\n\tif c.index >= c.HandlerContext.count {\n\t\treturn\n\t}\n\thandle := c.HandlerContext.handlers[c.index]\n\tc.index++\n\thandle(c)\n}", "func (c *Context) Next() {\n\tc.index++\n\tfor c.index < int8(len(c.handlers)) {\n\t\tif c.IsAborted() {\n\t\t\tbreak\n\t\t}\n\t\t(c.handlers)[c.index](c)\n\t\tc.index++\n\t}\n}", "func (it *SpanResolverIterator) Next(ctx context.Context) {\n\tif !it.Valid() {\n\t\tpanic(it.Error())\n\t}\n\tit.it.Next(ctx)\n}", "func (iter *ProductResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter * ConfigurationListResultIterator) NextWithContext(ctx context.Context) (err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/ConfigurationListResultIterator.NextWithContext\")\n defer func() {\n sc := -1\n if iter.Response().Response.Response != nil {\n sc = iter.Response().Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n iter.i++\n if iter.i < len(iter. page.Values()) {\n return nil\n }\n err = iter.page.NextWithContext(ctx)\n if err != nil {\n iter. i--\n return err\n }\n iter.i = 0\n return nil\n }", "func (iter * ServerListResultIterator) Next() error {\n return iter.NextWithContext(context.Background())\n }", "func (page *ResourceListResultPage) Next() error {\n\tnext, err := page.fn(page.rlr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.rlr = next\n\treturn nil\n}", "func (iter *ExemptionListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *CampaignsListResultIterator) Next() error {\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr := iter.page.Next()\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *ClusterListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (p *Context) Next() {\n\tif p.index >= uint8(len(p.handlers)) {\n\t\treturn\n\t}\n\th := p.handlers[p.index]\n\tp.index++\n\tlog.Debugf(\"call %s\", FuncName(h))\n\th(p)\n}", "func (iter *VMResourcesListResponseIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *ListSasTokensResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *OdataProductResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *PrivateCloudListIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func Next(err error) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\tif e, ok := err.(iNext); ok {\n\t\treturn e.Next()\n\t}\n\treturn nil\n}", "func (iter *DataSourceListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *MachineListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *ServiceSkuListIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *EndpointHealthDataListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (c *Context) Next() {\n\tc.index++ // 这一行不能忽略,对每个next 调用,都必须加 1\n\ts := len(c.handlers)\n\tfor ; c.index < s; c.index++ {\n\t\tc.handlers[c.index](c)\n\t}\n}", "func (this *Iter) Next() (interface{}, *Error) {\n\n\tif this.index > len(*this.list)-2 {\n\t\tif (this.nextPageQuery == nil) { return nil, MakeError(ErrorParse, nil, errors.New(\"At last item\")) }\n\t\tif err := this.nextPage(); err != nil { return nil, err }\n\t\tthis.index = -1\n\t}\n\t\n\tthis.index++\n\titem := (*this.list)[this.index]\n\t\n\treturn item, nil\n}", "func (iter *DeletedVaultListResultIterator) Next() error {\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr := iter.page.Next()\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *ServiceLocationListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (i *Iterator) Next() interface{} { // TODO return value needed?\n\tif len(i.Target) == 0 {\n\t\treturn nil\n\t}\n\tif i.Index+1 == len(i.Target) {\n\t\ti.Index = 0\n\t} else {\n\t\ti.Index++\n\t}\n\treturn i.Value()\n}", "func (it *ObjectPageIterator) Next() (Object, error) {\n\tretryCt := 0\n\n\tselect {\n\tcase <-it.ctx.Done():\n\t\t// If iterator has been closed\n\t\treturn nil, it.ctx.Err()\n\tdefault:\n\t\tif it.cursor < len(it.page) {\n\t\t\treturn it.returnPageNext()\n\t\t} else if it.cursor > 0 && it.q.Marker == \"\" {\n\t\t\t// no new page, lets return\n\t\t\treturn nil, iterator.Done\n\t\t}\n\t\tfor {\n\t\t\tresp, err := it.s.List(it.ctx, it.q)\n\t\t\tif err == nil {\n\t\t\t\tit.page = resp.Objects\n\t\t\t\tit.cursor = 0\n\t\t\t\tit.q.Marker = resp.NextMarker\n\t\t\t\tif len(it.page) == 0 {\n\t\t\t\t\treturn nil, iterator.Done\n\t\t\t\t}\n\t\t\t\treturn it.returnPageNext()\n\t\t\t} else if err == iterator.Done {\n\t\t\t\treturn nil, err\n\t\t\t} else if err == context.Canceled || err == context.DeadlineExceeded {\n\t\t\t\t// Return to user\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif retryCt < 5 {\n\t\t\t\tBackoff(retryCt)\n\t\t\t} else {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tretryCt++\n\t\t}\n\t}\n}", "func (iter *ConsumerGroupListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *MonitoredResourceListResponseIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/MonitoredResourceListResponseIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *LocationListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *MonitorResourceListResponseIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *SasTokenInformationListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *ProductResultValueIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ProductResultValueIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (page *ServiceProviderListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (iter *ClassicAdministratorListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (c *Context) Next() {\n\tc.index++\n\tfor c.index < int8(len(c.handlers)) {\n\t\tc.handlers[c.index](c)\n\t\tc.index++\n\t}\n}", "func (iter *UsageAggregationListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (c *Context) Next() {\n\tc.index++\n\tfor c.index < len(c.handlers) {\n\t\tc.handlers[c.index](c)\n\t\tc.index++\n\t}\n}", "func (iter *QuotaListIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (c *Context) Next() {\n\tc.index++\n\tif n := int8(len(c.handlers)); c.index < n {\n\t\tc.handlers[c.index](c)\n\t}\n}", "func (iter *RegisteredAsnListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter * FirewallRuleListResultIterator) NextWithContext(ctx context.Context) (err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/FirewallRuleListResultIterator.NextWithContext\")\n defer func() {\n sc := -1\n if iter.Response().Response.Response != nil {\n sc = iter.Response().Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n iter.i++\n if iter.i < len(iter. page.Values()) {\n return nil\n }\n err = iter.page.NextWithContext(ctx)\n if err != nil {\n iter. i--\n return err\n }\n iter.i = 0\n return nil\n }", "func (iter *ResourceSkusResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ResourceSkusResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *SingleSignOnResourceListResponseIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *JobResponseListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (itr *iterator) Next() {\n\tvar err error\n\titr.cur, err = itr.dic.Recv()\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"RemoteDB.Iterator.Next error: %v\", err))\n\t}\n}", "func (page *ProductResultValuePage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ProductResultValuePage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.prv)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.prv = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (iter * FirewallRuleListResultIterator) Next() error {\n return iter.NextWithContext(context.Background())\n }", "func (iter *ImportTaskListResultIterator) Next() error {\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr := iter.page.Next()\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter * DatabaseListResultIterator) Next() error {\n return iter.NextWithContext(context.Background())\n }", "func (iter *OperationListIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/OperationListIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *OperationListIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/OperationListIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *OperationListIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/OperationListIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (c *consumer) Next(ctx context.Context) (val *value, err error) {\n\t// Prevent Next from being called if the consumer already has one outstanding\n\t// unacknowledged message.\n\tif c.outstanding {\n\t\treturn nil, errors.New(\"unacknowledged message outstanding\")\n\t}\n\n\tvar ao int\n\n\t// Repeat trying to get the next value while the topic is either empty or not\n\t// created yet. It may exist sometime in the future.\n\tfor {\n\t\tval, ao, err = c.store.GetNext(c.topic)\n\t\tif !errors.Is(err, errTopicEmpty) && !errors.Is(err, errTopicNotExist) {\n\t\t\tbreak\n\t\t}\n\n\t\tselect {\n\t\tcase <-c.eventChan:\n\t\tcase <-ctx.Done():\n\t\t\treturn nil, errRequestCancelled\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getting next from store: %v\", err)\n\t}\n\n\tc.ackOffset = ao\n\tc.outstanding = true\n\n\treturn val, err\n}", "func (c *Context) Next() {\n\t// Call the next handler only if there is one and the response hasn't been written.\n\tif !c.Written() && c.index < len(c.handlersStack.Handlers)-1 {\n\t\tc.index++\n\t\tc.handlersStack.Handlers[c.index](c)\n\t}\n}", "func (page *MonitoredResourceListResponsePage) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/MonitoredResourceListResponsePage.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif page.Response().Response.Response != nil {\n\t\t\t\tsc = page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tfor {\n\t\tnext, err := page.fn(ctx, page.mrlr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpage.mrlr = next\n\t\tif !next.hasNextLink() || !next.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (c *Ctx) Next(f HandlerFunc) error {\n\tc.Path.Increment()\n\treturn c.Call(f)\n}", "func (iter *ComputePolicyListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *SQLServerListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *AccountsIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *ClusterListIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (it *StringIterator) Next() (string, error) {\n\tfor it.currentIndex >= len(it.items) {\n\t\tif it.atLastPage {\n\t\t\treturn \"\", Done\n\t\t}\n\t\tif err := it.apiCall(); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.currentIndex = 0\n\t}\n\tresult := it.items[it.currentIndex]\n\tit.currentIndex++\n\treturn result, nil\n}", "func (iter *ServiceProviderListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ServiceProviderListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (c *Context) Next() {\n\t// Call the next handler only if there is one and the response hasn't been written.\n\tif !c.written && c.index < len(c.handlersStack)-1 {\n\t\tc.index++\n\t\tc.handlersStack[c.index](c)\n\t}\n}", "func (iter *ListResultIterator) NextWithContext(ctx context.Context) (err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ListResultIterator.NextWithContext\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif iter.Response().Response.Response != nil {\n\t\t\t\tsc = iter.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr = iter.page.NextWithContext(ctx)\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}" ]
[ "0.69868004", "0.69868004", "0.6929111", "0.6824459", "0.67739797", "0.67739797", "0.67739797", "0.67739797", "0.67739797", "0.67739797", "0.67739797", "0.67348665", "0.67200214", "0.67200214", "0.67200214", "0.67144626", "0.6667816", "0.66638005", "0.65894705", "0.65862674", "0.6583233", "0.6562203", "0.65412205", "0.65353924", "0.65345323", "0.6503461", "0.64467406", "0.6445632", "0.6437739", "0.64349514", "0.6400231", "0.6400231", "0.6377876", "0.63730305", "0.6366551", "0.6353139", "0.63502306", "0.6349106", "0.6343321", "0.63408804", "0.6336551", "0.6334753", "0.631875", "0.6312728", "0.629938", "0.62769073", "0.62756497", "0.62651974", "0.6260622", "0.62590617", "0.62362176", "0.6215728", "0.6213999", "0.6213207", "0.6205404", "0.6205214", "0.6193957", "0.6187651", "0.61827654", "0.61570483", "0.6153885", "0.61507094", "0.61451334", "0.61443746", "0.614243", "0.6138815", "0.6131976", "0.6128701", "0.61250305", "0.61151206", "0.61128044", "0.61094946", "0.61092615", "0.6108104", "0.6105057", "0.6104126", "0.6103998", "0.60990226", "0.6097506", "0.609574", "0.6091812", "0.6086681", "0.60856104", "0.60825473", "0.60771066", "0.60771066", "0.60771066", "0.6066889", "0.6066819", "0.6059025", "0.6053603", "0.60527533", "0.60524005", "0.60425866", "0.60375077", "0.60365474", "0.60357493", "0.60299844", "0.6027818" ]
0.63554555
36
NotDone returns true if the enumeration should be started or is not yet complete.
func (iter StorageInsightListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (iter TaskListIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (page StorageInsightListResultPage) NotDone() bool {\n\treturn !page.silr.IsEmpty()\n}", "func (page StorageInsightListResultPage) NotDone() bool {\n\treturn !page.silr.IsEmpty()\n}", "func (page ImportTaskListResultPage) NotDone() bool {\n\treturn !page.itlr.IsEmpty()\n}", "func (page RegisteredAsnListResultPage) NotDone() bool {\n\treturn !page.ralr.IsEmpty()\n}", "func (page SetDefinitionListResultPage) NotDone() bool {\n\treturn !page.sdlr.IsEmpty()\n}", "func (page EndpointHealthDataListResultPage) NotDone() bool {\n\treturn !page.ehdlr.IsEmpty()\n}", "func (page OperationListPage) NotDone() bool {\n\treturn !page.ol.IsEmpty()\n}", "func (page OperationListPage) NotDone() bool {\n\treturn !page.ol.IsEmpty()\n}", "func (page OperationListPage) NotDone() bool {\n\treturn !page.ol.IsEmpty()\n}", "func (page OperationListResultPage) NotDone() bool {\n\treturn !page.olr.IsEmpty()\n}", "func (page OperationListResultPage) NotDone() bool {\n\treturn !page.olr.IsEmpty()\n}", "func (page OperationListResultPage) NotDone() bool {\n\treturn !page.olr.IsEmpty()\n}", "func (page OperationListResultPage) NotDone() bool {\n\treturn !page.olr.IsEmpty()\n}", "func (page OperationListResultPage) NotDone() bool {\n\treturn !page.olr.IsEmpty()\n}", "func (page OperationListResultPage) NotDone() bool {\n\treturn !page.olr.IsEmpty()\n}", "func (page OperationListResultPage) NotDone() bool {\n\treturn !page.olr.IsEmpty()\n}", "func (iter OperationListIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (iter OperationListIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (iter OperationListIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (page UsageAggregationListResultPage) NotDone() bool {\n\treturn !page.ualr.IsEmpty()\n}", "func (page ExportTaskListResultPage) NotDone() bool {\n\treturn !page.etlr.IsEmpty()\n}", "func (page DefinitionListResultPage) NotDone() bool {\n\treturn !page.dlr.IsEmpty()\n}", "func (page DataSourceListResultPage) NotDone() bool {\n\treturn !page.dslr.IsEmpty()\n}", "func (page MonitoredResourceListResponsePage) NotDone() bool {\n\treturn !page.mrlr.IsEmpty()\n}", "func (page AvailableSkusResultPage) NotDone() bool {\n\treturn !page.asr.IsEmpty()\n}", "func (page ResourceProviderOperationCollectionPage) NotDone() bool {\n\treturn !page.rpoc.IsEmpty()\n}", "func (page ProviderOperationsMetadataListResultPage) NotDone() bool {\n\treturn !page.pomlr.IsEmpty()\n}", "func (page RoleDefinitionListResultPage) NotDone() bool {\n\treturn !page.rdlr.IsEmpty()\n}", "func (page OperationsPage) NotDone() bool {\n\treturn !page.o.IsEmpty()\n}", "func (page ResourceListResultPage) NotDone() bool {\n\treturn !page.rlr.IsEmpty()\n}", "func (iter RoleEligibilityScheduleRequestListResultIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (page DevicesQueryResultPage) NotDone() bool {\n\treturn !page.dqr.IsEmpty()\n}", "func (iter RoleAssignmentScheduleRequestListResultIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (page PeerAsnListResultPage) NotDone() bool {\n\treturn !page.palr.IsEmpty()\n}", "func (iter OperationsIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (page MachineExtensionsListResultPage) NotDone() bool {\n\treturn !page.melr.IsEmpty()\n}", "func (page NamespaceListResultPage) NotDone() bool {\n\treturn !page.nlr.IsEmpty()\n}", "func (page MachineListResultPage) NotDone() bool {\n\treturn !page.mlr.IsEmpty()\n}", "func (page ListResultPage) NotDone() bool {\n\treturn !page.lr.IsEmpty()\n}", "func (page ListResultPage) NotDone() bool {\n\treturn !page.lr.IsEmpty()\n}", "func (page ClassicAdministratorListResultPage) NotDone() bool {\n\treturn !page.calr.IsEmpty()\n}", "func (page RoleAssignmentScheduleRequestListResultPage) NotDone() bool {\n\treturn !page.rasrlr.IsEmpty()\n}", "func (iter ServiceOperationListIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (page ResourceSkusResultPage) NotDone() bool {\n\treturn !page.rsr.IsEmpty()\n}", "func (page ConsumerGroupListResultPage) NotDone() bool {\n\treturn !page.cglr.IsEmpty()\n}", "func (page AssignmentListResultPage) NotDone() bool {\n\treturn !page.alr.IsEmpty()\n}", "func (iter RoleEligibilityScheduleListResultIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (page StorageAccountInformationListResultPage) NotDone() bool {\n\treturn !page.sailr.IsEmpty()\n}", "func (page IotHubDescriptionListResultPage) NotDone() bool {\n\treturn !page.ihdlr.IsEmpty()\n}", "func (page RoleEligibilityScheduleListResultPage) NotDone() bool {\n\treturn !page.reslr.IsEmpty()\n}", "func (page FirewallRuleListResultPage) NotDone() bool {\n\treturn !page.frlr.IsEmpty()\n}", "func (page ExemptionListResultPage) NotDone() bool {\n\treturn !page.elr.IsEmpty()\n}", "func (page MonitorResourceListResponsePage) NotDone() bool {\n\treturn !page.mrlr.IsEmpty()\n}", "func (iter ExportTaskListResultIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (iter MonitoredResourceListResponseIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (page RoleAssignmentScheduleListResultPage) NotDone() bool {\n\treturn !page.raslr.IsEmpty()\n}", "func (iter DevicesQueryResultIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (page SasTokenInformationListResultPage) NotDone() bool {\n\treturn !page.stilr.IsEmpty()\n}", "func (page ServiceListResultPage) NotDone() bool {\n\treturn !page.slr.IsEmpty()\n}", "func (page CampaignsListResultPage) NotDone() bool {\n\treturn !page.clr.IsEmpty()\n}", "func (page RoleEligibilityScheduleRequestListResultPage) NotDone() bool {\n\treturn !page.resrlr.IsEmpty()\n}", "func (iter EndpointHealthDataListResultIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (page AppListResultPage) NotDone() bool {\n\treturn !page.alr.IsEmpty()\n}", "func (iter ImportTaskListResultIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (page ServiceOperationListPage) NotDone() bool {\n\treturn !page.sol.IsEmpty()\n}", "func (page TaskListPage) NotDone() bool {\n\treturn !page.tl.IsEmpty()\n}", "func (iter ResourceProviderOperationCollectionIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (iter RoleAssignmentScheduleListResultIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (page DataLakeStoreAccountInformationListResultPage) NotDone() bool {\n\treturn !page.dlsailr.IsEmpty()\n}", "func (page RoleAssignmentScheduleInstanceListResultPage) NotDone() bool {\n\treturn !page.rasilr.IsEmpty()\n}", "func (page JobResponseListResultPage) NotDone() bool {\n\treturn !page.jrlr.IsEmpty()\n}", "func (page RegisteredPrefixListResultPage) NotDone() bool {\n\treturn !page.rplr.IsEmpty()\n}", "func (page IotHubSkuDescriptionListResultPage) NotDone() bool {\n\treturn !page.ihsdlr.IsEmpty()\n}", "func (page DeletedVaultListResultPage) NotDone() bool {\n\treturn !page.dvlr.IsEmpty()\n}", "func (iter ServiceSkuListIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (page RegistrationDefinitionListPage) NotDone() bool {\n\treturn !page.rdl.IsEmpty()\n}", "func (page EligibleChildResourcesListResultPage) NotDone() bool {\n\treturn !page.ecrlr.IsEmpty()\n}", "func (iter AvailableSkusResultIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (page DataPolicyManifestListResultPage) NotDone() bool {\n\treturn !page.dpmlr.IsEmpty()\n}", "func (iter ServiceListIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (iter OperationListResultIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (iter OperationListResultIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (iter OperationListResultIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (iter OperationListResultIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (iter OperationListResultIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (iter OperationListResultIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (iter OperationListResultIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (page IotHubQuotaMetricInfoListResultPage) NotDone() bool {\n\treturn !page.ihqmilr.IsEmpty()\n}", "func (page OrderListPage) NotDone() bool {\n\treturn !page.ol.IsEmpty()\n}", "func (iter MaintenanceWindowListResultIterator) NotDone() bool {\n return iter.page.NotDone() && iter.i < len(iter. page.Values())\n }", "func (page RegistrationAssignmentListPage) NotDone() bool {\n\treturn !page.ral.IsEmpty()\n}", "func (page StorageContainerListResultPage) NotDone() bool {\n\treturn !page.sclr.IsEmpty()\n}", "func (iter RegistrationDefinitionListIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (iter MonitorResourceListResponseIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}", "func (page RoleAssignmentListResultPage) NotDone() bool {\n\treturn !page.ralr.IsEmpty()\n}", "func (page ServicePrefixListResultPage) NotDone() bool {\n\treturn !page.splr.IsEmpty()\n}", "func (page FirewallRuleListResultPage) NotDone() bool {\n return !page.frlr.IsEmpty()\n }", "func (iter RegistrationAssignmentListIterator) NotDone() bool {\n\treturn iter.page.NotDone() && iter.i < len(iter.page.Values())\n}" ]
[ "0.74784005", "0.7400463", "0.7400463", "0.7395448", "0.7392844", "0.7388955", "0.7376365", "0.7374408", "0.7374408", "0.7374408", "0.7371007", "0.7371007", "0.7371007", "0.7371007", "0.7371007", "0.7371007", "0.7371007", "0.7357392", "0.7357392", "0.7357392", "0.7357319", "0.7354514", "0.73426074", "0.7324296", "0.73165447", "0.72870404", "0.72764176", "0.72724843", "0.72692436", "0.7265132", "0.72558486", "0.72515947", "0.72507477", "0.72505814", "0.725033", "0.72478646", "0.7242524", "0.7226928", "0.72258526", "0.7223231", "0.7223231", "0.72202796", "0.7219656", "0.7218518", "0.721729", "0.7204715", "0.7197915", "0.719584", "0.7194185", "0.718929", "0.71891975", "0.71856815", "0.7184931", "0.7182482", "0.71802413", "0.7179388", "0.71771204", "0.717294", "0.71687794", "0.7167605", "0.7166356", "0.71629715", "0.7162359", "0.71621984", "0.71464175", "0.71440303", "0.7141928", "0.71273106", "0.712537", "0.7123051", "0.71229076", "0.71196157", "0.71150845", "0.7114678", "0.71140945", "0.71010274", "0.709631", "0.7091963", "0.70895696", "0.7083001", "0.7082192", "0.7080931", "0.7080931", "0.7080931", "0.7080931", "0.7080931", "0.7080931", "0.7080931", "0.7075448", "0.70752764", "0.7074489", "0.70738834", "0.7073521", "0.70719916", "0.7069846", "0.7068587", "0.7067295", "0.706607", "0.7058111" ]
0.7128995
67
Response returns the raw server response from the last page request.
func (iter StorageInsightListResultIterator) Response() StorageInsightListResult { return iter.page.Response() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pl PageList) Response() *http.Response {\n\treturn pl.rawResponse\n}", "func (pbcir PageBlobsCopyIncrementalResponse) Response() *http.Response {\n\treturn pbcir.rawResponse\n}", "func (pbcpr PageBlobsClearPagesResponse) Response() *http.Response {\n\treturn pbcpr.rawResponse\n}", "func (pbupr PageBlobsUploadPagesResponse) Response() *http.Response {\n\treturn pbupr.rawResponse\n}", "func (pbusnr PageBlobsUpdateSequenceNumberResponse) Response() *http.Response {\n\treturn pbusnr.rawResponse\n}", "func (pbcr PageBlobsCreateResponse) Response() *http.Response {\n\treturn pbcr.rawResponse\n}", "func (bl BlockList) Response() *http.Response {\n\treturn bl.rawResponse\n}", "func (pbrr PageBlobsResizeResponse) Response() *http.Response {\n\treturn pbrr.rawResponse\n}", "func (bur BlobsUndeleteResponse) Response() *http.Response {\n\treturn bur.rawResponse\n}", "func (b *BaseHandler) Response() http.ResponseWriter {\n\treturn b.getResponse()\n}", "func (bcsr BlobsCreateSnapshotResponse) Response() *http.Response {\n\treturn bcsr.rawResponse\n}", "func (brlr BlobsReleaseLeaseResponse) Response() *http.Response {\n\treturn brlr.rawResponse\n}", "func (si SignedIdentifiers) Response() *http.Response {\n\treturn si.rawResponse\n}", "func (lcr ListContainersResponse) Response() *http.Response {\n\treturn lcr.rawResponse\n}", "func (dr downloadResponse) Response() *http.Response {\n\treturn dr.rawResponse\n}", "func (brlr BlobsRenewLeaseResponse) Response() *http.Response {\n\treturn brlr.rawResponse\n}", "func (abcr AppendBlobsCreateResponse) Response() *http.Response {\n\treturn abcr.rawResponse\n}", "func (ababr AppendBlobsAppendBlockResponse) Response() *http.Response {\n\treturn ababr.rawResponse\n}", "func (bblr BlobsBreakLeaseResponse) Response() *http.Response {\n\treturn bblr.rawResponse\n}", "func (bbur BlockBlobsUploadResponse) Response() *http.Response {\n\treturn bbur.rawResponse\n}", "func (bclr BlobsChangeLeaseResponse) Response() *http.Response {\n\treturn bclr.rawResponse\n}", "func (o *ServiceInstanceLastOperationGetOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\t// response header RetryAfter\n\n\tretryAfter := o.RetryAfter\n\tif retryAfter != \"\" {\n\t\trw.Header().Set(\"RetryAfter\", retryAfter)\n\t}\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) // let the recovery middleware deal with this\n\t\t}\n\t}\n}", "func (cdr ContainersDeleteResponse) Response() *http.Response {\n\treturn cdr.rawResponse\n}", "func (lpr LeasePathResponse) Response() *http.Response {\n\treturn lpr.rawResponse\n}", "func (crlr ContainersReleaseLeaseResponse) Response() *http.Response {\n\treturn crlr.rawResponse\n}", "func (balr BlobsAcquireLeaseResponse) Response() *http.Response {\n\treturn balr.rawResponse\n}", "func (p *AlertsClientGetAllPager) PageResponse() AlertsClientGetAllResponse {\n\treturn p.current\n}", "func WritePageResponse(w http.ResponseWriter, data interface{}, r *http.Request, p Page) error {\n\tif p.PrevPageExists() {\n\t\tp.PrevURL = p.Prev().SetQueryParams(r.URL).String()\n\t}\n\tif p.NextPageExists() {\n\t\tp.NextURL = p.Next().SetQueryParams(r.URL).String()\n\t}\n\n\tenv := map[string]interface{}{\n\t\t\"meta\": map[string]interface{}{\n\t\t\t\"code\": http.StatusOK,\n\t\t},\n\t\t\"data\": data,\n\t\t\"pagination\": p,\n\t}\n\treturn jsonResponse(w, env)\n}", "func (bshhr BlobsSetHTTPHeadersResponse) Response() *http.Response {\n\treturn bshhr.rawResponse\n}", "func (bstr BlobsSetTierResponse) Response() *http.Response {\n\treturn bstr.rawResponse\n}", "func (cclr ContainersChangeLeaseResponse) Response() *http.Response {\n\treturn cclr.rawResponse\n}", "func (bbsbr BlockBlobsStageBlockResponse) Response() *http.Response {\n\treturn bbsbr.rawResponse\n}", "func (lbhr ListBlobsHierarchyResponse) Response() *http.Response {\n\treturn lbhr.rawResponse\n}", "func (bdr BlobsDeleteResponse) Response() *http.Response {\n\treturn bdr.rawResponse\n}", "func (cblr ContainersBreakLeaseResponse) Response() *http.Response {\n\treturn cblr.rawResponse\n}", "func (sss StorageServiceStats) Response() *http.Response {\n\treturn sss.rawResponse\n}", "func (crlr ContainersRenewLeaseResponse) Response() *http.Response {\n\treturn crlr.rawResponse\n}", "func (o *ServiceInstanceLastOperationGetDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(o._statusCode)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) // let the recovery middleware deal with this\n\t\t}\n\t}\n}", "func (bscfur BlobsStartCopyFromURLResponse) Response() *http.Response {\n\treturn bscfur.rawResponse\n}", "func (cfr CreateFilesystemResponse) Response() *http.Response {\n\treturn cfr.rawResponse\n}", "func (csapr ContainersSetAccessPolicyResponse) Response() *http.Response {\n\treturn csapr.rawResponse\n}", "func (p *RouteTablesClientListAllPager) PageResponse() RouteTablesClientListAllResponse {\n\treturn p.current\n}", "func (p *ReservationClientListAllPager) PageResponse() ReservationClientListAllResponse {\n\treturn p.current\n}", "func (bsmr BlobsSetMetadataResponse) Response() *http.Response {\n\treturn bsmr.rawResponse\n}", "func (iter OperationsIterator) Response() Operations {\n\treturn iter.page.Response()\n}", "func (iter OrderListIterator) Response() OrderList {\n\treturn iter.page.Response()\n}", "func (upr UpdatePathResponse) Response() *http.Response {\n\treturn upr.rawResponse\n}", "func Responses(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer Default.Sync()\n\t\tvar written int64\n\t\tvar status = -1\n\n\t\twp := writerProxy{\n\t\t\th: func() http.Header {\n\t\t\t\treturn w.Header()\n\t\t\t},\n\t\t\tw: func(bytes []byte) (int, error) {\n\t\t\t\tbw, err := w.Write(bytes)\n\t\t\t\twritten += int64(bw)\n\t\t\t\treturn bw, err\n\t\t\t},\n\t\t\twh: func(code int) {\n\t\t\t\tstatus = code\n\t\t\t\tw.WriteHeader(code)\n\t\t\t},\n\t\t}\n\n\t\tstart := time.Now()\n\t\tnext.ServeHTTP(wp, r)\n\t\tduration := time.Now().Sub(start)\n\n\t\t// Use default status.\n\t\tif status == -1 {\n\t\t\tstatus = 200\n\t\t}\n\n\t\tlogResponse(r.Method, r.URL.String(), status, written, duration)\n\t})\n}", "func (bbcblr BlockBlobsCommitBlockListResponse) Response() *http.Response {\n\treturn bbcblr.rawResponse\n}", "func (p *RoutesClientListPager) PageResponse() RoutesClientListResponse {\n\treturn p.current\n}", "func (p *ManagementClientGetActiveSessionsPager) PageResponse() ManagementClientGetActiveSessionsResponse {\n\treturn p.current\n}", "func (p *ReservationClientListRevisionsPager) PageResponse() ReservationClientListRevisionsResponse {\n\treturn p.current\n}", "func (p *PoolsClientListPager) PageResponse() PoolsClientListResponse {\n\treturn p.current\n}", "func (calr ContainersAcquireLeaseResponse) Response() *http.Response {\n\treturn calr.rawResponse\n}", "func (lbfr ListBlobsFlatResponse) Response() *http.Response {\n\treturn lbfr.rawResponse\n}", "func (p *ManagementClientDisconnectActiveSessionsPager) PageResponse() ManagementClientDisconnectActiveSessionsResponse {\n\treturn p.current\n}", "func (ccr ContainersCreateResponse) Response() *http.Response {\n\treturn ccr.rawResponse\n}", "func (bgpr BlobsGetPropertiesResponse) Response() *http.Response {\n\treturn bgpr.rawResponse\n}", "func (b *BaseHandler) getResponse() http.ResponseWriter {\n\treturn b.response\n}", "func (s *Server) Response(body string) string {\n\treturn \"HTTP/1.1 200 OK\\r\\n\" +\n\t\t\"Content-Length: \" + strconv.Itoa(len(body)) + lineBreaker +\n\t\t\"Content-Type: text/html\\r\\n\" +\n\t\t\"Connection: close\\r\\n\" +\n\t\tlineBreaker + body\n}", "func (p *LinkedServerListPager) PageResponse() LinkedServerListResponse {\n\treturn p.current\n}", "func (cpr CreatePathResponse) Response() *http.Response {\n\treturn cpr.rawResponse\n}", "func (rpr ReadPathResponse) Response() *http.Response {\n\treturn rpr.rawResponse\n}", "func (dfr DeleteFilesystemResponse) Response() *http.Response {\n\treturn dfr.rawResponse\n}", "func (page OperationsPage) Response() Operations {\n\treturn page.o\n}", "func (bacfur BlobsAbortCopyFromURLResponse) Response() *http.Response {\n\treturn bacfur.rawResponse\n}", "func (p *ApplicationGatewaysClientListAllPager) PageResponse() ApplicationGatewaysClientListAllResponse {\n\treturn p.current\n}", "func (iter ServerListResultIterator) Response() ServerListResult {\n return iter.page.Response()\n }", "func (response ListPipelinesResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}", "func (p *AppsClientListPager) PageResponse() AppsClientListResponse {\n\treturn p.current\n}", "func (iter ListIterator) Response() List {\n\treturn iter.page.Response()\n}", "func (p *FlowLogsClientListPager) PageResponse() FlowLogsClientListResponse {\n\treturn p.current\n}", "func (csmr ContainersSetMetadataResponse) Response() *http.Response {\n\treturn csmr.rawResponse\n}", "func (cgpr ContainersGetPropertiesResponse) Response() *http.Response {\n\treturn cgpr.rawResponse\n}", "func (p *RouteTablesClientListPager) PageResponse() RouteTablesClientListResponse {\n\treturn p.current\n}", "func (iter TaskListIterator) Response() TaskList {\n\treturn iter.page.Response()\n}", "func (dpr DeletePathResponse) Response() *http.Response {\n\treturn dpr.rawResponse\n}", "func (o *ArtifactListerPartialContent) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\t// response header Next\n\n\tnext := o.Next\n\tif next != \"\" {\n\t\trw.Header().Set(\"Next\", next)\n\t}\n\n\t// response header Previous\n\n\tprevious := o.Previous\n\tif previous != \"\" {\n\t\trw.Header().Set(\"Previous\", previous)\n\t}\n\n\t// response header RemainingRecords\n\n\tremainingRecords := swag.FormatUint64(o.RemainingRecords)\n\tif remainingRecords != \"\" {\n\t\trw.Header().Set(\"RemainingRecords\", remainingRecords)\n\t}\n\n\t// response header TotalRecords\n\n\ttotalRecords := swag.FormatUint64(o.TotalRecords)\n\tif totalRecords != \"\" {\n\t\trw.Header().Set(\"TotalRecords\", totalRecords)\n\t}\n\n\trw.WriteHeader(206)\n\tpayload := o.Payload\n\tif payload == nil {\n\t\tpayload = make([]*weles.ArtifactInfo, 0, 50)\n\t}\n\n\tif err := producer.Produce(rw, payload); err != nil {\n\t\tpanic(err) // let the recovery middleware deal with this\n\t}\n\n}", "func (p *ManagementClientGetBastionShareableLinkPager) PageResponse() ManagementClientGetBastionShareableLinkResponse {\n\treturn p.current\n}", "func (p *VirtualNetworksClientListAllPager) PageResponse() VirtualNetworksClientListAllResponse {\n\treturn p.current\n}", "func (p *OperationsListPager) PageResponse() OperationsListResponse {\n\treturn p.current\n}", "func (p *OperationsListPager) PageResponse() OperationsListResponse {\n\treturn p.current\n}", "func (p *OperationsListPager) PageResponse() OperationsListResponse {\n\treturn p.current\n}", "func (iter OperationListIterator) Response() OperationList {\n\treturn iter.page.Response()\n}", "func (iter OperationListIterator) Response() OperationList {\n\treturn iter.page.Response()\n}", "func (iter OperationListIterator) Response() OperationList {\n\treturn iter.page.Response()\n}", "func (dr DownloadResponse) Response() *http.Response {\n\treturn dr.dr.Response()\n}", "func (p *InterfacesClientListAllPager) PageResponse() InterfacesClientListAllResponse {\n\treturn p.current\n}", "func (iter QuotaListIterator) Response() QuotaList {\n\treturn iter.page.Response()\n}", "func (iter PrivateCloudListIterator) Response() PrivateCloudList {\n\treturn iter.page.Response()\n}", "func (p *SmartGroupsClientGetAllPager) PageResponse() SmartGroupsClientGetAllResponse {\n\treturn p.current\n}", "func (gppr GetPathPropertiesResponse) Response() *http.Response {\n\treturn gppr.rawResponse\n}", "func (p *VirtualWansClientListPager) PageResponse() VirtualWansClientListResponse {\n\treturn p.current\n}", "func (page ServerListResultPage) Response() ServerListResult {\n return page.slr\n }", "func (cl *APIClient) RequestNextResponsePage(rr *R.Response) (*R.Response, error) {\n\tmycmd := cl.toUpperCaseKeys(rr.GetCommand())\n\tif _, ok := mycmd[\"LAST\"]; ok {\n\t\treturn nil, errors.New(\"Parameter LAST in use. Please remove it to avoid issues in requestNextPage\")\n\t}\n\tfirst := 0\n\tif v, ok := mycmd[\"FIRST\"]; ok {\n\t\tfirst, _ = fmt.Sscan(\"%s\", v)\n\t}\n\ttotal := rr.GetRecordsTotalCount()\n\tlimit := rr.GetRecordsLimitation()\n\tfirst += limit\n\tif first < total {\n\t\tmycmd[\"FIRST\"] = fmt.Sprintf(\"%d\", first)\n\t\tmycmd[\"LIMIT\"] = fmt.Sprintf(\"%d\", limit)\n\t\treturn cl.Request(mycmd), nil\n\t}\n\treturn nil, errors.New(\"Could not find further existing pages\")\n}", "func (iter VMResourcesListResponseIterator) Response() VMResourcesListResponse {\n\treturn iter.page.Response()\n}", "func (p *P2SVPNGatewaysClientListPager) PageResponse() P2SVPNGatewaysClientListResponse {\n\treturn p.current\n}", "func (response ListBatchInstancesResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}", "func (p *FileSharesClientListPager) PageResponse() FileSharesClientListResponse {\n\treturn p.current\n}", "func (p *HubRouteTablesClientListPager) PageResponse() HubRouteTablesClientListResponse {\n\treturn p.current\n}", "func (p *OperationsClientListPager) PageResponse() OperationsClientListResponse {\n\treturn p.current\n}" ]
[ "0.7152825", "0.6988708", "0.6846365", "0.6735078", "0.65995663", "0.633469", "0.63318527", "0.63217014", "0.62835306", "0.6281629", "0.6234478", "0.6225371", "0.62236917", "0.62086654", "0.617455", "0.61545783", "0.61418515", "0.61391413", "0.6127459", "0.609929", "0.6090572", "0.60891986", "0.6062124", "0.6047994", "0.60471755", "0.6044305", "0.6032144", "0.6030253", "0.60300547", "0.60223216", "0.6013413", "0.60097474", "0.60095435", "0.6002005", "0.599272", "0.5980507", "0.5954163", "0.5949233", "0.5945626", "0.59391683", "0.59363407", "0.59278023", "0.5921352", "0.59179103", "0.5911672", "0.5901132", "0.589899", "0.58865356", "0.5883034", "0.5881915", "0.58817816", "0.58703846", "0.58623105", "0.5858975", "0.5856571", "0.58497685", "0.58460647", "0.5840336", "0.5833904", "0.583201", "0.582968", "0.5822061", "0.58201134", "0.58109003", "0.5809613", "0.58025265", "0.5799737", "0.5798601", "0.579037", "0.5781486", "0.5777205", "0.577689", "0.5770703", "0.57658905", "0.57507455", "0.5749598", "0.57475555", "0.57419086", "0.57413733", "0.5737293", "0.57370555", "0.57370555", "0.57370555", "0.57369", "0.57369", "0.57369", "0.5733603", "0.57328236", "0.57302976", "0.5729266", "0.5728599", "0.5726558", "0.57259643", "0.57251877", "0.57248783", "0.5719684", "0.57191736", "0.5711424", "0.5710941", "0.5710339", "0.56989336" ]
0.0
-1