Beispiel #1
0
    def cmd_help(self, msg):
        Func.sendMessage("Available Commands:")
        for m, module in Func.getBot().modules.items():
            commands = m + ": "
            for name, target in module.commands.items():
                if name[1:2] != "@":
                    continue

                if commands != m + ": ":
                    commands += ", "

                if name[0:1] == "^":
                    name = name[1:]

                if name[-1] == "$":
                    name = name[0:-1]

                cmd = name.split(" ")

                full = ""

                for i in cmd:
                    if i[0:1] != "*" and i[0:1] != "(":
                        if full != "":
                            full += " "

                        full += i

                commands += full

            Func.sendMessage(commands)
Beispiel #2
0
 def getneighbor(self, lgrid, rgrid):
     # tmp = np.zeros(self.leftgridsize*self.neibor)
     #取出self.leftgridsize*self.neibor这么一小块的部分
     # rgrid=rgrid.reshape(-1)
     start = self.leftgridsize * (lgrid - self.neiborwidth)
     start[start <= 0] = 0
     end = start + self.leftgridsize * self.neibor
     if end[0] > self.img1.shape[0]:
         end[0] = self.img1.shape[0]
     if end[1] > self.img1.shape[1]:
         end[1] = self.img1.shape[1]
     mask = (self.leftimglabel[start[0]:end[0], start[1]:end[1]] >
             eps).reshape(-1)
     lr, lc = Func.value2index(
         self.leftimglabel[start[0]:end[0], start[1]:end[1]] - 1,
         shape=(self.lgn, self.lgn))
     lr = np.abs(lr - lgrid[0])
     lc = np.abs(lc - lgrid[1])
     rr, rc = Func.value2index(
         self.leftmatchgrid[start[0]:end[0], start[1]:end[1]] - 1,
         shape=(self.lgn, self.lgn))
     rr = np.abs(rr - rgrid[0])
     rc = np.abs(rc - rgrid[1])
     #取横轴坐标中大的
     lr[lr <= lc] = lc[lr <= lc]
     rr[rr <= rc] = rc[rr <= rc]
     num = ((lr == rr) & mask).sum()
     if self.DEBUG:
         print(lgrid, rgrid, start, end, rr.shape, lr.shape, num)
     klen = end - start
     #过滤网格不匹配的
     # return ((lr==rr).reshape(klen)*self.kernel[0:klen[0],0:klen[1]]).sum()
     return num
Beispiel #3
0
    def getMinMax(data, gs):  # get min/max az,el for 3d plot
        cordinateMin = np.max(data[0], axis=1)
        cordinateMax = np.max(data[0], axis=1)
        for item in data:
            cordinateMaxNew = np.max(item, axis=1)
            cordinateMinNew = np.min(item, axis=1)
            for i in range(6):
                if cordinateMaxNew[i] > cordinateMax[i]:
                    cordinateMax[i] = cordinateMaxNew[i]
                if cordinateMinNew[i] < cordinateMin[i]:
                    cordinateMin[i] = cordinateMinNew[i]
        xmin = min(cordinateMin[0], cordinateMin[3])
        ymin = min(cordinateMin[1], cordinateMin[4])
        zmin = min(cordinateMin[2], cordinateMin[5])
        xmax = max(cordinateMax[0], cordinateMax[3])
        ymax = max(cordinateMax[1], cordinateMax[4])
        zmax = max(cordinateMax[2], cordinateMax[5])

        xxrange = xmax - xmin
        yrange = ymax - ymin
        zrange = zmax - zmin

        ab = gs.B - gs.A

        abScale = [ab[0] / xxrange, ab[1] / yrange,
                   ab[2] / zrange]  #scale axis equal
        az = -90 - Func.degree(math.atan(abScale[0] / abScale[1]))
        el = -np.sign(ab[1]) * Func.degree(
            math.atan(abScale[2] / math.sqrt(abScale[0]**2 + abScale[1]**2)))
        return [[xmin, xmax, ymin, ymax, zmin, zmax], [az, el]]
	def run(self, type=0):
		if type == 0:
			self.computescoreandthre()  # 计算出TrueMatcher
			# self.TrueMatches[np.arange(1,100,2),np.arange(1,100,2)]=1
			# return self.getTrueMatch()
			ssds = self.drawTrueMatch()
			Func.imshow(ssds)
Beispiel #5
0
    def _calCordinate(self):
        A = np.array([self.A_X, self.A_Y, self.A_Z])
        Ap = np.array([self.Ap_X, self.Ap_Y, self.Ap_Z])
        F = np.array([self.F_X, self.F_Y, self.F_Z])
        Fp = np.array([self.Fp_X, self.Fp_Y, self.Fp_Z])
        F2 = np.array([self.F_X2, self.F_Y2, self.F_Z2])
        Fp2 = np.array([self.Fp_X2, self.Fp_Y2, self.Fp_Z2])
        B = Func.point(self.A, self.Ap, self.Distance)
        E = Func.point(self.F, self.Fp, self.FE)
        E2 = Func.point(self.F2, self.Fp2, self.FE2)

        if self.MechanicType == 'Center':
            A2 = A.copy()
            Ap2 = Ap.copy()
            A_X2 = self.A_X
            A_Y2 = self.A_Y
            A_Z2 = self.A_Z
            Ap_X2 = self.Ap_X
            Ap_Y2 = self.Ap_Y
            Ap_Z2 = self.Ap_Z
            errorP.A_X2 = self.errorP.A_X
            errorP.A_Y2 = self.errorP.A_Y
            errorP.A_Z2 = self.errorP.A_Z
            errorP.Ap_X2 = self.errorP.Ap_X
            errorP.Ap_Y2 = self.errorP.Ap_Y
            errorP.Ap_Z2 = self.errorP.Ap_Z
            errorN.A_X2 = self.errorN.A_X
            errorN.A_Y2 = self.errorN.A_Y
            errorN.A_Z2 = self.errorN.A_Z
            errorN.Ap_X2 = self.errorN.Ap_X
            errorN.Ap_Y2 = self.errorN.Ap_Y
            errorN.Ap_Z2 = self.errorN.Ap_Z
            Distance2 = (self.Distance + self.Distance2)
            B2 = Func.point(A2, Ap2, Distance2)
        else:
            A2 = E.copy()
            Ap2 = F.copy()
            A_X2 = self.E_X
            A_Y2 = self.E_Y
            A_Z2 = self.E_Z
            Ap_X2 = self.F_X
            Ap_Y2 = self.F_Y
            Ap_Z2 = self.F_Z
            errorP.A_X2 = self.errorP.Fp_X
            errorP.A_Y2 = self.errorP.Fp_Y
            errorP.A_Z2 = self.errorP.Fp_Z
            errorP.Ap_X2 = self.errorP.F_X
            errorP.Ap_Y2 = self.errorP.F_Y
            errorP.Ap_Z2 = self.errorP.F_Z
            errorN.A_X2 = self.errorN.Fp_X
            errorN.A_Y2 = self.errorN.Fp_Y
            errorN.A_Z2 = self.errorN.Fp_Z
            errorN.Ap_X2 = self.errorN.F_X
            errorN.Ap_Y2 = self.errorN.F_Y
            errorN.Ap_Z2 = self.errorN.F_Z
            B2 = Func.point(A2, Ap2, Distance2)
