Exemplo n.º 1
0
func (c *Client) Notify(hs *routing.HTTPSession) routing.HResult {
	log.D("Notify->%v", "xxx")
	var addr = hs.R.Header.Get("X-Real-IP")
	if len(addr) < 1 {
		addr = hs.R.RemoteAddr
	}
	hs.R.ParseForm()
	var vals = hs.R.Form
	var sign, sign_type = vals.Get("sign"), vals.Get("sign_type")
	vals.Del("sign")
	vals.Del("sign_type")
	var data = vals.Encode()
	data, _ = url.QueryUnescape(data)
	var err = c.Web.Verify(data, sign, sign_type)
	if err != nil {
		log.W("Client.Notify recieve bad request from address(%v),err:%v->\nsign_type=%v&sign=%v&%v", addr, err, sign_type, sign, data)
		hs.W.WriteHeader(400)
		hs.W.Write([]byte(err.Error()))
		return routing.HRES_RETURN
	}
	log.D("Client.Notify receive verify request from address(%v) by args:\nsign_type=%v&sign=%v&%v\n<-", addr, sign_type, sign, data)
	err = c.H.OnNotify(c, hs)
	if err == nil {
		hs.W.Write([]byte("success"))
	} else {
		log.W("Client.Notify call on notify fail with error(%v)", err)
		hs.W.WriteHeader(400)
		hs.W.Write([]byte(err.Error()))
	}
	return routing.HRES_RETURN
}
Exemplo n.º 2
0
Arquivo: dbm.go Projeto: Centny/dbm
func (m *MDbs) LoopPing() {
	log.D("MDbs loop ping is started...")
	for m.Running {
		for _, mdb := range m.Dbs {
			if mdb.ping < 1 {
				mdb.ping = 1
				go mdb.TPing()
			}
		}
		time.Sleep(time.Duration(m.Delay) * time.Millisecond)
	}
	log.D("MDbs loop ping is stopped...")
}
Exemplo n.º 3
0
Arquivo: sql.go Projeto: Centny/dbm
func (s *SQL_H) Create() (interface{}, error) {
	log.D("SQL_H start connect to %v", s)
	db, err := sql.Open(s.Driver, s.Url)
	if err == nil {
		db.SetMaxIdleConns(s.Idle)
		db.SetMaxOpenConns(s.Max)
		log.D("SQL_H connect to %v success", s)
		return db, nil
	} else {
		log.D("SQL_H connect to %v error->%v", s, err)
		return nil, err
	}
}
Exemplo n.º 4
0
Arquivo: util.go Projeto: dgdn/goutil
func InsertTx(tx *sql.Tx, o interface{}, tableName string) (int64, error) {
	dfs := parseToDbfield(o)
	s := bytes.Buffer{}
	s.WriteString("insert into ")
	s.WriteString(tableName)
	s.WriteString("(")
	s.WriteString(selectColumn(dfs))
	s.WriteString(")values(")
	s.WriteString(placeholders(dfs))
	s.WriteString(")")
	log.D("sql:%v", s.String())
	log.D("args:%v", args(dfs))
	return dbutil.DbInsert2(tx, s.String(), args(dfs))
}
Exemplo n.º 5
0
Arquivo: util.go Projeto: dgdn/goutil
func Insert(o DbModel) (int64, error) {
	dfs := parseToDbfield(o)
	s := bytes.Buffer{}
	s.WriteString("insert into ")
	s.WriteString(o.GetTableName())
	s.WriteString("(")
	s.WriteString(selectColumn(dfs))
	s.WriteString(")values(")
	s.WriteString(placeholders(dfs))
	s.WriteString(")")
	log.D("sql:%v", s.String())
	log.D("args:%v", args(dfs))
	return dbutil.DbInsert(DbConn(), s.String(), args(dfs))
}
Exemplo n.º 6
0
Arquivo: util.go Projeto: dgdn/goutil
func dbQueryStruct(db *sql.DB, res interface{}, query string, args ...interface{}) error {
	rows, err := db.Query(query, args...)
	if err != nil {
		return err
	}
	cols, err := rows.Columns()
	if err != nil {
		return err
	}
	rval := reflect.ValueOf(res).Elem()

	rtype := rval.Type()
	pls := []interface{}{}
	for _, col := range cols {
		for i := 0; i < rtype.NumField(); i++ {
			if rtype.Field(i).Tag.Get("m2s") == col {
				pls = append(pls, rval.Field(i).Addr().Interface())
			}
		}
	}
	log.D("query:%v \n pls:%v", query, pls)
	if rows.Next() {
		return rows.Scan(pls...)
	}
	return sql.ErrNoRows
}
Exemplo n.º 7
0
Arquivo: api.go Projeto: tomlovzki/ebs
func UpdateBankPaper(rc *impl.RCM_Cmd) (interface{}, error) {
	var uid, bankId int64
	var paperIds, p2bIds, ext string
	err := rc.ValidF(`
		uid,R|I,R:0;
		bankId,R|I,R:0;
		paperIds,R|S,L:0;
		p2bIds,O|S,L:0;
		ext,O|S,L:0;
		`, &uid, &bankId, &paperIds, &p2bIds, &ext)
	if err != nil {
		log.E("UpdateBankPaper arg err:%v", err)
		return 0, err
	}
	extParse := []P2b_Paper{}
	json.Unmarshal([]byte(ext), &extParse)
	rs := []P2b_Paper{}
	paperIdsArr := []int64{}
	err = json.Unmarshal([]byte(paperIds), &paperIdsArr)
	if err != nil {
		return nil, err
	}

	if p2bIds == "" {
		p2bIds = "0"
	}
	sql_ := "delete from ebs_p2b where bank_id=? and tid not in (" + p2bIds + ")"
	var conn *sql.DB = dbMgr.DbConn()
	tx, err := conn.Begin()
	if err != nil {
		return nil, err
	}

	//同步练习
	for _, v := range extParse {
		fmt.Println(tx.Exec("insert into ebs_p2b (tid,bank_id,paper_id,status,add1) values (?,?,?,'N','P')", v.P2bId, bankId, v.PId))
	}
	//同步练习

	if ext != "" {
		sql_ += " and add1='P'"
	} else {
		sql_ += " and (add1!='P' or add1 is null)"
	}
	log.D("%s", sql_)
	if _, err := tx.Exec(sql_, bankId); err != nil {
		tx.Rollback()
		return nil, err
	}
	for _, v := range paperIdsArr {
		if res, err := tx.Exec("insert into ebs_p2b (bank_id,paper_id,status) values (?,?,'N')", bankId, v); err != nil {
			tx.Rollback()
			return nil, err
		} else {
			p2bId, _ := res.LastInsertId()
			rs = append(rs, P2b_Paper{p2bId, v})
		}
	}
	return rs, tx.Commit()
}
Exemplo n.º 8
0
Arquivo: srv.go Projeto: tomlovzki/ebs
func CreateBank(rc *impl.RCM_Cmd) (interface{}, error) {
	log.D("rc CreateBank")
	var uid int64
	var uname string
	var bName string
	err := rc.ValidF(`
		uid,R|I,R:0;
		uname,R|S,L:0;
		bName,R|S,L:0;
		`, &uid, &uname, &bName)
	if err != nil {
		log.E("CreateBank arg err:%v", err)
		return 0, err
	}
	b := &bank.BANK{}
	b.UId = &uid
	b.Name = &bName
	b.UName = &uname
	b.Status = bank.GetString("N")
	b.Public = bank.GetInt(1)

	if n, err := b.C(nil); err != nil {
		log.E("CreateBank err:%v", err)
		return 0, err
	} else {
		return n, nil
	}
}
Exemplo n.º 9
0
Arquivo: mgo.go Projeto: Centny/dbm
func (m *MGO_H) Create() (interface{}, error) {
	if len(m.Url) < 1 || len(m.Name) < 1 {
		return nil, util.Err("the database con/name is empty")
	}
	log.D("MGO_H start dail to %v", m)
	ss, err := tmgo.Dial(m.Url)
	if err == nil {
		log.D("MGO_H dail to %v success", m)
		return ss.DB(m.Name), nil
	}
	log.D("MGO_H dail to %v error->%v", m, err)
	if ss != nil {
		ss.Close()
	}
	return nil, err
}
Exemplo n.º 10
0
func CallC(rc *impl.RCM_Cmd) (interface{}, error) {
	var cid = rc.Kvs().StrVal("cid")
	log.D("run_rc_s doing call_c by cid(%v)", cid)
	var cmd = rcs.CmdC(cid)
	if cmd == nil {
		return util.Map{
			"code": -1,
			"err":  "not found",
		}, nil
	}
	var name = rc.StrVal("name")
	var args = rc.MapVal("args")
	log.D("run_rc_s call client by name(%v),args(%v)", name, util.S2Json(args))
	var res, err = cmd.Exec_m(name, args)
	log.D("run_rc_s call client result->%v", util.S2Json(res))
	return res, err
}
Exemplo n.º 11
0
func RunFFCM_S_V(fcfg *util.Fcfg) error {
	if SRV == nil {
		return util.Err("server is not running")
	}
	var listen = fcfg.Val("listen")
	SRV.Hand("", routing.Shared)
	routing.Shared.Print()
	log.D("listen web server on %v", listen)
	return routing.ListenAndServe(listen)
}
Exemplo n.º 12
0
Arquivo: index.go Projeto: Centny/dbm
func ChkIdx(C func(string) *tmgo.Collection, indexes map[string]map[string]tmgo.Index) error {
	for cname, index := range indexes {
		tc := C(cname)
		if _, err := tc.Count(); err != nil {
			return err
		}
		log.D("ChkIdx checking index on collection(%v)...", cname)
		idx_l, err := tc.Indexes()
		if err != nil {
			if qerr, ok := err.(*tmgo.QueryError); !ok || qerr.Code != 26 {
				err = util.Err("ChkIdx list indexes fail with error(%v) on collection(%v)", err, cname)
				log.E("%v", err)
				return err
			}
			log.D("ChkIdx the collection(%v) is not found, it will create empty one...", cname)
			err = tc.Create(&tmgo.CollectionInfo{})
			if err != nil {
				err = util.Err("ChkIdx create collection(%v) fail with error(%v)", cname, err)
				log.E("%v", err)
				return err
			}
		}
		exists := map[string]tmgo.Index{}
		for _, idx := range idx_l {
			exists[idx.Name] = idx
		}
		for iname, idx := range index {
			if _, ok := exists[iname]; ok {
				continue
			}
			idx.Name = iname
			err = C(cname).EnsureIndex(idx)
			if err != nil {
				err = util.Err("ChkIdx ensure index by keys(%v),name(%v) fail with error(%v) on collection(%v)", idx.Key, idx.Name, err, cname)
				log.E("%v", err)
				return err
			}
			log.D("ChkIdx ensure index(%v) on collection(%v) success", iname, cname)
		}
	}
	return nil
}
Exemplo n.º 13
0
Arquivo: tsql.go Projeto: Centny/dbm
func tsql2() {
	db, err := vsql.Open("mysql", "cny:123@tcp(127.0.0.1:3306)/test?charset=utf8&loc=Local")
	if err != nil {
		panic(err.Error())
	}
	for {
		_, err := dbutil.DbQueryInt(db, "select 1")
		log.D("%v", err)
		time.Sleep(time.Second)
	}
}
Exemplo n.º 14
0
Arquivo: dbm.go Projeto: Centny/dbm
func (m *MDb) TPing() {
	var showlog = ShowLog && (util.Now()-m.log_time > ShowLogTime)
	if showlog {
		m.log_time = util.Now()
		log.D("MDb start ping to %v ", m.String())
	}
	err := m.H.Ping(m.DB)
	if err == nil || err.Error() != "Closed explicitly" {
		if err == nil {
			if showlog {
				log.D("MDb ping to %v success", m.String())
			}
		} else {
			log.E("MDb ping to %v error->%v, will mark to not active", m.String(), err)
		}
		m.lck.Lock()
		m.Active = err == nil
		m.ping = 0
		m.lck.Unlock()
		return
	}
	// m.H.Close(m.DB)
	//do reconnect
	log.E("MDb ping to %v error->%v, will try reconnect", m.String(), err)
	for {
		db, err := m.H.Create()
		if err == nil {
			log.D("MDb connect to %v success, will mark to active", m.String())
			m.lck.Lock()
			m.DB = db
			m.ping = 0
			m.Active = true
			m.lck.Unlock()
			break
		} else {
			log.E("MDb connect to %v error->%v, will retry after 5s", m.String(), err)
			time.Sleep(5 * time.Second)
		}
	}
}
Exemplo n.º 15
0
func run(args []string) {
	defer StopSrv()
	mux := http.NewServeMux()
	mux.Handle("/jsup/", NewSrvMux("/jsup", "www"))

	log.D("running server on %v", "7899")
	s = http.Server{Addr: ":7899", Handler: mux}
	err := s.ListenAndServe()
	if err != nil {
		fmt.Println(err)
	}
	// lock.Done()
}
Exemplo n.º 16
0
func ListData() error {
	var ts []TSt
	err := dbutil.DbQueryS(DbCon(), &ts, "select * from ttable where tid>?", 1)
	if err != nil {
		log.D("Err:%v", err.Error())
		return err
	}
	if len(ts) < 1 {
		log.D("Err:%v", "NOT DATA")
		return errors.New("NOT DATA")
	}
	iid, err := dbutil.DbInsert(DbCon(), "insert into ttable(tname,titem,tval,status,time) values('name','item','val','N',now())")
	if err != nil {
		log.D("Err:%v", err.Error())
		return err
	}
	_, err = dbutil.DbUpdate(DbCon(), "delete from ttable where tid=?", iid)
	if err != nil {
		log.D("Err:%v", err.Error())
		return err
	}
	return nil
}
Exemplo n.º 17
0
func FuncListBankQuestion(uid, bankId int64) ([]QUESTION, error) {
	rs := []QUESTION{}
	usrFilter := ""
	args := []interface{}{bankId, bankId}
	if uid != 0 {
		usrFilter = " and b.uid=?"
		args = append(args, uid)
	}
	conn := dbMgr.DbConn()
	sql_ := `select q.TID, q.NAME, q.BANK_ID, q.PID, q.TAG, q.DESCRIPTION, q.DURATION, q.SCORE, q.Q_ANALYZE, q.TYPE,q.Q_OPTION, q.ANSWER, q.UID, q.UNAME,q2b.score,q2b.ext,q2b.tid,q2b.seq
	from ebs_question q join ebs_q2b q2b on q2b.bank_id=? and q2b.q_id=q.tid join ebs_bank b on b.tid=?` + usrFilter + ` order by q2b.seq asc`
	log.D("sql:%s", sql_)
	if rows, err := conn.Query(sql_, args...); err != nil {
		return rs, err
	} else {
		columns := []string{"TID", "NAME", "BANK_ID", "PID", "TAG", "DESCRIPTION", "DURATION", "SCORE", "Q_ANALYZE", "TYPE",
			"Q_OPTION", "ANSWER", "UID", "UNAME", "SCORE"}
		for rows.Next() {
			vals := []interface{}{}
			b := QUESTION{}
			for _, v := range columns {
				(&b).GetFieldByColumn(v, &vals)
			}
			var ext sql.NullString
			var q2bId int64
			var q2bSeq sql.NullInt64
			vals = append(vals, &ext, &q2bId, &q2bSeq)
			if err := rows.Scan(vals...); err != nil {
				log.E("scan err:%v", err)
			}
			b.Q2bId = q2bId
			b.Q2bSeq = q2bSeq.Int64
			if ext.String != "" {
				extParse := EXT{}
				json.Unmarshal([]byte(ext.String), &extParse)
				b.SCORE = &extParse.Score
				b.DURATION = &extParse.Duration
				b.Ext = extParse
			}
			rs = append(rs, b)
		}
	}
	return rs, nil
}
Exemplo n.º 18
0
func (v *VideoProc) SrvHTTP(hs *routing.HTTPSession) routing.HResult {
	var tid string
	var duration int64
	err := hs.ValidCheckVal(`
		tid,R|S,L:0;
		duration,R|I,R:0;
		`, &tid, &duration)
	if err != nil {
		return hs.Printf("valid argument error by %v", err)
	}
	var reader = bufio.NewReader(hs.R.Body)
	var frame = util.Map{}
	for {
		bys, err := util.ReadLine(reader, 102400, false)
		if err != nil {
			break
		}
		line := strings.Trim(string(bys), " \n\t")
		lines := strings.SplitN(line, "=", 2)
		lines[0] = strings.Trim(lines[0], " \t")
		if len(lines) < 2 {
			frame[lines[0]] = ""
		} else {
			frame[lines[0]] = lines[1]
		}
		if lines[0] != "progress" {
			continue
		}
		var progress Progress
		frame.ToS(&progress)
		var rate = float64(progress.OutTimeMs) / float64(duration)
		if int(rate*1000)%10 == 0 {
			log.D("NofityProc receive rate(%v%%) to task(%v),duration(%v)", int(rate*100), tid, duration)
		}
		err = v.NotifyProc(tid, rate)
		if err != nil {
			return hs.Printf("notify procgress to task(%v) error by %v", tid, err)
		}
		frame = util.Map{}
	}
	return hs.Printf("%v", "DONE")
}
Exemplo n.º 19
0
func (a *AbsV) Build(dtcm *dtm.DTCM_S, id, info interface{}, args ...interface{}) (interface{}, interface{}, []interface{}, error) {
	var src = fmt.Sprintf("%v", args[0])
	video, err := ParseVideo(filepath.Join(a.WDir, src))
	if err != nil {
		err = util.Err("AbsV parse video by src(%v) error->%v", src, err)
		log.E("%v", err)
		return nil, nil, nil, err
	}
	video.Info = info
	video.Alias = a.Alias
	var mv, _ = util.Json2Map(util.S2Json(video))
	var tw, th, dur = video.Width, video.Height, int64(video.Duration * 1000000)
	var dst interface{}
	if len(args) > 1 {
		dst = args[1]
	} else {
		dst = strings.TrimSuffix(src, filepath.Ext(src))
	}
	log.D("AbsV adding task by src(%v),width(%v),height(%v),duration(%v)", src, tw, th, dur)
	return id, mv, []interface{}{
		src, dst, tw, th, dur,
	}, nil
}
Exemplo n.º 20
0
func Args_m(rc *impl.RCM_Cmd) (interface{}, error) {
	log.D("run_rc_s doing Args_m->%v", util.S2Json(rc.Map))
	return rc.Map, nil
}
Exemplo n.º 21
0
Arquivo: srv.go Projeto: tomlovzki/ebs
func run(args []string) {
	defer StopSrv()
	cfile := "conf/ebs.properties"
	if len(args) > 1 {
		cfile = args[1]
	}
	fmt.Println("Using config file:", cfile)
	err := conf.Cfg.InitWithFilePath(cfile)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	uap_conf.Cfg = conf.Cfg

	//init js conf
	conf.JsConf()

	log.I("Config:\n%v", conf.Cfg.Show())
	//test connect
	if len(conf.DbConn()) < 1 {
		fmt.Println("DB_CONN is not exist in config")
		return
	}

	// uri := "mongodb://*****:*****@192.168.2.30:27017/fs"
	// dbName := "fs"
	//	err = trak.DbInit(conf.TRACE_DB_CONN(), conf.TRACE_DB())
	//	if err != nil {
	//		panic(fmt.Sprintf("connect mongodb err %v", err.Error()))
	//	}

	dbMgr.Init("mysql", conf.DbConn())
	uap.InitDb(dbMgr.DbConn)
	usr.CheckUcs(dbMgr.DbConn())

	if err := nets.RedirectLog(conf.LOG_ADDR(), conf.LOG_PORT(), conf.LOG_KEY(), true); err != nil {
		fmt.Println("remote log error:", err)
	}
	sinfo := `{"description": "ebs接口文档",
    "version": "1.0.0",
    "title": "ebs接口文档"
    }`
	infoParse := map[string]interface{}{}
	json.Unmarshal([]byte(sinfo), &infoParse)
	go_swagger.NewH().InitSwagger(go_swagger.Swagger{
		SwaggerVersion: "2.0",
		Info:           infoParse,
		Host:           "ebs2.dev.jxzy.com",
		BasePath:       "",
		Schemes:        []string{"http"},
	}).AddTag(go_swagger.Tag{Name: "answer", Description: "作答相关接口"})

	//
	//
	mux := http.NewServeMux()
	mux.Handle("/", NewSrvMux(mux, "", "www"))
	log.D("running server on %s", conf.ListenAddr())
	s := http.Server{Addr: conf.ListenAddr(), Handler: mux}
	err = s.ListenAndServe()
	if err != nil {
		fmt.Println(err)
	}
}
Exemplo n.º 22
0
Arquivo: mdb.go Projeto: Centny/ffcm
//delete task to db
func (m *MdbH) Del(t *dtm.Task) error {
	log.D("MdbH delete task by id(%v)", t.Id)
	return m.C().RemoveId(t.Id)
}
Exemplo n.º 23
0
Arquivo: mdb.go Projeto: Centny/ffcm
//add task to db
func (m *MdbH) Add(t *dtm.Task) error {
	log.D("MdbH add task by id(%v)", t.Id)
	t.Time = util.Now()
	return m.C().Insert(t)
}
Exemplo n.º 24
0
//查看题库题目,不显示题目答案
func FuncListBankQuestion2(bankId int64, parse common.ListParam, aid int64) ([]QUESTION, common.Pagiation, error) {
	rs := []QUESTION{}
	args := []interface{}{bankId}
	args = append(args, aid)

	//	answerFilter := ""
	//	if aid!=0{
	//		answerFilter = " and a.answer_key=?"
	//	}
	statusFilter := ""
	//1答对,0答错,-1未答
	if parse.Status != "" {
		statusFilter = " and a.add1=?"
		s := parse.Status
		if parse.Status == "-1" {
			statusFilter = " and a.status=?"
			s = "N"
		}
		args = append(args, s)
	}

	typeFilter := ""
	if parse.Type != 0 {
		typeFilter = " and q.type=?"
		args = append(args, parse.Type)
	}
	if parse.Pa.Pn < 1 || parse.Pa.Ps < 1 {
		parse.Pa.Pn = 1
		parse.Pa.Ps = 10
	}
	start := (parse.Pa.Pn - 1) * parse.Pa.Ps
	end := parse.Pa.Ps

	conn := dbMgr.DbConn()
	tx, err := conn.Begin()
	if err != nil {
		return rs, parse.Pa, err
	}
	sql_ := fmt.Sprintf(`select SQL_CALC_FOUND_ROWS q.TID, q.NAME, q.BANK_ID, q.PID, q.TAG, q.DESCRIPTION, q.DURATION, q.SCORE, q.Q_ANALYZE, q.TYPE,q.Q_OPTION, q.UID, q.UNAME,q2b.score,q2b.ext,q2b.tid,q2b.seq,q.desc2,a.tid,a.status,a.content,a.paper_snapshot,a.answer_snapshot from
	ebs_answer a left join ebs_question q on q.tid=a.qid left join ebs_q2b q2b on q2b.tid=a.q2b_id and q2b.bank_id=?
	where a.answer_key=? %s order by q2b.seq asc limit %d,%d`, statusFilter+typeFilter, start, end)
	if aid == 0 {
		sql_ = fmt.Sprintf(`select SQL_CALC_FOUND_ROWS q.TID, q.NAME, q.BANK_ID, q.PID, q.TAG, q.DESCRIPTION, q.DURATION, q.SCORE, q.Q_ANALYZE, q.TYPE,q.Q_OPTION, q.UID, q.UNAME,q2b.score,q2b.ext,q2b.tid,q2b.seq,q.desc2,a.tid,a.status,a.content,a.paper_snapshot,a.answer_snapshot
	from ebs_question q join ebs_q2b q2b on q2b.bank_id=? and q2b.q_id=q.tid left join ebs_answer a on a.answer_key=? and a.q2b_id=q2b.tid where 1=1 %s order by q2b.seq asc limit %d,%d`, statusFilter+typeFilter, start, end)
	}
	log.D("%v", sql_)
	if rows, err := tx.Query(sql_, args...); err != nil {
		tx.Commit()
		return rs, parse.Pa, err
	} else {
		columns := []string{"TID", "NAME", "BANK_ID", "PID", "TAG", "DESCRIPTION", "DURATION", "SCORE", "Q_ANALYZE", "TYPE",
			"Q_OPTION", "UID", "UNAME", "SCORE"}
		for rows.Next() {
			vals := []interface{}{}
			b := QUESTION{}
			for _, v := range columns {
				(&b).GetFieldByColumn(v, &vals)
			}
			var ext, desc2, aStatus, aContent, paperSnapshot, answerSnapshot sql.NullString
			var q2bId sql.NullInt64
			var q2bSeq, aIdRes sql.NullInt64
			vals = append(vals, &ext, &q2bId, &q2bSeq, &desc2, &aIdRes, &aStatus, &aContent, &paperSnapshot, &answerSnapshot)
			if err := rows.Scan(vals...); err != nil {
				log.E("scan err:%v", err)
			}
			qParse := QUESTION{}
			json.Unmarshal([]byte(paperSnapshot.String), &qParse)
			if qParse.Tid != nil {
				log.D("qParse:%v", qParse.ToString())
				b = qParse
				bb, _ := json.Marshal(qParse.Ext)
				ext.String = string(bb)
			}

			b.Q2bId = q2bId.Int64
			b.Q2bSeq = q2bSeq.Int64
			if b.TYPE != nil {
				if *b.TYPE == 35 {
					b.DESCRIPTION = &desc2.String
				}
			}
			if aid != 0 {
				b.Extra = map[string]interface{}{"aid": aIdRes.Int64, "aStatus": aStatus.String, "aContent": aContent.String}
			}
			if ext.String != "" {
				extParse := EXT{}
				json.Unmarshal([]byte(ext.String), &extParse)
				b.SCORE = &extParse.Score
				b.DURATION = &extParse.Duration
				b.Ext = extParse
			}
			rs = append(rs, b)
		}
	}

	if err := tx.QueryRow(`select FOUND_ROWS()`).Scan(&parse.Pa.Total); err != nil {
		tx.Commit()
		return rs, parse.Pa, err
	}
	tx.Commit()
	return rs, parse.Pa, nil
}
Exemplo n.º 25
0
func exit(hs *routing.HTTPSession) routing.HResult {
	log.D("receiving exit command...")
	StopSrv()
	return hs.MsgRes("SUCCESS")
}
Exemplo n.º 26
0
//客观题批改
func correct(aId int64) (string, error) {
	var hasSubjective bool = false
	var totalScore float64
	sql_ := "select content,type,qid,paper_id,begin,q2b_id from ebs_answer where tid=?"
	var conn *sql.DB = dbMgr.DbConn()
	var content, type_ sql.NullString
	var qid, pId, begin, q2bId sql.NullInt64
	if err := conn.QueryRow(sql_, aId).Scan(&content, &type_, &qid, &pId, &begin, &q2bId); err != nil {
		return "", err
	}

	var qAnswerMap = make(map[string]string)
	var qAnswerMap2 = make(map[string]string)
	var qAnswerMap3 = make(map[string]string)

	//如果是一道题目
	if type_.String == "10" {
		sql_ := `select q.tid,q.answer,q2b.seq,q2b.ext,q.type from ebs_question q join ebs_q2b q2b on q2b.q_id=q.tid where q2b.tid=?`
		var v1 sql.NullInt64
		var v2 sql.NullString
		var v3 sql.NullString
		var v4, v5 sql.NullString
		if err := conn.QueryRow(sql_, q2bId.Int64).Scan(&v1, &v2, &v3, &v4, &v5); err != nil {
			return "", err
		} else {
			if v5.String == "40" {
				//如果是主观题
				hasSubjective = true
			}
			s_qId := fmt.Sprintf("%d", v1.Int64)
			qAnswerMap[s_qId] = v2.String
			qAnswerMap2[s_qId] = v4.String
			qAnswerMap3[s_qId] = v5.String
		}
	}
	//如果是一张试卷
	if type_.String == "20" {
		//获取试卷中的所有客观题题目
		cnt := 0
		if conn.QueryRow(`select count(*) from ebs_question q join ebs_p2q p2q on (p2q.qid=q.tid or q.pid=p2q.qid) and p2q.paper_id=? where q.type=40`, pId.Int64).Scan(&cnt); cnt != 0 {
			hasSubjective = true
		}

		//从analyze_snapshot字段中查找客观题解析
		sql_analyze := `select analyze_snapshot from ebs_answer where tid=?`
		var s sql.NullString
		if err := conn.QueryRow(sql_analyze, aId).Scan(&s); err != nil {
			return "", err
		} else {
			m := []map[string]interface{}{}
			//如果analyze_snapshot不为空
			if s.String != "" {
				json.Unmarshal([]byte(s.String), &m)
				for _, v := range m {
					s_qId := fmt.Sprintf("%v", v["v1"])
					qAnswerMap[s_qId] = fmt.Sprintf("%v", v["v2"])
					qAnswerMap2[s_qId] = fmt.Sprintf("%v", v["v4"])
					qAnswerMap3[s_qId] = fmt.Sprintf("%v", v["v5"])
				}
			} else {
				//从题目中查找解析
				sql_ := `select q.tid,q.answer,p2q.seq,p2q.ext,q.type from ebs_question q join ebs_p2q p2q on (p2q.qid=q.tid or q.pid=p2q.qid) and p2q.paper_id=? where q.type>=10 and q.type<=35`
				if rows, err := conn.Query(sql_, pId.Int64); err != nil {
					return "", err
				} else {
					for rows.Next() {
						var v1 sql.NullInt64
						var v2 sql.NullString
						var v3 sql.NullString
						var v4, v5 sql.NullString
						rows.Scan(&v1, &v2, &v3, &v4, &v5)
						s_qId := fmt.Sprintf("%d", v1.Int64)
						qAnswerMap[s_qId] = v2.String
						qAnswerMap2[s_qId] = v4.String
						qAnswerMap3[s_qId] = v5.String
					}
				}
			}
		}

	}

	//如果是题库作答
	if type_.String == "30" {
		sql_ := "select count(*) from ebs_answer where answer_key=? and status='REMARKING'"
		n := 0
		if conn.QueryRow(sql_, aId).Scan(&n); n > 0 {
			hasSubjective = true
		}
		conn.QueryRow("select sum(score) from ebs_answer where status='REMARKED' and answer_key=?", aId).Scan(&totalScore)
	}
	parse := []ANSWER2{}
	if err := json.Unmarshal([]byte(content.String), &parse); err != nil {
		return "", err
	}
	for i, v := range parse {
		s_qId := fmt.Sprintf("%v", v.QId)
		qAnswer := qAnswerMap[s_qId]
		s_ext := qAnswerMap2[s_qId]
		s_qType := qAnswerMap3[s_qId]
		ext := EXT{}
		json.Unmarshal([]byte(s_ext), &ext)
		qAnswerParse := [][]Q_ANSWER_ITEM{}
		if err := json.Unmarshal([]byte(qAnswer), &qAnswerParse); err != nil {
			log.D("qId为%s的题目答案格式错误,%v,%s", s_qId, err, qAnswer)
			parse[i].Msg = fmt.Sprintf("qId为%s的题目答案格式错误,%v,%s", s_qId, err, qAnswer)
			continue
			//			return err
		}
		if len(qAnswerParse) == 0 {
			log.D("qId为%s的题目没有答案", s_qId)
			parse[i].Msg = fmt.Sprintf("qId为%s的题目没有答案", s_qId)
			continue
		}
		if err := match(&(parse[i]), qAnswerParse, ext, s_qType); err != nil {
			return "", err
		} else {
			totalScore += (parse[i]).Score
		}
	}
	b, _ := json.Marshal(parse)
	//	now := time.Now().Unix()
	//	duration := now - begin.Int64
	status := "REMARKED"
	if hasSubjective {
		status = "REMARKING"
	}
	var add1 int64
	if len(parse) != 0 {
		add1 = parse[0].Right
	}
	if _, err := conn.Exec("update ebs_answer set score=?,content=?,status=?,add1=? where tid=?", totalScore, string(b), status, add1, aId); err != nil {
		return "", err
	}
	return status, nil
}
Exemplo n.º 27
0
func Args_s(rc *impl.RCM_Cmd) (interface{}, error) {
	log.D("run_rc_s doing Args_s->%v", string(rc.Data()))
	return rc.StrVal("val"), nil
}