def getRiderWorkDays(self): # 이 부분은 배달원의 업무 현황으로 사용될 수 있다 rdic = {} for r in self.order_df['DelivererID'].unique(): dftm = self.order_df[self.order_df['DelivererID'] == r] rdic[r] = dftm['Date'].unique() fig = plt.figure(figsize=(20, 15)) ax = fig.add_subplot(111) ax.grid(which='minor', axis='y') rlabel = [] rloop = 0 for r in rdic: ax.scatter(rdic[r], [rloop for i in range(len(rdic[r]))], label=r, marker='s', c='gray') rloop += 1 rlabel.append(r) ax.set_yticks([i for i in range(len(rdic))], minor=True) ax.set_yticklabels(rlabel, minor=True) ax.set_xlim(utils.parseDate('2015-06-15 00:00'), utils.parseDate('2015-11-02 00:00')) ax.set_ylim(-1, len(rdic)) ax.set_xlabel('Date') ax.set_ylabel('Deliverer ID') return ax
def radarRead(path=None): """Reads radar.dat file **Args**: * [**path**] (str): path to radar.dat file; defaults to RST environment variable SD_RADAR **Returns**: * A dictionary with keys matching the radar.dat variables each containing values of length #radars. **Example**: :: radars = pydarn.radar.radarRead() written by Sebastien, 2012-09 """ import shlex import os, sys from datetime import datetime from utils import parseDate # Read file try: if path: pathOpen = os.path.join(path, 'radar.dat') else: pathOpen = os.environ['SD_RADAR'] file_net = open(pathOpen, 'r') data = file_net.readlines() file_net.close() except: print 'radarRead: cannot read {}: {}'.format(pathOpen, sys.exc_info()[0]) return None # Initialize placeholder dictionary of lists radarF = {} radarF['id'] = [] radarF['status'] = [] radarF['stTime'] = [] radarF['edTime'] = [] radarF['name'] = [] radarF['operator'] = [] radarF['hdwfname'] = [] radarF['code'] = [] radarF['cnum'] = [] # Fill dictionary with each radar.dat lines for ldat in data: ldat = shlex.split(ldat) if len(ldat) == 0: continue radarF['id'].append( int(ldat[0]) ) radarF['status'].append( int(ldat[1]) ) tmpDate = parseDate( int(ldat[2]) ) radarF['stTime'].append( datetime(tmpDate[0], tmpDate[1], tmpDate[2]) ) tmpDate = parseDate( int(ldat[3]) ) radarF['edTime'].append( datetime(tmpDate[0], tmpDate[1], tmpDate[2]) ) radarF['name'].append( ldat[4] ) radarF['operator'].append( ldat[5] ) radarF['hdwfname'].append( ldat[6] ) radarF['code'].append( ldat[7:] ) radarF['cnum'].append( len(ldat[7:]) ) # Return return radarF
def generate_psd_rows_for_batch(start_time, end_time): start_datetime = parseDate(start_time, SENSOR_DATE_TIME_FORMAT) end_datetime = parseDate(end_time, SENSOR_DATE_TIME_FORMAT) start = start_datetime while start <= end_datetime: end = start + timedelta(seconds=REFRESH_INTERVAL_SEC) psd_rows = generate_psd_rows(start, end) start = end yield psd_rows
def __init__(self): prm = param.params() df = pd.read_csv('ORDER_DATA_2.csv', header=None) df['Date'] = df[0].apply(lambda x: utils.parseDate(x.split(' ')[0])) df['UpTS'] = df.apply( lambda x: utils.putTimeinDate(x['Date'], utils.parseDate(x[4])), axis=1) df['CatchTS'] = df.apply( lambda x: utils.putTimeinDate(x['Date'], utils.parseDate(x[8])), axis=1) df['PikupTS'] = df.apply( lambda x: utils.putTimeinDate(x['Date'], utils.parseDate(x[9])), axis=1) df['DeliverTS'] = df.apply( lambda x: utils.putTimeinDate(x['Date'], utils.parseDate(x[10])), axis=1) df = df.drop([0, 4, 8, 9, 10], axis=1) df.columns = [ 'OrderID', 'pLon', 'pLat', 'dLon', 'dLat', 'DelivererID', 'Date', 'UpTS', 'CatchTS', 'PickUpTS', 'DeliverTS' ] df['CatchDelay'] = (df['CatchTS'] - df['UpTS']).apply(lambda x: x.seconds) df['PickupTravelTime'] = (df['PickUpTS'] - df['CatchTS']).apply(lambda x: x.seconds) df['DeliverTravelTime'] = (df['DeliverTS'] - df['PickUpTS']).apply(lambda x: x.seconds) df['TotalTravelTime'] = (df['DeliverTS'] - df['CatchTS']).apply(lambda x: x.seconds) df['p-dDistance'] = df.apply(lambda x: utils.lonlatDist( x['pLon'], x['pLat'], x['dLon'], x['dLat']), axis=1) df['TimeSlot1'] = df['UpTS'].apply( lambda x: utils.getTimeSlot(x, prm.MINS)) df['TimeSlot2'] = df['CatchTS'].apply( lambda x: utils.getTimeSlot(x, prm.MINS)) df['TimeSlot3'] = df['PickUpTS'].apply( lambda x: utils.getTimeSlot(x, prm.MINS)) df['TimeSlot4'] = df['DeliverTS'].apply( lambda x: utils.getTimeSlot(x, prm.MINS)) df = df[df['PickupTravelTime'] > 59] df = df[df['DeliverTravelTime'] > 59] df['pxInd'] = df['pLon'].apply( lambda x: utils.toInd(x, prm.lonMin, prm.lonTick)) df['pyInd'] = df['pLat'].apply( lambda x: utils.toInd(x, prm.latMin, prm.latTick)) df['dxInd'] = df['dLon'].apply( lambda x: utils.toInd(x, prm.lonMin, prm.lonTick)) df['dyInd'] = df['dLat'].apply( lambda x: utils.toInd(x, prm.latMin, prm.latTick)) self.order_df = df
def get_sensor_data_in_time_range(start_time, end_time): st = parseDate(start_time, SENSOR_DATE_TIME_FORMAT) et = parseDate(end_time, SENSOR_DATE_TIME_FORMAT) cursor = db.cursor() cursor.execute( """SELECT daq_id,value FROM sensor_data WHERE timestamp>=%s and timestamp<=%s order by timestamp""", (st, et)) resp = cursor.fetchall() cursor.close() return resp
def get_psd_data_in_time_range(start_time, end_time): st = parseDate(start_time, SENSOR_DATE_TIME_FORMAT) et = parseDate(end_time, SENSOR_DATE_TIME_FORMAT) cursor = db.cursor() cursor.execute( """SELECT daq_id, average_power, freqs, power_spectrum FROM psd WHERE timestamp>=%s and timestamp<=%s order by timestamp""", (st, et)) resp = cursor.fetchall() cursor.close() return resp
def channel(channelID, source): import json channelIDs = channelID.split(':') responses = {} image = None for channelID in channelIDs: url = source + '/Channels/' + channelID + '/Episodes' html = utils.GetHTML(url) response = json.loads(html) responses[channelID] = response for channelID in responses: response = responses[channelID] for item in response: try: image = item['ImageFile'] except: pass if image: thumb = THUMBPATTERN % image fanart = FANARTPATTERN % image else: thumb = ICON fanart = FANART ordered = [] download = GETTEXT(30042) for channelID in responses: response = responses[channelID] for item in response: name = item['Name'] desc = item['Description'] link = item['MediaFiles'][0]['Filename'] start = utils.parseDate(item['StartDate']) ordered.append([start, [name, desc, link]]) ordered.sort() for item in ordered: name = item[1][0] desc = item[1][1] link = item[1][2] menu = [] menu.append((download, 'XBMC.RunPlugin(%s?mode=%d&url=%s&name=%s)' % (sys.argv[0], _DOWNLOAD, link, urllib.quote_plus(name)))) addDirectoryItem(name, url=link, mode=_EPISODE, thumbnail=thumb, fanart=fanart, isFolder=False, isPlayable=True, menu=menu)
def radarRead(path=None): """Reads radar.dat file **Args**: * [**path**] (str): path to radar.dat file; defaults to RST environment variable SD_RADAR **Returns**: * A dictionary with keys matching the radar.dat variables each containing values of length #radars. **Example**: :: radars = pydarn.radar.radarRead() Written by Sebastien, 2012-09 """ import shlex import os, sys from datetime import datetime from utils import parseDate # Read file try: if path: pathOpen = os.path.join(path, 'radar.dat') else: pathOpen = os.environ['SD_RADAR'] file_net = open(pathOpen, 'r') data = file_net.readlines() file_net.close() except: print 'radarRead: cannot read {}: {}'.format(pathOpen, sys.exc_info()[0]) return None # Initialize placeholder dictionary of lists radarF = {} radarF['id'] = [] radarF['status'] = [] radarF['stTime'] = [] radarF['edTime'] = [] radarF['name'] = [] radarF['operator'] = [] radarF['hdwfname'] = [] radarF['code'] = [] radarF['cnum'] = [] # Fill dictionary with each radar.dat lines for ldat in data: ldat = shlex.split(ldat) if len(ldat) == 0: continue radarF['id'].append( int(ldat[0]) ) radarF['status'].append( int(ldat[1]) ) tmpDate = parseDate( int(ldat[2]) ) radarF['stTime'].append( datetime(tmpDate[0], tmpDate[1], tmpDate[2]) ) tmpDate = parseDate( int(ldat[3]) ) radarF['edTime'].append( datetime(tmpDate[0], tmpDate[1], tmpDate[2]) ) radarF['name'].append( ldat[4] ) radarF['operator'].append( ldat[5] ) radarF['hdwfname'].append( ldat[6] ) radarF['code'].append( ldat[7:] ) radarF['cnum'].append( len(ldat[7:]) ) # Return return radarF
def judge(message, qid, name, group): if message.strip()[:2].lower() != 'ns': # 如果开头不是ns那么一切免谈,无事发生 return ############## Main ################### command = message.strip()[2:].strip() # 把ns去掉后面开始分割这个指令 commandPart = command.split() # 按照空格进行分割,但是后续要看看是不是加入更多的防傻判断 servername = init.SERVER try: entrance = commandPart[0].strip() except: entrance = '' if entrance in keyNewTeam: try: # 尝试解析参数,如果出错说明输入参数有误 date = parseDate(commandPart[1].strip()) time = parseTime(commandPart[2].strip()) dungeon = commandPart[3].strip() comment = commandPart[4].strip() assert (date != -1) assert (time != -1) except: mirai.throwError(target=group, errCode=100) return try: # 尝试解析是否指定了黑名单 useBlackList = commandPart[5].strip() except: useBlackList = 0 leader = sql.hasLeader(qid) if leader == -1: msg = '权限错误,请先申请成为团长' else: res = sql.createNewTeam(date, time, dungeon, comment, leader, useBlackList) if res == -1: msg = '数据库错误!请联系管理员' else: msg = '开团成功,{},团队ID为{}, 集合时间{} {} {}'.format( dungeon, res, date, parseWeekday(date), time) mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT", needAT=True, ATQQ=qid) elif entrance in keyShowall: res = sql.getTeam() if not res: msg = '当前没有在开团队' mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT") return else: msg = '' for i in range(len(res)): g = res[i] msg += '{}. ID:{} {} {} {} {} {} \n'.format( str(i + 1), g['teamID'], g['leaderName'], g['dungeon'], g['startTime'], parseWeekday(g['startTime']), g['comment']) msg += '------------------- \n' mirai.sendGroupMessage(target=group, content="在开团队已经通过临时会话发给您了~如果没收到请加机器人好友", messageType="TEXT", needAT=True, ATQQ=qid) mirai.sendTempMessage(target=group, QQ=qid, content=msg, messageType="TEXT") elif entrance in keyQuery: try: teamNumber = int(commandPart[1].strip()) res = sql.getInfo(teamNumber) except: res = [] teamNumber = None if teamNumber is None or not res: msg = '输入的团队ID不存在' mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT") else: image = img.GetImg(teamNumber) if image == -1: msg = '此团队目前没有人报名' mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT") else: mirai.sendGroupMessage(target=group, content=image, messageType="Image") elif entrance in keyEnroll: msg = '' try: teamNumber = int(commandPart[1].strip()) except: msg += '缺少团队ID ' try: vocation = commandPart[2].strip() mental = sql.getMental(vocation) assert (mental != -1) # 检查心法是否存在 except: msg += '缺少角色心法或心法不存在 ' try: memberName = commandPart[3].strip() except: msg += '缺少角色名称 ' try: syana = int(commandPart[4].strip()) assert (syana == 1 or syana == 0) except: syana = 0 if msg == '': res = sql.addMember(teamNumber, qid, memberName, mental, syana) if res == 0: team = sql.getInfo(teamNumber) msg = '已成功报名 {} {}团长 {} {}-{}'.format(team['startTime'], team['leaderName'], team['dungeon'], vocation, memberName) elif res == -1: msg = '已经在此团队中' elif res == -3: msg = '团队不存在或已过期' else: msg = '数据库错误!请联系管理员' else: msg += '\n报团格式:ns报团 团队ID 心法 角色名\n双修心法请在报团命令最后额外加空格加1' mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT", needAT=True, ATQQ=qid) elif entrance in keyDisenroll: msg = '' try: teamNumber = int(commandPart[1].strip()) except: msg += '缺少团队ID' if msg == '': res = sql.delMember(teamNumber, qid) if res == 0: team = sql.getInfo(teamNumber) msg = '已成功取消报名 {} {}团长'.format(team['startTime'], team['leaderName']) elif res == -1: msg = '不在此团队中' elif res == -3: msg = '团队不存在或已过期' else: msg = '数据库错误!请联系管理员' mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT", needAT=True, ATQQ=qid) elif entrance in keyDeleteTeam: msg = '' try: teamNumber = int(commandPart[1].strip()) except: msg = '缺少团队ID' if msg == '': leader = sql.hasLeader(qid) if leader == -1: msg = '权限错误,请先申请成为团长' else: res = sql.delTeam(teamNumber, leader) if res == 0: msg = '团队{}已经取消'.format(teamNumber) elif res == -1: msg = '此团队不存在' elif res == -2: msg = '取消开团失败,没有该权限' else: msg = '数据库错误!请联系管理员' mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT", needAT=True, ATQQ=qid) elif entrance in keyMacro: msg = '' try: mental = sql.getMental(commandPart[1].strip()) assert (mental != -1) # 检查心法是否存在 except: msg += '缺少心法名称或心法不存在' mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT", needAT=True, ATQQ=qid) return if msg == '': try: with open(init.MACRO_PATH + str(mental), 'r') as f: lines = f.readlines() msg = ''.join(lines) except: msg = '心法文件错误!请联系管理员' mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT", needAT=True, ATQQ=qid) return mirai.sendGroupMessage(target=group, content='宏命令已经通过临时会话私发给您了,如果没收到请加机器人好友', messageType="TEXT", needAT=True, ATQQ=qid) mirai.sendTempMessage(target=group, QQ=qid, content=msg, messageType="TEXT") elif entrance in keyHelp: msg = '在线用户手册: \nhttps://www.nsrobot.life/userguide/' mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT") elif entrance in keyAuthor: msg = '致谢与授权说明: \nhttps://github.com/Hallows/nsRobot/blob/main/README.md' mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT") elif entrance in keyFormation: try: mentalName = str(commandPart[1].strip()) except: msg = '通用阵眼:田螺(会会+无视防御)\n常用外功阵眼:\n凌雪(攻会会) 鲸鱼(破无会) 剑纯(会会无)\n常用内功阵眼:\n莫问(攻会无) 大师(攻破无) 气纯(会会无) \n花间(回蓝破防) 毒经(破会会)' mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT") return mentalID = sql.getMental(mentalName=mentalName) if mentalID != -1: try: image = jx3api.getFormation(mentalID) mirai.sendGroupMessage(target=group, content=image, messageType="Image") return except: msg = '无法获得心法名称,请检查名称' mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT") elif entrance in keyDaily: if len(commandPart) > 1: servername = str(commandPart[1].strip()) msg = jx3api.getDaily(servername) if msg == 'error': mirai.sendGroupMessage(target=group, content='日常查询错误!请联系管理员', messageType="TEXT") else: mirai.sendGroupMessage(target=group, content=msg, messageType="Image") elif entrance in keyGold: if len(commandPart) > 1: servername = str(commandPart[1].strip()) msg = jx3api.getGold(servername) if msg == 'error': mirai.sendGroupMessage(target=group, content='金价查询错误!请联系管理员', messageType="TEXT") else: mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT") elif entrance in keyServer: if len(commandPart) > 1: servername = str(commandPart[1].strip()) msg = jx3api.getServer(servername) if msg == 'error': mirai.sendGroupMessage(target=group, content='服务器状态查询错误!请联系管理员', messageType="TEXT") elif msg == 'UncertainServer': mirai.sendGroupMessage(target=group, content='请输入正确的区服名!', messageType="TEXT") else: mirai.sendGroupMessage(target=group, content=msg, messageType="Image") elif entrance in keyMethod: name = '' if len(commandPart) > 1: name = str(commandPart[1].strip()) msg = jx3api.getMethod(name) if msg == 'error': mirai.sendGroupMessage(target=group, content='参数错误!或者联系管理员', messageType="TEXT") else: mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT") elif entrance in keyFlower: name = '' if len(commandPart) > 1: name = str(commandPart[1].strip()) if len(commandPart) > 2: servername = str(commandPart[2].strip()) if name == '': mirai.sendGroupMessage(target=group, content='查询口令请增加具体花类', messageType="TEXT") return msg = jx3api.getFlower(name, servername) if msg == 'error': mirai.sendGroupMessage(target=group, content='花价查询错误!请联系管理员', messageType="TEXT") else: mirai.sendGroupMessage(target=group, content=msg, messageType="Image") elif entrance in keyExam: subject = '' if len(commandPart) > 1: subject = str(commandPart[1].strip()) msg = jx3api.getExam(subject) if msg == 'error': mirai.sendGroupMessage(target=group, content='科举查询错误!请联系管理员', messageType="TEXT") else: mirai.sendGroupMessage(target=group, content=msg, messageType="Image") elif entrance in keyMedicine: if len(commandPart) == 0: msg = jx3api.GetMedicine() else: msg = jx3api.GetMedicine(commandPart[1].strip()) if msg == -1: mirai.sendGroupMessage(target=group, content="小药查询错误,请检查心法名称", messageType="TEXT") else: mirai.sendGroupMessage(target=group, content=msg, messageType="Image") elif entrance in keyBroadcast: try: teamID = commandPart[1].strip() broadMsg = commandPart[2].strip() except: mirai.throwError(target=group, errCode=100) return teamInfo = sql.getInfo(teamID=teamID) if teamInfo == []: mirai.sendGroupMessage(target=group, content="输入的团队ID不存在", messageType="TEXT") return leader = sql.hasLeader(qid) if leader == -1: mirai.sendGroupMessage(target=group, content="你还不是团长,请联系管理员", messageType="TEXT", needAT=True, ATQQ=qid) teamInfo = sql.getMember(teamID=teamID) if teamInfo == []: mirai.sendGroupMessage(target=group, content="此团队暂时无人报名", messageType="TEXT") return mirai.sendGroupMessage(target=group, content="信息开始私聊给指定团队,根据人数机器人可能无响应数分钟", messageType="TEXT") for key in teamInfo: QQ = key['QQNumber'] print('sending to {}'.format(QQ)) mirai.sendTempMessage(target=group, QQ=QQ, content=broadMsg, messageType="TEXT") Lib_Time.sleep(5) return elif entrance in keyApplyLeader: try: nickName = commandPart[1].strip() activeTime = commandPart[2].strip() except: mirai.throwError(target=group, errCode=100) return result = sql.newLeader(QQ=qid, nickName=nickName, activeTime=activeTime) if result['result'] == -1: msg = '你已经申请过了,你的团长ID是{},请等待审核'.format(result['id']) elif result['result'] == -2: msg = '你已经是团长了,别闹' else: msg = '申请成功!你的团长ID是{}请联系管理审批!'.format(result['id']) mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT", needAT=True, ATQQ=qid) elif entrance in keyAcceptLeader: try: leaderID = commandPart[1].strip() except: mirai.throwError(target=group, errCode=100) return if qid not in init.managerQQ: msg = '你不是管理员,无权批准,请检查init.py文件中的managerQQ字段确认管理员QQ号' mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT", needAT=True, ATQQ=qid) return result = sql.acceptLeader(leaderID=leaderID) if result == -1: msg = '团长ID不存在或已通过申请' else: msg = '批准成功!' mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT", needAT=True, ATQQ=qid) elif entrance in keyMyteam: try: res = sql.inTeam(qid) except: mirai.throwError(target=group, errCode=500) return if res: msg = '' for i in range(len(res)): g = res[i] msg += '{}. ID:{} 团长:{},{} {} {} {} \n'.format( str(i + 1), g['teamID'], g['leaderName'], g['dungeon'], g['startTime'], parseWeekday(g['startTime']), g['comment']) msg += '------------------- \n' print(msg) mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT", needAT=True, ATQQ=qid) return else: msg = '目前您未报名任何团队!' mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT", needAT=True, ATQQ=qid) return elif entrance in keyMyleader: try: teams = [] leaderID = sql.hasLeader(qid) if leaderID != -1: leadername = sql.getLeader(leaderID) teams = sql.getTeam() except: mirai.throwError(target=group, errCode=500) return myteams = [] if teams and leaderID != -1: for team in teams: if team['leaderName'] == leadername: myteams.append(team) if myteams: msg = "团长{},您当前的在开团队有:\n".format(leadername) for myteam in myteams: msg += "在{}的{},id为:{}\n".format(myteam['startTime'], myteam['dungeon'], myteam['teamID']) print(msg) mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT", needAT=True, ATQQ=qid) return else: msg = "团长{},您目前没有在开团队,——干点正事吧!{}!——".format( leadername, leadername) print(msg) mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT", needAT=True, ATQQ=qid) return elif leaderID == -1: msg = "别闹,你还不是团长" print(msg) mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT", needAT=True, ATQQ=qid) return else: msg = "当前没有在开团队" print(msg) mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT", needAT=True, ATQQ=qid) return else: msg = '未知指令,请通过 ns帮助 进行查看' mirai.sendGroupMessage(target=group, content=msg, messageType="TEXT", needAT=True, ATQQ=qid)
def parseStartDateTime(h5name): return parseDate(h5name.split('/')[-1].split('.')[0])