Beispiel #6
0
def cnnnet():
    learnrate = 1e-4
    out = 120
    # 存name。模型可取出
    x_images = tf.placeholder(tf.float32, [None, 224, 224, 3], name='input_x')
    # y_ = tf.placeholder(tf.float32, [None, 224, 224, 3])
    y_ = tf.placeholder(tf.float32, shape=[None, out], name='input_y')
    #drop out
    keep_prob = tf.placeholder(tf.float32, name='keep_prob')
    #batchsize
    batch_size = tf.placeholder(tf.float32, name='batch_size')
    vgg = vgg16(x_images)
    with tf.name_scope('softmax_layer') as scope:
        # 直接在这里取最后一层全连接,使用softmax,自己定义loss函数,进行训练
        sw = tf.Variable(tf.truncated_normal([4096, out],
                                             dtype=tf.float32,
                                             stddev=1e-1),
                         name='weights')
        sb = tf.Variable(tf.constant(1.0, shape=[out], dtype=tf.float32),
                         trainable=True,
                         name='biases')
        fc2_drop = tf.nn.dropout(vgg.fc2, keep_prob)
        fc3l = tf.nn.bias_add(tf.matmul(fc2_drop, sw), sb)
        # parameters += [fc3w, fc3b]
        # softmax多分类器
        y_conv = tf.nn.softmax(fc3l)
        # 防止在0log(0)出现Nan

        cross_entropy = -(
            tf.reduce_sum(y_ * tf.log(tf.clip_by_value(y_conv, 1e-10, 1.0))) /
            batch_size)  # 定义交叉熵为loss函数,应该每次除以batch的深度,因为batch可能会不一样多
        train_step = tf.train.AdamOptimizer(learnrate).minimize(
            cross_entropy)  # 调用优化器优化
        correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
        #保存参数到集合,方便模型取出
        tf.add_to_collection('pred_network', y_conv)
        tf.add_to_collection('accuracy', accuracy)
        tf.add_to_collection('loss', cross_entropy)
    # sess.run(tf.global_variables_initializer())  # 变量初始化
    # vgg.load_weights('../../../include_data/vgg_npz/vgg16_weights.npz', sess)

    # 记录日志
    with tf.name_scope('log') as scope:
        #vgg.fc1
        Func.variable_summaries(vgg.fc1, 'vgg_fc1')
        #vgg.fc2
        Func.variable_summaries(vgg.fc2, 'vgg_fc2')
        # 首先再源码中加入需要跟踪的变量:
        tf.summary.scalar("loss", cross_entropy)  # 损失函数值
        tf.summary.scalar("accuracy", accuracy)  # 损失函数值
        # )然后定义执行操作:
        merged_summary_op = tf.summary.merge_all()
        # 再session中定义保存路径:
    return train_step, accuracy, cross_entropy, y_conv, vgg, x_images, y_, keep_prob, batch_size, merged_summary_op
    def test(self):
	    self.setparam()
	    lens = len(self.matches)
	    kp1r = np.zeros([lens]).astype(np.int32)
	    kp1c = np.zeros([lens]).astype(np.int32)
	    kp2r = np.zeros([lens]).astype(np.int32)
	    kp2c = np.zeros([lens]).astype(np.int32)
	    self.leftgridsize = np.array([self.grid1h, self.grid1w])
	    self.rightgridsize = np.array([self.grid2h, self.grid2w])
	    self.leftlabel = (np.arange(1, self.rows1 ** 2 + 1).reshape(self.rows1, self.rows1))\
		    .repeat(self.leftgridsize[0],0)\
		    .repeat(self.leftgridsize[1], 1).astype(np.int32)
	    self.rightlabel = (np.arange(1, self.rows2 ** 2 + 1).reshape(self.rows2, self.rows2))\
		    .repeat(self.rightgridsize[0],0)\
		    .repeat(self.rightgridsize[1], 1).astype(np.int32)
	    grid1=np.zeros(self.rows1**2)
	    # 用于卷积计算阈值
	    leftsize = self.img1.shape[:2]
	    rightsize = self.img2.shape[:2]
	    self.leftimg = np.zeros(leftsize)
	    self.rightimg = np.zeros(rightsize)
	    for i in range(lens):
		    pt1 = np.array(self.kp1[self.matches[i].queryIdx].pt)
		    pt2 = np.array(self.kp2[self.matches[i].trainIdx].pt)
		    kp1r[i] = int(pt1[1])
		    kp1c[i] = int(pt1[0])
		    kp2r[i] = int(pt2[1])
		    kp2c[i] = int(pt2[0])
		    id1, id2 = self.getRegion(self.matches[i], 1)
		    id11=self.leftlabel[kp1r[i], kp1c[i]]-1
		    id22=self.rightlabel[kp2r[i], kp2c[i]]-1
		    if id1!=id11 or id2!=id22:
			    print("error:\nid1=%d but id11=%d \nid2=%d but id22=%d"%(id1,id11,id2,id22))
		    grid1[id1]+=1
		    self.leftimg[(kp1r[i],kp1c[i])] =self.leftimg[(kp1r[i],kp1c[i])]+ 1
		    self.rightimg[(kp2r[i], kp2c[i])] = self.rightimg[(kp2r[i], kp2c[i])] + 1
	    kp1list = (kp1r,kp1c)
	    kp2list = (kp2r,kp2c)
	    if (self.leftimg>1).sum()>0:
		    print('it is one to more!')
	    if(self.rightimg > 1).sum() > 0:
	        print('it is more to one!')
	    
	    filter=np.ones(shape=self.leftgridsize)
	    self.leftgridkpoints= Func.conv2withstride(self.leftimg, filter, stride=self.leftgridsize, start=None, gridnum=self.rows1)
	    self.testimg=np.zeros(shape=(self.img1h,self.img1w))
	    for i in range(self.img1h):
		    for j in range(self.img1w):
			    id1 = (math.floor((j % self.img1w) / self.grid1w) + math.floor(
				    (i % self.img1h) / self.grid1h) * self.rows1)
			    self.testimg[i,j]=id1
	    Func.imagesc(grid1.reshape(self.rows1, self.rows1) - self.leftgridkpoints, 'GMS score')
	    Func.imagesc(self.testimg - self.leftlabel, 'GMS-GGF label testimg')
Beispiel #8
0
def gameLoop():
    pygame.init()
    pygame.font.init()
    #pygame.mixer.init()

    #pygame.mixer.music.load("audio/halo_themes.wav")
    #pygame.mixer.music.play(-1)

    invalids = tuple(invalids_func())

    for y in range(0, screen.get_height(), 32):
        for x in range(0, screen.get_width(), 32):
            if Tile.total_tiles in invalids:
                Tile(x, y, 'solid')
            else:
                Tile(x, y, 'empty')

    #set time
    #clock = pygame.time.Clock()
    FPS = 24
    total_frames = 0

    background = pygame.image.load('images/Background.png')
    player = Player(64, 128)

    while player.health > 1:

        screen.blit(background, (0, 0))

        Enemy.spawn(total_frames, FPS)
        Enemy.update(screen, player)

        player.movement()

        Bullet.super_massive_jumbo_loop(screen)

        A_Star(screen, player, total_frames, FPS)
        interaction(screen, player)
        player.draw(screen)

        Func.text_to_screen(screen, "Health {0}".format(player.health), 0, 0)

        pygame.display.flip()
        clock.tick(FPS)
        total_frames += 1

        if player.health <= 0:
            sleep(2)
            screen.blit(pygame.image.load("images/End.png"), (0, 0))
            pygame.display.update()
            break

    sleep(4)
 def computescoreandthre(self):
     # 计算阈值
     self.thre = Func.conv2withstride(self.leftimg,
                                      self.kernel,
                                      stride=self.stride,
                                      start=self.start,
                                      gridnum=self.lgn)
     De = self.neibor**2
     self.thre = self.TreshFactor * np.sqrt(self.thre / De)  # 阈值计算公式
     if self.DEBUG:
         print("self.leftimg:max:%f,min:%f" %
               (self.leftimg.max(), self.leftimg.min()))
         print("self.thre:max:%f,min:%f" %
               (self.thre.max(), self.thre.min()))
         print("self.thre:max:%f,min:%f" %
               (self.thre.max(), self.thre.min()))
     # 计算打分
     self.score = np.zeros((self.lgn, self.lgn))
     self.lgshape = (self.lgn, self.lgn)
     # nnb=1
     for i in range(self.lgn):  # r
         for j in range(self.lgn):  # c
             if self.thre[i, j] == 0:
                 continue
             leftvalue = Func.index2value((i, j), self.lgshape) + 1
             bestmatchgrid = self.leftmatchgrid[self.leftimglabel ==
                                                leftvalue]
             if bestmatchgrid.size < 1:
                 continue  # 点数小于阈值则不计算,默认为不匹配
             number, n_counts = np.unique(bestmatchgrid, return_counts=True)
             rbestindex = number[np.argsort(n_counts)[-1]]
             index = (self.leftimglabel == leftvalue) & (self.leftmatchgrid
                                                         == rbestindex)
             neiborsindex = (((self.leftimglabel - self.leftmatchgrid)
                              == (leftvalue - rbestindex))
                             & self.leftimg.astype(np.bool)).astype(
                                 np.float32)
             neiborsindexconv = Func.conv2withstride(neiborsindex,
                                                     self.kernel,
                                                     stride=self.stride,
                                                     start=self.start,
                                                     gridnum=self.lgn)
             self.score[i, j] = neiborsindexconv[i, j]
             if self.DEBUG:
                 print(
                     "calc grid(%d,%d)\n thre=%f,index.sum=%d,neiborsindex.sum=%d,score=%f"
                     % (i, j, self.thre[i, j], index.sum(),
                        neiborsindex.sum(), self.score[i, j]))
             if neiborsindexconv[i, j] < self.thre[i, j]:
                 continue
             # nnb += 1
             self.TrueMatches += index
Beispiel #10
0
def FilDelta(n_clicks, value1, lid, children):
    if (n_clicks != None) & (value1 != None) & (lid != None) & (children !=
                                                                None):
        optionsInfo_C = pd.DataFrame(
            json.loads(json.loads(children)['optionsInfo_C']))
        optionsInfo_P = pd.DataFrame(
            json.loads(json.loads(children)['optionsInfo_P']))
        optionsInfo = pd.DataFrame(
            json.loads(json.loads(children)['optionsInfo']))

        optionsInfo = optionsInfo.sort_values('STRIKE_PRC')
        optionsInfo_C = optionsInfo_C.sort_values('STRIKE_PRC')
        optionsInfo_P = optionsInfo_P.sort_values('STRIKE_PRC')

        optionsInfo.index = range(len(optionsInfo))
        optionsInfo_C.index = range(len(optionsInfo_C))
        optionsInfo_P.index = range(len(optionsInfo_P))

        # lldate=list(set(optionsInfo.EXPIR_DATE.values))
        # lldate.sort()
        lid.sort()
        lldate = lid
        Selec_C = Func.DeltaStreikFilter(optionsInfo_C, lldate, value1)
        Selec_P = Func.DeltaStreikFilter(optionsInfo_P, lldate, value1)

        callRIC = pd.DataFrame(Selec_C).T
        callRIC.columns = lldate

        call = pd.DataFrame([
            optionsInfo[optionsInfo.Instrument.isin(
                Selec_C[i])].STRIKE_PRC.values for i in range(len(Selec_C))
        ]).T
        call.columns = lldate

        putRIC = pd.DataFrame(Selec_P).T
        putRIC.columns = lldate
        put = pd.DataFrame([
            optionsInfo[optionsInfo.Instrument.isin(
                Selec_P[i])].STRIKE_PRC.values for i in range(len(Selec_P))
        ]).T
        put.columns = lldate
        RE = {
            "callRIC": callRIC.to_json(),
            "call": call.to_json(),
            "putRIC": putRIC.to_json(),
            "put": put.to_json(),
        }

        return (json.dumps(RE))
    else:
        return (None)
Beispiel #11
0
    def draw_tiles(screen):
        half = Tile.width // 2

        for tile in Tile.List:

            if not (tile.type == 'empty'):
                pygame.draw.rect(screen, [40, 40, 40], tile)

            if tile.G != 0:
                Func.text_to_screen(screen,
                                    tile.G,
                                    tile.x,
                                    tile.y + half,
                                    colour=[120, 157, 40])

            if tile.H != 0:
                Func.text_to_screen(screen,
                                    tile.H,
                                    tile.x + half,
                                    tile.y + half,
                                    colour=[20, 69, 150])

            if tile.F != 0:
                Func.text_to_screen(screen,
                                    tile.F,
                                    tile.x + half,
                                    tile.y,
                                    colour=[56, 177, 177])

            Func.text_to_screen(screen, tile.number, tile.x, tile.y)
def run(interval, command):
    Log.info("*" * 51)
    #log.print_ts("Command %s"%command)
    Log.info("Run every %s seconds." % interval)
    Log.info("*" * 51)
    main = Func.Func()
    monitor = Monitor.Monitor()
    while True:
        try:
            # sleep for the remaining seconds of interval
            time_remaining = interval - time.time() % interval
            Log.info("Sleeping until %s(%.3f seconds).." % (time.strftime(
                "%Y-%m-%d %H:%M:%S",
                time.localtime(
                    (time.time() + time_remaining))), time_remaining))
            time.sleep(time_remaining)
            Log.info("-" * 51)
            #log.print_ts("Starting command.")
            Log.info("Starting Run...")
            # execute the command
            main.Run()
            monitor.Run()
            Log.info("Stop...")
            #status = os.system(command)
            Log.info("-" * 51)
            #log.print_ts("Command status = %s."%status)
        except Exception as e:
            Log.error("LogtextArchived.run() error code: %s" % (str(e)))
Beispiel #13
0
def controls():
    progress = 0
    controlsImage = pygame.image.load("Images/ControlsPg.png")
    progressOutlineImage = pygame.image.load("Images/progressBar.png")

    t = 15
    screen.blit(controlsImage, (0, 0))
    loadingBlockX = 111
    screen.blit(progressOutlineImage, (108, 10))
    while t:
        pygame.draw.rect(screen, white, (loadingBlockX, 14, 55, 15))
        Func.text_to_screen(screen, "Loading: ", 8, 8)
        pygame.display.flip()
        loadingBlockX += 48.25
        clock.tick(1)
        t -= 1
	def computescoreandthre(self):
		# 计算阈值
		filter = np.ones(self.leftgridsize)
		print("self.leftimg:max:%f,min:%f" % (self.leftimg.max(), self.leftimg.min()))
		self.leftgridkpoints = Func.conv2withstride(self.leftimg, filter, stride=self.leftgridsize, start=None, gridnum=self.lgn)
		print("self.leftgridkpoints:max:%f,min:%f" % (self.leftgridkpoints.max(), self.leftgridkpoints.min()))
		# 显示计数
		# Func.imagesc(tmp, '左图计数')
		threfilter = np.ones((3, 3)) / 9  # 计算均值
		# threfilter = np.ones((3, 3))
		self.thre = ss.convolve2d(self.leftgridkpoints, threfilter,'same')
		print("self.thre:max:%f,min:%f" % (self.thre.max(), self.thre.min()))
		self.thre = self.TreshFactor * np.sqrt(self.thre*(self.leftgridkpoints>0))  # 阈值计算公式
		print("self.thre:max:%f,min:%f"%(self.thre.max(),self.thre.min()))
		# 显示阈值
		# Func.imagesc(self.thre, 'thre')
		# 计算打分
		self.score = np.zeros((self.lgn, self.lgn))
		self.lgshape=(self.lgn,self.lgn)
		neiborwidth = 1  # 多远 的算邻居
		filtershape=(self.leftgridsize[0]*(2*neiborwidth+1),self.leftgridsize[1]*(2*neiborwidth+1))
		neiborfilter = np.ones(filtershape)
		nnd=1
		for i in range(self.lgn):  # r
			for j in range(self.lgn):  # c
				if self.leftgridkpoints[i,j]==0:
					continue
				leftvalue=Func.index2value((i,j),self.lgshape)+1
				bestmatchgrid=self.leftmatchgrid[self.leftimglabel==leftvalue]
				if bestmatchgrid.size <1:
					continue  # 点数小于阈值则不计算,默认为不匹配
				number,n_counts=np.unique(bestmatchgrid,return_counts=True)
				rbestindex=number[np.argsort(n_counts)[-1]]
				index=(self.leftimglabel==leftvalue)&(self.leftmatchgrid==rbestindex)

				neiborsindex=(((self.leftimglabel-self.leftmatchgrid)==(leftvalue-rbestindex))&(self.leftimg>0)).astype(np.int32)
				lsize=np.array(self.leftgridsize)
				neiborsindexconv = Func.conv2withstride(neiborsindex,neiborfilter,
				                                        stride=self.leftgridsize,start=None,gridnum=self.lgn)
				self.score[i, j]=neiborsindexconv[i,j]
				# print("calc grid(%d,%d)\n thre=%.f,index.sum=%d,neiborsindex.sum=%d,score=%d"
				#       % (i, j,self.thre[i,j],index.sum(),neiborsindex.sum(),self.score[i, j]))
				nnd+=1
				if neiborsindexconv[i,j]<self.thre[i,j]:
					continue
				self.TrueMatches+= index
		print("batchsize %d"%(nnd))
Beispiel #15
0
    def InsData(self, url, newskind, DateDif):
        res = Func.GetHeader(url)
        if res == '':
            print 'Time Out!'
        else:
            soup = bs(res, 'html.parser')

            souptitle = soup.find('h2', attrs={'class': 'news_title'})
            title = souptitle.text

            timesoup = soup.find('span', attrs={'class': 'gray9 mgl10'})
            timestr = timesoup.text
            newstime = datetime.datetime.strptime(timestr, '%Y-%m-%d %H:%M')

            source = ''
            cmt = 0
            author = ''

            txtsoup = soup.find('div', attrs={'class': 'newsDetail_txt'})
            newstxt = txtsoup.text.strip()

            now = datetime.datetime.now() - datetime.timedelta(days=DateDif)
            currdate = newstime

            if (now.year == currdate.year and now.month == currdate.month
                    and now.day == currdate.day) or DateDif == -1:

                conn = MySQLdb.connect(host='.',
                                       port=3306,
                                       user='******',
                                       passwd='123456',
                                       db='news_info',
                                       charset='utf8')
                cur = conn.cursor()

                #insert数据
                dictypename = {1: '双色球', 2: '福彩3D', 3: "七彩乐"}
                sql = 'insert into tbl_news_info(title,newstype,source,pubtime,typename,webname,newsurl,contenttxt,joincount,author) select \'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',%d,\'%s\' from DUAL' % (
                    title, '其它', source, newstime, dictypename[newskind],
                    '澳客网', url, newstxt, cmt, author)
                try:
                    cur.execute(sql)
                    cur.close()
                    conn.commit()
                    conn.close()
                except Exception, e:
                    print 'str(Exception):\t', str(Exception)
                    print 'str(e):\t\t', str(e)
                    print 'repr(e):\t', repr(e)
                    print 'e.message:\t', e.message
                    print 'traceback.print_exc():'
                    traceback.print_exc()
                    print 'traceback.format_exc():\n%s' % traceback.format_exc(
                    )
                    print 'url:%s' % url
                    print '########################################################'
                finally:
                    pass
Beispiel #16
0
    def cmd_alpha(self, msg, alpha):
        res = Var.client.query(alpha)
        try:
            interpretation = res.pods[0].text
            link = "http://wolframalpha.com/input/?i=" + urllib.quote_plus(
                alpha)

            Func.sendMessage(interpretation + " ('" + alpha + "') " + link)

            first = True
            for i in res.pods:
                if first:
                    first = False
                    continue

                Func.sendMessage(i.text)

        except Exception:
            return "No results found on WolframAlpha for '" + alpha + "'"
Beispiel #17
0
 def createlabel(self, shift=(0, 0), show=False):
     # 生成标签矩阵
     self.leftlabel = (np.arange(1, self.lgn ** 2 + 1).reshape(self.lgn, self.lgn)) \
      .repeat(self.leftgridsize[0], 0).repeat(self.leftgridsize[1], 1).astype(np.int32)
     self.rightlabel = (np.arange(1, self.rgn ** 2 + 1).reshape(self.rgn, self.rgn)) \
      .repeat(self.rightgridsize[0], 0).repeat(self.rightgridsize[1], 1).astype(np.int32)
     if shift[0] == 1:
         self.leftlabel = np.roll(self.leftlabel,
                                  -int(self.leftgridsize[0] / 2),
                                  axis=0)
         self.rightlabel = np.roll(self.rightlabel,
                                   -int(self.rightgridsize[0] / 2),
                                   axis=0)
     if shift[1] == 1:
         self.leftlabel = np.roll(self.leftlabel,
                                  -int(self.leftgridsize[1] / 2),
                                  axis=1)
         self.rightlabel = np.roll(self.rightlabel,
                                   -int(self.rightgridsize[1] / 2),
                                   axis=1)
     # 标签
     self.leftimglabel[self.kp1list] = self.leftlabel[self.kp1list]
     # 只保存匹配特征所在的网格,反正也不会计算其实际坐标
     self.leftmatchgrid[self.kp1list] = self.rightlabel[
         self.kp2list]  # index2value(rightkpt, shape)
     if self.DEBUG or show:
         Func.imagesc(self.leftlabel,
                      "leftlabel shift=(%d,%d)" % (shift[0], shift[1]))
         Func.imagesc(self.leftimglabel,
                      "leftimglabel shift=(%d,%d)" % (shift[0], shift[1]))
         Func.imagesc(self.leftmatchgrid,
                      "leftmatchgrid shift=(%d,%d)" % (shift[0], shift[1]))
Beispiel #18
0
    def cmd_a(self, msg, alpha):
        if not (msg.FromHandle in Var.lastalpha):
            Var.lastalpha[msg.FromHandle] = 0

        if Var.lastalpha[msg.FromHandle] > time.time() - 60:
            return "Please wait for " + str(
                round(60 - (time.time() - Var.lastalpha[msg.FromHandle]),
                      2)) + " seconds!"

        Var.lastalpha[msg.FromHandle] = time.time()

        res = Var.client.query(alpha)
        try:
            interpretation = res.pods[0].text
            result = res.pods[1].text
            link = "http://wolframalpha.com/input/?i=" + urllib.quote_plus(
                alpha)

            Func.sendMessage(interpretation + " ('" + alpha + "') " + link)
            return result
        except Exception:
            return "No results found on WolframAlpha for '" + alpha + "'"
def main():
    print(__name__)
    root='./images/'
    # img1path='./images/000.png'
    # img2path = './images/020.png'
    img1path=root+'img1.jpg'
    img2path = root+'img2.jpg'
    # img1path='./images/img.jpg'
    # img2path = './images/img2.jpg'
    img1=cv2.imread(img1path)
    img2=cv2.imread(img2path)
    ddsize=(640,480)
    img1 = cv2.resize(img1, ddsize)
    img2 = cv2.resize(img2, ddsize)
    #gms
    time_start = time.time()
    gms = GMS(img1, img2)
    gms.run()
    gms.show()
    time_end = time.time();  # time.time()为1970.1.1到当前时间的毫秒数
    print('cost time is %fs' % (time_end - time_start))
    # #GMSwithMatrix
    # time_start=time.time()
    # gmsm=GMSwithMatrix(img1,img2)
    # gmsm.run()
    # time_end=time.time();#time.time()为1970.1.1到当前时间的毫秒数
    # print('cost time is %fs'%(time_end-time_start))
    #GMSwithGridFilter
    time_start = time.time()
    ggf = GMSwithGridFilter(img1, img2)
    ggf.run()
    time_end = time.time();  # time.time()为1970.1.1到当前时间的毫秒数
    print('cost time is %fs' % (time_end - time_start))
    print('var %f' % (gms.listgrid1.reshape(gms.rows1, gms.rows1) - ggf.leftgridkpoints).var())
    # Func.imagesc(ggf.leftgridkpoints, 'GGF point')
	#测试
    # TreshFactor=6
    # leftgridkpoints=gms.listgrid1.reshape(gms.rows1, gms.rows1)
    # threfilter = np.ones((3, 3))
    # thre = cv2.filter2D(leftgridkpoints, -1, threfilter)
    # delta=ggf.thre-gms.thre.reshape(gms.rows1,gms.rows1)
    # print("gms.thre:max:%f,min:%f" % (gms.thre.max(), gms.thre.min()))
    # print("thre sum=%f var=%f,mean=%f"%(delta.sum(),delta.var(),delta.mean()))
    # Func.imagesc(gms.thre.reshape(gms.rows1, gms.rows1), 'GMS thre')
    # Func.imagesc(ggf.thre, 'GGF thre')
    # Func.imagesc(delta, 'GGF thre - GMS thre')
    
    delta=ggf.score-gms.score.reshape(gms.rows1,gms.rows1)
    print("gms.score:max:%f,min:%f" % (gms.score.max(), gms.thre.min()))
    print("ggf.score:max:%f,min:%f" % (ggf.score.max(), ggf.thre.min()))
    print("score sum=%f var=%f,mean=%f" % (delta.sum(), delta.var(), delta.mean()))
    Func.imagesc(gms.score.reshape(gms.rows1, gms.rows1), 'GMS score')
    Func.imagesc(ggf.score, 'GGF score')
    Func.imagesc(delta, 'GGF score - GMS score')

    #gms.show()
    a=np.ones([4,4])
    b=np.ones([3,3])
Beispiel #20
0
    def MessageStatus(self, msg, status):
        print(msg.FromHandle + ": " + msg.Body)

        if Var.chat.qsize() >= 100:
            Var.chat.get()
            pass

        Var.chat.put("[" + Func.now() + "] " + msg.FromHandle + ": " +
                     msg.Body + "\n")

        for m, module in self.modules.items():
            for regexp, target in module.commands.items():
                match = re.match(regexp, msg.Body, re.IGNORECASE)

                if match:
                    msg.MarkAsSeen()

                    #try:s

                    reply = module.runMethod(target, msg, match)

                    if reply:
                        Func.sendMessage(reply)

                    #except Exception as ex:
                    #    e = traceback.format_stack()
                    #    e[-1] += "\n"
                    #    e.append(ex[0])

                    #    code, error = Func.pastebin(e)
                    #    Func.sendMessage("Error: " + error)

                    return

        if len(msg.Body) > 0:
            if msg.Body[0:1] == "@":
                Func.sendMessage("Command Not Found")
Beispiel #21
0
    def MessageStatus(self, msg, status):
        print(msg.FromHandle + ": " + msg.Body)

        if Var.chat.qsize() >= 100:
            Var.chat.get()
            pass

        Var.chat.put("[" + Func.now() + "] " + msg.FromHandle + ": " + msg.Body + "\n")

        for m, module in self.modules.items():
            for regexp, target in module.commands.items():
                match = re.match(regexp, msg.Body, re.IGNORECASE)

                if match:
                    msg.MarkAsSeen()

                    #try:s

                    reply = module.runMethod(target, msg, match)

                    if reply:
                        Func.sendMessage(reply)

                    #except Exception as ex:
                    #    e = traceback.format_stack()
                    #    e[-1] += "\n"
                    #    e.append(ex[0])

                    #    code, error = Func.pastebin(e)
                    #    Func.sendMessage("Error: " + error)

                    return

        if len(msg.Body) > 0:
            if msg.Body[0:1] == "@":
                Func.sendMessage("Command Not Found")
Beispiel #22
0
def defineNumbers(orig):
    pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
    custom_config = r'--oem 3 --psm 6 outputbase digits'

    v = []
    for i in range(len(orig)):
        aux = []
        for j in range(len(orig[i])):
            img = Func.cleanSquare(orig[i][j])
            cv2.imshow('Janela ' + str(i) + ' ' + str(j), img)
            s = pytesseract.image_to_string(img, config=custom_config)
            aux.append(retireNoise(s))
        v.append(aux)

    return (v)
Beispiel #23
0
 def classify(self, img):
     IHandler = Func.PornImageHandler()
     #img = cv2.imread(filename)
     num = 1
     VecList = []
     label = []
     #   将图片特征向量
     VecList.append(IHandler.GetFeature(img))
     label.append(1)
     num += 1
     if os.path.exists(self.modelpath):
         model = svm.svm_load_model(self.modelpath)
     else:
         self.train()
     p_labs, p_acc, p_vals = svm.svm_predict(label, VecList, model, '-b 1')
     print p_labs, p_acc, p_vals
     if p_labs[0] > 0.5:
         return True
     else:
         return False
Beispiel #24
0
 def ExtractFeature(self, truepath, falsepath):
     num = 1
     VecList = []
     label = []
     self.truelist = self.__load_images(truepath)
     self.falselist = self.__load_images(falsepath)
     IHandler = Func.PornImageHandler()
     #   训练正样本
     for img in self.truelist:
         self.__SubProc(IHandler, VecList, label, img, 1, num,
                        len(self.truelist) + len(self.falselist))
         num += 1
     #   训练负样本
     for img in self.falselist:
         self.__SubProc(IHandler, VecList, label, img, 0, num,
                        len(self.truelist) + len(self.falselist))
         num += 1
     print "[*]  Created Process Pool!"
     print len(VecList), " ", len(label)
     return label, VecList
Beispiel #25
0
    def cmd_capture(self, msg):
        if Var.lastcapture > time.time() - 60:
            return "Please wait for " + str(
                round(60 - (time.time() - Var.lastcapture), 2)) + " seconds!"

        lastcapture = time.time()

        newChat = Queue.Queue()
        oldChat = []

        while not Var.chat.empty():
            message = Var.chat.get()
            newChat.put(message)
            oldChat.append(message)

        code, paste = Func.pastebin(oldChat)

        chat = newChat

        if code == 1:
            return paste
        else:
            return "Capture: " + paste
Beispiel #26
0
    def loadtemplate(self):
        self.wb = xl.load_workbook(self.template_path)
        patch_worksheet()

        self.sheet1 = self.wb['Input']
        list1 = [[5, 2, 5], [5, 9, 12], [5, 15, 18], [12, 5, 8], [12, 15, 18],
                 [14, 7, 8], [14, 15, 18], [16, 6, 7], [16, 10, 11],
                 [16, 17, 18], [22, 2, 5], [22, 11, 14], [24, 4, 5],
                 [24, 9, 10], [24, 13, 14], [26, 4, 5], [26, 9, 10],
                 [26, 13, 14], [26, 18, 19], [29, 2, 4], [29, 9, 11],
                 [29, 15, 17], [32, 2, 4], [32, 9, 11], [32, 15,
                                                         17], [38, 2, 4],
                 [38, 9, 11], [38, 15, 17], [41, 2, 4], [41, 9, 11],
                 [41, 15, 17], [44, 2, 4], [44, 9, 11], [44, 15,
                                                         17], [47, 2, 4],
                 [47, 9, 11], [47, 15, 17], [49, 4, 5], [49, 9, 10],
                 [49, 17, 19], [55, 2, 4], [55, 9, 11], [55, 15,
                                                         17], [58, 2, 4],
                 [58, 9, 11], [58, 15, 17], [61, 2, 4], [61, 9, 11],
                 [61, 15, 17], [64, 2, 4], [64, 9, 11], [64, 15,
                                                         17], [66, 4, 5],
                 [66, 9, 10], [66, 17, 18], [19, 14, 20], [35, 14, 20],
                 [21, 7, 8], [22, 7, 8], [21, 16, 17], [22, 16, 17]]

        list4 = [[5, 2, 8], [5, 9, 15]]
        list5 = [[14, 2, 8], [15, 3, 8], [16, 3, 8], [31, 2, 8], [32, 3, 8],
                 [33, 3, 8]]

        for lists in [list1, list4, list5]:
            for item in lists:
                x = item[0]
                item.insert(2, x)
        list1.extend([[70, 2, 71, 5], [70, 7, 71, 9], [70, 11, 71, 13],
                      [70, 15, 71, 20]])
        self.sheet2 = self.wb['Optimization']
        self.sheet3 = self.wb['Input']
        self.sheet4 = self.wb['Output-Alphanumeric']
        self.sheet5 = self.wb['Output-Alphanumeric (2)']
        self.sheet6 = self.wb['Output-Tolerance calcuation']
        for item1 in list1:
            Func.writeborder(self.sheet1, item1)
        for item4 in list4:
            Func.writeborder(self.sheet4, item4)
        for item5 in list5:
            Func.writeborder(self.sheet5, item5)
Beispiel #27
0
def run(P, truepath, falsepath):
    IHandler = Func.PornImageHandler()
    truelist = __load_images(truepath)
    falselist = __load_images(falsepath)
    #   Multi Proc
    VecList = []
    label = []
    result = []
    num = 1
    pool = Pool()
    for img in truelist:
        result.append(pool.apply_async(SubProc, args = (IHandler, img, 1, num, len(truelist) + len(falselist), )))
        num += 1
    for img in falselist:
        result.append(pool.apply_async(SubProc, args = (IHandler, img, 0, num, len(truelist) + len(falselist), )))
        num += 1
    pool.close()
    pool.join()
    for r in result:
        print r.get()[1]
        VecList.append(r.get()[0])
        label.append(r.get()[1])
    return label, VecList
Beispiel #28
0
def FrameMasking(image, Face1_lower, Face1_upper, Face2_lower, Face2_upper,
                 Face3_lower, Face3_upper):
    hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    filtered = cv2.bilateralFilter(hsv, 5, 10, 10)
    sharpened = unsharped_filter(filtered)
    mask_Face1 = cv2.inRange(sharpened, Face1_lower, Face1_upper)
    mask_Face2 = cv2.inRange(sharpened, Face2_lower, Face2_upper)
    mask_Face3 = cv2.inRange(sharpened, Face3_lower, Face3_upper)

    mask_Face1 = Func.erode(mask_Face1, cv2.MORPH_ELLIPSE, (3, 3))
    mask_Face1 = Func.dilate(mask_Face1, cv2.MORPH_ELLIPSE, (3, 3))
    mask_Face2 = Func.erode(mask_Face2, cv2.MORPH_ELLIPSE, (3, 3))
    mask_Face2 = Func.dilate(mask_Face2, cv2.MORPH_ELLIPSE, (3, 3))
    mask_Face3 = Func.erode(mask_Face3, cv2.MORPH_ELLIPSE, (3, 3))
    mask_Face3 = Func.dilate(mask_Face3, cv2.MORPH_ELLIPSE, (3, 3))
    #mask_face1 = cv2.bitwise_not(mask_Face1)
    #frame = mask_Face2 + mask_Face1
    frame = cv2.bitwise_and(mask_Face3, mask_Face2, mask=mask_Face1)
    return mask_Face1, mask_Face2, mask_Face3, frame
Beispiel #29
0
        url = urllib.request.urlopen(Oper + key)



    tree = ET.parse(url)
    note=tree.getroot()


#정리해서 보여줌
    indent(note)

#xml 문서 그대로 보여줌
#ET.dump(note)

    if Operation=="일일":
        Func.daily(note)
    elif Operation=="주간":
        Func.weekly(note)
    elif Operation=="영화목록":
        Func.MovieList(note)
    elif Operation=="영화사목록":
        Func.CompanyList(note)

    answer=input("메일을 보내시겠습니까? Y/N ")
    if answer=="Y"or answer== "y":
        m=gmail.Mail()
        m.login()
        m.write()
        m.add(Func.tag_list,Func.value_list)
        m.send()
Beispiel #30
0
    #     self.close()

    # def closeEvent(self, ce):
    #     self.fileQuit()

    def about(self):
        QMessageBox.about(
            self, "About", """embedding_in_qt5.py example
        Copyright 2015 BoxControL

        This program is a simple example of a Qt5 application embedding matplotlib
        canvases. It is base on example from matplolib documentation, and initially was
        developed from Florent Rougon and Darren Dale.

        http://matplotlib.org/examples/user_interfaces/embedding_in_qt4.html

        It may be used and modified with no restriction; raw copies as well as
        modified versions may be distributed without limitation.
        """)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    outputs = parameters.Outputs()
    gs = parameters.GS()
    outjson = 'output.json'
    Func.LoadJson(outjson, outputs, gs)
    aw = ApplicationWindow(gs)
    aw.show()
    #sys.exit(qApp.exec_())
    app.exec_()
Beispiel #31
0
 def __init__(self):
     self.skype = Skype4Py.Skype(Events=self)
     self.skype.Attach()
     self.loadComamnds()
     Func.sendMessage("/me " + Var.version + " Initialized")
Beispiel #32
0
 def on_getIPBtn_clicked(self):
     domainName = self.domainInput.text()
     ipaddress = Func.getIP(domainName)
     self.ipInput.setText(ipaddress)
Beispiel #33
0
 def traceInfo(info):
         sExceptMsg = ""
         if Config.B_SYS_DEBUG:
             sExceptMsg += "\r\n**********************Trace %s*********************************\r\n"%(Func.fNow())
             sExceptMsg += "\r\nTrace Messages:%s"%(str(info))
             sExceptMsg += "\r\n"
         if Config.B_SYS_WRITE_LOG:
             logger = LogInfo.initlog()
             logger.info(info)            
         if Config.B_SYS_TRACE:
                 print "\r\nTrace stack is flow:\r\n"
                 traceback.print_stack()
                 print "\r\n"
         if Config.B_SYS_DEBUG:
                 sExceptMsg += "\r\n*********************Trace END**********************************\r\n"
                 print   sExceptMsg                                                  
Beispiel #34
0
        def writeLog(logLevel,logMessage):
#                alogLevel = ["trace","warning","error"]
                sExceptMsg = ""
                if Config.B_SYS_DEBUG:
                    sExceptMsg += "\r\n**********************%s %s*********************************\r\n"%(logLevel.upper(),Func.fNow())
                    sExceptMsg += "\r\n%s Messages:%s"%(logLevel.upper(),str(logMessage))
                    sExceptMsg += "\r\n"
                if logLevel=="trace":
                        if Config.B_SYS_WRITE_LOG:
                                logger = LogInfo.initlog()
                                logger.info(logMessage)
                        if Config.B_SYS_TRACE:
                                print "\r\nTrace stack is flow:\r\n"
                                traceback.print_stack()
                                print "\r\n"                
                elif logLevel=="warning":
                        pass
                elif logLevel=="error":
                        exc_type, exc_value, exc_traceback = sys.exc_info()
                        if exc_type!=None:
                                sExceptMsg += "\r\n"
                                sExceptMsg += repr(traceback.format_tb(exc_traceback))
                                sExceptMsg += "\r\n"
                        else:
                                print "\r\nTrace stack is flow:\r\n"
                                traceback.print_stack()
                                sExceptMsg += "\r\n"
                         
                        if Config.B_SYS_WRITE_LOG and exc_type!=None:
                                logger = LogInfo.initlog()
                                logger.error(sExceptMsg)
                if Config.B_SYS_DEBUG:
                    sExceptMsg += "\r\n*********************%s END**********************************\r\n"%(logLevel.upper())
                    print   sExceptMsg      
Beispiel #35
0
 elif lineNum==mainBlock[0]:
     func = True
 elif lineNum==mainBlock[1]:
     func = False
 else:
     if line[len(line)-1]=='\n':
         line = line[:len(line)-1]
     if quote:
         pass
     elif switch:
         if line.lstrip()=="{": pass
         elif line.lstrip()=="}":
             switch = False
             Func.Switch().delVarName()
         else:
             newLines = Func.generate(Func.determineBegin(line),line)
             if newLines!= None:
                 for newLine in newLines:
                     if lineNum>mainBlock[0] and lineNum<mainBlock[1]: mainCode.append(tab*'\t' + newLine + '\n')
                     else: newProg.append(tab*'\t' + newLine + '\n')
     elif func:
         if line.lstrip()=="}":
             tab -= 1
             if line=="\t}": func = False
             if Loop:
                 if lineNum>mainBlock[0] and lineNum<mainBlock[1]: mainCode.append((tab+Func.add())*'\t' + Func.getToAppend() + '\n')
                 else: newProg.append((tab+Func.add())*'\t' + Func.getToAppend() + '\n')
             Loop = False
             Func.add()
         elif line.lstrip()=="{":
             tab += 1
Beispiel #36
0
def SubProc(Func, img, label, num, length):
    print "%3.2f %% \t (%4d/%4d)"%(float(num) * 100 / length, num, length)
    return Func.GetFeature(img), label
Beispiel #37
0
 def __init__(self):
     self.skype = Skype4Py.Skype(Events=self)
     self.skype.Attach()
     self.loadComamnds()
     Func.sendMessage("/me " + Var.version + " Initialized")