text
stringlengths
8
6.05M
# coding=utf-8 '''返回不同格式的约拍模型 @author:黄鑫晨 @attention: Model为模型,model为模特 ''' import time from Database.models import get_db from Database.tables import AppointLike, AppointmentImage, CompanionImg, User, AppointEntry, WApCompanionImage, \ AppointmentInfo, UserImage from FileHandler.Upload import AuthKeyHandler from Userinfo.Ufuncs import Ufuncs class APmodelHandler(object): @classmethod def ap_Model_simply(clas, appointments, retdata, userid): '''简单约拍模型,用于登录首页 :param appointment: 传入多个appointment对象 :return: 返回多个简单约拍模型 ''' #todo:查找待变更为最新10个 liked = 0 try: for appointment in appointments: retdata.append(APmodelHandler.ap_Model_simply_one(appointment,userid)) return retdata except Exception, e: print e @classmethod def ap_get_imgs_from_apid(clas, appointmentid): ''' 得到某约拍的图片 Args: appointmentid: 约拍Id Returns:图片名数组 ''' img_tokens = [] authkeyhandler = AuthKeyHandler() try: imgs = get_db().query(AppointmentImage).filter(AppointmentImage.APIapid == appointmentid).all() # 返回所有图片项 for img in imgs: img_url = img.APIurl img_tokens.append(authkeyhandler.download_assign_url(img_url,200,200)) except Exception,e: print '无图片' return img_tokens @classmethod def ap_Model_simply_one(clas, appointment, userid): '''得到简单约拍模型,约拍列表 :param appointment: 传入一个appointment对象 :return: 返回单个约拍简单模型 ''' # todo:查找待变更为最新10个 liked = 0 try: likedentry = get_db().query(AppointLike).filter(AppointLike.ALuid == userid, AppointLike.ALapid == appointment.APid, AppointLike.ALvalid == 1).one() # 寻找是否点过赞 if likedentry: liked = 1 #print "点过赞", liked except Exception, e: print e liked = 0 # todo:userliked不对 #print '得到Url前' apimgurls = APmodelHandler.ap_get_imgs_from_apid(appointment.APid) headimage = Ufuncs.get_user_headimage_intent_from_userid(appointment.APsponsorid) user_id = appointment.APsponsorid # 创建者的id user = get_db().query(User).filter(User.Uid == user_id).one() user_bir = user.Ubirthday.strftime('%Y') # 获取用户生日(年) now = time.strftime('%Y',time.localtime(time.time())) # 获取当前年份 user_age = int(now)-int(user_bir) # 用户年龄 user_sex = ( "男" if user.Usex else "女") ret_ap = dict( APid=appointment.APid, # APtitle=appointment.APtitle, APimgurl=apimgurls, APtime=appointment.APtime, # 这里我改过了。。。。 2017-4-7 兰威 apstartime APlikeN=appointment.APlikeN, APregistN=appointment.APregistN, Userimg=headimage, Userliked=liked, Userage=str(user_age)+"岁", Useralais=user.Ualais, APpricetype=appointment.APpricetag, APprice=appointment.APprice, Userlocation=user.Ulocation, APcreatetime=appointment.APcreateT.strftime("%Y-%m-%d %H:%M:%S"), Usex=user_sex, APcontent=appointment.APcontent, APgroup=appointment.APgroup, sponsorid=int(user_id), ) return ret_ap @classmethod def ap_Model_multiple(clas, appointment, userid): ap_regist_users = [] registed = 0 liked = 0 commented = 0 try: likedentry = get_db().query(AppointLike).filter(AppointLike.ALuid == userid, AppointLike.ALapid == appointment.APid, AppointLike.ALvalid == 1).one() # 寻找是否点过赞 if likedentry: liked = 1 #print "点过赞", liked except Exception, e: print e liked = 0 try: headimage = Ufuncs.get_user_headimage_intent_from_userid(appointment.APsponsorid) apimgurls = APmodelHandler.ap_get_imgs_from_apid(appointment.APid) ap_regist_users = Ufuncs.get_userlist_from_ap(appointment.APid) user_id = appointment.APsponsorid # 创建者的id user = get_db().query(User).filter(User.Uid == user_id).one() user_bir = user.Ubirthday.strftime('%Y') # 获取用户生日(年) now = time.strftime('%Y', time.localtime(time.time())) # 获取当前年份 user_age = int(now) - int(user_bir) # 用户年龄 user_sex = ("男" if user.Usex else "女") exist = get_db().query(AppointEntry).filter(AppointEntry.AEregisterID == userid,AppointEntry.AEapid == appointment.APid,AppointEntry.AEvalid == 1 ).all() if exist: registed = 1 if appointment.APstatus == 3: appointmentinfo = get_db().query(AppointmentInfo).filter( AppointmentInfo.AIappoid == appointment.APid).one() if int(userid) == appointmentinfo.AIpid: if appointmentinfo.AIpcomment: commented = 1 if int(userid) == appointmentinfo.AImid: if appointmentinfo.AImcomment: commented = 1 if appointment.APstatus == 4: commented = 1 m_response = dict( APid=appointment.APid, # APtitle=appointment.APtitle, APsponsorid=appointment.APsponsorid, APtag=appointment.APtag, APtype=int(appointment.APtype), APlocation=appointment.APlocation, # APstartT=appointment.APstartT.strftime('%Y-%m-%d %H:%M:%S'), # APendT=appointment.APendT.strftime('%Y-%m-%d %H:%M:%S'), # APjoinT=appointment.APjoinT.strftime('%Y-%m-%d %H:%M:%S'), APtime=appointment.APtime, APcontent=appointment.APcontent, #APfree=int(appointment.APfree), APpricetag=appointment.APpricetag, APprice=appointment.APprice, APcreateT=appointment.APcreateT.strftime('%Y-%m-%d %H:%M:%S'), APaddallowed=int(appointment.APaddallowed), APlikeN=appointment.APlikeN, APvalid=int(appointment.APvalid), APregistN=appointment.APregistN, APregisters=ap_regist_users, # 返回所有报名人用户模型 APimgurl=apimgurls, APstatus=appointment.APstatus, Userliked=liked, APgroup=appointment.APgroup, Userimg=headimage, Userage=str(user_age) + "岁", Useralais=user.Ualais, Userlocation=user.Ulocation, Usex=user_sex, Useregistd=registed, Usercommented=commented, sponsorid=int(user_id), ) if appointment.APstatus == 4: # 状态为4时返回两边的评价 appointmentinfo = get_db().query(AppointmentInfo).filter(AppointmentInfo.AIappoid == appointment.APid).one() user_p_headimage = Ufuncs.get_user_headimage_intent_from_userid(appointmentinfo.AIpid) user_m_headimage = Ufuncs.get_user_headimage_intent_from_userid(appointmentinfo.AImid) user_p = get_db().query(User).filter(User.Uid == appointmentinfo.AIpid ).one() user_m = get_db().query(User).filter(User.Uid == appointmentinfo.AImid ).one() comment_p = dict( uid=appointmentinfo.AIpid, ucomment=appointmentinfo.AIpcomment, uscore=appointmentinfo.AIpscore, uheadimage=user_p_headimage, ualias=user_p.Ualais ) comment_m = dict( uid = appointmentinfo.AImid, ucomment=appointmentinfo.AImcomment, uscore=appointmentinfo.AImscore, uheadimage=user_m_headimage, ualias=user_m.Ualais ) comment = [] comment.append(comment_p) comment.append(comment_m) m_response['comment'] = comment return m_response except Exception, e: print e,'dff' @classmethod def ApInforesponse(appointment, retdata): ''' Returns:返回选择约拍的人关于约拍的详细信息 #todo:查找待变更为最新10个 ''' m_ApInforesponse = dict( AIid=appointment.AIid, AImid=appointment.AImid, AIpid=appointment.Aipid, AImscore=appointment.AImscore, AIpscore=appointment.AIpscore, AImcomment=appointment.AImcomment, AIpcomment=appointment.AIpcomment, AIappoid=appointment.AIappoid ) retdata.append(m_ApInforesponse) def ApCompanion(clas, Companion, retdata): auth = AuthKeyHandler() Companion_imgs = get_db().query(WApCompanionImage).filter(WApCompanionImage.WAPCid == Companion.WAPCid).all() Imgs = [] for item in Companion_imgs: Imgs.append(auth.download_url(item.WAPCurl)) ApCompanion_model = dict( CompanionId=Companion.WAPCid, CompanionTitle=Companion.WAPCname, CompanionContent=Companion.WAPCServeintro, CompanionUrl=Companion.WAPCContact, CompanionPic=Imgs, ) retdata.append(ApCompanion_model)
money, c50000, c10000, c5000, c1000 = 0, 0, 0, 0, 0 money = int(input("고환할 돈은 얼마?")) c50000 = money // 50000 money %= 50000 c10000 = money // 10000 money %= 10000 c5000 = money // 5000 money %= 5000 c1000 = money // 1000 money %= 1000 print('\n 500원짜리 => %d개' % c50000) print(' 500원짜리 => %d개' % c10000) print(' 500원짜리 => %d개' % c5000) print(' 500원짜리 => %d개' % c1000) print(' 바꾸지 못한 잔돈 => %d개' %money)
#input # ;>;<>;<>-<>;<[->++<][->+<]>:<:>;<;[->+>+<<]>>[-<<+>>]<<[->+<];>++++<>;<>;<>;<>;<+:>-:<;[->+>+<<]>>[-<<+>>]<<>-<>;<>:<>;<>:<[->+>++<<];+:>-:<:[>+<-]>++++<>:<>:<[->+>++<<]>-<[->++<][->+<]>-<:[->+<]+:>-:<:>: # 7 14 11 4 2 7 7 10 12 17 5 2 11 14 2 class Brainfuck: def __init__(self): self.stack = [0] * 100 self.pointer = 0 def set_script(self, script): self.script = script def resize_stack(self): for i in range(0, len(self.stack)): self.stack.append(0) def set_input(self,inp): self.inp = inp.split() def interpret_token(self,t): if t == '+': self.stack[self.pointer] += 1 elif t == '-': self.stack[self.pointer] -= 1 elif t == ':': print(self.stack[self.pointer], end=' ') elif t == ';': self.stack[self.pointer] = int(self.inp.pop(0)) elif t == '>': self.pointer += 1 if self.pointer >= len(self.stack) - 1: self.resize_stack() elif t == '<': self.pointer -= 1 if self.pointer < 0: raise IndexError('Error: Data pointer is decremented below zero with "<" operation') def interpret(self,script): i = 0 while i < len(script): t = script[i] if t == '[': while True: if self.stack[self.pointer] != 0: result = self.interpret(script[i+1:]) if result != None: end_index = script.index(result) else: break else: if end_index != None: i = end_index end_index = None else: j = i while script[j] != ']': j += 1 i = j break elif t == ']': return script[i:] else: self.interpret_token(t) i += 1 def main(): bf = Brainfuck() script = input() bf.set_input(input()) bf.interpret(script) if __name__ == '__main__': main()
# python 2.7.3 import sys import math [n, m, p] = map(int, sys.stdin.readline().split()) m = {} for i in range(n): s = raw_input() for c in s: m[c] = m.get(c, 0) + 1 for i in range(p): s = raw_input() for c in s: m[c] = m.get(c, 0) - 1 ans = [] for i, v in m.items(): ans.extend(i * v) ans.sort() print ''.join(ans)
from django.conf.urls import patterns, url from accounts import views as accounts # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', url(r'^remind-me/(?P<single_event_id>\d+)/$', accounts.remind_me, name='remind_me' ), url(r'^remove-remind-me/(?P<single_event_id>\d+)/$', accounts.remove_remind_me, name='remove_remind_me' ), url(r'^add-in-the-loop/$', accounts.add_in_the_loop, name='add_in_the_loop' ), url(r'^reminder-settings/$', accounts.reminder_settings, name="reminder_settings" ), url(r'^in-the-loop-settings/$', accounts.in_the_loop_settings, name="in_the_loop_settings" ), url(r'^in-the-loop-tags/$', accounts.in_the_loop_tags, name="in_the_loop_tags" ), url(r'^cities-autosuggest/$', accounts.cities_autosuggest, name="cities_autosuggest" ), url(r'^remind-email-preview/$', accounts.remind_preview, name="remind_preview"), url(r'^in-the-loop-email-preview/$', accounts.in_the_loop_preview, name="in_the_loop_preview"), url(r'^orders/$', accounts.orders, name='account_orders' ), url(r'^order-advertising-printed/(?P<order_id>\d+)/$', accounts.order_advertising_printed, name='account_order_advertising_printed' ), url(r'^order-featured-printed/(?P<order_id>\d+)/$', accounts.order_featured_printed, name='account_order_featured_printed' ), url(r'^order-advertising-pdf/(?P<order_id>\d+)/$', accounts.OrderAdvertisingPdf.as_view(), name='account_order_advertising_pdf' ), url(r'^order-featured-pdf/(?P<order_id>\d+)/$', accounts.OrderFeaturedPdf.as_view(), name='account_order_featured_pdf' ), url(r'^set-user-context/(?P<context>[-\w]+)/$', accounts.set_context, name="account_set_context" ), url(r'^user-context-profile/$', accounts.redirect_to_active_user_context, name="user_account_context_page" ), url(r'^refresh-facebook-graph/$', accounts.refresh_facebook_graph, name='refresh_facebook_graph'), url(r'^accept-transferring/(?P<transferring_id>\d+)/$', accounts.accept_transferring, name='accept_transferring'), url(r'^reject-transferring/(?P<transferring_id>\d+)/$', accounts.reject_transferring, name='reject_transferring'), url(r'^accept-venue-transferring/(?P<venue_transferring_id>\d+)/$', accounts.accept_venue_transferring, name='accept_venue_transferring'), url(r'^reject-venue-transferring/(?P<venue_transferring_id>\d+)/$', accounts.reject_venue_transferring, name='reject_venue_transferring'), url(r'^test-location-determining/$', accounts.test_location_determining, name='test_location_determining') )
import math for a in range(1,21): for b in range(1,21): c = math.sqrt(a**2+b**2) if c<=20: if c == math.floor(c): print "Side1 = %d\tSide2 = %d\tHypotenuse = %d" %(a, b, c)
from bs4 import BeautifulSoup import requests import random for i in range(1,4): html_text=requests.get('https://www.gettyimages.in/photos/telangana-indians?family=creative&license=rf&page='+str(i)+'&phrase=telangana%20indians&sort=mostpopular#license').text #This iterates over 4 pages of images soup=BeautifulSoup(html_text,'lxml') images=soup.find_all('img',class_='gallery-asset__thumb gallery-mosaic-asset__thumb') for image in images: name='TS_'+str(random.randrange(3730,4035)) link=image['src'] with open(f'Photos/{name}.jpg','wb') as f: #wb is to store with bytes im =requests.get(link) f.write(im.content)
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html from scrapy import Request from scrapy.pipelines.images import ImagesPipeline from scrapy.exceptions import DropItem import re import codecs import json class ScrapyPipeline(object): def __init__(self): pass def process_item(self,item,spider): #原本接受 爬虫 guoyuan item 传过来的值 #item是一个字典 item的key 就是 items 类定义的属性 #{'image_url':'http://www.baidu.com'} # print('pipline ---->进入') # print(item) # with open('chouti1.md','w') as f: # while item['image_url']: # f.write(item['image_url']) # print('pipline ---->出去') pass
# -*- coding:utf-8- *- import numpy as np import cv2 img = np.zeros((512,512,3), np.uint8) cv2.line(img, (0, 0), (511, 511), (255, 0, 0), 5) cv2.rectangle(img, (384, 0), (510, 128), (0, 255, 0), 5) cv2.circle(img, (447, 63), 50, (0, 0, 255),-1) cv2.ellipse(img, (256, 256), (100, 50), 90, 0,360, (0, 255, 0), -1) pts = np.array([[10, 5], [20, 30], [70, 20], [50, 10], [50, 30], [70, 70]], np.int32) pts = pts.reshape((-1,1,2)) cv2.polylines(img, [pts], False,(255, 255, 0),1) font = cv2.FONT_HERSHEY_TRIPLEX cv2.putText(img, 'Ni Hao Ma ?' , (10, 200), font, 1, (255, 0, 0), 1,False) cv2.imshow('example', img) cv2.waitKey(0) cv2.destroyAllWindows()
"""Author Arianna Delgado Created on June 18, 2020 """ """Create a Lambda that will return YES if a given number is even and NO if the given number is odd.""" f = lambda x: 'Yes' if x % 2 == 0 else 'No' print (f(2))
from __future__ import division import os import sys import pandas as pd import numpy as np pilot_sub = int(sys.argv[1]) final_sub = int(sys.argv[2]) sims = int(sys.argv[3]) conditions = int(sys.argv[4]) modality = sys.argv[5] adaptive = sys.argv[6] threshold = sys.argv[7] basefolder = sys.argv[8] outfolder = sys.argv[9] folder = os.path.join(basefolder+'/interim',modality+'_'+adaptive,threshold) outfile = os.path.join(outfolder,'powpred_'+modality+'_'+adaptive+'_'+threshold+'.csv') simw = [2,4,6,8]*4 simef = np.repeat(['half','one','onehalf','two'],4) results = [] for p in range(sims): for c in range(conditions): if modality == 'hcp': file = os.path.join(folder,"powpre_"+modality+"_"+str(p+1)+"_contrast_"+str(c)+".csv") else: file = os.path.join(folder,"powpre_"+modality+"_"+str(p+1)+"_w_"+str(simw[c])+"_e_"+str(simef[c])+".csv") if not os.path.isfile(file): print(file) continue res = pd.read_csv(file) res['sim']=p+1 if not 'BH' in res: res['BH']='nan' res['subjects']=range(pilot_sub,final_sub) longres = pd.melt(res,id_vars=['subjects'],value_vars=['BF','UN','BH','RFT']) longres.columns = ['subjects','mcp','power'] longres.mcp = [x if not x=="RFT" else "RF" for x in longres.mcp] longres['simulation'] = p+1 longres['condition'] = c+1 results.append(longres) results = pd.concat(results) results.to_csv(outfile)
""" Home Page application view. Loads the home page from React. """ from django.shortcuts import render def home(request): """Return React front-end.""" return render(request, 'index.html')
# -*- coding: utf-8 -*- # for python3 # # 特徴抽出した正例・負例の位置関係をグラフ化する # python chk_feature.py {pcsv} {ncsv} # pcsv : 正例のCSVファイル名 # ncsv : 負例のCSVファイル名 import sys import numpy as np import matplotlib.pyplot as plt import pandas as pd from pandas import DataFrame # Main if __name__ == '__main__': # 特徴量データを入力する # 1行が、特徴ベクトルで、行数=件数となる # ヘッダはなし posiX = pd.read_csv(sys.argv[1], header=None, skiprows=1) negaX = pd.read_csv(sys.argv[2], header=None, skiprows=1) # 各次元の平均値を計算する # 新たにDataFrameを用意して、各次元の平均値を格納する # 正例 - 負例の差も計算する v = DataFrame() v['posi'] = posiX.apply(np.mean, axis=0) v['nega'] = negaX.apply(np.mean, axis=0) v['diff'] = v['posi'] - v['nega'] # グラフ描画する plt.style.use('ggplot') # スタイルの設定。なくてもOK v.plot() # 描画する plt.show() # 描画したグラフを表示する
# -*- coding: utf-8 -*- # !/usr/bin/env python import itchat @itchat.msg_register(itchat.content.TEXT) def print_content(msg): message = msg['Text'] itchat.auto_login() itchat.run()
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # ------------------------------------------------------------------------------ """This package contains the handlers.""" from typing import Dict, Optional, Tuple, cast from aea.configurations.base import ProtocolId from aea.decision_maker.messages.state_update import StateUpdateMessage from aea.decision_maker.messages.transaction import TransactionMessage from aea.mail.base import Address from aea.protocols.base import Message from aea.skills.base import Handler from packages.fetchai.contracts.erc1155.contract import ERC1155Contract from packages.fetchai.protocols.oef_search.message import OefSearchMessage from packages.fetchai.protocols.tac.message import TacMessage from packages.fetchai.protocols.tac.serialization import TacSerializer from packages.fetchai.skills.tac_participation.game import Game, Phase from packages.fetchai.skills.tac_participation.search import Search class OEFSearchHandler(Handler): """This class handles oef messages.""" SUPPORTED_PROTOCOL = OefSearchMessage.protocol_id def setup(self) -> None: """ Implement the handler setup. :return: None """ pass def handle(self, message: Message) -> None: """ Implement the reaction to a message. :param message: the message :return: None """ oef_message = cast(OefSearchMessage, message) self.context.logger.debug( "[{}]: Handling OEFSearch message. performative={}".format( self.context.agent_name, oef_message.performative ) ) if oef_message.performative == OefSearchMessage.Performative.SEARCH_RESULT: self._on_search_result(oef_message) elif oef_message.performative == OefSearchMessage.Performative.OEF_ERROR: self._on_oef_error(oef_message) def teardown(self) -> None: """ Implement the handler teardown. :return: None """ pass def _on_oef_error(self, oef_error: OefSearchMessage) -> None: """ Handle an OEF error message. :param oef_error: the oef error :return: None """ self.context.logger.warning( "[{}]: Received OEF Search error: dialogue_reference={}, oef_error_operation={}".format( self.context.agent_name, oef_error.dialogue_reference, oef_error.oef_error_operation, ) ) def _on_search_result(self, search_result: OefSearchMessage) -> None: """ Split the search results from the OEF search node. :param search_result: the search result :return: None """ search = cast(Search, self.context.search) search_id = int(search_result.dialogue_reference[0]) agents = search_result.agents self.context.logger.debug( "[{}]: on search result: search_id={} agents={}".format( self.context.agent_name, search_id, agents ) ) if search_id in search.ids_for_tac: self._on_controller_search_result(agents) else: self.context.logger.debug( "[{}]: Unknown search id: search_id={}".format( self.context.agent_name, search_id ) ) def _on_controller_search_result( self, agent_addresses: Tuple[Address, ...] ) -> None: """ Process the search result for a controller. :param agent_addresses: list of agent addresses :return: None """ game = cast(Game, self.context.game) if game.phase.value != Phase.PRE_GAME.value: self.context.logger.debug( "[{}]: Ignoring controller search result, the agent is already competing.".format( self.context.agent_name ) ) return if len(agent_addresses) == 0: self.context.logger.info( "[{}]: Couldn't find the TAC controller. Retrying...".format( self.context.agent_name ) ) elif len(agent_addresses) > 1: self.context.logger.warning( "[{}]: Found more than one TAC controller. Retrying...".format( self.context.agent_name ) ) else: self.context.logger.info( "[{}]: Found the TAC controller. Registering...".format( self.context.agent_name ) ) controller_addr = agent_addresses[0] self._register_to_tac(controller_addr) def _register_to_tac(self, controller_addr: Address) -> None: """ Register to active TAC Controller. :param controller_addr: the address of the controller. :return: None """ game = cast(Game, self.context.game) game.update_expected_controller_addr(controller_addr) game.update_game_phase(Phase.GAME_REGISTRATION) tac_msg = TacMessage( performative=TacMessage.Performative.REGISTER, agent_name=self.context.agent_name, ) tac_bytes = TacSerializer().encode(tac_msg) self.context.outbox.put_message( to=controller_addr, sender=self.context.agent_address, protocol_id=TacMessage.protocol_id, message=tac_bytes, ) self.context.behaviours.tac.is_active = False class TACHandler(Handler): """This class handles oef messages.""" SUPPORTED_PROTOCOL = TacMessage.protocol_id def setup(self) -> None: """ Implement the handler setup. :return: None """ pass def handle(self, message: Message) -> None: """ Implement the reaction to a message. :param message: the message :return: None """ tac_msg = cast(TacMessage, message) game = cast(Game, self.context.game) self.context.logger.debug( "[{}]: Handling controller response. performative={}".format( self.context.agent_name, tac_msg.performative ) ) try: if message.counterparty != game.expected_controller_addr: raise ValueError( "The sender of the message is not the controller agent we registered with." ) if tac_msg.performative == TacMessage.Performative.TAC_ERROR: self._on_tac_error(tac_msg) elif game.phase.value == Phase.PRE_GAME.value: raise ValueError( "We do not expect a controller agent message in the pre game phase." ) elif game.phase.value == Phase.GAME_REGISTRATION.value: if tac_msg.performative == TacMessage.Performative.GAME_DATA: self._on_start(tac_msg) elif tac_msg.performative == TacMessage.Performative.CANCELLED: self._on_cancelled() elif game.phase.value == Phase.GAME.value: if ( tac_msg.performative == TacMessage.Performative.TRANSACTION_CONFIRMATION ): self._on_transaction_confirmed(tac_msg) elif tac_msg.performative == TacMessage.Performative.CANCELLED: self._on_cancelled() elif game.phase.value == Phase.POST_GAME.value: raise ValueError( "We do not expect a controller agent message in the post game phase." ) except ValueError as e: self.context.logger.warning(str(e)) def teardown(self) -> None: """ Implement the handler teardown. :return: None """ pass def _on_tac_error(self, tac_message: TacMessage) -> None: """ Handle 'on tac error' event emitted by the controller. :param tac_message: The tac message. :return: None """ error_code = tac_message.error_code self.context.logger.debug( "[{}]: Received error from the controller. error_msg={}".format( self.context.agent_name, TacMessage.ErrorCode.to_msg(error_code.value) ) ) if error_code == TacMessage.ErrorCode.TRANSACTION_NOT_VALID: info = cast(Dict[str, str], tac_message.info) transaction_id = ( cast(str, info.get("transaction_id")) if (info is not None and info.get("transaction_id") is not None) else "NO_TX_ID" ) self.context.logger.warning( "[{}]: Received error on transaction id: {}".format( self.context.agent_name, transaction_id[-10:] ) ) def _on_start(self, tac_message: TacMessage) -> None: """ Handle the 'start' event emitted by the controller. :param tac_message: the game data :return: None """ self.context.logger.info( "[{}]: Received start event from the controller. Starting to compete...".format( self.context.agent_name ) ) game = cast(Game, self.context.game) game.init(tac_message, tac_message.counterparty) game.update_game_phase(Phase.GAME) if game.is_using_contract: contract = cast(ERC1155Contract, self.context.contracts.erc1155) contract_address = ( None if tac_message.info is None else tac_message.info.get("contract_address") ) if contract_address is not None: ledger_api = self.context.ledger_apis.get_api(game.ledger_id) contract.set_deployed_instance( ledger_api, contract_address, ) self.context.logger.info( "[{}]: Received a contract address: {}".format( self.context.agent_name, contract_address ) ) # TODO; verify on-chain matches off-chain wealth self._update_ownership_and_preferences(tac_message) else: self.context.logger.warning( "[{}]: Did not receive a contract address!".format( self.context.agent_name ) ) else: self._update_ownership_and_preferences(tac_message) def _update_ownership_and_preferences(self, tac_message: TacMessage) -> None: """ Update ownership and preferences. :param tac_message: the game data :return: None """ state_update_msg = StateUpdateMessage( performative=StateUpdateMessage.Performative.INITIALIZE, amount_by_currency_id=tac_message.amount_by_currency_id, quantities_by_good_id=tac_message.quantities_by_good_id, exchange_params_by_currency_id=tac_message.exchange_params_by_currency_id, utility_params_by_good_id=tac_message.utility_params_by_good_id, tx_fee=tac_message.tx_fee, ) self.context.decision_maker_message_queue.put_nowait(state_update_msg) def _on_cancelled(self) -> None: """ Handle the cancellation of the competition from the TAC controller. :return: None """ self.context.logger.info( "[{}]: Received cancellation from the controller.".format( self.context.agent_name ) ) game = cast(Game, self.context.game) game.update_game_phase(Phase.POST_GAME) self.context.is_active = False self.context.shared_state["is_game_finished"] = True def _on_transaction_confirmed(self, message: TacMessage) -> None: """ Handle 'on transaction confirmed' event emitted by the controller. :param message: the TacMessage. :return: None """ self.context.logger.info( "[{}]: Received transaction confirmation from the controller: transaction_id={}".format( self.context.agent_name, message.tx_id[-10:] ) ) state_update_msg = StateUpdateMessage( performative=StateUpdateMessage.Performative.APPLY, amount_by_currency_id=message.amount_by_currency_id, quantities_by_good_id=message.quantities_by_good_id, ) self.context.decision_maker_message_queue.put_nowait(state_update_msg) if "confirmed_tx_ids" not in self.context.shared_state.keys(): self.context.shared_state["confirmed_tx_ids"] = [] self.context.shared_state["confirmed_tx_ids"].append(message.tx_id) class TransactionHandler(Handler): """This class implements the transaction handler.""" SUPPORTED_PROTOCOL = TransactionMessage.protocol_id # type: Optional[ProtocolId] def setup(self) -> None: """ Implement the setup. :return: None """ pass def handle(self, message: Message) -> None: """ Dispatch message to relevant handler and respond. :param message: the message :return: None """ tx_message = cast(TransactionMessage, message) if ( tx_message.performative == TransactionMessage.Performative.SUCCESSFUL_SIGNING ): # TODO: Need to modify here and add the contract option in case we are using one. self.context.logger.info( "[{}]: transaction confirmed by decision maker, sending to controller.".format( self.context.agent_name ) ) game = cast(Game, self.context.game) tx_counterparty_signature = cast( str, tx_message.info.get("tx_counterparty_signature") ) tx_counterparty_id = cast(str, tx_message.info.get("tx_counterparty_id")) if (tx_counterparty_signature is not None) and ( tx_counterparty_id is not None ): tx_id = tx_message.tx_id + "_" + tx_counterparty_id msg = TacMessage( performative=TacMessage.Performative.TRANSACTION, tx_id=tx_id, tx_sender_addr=tx_message.tx_sender_addr, tx_counterparty_addr=tx_message.tx_counterparty_addr, amount_by_currency_id=tx_message.tx_amount_by_currency_id, tx_sender_fee=tx_message.tx_sender_fee, tx_counterparty_fee=tx_message.tx_counterparty_fee, quantities_by_good_id=tx_message.tx_quantities_by_good_id, tx_sender_signature=tx_message.signed_payload.get("tx_signature"), tx_counterparty_signature=tx_message.info.get( "tx_counterparty_signature" ), tx_nonce=tx_message.info.get("tx_nonce"), ) self.context.outbox.put_message( to=game.conf.controller_addr, sender=self.context.agent_address, protocol_id=TacMessage.protocol_id, message=TacSerializer().encode(msg), ) else: self.context.logger.warning( "[{}]: transaction has no counterparty id or signature!".format( self.context.agent_name ) ) else: self.context.logger.info( "[{}]: transaction was not successful.".format(self.context.agent_name) ) def teardown(self) -> None: """ Implement the handler teardown. :return: None """ pass
VTABLE(_Main) { <empty> Main } VTABLE(_A) { _Main A } FUNCTION(_Main_New) { memo '' _Main_New: _T0 = 4 parm _T0 _T1 = call _Alloc _T2 = VTBL <_Main> *(_T1 + 0) = _T2 return _T1 } FUNCTION(_A_New) { memo '' _A_New: _T3 = 4 parm _T3 _T4 = call _Alloc _T5 = VTBL <_A> *(_T4 + 0) = _T5 return _T4 } FUNCTION(main) { memo '' main: _T7 = call _Main_New _T6 = _T7 _T10 = VTBL <_A> _T11 = *(_T6 + 0) _L11: _T9 = (_T10 == _T11) if (_T9 != 0) branch _L12 _T11 = *(_T11 + 0) if (_T11 != 0) branch _L11 _T12 = "Decaf runtime error: " parm _T12 call _PrintString _T13 = *(_T6 + 0) _T14 = *(_T13 + 4) parm _T14 call _PrintString _T15 = " cannot be cast to " parm _T15 call _PrintString _T16 = VTBL <_A> _T17 = *(_T16 + 4) parm _T17 call _PrintString _T18 = "\n" parm _T18 call _PrintString call _Halt _L12: _T8 = _T6 }
from __future__ import unicode_literals # from django.conf import settings
import pytest import pandas as pd @pytest.fixture def missing_data(): """Sample data for grouping by 1 column """ data_dict = {'a': [2, 2, None, None, 4, 4, 7, 8, None, 8], 'b': ['123', '123', '123', '234', '456', '456', '789', '789', '789', '789'], 'c': [1, 2, None, 4, 4, 4, 7, 9, None, 9], 'd': ['a', 'a', None, None, 'e', 'f', None, 'h', 'j', 'j'], 'e': [1, 2, None, None, None, None, None, None, None, None], 'f': ['a', 'b', None, None, None, None, None, None, None, None], 'g': ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'b', None], 'h': ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', None, None] } df = pd.DataFrame(data_dict) return df @pytest.fixture def missing_data2(): """Sample data for grouping by 2 columns """ data_dict = {'a': [1, 2, None, None, 4, 4, 7, 8, None, 8], 'b': ['123', '123', '123', '123', '123', '789', '789', '789', '789', '789'], 'c': ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'a', 'a', 'c'], 'd': ['a', 'a', None, None, 'e', 'f', None, 'h', 'j', 'j'] } df = pd.DataFrame(data_dict) return df @pytest.fixture def missing_data_factors(): """DataFrame with missing factors data """ data_dict = {'c': ['a', None, 'a', 'b', 'b', None, 'c', 'a', 'a', 'c'], 'd': ['a', 'a', None, None, 'e', 'f', None, 'h', 'j', 'j'] } df = pd.DataFrame(data_dict) return df @pytest.fixture def missing_data_numeric(): """DataFrame with missing numeric data """ data_dict = {'a': [2, 2, None, None, 4, 4, 7, 8, None, 8], 'c': [1, 2, None, 4, 4, 4, 7, 9, None, 9], 'e': [1, 2, None, None, None, None, None, None, None, None] } df = pd.DataFrame(data_dict) return df @pytest.fixture def full_data_factors(): """DataFrame with no missing factors values """ data_dict = {'c': ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'a', 'a', 'c'], 'd': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'j'] } df = pd.DataFrame(data_dict) return df @pytest.fixture def full_data_factors_subset(): """DataFrame with no missing factors values """ data_dict = {'c': ['b', 'b', 'c', 'c', 'a', 'a', 'c'], 'd': ['d', 'e', 'f', 'g', 'h', 'j', 'j'] } df = pd.DataFrame(data_dict) return df @pytest.fixture def full_data_numeric(): """DataFrame with numeric data """ data_dict = {'a': [2, 2, 2, 3, 4, 4, 7, 8, 8, 8], 'c': [1, 2, 3, 4, 4, 4, 7, 9, 9, 9], 'e': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] } df = pd.DataFrame(data_dict) return df @pytest.fixture def single_values_data(): """DataFrame with single values in colums """ data_dict = {'a': [2, 2, 2, 3, 4, 4, 7, 8, 8, 8], 'b': ['123', '123', '123', '234', '456', '456', '789', '789', '789', '789'], 'c': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 'd': [1, 1, 1, 1, 1, 1, 1, 1, 1, None], 'e': [1, 2, None, None, None, None, None, None, None, None], 'f': [None, None, None, None, None, None, None, None, None, None], 'g': ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', None], 'h': ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'] } df = pd.DataFrame(data_dict) return df @pytest.fixture def text_data(): """DataFrame with text data """ data_dict = {'a': ['Happy Birthday!', 'It\'s your bday!'], 'b': ['Happy Arbor Day!', 'Happy Gilmore'], 'c': ['a', 'b'] } df = pd.DataFrame(data_dict) return df @pytest.fixture def boolean_data(): """Sample boolean data for bitwise operators """ data_dict = {'a': [True, True, False, False], 'b': [True, False, False, True], 'c': [False, True, True, False], 'd': [True, False, True, False], 'e': [False, True, False, True] } df = pd.DataFrame(data_dict) return df @pytest.fixture def binary_data(): """Sample binary data for bitwise operators """ data_dict = {'a': [1, 1, 0, 0], 'b': [1, 0, 0, 1], 'c': [0, 1, 1, 0], 'd': [1, 0, 1, 0], 'e': [0, 1, 0, 1] } df = pd.DataFrame(data_dict) return df @pytest.fixture def binary_series(): return pd.Series([1, 1, 0, 0]) @pytest.fixture def interaction_data(): """Sample binary data for bitwise operators """ data_dict = {'a': [2, 3, 4, 5], 'b': [1, 0, 0, 1], 'c': [0, 1, 1, 0], 'd': [1, 0, 1, 0], 'e': [0, 1, 0, 1] } df = pd.DataFrame(data_dict) return df @pytest.fixture def column_name_data(): """Sample binary data for bitwise operators """ data_dict = {' this column ': [1, 1], 'that+column': [1, 1], 'these/columns': [1, 1], 'those*columns': [1, 1], 'them-columns': [1, 1], '(thecolumns)': [1, 1] } df = pd.DataFrame(data_dict) return df
# Write a function filter_long_words() that takes a list of words # and an integer n and returns the list of # words that are longer than n. def filter_long_words(num, listOfWords): out_list = [] for word in listOfWords: if len(word) > num: out_list.append(word) return out_list listOfWords = ['ok', 'Thress', 'bolkat', 'servers', 'ss', 's'] print(filter_long_words(2, listOfWords))
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('course_selection', '0009_remove_semester_name'), ] operations = [ migrations.AddField( model_name='section', name='section_capacity', field=models.IntegerField(default=999), preserve_default=True, ), migrations.AddField( model_name='section', name='section_enrollment', field=models.IntegerField(default=0), preserve_default=True, ), ]
import os import webapp2 import jinja2 from google.appengine.ext import db import urllib from xml.dom import minidom template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape=True) class Handler(webapp2.RequestHandler): def write(self, *a, **kw): self.response.out.write(*a, **kw) def render_str(self, template, **params): t = jinja_env.get_template(template) return t.render(params) def render(self, template, **kw): self.write(self.render_str(template, **kw)) class Query(db.Model): source = db.StringProperty(required = True) destination = db.StringProperty(required = True) class MainPage(Handler): def get(self): qo = db.GqlQuery("SELECT * FROM Query") self.render('map.html', qo = qo) def post(self): addr1 = self.request.get("addr1") addr2 = self.request.get("addr2") a = Query(source = addr1, destination = addr2) a.put() url = 'http://maps.googleapis.com/maps/api/distancematrix/xml?origins=' + urllib.quote_plus(addr1) + '&destinations=' + urllib.quote_plus(addr2) + '&mode=driving&sensor=false' link = urllib.urlopen(url).read() x = minidom.parseString(link) p = x.getElementsByTagName('text')[1].childNodes [0].nodeValue li = p.split() dist = float(li[0]) dii = str(dist) self.response.write('The total distance between the source and the destination is' + ' ' + dii + 'km') if(dist <= 1.5): ans = 'Rs.15' total_taxi = 'Rs.19' else: districk = dist*10 ans = 'Rs.' + str(districk) d = dist - 1.5 t = d * 12.35 tot_taxi = t + 19 total_taxi = 'Rs.' + str(tot_taxi) dist_bus = dist if(dist_bus <= 2): j = 'Rs.6' self.render('fare.html', j = j, total_taxi = total_taxi, ans = ans) elif(dist_bus >=2 and dist_bus <=3): j = 'Rs.8' self.render('fare.html', j = j, total_taxi = total_taxi, ans = ans) elif(dist_bus >=3 and dist_bus <=5): j = 'Rs.10' self.render('fare.html', j = j, total_taxi = total_taxi, ans = ans) elif(dist_bus >=5 and dist_bus <=7): j = 'Rs.12' self.render('fare.html', j = j, total_taxi = total_taxi, ans = ans) elif(dist_bus >=7 and dist_bus <=10): j = 'Rs.15' self.render('fare.html', j = j, total_taxi = total_taxi, ans = ans) elif(dist_bus >=10 and dist_bus <=15): j = 'Rs.18' self.render('fare.html', j = j, total_taxi = total_taxi, ans = ans) elif(dist_bus >=15 and dist_bus <=20): j = 'Rs.20' self.render('fare.html', j = j, total_taxi = total_taxi, ans = ans) elif(dist_bus >=20 and dist_bus <=25): j = 'Rs.22' self.render('fare.html', j = j, total_taxi = total_taxi, ans = ans) elif(dist_bus >=25 and dist_bus <=30): j = 'Rs.25' self.render('fare.html', j = j, total_taxi = total_taxi, ans = ans) elif(dist_bus >=30 and dist_bus <=35): j = 'Rs.28' self.render('fare.html', j = j, total_taxi = total_taxi, ans = ans) elif(dist_bus >=35 and dist_bus <=40): j = 'Rs.30' self.render('fare.html', j = j, total_taxi = total_taxi, ans = ans) elif(dist_bus >=40 and dist_bus <=45): j = 'Rs.35' self.render('fare.html', j = j, total_taxi = total_taxi, ans = ans) elif(dist_bus >=45 and dist_bus <=50): j = 'Rs.40' self.render('fare.html', j = j, total_taxi = total_taxi, ans = ans) app = webapp2.WSGIApplication([('/', MainPage)], debug=True)
import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, "Add Menu Items") p = wx.Panel(self) self.txt = wx.TextCtrl(p, -1, "new item") btn = wx.Button(p, -1, "Add Menu Item") self.Bind(wx.EVT_BUTTON, self.OnAddItem, btn) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(self.txt, 0, wx.ALL, 20) sizer.Add(btn, 0, wx.TOP|wx.RIGHT, 20) p.SetSizer(sizer) self.menu = menu = wx.Menu() simple = menu.Append(-1, "Simple menu item") menu.AppendSeparator() exit = menu.Append(-1, "Exit") self.Bind(wx.EVT_MENU, self.OnSimple, simple) self.Bind(wx.EVT_MENU, self.OnExit, exit) menuBar = wx.MenuBar() menuBar.Append(menu, "Menu") self.SetMenuBar(menuBar) def OnSimple(self, event): wx.MessageBox("Simple menu item selected") def OnExit(self, event): self.Close() def OnAddItem(self, event): description = self.txt.GetValue() item = self.menu.Append(-1, description) self.BindNewAction(item, description) def BindNewAction(self, menu_item, text): def OnNewAction(event): message = '"%s" selected' % text wx.MessageBox(message) self.Bind(wx.EVT_MENU, OnNewAction, menu_item) wx.MessageBox("%s added" % text) app = wx.PySimpleApp() frame = MyFrame() frame.Show() app.MainLoop()
# -*- coding: utf-8 -*- """ Configuration file for the main ctip test suite. Created on Sat Jul 9 23:48:43 2016 @author: Aaron Beckett """ import sys, os import pytest sys.path.append(os.path.join(os.getcwd(), '.')) sys.path.append(os.path.join(os.getcwd(), '..')) pytest_plugins = ['helpers_namespace'] ########### Fixtures ################ ########### Helper funcs ############## @pytest.helpers.register def compare_configs(configs, schema): """Compare configs generated by a schema with a list of configs.""" # Define error messages incorrect_length = "Incorrect number of configs generated: {} != {}" incorrect_values = "Incorrect config values" generated = schema.configs() i = 0 try: while True: config = next(generated) i += 1 if not configs: pytest.fail(incorrect_length.format(i, i - 1)) for i in range(len(configs)): if configs[i] == config: del configs[i] break else: pytest.fail(incorrect_values) except StopIteration: if configs: pytest.fail(incorrect_length.format(i, i + len(configs)))
import os from flask import Flask, render_template, request, send_from_directory, jsonify from flask_mail import Mail, Message from flask_table import Table, Col import etherscan.accounts as accounts import config ''' Init ''' app = Flask(__name__) app.config['MAIL_SERVER'] = config.MAIL_SERVER app.config['MAIL_PORT'] = config.MAIL_PORT app.config['MAIL_USERNAME'] = config.MAIL_USERNAME app.config['MAIL_PASSWORD'] = config.MAIL_PASSWORD app.config['MAIL_USE_TLS'] = config.MAIL_USE_TLS app.config['MAIL_USE_SSL'] = config.MAIL_USE_SSL mail = Mail(app) eth_wallet_address = config.ETH_WALLET_ADDRESS etherscan_api_key = config.ETHERSCAN_API_KEY etherscan_api = accounts.Account(address=eth_wallet_address, api_key=etherscan_api_key) ''' Ethereum Table ''' ''' class EthTable(Table): #tx_hash = Col('TxHash') #tx_age = Col('Age') tx_from = Col('From') tx_to = Col('To') tx_value = Col('Value') #tx_fee = Col('TxFee') class Transaction(object): def __init__(self, tx_hash, tx_age, tx_from, tx_to, tx_value, tx_fee): self.tx_hash = tx_hash self.tx_age = tx_age self.tx_from = tx_from self.tx_to = tx_to self.tx_value = tx_value self.tx_fee = tx_fee # Get the eth transactions eth_transactions = etherscan_api.get_transaction_page(page=1, offset=10) # Create and populate the eth transaction table objects table_transactions = [] for transaction in eth_transactions: table_transactions.append( dict(#tx_hash=transaction["hash"], #tx_age=transaction["timeStamp"], tx_from=transaction["from"], tx_to=transaction["to"], tx_value=transaction["value"], #tx_fee=transaction["gasUsed"] ) ) # Populate the table with the transaction objects eth_table = EthTable(table_transactions, table_id='eth_table', classes=['table-responsive', 'table']) ''' ''' Ethereum Price ''' eth_value = int(etherscan_api.get_balance()) / config.WEI_DIVIDER ''' Web Page Routes ''' @app.route("/", methods=['GET']) def landing(): return render_template("index.html", eth_value=eth_value, eth_wallet=config.ETH_WALLET_ADDRESS) @app.route("/ajax/send_mail", methods=['POST']) def send_mail(): sender_name = request.form['name'] sender_email = request.form['email'] sender_phone = request.form['phone'] sender_message = request.form['message'] msg = Message( sender_name + ' has sent an email', sender=config.MAIL_SENDER_EMAIL, recipients=[config.MAIL_RECEIVER_EMAIL] ) msg.body = "Name: " + sender_name + "\n\n" + \ "Email: " + sender_email + "\n\n" + \ "Phone: " + sender_phone + "\n\n" + \ sender_message mail.send(msg) return "Sent" @app.route('/keybase.txt') def keybase(): return send_from_directory( os.path.join(app.root_path, 'static'), 'keybase.txt', mimetype='text/plain' ) @app.route('/.well-known/keybase.txt') def keybase_well_known(): return send_from_directory( os.path.join(app.root_path, 'static'), 'keybase.txt', mimetype='text/plain' ) if __name__ == '__main__': app.run(host='0.0.0.0')
from django.shortcuts import render, render_to_response from django.http import HttpResponse, Http404, HttpResponseRedirect from django.core.urlresolvers import reverse # Create your views here. def teacher(r): return HttpResponse('这是teacher的一个视图') def v2_exception(r): raise Http404 return HttpResponse('ok') def v10_1(request): return HttpResponseRedirect('/v11') def v10_2(requeset): return HttpResponseRedirect(reverse('v11')) def v8_get(request): rst = '' for k,v in request.GET.items(): rst += k + '--->' +v rst += ',' return HttpResponse('Get value of Request is {0}'.format(rst)) def v9_get(request): # 渲染模板并返回 return render_to_response('for_post.html') def v9_post(request): rst = '' for k,v in request.POST.items(): rst += k + '--->' + v rst += ',' return HttpResponse('Get value of POST is {0}'.format(rst)) def v11(requeset): return HttpResponse('这个是v11的访问返回哈') def render_test(request): # 环境变量 c = dict() rsp = render(request, 'render.html') return rsp def render2_test(request): # 环境变量 c = dict() c['name'] = 'xiaojiayu' rsp = render(request, 'render2.html', context=c) return rsp def render3_test(request): from django.template import loader # 得到模板 t = loader.get_template('render2.html') print(type(t)) r = t.render({'name':'are you ok? '}) print(type(r)) return HttpResponse(r) def render4_test(request): # 反馈回模板render rsp = render_to_response('render2.html', context={'name':'are you'}) return rsp
import csv """ Functions: create_portfolio() ---> creates a stock portfolio from user input best_investments() ---> finds the best x number of investments in a portfolio during a certain period worst_investments() ---> finds the worst x number of investments in a portfolio during a certain period """ def create_portfolio(): portfolio = set() ftse_codes = set([row['code'] for row in data[0:len(data)]]) code = input("Enter company code to add to portfolio. Enter EXIT when done: ") while code != "EXIT": if len(portfolio) >= 100: print("Sorry portfolio max reached. Your portfolio has been created") return(list(portfolio)) else: if code in ftse_codes: portfolio.add(code) code = input("Enter another code or enter EXIT to exit: ") else: code = input("Company not in FTSE. Enter another code or enter EXIT: ") else: if len(portfolio) >= 1: print("Your portfolio has been created") return(list(portfolio)) else: print("Portfolio is empty") return([]) def best_investments(data, portfolio, x, start_date, end_date): if end_date >= start_date and type(x) is int: if x >= 1 and x <= len(portfolio): returns = [] for code in portfolio: for r in data: if r['code'] == code and r['date'] == start_date and r['time'] == "09:00": start_price = float(r['price']) elif r['code'] == code and r['date'] == end_date and r['time'] == "17:00": end_price = float(r['price']) else: continue percent_returns = ((end_price - start_price) / start_price) * 100 returns.append(dict(code = code, percent_returns = percent_returns)) ordered_returns = sorted(returns, key=lambda t: t['percent_returns'], reverse=True) print("Returning top %d investments in portfolio" % x ) return([i['code'] for i in ordered_returns[0:x]]) else: print("Error: x must more than 1 and cannot be more than items in portfolio") return([]) else: print("Invalid input(s): End date cannot be earlier than start date and x has to be an integer") return([]) def worst_investments(data, portfolio, x, start_date, end_date): if end_date >= start_date and type(x) is int: if x >= 1 and x <= len(portfolio): returns = [] for code in portfolio: for r in data: if r['code'] == code and r['date'] == start_date and r['time'] == "09:00": start_price = float(r['price']) elif r['code'] == code and r['date'] == end_date and r['time'] == "17:00": end_price = float(r['price']) else: continue percent_returns = ((end_price - start_price) / start_price) * 100 returns.append(dict(code = code, percent_returns = percent_returns)) ordered_returns = sorted(returns, key=lambda t: t['percent_returns']) print("Returning worst %d investments in portfolio" % x ) return([i['code'] for i in ordered_returns[0:x]]) else: print("Error: x must more than 1 and cannot be more than items in portfolio") return([]) else: print("Invalid input(s): End date cannot be earlier than start date and x has to be an integer") return([]) if __name__ == "__main__": data = [] with open("ftse100.csv", "r") as f: reader = csv.DictReader(f) data = [r for r in reader] # Tests #p = create_portfolio() #print(p) #print(best_investments(data, p, 3, "14/10/2019", "16/10/2019")) #print(worst_investments(data, p, 3, "14/10/2019", "16/10/2019")) #print(worst_investments(data, ["AVV", "BARC","BKG", "AV.", "BLND", "BATS"], 3, "14/10/2019", "16/10/2019")) pass
# -*- encoding:utf-8 -*- from mako import runtime, filters, cache UNDEFINED = runtime.UNDEFINED __M_dict_builtin = dict __M_locals_builtin = locals _magic_number = 5 _modified_time = 1281454040.870805 _template_filename='/Library/Python/2.6/site-packages/pcpbridge/templates/pcast_error.mako' _template_uri='/pcast_error.mako' _template_cache=cache.Cache(__name__, _modified_time) _source_encoding='utf-8' from webhelpers.html import escape _exports = ['body', 'head_tags'] def _mako_get_namespace(context, name): try: return context.namespaces[(__name__, name)] except KeyError: _mako_generate_namespaces(context) return context.namespaces[(__name__, name)] def _mako_generate_namespaces(context): pass def _mako_inherit(template, context): _mako_generate_namespaces(context) return runtime._inherit_from(context, u'/base.mako', _template_uri) def render_body(context,**pageargs): context.caller_stack._push_frame() try: __M_locals = __M_dict_builtin(pageargs=pageargs) __M_writer = context.writer() # SOURCE LINE 2 __M_writer(u'\n\n') # SOURCE LINE 6 __M_writer(u'\n\n') # SOURCE LINE 10 __M_writer(u'\n\n') return '' finally: context.caller_stack._pop_frame() def render_body(context): context.caller_stack._push_frame() try: c = context.get('c', UNDEFINED) __M_writer = context.writer() # SOURCE LINE 8 __M_writer(u'\n <div name="error" title="') # SOURCE LINE 9 __M_writer(escape(c.code)) __M_writer(u'">') __M_writer(escape(c.exception)) __M_writer(u'</div>\n') return '' finally: context.caller_stack._pop_frame() def render_head_tags(context): context.caller_stack._push_frame() try: __M_writer = context.writer() # SOURCE LINE 4 __M_writer(u'\n <title>PCAST ERROR</title>\n') return '' finally: context.caller_stack._pop_frame()
from datetime import date, timedelta from django.contrib.auth.mixins import UserPassesTestMixin from django.contrib.auth.decorators import login_required from django.core.paginator import PageNotAnInteger, Paginator, EmptyPage from django.db.models import Q from django.http import Http404, HttpResponseRedirect, HttpResponse, JsonResponse from django.urls import reverse from django.utils.text import slugify from django.views.decorators.http import require_POST from django.views.generic import ListView, DetailView, TemplateView from django.views.generic.edit import CreateView from .forms import FermentativeProfileCreateForm, TodoForm, YeastCreateForm, BrandCreateForm from .helpers import * from .models import ActivityLog, Yeast, Brand, FermentativeProfile, Todo class AuthenticatedMixin(UserPassesTestMixin): def test_func(self): return self.request.user.is_authenticated class HomeView(AuthenticatedMixin, TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) yeasts = Yeast.objects.all().order_by( 'next_reinnoculation_limit_date') context['leveduras'] = yeasts[:4] context['activities'] = ActivityLog.objects.all() context['brands'] = model_shares(Brand) context['profiles'] = model_shares(FermentativeProfile) context['todo_form'] = TodoForm context['todo_list'] = self.request.user.todo_set.all() return context def todoDelete(request, id): obj = Todo.objects.get(pk=id) obj.delete() return HttpResponse("OK") @require_POST def todoAdd(request): form = TodoForm(request.POST) if form.is_valid(): obj = Todo(activity=request.POST['activity'], user=request.user) obj.save() return JsonResponse({'id': obj.id}) def todoComplete(request, id): obj = Todo.objects.get(pk=id) if obj.complete == True: obj.complete = False else: obj.complete = True obj.save() return HttpResponse("OK") class SearchView(AuthenticatedMixin, TemplateView): template_name = 'search.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) request = self.request query = request.GET.get("search") if query is not None: query = (Q(name__icontains=query)) context['results'] = True context['yeast'] = Yeast.objects.filter(query).order_by('name') context['brand'] = Brand.objects.filter(query).order_by('name') context['profile'] = FermentativeProfile.objects.filter(query).order_by( 'name') return context context['results'] = None return context class YeastListView(AuthenticatedMixin, ListView): model = Yeast template_name = 'bank/yeasts/yeast_list.html' def get_context_data(self, **kwargs): context = super().get_context_data() obj = yeast_order_by(self.request, context['object_list']) paginator = Paginator(obj, 8) page = self.request.GET.get('page') try: objects = paginator.page(page) except PageNotAnInteger: objects = paginator.page(1) except EmptyPage: objects = paginator.page(paginator.num_pages) context['object_list'] = objects context['page_obj'] = paginator.get_page(page) return context class YeastDetailView(AuthenticatedMixin, DetailView): model = Yeast template_name = 'bank/yeasts/yeast_detail.html' class YeastCreateView(AuthenticatedMixin, CreateView): model = Yeast form_class = YeastCreateForm template_name = 'bank/yeasts/yeast_create.html' def form_valid(self, form): obj = form.save(commit=False) obj.name = obj.name.title().strip() obj.user = self.request.user obj.slug = slugify(obj.name) obj.next_reinnoculation_limit_date = obj.last_reinnoculation + \ timedelta(days=180) obj.save() creation_log(Yeast, obj, self.request.user) return super().form_valid(form) @login_required(login_url='/login') def reinnoculate(request, slug): try: obj = Yeast.objects.get(slug=slug) obj.reinnoculation_count += 1 obj.last_reinnoculation = date.today() obj.next_reinnoculation_limit_date = date.today() + \ timedelta(weeks=24) obj.save() except Exception: raise Http404("Levedura não existe") reinnoculation_log(obj, request.user) return HttpResponseRedirect(reverse('yeast_detail', args=[slug])) @login_required(login_url='/login') def delete_yeast_from_bank(request, slug): try: obj = Yeast.objects.get(slug=slug) obj.delete() except Exception: raise Http404("Levedura não encontrada") deletion_log(Yeast, obj, request.user) return HttpResponseRedirect(reverse('home')) # Brand Views class BrandListView(AuthenticatedMixin, ListView): model = Brand paginate_by = 10 template_name = 'bank/brand/brand_list.html' class BrandCreateView(AuthenticatedMixin, CreateView): model = Brand form_class = BrandCreateForm template_name = 'bank/brand/brand_create.html' def form_valid(self, form): obj = form.save(commit=False) obj.name = obj.name.title().strip() obj.slug = slugify(obj.name) obj.save() creation_log(Brand, obj, self.request.user) return super().form_valid(form) class BrandDetailView(AuthenticatedMixin, DetailView): model = Brand template_name = 'bank/brand/brand_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data() obj = yeast_order_by(self.request, context['object'].yeast_set) paginator = Paginator(obj, 8) page = self.request.GET.get('page') try: objects = paginator.page(page) except PageNotAnInteger: objects = paginator.page(1) except EmptyPage: objects = paginator.page(paginator.num_pages) context['leveduras'] = objects context['page_obj'] = paginator.get_page(page) return context @login_required(login_url='/login') def delete_brand_from_bank(request, slug): try: obj = Brand.objects.get(slug=slug) obj.delete() except Exception as err: raise Http404("Marca não encontrada") deletion_log(Brand, obj, request.user) return HttpResponseRedirect(reverse('brand_list')) # Fermentative Profile class FermentativeProfileListView(AuthenticatedMixin, ListView): model = FermentativeProfile paginate_by = 10 template_name = 'bank/profile/profile_list.html' class FermentativeProfileCreateView(AuthenticatedMixin, CreateView): model = FermentativeProfile form_class = FermentativeProfileCreateForm template_name = 'bank/profile/profile_create.html' def form_valid(self, form): obj = form.save(commit=False) obj.name = obj.name.title().strip() obj.slug = slugify(obj.name) obj.save() creation_log(FermentativeProfile, obj, self.request.user) return super().form_valid(form) class FermentativeProfileDetailView(AuthenticatedMixin, DetailView): model = FermentativeProfile template_name = 'bank/profile/profile_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data() obj = yeast_order_by(self.request, context['object'].yeast_set) paginator = Paginator(obj, 8) page = self.request.GET.get('page') try: objects = paginator.page(page) except PageNotAnInteger: objects = paginator.page(1) except EmptyPage: objects = paginator.page(paginator.num_pages) context['leveduras'] = objects context['page_obj'] = paginator.get_page(page) return context @login_required(login_url='/login') def delete_profile_from_bank(request, slug): try: obj = FermentativeProfile.objects.get(slug=slug) obj.delete() except Exception: raise Http404("Perfil não encontrada") deletion_log(FermentativeProfile, obj, request.user) return HttpResponseRedirect(reverse('profile_list'))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # class BTree: class Node: def __init__(self): self.sons = [] self.keys = [] def __repr__(self): return 'Node' + str(self.keys) + str(self.sons) def _lower_bound(self, key): b = 0 e = len(self.sons) - 1 while b < e: mid = (b + e + 1) // 2 if mid == 0: # mid is never 0 actually pass elif self.keys[mid - 1] <= key: b = mid else: e = mid - 1 return b def __init__(self, t): self.root = self.Node() self.t = t def _inorder(self, cur): if cur == None: return for i, son in enumerate(cur.sons): if i > 0: yield cur.keys[i - 1] yield from self._inorder(son) def inorder(self): yield from self._inorder(self.root) def _preorder(self, cur): if cur == None: return for key in cur.keys: yield key for son in cur.sons: yield from self._preorder(son) def preorder(self): yield from self._preorder(self.root) def _split(self, node, parnode, pos): # root case if parnode is None: self.root = self.Node() left = self.Node() right = self.Node() left.keys = node.keys[:self.t - 1] right.keys = node.keys[self.t:] left.sons = node.sons[:self.t] right.sons = node.sons[self.t:] self.root.keys = [ node.keys[self.t - 1] ] self.root.sons = [left, right] return self.root else: left = self.Node() right = self.Node() left.keys = node.keys[:self.t - 1] right.keys = node.keys[self.t:] left.sons = node.sons[:self.t] right.sons = node.sons[self.t:] parnode.keys = parnode.keys[:pos] + [ node.keys[self.t - 1] ] + parnode.keys[pos:] parnode.sons = parnode.sons[:pos] + [left, right] + parnode.sons[pos + 1:] def _insert(self, key, node, parnode): if node is None: return None # node is full, and must be root if len(node.keys) == 2 * self.t - 1: assert node == self.root node = self._split(node, parnode, -1) assert len(node.keys) == 1 # to the right if node.keys[0] <= key: self._insert(key, node.sons[1], node) else: self._insert(key, node.sons[0], node) return # only possible for root at the beginning if len(node.sons) == 0: assert node == self.root node.sons.append(None) node.keys.append(key) node.sons.append(None) return pos = node._lower_bound(key) # we are in a leaf if node.sons[pos] is None: node.keys = node.keys[:pos] + [key] + node.keys[pos:] node.sons.append(None) else: # son is full, doing split from here if node.sons[pos] is not None and len(node.sons[pos].keys) == 2 * self.t - 1: self._split(node.sons[pos], node, pos) # go to right if node.keys[pos] <= key: self._insert(key, node.sons[pos + 1], node) else: self._insert(key, node.sons[pos], node) else: self._insert(key, node.sons[pos], node) def insert(self, key): self._insert(key, self.root, None) def _find(self, key, node): if node is None or len(node.sons) == 0: return None pos = node._lower_bound(key) if pos >= 1 and node.keys[pos - 1] == key: return node.keys[pos - 1] else: return self._find(key, node.sons[pos]) def find(self, key): return self._find(key, self.root) def _find_predecessor(self, key, node): if node.sons[0] == None: return node.keys[-1] else: return self._find_predecessor(key, node.sons[-1]) def _find_succesor(self, key, node): if node.sons[0] == None: return node.keys[0] else: return self._find_succesor(key, node.sons[0]) def _delete_key_leaf(self, key, node, pos): # condition for correctness of algorithm assert node == self.root or len(node.sons) >= self.t assert node.keys[pos] == key node.keys = node.keys[:pos] + node.keys[pos + 1:] node.sons.pop() def _merge_children_around_key(self, key, node, pos): assert pos >= 0 and pos < len(node.sons) - 1 y = self.Node() y.sons = node.sons[pos].sons + node.sons[pos + 1].sons y.keys = node.sons[pos].keys + [node.keys[pos]] + node.sons[pos + 1].keys node.keys = node.keys[:pos] + node.keys[pos + 1:] node.sons = node.sons[:pos] + [y] + node.sons[pos + 2:] def _move_node_from_left_child(self, node, pos): assert pos > 0 and len(node.sons[pos - 1].keys) >= self.t node.sons[pos].keys = [node.keys[pos - 1] ] + node.sons[pos].keys node.sons[pos].sons = [ node.sons[pos - 1].sons[-1] ] + node.sons[pos].sons node.keys[pos - 1] = node.sons[pos - 1].keys[-1] node.sons[pos - 1].sons = node.sons[pos - 1].sons[:-1] node.sons[pos - 1].keys = node.sons[pos - 1].keys[:-1] def _move_node_from_right_child(self, node, pos): assert pos < len(node.sons) - 1 and len(node.sons[pos + 1].keys) >= self.t node.sons[pos].keys = node.sons[pos].keys + [node.keys[pos] ] node.sons[pos].sons = node.sons[pos].sons + [ node.sons[pos + 1].sons[0] ] node.keys[pos] = node.sons[pos + 1].keys[0] node.sons[pos + 1].sons = node.sons[pos + 1].sons[1:] node.sons[pos + 1].keys = node.sons[pos + 1].keys[1:] def _fix_empty_root(self, node): if node == self.root and len(node.sons) == 1: self.root = node.sons[0] return self.root else: return node def _delete(self, key, node): if node is None or len(node.sons) == 0: return pos = node._lower_bound(key) # the key to delete is here if pos > 0 and node.keys[pos - 1] == key: # this node is a leaf if node.sons[pos] is None: self._delete_key_leaf(key, node, pos - 1) # left child node has enough keys elif len(node.sons[pos - 1].keys) >= self.t: kp = self._find_predecessor(key, node.sons[pos - 1]) node.keys[pos - 1] = kp self._delete(kp, node.sons[pos - 1]) # right child node has enough keys elif len(node.sons[pos].keys) >= self.t: kp = self._find_succesor(key, node.sons[pos]) node.keys[pos - 1] = kp self._delete(kp, node.sons[pos]) # both children have minimal number of keys, must combine them else: self._merge_children_around_key(key, node, pos - 1) # here I should take care of missing root node = self._fix_empty_root(node) self._delete(key, node) else: # we are on a leave and haven't found the key, we have nothing to do if node.sons[pos] is None: pass # the amount of keys in the child is enough, simply recurse elif len(node.sons[pos].keys) >= self.t: self._delete(key, node.sons[pos]) # we must push a key to the child else: # left sibbling has enough keys if pos > 0 and len(node.sons[pos - 1].keys) >= self.t: self._move_node_from_left_child(node, pos) self._delete(key, node.sons[pos]) # right sibbling has enough keys elif pos < len(node.sons) - 1 and len(node.sons[pos + 1].keys) >= self.t: self._move_node_from_right_child(node, pos) self._delete(key, node.sons[pos]) # must merge with one of sibblings else: if pos > 0: self._merge_children_around_key(key, node, pos - 1) # here I should take care of missing root node = self._fix_empty_root(node) self._delete(key, node) elif pos < len(node.sons) - 1: self._merge_children_around_key(key, node, pos) # here I should take care of missing root node = self._fix_empty_root(node) self._delete(key, node) # this shouldn't be possible else: assert False def delete(self, key): self._delete(key, self.root) def _find_all(self, key, node, ans): if node is None or len(node.sons) == 0: return b = 0 e = len(node.sons) - 1 while b < e: mid = (b + e + 1) // 2 if mid == 0: # mid is never 0 actually pass elif node.keys[mid - 1] < key: b = mid else: e = mid - 1 left = b b = 0 e = len(node.sons) - 1 while b < e: mid = (b + e + 1) // 2 if mid == 0: # mid is never 0 actually pass elif node.keys[mid - 1] > key: e = mid - 1 else: b = mid right = b # print(left, right, len(node.sons)) for i in range(left, right + 1): self._find_all(key, node.sons[i], ans) if i < right: assert node.keys[i] == key ans.append(node.keys[i]) def find_all(self, key): ans = [] self._find_all(key, self.root, ans) return ans def dummy_test0(): T = BTree(6) rng = list(range(9000)) shuffle(rng) for i in rng: T.insert(i) #print(T.root, '\n') for i in range(9): print(T.find(i), '\n') def dummy_test1(): T = BTree(3) for i in range(9): T.insert(i) print(T.root) T.delete(5) print(T.root) T.delete(4) print(T.root) T.insert(100) T.insert(101) T.insert(3) T.insert(3) T.insert(3) print(T.root) T.delete(1) print(T.root) def dummy_test2(): T = BTree(3) for _ in range(10): T.insert(0) T.insert(1) T.insert(2) T.insert(-1) print(T.root) ans = T.find_all(0) print(len(ans), ans) import random import collections def map_test(): ''' It's purpose is to compare againt map implementation ''' seed = random.randint(0, 1000) print('random seed %d' % seed) # seed = 195 random.seed(seed) num_tests = 10000 num_ops = 200 debug = False for deg in range(2, 20): for test in range(num_tests): B = BTree(deg) M = collections.defaultdict(int) if debug: print('Beginning block of tests %d %d' % (deg, test)) for _ in range(num_ops): if debug: print(B.root) prob = random.random() elem = random.randint(0, 10) if prob < 1 / 3: # insert if debug: print('insert %d' % elem) B.insert(elem) M[elem] += 1 elif prob < 1/3 + 1/3: # find if debug: print('find %d' % elem) r1 = (B.find(elem) != None) r2 = (elem in M and M[elem] > 0) if r1 != r2: print(B.root) print(r1, r2, elem) assert r1 == r2 elif prob < 1/3 + 1/3 + 1/6: # findall if debug: print('findall %d' % elem) r1 = len(B.find_all(elem)) if elem not in M: r2 = 0 else: r2 = M[elem] if r1 != r2: print(B.root) print(r1, r2, elem) assert r1 == r2 else: # delete if debug: print('delete %d' % elem) if elem in M and M[elem] > 0: M[elem] -= 1 B.delete(elem) if debug: print('Block finished correctly') def walk_test(): B = BTree(3) for i in range(10): B.insert(i) print(B.root) print(list(B.preorder())) print(list(B.inorder())) def dummy_tests(): walk_test() def main(args): ''' Testing BTree Implementation ''' dummy_tests() return 0 if __name__ == '__main__': import sys #sys.setrecursionlimit(10 ** 4) sys.exit(main(sys.argv))
import cv2 as cv import numpy as np img = cv.imread('../sample/affine.png') img2 = cv.imread('../sample/median.png') kernel = np.ones((5,5), np.float32)/25 dst = cv.filter2D(img, -1, kernel) # img_blur = cv.blur(img, (5,5)) img_blur = cv.GaussianBlur(img, (5,5), 0) median = cv.medianBlur(img2, 5) img3 = cv.imread('../sample/texture.png') bilateral_blur = cv.bilateralFilter(img3, 9, 75, 75) cv.imshow('original', img) cv.imshow('result', dst) cv.imshow('gaussizn blur', img_blur) cv.imshow('megian blur', median) cv.imshow('bilateral blur', bilateral_blur) cv.waitKey(0) cv.destroyAllWindows()
from itsdangerous import TimedJSONWebSignatureSerializer from mall import settings from itsdangerous import BadSignature def verify_token(id,email): s = TimedJSONWebSignatureSerializer(settings.SECRET_KEY,expires_in=3600) token = s.dumps({'id':id,'email':email}) return token.decode() def decode_token(token): s = TimedJSONWebSignatureSerializer(settings.SECRET_KEY,expires_in=3600) try: result = s.loads(token) except BadSignature: return None return result
#coding=utf-8 from django.http import HttpResponse from django.utils import simplejson import logging import time logger = logging.getLogger(__name__) def grid_filter_toggle(request): # time.sleep(5) result=[] for i in range(10): result.append({'UV':'60','source' :'http://www.sina.com.cn','name':'bill','sex':'test','test1':i+1}) json = simplejson.dumps({'stores':result,'totalItem':500,'countCol':500}) logger.info(json) return HttpResponse(json, mimetype='application/json') def grid_index(request): result=[] result.append({'source' :'http://www.sina.com.cn','name':'bill','sex':'test'}) # result.append({'source' :'http://www.douban.com','name':{'content':'im','attr':{'rowspan':5,'colspan':2}},'sex':'111111','test1':'w'}) for i in range(4): result.append({'source' :'http://www.sina.com.cn','name':'bill','sex':'test','test1':i+1}) result.append({'source' :'http://www.google.com.cn','name':'alex','sex':'m'}) result.append({'sex':'test'}) # for i in range(17): # result.append({'source' :'http://www.sina.com.cn','name':'bill','sex':'test'}) result.append({'source' :'http://www.sina.com.cn','name':'bill','sex':'test'}) json = simplejson.dumps({'stores':result,'totalItem':500}) logger.info(json) return HttpResponse(json, mimetype='application/json') def get_group_message(request): result=[] result.append({'source' :'http://www.sina.com.cn','name':'bill','sex':'test'}) result.append({'source' :'http://www.apache.com.cn','name':'bill','sex':'test'}) json = simplejson.dumps({'stores':result,'totalItem':500}) logger.info(json) return HttpResponse(json, mimetype='application/json') def get_compare_group(request): result=[] result.append({ 'source':'http://www.sina.com.cn', 'date1':{'pv':20,'uv':21,'vistor':12}, 'date2':{'pv':20,'uv':21,'vistor':12} }) result.append({ 'source':'http://www.weibo.com', 'date1':{'pv':20,'uv':21,'vistor':12}, 'date2':{'pv':20,'uv':21,'vistor':12} }) result.append({ 'source':'http://www.google.com', 'date1':{'pv':20,'uv':21,'vistor':12}, 'date2':{'pv':20,'uv':21,'vistor':12} }) json = simplejson.dumps({'stores':result,'totalItem':500}) logger.info(json) return HttpResponse(json, mimetype='application/json') def get_tree_deep_main(request): result=[] result.append({'source' :{'content':'http://www.sina.com.cn','attr':{'colspan':'all'}}}) result.append({'source' :{'content':'http://www.weibo.com','attr':{'colspan':'all'}}}) result.append({'source' :{'content':'http://www.google.com','attr':{'colspan':'all'}}}) json = simplejson.dumps({'stores':result,'totalItem':500}) logger.info(json) return HttpResponse(json, mimetype='application/json') def get_tree_deep_item(request): result=[] result.append({ 'pv':20,'uv':21,'vistor':12}) result.append({ 'pv':20,'uv':21,'vistor':12}) result.append({ 'pv':20,'uv':21,'vistor':12}) json = simplejson.dumps({'stores':result,'totalItem':500}) logger.info(json) return HttpResponse(json, mimetype='application/json') def get_pie_grid(request): result=[] piedata= [] piedata.append({ "value": "25", "label": "google" }) piedata.append( { "value": "35", "label": "baidu", }) piedata.append( { "value": "40", "label": "weibo", }) result.append({'source':'http://www.google.com','pv':20,'uv':21,'vistor':12,'pie':{'type':'pieType','data':piedata}}) result.append({'source':'http://www.baidu.com','pv':20,'uv':21,'vistor':12}) result.append({'source':'http://www.weibo.com','pv':20,'uv':21,'vistor':12}) json = simplejson.dumps({'stores':result,'totalItem':500}) logger.info(json) return HttpResponse(json, mimetype='application/json') def get_group(request): result=[] result.append({ 'source':'http://www.sina.com.cn', 'group':[{ 'dateRange':'2012' , 'pv':20,'uv':21,'vistor':12},{'dateRange':'2011' ,'pv':50,'uv':21,'vistor':12}] }) result.append({ 'source':'http://www.weibo.com', 'group':[{'pv':20,'uv':21,'vistor':12},{'pv':20,'uv':21,'vistor':12}] }) result.append({ 'source':'http://www.google.com', 'group':[{'pv':20,'uv':21,'vistor':12},{'pv':20,'uv':21,'vistor':12}] }) json = simplejson.dumps({'stores':result,'totalItem':500}) logger.info(json) return HttpResponse(json, mimetype='application/json')
# -*- coding: utf-8 -*- import tensorflow as tf import tensorflow_hub as hub import numpy as np import time import requests from flask import Flask, request, jsonify from elasticsearch import Elasticsearch # Flask Server 설정 app = Flask(__name__) flask_host = "localhost" flask_port = "5000" # ElasticSearch Address es_address = "http://localhost:9200" ''' 이미지 URL 을 통해 이미지 전처리 299 x 299 x 3 shape tensor 로 전처리된 이미지 반환 ''' def load_img(url): # URL 로 부터 이미지 읽기 # JPEG 이미지를 uint8 W X H X 3 tensor 로 Decode img = tf.image.decode_jpeg(requests.get(url).content, channels=3) # Resize 299 x 299 x 3 shape tensor img = tf.compat.v1.image.resize_image_with_pad(img, 299, 299) # new axis 를 추가하여 Data type 을 uint8 에서 float32 로 변환 # float32 1 x 299 x 299 x 3 tensor (inception_v3 model 에서 요구하는 형태) img = tf.image.convert_image_dtype(img, tf.float32)[tf.newaxis, ...] return img ''' 이미지 TF 특징점 저장 이미지 URL 을 사용하여 이미지의 TF 특징점을 뽑고, Elasticsearch의 "img_list"에 저장 ''' @app.route("/saveImagenetFeature", methods=['POST']) def saveImagenetFeature(): data = request.get_json() img_url = data["img_url"] # 이미지 URL을 활용하여 이미지 전처리 후 로드 img = load_img(img_url) # 이미지 feature vector 계산 features = module(img) # 배열에서 single-dimensional entries 제거 # type : numpy.ndarray, float32, 2048 columns feature_vector = np.squeeze(features) # Update ElasticSearch - ES의 'img_list' 에서 'item_id' 에 해당하는 이미지 정보에 'imagenet_feature' 넣어주기 source_to_update = { "doc": { "imagenet_feature": feature_vector.tolist() } } response = es.update(index="img_list", doc_type="_doc", id=data["item_id"], body=source_to_update) return response['result'] ''' 이미지 TF 특징점 + 일반 정보 저장 이미지 URL 을 사용하여 이미지의 TF 특징점을 뽑고, 이미지의 일반 정보(item_id, item_name, category_id, img_url)와 함께 ES의 "tf_img_list"에 저장 ''' @app.route("/saveAllImageInfo", methods=['POST']) def saveAllImageInfo(): data = request.get_json() item_id = data["item_id"] item_name = data["item_name"] img_url = data["img_url"] # 저장 시간 register_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) # 이미지 URL을 활용하여 이미지 전처리 후 로드 img = load_img(img_url) # 이미지 feature vector 계산 features = module(img) # 배열에서 single-dimensional entries 제거 # type : numpy.ndarray, float32, 2048 columns feature_vector = np.squeeze(features) # Save in ElasticSearch - 'tf_img_list' index 에 저장 imagenet_feature = {"item_id": item_id, "item_name": item_name, "img_url": img_url, "register_time": register_time, "category_id": data["category_id"], "imagenet_feature": feature_vector.tolist()} response = es.index(index="tf_img_list", id=item_id, body=imagenet_feature) return response['result'] ''' 이미지 TF 특징점 추출 이미지 URL을 사용하여 이미지의 TF 특징점을 뽑고 반환 ''' @app.route("/getImagenetFeature") def getImagenetFeature(): parameter_dict = request.args.to_dict() img_url = parameter_dict["img_url"] # 이미지 URL을 활용하여 이미지 전처리 후 로드 img = load_img(img_url) # 이미지 feature vector 계산 features = module(img) # 배열에서 single-dimensional entries 제거 # type : numpy.ndarray, float32, 2048 columns feature_vector = np.squeeze(features) # json imagenet_feature = {"imagenet_feature": feature_vector.tolist()} return jsonify(imagenet_feature) if __name__ == "__main__": # ElasticSearch 접속 es = Elasticsearch(es_address) # tfhub.dev handle 사용 모듈 정의 # https://tfhub.dev/google/imagenet/inception_v3/feature_vector/4 에서 Download Model module_handle = "model/inception_v3/" # 아래 방식은 환경이 달라지면 에러를 유발하므로 지양 # module_handle = "https://tfhub.dev/google/imagenet/inception_v3/feature_vector/4" # 모듈 로드 module = hub.load(module_handle) # run Server app.run(host=flask_host, port=flask_port, debug=True)
from ._builtin import Page, WaitPage from .translator import system_start from .models import Constants from .utility import nanoseconds_since_midnight as labtime from django.core.cache import cache from django.conf import settings class PreWaitPage(WaitPage): pass # def after_all_players_arrive(self): # # self.group.connect_to_exchange() # # self.group.send_exchange(system_start('S')) # # self.group.spawn( # # Constants.investor_py, # # Constants.investor_url, # # self.group.investor_file # # ) # # self.group.spawn( # # Constants.jump_py, # # Constants.jump_url, # # self.group.jump_file # # ) # self.subsession.start_time = labtime() class index(Page): pass class ResultsWaitPage(WaitPage): def after_all_players_arrive(self): self.group.disconnect_from_exchange() # cache.clear() # this will go somewhere here dont forget !! class Results(Page): pass page_sequence = [ PreWaitPage, index, ResultsWaitPage, Results ]
#!/usr/bin/python # -*- coding: utf-8 -*- from openravepy import * env = Environment() # create the environment env.SetViewer('qtcoin') # start the viewer env.Load('data/katanatable.env.xml') # load a scene robot = env.GetRobots()[0] # get the first robot raw_input("Press Enter to start...") manip = robot.GetActiveManipulator() ikmodel = databases.inversekinematics.InverseKinematicsModel(robot,iktype=IkParameterization.Type.Translation3D) if not ikmodel.load(): ikmodel.autogenerate() with robot: # lock environment and save robot state robot.SetDOFValues([2.58, 0.547, 1.5, -0.7],[0,1,2,3]) # set the first 4 dof values Tee = manip.GetEndEffectorTransform() # get end effector ikparam = IkParameterization(Tee[0:3,3],ikmodel.iktype) # build up the translation3d ik query sols = manip.FindIKSolutions(ikparam, IkFilterOptions.CheckEnvCollisions) # get all solutions h = env.plot3(Tee[0:3,3],10) # plot one point with robot: # save robot state for sol in sols[::10]: # go through every 10th solution robot.SetDOFValues(sol,manip.GetArmIndices()) # set the current solution env.UpdatePublishedBodies() # allow viewer to update new robot raw_input('press any key') print robot.GetDOFValues() # robot state is restored to original raw_input("Press Enter to exit...") env.Destroy()
# 自己的解法超时了,判断确实很僵硬 # 评论区有个思路我类似但是判断有优化的解法,见solution2 # solution3的大体思路是相同的,实现更妙一些 class Solution: def solveNQueens(self, n): """ :type n: int :rtype: List[List[str]] """ ans = [['.' for _ in range(n)] for _ in range(n)] ret = [] self.tback(n, ans, n, ret, -1) return ret def tback(self, n, ans, left, ret, num): if left == 0: tmp = ["" for _ in range(n)] for i in range(n): t = '' for j in ans[i]: t+=j tmp[i] = t ret.append(tmp) return for i in range(n): for j in range(n): if i*n+j <= num:continue if not self.islegal(ans,i,j): continue ans[i][j] = 'Q' self.tback(n,ans,left-1,ret,i*n+j) ans[i][j] = '.' return def islegal(self, ans, n, m): l,j = n,m while l+1<len(ans) and j+1<len(ans): if ans[l+1][j+1] == 'Q':return False else: l+=1;j+=1 l,j = n,m while l-1>=0 and j-1>=0: if ans[l-1][j-1] == 'Q':return False else: l=l-1;j=j-1 l, j = n, m while l+1<len(ans) and j-1>=0: if ans[l+1][j-1] == 'Q':return False l=l+1;j=j-1 l, j = n, m while l-1>=0 and j + 1 <len(ans): if ans[l - 1][j + 1] == 'Q': return False l = l - 1; j = j + 1 l, j = n, m while l+1<len(ans): if ans[l+1][j] == 'Q':return False l+=1 l = n while l-1>=0: if ans[l-1][j] == 'Q':return False l-=1 l, j = n, m while j+1<len(ans): if ans[l][j+1] == 'Q':return False j+=1 j = m while j - 1 >=0: if ans[l][j - 1] == 'Q': return False j -= 1 return True class Solution2: def solveNQueens(self, n): ans,ret = [['.' for _ in range(n)] for _ in range(n)],[] self.tback(ans, 0, ret) return ret def tback(self, ans, col, ret): n = len(ans) if col==len(ans): tmp = ["" for _ in range(n)] for i in range(n): tmp[i] = ''.join(ans[i]) ret.append(tmp) return for i in range(n): if self.isvalid(ans,i,col): ans[i][col] = 'Q' self.tback(ans, col+1, ret) ans[i][col] = '.' return def isvalid(self,ans,x,y): for i in range(len(ans)): for j in range(0,y): #分别对应 与ans[i][j]成45度,135度角,水平成直线的点 if ans[i][j] == 'Q' and (x+y==i+j or x+j==y+i or x==i): return False return True def solveNQueens3(self, n): def dfs(queens, t45, t135): if len(queens) == n: result.append(queens) return for i in range(n): j = len(queens) if i not in queens and i-j not in t45 and i+j not in t135: dfs(queens+[i],t45+[i-j],t135+[i+j]) result = [] dfs([],[],[]) return len(result) print(Solution2().solveNQueens3(1))
""" Django settings for quartz_project project. Generated by 'django-admin startproject' using Django 3.0.1. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["localhost", "127.0.0.1", "qwartz.herokuapp.com", "www.qwartz.digital"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'cloudinary_storage', 'django.contrib.staticfiles', "cloudinary", 'crispy_forms', 'quartz_app', 'library_app', 'users_app', 'storages', 'collectfast', 'sorl.thumbnail', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'quartz_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'quartz_project.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } # } DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": os.environ.get('NAME'), "USER": os.environ.get('USER'), "PASSWORD": os.environ.get('PASSWORD'), "HOST": os.environ.get('HOST'), "PORT": "", } } DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True) # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) CRISPY_TEMPLATE_PACK = 'bootstrap4' #this modifies the redirect after the login - very important -- change to any page LOGIN_REDIRECT_URL = 'profile' ##this tells django to look for the login page after using the decorator LOGIN_URL = 'login' if DEBUG: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' ##during development # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID") # AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY") # AWS_STORAGE_BUCKET_NAME = "django-image-library" # AWS_S3_FILE_OVERWRITE = False # AWS_DEFAULT_ACL = None CLOUDINARY_STORAGE ={ 'CLOUD_NAME': os.environ.get("CLOUD_NAME"), 'API_KEY': os.environ.get("API_KEY"), 'API_SECRET': os.environ.get("API_SECRET") } DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage'
# Must install more_itertools and scikit-bio(need to run "python setup.py install" from source for skbio) # Written by Griffin Calme (2016) # Runs a Needleman-Wunsch global sequence alignment and iteratively merges the overlapping sequences # Takes a line-separated text file of overlapping peptide subsequences and outputs the original supersequence # This is similar to shotgun sequencing of DNA, but for peptides from skbio import Protein from skbio.alignment import global_pairwise_align_protein from more_itertools import unique_everseen import sys def open_fragment_library(filename): # Not a dependency with open(filename) as f: subsequence_library = f.read().splitlines() # Open file and save to list, split items by line no_duplicates_library = list(unique_everseen(subsequence_library)) # Remove duplicate subsequences no_duplicates_library = [x.upper() for x in no_duplicates_library] # Force uppercase amino acids print('\nFilename: ' + filename) print('\nTotal number of amino acid subsequences: ' + str(len(subsequence_library))) print('Unique amino acid subsequences: ' + str(len(no_duplicates_library))) print('\nSubsequence library with duplicates removed:') print(no_duplicates_library) print('\n') return no_duplicates_library def contig_merger(growing_seq, compared_seq, original_growing_sequence): merged_contig = [] # List for containing each AA of merged sequence for index, letter1 in enumerate(growing_seq): letter2 = compared_seq[index] if letter1 == '-': # If the letter in seq1 is hyphen, take letter from seq2 merged_contig.append(letter2) elif letter2 == '-': merged_contig.append(letter1) # If the letter in seq2 is a hyphen, take letter from seq1 elif letter1 != letter2: # If the letters do not match anywhere in the sequence, abort merging merged_contig = original_growing_sequence # But return the growing sequence break elif letter1 == letter2: # If the letters match, take the letter from the growing seq merged_contig.append(letter1) # In the case that merging was aborted, this will do nothing to a string type merged_contig = ''.join(merged_contig) # Takes the list of letters and merges back to a sequence string return merged_contig def sequence_assembler(fragment_library, min_overlap, min_match_score=40): working_library = fragment_library assembled_peptide_library = [] while len(working_library) != 0: # try first: growing_sequence = working_library[0] working_library.remove(growing_sequence) # This part runs the assembly for sequence in working_library: aln, score, position_list = global_pairwise_align_protein(Protein(growing_sequence), Protein(sequence), gap_open_penalty=10000, penalize_terminal_gaps=False) grow_seq, compare_seq = aln match = grow_seq.match_frequency(compare_seq, relative=False) if match >= min_overlap and score > min_match_score: my_merged_contig = contig_merger(str(grow_seq), str(compare_seq), growing_sequence) growing_sequence = my_merged_contig sys.stdout.write('\r') sys.stdout.write(growing_sequence) sys.stdout.flush() # removes used fragments from working library working_library = [fragment for fragment in working_library if fragment not in growing_sequence] print('') assembled_peptide_library.append(growing_sequence) # Remove peptides that have not found any matches unmatched_peptides = [peptide for peptide in assembled_peptide_library if peptide in fragment_library] assembled_peptide_library = [peptide for peptide in assembled_peptide_library if peptide not in fragment_library] return assembled_peptide_library, unmatched_peptides
# Create your views here. from django.shortcuts import get_object_or_404, render_to_response from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from django.template import RequestContext from comptetence.models import Candidat def index(request): return render_to_response('comptetence/index.html', context_instance=RequestContext(request)) def candidats(request): candidats=Candidat.objects.all() return render_to_response('comptetence/candidat_list.html', {'listeCandidats':candidats} ,context_instance=RequestContext(request)) def candidatsAvecCriteres(request): return render_to_response('comptetence/candidat_rechercher.html',context_instance=RequestContext(request)) def candidatDetail(request, candidat_id): p = get_object_or_404(Candidat, pk=candidat_id) return render_to_response('comptetence/candidat_detail.html', {'candidat': p}) def searchCandidats(request): listeResultat = Candidat.objects.filter(nom__contains=request.POST['nameSearched']) return render_to_response('comptetence/candidat_list.html', {'listeCandidats':listeResultat} ,context_instance=RequestContext(request))
from flask import Flask, request, abort import numpy as np import cv2 import json import base64 app = Flask(__name__) @app.before_first_request def startup(): global face_cascade face_cascade = cv2.CascadeClassifier('cascade.xml') @app.route("/detect", methods=['POST']) def detect(): global face_cascade req_json = request.get_json() if 'content' in req_json: np_img = np.fromstring(base64.b64decode(req_json['content']), np.uint8) img = cv2.imdecode(np_img, cv2.IMREAD_COLOR) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray = cv2.equalizeHist(gray) faces = face_cascade.detectMultiScale(gray, scaleFactor = 1.1, minNeighbors = 5, minSize = (24, 24)) detected = [] for (x,y,w,h) in faces: detected.append({ "x" : int(x), "y" : int(y), "w" : int(w), "h" : int(h) }) print(detected) return json.dumps({ "detected" : detected}) else: abort(400, "Invalid request for /detect") @app.route("/auto_crop", methods=['POST']) def auto_crop(): global face_cascade req_json = request.get_json() if 'content' in req_json: np_img = np.fromstring(base64.b64decode(req_json['content']), np.uint8) img = cv2.imdecode(np_img, cv2.IMREAD_COLOR) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray = cv2.equalizeHist(gray) faces = face_cascade.detectMultiScale(gray, scaleFactor = 1.1, minNeighbors = 5, minSize = (24, 24)) print(faces) faces = faces.tolist() if len(faces): max_face_ind = faces.index(max(faces, key=lambda x: x[2]*x[3])) x,y,w,h = faces[max_face_ind] cropped = img[y:y+h, x:x+w] else: cropped = img cv2.imwrite("res_img.png", cropped) _, buffer = cv2.imencode('.jpg', cropped) jpg_as_text = base64.b64encode(buffer) return json.dumps({"image": jpg_as_text.decode("utf-8")}) else: abort(400, "Invalid request for /auto_crop") if __name__ == "__main__": app.run()
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect from django.shortcuts import render, redirect from django.utils.http import is_safe_url from django.conf import settings from .models import Container, Item from .forms import ContainerForm, ItemForm ALLOWED_HOSTS = settings.ALLOWED_HOSTS def home_view(request, *args, **kwargs): return render(request, "pages/home.html", context={}, status=200) def container_detail_view(request, container_id, *args, **kwargs): data = { "id": container_id, } status = 200 try: obj = Container.objects.get(id=container_id) data["id"] = container_id data["what"] = "container" data["name"] = obj.name data["length"] = obj.length data["width"] = obj.width data["height"] = obj.height data["color"] = obj.color data["purpose"] = obj.purpose data["note"] = obj.note except: # if cannot get the object data["message"] = "not found" status = 404 # return JsonResponse(data, status=status) return render(request, 'components/detail.html', context={"data": data}, status=status) def container_list_view(request, *args, **kwargs): qs = Container.objects.all() container_list = [ {"id": x.id, "name": x.name, "color": x.color} for x in qs] data = { "response": container_list } return JsonResponse(data) def container_create_view(request, *args, **kwargs): form = ContainerForm(request.POST or None) next_url = request.POST.get("next") or None if form.is_valid(): obj = form.save(commit=False) obj.save() if next_url != None and is_safe_url(next_url, ALLOWED_HOSTS): return redirect(next_url) form = ContainerForm() return render(request, 'components/form.html', context={"form": form, "what": "container"}) def item_detail_view(request, item_id, *args, **kwargs): data = { "id": item_id, } status = 200 try: obj = Item.objects.get(id=item_id) data["id"] = item_id data["what"] = "item" data["name"] = obj.name data["length"] = obj.length data["width"] = obj.width data["height"] = obj.height data["color"] = obj.color data["category"] = obj.category data["in_container"] = obj.in_container data["purpose"] = obj.purpose data["note"] = obj.note except: # if cannot get the object data["message"] = "not found" status = 404 # return JsonResponse(data, status=status) return render(request, 'components/detail.html', context={"data": data}, status=status) def item_list_view(request, *args, **kwargs): qs = Item.objects.all() item_list = [ {"id": x.id, "name": x.name, "color": x.color, "in_container": x.in_container} for x in qs] data = { "response": item_list } return JsonResponse(data) def item_in_list_view(request, container_id, *args, **kwargs): qs = Item.objects.all().filter(in_container = container_id) item_list = [ {"id": x.id, "name": x.name, "color": x.color, "in_container": x.in_container} for x in qs] data = { "response": item_list } return JsonResponse(data) def item_create_view(request, *args, **kwargs): form = ItemForm(request.POST or None) next_url = request.POST.get("next") or None if form.is_valid(): obj = form.save(commit=False) obj.save() if next_url != None and is_safe_url(next_url, ALLOWED_HOSTS): return redirect(next_url) form = ItemForm() return render(request, 'components/form.html', context={"form": form, "what": "item"})
from collections import namedtuple from webpreview import OpenGraph, TwitterCard def get_webpreview(url): """Gets the web preview for URL.""" WebPrev = namedtuple('WebPrev', ['title', 'description', 'image']) og = OpenGraph(url, {'og:title', 'og:description', 'og:image'}) tc = TwitterCard(url, {'twitter:title', 'twitter:description', 'twitter:image'}) title = og.title or tc.title description = og.description or tc.description image = og.image or tc.image return WebPrev(title=title, description=description, image=image)
from collections import namedtuple, deque from apscheduler.schedulers.asyncio import AsyncIOScheduler __all__ = [ 'CB_FUNC', 'CD_TIME', 'F_AT', 'F_MSG', 'F_PRIV_GRP', 'F_REGEX', 'WHITELIST', 'Holder' ] CB_FUNC = 0 CD_TIME = 1 F_PRIV_GRP = 2 WHITELIST = 3 F_REGEX = 4 F_MSG=5 F_AT=6 class Holder(object): def __init__(self): self.cmd_stats = {} self.chat_history = {} self.scheduler = AsyncIOScheduler() self.plugin_storage = {} def __getattr__(self, item): if item in self.plugin_storage: return self.plugin_storage[item] else: raise AttributeError("Object has no attribute '{}'".format(item)) def append_msg(self, group_id, sender_id, msg): if group_id not in self.chat_history: self.chat_history[group_id] = deque([], maxlen=200) # left is new self.chat_history[group_id].appendleft((sender_id, msg)) def find_msg(self, group_id, sender_id, maxlen=3): msg = [] if group_id not in self.chat_history: return if sender_id == 0: if maxlen > len(self.chat_history[group_id]): return list(self.chat_history[group_id]) else: return list(self.chat_history[group_id])[:maxlen] for entry in self.chat_history[group_id]: if entry[0] == sender_id: msg.append(entry) if len(msg) >= maxlen: break return msg def set_plugin_storage(self, name, value): if name not in self.plugin_storage: self.plugin_storage[name] = value else: raise Exception('Do not call set_plugin_storage twice for {}'.format(name)) # Not __all__ constants = namedtuple('Constants', ['MSG', 'NO_MSG', 'REGEX', 'NOT_REGEX', 'AT_SENDER', 'NO_AT_SENDER', 'PRIVATE', 'GROUP', 'PRIV_GRP']) const = constants(True, False, True, False, True, False, {'private'}, {'group'}, {'private', 'group'})
from time import time, sleep from random import randint import requests import numpy as np import pandas as pd from bs4 import BeautifulSoup from emails.send_emails import Email from src.general_functions import GeneralFunctions class IhubData(Email, GeneralFunctions): def __init__(self, verbose=0, delay=True): super().__init__() self.verbose = verbose self.delay = delay def check_link_integrity(self, symbol_id): ''' Input: symbol_id (int) If a stock has updated it's symbol, the investorshub website will have a new link for the message board forum. This function is a failsafe to make sure the link is up to date. ''' ihub_code = self.get_value('ihub_code', symbol_id=symbol_id) url = "https://investorshub.advfn.com/"+str(ihub_code) content = requests.get(url).content soup = BeautifulSoup(content, "lxml") # This location in the website will contain the current link tag = soup.find_all('a', id="ctl00_CP1_btop_hlBoard")[0]['href'][1:-1] # If there is in fact a new link, then this will update the database # with the new link and symbol if ihub_code != tag: new_symbol = tag.split('-')[-2].lower() self._update_link(symbol_id, tag, new_symbol) print(f'New Symbol. Changed to {new_symbol}') else: print(f'No change in symbol') def _update_link(self, symbol_id, tag, new_symbol): ''' If the symbol has been updated, this function will update the databases for the messsage boards, stock prices, ticker_symbols. The function will also send an email update to notify the user ''' # First pull the existing symbol old_symbol = self.get_value('symbol', symbol_id=symbol_id) # First append the changed symbol table df = pd.DataFrame(columns=['symbol_id', 'changed_from', 'changed_to', 'date_modified']) df.loc[0] = [symbol_id, old_symbol, new_symbol, pd.Timestamp.now()] self.to_table(df, 'items.changed_symbol') # Then modify the symbols table update_query = f''' UPDATE items.symbol SET symbol = "{new_symbol}", ihub_code = "{tag}", modified_date = "{pd.Timestamp.now()}" WHERE symbol_id = {symbol_id};''' self.cursor.execute(update_query) self.conn.commit() self.send_email('update_symbol', ['', new_symbol]) def _total_and_num_pinned(self, url): ''' Function call gets the most recent page for the message board and extracts both num_pinned, and num_posts (desc below) Output ------ num_pinned: int, shows how many posts are 'pinned' on the top of the board. num_posts: int, shows, to-date, how many messages have been posted on the specific board ''' try: # Retrieve the first page on the board df, _ = self._get_page(url, most_recent=True, sort=False) # Number of pinned posts determined by the number of posts that are not # in 'numerical' order at the top of the page post_list = df.post_number.tolist() for i, post in enumerate(post_list): if post == post_list[i+1]+1: return i, post_list[i] except: return 0, 0 def _clean_table(self, table, sort): ''' Function takes the raw dataframe and formats it Parameters ---------- df: pandas dataframe, sort: boolean, the message board posts are displayed in descending order. Sort=True sorts them Output ------ df: pandas dataframe, message board table ''' # 0 - post_number # 1 - subject # 2 - username # 3 - post_time df = pd.DataFrame(table) df = df.applymap(lambda x: x.text) df.columns = ['post_number', 'subject', 'username', 'post_time'] df[['subject', 'username']] = df[['subject', 'username']].applymap( lambda x: x.strip('-#\n\r').replace('\n', "").replace( '\r', '').replace('\t', '').replace('\\', '')) df.post_number = df['post_number'].map(lambda x: x.strip( '-#\n\r').replace(' ', '').replace('\n', "").replace( '\r', '').split('\xa0')[0]) df.post_number = df.post_number.astype(float) df.post_number = df.post_number.astype(int) df['post_time'] = pd.to_datetime(df['post_time']) if sort: df.sort_values('post_number', inplace=True) return df def _get_page(self, url, num_pinned=0, post_number=1, most_recent=False, sort=True, error_list=[]): ''' Parameters ---------- post_number: int, specific post number of page to be returned most_recent: boolean, returns the currently displayed page if True sort: boolean, as displayed on the webpage, the message board posts are displayed in descending order. Sort sorts them Output ------ df: pandas dataframe, pulled from the webpage, parsed, and cleaned ''' url = "https://investorshub.advfn.com/"+str(url) if not most_recent: url += "/?NextStart="+str(post_number) content = requests.get(url).content soup = BeautifulSoup(content, "lxml") rows = list(soup.find('table', id="ctl00_CP1_gv")) table = [] for row in rows[(2+num_pinned):-2]: cell_lst = [cell for cell in list(row)[1:5]] table.append(cell_lst) return self._clean_table(table, sort), error_list def _add_deleted_posts(self, page_df, post_number): ''' Parameters ---------- df: pandas dataframe, full message board data Output ------ df: pandas dataframe, original data with deleted posts added in Moderators of a message board forum may remove a post if it violates the ihub policy. While the content of these posts is unknown the actual post is important when suming the posts per a given day. ''' should_be_on_page = set(range(min(page_df.post_number), post_number+1)) should_be_on_page.add(post_number) deleted_post_numbers = should_be_on_page - set(page_df.post_number) del_df = pd.DataFrame(columns=page_df.columns) for num, post_num in enumerate(deleted_post_numbers): del_df.loc[num] = [post_num, '<del>', '<del>', np.nan] return pd.concat([page_df, del_df]) def update_posts(self, symbol_id): # first, pull the necessary symbol info symbol = self.get_value('symbol', symbol_id=symbol_id) ihub_code = self.get_value('ihub_code', symbol_id=symbol_id) num_pinned, num_posts = self._total_and_num_pinned(ihub_code) self.interval_time, self.original_time = time(), time() # calculate which post numbers are missing from the database posts_to_add = set(range(1, num_posts+1)) already_added = set(self.get_list('existing_posts', symbol_id=symbol_id)) posts_to_add -= already_added error_list = [] total_posts_to_add = len(posts_to_add) print(f"Adding {total_posts_to_add} post(s) for {symbol} ({symbol_id})") while posts_to_add: post_number = max(posts_to_add) page = post_number while True: try: page_df, error_list = self._get_page(ihub_code, post_number=page, num_pinned=num_pinned, error_list=error_list) break # if the number one post is deleted and you're calling it, it will fail except ValueError: page += 1 except Exception as e: print(f'{e} ERROR ON PAGE: {str(post_number)} for {ihub_code}') error_list.append(post_number) page_df = pd.DataFrame() break page_df = self._add_deleted_posts(page_df, post_number) page_df['symbol_id'] = symbol_id self.to_table(page_df, 'ihub.message_board') posts_to_add -= set(page_df.post_number) if self.verbose: num = (total_posts_to_add-len(posts_to_add)) total = total_posts_to_add self.status_update(num, total) if self.delay: sleep(randint(2, 15))
""" @File: settings.py @CreateTime: 2019/12/9 下午8:45 @Desc: 数据库的配置信息 """ # mysql CONFIG = { 'default': 'mysql', 'mysql': { "driver": "mysql", "host": "127.0.0.1", "database": "test_one", "user": "root", "password": "123456", "prefix": "", "port": 3306 } } # redis redis_settings = { "host": "127.0.0.1", "port": 6379, "password": "", "db": 0 } # MongoDB URI = "mongodb://127.0.0.1:27017/" DB_NAME = "test-data" DOC_NAME = "record" USERNAMR = "libai" PASSWORD = "123456"
#!/usr/bin/python3 # Why do we need to use functions? # 1. Because you can pass different parameters to the same function # 2. Because it represent a unit of computation, which can be reused # 3. Functions can be reused by other people # examples of functions def add(x,y): #here x and y are parameters of the function # x and y can be used in the body of the function return(x+y) add(3,5) def sq(x): return(x*x) sq(4) sq(29) def area_of_triangle(b,h): return(b*h/2) area_of_triangle(300,467) area_of_triangle(1,2) ## Fibonacci ## can you write a function that can give you the ## n-th Fibonacci number? def fib(a): if a == 1: return(1) if a == 2: return(1) else: return(fib(a-1)+fib(a-2)) fib(1) fib(2) fib(3) fib(10) for a in range(1,20): fib(a)
"""Create Reply Table Revision ID: e1e764225513 Revises: eb3c24fa735b Create Date: 2018-12-07 23:56:29.728584 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = 'e1e764225513' down_revision = 'eb3c24fa735b' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('reply', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('reply_type', mysql.ENUM('SMS', 'MAIL'), nullable=False), sa.Column('subject', sa.String(length=100), nullable=False), sa.Column('content', sa.String(length=4294000000), nullable=False), sa.Column('name_placeholder', sa.String(length=10), nullable=False), sa.Column('created_at', mysql.TIMESTAMP(timezone=True), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=False), sa.Column('updated_at', mysql.TIMESTAMP(timezone=True), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=False), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('reply') # ### end Alembic commands ###
# filters RNIE output by score, write file with RNIE scores over 20 and make scatterplots import argparse import os.path import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import collections import sys import os.path ####################################################################### ####################################################################### def checkGffFormat(v): b = os.path.splitext(v)[1][1:].lower() if b != 'gff': raise argparse.ArgumentTypeError('gff format file type expected') else: return v ####################################################################### ####################################################################### parser = argparse.ArgumentParser(description= 'Filter RNIE output by score (>20.0)' + '\n' 'Usage:' + '\t' + 'filterRNIE.py <options> -i -o') #required files: parser.add_argument('-i', dest='rnieFile', help='path to RNIE output in gff format', type=checkGffFormat, required=True) parser.add_argument('-o', dest='outpath', help='output path and filename prefix', required=True) args = parser.parse_args() rnieFile = args.rnieFile outpath = args.outpath outfile = outpath + 'filtered_trim_50_nucsRNIE_TSvsRS_RNIEover20.bed' plot = outpath + 'filtered_trim_50_nucsRNIE_TSvsRS_RNIEover20.png' ####################################################################### ####################################################################### RNIEdict = {} xs = [] ys = [] RNIEover20X = [] RNIEover20Y = [] with open(rnieFile, 'r') as rnie: for line in rnie: coord = int(line.split('_')[0]) x = float(line.split('_')[1]) y = float(line.split('_')[2]) strand = line.split('_')[3].split()[0] score = float(line.split()[5]) xs.append(x) ys.append(y) if coord not in RNIEdict and score > 20.0: RNIEdict[coord] = [x,y,strand,score] RNIEover20X.append(x) RNIEover20Y.append(y) with open(outfile, 'w') as out: for value, key in list(RNIEdict.items()): out.write(str(value) + '\t' + str(key[0]) + '\t' + str(key[1]) + '\t' + str(key[2]) + '\t' + str(key[3]) + '\n') npX = np.array(xs) npY = np.array(ys) npRNIEover20X = np.array(RNIEover20X) npRNIEover20Y = np.array(RNIEover20Y) print('RNIE scores over 20.0: ' + str(len(RNIEover20X))) ####################################################################### ####################################################################### fig, ax = plt.subplots(1,1, figsize=(6,6), dpi=120) plt.title('Filter RNIE scores', fontsize=14) plt.scatter(npY+1, npX+1, s=15) plt.scatter(npRNIEover20Y+1, npRNIEover20X+1, label='RNIE over 20.0', c='red', marker='x', s=12 ) plt.xscale('log') plt.yscale('log') plt.xlim(1, 100000) plt.ylim(1, 100000) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.xlabel('Avg. RNA-Seq count', fontsize=14) plt.ylabel('Max. Term-Seq count', fontsize=14) plt.grid(True) ax.set_axisbelow(True) plt.legend(prop={'size': 14}) plt.savefig(plot,dpi=300)
fib = [0,1] print(fib[-1]) print(fib[-2]) for x in range(1,int(input('fib '))): fib.extend([int(fib[-1]+fib[-2])]) print(fib[-1]) input()
import math import time num_times = 3 v = 0 while v <= 2.0 * math.pi * num_times: ledpower = 0.1 * (-math.cos(v) + 1) #print ledpower setLEDBack(ledpower) v = v + .03 time.sleep(0.01) setLEDBack(0)
# Dwight Kappl # Word count def lengthSent(txt): temp = txt.split() tempLen = len(temp) print("There are " + str(tempLen) + " words.") return tempLen #usr = input("Enter a sentence: ") #lengthSent(usr)
# -*- mode:python; coding:utf-8; tab-width:4 -*- import Ice Ice.loadSlice('-I {} cannon.ice'.format(Ice.getSliceDir())) import Cannon import numpy as np import math import itertools def matrix_add(A,B): order=A.ncols C=Cannon.Matrix(order,[]) for i in range(order**2): C.data.append(sum([A.data[i]]+[B.data[i]])) return C def matrix_multiply(A, B): order = A.ncols C = Cannon.Matrix(order, []) for i, j in itertools.product(xrange(order), repeat=2): C.data.append( sum(A.data[i * order + k] * B.data[k * order + j] for k in xrange(order)) ) return C def list_split(list, parts): x=np.array(list) list=np.array(np.split(x,parts)) return list.tolist() def matrix_split(matrix, block_order): x=np.array(matrix.data,dtype=int) x=x.reshape(matrix.ncols,matrix.ncols) pr=np.array(np.hsplit(x,(matrix.ncols/block_order))) result=[None]*((matrix.ncols/block_order)**2) it=0 for z in xrange(0,matrix.ncols,block_order): for i in range(matrix.ncols/block_order): aux=pr[i][z] for j in xrange(1,block_order): aux=np.concatenate((aux,pr[i][z+j])).tolist() result[it]=Cannon.Matrix(block_order,aux) it=it+1 return result def matrix_horizontal_shift(matrix, block_order): x=np.array(matrix.data,dtype=int) x=x.reshape(matrix.ncols,matrix.ncols) pr=np.array(np.hsplit(x,(matrix.ncols/block_order))) result=[None]*block_order parcial=x[0] i=1 while(i<matrix.ncols): if((i%block_order)==0): aux=i for j in range(block_order): parcial=np.concatenate((parcial,np.roll(x[i],matrix.ncols-aux))).tolist() i=i+1 else: parcial=np.concatenate((parcial,x[i])).tolist() i=i+1 result=Cannon.Matrix(matrix.ncols,parcial) return result def matrix_vertical_shift(matrix, block_order): x=np.array(matrix.data,dtype=int) x=x.reshape(matrix.ncols,matrix.ncols) pr=np.array(np.hsplit(x,(matrix.ncols/block_order))) data=pr result=data[0][0] for i in range(matrix.ncols/block_order): for k in range(i): for j in range(matrix.ncols): if(i>=(1)and j<(matrix.ncols-block_order)):#PROBLEMA aux=data[i][j].tolist() data[i][j]=data[i][j+block_order] data[i][j+block_order]=aux for j in range(matrix.ncols): for i in range(matrix.ncols/block_order): result=np.concatenate((result,data[i][j])) for i in range(block_order): result=np.delete(result,0,0) result=Cannon.Matrix(matrix.ncols,result.tolist()) return result def matrix_join(*lista): aux=np.array(lista[0].data,dtype=int) for i in range(0,len(lista),int(math.sqrt(len(lista)))): it=0 k=(int(math.sqrt(len(lista)))) for j in range(int(math.sqrt(len(lista)))*lista[0].ncols): x=np.array(lista[i+j%int(math.sqrt(len(lista)))].data,dtype=int) x=x.reshape(lista[i].ncols,lista[i].ncols) if(j>=k): it=it+1 k=(int(math.sqrt(len(lista))))+k aux=np.concatenate((aux,x[it])) for i in range(lista[0].ncols**2): aux=np.delete(aux,0) result=Cannon.Matrix(int(math.sqrt(len(lista)))*lista[0].ncols,aux.tolist()) return result
''' Function: define the network Author: Charles 微信公众号: Charles的皮卡丘 ''' import numpy as np '''define the network''' class Network(): def __init__(self, fc1=None, fc2=None, **kwargs): self.fc1 = np.random.randn(5, 16) if fc1 is None else fc1 self.fc2 = np.random.randn(16, 2) if fc2 is None else fc2 self.fitness = 0 '''predict the action''' def predict(self, x): x = x.dot(self.fc1) x = self.activation(x) x = x.dot(self.fc2) x = self.activation(x) return x '''activation function''' def activation(self, x): return 0.5 * (1 + np.tanh(0.5 * x))
import re from lib.common.abc import Vulnerability class XSS(Vulnerability): name = 'CROSS-SITE SCRIPTING (XSS)' keyname = 'xss' def __init__(self, file_path): super().__init__(file_path) def find(self): return self._find(r'<.+>.*(\'|").*(\$[a-zA-Z0-9_]+).*(\'|").*</.+>|<.*(\'|").*<\?php.*(\$[a-zA-Z0-9_]+).*(\'|").*>', False) def __is_user_input(self, field): for line in self.get_lines(): if re.search(r'_(GET|POST|DELETE|PUT|PATCH|OPTIONS)\[(.*)%s.*\]' % field, line): return True return False
""" Serialize data to/from CSV """ import os import csv from functools import partial from orun.core.serializers import python, base from orun.apps import apps from orun.db import connection class Deserializer(base.Deserializer): def deserialize(self, update=False): """ Deserialize a stream or string of CSV data. """ h = self.stream.readline().strip() stream_or_string = self.stream if self.format == 'csv': delimiter = ';' if delimiter not in h and ',' in h: delimiter = ',' else: delimiter = '\t' cols = h.split(delimiter) reader = csv.DictReader(stream_or_string, fieldnames=cols, delimiter=delimiter) cols = reader.fieldnames model_name = self.path.name.rsplit('.', 1)[0] model = apps[model_name] try: # set identity_insert on mssql database table if connection.vendor == 'mssql': cur = connection.cursor() cur.execute('''set identity_insert %s on''' % model._meta.db_table) # mandatory fields for csv deserializer i = 0 try: for i, obj in enumerate(python.Deserializer(reader, model=model, fields=cols, force=update)): obj.save(using=self.database) except Exception as e: print('Error at line:', i) raise self.postpone = [partial(self.reset_sequence, model)] finally: # set identity_insert on mssql database table if connection.vendor == 'mssql': cur = connection.cursor() cur.execute('''set identity_insert %s off''' % model._meta.db_table)
def pares_rango(lim_inf, lim_sup): def main(): lim_inf = int(input("Valor 1: ")) lim_sup = int(input("Valor 2: ")) pares_rango(lim_inf, lim_sup) if __name__=='__main__': main()
import sys import argparse from math import sqrt, pi, exp, fabs import matplotlib.pyplot as plt from scipy import integrate from .utils.numerical_integration import composite_trapezoidal, composite_simpson def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--a', type=float, default=0) parser.add_argument('--b', type=float, default=1) parser.add_argument('--method', default='cs') parser.add_argument('--h', type=float, default=0.01, help='步长') parser.add_argument('--tol', type=float) return parser.parse_args() def main(): args = get_args() a = args.a b = args.b fn = lambda x: 1 / sqrt(2 * pi) * exp(-(x**2)/2) real_val = integrate.quad(fn, 0, 1)[0] if args.tol not in [None]: tol = args.tol for M in range(1, 100): if fabs(composite_trapezoidal(fn, a, b, M) - real_val) < tol: print("使用复合梯形公式计算, 当精度为1e-4时, h=%f, n=%d" % ((b-a)/M, M)) break for M in range(1, 100): if fabs(composite_simpson(fn, a, b, M) - real_val) < tol: print("使用复合辛普森公式计算, 当精度为1e-4时, h=%f, n=%d" % ((b-a)/(2*M), M)) break elif args.method == 'cs': M = int((b-a) / (2 * args.h)) answer = composite_simpson(fn, a, b, M) print("使用复合辛普森公式计算的结果为: %f, 误差为: %.15f" % (answer, fabs(real_val-answer))) elif args.method == 'ct': M = int((b-a)/args.h) answer = composite_trapezoidal(fn, a, b, M) print("使用复合梯形公式计算的结果为: %f, 误差为: %.15f" % (answer, fabs(real_val-answer))) if __name__ == '__main__': print(sys.argv) main()
def two_teams(sailors): a = [] b = [] for i in sailors: a.append(i) if sailors[i] > 40 or sailors[i] < 20 else b.append(i) return [sorted(a),sorted(b)] print(two_teams({'Smith': 34,'Wesson': 22,'Coleman': 45,'Abrahams': 19}), [['Abrahams', 'Coleman'],['Smith', 'Wesson'] ]) print(two_teams({'Fernandes': 18,'Johnson': 22,'Kale': 41,'McCortney': 54}), [['Fernandes', 'Kale', 'McCortney'],['Johnson'] ]) # if __name__ == '__main__': # print("Example:") # print(two_teams({'Smith': 34, 'Wesson': 22, 'Coleman': 45, 'Abrahams': 19})) # # # These "asserts" using only for self-checking and not necessary for auto-testing # assert two_teams({ # 'Smith': 34, # 'Wesson': 22, # 'Coleman': 45, # 'Abrahams': 19}) == [ # ['Abrahams', 'Coleman'], # ['Smith', 'Wesson'] # ] # # assert two_teams({ # 'Fernandes': 18, # 'Johnson': 22, # 'Kale': 41, # 'McCortney': 54}) == [ # ['Fernandes', 'Kale', 'McCortney'], # ['Johnson'] # ] # print("Coding complete? Click 'Check' to earn cool rewards!")
print('Para finalizar o progama digite \033[34m999\033[m') cont = soma = n = 0 n = int(input('Digite um número: ')) while n != 999: soma += n cont += 1 n = int(input('Digite um número: ')) print(f'Foram digitados {cont} número(s) e a soma entre eles foi {soma}')
from PyQt5.QtWidgets import QWidget, QLabel from PyQt5.QtGui import QPainter, QColor from PyQt5.QtGui import QIcon, QPixmap class GameScreen(QWidget): def __init__(self, parent): super(GameScreen, self).__init__(parent) self._parent = parent self._music_on = False self._on_pause = False self._music_img_pixmap = QPixmap('assets/music.png') self._pause_img_pixmap = QPixmap('assets/coffee.png') self._game_grid_values = [[None for _ in range(10)] for __ in range(20)] self._option_grid_values = [[None for _ in range(4)] for __ in range(4)] self._init_view() def _init_view(self): padding_x = 50 padding_y = 25 width = self._parent.width() - 2 * padding_x height = self._parent.height() // 2 - 2 * padding_y height -= height % 20 self.resize(width, height) self.move(padding_x, padding_y) self._init_game_grid() self._init_option_grid() self._init_labels() def _init_game_grid(self): height = self.height() - 20 self._game_grid_dims = { 'x': 10, 'y': 10, 'w': height // 2, 'h': height } self._atom_dims = { 'w': self._game_grid_dims['w'] // 10, 'h': self._game_grid_dims['h'] // 20, } def _init_option_grid(self): width = self._atom_dims['w'] * 4 + 4 self._option_grid_dims = { 'x': self.width() * 0.8 - (width // 2), 'y': self.height() // 2 - 20, 'w': width, 'h': self._atom_dims['h'] * 4 + 4 } def _init_labels(self): def _create_label(y, text): x = self.width() * 0.8 label = QLabel(self) label.setText(text) label.show() label.move(x - (label.width() // 2), y) label.setStyleSheet("background-color: Transparent") return label self._labels = [] self._labels.append(_create_label(10, 'SCORE')) self._labels.append(_create_label(30, '0000')) self._labels.append(_create_label(50, 'HI-SCORE')) self._labels.append(_create_label(70, '0000')) lower_label_height_ref = self._option_grid_dims['y'] + self._option_grid_dims['h'] + 5 self._labels.append(_create_label(lower_label_height_ref, '0/0')) self._labels.append(_create_label(lower_label_height_ref + 20, 'LEVEL 1')) self._labels.append(_create_label(lower_label_height_ref + 40, 'SPEED 1')) self.hide_labels() def show_labels(self): for label in self._labels: label.show() def hide_labels(self): for label in self._labels: label.hide() def _draw_atom(self, painter, dims, x, y, should_erase=False): gd = dims ad = self._atom_dims x = gd['x'] + x * ad['w'] y = gd['y'] + y * ad['h'] w = ad['w'] h = ad['h'] if not should_erase: painter.drawRect(x, y, w, h) color = QColor('#222') else: color = QColor('#c6d4cd') painter.fillRect(x + 2, y + 2, w - 3, h - 3, color) def paintEvent(self, QPaintEvent): painter = QPainter(self) painter.fillRect(self.rect(), QColor('#c6d4cd')) painter.drawRect( self._game_grid_dims['x'] - 5, self._game_grid_dims['y'] - 5, self._game_grid_dims['w'] + 10, self._game_grid_dims['h'] + 10, ) painter.drawRect( self._option_grid_dims['x'] - 2, self._option_grid_dims['y'] - 2, self._option_grid_dims['w'], self._option_grid_dims['h'], ) for h in range(20): for w in range(10): if self._game_grid_values[h][w]: self._draw_atom(painter, self._game_grid_dims, w, h) elif self._game_grid_values[h][w] is False: self._game_grid_values[h][w] = None self._draw_atom(painter, self._game_grid_dims, w, h, True) for h in range(4): for w in range(4): if self._option_grid_values[h][w]: self._draw_atom(painter, self._option_grid_dims, w, h) elif self._option_grid_values[h][w] is False: self._option_grid_values[h][w] = None self._draw_atom(painter, self._option_grid_dims, w, h, True) if self._music_on: painter.drawPixmap( self.width() * 0.67, self.height() - 25, 17, 17, self._music_img_pixmap ) if self._on_pause: painter.drawPixmap( self.width() * 0.67 + 30, self.height() - 26, 17, 17, self._pause_img_pixmap ) def draw_game_atoms(self, *coordinates, value=True): for x, y in coordinates: if x < 20 and y < 10 and x >= 0 and y >= 0: self._game_grid_values[x][y] = value self.update() def draw_option_atoms(self, *coordinates, value=True): for x, y in coordinates: if x < 20 and y < 10 and x >= 0 and y >= 0: self._option_grid_values[x][y] = value self.update() def show_music_icon(self): self._music_on = True self.update() def hide_music_icon(self): self._music_on = False self.update() def show_pause_icon(self): self._on_pause = True self.update() def hide_pause_icon(self): self._on_pause = False self.update()
# 314 Binary Tree Vertical Order Traversal # # Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column). # # If two nodes are in the same row and column, the order should be from left to right. # # Examples: # Given binary tree [3,9,20,null,null,15,7], # 3 # / \ # 9 20 # / \ # 15 7 # return its vertical order traversal as: # [ # [9], # [3,15], # [20], # [7] # ] # Given binary tree [3,9,20,4,5,2,7], # _3_ # / \ # 9 20 # / \ / \ # 4 5 2 7 # return its vertical order traversal as: # [ # [4], # [9], # [3,5,2], # [20], # [7] # ] import sys sys.path.append('../../') from leetCodeUtil import TreeNode from collections import defaultdict class Solution(object): def verticalOrder(self, root): if not root: return [] nodeQueue, res, table = [], [], defaultdict(list) nodeQueue.append([0, root]) while len(nodeQueue) > 0: pair = nodeQueue.pop(0) seq, node = pair[0], pair[1] table[seq].append(node.value) if node.left: nodeQueue.append([seq-1, node.left]) if node.right: nodeQueue.append([seq+1, node.right]) for key in sorted(table.keys()): res.append(table[key]) return res if __name__ == '__main__': sol = Solution() root = TreeNode(3) node1 = TreeNode(9) node2 = TreeNode(20) node3 = TreeNode(15) node4 = TreeNode(7) root.left = node1 root.right = node2 node2.left = node3 node2.right = node4 exp = [ [9], [3,15], [20], [7] ] assert sol.verticalOrder(root) == exp # Given binary tree [3,9,20,4,5,2,7], # _3_ # / \ # 9 20 # / \ / \ # 4 5 2 7 root = TreeNode(3) node1 = TreeNode(9) node2 = TreeNode(20) node3 = TreeNode(15) node4 = TreeNode(4) node5 = TreeNode(5) node6 = TreeNode(2) node7 = TreeNode(7) root.left = node1 root.right = node2 node1.left = node4 node1.right = node5 node2.left = node6 node2.right = node7 exp = [ [4], [9], [3,5,2], [20], [7] ] assert sol.verticalOrder(root) == exp
''' mortgage_loan_calc1.py calculate the monthly payment on a mortgage loan tested with Python27 and Python33 ''' import math def calc_mortgage_bank(bank_principal, bank_interest, bank_years): ''' given mortgage loan principal, interest(%) and years to pay calculate and return monthly payment amount ''' # monthly rate from annual percentage rate interest_rate_calc_bank = bank_interest/(100 * 12) # total number of payments payment_num_bank_calc = bank_years * 12 # calculate monthly payment monthly_bank_payment = bank_principal * \ (interest_rate_calc_bank / (1-math.pow((1+interest_rate_calc_bank), (-payment_num_bank_calc)))) return monthly_bank_payment def calc_mortgage_family(family_principal, family_interest, family_years): ''' this calculates the second part of the mortgage, that's provided outside of the bank loan ''' # monthly rate form annual percentage rate interest_rate_family = family_interest/(100*12) # total number of payments payment_num_family = family_years * 12 # calcullate monthly payments payment_family = family_principal * \ (interest_rate_family/(1-math.pow((1+interest_rate_family), (-payment_num_family)))) return payment_family ## EDITABLE INFORMATION # down payment purchase_price = 399000 down_payment = 100000 monthly_hoas = 610 annual_taxes = 4915 bank_mortgage_total = 100000 monthly_insurance = 80 ## BANK MORTAGE INFORMATION # bank mortgage amount bank_principal = bank_mortgage_total #bank annual interest bank_interest = 3.4 # years to pay off mortgage bank_years = 30 ## FAMILY MORTAGE INFORMATION # family mortgage amount family_principal = purchase_price - down_payment - bank_principal #family annual interest family_interest = 2.0 # years to pay off mortgage family_years = 30 # calculate monthly payment amount frp, baml monthly_payment_bank = calc_mortgage_bank(bank_principal, bank_interest, bank_years) # calculate monthly payment amount monthly_payment_family = calc_mortgage_family(family_principal, family_interest, family_years) # combine the two mortages total_monthly_mortgage_amount = int(monthly_payment_bank) + int(monthly_payment_family) total_monthly_cost = total_monthly_mortgage_amount + monthly_hoas + (annual_taxes/12) + monthly_insurance # calculate total amount paid total_mortgage_amount = int(monthly_payment_bank * bank_years * 12) + int(monthly_payment_family * family_years * 12) total_30_year_costs = total_mortgage_amount + (annual_taxes*bank_years) + (monthly_hoas * 12 * bank_years) + (monthly_insurance * 12 * bank_years) # show result ... # {:,} uses the comma as a thousands separator print('-'*40) print 'START:::' print('-'*40) print 'BANK PORTION:' sf = '''\ For a {} year mortgage loan of ${:,} at an annual interest rate of {:.2f}% you pay ${:.2f} monthly''' print(sf.format(bank_years, bank_principal, bank_interest, monthly_payment_bank)) print('-'*40) print '2nd MORTGAGE PORTION:' sf = '''\ For a {} year mortgage loan of ${:,} at an annual interest rate of {:.2f}% you pay ${:.2f} monthly''' print(sf.format(family_years, family_principal, family_interest, monthly_payment_family)) print('-'*40) print 'TOTAL:' sf = '''\ The Total Monthly Mortgage Payment is ${:,.2f}''' print (sf.format(total_monthly_mortgage_amount)) print('-'*40) print 'ADDITIONAL MONTHLY COSTS:' sf = '''\ Monthly HOAs : ${:,.2f}''' print (sf.format(monthly_hoas)) sf = '''\ Monthly Taxes : ${:,.2f}''' print (sf.format(annual_taxes/12)) sf = '''\ Monthly Insurance : ${:,.2f}''' print (sf.format(monthly_insurance)) print('-'*40) print 'TOTAL ALL-IN MONTHLY COSTS:' sf = '''\ Total costs are : ${:,.2f}''' print (sf.format(total_monthly_cost)) print('-'*40) print 'LIFETIME OF MORTAGE (30 Years):' print("Total mortgage paid will be ${:,.2f}".format(total_mortgage_amount)) print("Total all-in costs (at current levels) will be : ${:,.2f}".format(total_30_year_costs)) print('-'*40) ''' result ... For a 30 year mortgage loan of $100,000 at an annual interest rate of 7.50% you pay $699.21 monthly ---------------------------------------- Total amount paid will be $251,717.22 '''
from Login.LoginPage import * from PersonalCertificate.Certificate import * from selenium import webdriver import yaml driver = webdriver.Chrome() driver.maximize_window() driver.implicitly_wait(10) with open("../PersonalCertificate/certificate.yaml", "r", encoding="utf8") as file: data = yaml.load(file) username = data["username"] password = data["password"] name = data["name"] number = data["number"] email = data["email"] value = data["value"] test_user_login(driver, username, password) test_personal_certificate(driver,name,number,email,value)
import matplotlib import numpy as np import tensorflow as tf import tf_agents import math from tf_agents.agents.dqn import dqn_agent from tf_agents.drivers import dynamic_step_driver from tf_agents.environments import suite_gym from tf_agents.environments import tf_py_environment from tf_agents.environments import py_environment from tf_agents.environments import tf_environment from tf_agents.environments import utils from tf_agents.specs import array_spec from tf_agents.environments import wrappers from tf_agents.environments import suite_gym from tf_agents.trajectories import time_step as ts from tf_agents.eval import metric_utils from tf_agents.metrics import tf_metrics from tf_agents.networks import q_network from tf_agents.policies import random_tf_policy from tf_agents.replay_buffers import tf_uniform_replay_buffer from tf_agents.trajectories import trajectory from tf_agents.utils import common from selenium import webdriver # Hyperparameters num_iterations = 20000 initial_collect_steps = 100 collect_steps_per_iteration = 1 replay_buffer_max_length = 100000 i = 16 j = 16 initialState = np.zeros(i*j) batch_size = 64 learning_rate = 1e-3 log_interval = 200 num_eval_episodes = 10 eval_interval = 1000 def getList(): driver = webdriver.Firefox(firefox_binary="C:\Program Files\Mozilla Firefox\geckodriver.exe") # Link to firefox binary driver.get("http://minesweeperonline.com/#intermediate") # App link observation = { "blocks": [], "face": "" } # Loop through i*j blocks for i_component in range(1, i): for j_component in range(1, j): id = i_component + "_" + j_component block = driver.find_element_by_id(id) blockClasses = block.CLASS_NAME.split(" ") blockClass = blockClasses[1] n = blockClass[4] # get number of bombs/ blank if math.isnan(n): # if it is blank elem = -1 else: # if it is not blank elem = int(n) observation["blocks"].append(elem) # append that to the observation blocks array observation["face"] = driver.find_element_by_id(id).CLASS_NAME # append the state of game to the face element return observation class SimplifiedTicTacToe(py_environment.PyEnvironment): def __init__(self): self._action_spec = array_spec.BoundedArraySpec( shape=(), dtype=np.int32, minimum=0, maximum=i*j-1, name='action') self._observation_spec = array_spec.BoundedArraySpec( shape=(1,9), dtype=np.int32, minimum=0, maximum=i*j-1, name='observation') self._state = initialState self._episode_ended = False def action_spec(self): return self._action_spec def observation_spec(self): return self._observation_spec def _reset(self): self._state = initialState self._episode_ended = False return ts.restart(np.array([self._state], dtype=np.int32)) def __is_spot_blank(self, position): return self._state[position] == 0 def __all_spots_blank(self): return all(i == -1 for i in self._state) def _step(self, action): if self._episode_ended: return self.reset() if self.__is_spot_blank(action): self._state[action] = getList["blocks"] print(getList()) """def sendRequest(action): driver = selenium.webdriver.Firefox() driver.get("http://minesweeperonline.com/#intermediate") assert "Minesweeper" in driver.title def getList(): mainList = [[], ""] for(i_component in range(1, i)): for(j_component in range(1, j)): id = i_component + "_" + j_component block = driver.find_element_by_id(id) blockClasses = block.CLASS_NAME.split(" ") blockClass = blockClasses[1] n = blockClass[4] if math.isnan(n): elem = -1 elif: elem = int(n) mainList[0].append(elem) mainList[1] = driver.find_element_by_id(id).CLASS_NAME return mainList return getList()"""
#!/usr/bin/env python import time import pyrealsense2 as rs import numpy as np import cv2 from PIL import Image import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import json DS5_product_ids = ["0AD1", "0AD2", "0AD3", "0AD4", "0AD5", "0AF6", "0AFE", "0AFF", "0B00", "0B01", "0B03", "0B07"] def find_device_that_supports_advanced_mode() : ctx = rs.context() ds5_dev = rs.device() devices = ctx.query_devices(); for dev in devices: if dev.supports(rs.camera_info.product_id) and str(dev.get_info(rs.camera_info.product_id)) in DS5_product_ids: if dev.supports(rs.camera_info.name): print("Found device that supports advanced mode:", dev.get_info(rs.camera_info.name)) return dev raise Exception("No device that supports advanced mode was found") class Camera(object): def __init__(self): dev = find_device_that_supports_advanced_mode() advnc_mode = rs.rs400_advanced_mode(dev) print("Advanced mode is", "enabled" if advnc_mode.is_enabled() else "disabled") # Loop until we successfully enable advanced mode while not advnc_mode.is_enabled(): print("Trying to enable advanced mode...") advnc_mode.toggle_advanced_mode(True) # At this point the device will disconnect and re-connect. print("Sleeping for 5 seconds...") time.sleep(5) # The 'dev' object will become invalid and we need to initialize it again dev = find_device_that_supports_advanced_mode() advnc_mode = rs.rs400_advanced_mode(dev) print("Advanced mode is", "enabled" if advnc_mode.is_enabled() else "disabled") with open("/home/schortenger/Desktop/IROS/tactile_prior/camera_config.json") as f: load_string = json.load(f) if type(next(iter(load_string))) != str: load_string = {k.encode('utf-8'): v.encode("utf-8") for k, v in load_string.items()} json_string = str(load_string).replace("'", '\"') advnc_mode.load_json(json_string) self.pipeline = rs.pipeline() self.config = rs.config() self.config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 6) self.config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30) self.align_to = rs.stream.color self.align = rs.align(self.align_to) self.pipeline.start(self.config) for i in range(10): self.get_data(False) print('Camera is initialized') def get_data(self,get_depth=True): while True: frames = self.pipeline.wait_for_frames() aligned_frames = self.align.process(frames) aligned_depth_frame = aligned_frames.get_depth_frame() color_frame = aligned_frames.get_color_frame() self.color_intrinsics = color_frame.profile.as_video_stream_profile().intrinsics color_image = np.asanyarray(color_frame.get_data()) dis_none = np.zeros([480, 640]) if get_depth: depth_frame = aligned_frames.get_depth_frame() depth_image = np.asanyarray(aligned_depth_frame.get_data()).astype(float) return color_image, depth_image/1000 else: return color_image, dis_none def get_intrinsics(self): return self.color_intrinsics if __name__ == "__main__": camera = Camera() color_image, depth_image = camera.get_data(get_depth=True) print(color_image.shape, depth_image.shape) print(camera.color_intrinsics) count = 0.0 # for x in range(depth_image.shape[0]): # for y in range(depth_image.shape[1]): # if depth_image[x,y]==0: # count = count+1 # # plt.subplot(211) # plt.imshow(color_image) # plt.subplot(212) # plt.imshow(depth_image) # plt.show() # camera.pipeline.stop()
"""this application deals with autocompletion. It needs to : - redis - redis python - python requests - Jquery autocomplete It also uses django_webpack. """ from django.apps import AppConfig class AutocompleteConfig(AppConfig): name = 'autocomplete'
from django import forms from .models import Table from site_web.models import Site class TableForm(forms.ModelForm): #sites = MultipleChoiceField(queryset=Site.objects.all()) class Meta: model = Table fields = "__all__"
from __future__ import unicode_literals, print_function, generators, division from manager import Manager from model import Message from utils import get_first_element from view import View __author__ = 'pahaz' view = View('main.html') manager = Manager('data.db') def index(method, get, post, headers): messages = manager.all() byte_messages = b'<hr>'.join([m.name.encode() + b" <br> Message: " + m.message.encode() for m in messages]) status = '200 OK' body = view.render(messages=byte_messages) if method == 'POST': status = '303 See Other' body = b'' headers.append(('Location', '/')) message_name = get_first_element(post, 'name', '') message_message = get_first_element(post, 'message', '') message = Message(message_name, message_message) manager.save(message) return status, body def add(method, get, post, headers): a = get_first_element(get, 'a', '') b = get_first_element(get, 'b', '') print(a, b) status = '200 OK' summ = int(a) + int(b) body = b'<p>' + str(summ).encode() + b'</p>' return status, body # def static(method, get, post, headers): # headers[0] = ('Content-type', 'image/png; charset=utf-8') # status = '200 OK' # f = open('data/logo.png', 'rb') # body = f.read() # f.close() # return status, body
import requests import time from impl.submit_flag import submit_flag ''' 提交所有flag的函数,该文件不需要更改。 ''' def submit_all(flagset): success_submit = 0 fail_submit = 0 for pair in flagset: time.sleep(0.1) target = pair[0] flag = pair[1] if submit_flag(target=target,flag=flag) == True: print(" [√] 提交{}的{}成功!".format(target,flag)) success_submit += 1 else: print("[x] 提交{}的{}失败!".format(target,flag)) fail_submit += 1 print("本轮提交完成,成功提交{}个,失败提交{}个".format(success_submit,fail_submit))
# coding: utf-8 import time import pymongo import logging import datetime import bisect from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from modules import Unimac, Init_sta1, init_db from sqlalchemy import or_, and_ from sqlalchemy import text from sqlalchemy import distinct import pymysql pymysql.install_as_MySQLdb() DB_CONNECT_STRING = "mysql+mysqldb://root:123@192.168.3.108:3306/router" engine = create_engine(DB_CONNECT_STRING, encoding="utf-8", echo=True) DB_Session = sessionmaker(bind=engine) session = DB_Session() init_db(engine) import datetime now = datetime.datetime.now() def manyapname(early_time): aplists = (i[0] for i in session.query(distinct(Unimac.ap_no_empty)).filter(Unimac.end_time>=early_time).all() if i[0]) aset = set(aplists) return aset def get_manu_flag(manyap_items): manu_flag = None if len(manyap_items) < 2: item = manyap_items[0] if item.flag: return None if 'UnKnow' in item.manu: manu_flag = '1IOS+' + str(hash(item.mac)) elif 'Apple' in item.manu: manu_flag = 'IOS+' + str(hash(item.mac)) return manu_flag for i in manyap_items: if 'UnKnow' in i.manu: continue elif 'Apple' in i.manu: manu_flag = 'IOS+' + str(hash(i.mac)) else: return None if not manu_flag: manu_flag = '1IOS+' + str(hash(i.mac)) return manu_flag def getmidtime(start, end): startstamp = start.timestamp() endstamp = end.timestamp() midtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime((startstamp + endstamp) // 2)) return midtime def update_item(item_info): update_apname_flag = False mac = item_info.mac manu = item_info.manu station = item_info.station curren_time = item_info.reqtime apname = item_info.apname station = item_info.station item_info.newitem = False ten_min_before_time = curren_time - datetime.timedelta(minutes=10) ten_min_after_time = curren_time + datetime.timedelta(minutes=10) is_middle_time_item = session.query(Unimac).filter(and_( text("end_time>=:curren_time"), text("start_time<=:curren_time") ).params(curren_time=curren_time)).first() if is_middle_time_item: item = is_middle_time_item if apname: ap_set = item.get_eval("ap") | {apname} ap_no_empty_list = item.get_eval("ap_no_empty") if not ap_no_empty_list: ap_no_empty_list = [apname] elif apname not in ap_no_empty_list: bisect.insort(ap_no_empty_list, apname) item.ap = repr(ap_set) item.ap_no_empty = repr(ap_no_empty_list) session.commit() else: has_start_time_item = session.query(Unimac).filter(and_( text("end_time>=:ten_min_before_time"),text("end_time<=:curren_time"), Unimac.mac==mac, Unimac.station==station )).params(ten_min_before_time=ten_min_before_time, curren_time=curren_time).first() has_end_time_item = session.query(Unimac).filter(and_( text("start_time<:ten_min_after_time"), text("start_time>:curren_time"), Unimac.mac==mac, Unimac.station==station )).params(ten_min_after_time=ten_min_after_time, curren_time=curren_time).first() if has_start_time_item and has_end_time_item: start_time = has_start_time_item.start_time end_time = has_start_time_item.end_time ap_set = eval(has_start_time_item.ap) | eval(has_end_time_item.ap) | {apname} has_end_time_item.start_time = start_time has_end_time_item.mid_time = getmidtime(start_time, end_time) has_end_time_item.ap = repr(ap_set) has_end_time_item.ap_no_empty = repr(sorted(list(ap_set-{''}))) session.delete(has_start_time_item) session.commit() elif has_start_time_item: item = has_start_time_item start_time = item.start_time end_time = curren_time if apname: ap_set = item.get_eval("ap") | {apname} ap_no_empty_list = item.get_eval("ap_no_empty") if not ap_no_empty_list: ap_no_empty_list = [apname] elif apname not in ap_no_empty_list: bisect.insort(ap_no_empty_list, apname) item.ap = repr(ap_set) item.ap_no_empty = repr(ap_no_empty_list) has_start_time_item.end_time = end_time has_start_time_item.mid_time = getmidtime(start_time, end_time) session.commit() elif has_end_time_item: item = has_end_time_item start_time = curren_time end_time = item.end_time if apname: ap_set = item.get_eval("ap") | {apname} ap_no_empty_list = item.get_eval("ap_no_empty") if not ap_no_empty_list: ap_no_empty_list = [apname] elif apname not in ap_no_empty_list: bisect.insort(ap_no_empty_list, apname) item.ap = repr(ap_set) item.ap_no_empty = repr(ap_no_empty_list) item.start_time = start_time item.mid_time = getmidtime(start_time, end_time) session.commit() else: item = Unimac(); item.mac = mac item.manu = manu item.station = station item.start_time = curren_time item.end_time = curren_time item.mid_time = getmidtime(item.start_time, item.end_time) item.ap = repr({apname}) if apname: item.ap_no_empty = repr([apname]) else: item.ap_no_empty = None session.add(item) session.commit() return def log(filename): mylogger = logging.getLogger('macname') logformat = '%(levelname)s %(name)-12s %(asctime)s: %(message)s' logging.basicConfig(filename=filename, format=logformat) console_handler = logging.StreamHandler() console_handler.setLevel(logging.ERROR) mylogger.addHandler(console_handler) return mylogger def main(): while True: list(map(update_item, session.query(Init_sta1).filter(Init_sta1.newitem == True).all())) interval = 24 * 2 # two day early early_time = datetime.datetime.now() - datetime.timedelta(hours=interval) unque_manyap_set = manyapname(early_time) for index in unque_manyap_set: manyap_items = session.query(Unimac).filter(and_(Unimac.ap>=early_time, Unimac.ap_no_empty == index)).all() flag = get_manu_flag(manyap_items) if flag: session.query(Unimac).filter(text("ap_no_empty=:index and end_time>=:early_time")).params(index=index, early_time=early_time).update({Unimac.flag : flag}, synchronize_session=False) session.commit() print('--------------') time.sleep(5) if __name__ == "__main__": logger = log('macname.log') try: main() except Exception as e: session.rollback() session.close() logger.exception(e)
from django.db.models import Q from haystack import indexes from .models import Profile class ProfileIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) name = indexes.EdgeNgramField(model_attr='name') surname = indexes.EdgeNgramField(model_attr='surname') created = indexes.DateTimeField(model_attr='created') def get_model(self): return Profile def index_queryset(self, using=None): return self.get_model().objects.all() #filter(Q(user=None) | Q(user__is_superuser=False))
class Taxonomy: ''' Taxonomy represents a Linnean category (order, family, or genus) If a Taxonomy object's level is 'genus', then its item list contains strings of the form <species-name> [(<common-name>)] If the Taxonomy object's level is 'Order' or 'Family', then its item list contains Taxonomy objects of the next level down. ''' def __init__(self, category, level='Order'): import pickle import os.path ''' Create a new Taxonomy based on 'category' if 'level' is 'Order' and a serialization file for this order exists, then populate this object from that file; otherwise, create an empty Taxonomy category: the name of an order, a family, or a genus level: one of 'Order', 'Family', or 'Genus' ''' self.errorMessageStatement = 'Insertion OK' if level == 'Order': # does the file already exist? if (os.path.isfile(category + ".p")): self.itemList = pickle.load(open(category + ".p", "rb")) self.level = 'Order' self.itemList = [] self.categoryName = category; else: # just make an empty taxonomy object self.categoryName = category self.level = level self.itemList = [] def addSpecies(self, species): ''' Add a species to this taxonomy and return True. The level of this taxonomy must be 'genus'. If not, set an error message and return False. ''' if self.level != 'Genus': self.errorMessageStatement = 'Taxonomy is not of level Genus.' return False else: self.itemList.append(species) self.serialize() return True def addTaxonomy(self, subTaxonomy): ''' Add a sub-taxonomy to this taxonomy and return True. The sub-taxonomy must be at one level below this taxonomy. If not, set an error message and return False. ''' # checks to see one level below if self.level == 'Order' and subTaxonomy.level != 'Family': self.errorMessageStatement = 'Subtaxonomy was not one level below.' return False if self.level == 'Family' and subTaxonomy.level != 'Genus': self.errorMessageStatement = 'Subtaxonomy was not one level below.' return False self.itemList.append(subTaxonomy) self.serialize() return True def errorMessage(self): ''' Return the error message generated by the last insertion, or 'Insertion OK' if the last insertion did not create an error ''' return self.errorMessageStatement def insert(self, path): ''' Insert the species that is the last element of 'path' into this object,creating order, family, or genus Taxonomy objects as needed. If the length of path does not match the level of this Taxonomy object, set an error message ,abort the insertion, and return False; otherwise return True after successful insertion. This Taxonomy Level Expected path length Order 3 Family 2 Genus 1 path: front-slash-separated list of categories. ''' # to see if there is an existing species, otherwise add it temp = path.split('/') if self.level == 'Genus': if len(temp) != 1: self.errorMessageStatement = 'Error inserting ' + path + ' into ' + self.categoryName + ': wrong length' return False else: self.itemList.append( temp[0] ) self.serialize() return True if self.level == 'Family': if len(temp) != 2: self.errorMessageStatement = 'Error inserting ' + path + ' into ' + self.categoryName + ': wrong length' return False for item in self.itemList: if item.categoryName == temp[0]: # in the event genus already exists for _item in item.itemList: if _item == temp[1]: # species already exists in heirarchy return True # species does not exist, but the genus does item.itemList.append( temp[0] ) return True # in the event no genus exists in the family newGenus = Taxonomy(temp[0], 'Genus') newGenus.itemList.append( temp[1] ) self.itemList.append( newGenus ) self.serialize() return True # error check on order if self.level == 'Order': if len(temp) != 3: self.errorMessageStatement = 'Error inserting ' + path + ' into ' + self.categoryName + ': wrong length' return False print '\n' # iterate through family objects in order to see match for item in self.itemList: # check if there is a family that already exists if item.categoryName == temp[0]: # there is already a family object with the same category name for _item in item.itemList: # for every genus in this family object if _item.categoryName == temp[1]: # genus already exists in this family object for _item_ in _item.itemList: # for every species string in this genus if _item_ == temp[2]: # this species already exists in the genus return True # genus exists but the species does not _item.itemList.append(temp[2]) return True # there is a family object, but no genus or therefore species newGenus = Taxonomy(temp[1], 'Genus') newGenus.itemList.append(temp[2]) _item.itemList.append(newGenus) return True # adds a family with a new genus and new species in that genus newFamily = Taxonomy( temp[0], 'Family') _newGenus = Taxonomy( temp[1], 'Genus') _newGenus.itemList.append( temp[2] ) self.itemList.append(newFamily) newFamily.itemList.append( _newGenus ) self.serialize() return True def list(self): ''' Return a string representing the contents of this Taxonomy and its sub-Taxonomies, in the format top-category-name (subitem1, subitem2,...), where subitem1, subitem2... are either strings representing species, in the form <latin-name> [(common-name)], or sublists representing Taxonomies. ''' # iterates through objects in an order's item list if self.level == 'Order': listSpecies = "" listSpecies += self.categoryName for family in self.itemList: listSpecies += " (" + family.categoryName for genus in family.itemList: listSpecies += " (" + genus.categoryName for species in genus.itemList: listSpecies += " (" + species listSpecies += ")" listSpecies += ")" listSpecies += ")" return listSpecies # iteratees through the items of a family if self.level == 'Family': listSpecies = "" listSpecies += self.categoryName for genus in self.itemList: listSpecies += " (" + genus.categoryName for species in genus.itemList: listSpecies += " (" + species listSpecies += ")" listSpecies += ")" return listSpecies # iterates through items in a genus if self.level == 'Genus': listSpecies = "" listSpecies += self.categoryName for species in self.itemList: listSpecies += " (" + species listSpecies += ")" return listSpecies def serialize(self): import pickle ''' Save contents of this object using pickle ''' pickle.dump(self.itemList, open(self.categoryName + ".p", "wb")) if __name__ == "__main__": import taxonomy import unittest import sys '''Test adding a species to a genus with no errors''' genus1 = taxonomy.Taxonomy('') while(1): userInput = raw_input('> ') commandList = [] commandList = userInput.split(' ') for str in commandList: print( str + ' ' ) if userInput.strip() == 'quit' or userInput.strip() == 'exit': print 'Closing application' sys.exit(0) if commandList[0] == 'insert': genus1.insert(commandList[1]) if commandList[0] == 'list': print( genus1.list() ) else: print('The command ' + userInput + ' does not exist.')
from jinja2 import Template from lxml import html import os template=''' cache_size={{ cache_size }}&nrbanks={{banks}}&rwports=0&read_ports=1&write_ports=1&ser_ports=0&output={{bits_out}}&technode=35&temp=300& data_arr_ram_cell_tech_flavor_in=0&data_arr_periph_global_tech_flavor_in=0&tag_arr_ram_cell_tech_flavor_in=0&tag_arr_periph_global_tech_flavor_in=0&interconnect_projection_type_in=1&wire_outside_mat_type_in=0& preview-article=Submit&action=submit&cacti=cache&pure_sram=pure_sram" ''' jtem = Template(template) url = "http://quid.hpl.hp.com:9081/cacti/sram.y" def get_params(**kwargs): #(cache_size = 16384, banks = 1, bits_out = 128): query = jtem.render(kwargs) os.system("curl -s %s %s > tmp.html"%(query, url)) html_f = open('tmp.html').read() tree = html.parse(html_f) x = tree.xpath(r"/html/body/div[@class='page']/div[@class='contentcolumn']/table/tr[3]/td/text()") return x if __name__ == "__main__": print get_params(cache_size = 16384, banks = 1, bits_out = 128)
from .unicycle_controller import UnicycleController
# Create your views here. from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt # import key from project settings.py from imagely.settings import CLARIFAI_API_KEY # import python ClarifaiApp from clarifai.rest import ClarifaiApp cf_app = ClarifaiApp(api_key=CLARIFAI_API_KEY) # View Functions for /image routes # csrf added to handle POST request not related to FE Form @csrf_exempt def images(request): """ Handles all requests for /image route, methods: GET, POST """ if request.method == 'POST': # get encoded base64 pic from post request encodedpic = request.POST.get('encodedpic') # set clarifai model to use # model = cf_app.public_models.general_model model = cf_app.models.get('food-items-v1.0') # get dict from clarifai raw_response = model.predict_by_base64(bytes(encodedpic, 'UTF-8')) # get list of dicts representing relations response = raw_response['outputs'][0]['data']['concepts'] # list comp over response and format output relations = [{ "association": concept['name'], "value": concept['value'] } for concept in response] return JsonResponse({"relations": relations}) # otherwise return get request JSON elif request.method == 'GET': # raw_response is a generator raw_response = cf_app.models.get_all() # list of model objects from generator response_list = list(raw_response) # create list of models dicts response_models = [model.dict() for model in response_list] # extract just name and id from model models = [{ "name": model_dict['model']['name'], "id": model_dict['model']['id'] } for model_dict in response_models] return JsonResponse({'message': 'Clarifai Models', 'models': models}) else: return JsonResponse({'message': 'Nothing to do!'})
import serial import os import struct class PyRfid(object): RFID_STARTCODE = 0x02 RFID_ENDCODE = 0x03 __serial = None __rawTag = None def __init__(self, port = '/dev/ttyUSB0', baudRate = 9600): """ Constructor @param string port @param integer baudRate """ ## Validates port if ( os.path.exists(port) == False ): raise Exception('The RFID sensor port "' + port + '" was not found!') ## Initializes connection self.__serial = serial.Serial(port = port, baudrate = baudRate, bytesize = serial.EIGHTBITS, timeout = 1) def __del__(self): """ Destructor """ ## Closes connection if established if ( ( self.__serial != None ) and ( self.__serial.isOpen() == True ) ): self.__serial.close() def __read(self): """ Reads the complete tag and returns status. @return boolean """ self.__rawTag = None rawTag = b'' calculatedChecksum = 0 receivedPacketData = [] index = 0 while ( True ): ## Reads on byte receivedFragment = self.__serial.read() ## Collects RFID data if ( len(receivedFragment) != 0 ): ## Start and stop bytes are string encoded and must be byte encoded if ( ( index == 0 ) or ( index == 13 ) ): receivedFragment = struct.unpack('@B', receivedFragment)[0] else: rawTag += receivedFragment receivedFragment = int(receivedFragment, 16) ## Collects RFID data (hexadecimal) receivedPacketData.append(receivedFragment) index += 1 ## Packet completly received if ( index == 14 ): ## Checks for invalid packet data if ( ( receivedPacketData[0] != self.RFID_STARTCODE ) or ( receivedPacketData[13] != self.RFID_ENDCODE ) ): raise Exception('Invalid start or stop bytes!') ## Calculates packet checksum for i in range(1, 11, 2): byte = receivedPacketData[i] << 4 byte = byte | receivedPacketData[i+1] calculatedChecksum = calculatedChecksum ^ byte ## Gets received packet checksum receivedChecksum = receivedPacketData[11] << 4 receivedChecksum = receivedChecksum | receivedPacketData[12] ## Checks for wrong checksum if ( calculatedChecksum != receivedChecksum ): raise Exception('Calculated checksum is wrong!') ## Sets complete tag for other methods self.__rawTag = rawTag return True def readTag(self): """ Reads the complete raw tag. @return boolean """ try: while ( self.__read() != True ): pass except KeyboardInterrupt: return False return True @property def rawTag(self): """ Returns read raw tag in hexadecimal format "1A2B345C67" without checksum. @return string (10 bytes) """ return self.__rawTag[0:10] @property def tagType(self): """ Returns type of read tag (first 4 bytes). @return hex (4 bytes) """ if ( self.__rawTag != None ): return hex(int(self.__rawTag[0:4], 16)) return None @property def tagTypeFloat(self): """ Returns type of read tag (first 2 bytes). @return hex (2 bytes) """ if ( self.__rawTag != None ): return hex(int(self.__rawTag[0:2], 16)) return None @property def tagId(self): """ Returns ID of read tag in decimal format "0001234567". @return string (10 chars) """ if ( self.__rawTag != None ): ## Length of ID is 10 anyway return '%010i' % int(self.__rawTag[4:10], 16) return None @property def tagIdFloat(self): """ Returns ID of read tag in float format "123,45678". @return string (9 chars) """ if ( self.__rawTag != None ): pre = float.fromhex(self.__rawTag[2:6]) post = float.fromhex(self.__rawTag[6:10]) / 100000 tag = pre + post return str(tag) return None @property def tagChecksum(self): """ Returns checksum of read tag (last 2 bytes). @return hex (2 bytes) """ if ( self.__rawTag != None ): return hex(int(self.__rawTag[10:12], 16)) return None
# -*-coding:utf-8-*- # @ Auth:zhao xy # @ Time:2021/5/11 12:39 # @ File:user_sql.py from sqlalchemy.orm import sessionmaker # 用以创建session类 from sqlalchemy import create_engine # 保存数据库连接信息 url = "mysql+mysqlconnector://root:zxy19981013@172.18.0.3:3306/test" # 数据库用户名密码地址端口及库名 engin = create_engine(url,pool_size=5) # 数据库连接池对象个数 Session = sessionmaker(bind=engin) # 创建session类
''' author: juzicode address: www.juzicode.com 公众号: juzicode/桔子code date: 2020.6.23 ''' print('\n') print('-----欢迎来到www.juzicode.com') print('-----公众号: juzicode/桔子code\n') import keyword print('keyword.kwlist:\n',keyword.kwlist) #调用kwlist,使用keyword.作为前缀
import scrapy import re import datetime import os from scrapy.exporters import CsvItemExporter ################################### URLname = 'loanURLs.csv' try: URLdir = os.path.join(os.getcwd(),'../../../',URLname) # please change to relative links to the loanURLs.csv file if necessary except: URLdir = URLname # starting time start = datetime.datetime.now() ################################### # define function to manipulate the raw data def trim(string): # remove tabs, line breaks and redundant spaces in a string try: return re.sub('[\s]{2,}','',re.sub('[\t\n\,]|\s+',' ',string)) except: return '' def concat(listOfStrings): # join a list of strings into a string try: return trim(' '.join(listOfStrings)) except: return '' def convertAmount(amountStr): # convert strings of amounts into float type if amountStr == '': return 0 else: return float(re.sub('[^\d|\.]','',amountStr)) def convertPercentage(percentageStr): # convert strings of percentage into float type if percentageStr == 'Funded': return 100 elif percentageStr == 'Expired': return 0 else: return float(re.sub('[^\d|\.]','',percentageStr)) ################################### # define Scrapy class class loan(scrapy.Item): borrowerName = scrapy.Field() loanAmount = scrapy.Field() fundingStatus = scrapy.Field() percentageFunded = scrapy.Field() timeLeft = scrapy.Field() amountToGo = scrapy.Field() country = scrapy.Field() sector = scrapy.Field() loanBrief = scrapy.Field() noLenders = scrapy.Field() loanLength = scrapy.Field() repaymentSchedule = scrapy.Field() disbursedDate = scrapy.Field() fundingModel = scrapy.Field() partnerCoverCurLoss = scrapy.Field() fieldPartner = scrapy.Field() whySpecial = scrapy.Field() payInterest = scrapy.Field() borrowerStory = scrapy.Field() moreAbout = scrapy.Field() url = scrapy.Field() class LinksSpider(scrapy.Spider): name = 'kivaLoans' delimiter = ';' allowed_domains = ['kiva.org'] try: with open(URLdir, "rt") as f: start_urls = [url.strip() for url in f.readlines()] except: start_urls = [] ################################### # design the scraper def parse(self, response): l = loan() borrowerName_xpath = '//h1/text()' loanAmount_xpath = '//div[@class = "loan-total"]/text()' percentageFunded_xpath = '//h2[@class = "green-bolded inline"]/text()' timeLeft_xpath = '//div[re:match(@class, "^days-left-stat.*")]/text()' amountToGo_xpath = '//div[@class = "amount-to-go-stat"]/text()' country_xpath = '//h2[re:match(text(),".*Country.*")]/text()' sector_xpath = '//span[@class = "typeName"]/text()' loanBrief_xpath = '//div[@class = "loan-use"]/h2/text()' noLenders_xpath = '//a[@class = "lender-count black-underlined"]/text()' loanLength_xpath = '//a[text() = "Loan length"]/../following-sibling::div[1]/text()' repaymentSchedule_xpath = '//a[text() = "Repayment schedule"]/following-sibling::strong[1]/text()' disbursedDate_xpath = '//a[text() = "Disbursed date"]/following-sibling::strong[1]/text()' fundingModel_xpath = '//a[text() = "Funding model"]/following-sibling::strong[1]/text()' partnerCoverCurLoss_xpath = '//a[text() = "Partner covers currency loss"]/following-sibling::strong[1]/text()' fieldPartner_xpath = '//a[text() = "Facilitated by Field Partner"]/following-sibling::strong[1]/text()' whySpecial_xpath = '//section[@class = "why-special"]/div[2]/div/text()' payInterest_xpath = '//a[text() = "Is borrower paying interest"]/following-sibling::strong[1]/text()' borrowerStory_xpath = '//section[@class = "loan-description"]//text()' moreAbout_xpath = '//div[@id = "ac-more-loan-info-body"]//text()' l['url'] = response.request.url l['borrowerName'] = response.xpath(borrowerName_xpath).get() l['loanAmount'] = convertAmount(trim(response.xpath(loanAmount_xpath).get()).replace('Total loan: ','')) l['percentageFunded'] = convertPercentage(trim(response.xpath(percentageFunded_xpath).get())) l['timeLeft'] = trim(response.xpath(timeLeft_xpath).get()) l['amountToGo'] = convertAmount(trim(response.xpath(amountToGo_xpath).get()).replace(' to go','')) l['country'] = trim(response.xpath(country_xpath).get()).replace('Country: ','') l['sector'] = trim(response.xpath(sector_xpath).get()) l['loanBrief'] = trim(response.xpath(loanBrief_xpath).get()) l['noLenders'] = convertAmount(trim(response.xpath(noLenders_xpath).get())) l['loanLength'] = trim(response.xpath(loanLength_xpath).get()) l['repaymentSchedule'] = trim(response.xpath(repaymentSchedule_xpath).get()) l['disbursedDate'] = trim(response.xpath(disbursedDate_xpath).get()) l['fundingModel'] = trim(response.xpath(fundingModel_xpath).get()) l['partnerCoverCurLoss'] = trim(response.xpath(partnerCoverCurLoss_xpath).get()) l['fieldPartner'] = trim(response.xpath(fieldPartner_xpath).get()) l['whySpecial'] = trim(response.xpath(whySpecial_xpath).get()) l['payInterest'] = trim(response.xpath(payInterest_xpath).get()) l['borrowerStory'] = concat(response.xpath(borrowerStory_xpath).getall()) l['moreAbout'] = concat(response.xpath(moreAbout_xpath).getall()) if l['percentageFunded'] == 0: l['fundingStatus'] = 'Expired' elif l['percentageFunded'] == 100: l['fundingStatus'] = 'Funded' else: l['fundingStatus'] = 'Funding' yield l print('Crawling loan details by BeautifulSoup completed') print('Total crawling time:', int((datetime.datetime.now()- start).seconds)//60, ' minutes')
# # Text-related utilities # import os import string import sys import textwrap # This is not available on Debian 9, so if it isn't, roll our own. # DEBIAN: Go back to using secrets directly when Debian 9 goes away. try: import secrets SECRETS_CHOICE = secrets.choice SECRETS_RANDBELOW = secrets.randbelow except ImportError: import random def secrets_randbelow(below): return random.randint(0, below-1) def secrets_choice(charset): return charset[secrets_randbelow(len(charset)-1)] SECRETS_CHOICE = secrets_choice SECRETS_RANDBELOW = secrets_randbelow def terminal_size(): """ Return the number of terminal columns and rows, defaulting to 80x24 if the standard output is not a TTY. NOTE THAT THIS ONLY WORKS ON UNIX. """ if sys.stdout.isatty(): # PORT: This only works on Unix. rows, columns = [int(x) for x in os.popen('stty size', 'r').read().split()] else: rows = 24 columns = 80 return rows, columns def prefixed_wrap(prefix, text, width=None, indent=0): """ Wrap text with a prefix and optionally indenting the second and later lines. If the width is None, the terminal size will be used. (See terminal_size() for details.) """ if width is None: height, width = terminal_size() wrapped = textwrap.wrap(text, width - len(prefix)) leader = " " * (len(prefix) + indent) lines = [wrapped.pop(0)] lines.extend(["%s%s" % (leader, line) for line in wrapped]) return "%s%s" % (prefix, "\n".join(lines)) def indent( text, # Text to indent char=' ', # Character to use in indenting indent=2 # Repeats of char ): """ Indent single- or multi-lined text. """ prefix = char * indent return "\n".join([prefix + s for s in text.split("\n")]) def random_string(length, randlength=False, safe=False): """Return a random string of length 'length' Set 'randlength' True to pick a random length between half of 'length' and 'length'. Set 'safe' True to onlu include alphanumeric characters. """ if randlength: length = length - SECRETS_RANDBELOW(int(length/2)) charset = string.digits + string.ascii_letters if not safe: charset += string.punctuation charset_len = len(charset) characters = [ SECRETS_CHOICE(charset) for _ in range(0, length) ] return "".join(characters)
parameters_v1 = { 'learning_rate': 0.003, 'boosting_type': 'gbdt', 'objective': 'cross_entropy', 'metric': 'binary_logloss', 'sub_feature': .684263, 'num_leaves': 6, 'max_depth': 3, 'min_data': 26, 'verbosity': 0, 'bagging_fraction': 0.85, 'lambda_l1': 0, 'lambda_l2': 0, 'bagging_freq': 5, 'num_iterations': 5000 }
""" java error:java.lang.error 代表严重错误,比如:内存溢出-》死循环-》修改代码逻辑 exception:java.lang.Exception 1/0-》简易程序处理-》可以处理 error无法处理,异常是建议处理 异常是不正常程序的状态 异常处理: 错误: 错误是指由逻辑或者语法等导致一个程序无法正执行问题 特点: 有些错误是无法预知的 异常: 异常是程序出错时标识的一种状态 当异常发生时,程序转到函数调用的地方等待处理,直到错误恢复 作用: 用作信号,通知上层调用者有错误需要处理 有些程序员开发: 第一期:sleep(10) 第二期:加钱,sleep(5) 第三期:sleep(3) 第四期:删sleep(1) python中捕获异常(两种): 1.try-except语句 格式: try: 可能触发异常的语句 except 错误类型1 as e: 异常处理语句 except 错误类型2 as e: 异常处理语句 except 错误类型3 as e: 异常处理语句 else: print(’无异常‘) 2.try-finally语句 finally: 最终语句里面的程序一定会执行 Exception是所有异常的父类,但不建议这么写 try-finally 语法: try: finally: 说明: 1.finally子句不可省略 2.不存在except子句 作用: try-finally语句用来做触发异常时必须要做的事,无论异常是否 发生,finally子句都会被执行 """ # def apple(num): # print('%d个苹果您想分给几个人?' % num) # s = input('请输入人数:') # p = int(s) # 字符小数,ValueError # result = num/p # p为0异常 ZeroDivisionError # print('每个人分了%d个苹果' % result) # 捕获特定异常 # try: # apple(10) # 此函数可能会触发异常,导致分苹果失败 # print('分完苹果了') # except ValueError as e: # print('人数应为整数') # except ZeroDivisionError as e: # print('错误代码:%s' % e) # 捕获所有异常 # try: # apple(10) # except Exception as e: # print('程序异常,错误代码:%s' % e) # def get_score(): # try: # gra = eval(input('请输入学生成绩(0-100):')) # if 0 <= gra <= 100: # return gra # else: # raise ValueError('输入错误') # except ValueError as e: # print('异常为:%s' % e) # return 0 # # # score = get_score() # print('您输入的成绩是:%s' % score) # def fry_egg(): # try: # print('打开天然气。。。') # egg_num = int(input('请输入鸡蛋的数量:')) # print('一共煎好了%d个鸡蛋' % egg_num) # finally: # print('关闭天然气') # # # try: # fry_egg() # except ValueError: # pass
a=[1,2,3,4,5,6] print (a) #adding one string with another string a=[1,2,3] b=a+[4,5,6] a=[1,2,3]*2
from time import time start = time() sum_list = [] for i in range(1,101): sum_list.append(i**2) print((sum(range(1,101))**2) - sum(sum_list)) print "1 : Seconds", time() - start
'''Utilities to help manage the various environments required in the LHCb software.''' import subprocess, select, timeit, exceptions, pprint, tempfile, os strippingDVVersions = {'stripping21' : ('v36r2', 'x86_64-slc6-gcc48-opt'), # Should be 'v36r1p3' but it crashes when importing anything Stripping related. 'stripping20' : ('v32r2p1', 'x86_64-slc5-gcc46-opt'), 'stripping20r1' : ('v32r2p3', 'x86_64-slc5-gcc46-opt')} def get_stripping_dv_version(version) : version = version.lower() if version in strippingDVVersions : return strippingDVVersions[version] version = 'stripping' + version.replace('stripping', '').split('p')[0] if version in strippingDVVersions : return strippingDVVersions[version] version = 'stripping' + version.replace('stripping', '').split('r')[0] if version in strippingDVVersions : return strippingDVVersions[version] return None, None class Shell(object) : __slots__ = ('args', 'process', 'stdoutpoller', 'stderrpoller', 'exitcodeline', 'exittest', 'getexitcode', 'initoutput', 'stdout', 'stderr') def __init__(self, args, exitcodeline, exittest, getexitcode, inittimeout = None, env = None) : if isinstance(args, str) : args = [args] self.args = args self.exitcodeline = exitcodeline if isinstance(exittest, str) : self.exittest = lambda line : exittest in line else : self.exittest = exittest self.getexitcode = getexitcode self.process = subprocess.Popen(args, stdout = subprocess.PIPE, stderr = subprocess.PIPE, stdin = subprocess.PIPE, env = env, bufsize = -1) self.stdout = self.process.stdout self.stderr = self.process.stderr self.stdoutpoller = select.poll() self.stdoutpoller.register(self.stdout.fileno(), select.POLLIN) self.stderrpoller = select.poll() self.stderrpoller.register(self.stderr.fileno(), select.POLLIN) # Ensure that any initial configuration of the environment is done before proceeding. self.initoutput = None self.initoutput = self.eval('', timeout = inittimeout, raiseerror = True) def is_alive(self, raiseError = False) : if self.process.poll() : if raiseError : raise RuntimeError('The shell with args ' + repr(self.args) + ', pid ' + str(self.process.pid) + ', has died!') return False return True def _read(self, polltime = 100, timeout = None) : if not self.is_alive() : stdout = '' exitcode = None for line in self.stdout : stdout += line if self.exittest(line) : exitcode = self.getexitcode(line) stderr = self.stderr.read() self.stdout.close() self.stderr.close() return {'stdout' : stdout, 'stderr' : stderr, 'exitcode' : exitcode} stdout = stderr = '' exitcode = None if timeout : now = timeit.default_timer() testtimeout = lambda : ((timeit.default_timer() - now) < timeout) else : testtimeout = lambda : True # Read stdout at a frequency of polltime til the exit signature is found or # the timeout is reached. while testtimeout() : if not self.stdoutpoller.poll(polltime) : continue line = self.stdout.readline() if self.exittest(line) : exitcode = self.getexitcode(line) break stdout += line # Read stderr til there's nothing left to read. while self.stderrpoller.poll(10) and testtimeout() : stderr += self.stderr.readline() return {'stdout' : stdout, 'stderr' : stderr, 'exitcode' : exitcode} def eval(self, cmd, polltime = 100, timeout = None, raiseerror = False) : self.is_alive(True) if cmd[-1:] != '\n' : cmd += '\n' cmd += self.exitcodeline self.process.stdin.write(cmd) self.process.stdin.flush() returnvals = self._read(polltime, timeout) if raiseerror and returnvals['exitcode'] != 0 : msg = '''{module}.{cls} environment with args: {args} init output: {initoutput} failed to execute command: {cmd} giving output: {output}'''.format(module = self.__module__, cls = self.__class__.__name__, args = pprint.pformat(self.args), initoutput = pprint.pformat(self.initoutput), cmd = cmd, output = pprint.pformat(returnvals)) raise Exception(msg) return returnvals def eval_python(self, cmd, objnames = None, evalobjects = True, polltime = 10, timeout = None, raiseerror = False) : if objnames : if cmd[-1:] != '\n' : cmd += '\n' cmd += 'print "__PYOBJECTS__", repr(dict(' if evalobjects : cmd += ', '.join([name + ' = ' + name for name in objnames]) else : cmd += ', '.join([name + ' = repr(' + name + ')' for name in objnames]) cmd += '))\n' # Writing the cmd to a tempfile seems to be the safest way to retain the correct # quotation marks, rather than using python -c. flag, fname = tempfile.mkstemp() with open(fname, 'w') as tmpfile : tmpfile.write(cmd) try : returnvals = self.eval('python ' + fname, polltime, timeout, raiseerror) except Exception as excpt : msg = excpt.message msg += '\nCommand written to file ' + fname + ':\n' + cmd os.remove(fname) raise Exception(msg) os.remove(fname) if objnames : if returnvals['exitcode'] == 0 : lastline = filter(lambda line : '__PYOBJECTS__' in line, returnvals['stdout'].split('\n'))[-1] returnvals['objects'] = eval(lastline[len('__PYOBJECTS__'):]) else : returnvals['objects'] = None return returnvals class LHCbEnv(Shell) : def __init__(self, env, version = 'latest', platform = None, shell = 'bash', exitcodeline = 'echo "*_*_*_* EXITCODE: $?"\n', exittest = '*_*_*_* EXITCODE: ', getexitcode = lambda line : int(line.rstrip('\n').split()[-1]), inittimeout = 600, ignoreenv = True) : # Probably more options could be considered here. args = ['lb-run'] if platform : args += ['-c', platform] if ignoreenv : args += ['-i'] args += [env + '/' + version] args += [shell] Shell.__init__(self, args, exitcodeline, exittest, getexitcode, inittimeout) lhcbenvs = {} def get_lhcb_env(env, version = 'latest', platform = None, **kwargs) : global lhcbenvs key = env if version : key += '_' + version if platform : key += '_' + platform if not key in lhcbenvs : lhcbenvs[key] = LHCbEnv(env, version, platform, **kwargs) return lhcbenvs[key] def get_stripping_env(version, **kwargs) : ver, platform = get_stripping_dv_version(version) return get_lhcb_env('DaVinci', version = ver, platform = platform, **kwargs) if __name__ == '__main__' : diracEnv = get_lhcb_env('LHCbDirac') stdout, stderr = diracEnv.eval('dirac-version', 2e3) print 'stdout' print stdout print 'stderr' print stderr # For some reason python shells don't work. # diracPythonEnv = LHCbEnv('LHCbDirac', 'python') # stdoutpy, stderrpy = diracPythonEnv.eval('print "spam"') # print 'stdoutpy' # print stdoutpy # print 'stderrpy' # print stderrpy
import configparser as ConfigParser import sys import pandas as pd import os from datetime import datetime import time import re import owners import datacleansing as dtc class csv: pcol = { "Indicator": [], "Type": [], #"Value": [], "Organization": [], "Rating": [], "Confidence": [], "DateAdded": [], #"LastModified": [], "Description": [], "Source": [], # TODO IN CASE MENG HONG NEEDS IT # "DNS": [], # "Whois": [], # "Active": [], # "Observations": [], # "Date Last Observed": [], # "False Positives": [], # "Date FP Last Reported": [], "Tags": [] } dc = dtc.dataCleanse() now = datetime.now() log_directory = os.getcwd() + r"\log" log_filename = os.path.join(log_directory, "{}.csv".format(now.strftime("%Y%m%dT%H%M%S"))) def format(self, indicators): col = self.pcol try: for indicator in indicators: tagname = "" # value = "" indicator.load_attributes() indicator.load_tags() col["Indicator"].append(indicator.indicator) col["Type"].append(indicator.type) col["Organization"].append(indicator.owner_name) col["Rating"].append(indicator.rating) col["Confidence"].append(indicator.confidence) col["DateAdded"].append(indicator.date_added) col["Description"].append(indicator.description if not self.dc.checkForEmptyValues(indicator.description) else "0") col["Source"].append(indicator.source if not self.dc.checkForEmptyValues(indicator.source) else "0") if len(indicator.tags) > 0: for tag in indicator.tags: if pd.notna(tag): c_type = self.dc.checkCountryCodeType(tag.name) if bool(c_type): tagname = self.dc.convertToCountryObject(tag=tag.name, t_type=c_type).name else: tagname = tag.name else: tagname = "" tagname += ";" else: tagname = "0" col["Tags"].append(tagname) """ for attr_obj in indicator.attributes: value += attr_obj.value + ";" col["LastModified"].append(attr_obj.last_modified) col["Value"].append(value) """ return col except Exception as exception: assert exception.__class__.__name__ == "NameError" def tocsv(self, data, directory, logging=True): try: df = pd.DataFrame.from_dict(data, orient='columns', columns=None) df.to_csv(directory) time.sleep(5) if logging: df.to_csv(self.log_filename) except Exception as exception: assert exception.__class__.__name__ == "NameError"
import os import pygame import kezmenu from team import Team class Custom(object): running = True def main(self, screen): clock = pygame.time.Clock() background = pygame.image.load(os.path.join('img', 'background.png')) menu = kezmenu.KezMenu( ['Done!', lambda: Team().main(screen)], ) menu.font = pygame.font.SysFont('Arial', 40, bold=True) menu.x = 320 menu.y = 400 menu.enableEffect('raise-col-padding-on-focus', enlarge_time=0.1) rect1 = pygame.Rect(200, 25, 310, 50) rect2 = pygame.Rect(50, 125, 300, 40) rect3 = pygame.Rect(50, 225, 300, 40) rect4 = pygame.Rect(50, 325, 300, 40) rect5 = pygame.Rect(500, 125, 40, 40) rect6 = pygame.Rect(500, 225, 40, 40) rect7 = pygame.Rect(500, 325, 40, 40) font = pygame.font.SysFont('Arial', 30, bold=True) while self.running: menu.update(pygame.event.get(), clock.tick(30)/1000.) screen.blit(background, (0, 0)) menu.draw(screen) pygame.draw.rect(screen, (255, 0, 0), rect1) pygame.draw.rect(screen, (255, 0, 0), rect2) pygame.draw.rect(screen, (255, 0, 0), rect3) pygame.draw.rect(screen, (255, 0, 0), rect4) pygame.draw.rect(screen, (0, 0, 255), rect5) pygame.draw.rect(screen, (0, 0, 255), rect6) pygame.draw.rect(screen, (0, 0, 255), rect7) screen.blit(font.render("Customize Character", True, (0, 0, 0), (0, 0)), rect1) screen.blit(font.render("Programming", True, (0, 0, 0), (0, 0)), rect2) screen.blit(font.render("Design", True, (0, 0, 0), (0, 0)), rect3) screen.blit(font.render("Soft Skills", True, (0, 0, 0), (0, 0)), rect4) screen.blit(font.render("6", True, (0, 0, 0), (0, 0)), rect5) screen.blit(font.render("1", True, (0, 0, 0), (0, 0)), rect6) screen.blit(font.render("13", True, (0, 0, 0), (0, 0)), rect7) pygame.display.flip() if __name__ == '__main__': pygame.init() screen = pygame.display.set_mode((640, 480)) Custom().main(screen)
#!/usr/bin/env python2.7 from bottle import route, run, Bottle, request import random ''' Define the app ''' tile_calc_app = Bottle() @tile_calc_app.get('/') @tile_calc_app.get('/tilecalc') def main_page(): ''' Display main form ''' html = ''' <h1>Welcome to Tile Calc</h1> <p>Enter the width, length, and price per unit</p> <form action="/tilecalc" method="post"> Width: <input name="width" type="text" /><br /><br /> Length: <input name="length" type="text" /><br /><br /> Cost Per Unit: <input name="cost_per_unit" type="text" /><br /><br /> <input value="Calculate" type="submit" /> </form> <p>Testimonial from our customers: <i><b>%s</b></i></p> ''' return html % get_cust_feedback() @tile_calc_app.post('/') @tile_calc_app.post('/tilecalc') def result_page(): ''' Display the error or results page ''' try: width = float(request.forms.get('width')) length = float(request.forms.get('length')) cost_per_unit = float(request.forms.get('cost_per_unit')) html = ''' <h2>Total cost: %s</h2> <a href="/">Go back</a> ''' % (width * length * cost_per_unit) except: html = ''' <h1>ERROR: All inputs must be ints or floats</h1> <a href="/">Go back</a> ''' return html def get_cust_feedback(): ''' Teen talk barbie really likes our app! ''' cust_feedback = ( "Will we ever have enough clothes?", "I love shopping!", "Wanna have a pizza party?", "Math class is tough!" ) return random.choice(cust_feedback) ''' Run the app ''' run(tile_calc_app, host='localhost', port=8081, debug=True)
import pykov import numpy as np from multiprocessing import Pool from collections import OrderedDict def update_word_probabilities(word_probabilities, index, reward): word_probabilities[index] += reward summ = sum(word_probabilities) corrected_word_probabilities = list(map(lambda i: float(i) / summ, word_probabilities)) return corrected_word_probabilities def normalize(vector): summ = sum(vector) return list(map(lambda i: float(i) / summ, vector)) def markov_update_words(pykov_words, association, reward): pykov_words[association] = pykov_words[association] + reward summ = sum(pykov_words.values()) normalized_probabilities = list(map(lambda i: float(i) / summ, pykov_words.values())) for i in range(len(normalized_probabilities)): if normalized_probabilities[i] < 4.768371584931426e-04: normalized_probabilities[i] = 0.001 normalized_probabilities = OrderedDict(zip(pykov_words.keys(), normalized_probabilities)) return pykov.Vector(normalized_probabilities)
#_*_ coding:utf-8 _*_ def Questao21_Lista3(N): S = 0 for i in range(1, 100): if i % 2 != 0: S += (i /(float(i/2)+1)) print "%.2f" % S def main(): n=input("Insira N: ") Questao21_Lista3(n) if __name__=="__main__": main()
import requests from bs4 import BeautifulSoup import json from urllib import request, parse import os import time import lxml.html import re import urllib.parse from opencc import OpenCC import pandas as pd import numpy as np import jieba import csv cc = OpenCC('s2t') jieba.load_userdict('E:\YoutubeYear\SortDict.csv') #字典抓頻道名 SavePath='E:\YoutubeYear\FeatDate.csv' FilePath=open(r'E:\YoutubeYear\Feat.csv',encoding='utf-8-sig') #feat頻道名 LenDictPath=open(r'E:\YoutubeYear\SortDict.csv',encoding='utf-8-sig') StatisticsPath=open(r'E:\YoutubeYear\NewAllStatistics.csv',encoding='utf-8-sig') all_title='' job_pd=pd.DataFrame() stopword={} LenDict={} Statistics_pd=pd.read_csv(r'E:\YoutubeYear\NewAllStatistics.csv') LongSortDict_pd=pd.read_csv(r'E:\YoutubeYear\SortDict.csv') #print(Statistics_pd) name_list=list(LongSortDict_pd['name']) def is_alphabet(keyword): return all(ord(c) < 128 and ord(c)>64 for c in keyword) StopPath=open(r'E:\dict\wordstop.txt',encoding='utf-8-sig') reader=csv.reader(StopPath) for row in reader: try: stopword[row[0]]=1 except: stopword['']=1 # searchpath= open('E:\YoutubeYear\StopNew.csv', 'r', encoding='utf-8-sig') # reader=csv.reader(searchpath) # for row in reader: # stopword[row[0]]=1 reader=csv.reader(LenDictPath) for n,row in enumerate(reader): if n==0 : pass elif LenDict.get(len(row[0]))==None: LenDict[len(row[0])]=(n+1) No_dict={} same={} same_path=open(r'E:\dict\same.txt') reader=csv.reader(same_path) for row in reader: for i in row: same[i.lower()]=row[0].lower() print(same) reader=csv.reader(FilePath)#抓合作的影片 stop=[] Feat_channelID_dict={} Feat_name_dict={} Feat_median_dict={} Feat_follow_dict={} Feat_avg_dict = {} Feat_Quartile1_dict = {} Feat_Quartile3_dict = {} for q,row in enumerate(reader): channel_name=[''] row[1]=row[1].lower() if len(row[1].split('ft'))>2: all_title = row[1].split('ft')[-1].split('|')[0].split('|')[0].split(')')[0].split('。')[0] elif 'feat' in row[1]: all_title = row[1].split('feat')[-1].split('|')[0].split('|')[0].split(')')[0].split('。')[0] elif 'ft' in row[1]: all_title = row[1].split('ft')[1].split('|')[0].split('|')[0].split(')')[0].split('。')[0] s_list = jieba.cut(all_title, cut_all=False) jieba_title=' '.join(s_list) jieba_title=jieba_title.split(' ') #print('p:',p) for title in jieba_title: if stopword.get(title)!=None or len(title)<2: #不在停用詞裡面 而且長度不是1 pass elif is_alphabet(channel_name[-1]) == True and is_alphabet(title) == True: #連續是英文的詞 channel_name[-1] = channel_name[-1]+title else: channel_name.append(title.lower())#不在停用字的詞 new_channel_name=[] for name in channel_name: #查詢是否在7100個頻道名單內 可以的話存入準備搜尋 if same.get(name) != None: name = same[name] try: for i in name_list[LenDict[len(name)]:]: if name in str(i) : new_channel_name.append(name.lower()) break except Exception as e: if str(e) =='0': pass else: print(e,end='') #print('可以使用',new_channel_name) # === go to page1 url = "https://www.youtube.com/results?" headers = {'user-agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) ' 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36', "content-type": "application/x-www-form-urlencoded"} para = {"search_query": "TEST123", "sp": "EgIQAg%253D%253D"} count=0 Feat_channel=[] Feat_name=[] Feat_median=[] Feat_follow=[] Feat_avg=[] Feat_Quartile1=[] Feat_Quartile3=[] Feat_dict={} if len(new_channel_name) <1: pass else: print('\n',new_channel_name,'-------------'+row[1]) for n, name in enumerate(new_channel_name): # 一個關鍵字搜尋頻道 if same.get(name)!=None: name=same[name] if No_dict.get(name)==None: try:#搜尋不到結果 if Feat_channelID_dict.get(name)==None: #假如這個詞沒搜尋過 for i in range(10): try:#請求錯誤 para["search_query"] = name html = requests.get(url, headers=headers, params=para) response = BeautifulSoup(html.text, 'html.parser') a = response.select('script') # 目標json在window["ytInitialData"]在當中,在a的倒數第3個 data_str = str(a[-3].text) # window["ytInitialData"] = {"responseContext":{... 的字串檔 data_str = '{' + data_str.split('= {')[1].split('window["ytInitialPlayerResponse"]')[0].strip(' ').strip('\n').strip(';') data_dict = json.loads(data_str) break except: time.sleep(2) pass channel_id = re.findall(r"channelId\': \'(.*?)\'", str(data_dict))[0] for i in range(5): try: set_a = data_dict['contents']['twoColumnSearchResultsRenderer']['primaryContents']['sectionListRenderer']['contents'][i]['itemSectionRenderer']['contents'] try: try: channel_feat_name = set_a[0]['channelRenderer']['title']['simpleText'].lower() break except: channel_feat_name = set_a[0]['videoRenderer']['longBylineText']['runs'][0]['text'].lower() break except: channel_feat_name = set_a[1]['channelRenderer']['title']['simpleText'].lower() break except: pass c = Statistics_pd.loc[ Statistics_pd['channel_id'] == row[0], ['channel_id', 'Channel_name', 'count', 'watch_all_count', 'median', 'avg', 'Quartile1', 'Quartile3', 'Follow']] # 取原頻道名稱 # print(c) # print(row[0]) MainName = (list(c['Channel_name']))[0] MainMedian = (list(c['median']))[0] MainFollow = (list(c['Follow']))[0] MainAvg=(list(c['avg']))[0] MainWatch_all=(list(c['watch_all_count']))[0] Main_Quartile1 = (list(c['Quartile1']))[0] Main_Quartile3 = (list(c['Quartile3']))[0] b = Statistics_pd.loc[ Statistics_pd['channel_id'] == channel_id, ['channel_id', 'Channel_name', 'count', 'watch_all_count', 'median', 'avg', 'Quartile1', 'Quartile3', 'Follow']] median = (list(b['median']))[0] follow = (list(b['Follow']))[0] avg=(list(b['avg']))[0] Quartile1=(list(b['Quartile1']))[0] Quartile3=(list(b['Quartile3']))[0] Feat_dict[row[0]] = 1 Feat_channelID_dict[name] = channel_id Feat_name_dict[name] = channel_feat_name.lower() Feat_median_dict[name] = median Feat_follow_dict[name] = follow Feat_avg_dict[name] = avg Feat_Quartile1_dict[name] = Quartile1 Feat_Quartile3_dict[name] = Quartile3 if Feat_dict.get(channel_id) == None: count += 1 Feat_dict[channel_id] = 1 Feat_name.append(cc.convert(channel_feat_name)) # 儲存合作的頻道名稱 Feat_channel.append(channel_id) # 儲存合作的頻道ID Feat_median.append(median) # 儲存合作的中位數 Feat_follow.append(follow) # 儲存合作的追隨數 Feat_avg.append(avg) Feat_Quartile1.append(Quartile1) Feat_Quartile3.append(Quartile3) print(name, channel_id, end=' ') #print('\n存入 ' + '查詢使用:' + name + ' ' + channel_name + ' ' + channel_id) else: #這個詞有搜尋過 c = Statistics_pd.loc[Statistics_pd['channel_id'] == row[0], ['channel_id', 'Channel_name', 'count','watch_all_count', 'median', 'avg','Quartile1', 'Quartile3', 'Follow']]#取原頻道名稱 #print(c) #print(row[0]) channel_id=Feat_channelID_dict[name] channel_feat_name=Feat_name_dict[name] Feat_dict[row[0]] = 1 median=Feat_median_dict[name] follow=Feat_follow_dict[name] avg=Feat_avg_dict[name] Quartile1=Feat_Quartile1_dict[name] Quartile3=Feat_Quartile3_dict[name] MainName = (list(c['Channel_name']))[0] MainMedian = (list(c['median']))[0] MainFollow = (list(c['Follow']))[0] MainAvg=str((list(c['avg']))[0]) MainWatch_all=(list(c['watch_all_count']))[0] Main_Quartile1 = (list(c['Quartile1']))[0] Main_Quartile3 = (list(c['Quartile3']))[0] if Feat_dict.get(channel_id)==None: count += 1 Feat_dict[channel_id]=1 Feat_name.append(cc.convert(channel_feat_name))#儲存合作的頻道名稱 Feat_channel.append(channel_id)#儲存合作的頻道ID Feat_median.append(median)#儲存合作的中位數 Feat_follow.append(follow)#儲存合作的追隨數 Feat_avg.append(avg) Feat_Quartile1.append(Quartile1) Feat_Quartile3.append(Quartile3) print(name,channel_id,end=' ') except Exception as e: No_dict[name]=1 stop.append(name) print('') print(e) pass #print(type(b)) #print(b.iloc[[0,2]]) #print(Statistics_pd.loc[Statistics_pd['channel_id']==channel_id,['median']]) if(len(Feat_channel) <1) or count ==0:#沒合作對象不用做 pass else: print(row[0],count) df = pd.DataFrame( data=[{'MainID': row[0], 'MainName':MainName, 'MainVideoTitle': row[1], 'MainVideoID': row[2], 'MainMedian': MainMedian, 'MainFollow': MainFollow, 'MainLookCount': row[3], 'MainAvg':MainAvg, 'MainWatch_all':MainWatch_all, 'Main_Quartile1' :Main_Quartile1, 'Main_Quartile3' :Main_Quartile3, 'FeatCount': count}], columns=['MainID', 'MainName','MainVideoTitle', 'MainVideoID','MainMedian','MainFollow','MainLookCount','MainAvg','MainWatch_all','Main_Quartile1','Main_Quartile3','FeatCount']) for i in range(len(Feat_channel)):#新增欄位到右邊 df['Feat_channel{}'.format(i+1)]=Feat_channel[i] df['Feat_name{}'.format(i+1)]=Feat_name[i] df['Feat_median{}'.format(i+1)]=Feat_median[i] df['Feat_follow{}'.format(i+1)]=Feat_follow[i] df['Feat_avg{}'.format(i+1)]=Feat_avg[i] df['Feat_Quartile1{}'.format(i + 1)] = Feat_Quartile1[i] df['Feat_Quartile3{}'.format(i + 1)] = Feat_Quartile3[i] #print(Feat_channel[i],Feat_name[i],Feat_median[i],end='') job_pd=job_pd.append(df,sort=False) if q%2==0: searchpath = open('E:\YoutubeYear\StopNew.csv', 'a', encoding='utf-8-sig') #print('寫入') for i in stop: searchpath.write(i) searchpath.write('\n') stop=[] job_pd=job_pd.sort_values(by='FeatCount') job_pd.to_csv(SavePath,index=0,header=True,encoding='utf-8-sig') #使用pandas的groupby之後轉成List,其中每個元素會是tuple,第一項是goupby的值,第二項為datarame a = job_pd.groupby('FeatCount') #根據'date'這個欄位做groupby for item in list(a): print(item[0]) item[1].dropna(axis=1,how='any',inplace=True) item[1].to_csv('./FeatCountPeoPle{}.csv'.format(item[0]), encoding='utf-8-sig', index=0)
#!/usr/bin/python import os import time from SpeechToTextEngine import SpeechToTextEngine from TextToSpeechEngine import TextToSpeechEngine """ This Python executable is for omega-desktop. The trigger word is omega. """ TRIGGER_WORD = "omega" class VoiceControl(): def __init__(self): self.stt = SpeechToTextEngine() self.tts = TextToSpeechEngine() def doAction(self, input): if input.find("studio") != -1: self.tts.say("starting android studio") os.system("studio.sh &") elif input.find("brackets") != -1: self.tts.say("starting brackets") os.system("brackets &") elif input.find("test") != -1: self.tts.say("voice command utility functioning") else: self.tts.say("unrecognized action") def run(self): input = self.stt.listen() while True: print "Received: " + input if input.find(TRIGGER_WORD) != -1: self.doAction(input) input = self.stt.listen() def main(): control = VoiceControl() control.run() if __name__ == "__main__": main()
import nltk import numpy from fuel.transformers import AgnosticSourcewiseTransformer, Transformer, SourcewiseTransformer from .utils import sort_dict from PIL import Image, ImageOps class OneHotTransformer(AgnosticSourcewiseTransformer): def __init__(self, data_stream, nclasses, **kwargs): self.nclasses = nclasses self.I = numpy.eye(self.nclasses, dtype='int32') if data_stream.axis_labels: kwargs.setdefault('axis_labels', data_stream.axis_labels.copy()) super(OneHotTransformer, self).__init__( data_stream, data_stream.produces_examples, **kwargs) def transform_any_source(self, source_data, _): return self.I[source_data] class SequenceTransposer(AgnosticSourcewiseTransformer): def __init__(self, data_stream, **kwargs): if data_stream.axis_labels: kwargs.setdefault('axis_labels', data_stream.axis_labels.copy()) super(SequenceTransposer, self).__init__( data_stream, data_stream.produces_examples, **kwargs) def transform_any_source(self, source_data, _): if source_data.ndim == 2: return source_data.T elif source_data.ndim == 3: return source_data.transpose(1, 0, 2) else: raise ValueError('Invalid dimensions of this source.') class PairwiseTransformer(Transformer): def __init__(self, data_stream, target_source, **kwargs): super(PairwiseTransformer, self).__init__( data_stream, produces_examples=False, **kwargs) self.target_source = target_source @property def sources(self): sources = [] for source in self.data_stream.sources: if source != self.target_source: sources.append(source + '_1') sources.append(source + '_2') else: sources.append(source) return tuple(sources) def transform_batch(self, batch): batches = [] for i, (source, source_batch) in enumerate( zip(self.data_stream.sources, batch)): if source_batch.shape[0] % 2 != 0: source_batch = source_batch[:-1] half_batch = int(source_batch.shape[0] / 2) first_batch = source_batch[0:half_batch] second_batch = source_batch[half_batch:] if source == self.target_source: targets = numpy.equal(first_batch, second_batch) batches.append(targets) else: batches.extend([first_batch, second_batch]) return tuple(batches) class SentTokenizer(Transformer): def __init__(self, word_to_ix, ix_to_word, data_stream, which_source, **kwargs): if not data_stream.produces_examples: raise ValueError('the wrapped data stream must produce examples, ' 'not batches of examples.') self.which_source = which_source self.word_to_ix = word_to_ix self.ix_to_word = ix_to_word super(SentTokenizer, self).__init__(data_stream, produces_examples=True, **kwargs) @property def sources(self): sources = [] for source in self.data_stream.sources: sources.append(source) if source == self.which_source: sources.append(source + '_mask') return tuple(sources) def transform_example(self, source_example): example_with_mask = [] for source, example in zip(self.data_stream.sources, source_example): if source != self.which_source: example_with_mask.append(example) continue sentences = nltk.sent_tokenize( ' '.join([self.ix_to_word[ix] for ix in example])) sentences = [[self.word_to_ix[w] for w in sent.split()] for sent in sentences] max_length = max([len(s) for s in sentences]) batch = numpy.zeros( (len(sentences), max_length), dtype=example.dtype) mask = numpy.zeros((len(sentences), max_length), dtype='float32') for i, s in enumerate(sentences): batch[i, :len(s)] = s mask[i, :len(s)] = 1 example_with_mask.append(batch) example_with_mask.append(mask) return tuple(example_with_mask) class Resizer(SourcewiseTransformer): def __init__(self, data_stream, shape, **kwargs): self.shape = shape kwargs.setdefault('axis_labels', data_stream.axis_labels) super(Resizer, self).__init__( data_stream, data_stream.produces_examples, **kwargs) def transform_source_example(self, source_example, source_name): out = numpy.empty( (source_example.shape[0],) + self.shape, dtype=source_example.dtype) if source_example.shape[0] in [1, 3]: img = Image.fromarray(source_example.transpose(1, 2, 0)) img = img.resize(self.shape) out[...] = numpy.asarray(img).transpose(2, 0, 1) else: for i in range(source_example.shape[0]): img = Image.fromarray(source_example[i]) img = img.resize(self.shape) out[i] = numpy.asarray(img) return out def transform_source_batch(self, source_batch, source_name): out = [] for source_example in source_batch: out.append(self.transform_source_example( source_example, source_name)) return numpy.asarray(out)
from ED6ScenarioHelper import * def main(): # 卢安 CreateScenaFile( FileName = 'T2310 ._SN', MapName = 'Ruan', Location = 'T2310.x', MapIndex = 1, MapDefaultBGM = "ed60015", Flags = 0, EntryFunctionIndex = 0xFFFF, Reserved = 0, IncludedScenario = [ '', '', '', '', '', '', '', '' ], ) BuildStringList( '@FileName', # 8 '迪恩', # 9 '雷斯', # 10 '洛克', # 11 '青年', # 12 '青年', # 13 '青年', # 14 '青年', # 15 '青年', # 16 '青年', # 17 '秘书基尔巴特', # 18 '卡露娜', # 19 '阿梅莉娅', # 20 '扎古', # 21 '索雷诺', # 22 '塞尔吉村长', # 23 ) DeclEntryPoint( Unknown_00 = 0, Unknown_04 = 0, Unknown_08 = 6000, Unknown_0C = 4, Unknown_0E = 0, Unknown_10 = 0, Unknown_14 = 9500, Unknown_18 = -10000, Unknown_1C = 0, Unknown_20 = 0, Unknown_24 = 0, Unknown_28 = 2800, Unknown_2C = 262, Unknown_30 = 45, Unknown_32 = 0, Unknown_34 = 360, Unknown_36 = 0, Unknown_38 = 0, Unknown_3A = 0, InitScenaIndex = 0, InitFunctionIndex = 0, EntryScenaIndex = 0, EntryFunctionIndex = 1, ) AddCharChip( 'ED6_DT07/CH00374 ._CH', # 00 'ED6_DT07/CH02420 ._CH', # 01 'ED6_DT07/CH01240 ._CH', # 02 'ED6_DT07/CH01050 ._CH', # 03 'ED6_DT07/CH01460 ._CH', # 04 'ED6_DT07/CH01040 ._CH', # 05 'ED6_DT07/CH01000 ._CH', # 06 ) AddCharChipPat( 'ED6_DT07/CH00374P._CP', # 00 'ED6_DT07/CH02420P._CP', # 01 'ED6_DT07/CH01240P._CP', # 02 'ED6_DT07/CH01050P._CP', # 03 'ED6_DT07/CH01460P._CP', # 04 'ED6_DT07/CH01040P._CP', # 05 'ED6_DT07/CH01000P._CP', # 06 ) DeclNpc( X = -31270, Z = 0, Y = 42780, Direction = 90, Unknown2 = 0, Unknown3 = 0, ChipIndex = 0x0, NpcIndex = 0x181, InitFunctionIndex = -1, InitScenaIndex = -1, TalkFunctionIndex = -1, TalkScenaIndex = -1, ) DeclNpc( X = -30310, Z = 0, Y = 42270, Direction = 90, Unknown2 = 0, Unknown3 = 0, ChipIndex = 0x0, NpcIndex = 0x181, InitFunctionIndex = -1, InitScenaIndex = -1, TalkFunctionIndex = -1, TalkScenaIndex = -1, ) DeclNpc( X = -28770, Z = 0, Y = 42770, Direction = 90, Unknown2 = 0, Unknown3 = 0, ChipIndex = 0x0, NpcIndex = 0x181, InitFunctionIndex = -1, InitScenaIndex = -1, TalkFunctionIndex = -1, TalkScenaIndex = -1, ) DeclNpc( X = -31020, Z = 0, Y = 44700, Direction = 90, Unknown2 = 0, Unknown3 = 0, ChipIndex = 0x0, NpcIndex = 0x181, InitFunctionIndex = -1, InitScenaIndex = -1, TalkFunctionIndex = -1, TalkScenaIndex = -1, ) DeclNpc( X = -30070, Z = 0, Y = 44130, Direction = 90, Unknown2 = 0, Unknown3 = 0, ChipIndex = 0x0, NpcIndex = 0x181, InitFunctionIndex = -1, InitScenaIndex = -1, TalkFunctionIndex = -1, TalkScenaIndex = -1, ) DeclNpc( X = -29310, Z = 0, Y = 43790, Direction = 90, Unknown2 = 0, Unknown3 = 0, ChipIndex = 0x0, NpcIndex = 0x181, InitFunctionIndex = -1, InitScenaIndex = -1, TalkFunctionIndex = -1, TalkScenaIndex = -1, ) DeclNpc( X = -31330, Z = 0, Y = 43790, Direction = 90, Unknown2 = 0, Unknown3 = 0, ChipIndex = 0x0, NpcIndex = 0x181, InitFunctionIndex = -1, InitScenaIndex = -1, TalkFunctionIndex = -1, TalkScenaIndex = -1, ) DeclNpc( X = -30780, Z = 0, Y = 43810, Direction = 90, Unknown2 = 0, Unknown3 = 0, ChipIndex = 0x0, NpcIndex = 0x181, InitFunctionIndex = -1, InitScenaIndex = -1, TalkFunctionIndex = -1, TalkScenaIndex = -1, ) DeclNpc( X = -30050, Z = 0, Y = 43240, Direction = 90, Unknown2 = 0, Unknown3 = 0, ChipIndex = 0x0, NpcIndex = 0x181, InitFunctionIndex = -1, InitScenaIndex = -1, TalkFunctionIndex = -1, TalkScenaIndex = -1, ) DeclNpc( X = -26650, Z = 0, Y = 44050, Direction = 180, Unknown2 = 0, Unknown3 = 1, ChipIndex = 0x1, NpcIndex = 0x181, InitFunctionIndex = -1, InitScenaIndex = -1, TalkFunctionIndex = -1, TalkScenaIndex = -1, ) DeclNpc( X = -30050, Z = 0, Y = 39240, Direction = 0, Unknown2 = 0, Unknown3 = 2, ChipIndex = 0x2, NpcIndex = 0x181, InitFunctionIndex = 0, InitScenaIndex = 2, TalkFunctionIndex = 0, TalkScenaIndex = 7, ) DeclNpc( X = -200, Z = 0, Y = 8850, Direction = 0, Unknown2 = 0, Unknown3 = 3, ChipIndex = 0x3, NpcIndex = 0x101, InitFunctionIndex = 0, InitScenaIndex = 2, TalkFunctionIndex = 0, TalkScenaIndex = 3, ) DeclNpc( X = -3700, Z = 0, Y = 5500, Direction = 270, Unknown2 = 0, Unknown3 = 4, ChipIndex = 0x4, NpcIndex = 0x101, InitFunctionIndex = 0, InitScenaIndex = 2, TalkFunctionIndex = 0, TalkScenaIndex = 4, ) DeclNpc( X = -25570, Z = 0, Y = 2300, Direction = 180, Unknown2 = 0, Unknown3 = 5, ChipIndex = 0x5, NpcIndex = 0x101, InitFunctionIndex = 0, InitScenaIndex = 2, TalkFunctionIndex = 0, TalkScenaIndex = 5, ) DeclNpc( X = -27510, Z = 0, Y = 8670, Direction = 0, Unknown2 = 0, Unknown3 = 6, ChipIndex = 0x6, NpcIndex = 0x101, InitFunctionIndex = 0, InitScenaIndex = 2, TalkFunctionIndex = 0, TalkScenaIndex = 6, ) ScpFunction( "Function_0_2C2", # 00, 0 "Function_1_420", # 01, 1 "Function_2_442", # 02, 2 "Function_3_458", # 03, 3 "Function_4_12BE", # 04, 4 "Function_5_1D3E", # 05, 5 "Function_6_24F9", # 06, 6 "Function_7_3053", # 07, 7 "Function_8_30AE", # 08, 8 ) def Function_0_2C2(): pass label("Function_0_2C2") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA0, 0)), scpexpr(EXPR_END)), "loc_2FF") SetChrPos(0x14, -26670, 0, 39530, 90) SetChrPos(0x16, -30150, 0, 3860, 270) SetChrPos(0x15, -29310, 0, 43880, 0) Jump("loc_3E4") label("loc_2FF") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x86, 5)), scpexpr(EXPR_END)), "loc_313") SetChrFlags(0x14, 0x80) SetChrFlags(0x14, 0x8) Jump("loc_3E4") label("loc_313") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x85, 5)), scpexpr(EXPR_END)), "loc_31D") Jump("loc_3E4") label("loc_31D") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x85, 0)), scpexpr(EXPR_END)), "loc_33B") SetChrFlags(0x14, 0x80) SetChrFlags(0x14, 0x8) SetChrFlags(0x15, 0x80) SetChrFlags(0x15, 0x8) Jump("loc_3E4") label("loc_33B") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x83, 4)), scpexpr(EXPR_END)), "loc_359") SetChrFlags(0x14, 0x80) SetChrFlags(0x14, 0x8) SetChrFlags(0x15, 0x80) SetChrFlags(0x15, 0x8) Jump("loc_3E4") label("loc_359") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x82, 1)), scpexpr(EXPR_END)), "loc_396") SetChrPos(0x14, -26670, 0, 39530, 90) SetChrPos(0x16, -30150, 0, 3860, 270) SetChrPos(0x15, -29310, 0, 43880, 0) Jump("loc_3E4") label("loc_396") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x81, 5)), scpexpr(EXPR_END)), "loc_3D3") SetChrPos(0x14, -26670, 0, 39530, 90) SetChrPos(0x16, -30150, 0, 3860, 270) SetChrPos(0x15, -29310, 0, 43880, 0) Jump("loc_3E4") label("loc_3D3") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x81, 4)), scpexpr(EXPR_END)), "loc_3DD") Jump("loc_3E4") label("loc_3DD") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x6B, 6)), scpexpr(EXPR_END)), "loc_3E4") label("loc_3E4") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x85, 5)), scpexpr(EXPR_EXEC_OP, "OP_29(0x1F, 0x0, 0x40)"), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_411") Jc((scpexpr(EXPR_EXEC_OP, "OP_29(0x1F, 0x0, 0x4)"), scpexpr(EXPR_EQUZ), scpexpr(EXPR_EXEC_OP, "OP_29(0x1F, 0x1, 0x4000)"), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_411") SetChrFlags(0x13, 0x80) SetChrFlags(0x13, 0x8) label("loc_411") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x7F, 2)), scpexpr(EXPR_END)), "loc_41F") OP_A3(0x3FA) Event(0, 8) label("loc_41F") Return() # Function_0_2C2 end def Function_1_420(): pass label("Function_1_420") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x86, 4)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x87, 4)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_438") OP_B1("t2310_y") Jump("loc_441") label("loc_438") OP_B1("t2310_n") label("loc_441") Return() # Function_1_420 end def Function_2_442(): pass label("Function_2_442") Jc((scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_END)), "loc_457") OP_99(0xFE, 0x0, 0x7, 0x5DC) Jump("Function_2_442") label("loc_457") Return() # Function_2_442 end def Function_3_458(): pass label("Function_3_458") TalkBegin(0x13) Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA0, 0)), scpexpr(EXPR_END)), "loc_4C7") ChrTalk( 0xFE, ( "扎古这次\x01", "又跑到哪里去了呢?\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "我还想要他\x01", "去卢安买东西呢……\x02", ) ) CloseMessageWindow() Jump("loc_12BA") label("loc_4C7") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x87, 4)), scpexpr(EXPR_END)), "loc_558") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 1)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_535") OP_A2(0x1) ChrTalk( 0xFE, ( "听说犯人都藏在\x01", "巴伦诺灯塔里。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "不知道守护灯塔的\x01", "弗科特爷爷有没有出事……\x02", ) ) CloseMessageWindow() Jump("loc_555") label("loc_535") ChrTalk( 0xFE, ( "不知道守护灯塔的\x01", "弗科特爷爷有没有出事……\x02", ) ) CloseMessageWindow() label("loc_555") Jump("loc_12BA") label("loc_558") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x86, 5)), scpexpr(EXPR_END)), "loc_614") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 1)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_5E1") OP_A2(0x1) ChrTalk( 0xFE, ( "孩子们都一边哭,\x01", "一边回来了……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "真是让人担心啊……\x01", "是不是碰到什么事了?\x02", ) ) CloseMessageWindow() Jump("loc_611") label("loc_5E1") ChrTalk( 0xFE, ( "说起来,\x01", "扎古去了哪里呢……\x02", ) ) CloseMessageWindow() label("loc_611") Jump("loc_12BA") label("loc_614") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x85, 5)), scpexpr(EXPR_END)), "loc_C23") Jc((scpexpr(EXPR_EXEC_OP, "OP_29(0x1F, 0x0, 0x10)"), scpexpr(EXPR_END)), "loc_AFF") Jc((scpexpr(EXPR_EXEC_OP, "OP_29(0x1F, 0x1, 0x8000)"), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_A8A") OP_28(0x1F, 0x1, 0x8000) Jc((scpexpr(EXPR_EXEC_OP, "OP_29(0x1F, 0x0, 0x4)"), scpexpr(EXPR_END)), "loc_777") ChrTalk( 0xFE, "啊,是各位游击士……\x02", ) CloseMessageWindow() ChrTalk( 0xFE, ( "唉,\x01", "叔父还是没有回家来呢。\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, ( "#000F啊,已经没事了。\x02\x03", "现在,您叔父\x01", "应该已经精神抖擞地向卢安进发了。\x02", ) ) CloseMessageWindow() TurnDirection(0xFE, 0x101, 400) ChrTalk( 0xFE, "什么?\x02", ) CloseMessageWindow() ChrTalk( 0xFE, "怎么回事?\x02", ) CloseMessageWindow() ChrTalk( 0x102, ( "#010F您叔父在古罗尼山道\x01", "被魔兽袭击的时候,\x01", "我们正巧路过把他救了出来。\x02\x03", "他没有受伤,请您放心。\x01", " \x02", ) ) CloseMessageWindow() Jump("loc_992") label("loc_777") ChrTalk( 0xFE, ( "呼,\x01", "叔父真是的……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "难道真的\x01", "自己一个人\x01", "去了古罗尼山道吗。\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, ( "#000F啊,\x01", "你说的那个叔父,\x02\x03", "难不成是去采野菜了吗?\x01", " \x02", ) ) CloseMessageWindow() TurnDirection(0xFE, 0x101, 400) ChrTalk( 0xFE, ( "嗯,\x01", "他确实这么说过……\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, ( "#000F那就没事了。\x02\x03", "他现在正在去卢安的路上呢。\x01", " \x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, "哎?\x02", ) CloseMessageWindow() ChrTalk( 0xFE, "怎么回事?\x02", ) CloseMessageWindow() ChrTalk( 0x102, ( "#010F您叔父在古罗尼山道\x01", "被魔兽袭击的时候,\x01", "我们正巧路过把他救了出来。\x02\x03", "他没有受伤,请您放心。\x01", " \x02", ) ) CloseMessageWindow() label("loc_992") TurnDirection(0xFE, 0x102, 400) ChrTalk( 0xFE, "啊,是这样啊。\x02", ) CloseMessageWindow() ChrTalk( 0xFE, ( "对不起啊。\x01", "给你们添麻烦了……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "但是,\x01", "发生那种事情,\x01", "叔父好歹也该跟家里说一声吧。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "真是的,\x01", "他也太性急了吧。\x02", ) ) CloseMessageWindow() Jump("loc_AFC") label("loc_A8A") ChrTalk( 0xFE, ( "对不起啊。\x01", "给你们添麻烦了……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "真是的,\x01", "叔父他也太性急了吧。\x02", ) ) CloseMessageWindow() label("loc_AFC") Jump("loc_C20") label("loc_AFF") ChrTalk( 0xFE, ( "以前我是和扎古还有叔父\x01", "三个人一起生活的。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "自从奥维德叔父走了之后\x01", "已经过了好几年了……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "虽然他偶尔也会回来,\x01", "但是马上又不见踪影了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "呼,\x01", "我可不希望扎古也变成那样……\x02", ) ) CloseMessageWindow() label("loc_C20") Jump("loc_12BA") label("loc_C23") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x85, 0)), scpexpr(EXPR_END)), "loc_D12") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 1)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_CCD") OP_A2(0x1) ChrTalk( 0xFE, ( "听说孤儿院的火灾\x01", "是有人故意纵火造成的。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "好过分啊……\x01", "那些人为什么要这么做……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "我等会儿也要去\x01", "卡拉那里帮忙。\x02", ) ) CloseMessageWindow() Jump("loc_D0F") label("loc_CCD") ChrTalk( 0xFE, ( "听说孤儿院的火灾\x01", "是有人故意纵火造成的。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, "好过分啊……\x02", ) CloseMessageWindow() label("loc_D0F") Jump("loc_12BA") label("loc_D12") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x83, 4)), scpexpr(EXPR_END)), "loc_E4B") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 1)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_DD4") OP_A2(0x1) ChrTalk( 0xFE, ( "昨天晚上,一听说孤儿院着火,\x01", "扎古就飞奔出去了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "现在好像又在\x01", "处理火灾的后事了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "这种时候\x01", "他还真靠得住。\x02", ) ) CloseMessageWindow() Jump("loc_E48") label("loc_DD4") ChrTalk( 0xFE, ( "昨天晚上,一听说孤儿院着火,\x01", "扎古就飞奔出去了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "这种时候\x01", "他还真靠得住。\x02", ) ) CloseMessageWindow() label("loc_E48") Jump("loc_12BA") label("loc_E4B") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x82, 1)), scpexpr(EXPR_END)), "loc_F9E") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 1)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_F19") OP_A2(0x1) ChrTalk( 0xFE, ( "啊啊~\x01", "老是担心弟弟的话,\x01", "我就要成老寡妇了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "不过在扎古成家之前,\x01", "还是得不断操心啊……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "实在没办法\x01", "先考虑自己的事。\x02", ) ) CloseMessageWindow() Jump("loc_F9B") label("loc_F19") ChrTalk( 0xFE, ( "啊啊~\x01", "老是担心弟弟的话,\x01", "我就要成老寡妇了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "不过在扎古成家之前,\x01", "还是得不断操心啊……\x02", ) ) CloseMessageWindow() label("loc_F9B") Jump("loc_12BA") label("loc_F9E") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x81, 5)), scpexpr(EXPR_END)), "loc_10FD") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 1)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_107C") OP_A2(0x1) ChrTalk( 0xFE, ( "扎古今后\x01", "到底想做什么呢……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "不认真工作的话,\x01", "可不会有女孩子喜欢上他哦。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "那个孩子,\x01", "一直都很让人替他操心啊。\x02", ) ) CloseMessageWindow() Jump("loc_10FA") label("loc_107C") ChrTalk( 0xFE, ( "扎古今后\x01", "到底想做什么呢……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "那个孩子,\x01", "一直都很让人替他操心啊。\x02", ) ) CloseMessageWindow() label("loc_10FA") Jump("loc_12BA") label("loc_10FD") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x81, 4)), scpexpr(EXPR_END)), "loc_116E") ChrTalk( 0xFE, "问我有没有看到一个男孩?\x02", ) CloseMessageWindow() ChrTalk( 0xFE, ( "要说这村里的孩子,\x01", "只有卢希娅一个,\x01", "看来他不是这个村里的……\x02", ) ) CloseMessageWindow() Jump("loc_12BA") label("loc_116E") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x6B, 6)), scpexpr(EXPR_END)), "loc_12BA") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 1)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_1237") OP_A2(0x1) ChrTalk( 0xFE, ( "扎古在卢安工作的时候被开除了,\x01", "然后就回村里来了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "真是的,\x01", "一点也不为自己的将来着想。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "我作为他的姐姐,\x01", "为他担心得不得了。\x02", ) ) CloseMessageWindow() Jump("loc_12BA") label("loc_1237") ChrTalk( 0xFE, ( "扎古在卢安工作的时候被开除了,\x01", "然后就回村里来了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "真是的,\x01", "一点也不为自己的将来着想。\x02", ) ) CloseMessageWindow() label("loc_12BA") TalkEnd(0x13) Return() # Function_3_458 end def Function_4_12BE(): pass label("Function_4_12BE") TalkBegin(0x14) Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA0, 0)), scpexpr(EXPR_END)), "loc_1442") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_13AE") OP_A2(0x0) ChrTalk( 0xFE, ( "真没想到竟然是市长他们犯的罪,\x01", "太让人吃惊了……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "嗯,事件被查证清楚后\x01", "老师他们应该也能获得赔偿金吧。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "要是修建孤儿院的话,\x01", "我是很乐意帮忙的。\x02", ) ) CloseMessageWindow() Jump("loc_143F") label("loc_13AE") ChrTalk( 0xFE, ( "事件被查证清楚后,\x01", "老师他们应该也能获得赔偿金吧。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "要是修建孤儿院的话,\x01", "我是很乐意帮忙的。\x02", ) ) CloseMessageWindow() label("loc_143F") Jump("loc_1D3A") label("loc_1442") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x87, 4)), scpexpr(EXPR_END)), "loc_15AF") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_1533") OP_A2(0x0) ChrTalk( 0xFE, ( "纵火犯被关起来了,\x01", "是真的吗?\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, "是你们逮捕他们的吧。\x02", ) CloseMessageWindow() ChrTalk( 0xFE, ( "干得好啊!\x01", "不愧是守护正义的游击士。\x02", ) ) CloseMessageWindow() Jump("loc_15AC") label("loc_1533") ChrTalk( 0xFE, ( "就是你们\x01", "把纵火犯给逮捕了吧。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "干得好啊!\x01", "不愧是守护正义的游击士。\x02", ) ) CloseMessageWindow() label("loc_15AC") Jump("loc_1D3A") label("loc_15AF") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x85, 5)), scpexpr(EXPR_END)), "loc_1824") Jc((scpexpr(EXPR_EXEC_OP, "OP_29(0x1F, 0x1, 0x8000)"), scpexpr(EXPR_END)), "loc_16B1") ChrTalk( 0xFE, ( "就是你们\x01", "救了叔父吗?\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "真是非常感谢。\x01", "这么忙还劳烦你们。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "那么,孤儿院事件的\x01", "调查工作也要加油哦。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "做出那种事情的家伙,\x01", "我是绝对不会原谅他的……\x02", ) ) CloseMessageWindow() Jump("loc_1821") label("loc_16B1") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_17A4") OP_A2(0x0) ChrTalk( 0xFE, ( "失火现场的整理\x01", "终于告一段落了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "说起来,\x01", "到底是谁做出这种事情的啊。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "可恶,\x01", "我绝对不饶恕那些放火的犯人……\x02", ) ) CloseMessageWindow() Jump("loc_1821") label("loc_17A4") ChrTalk( 0xFE, ( "失火现场的整理\x01", "终于告一段落了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "可恶,\x01", "我绝对不饶恕那些放火的犯人……\x02", ) ) CloseMessageWindow() label("loc_1821") Jump("loc_1D3A") label("loc_1824") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x82, 1)), scpexpr(EXPR_END)), "loc_1974") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_1922") OP_A2(0x0) ChrTalk( 0xFE, ( "那个城市……\x01", "卢安变了呢。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "以前卢安是以贸易\x01", "和渔业为中心的城镇。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "现在渐渐被游客看作是\x01", "观光和休闲胜地。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "最近听说那里\x01", "治安有点不太好。\x02", ) ) CloseMessageWindow() Jump("loc_1971") label("loc_1922") ChrTalk( 0xFE, ( "最近听说卢安的\x01", "治安有点不太好。\x02", ) ) CloseMessageWindow() label("loc_1971") Jump("loc_1D3A") label("loc_1974") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x81, 5)), scpexpr(EXPR_END)), "loc_1B1D") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_1A77") OP_A2(0x0) ChrTalk( 0xFE, ( "我也去过\x01", "玛西亚孤儿院。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "有时候会和索雷诺那家伙\x01", "一起去帮忙干些体力活。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "因为那里只有\x01", "特蕾莎老师一个人在打理,\x01", "一个男的劳动力都没有。\x02", ) ) CloseMessageWindow() Jump("loc_1B1A") label("loc_1A77") ChrTalk( 0xFE, ( "我也去过\x01", "玛西亚孤儿院。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "因为那里只有\x01", "特蕾莎老师一个人在打理,\x01", "一个男的劳动力都没有。\x02", ) ) CloseMessageWindow() label("loc_1B1A") Jump("loc_1D3A") label("loc_1B1D") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x81, 4)), scpexpr(EXPR_END)), "loc_1B9C") ChrTalk( 0xFE, "……男孩吗?\x02", ) CloseMessageWindow() ChrTalk( 0xFE, ( "我一直在家,\x01", "没有看到你说的那个男孩。\x02", ) ) CloseMessageWindow() Jump("loc_1D3A") label("loc_1B9C") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x6B, 6)), scpexpr(EXPR_END)), "loc_1D3A") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_1C97") OP_A2(0x0) ChrTalk( 0xFE, ( "我曾经在卢安的港口工作过,\x01", "不过现在我\x01", "回到了自己的故乡。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "果然还是在自己生长的\x01", "土地上生活比较安稳。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "除了姐姐一直\x01", "在旁边啰里啰嗦的……\x02", ) ) CloseMessageWindow() Jump("loc_1D3A") label("loc_1C97") ChrTalk( 0xFE, ( "我曾经在卢安的港口工作过,\x01", "不过现在我\x01", "回到了自己的故乡。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "果然还是在自己生长的\x01", "土地上生活比较安稳。\x02", ) ) CloseMessageWindow() label("loc_1D3A") TalkEnd(0x14) Return() # Function_4_12BE end def Function_5_1D3E(): pass label("Function_5_1D3E") TalkBegin(0x15) Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA0, 0)), scpexpr(EXPR_END)), "loc_1D8F") ChrTalk( 0xFE, ( "在这里也能听到\x01", "孩子们玩耍的声音。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, "真是太好了。\x02", ) CloseMessageWindow() Jump("loc_24F5") label("loc_1D8F") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x87, 4)), scpexpr(EXPR_END)), "loc_1E21") ChrTalk( 0xFE, ( "犯人被逮捕了,\x01", "我也松了一口气。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "真不愧是游击士。\x01", "果然很靠得住啊。\x02", ) ) CloseMessageWindow() Jump("loc_24F5") label("loc_1E21") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x86, 5)), scpexpr(EXPR_END)), "loc_1FBE") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 2)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_1F11") OP_A2(0x2) ChrTalk( 0xFE, ( "玛西亚孤儿院的老师和孩子们\x01", "到底被什么人袭击了?\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "如果是同一伙犯人所为,\x01", "为什么他们还要加害那些孩子们……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "那些孩子们\x01", "什么坏事也没有做啊。\x02", ) ) CloseMessageWindow() Jump("loc_1FBB") label("loc_1F11") ChrTalk( 0xFE, ( "如果是同一伙犯人所为,\x01", "为什么他们还要加害那些孩子们……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "那些孩子们\x01", "什么坏事也没有做啊。\x02", ) ) CloseMessageWindow() label("loc_1FBB") Jump("loc_24F5") label("loc_1FBE") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x85, 5)), scpexpr(EXPR_END)), "loc_20E7") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 2)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_2074") OP_A2(0x2) ChrTalk( 0xFE, ( "孤儿院里只剩下\x01", "瓦砾和灰烬了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "那天的火势\x01", "还真是强啊……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "那里本来是一个能勾起老师和\x01", "孩子们许多回忆的地方……\x02", ) ) CloseMessageWindow() Jump("loc_20E4") label("loc_2074") ChrTalk( 0xFE, ( "孤儿院里只剩下\x01", "瓦砾和灰烬了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "那里本来是一个能勾起老师和\x01", "孩子们许多回忆的地方……\x02", ) ) CloseMessageWindow() label("loc_20E4") Jump("loc_24F5") label("loc_20E7") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x82, 1)), scpexpr(EXPR_END)), "loc_2201") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 2)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_2194") OP_A2(0x2) ChrTalk( 0xFE, ( "明天要和扎古一起\x01", "运送食物到孤儿院。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "我考虑到孩子的数量,\x01", "所以准备了很多哦。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, "现在必须要开始准备了。\x02", ) CloseMessageWindow() Jump("loc_21FE") label("loc_2194") ChrTalk( 0xFE, ( "明天要和扎古一起\x01", "运送食物到孤儿院。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, "现在必须要开始准备了。\x02", ) CloseMessageWindow() label("loc_21FE") Jump("loc_24F5") label("loc_2201") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x81, 5)), scpexpr(EXPR_END)), "loc_2360") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 2)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_22EB") OP_A2(0x2) ChrTalk( 0xFE, ( "这个村的村民\x01", "也在帮助玛西亚孤儿院。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "特蕾莎院长\x01", "真的是非常辛苦呢。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "扎古辞掉了工作\x01", "回到这里之后,\x01", "好像经常去那里帮忙呢。\x02", ) ) CloseMessageWindow() Jump("loc_235D") label("loc_22EB") ChrTalk( 0xFE, ( "这个村的村民\x01", "也在帮助玛西亚孤儿院。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "特蕾莎院长\x01", "真的是非常辛苦呢。\x02", ) ) CloseMessageWindow() label("loc_235D") Jump("loc_24F5") label("loc_2360") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x81, 4)), scpexpr(EXPR_END)), "loc_23A0") ChrTalk( 0xFE, "戴着帽子的男孩子?\x02", ) CloseMessageWindow() ChrTalk( 0xFE, "真抱歉,我没看到。\x02", ) CloseMessageWindow() Jump("loc_24F5") label("loc_23A0") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x6B, 6)), scpexpr(EXPR_END)), "loc_24F5") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 2)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_2487") OP_A2(0x2) ChrTalk( 0xFE, "啊呀,是旅行者吗?\x02", ) CloseMessageWindow() ChrTalk( 0xFE, ( "如果你们要找吃饭的地方,\x01", "我推荐你们去『白之木莲亭』。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "那里的饭菜味道很好,\x01", "价格也非常适中。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, "还有许多额外的赠品哦。\x02", ) CloseMessageWindow() Jump("loc_24F5") label("loc_2487") ChrTalk( 0xFE, ( "如果你们要找吃饭的地方,\x01", "我推荐你们去『白之木莲亭』。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "『白之木莲亭』\x01", "就在这座房屋的旁边。\x02", ) ) CloseMessageWindow() label("loc_24F5") TalkEnd(0x15) Return() # Function_5_1D3E end def Function_6_24F9(): pass label("Function_6_24F9") TalkBegin(0x16) Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA0, 0)), scpexpr(EXPR_END)), "loc_25B1") ChrTalk( 0xFE, ( "真没想到戴尔蒙市长\x01", "竟然做出这么过分的事……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "简直不敢相信,\x01", "实在难以理解呀。\x02", ) ) CloseMessageWindow() Jump("loc_304F") label("loc_25B1") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x87, 4)), scpexpr(EXPR_END)), "loc_26AF") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 3)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_2655") OP_A2(0x3) ChrTalk( 0xFE, ( "哦哦,是几位游击士啊。\x01", "听说你们抓到了犯人。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "只要我们能帮得上忙,\x01", "请你们尽管开口。\x02", ) ) CloseMessageWindow() Jump("loc_26AC") label("loc_2655") ChrTalk( 0xFE, "竟然做出这么过分的事……\x02", ) CloseMessageWindow() ChrTalk( 0xFE, ( "他们到底\x01", "打算干什么啊?\x02", ) ) CloseMessageWindow() label("loc_26AC") Jump("loc_304F") label("loc_26AF") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x86, 5)), scpexpr(EXPR_END)), "loc_27C7") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 3)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_2755") OP_A2(0x3) ChrTalk( 0xFE, ( "事情的经过\x01", "我已经听说了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "一次还不够,\x01", "竟然又做出如此令人发指的事情……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "这真是令人\x01", "痛心不已啊……\x02", ) ) CloseMessageWindow() Jump("loc_27C4") label("loc_2755") ChrTalk( 0xFE, ( "一次还不够,\x01", "竟然又做出如此令人发指的事情……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "这真是令人\x01", "痛心不已啊……\x02", ) ) CloseMessageWindow() label("loc_27C4") Jump("loc_304F") label("loc_27C7") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x85, 5)), scpexpr(EXPR_END)), "loc_28E1") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 3)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_2885") OP_A2(0x3) ChrTalk( 0xFE, ( "孤儿院的孩子们\x01", "好像渐渐恢复精神了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "而且也习惯了这里的生活,\x01", "最近都能够听得到他们的笑声了。\x02", ) ) CloseMessageWindow() Jump("loc_28DE") label("loc_2885") ChrTalk( 0xFE, ( "孤儿院的孩子们\x01", "好像渐渐恢复精神了。\x02", ) ) CloseMessageWindow() label("loc_28DE") Jump("loc_304F") label("loc_28E1") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x85, 0)), scpexpr(EXPR_END)), "loc_2A32") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 3)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_29B9") OP_A2(0x3) ChrTalk( 0xFE, ( "哎呀~『白之木莲亭』的雷克斯\x01", "主动向孤儿院提供房间,\x01", "真是帮了院长和孩子们大忙了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, "这就是患难见真情啊。\x02", ) CloseMessageWindow() ChrTalk( 0xFE, ( "我们也会不惜一切\x01", "来帮助孤儿院的孩子们的。\x02", ) ) CloseMessageWindow() Jump("loc_2A2F") label("loc_29B9") ChrTalk( 0xFE, "这就是患难见真情啊。\x02", ) CloseMessageWindow() ChrTalk( 0xFE, ( "我们也会不惜一切\x01", "来帮助孤儿院的孩子们的。\x02", ) ) CloseMessageWindow() label("loc_2A2F") Jump("loc_304F") label("loc_2A32") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x83, 4)), scpexpr(EXPR_END)), "loc_2C43") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 3)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_2B70") OP_A2(0x3) ChrTalk( 0xFE, ( "昨天晚上,\x01", "可以在这里看到东边的天空\x01", "有红色的火光和冲天的黑烟。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "虽然我马上叫\x01", "村里的年轻人都赶去了,\x01", "但还是没有免除全部烧毁的命运……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "总之,\x01", "孤儿院的老师和孩子们都没有受伤,\x01", "这已经是不幸中的万幸了。\x02", ) ) CloseMessageWindow() Jump("loc_2C40") label("loc_2B70") ChrTalk( 0xFE, ( "昨天晚上,\x01", "可以在这里看到东边的天空\x01", "有红色的火光和冲天的黑烟。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "虽然我马上叫\x01", "村里的年轻人都赶去了,\x01", "但还是没有免除全部烧毁的命运……\x02", ) ) CloseMessageWindow() label("loc_2C40") Jump("loc_304F") label("loc_2C43") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x82, 1)), scpexpr(EXPR_END)), "loc_2DD1") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 3)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_2D2F") OP_A2(0x3) ChrTalk( 0xFE, ( "通往卢安的\x01", "梅威海道被称为\x01", "『风与海的道路』。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "那条街道的景色非常美丽,\x01", "经常有舒服的海风吹过。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "我把去那里散步\x01", "作为我的每日必行之事。\x02", ) ) CloseMessageWindow() Jump("loc_2DCE") label("loc_2D2F") ChrTalk( 0xFE, ( "通往卢安的\x01", "梅威海道被称为\x01", "『风与海的道路』。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "那条街道的景色非常美丽,\x01", "经常有舒服的海风吹过。\x02", ) ) CloseMessageWindow() label("loc_2DCE") Jump("loc_304F") label("loc_2DD1") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x81, 5)), scpexpr(EXPR_END)), "loc_2E8B") ChrTalk( 0xFE, ( "特蕾莎老师有时候\x01", "会带着孤儿院的孩子们\x01", "来玛诺利亚村玩。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "大家都相处得非常好,\x01", "就像亲兄弟姐妹一样。\x02", ) ) CloseMessageWindow() Jump("loc_304F") label("loc_2E8B") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x81, 4)), scpexpr(EXPR_END)), "loc_2EC4") ChrTalk( 0xFE, "男孩子吗?\x02", ) CloseMessageWindow() ChrTalk( 0xFE, "他没有到这里来过哦。\x02", ) CloseMessageWindow() Jump("loc_304F") label("loc_2EC4") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x6B, 6)), scpexpr(EXPR_END)), "loc_304F") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 3)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_2FC6") OP_A2(0x3) ChrTalk( 0xFE, ( "哦,是旅行者啊。\x01", "欢迎来到玛诺利亚村。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "以前,这个村子是\x01", "作为『驿站之村』而繁荣起来的。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "但是,自从定期船开航以来,\x01", "这里过往的行人就明显减少了……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "现在只能勉勉强强\x01", "以『花之村』闻名了。\x02", ) ) CloseMessageWindow() Jump("loc_304F") label("loc_2FC6") ChrTalk( 0xFE, ( "自从定期船开航以来,\x01", "这里过往的行人就明显减少了……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "现在只能勉勉强强\x01", "以『花之村』闻名了。\x02", ) ) CloseMessageWindow() label("loc_304F") TalkEnd(0x16) Return() # Function_6_24F9 end def Function_7_3053(): pass label("Function_7_3053") TalkBegin(0x12) ChrTalk( 0x12, ( "那帮家伙由我看着。\x02\x03", "你们就赶去卢安,\x01", "向嘉恩报告昨天的事情吧。\x02", ) ) CloseMessageWindow() TalkEnd(0x12) Return() # Function_7_3053 end def Function_8_30AE(): pass label("Function_8_30AE") ClearMapFlags(0x1) EventBegin(0x0) OP_6D(-29840, 0, 41310, 0) RemoveParty(0x5, 0xFF) SetChrPos(0x101, -29970, 0, 37680, 0) SetChrPos(0x102, -30850, 0, 37060, 0) SetChrPos(0x105, -29450, 0, 36780, 0) OP_8C(0x12, 180, 0) ChrTalk( 0x12, ( "好了……\x01", "那帮家伙由我看着。\x02", ) ) CloseMessageWindow() ChrTalk( 0x12, ( "你们就赶去卢安,\x01", "向嘉恩报告昨天的事情吧。\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, ( "#000F我们倒是没关系,不过……\x01", "卡露娜姐姐您已经没事了吗?\x02", ) ) CloseMessageWindow() ChrTalk( 0x12, ( "当然啦。只是被人抓住破绽,\x01", "熏了点催眠药而已嘛。\x02", ) ) CloseMessageWindow() ChrTalk( 0x12, ( "还真是丢脸啊。\x01", "竟然被那些家伙钻了空子……\x02", ) ) CloseMessageWindow() ChrTalk( 0x102, ( "#010F这也不能怪您。\x02\x03", "我们也是四人联手\x01", "才勉强击退那些犯人的。\x02", ) ) CloseMessageWindow() ChrTalk( 0x105, ( "#040F那些孩子们平安无事,\x01", "也都多亏了卡露娜小姐啊。\x02\x03", "真是太感谢了。\x02", ) ) CloseMessageWindow() ChrTalk( 0x12, ( "哈哈……\x01", "是啊,总算是不幸中的大幸。\x02", ) ) CloseMessageWindow() ChrTalk( 0x12, ( "我听说阿加特\x01", "自己一个人去追那帮家伙了……\x02", ) ) CloseMessageWindow() ChrTalk( 0x12, ( "虽然他的身手不容置疑,\x01", "但说到底还是有点担心啊。\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, ( "#000F嗯、嗯……\x01", "要是没捉到他们反而受伤的话……\x02", ) ) CloseMessageWindow() ChrTalk( 0x102, ( "#010F现在也唯有相信阿加特先生了。\x02\x03", "从昨天他所说的话判断,\x01", "他好像一直在追那些犯人。\x02\x03", "对于他们的做事手法似乎也很了解,\x01", "我想应该不会那么轻易失手的。\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, ( "#000F嗯……也对呢。\x02\x03", "所以,我们现在也应该\x01", "尽力做好自己能做的事情。\x02", ) ) CloseMessageWindow() ChrTalk( 0x12, "没错,就是这样。\x02", ) CloseMessageWindow() ChrTalk( 0x12, ( "在事情了结之前,\x01", "这些属于特蕾莎院长的捐款\x01", "就先由我来暂代保管吧。\x02", ) ) CloseMessageWindow() ChrTalk( 0x12, ( "这次我一定会保护好的,\x01", "所以你们就安心出发吧。\x02", ) ) CloseMessageWindow() ChrTalk( 0x105, "#040F好的,拜托你了。\x02", ) CloseMessageWindow() OP_8C(0x101, 180, 400) ChrTalk( 0x101, "#000F那么,Let’s go!\x02", ) CloseMessageWindow() EventEnd(0x0) Return() # Function_8_30AE end SaveToFile() Try(main)
#!/usr/bin/python ''' Longest Substring with Same Letters after Replacement Problem Statement # Given a string with lowercase letters only, if you are allowed to replace no more than ‘k’ letters with any letter, find the length of the longest substring having the same letters after replacement. Example 1: Input: String="aabccbb", k=2 Output: 5 Explanation: Replace the two 'c' with 'b' to have a longest repeating substring "bbbbb". Example 2: Input: String="abbcb", k=1 Output: 4 Explanation: Replace the 'c' with 'b' to have a longest repeating substring "bbbb". Example 3: Input: String="abccde", k=1 Output: 3 Explanation: Replace the 'b' or 'd' with 'c' to have the longest repeating substring "ccc". ''' def max_length_substring(str, k): char_freq = {} max_repeat_leter_count = 0 ws = 0 max_len = 0 for we in range(len(str)): rc = str[we] char_freq[rc] = char_freq.get(rc,0) + 1 # at any given point keep track of the max count in the current window max_repeat_leter_count = max(max_repeat_leter_count, char_freq[rc]) #if number of replaceable chrs exceed K shrink the window if (we-ws+1) - max_repeat_leter_count > k: lc = str[ws] ws += 1 char_freq[lc] -= 1 max_len = max(max_len, we-ws+1) return max_len def main(): k = 2 str = "aabccbb" print("Max length of substring of '{0}' after replacement is {1}".format(str,max_length_substring(str,k))) k = 1 str = "abbcb" print("Max length of substring of '{0}' after replacement is {1}".format(str,max_length_substring(str,k))) k = 1 str = "abccde" print("Max length of substring of '{0}' after replacement is {1}".format(str,max_length_substring(str,k))) if __name__ == "__main__": main()
""" This extends the HTMLCalendar class from calendar. All aesthetic adjustments should be made in the mdStyle.css function """ from calendar import HTMLCalendar import datetime # Extending HTMLCalendar class from calendar class mdCalendar(HTMLCalendar): def __init__(self,firstweekday=6): self.firstweekday = firstweekday self.cssclass_today = "today" self.dtToday = datetime.datetime.today().date() def formatMonthMd(self, theyear, themonth, mdList, rrList, customIdDict): v=[] a = v.append a('<table ' 'width="100%%" ' 'cellpadding="0" ' 'cellspacing="0" ' 'class="%s">' % (self.cssclass_month)) a('\n') a(self.formatmonthname(theyear,themonth)) a('\n') a(self.formatweekheader()) a('\n') for week in self.monthdays2calendar(theyear, themonth): a(self.formatweekMd(week,themonth,theyear,mdList,rrList,customIdDict)) a('\n') a('</table>') a('\n') return ''.join(v) def formatweekMd(self,theweek,mo,yr,mdList,rrList,customIdDict): # just passes mdList through s = ''.join(self.formatdayMd(d,wd,mo,yr,mdList,rrList,customIdDict) for (d,wd) in theweek) return '<tr>%s</tr>' % s def formatdayMd(self,day,weekday,mo,yr,mdList,rrList,customIdDict): if day == 0: return '<td class="%s">&nbsp;</td>' % self.cssclass_noday else: thisDay = datetime.date(yr,mo,day) thisDayStr = thisDay.strftime('%Y-%m-%d') if thisDay == self.dtToday: dayCssClass = self.cssclass_today elif thisDay < self.dtToday: dayCssClass = self.cssclasses[weekday] + " crossed" else: dayCssClass = self.cssclasses[weekday] if (thisDayStr in customIdDict) and (customIdDict[thisDayStr] != ""): dayCssClass = dayCssClass + " " + customIdDict[thisDayStr] if thisDayStr in mdList: dayContents = mdList[thisDayStr] else: dayContents = '' if thisDayStr in rrList: dayContents = dayContents + "" + rrList[thisDayStr] return ('<td height="100px" width="14%%" class="%s">%d<br/>'+ dayContents + '</td>') % (dayCssClass,day)
import random import cv2 import gym import numpy as np class MinesweeperEnv(gym.Env): metadata = {'render.modes': ["ansi", "rgb_array", "human"]} reward_range = (-float(1), float(1)) def __init__(self, width=8, height=8, mine_count=10, flood_fill=True, debug=True, punishment=0.01, seed=None, first_move_safe=True): self.first_move_safe = first_move_safe self.width = width self.height = height self.mines_count = mine_count self.debug = debug self.flood_fill = flood_fill self.punishment = punishment self.window = None self.observation_space = gym.spaces.Box(low=np.float32(-2), high=np.float32(8), shape=(self.width, self.height)) self.action_space = gym.spaces.Discrete(self.width * self.height) self.NEIGHBORS = [(-1, -1), (0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1), (1, 1)] self.open_cells = np.zeros((self.width, self.height)) random.seed(a=seed) self.mines = self._generate_mines() self.steps = 0 self.unnecessary_steps = 0 if self.debug: self._assert_invariants() def step(self, action): """ Parameters ---------- action (int) : A z-order zero-based index indicating which cell to dig. If the board is of width 5 and height 2, an action of 0 means the upper left corner, 4 means the upper right corner, 5 is the lower left corner and 9 is the lower right corner. The actual cells that change are determined by standard minesweeper rules, eg. if you open a cell with 0 mines around it, a larger space will be opened. Returns ------- ob, reward, episode_over, info : tuple ob (np.ndarray) : An int array of shape (width, height) with integer values ranging from -2 to 8 where -2 = opened mine -1 = closed cell 0-8 = Amount of mines in the surrounding cells reward (float) : A value between -1 and 1. Increases from 0 to 1 while the game is played based on how many cells have been opened. Pressing on a mine reduces the reward to the range -1 to 0. Playing a perfect game gives a reward of 1. Pressing on an already-opened cell decreases the score by self.punishment (default 0.01). episode_over (bool) : If a mine has been pressed. If reset() is not called, you could theoretically continue playing, but this is not advised. info (dict) : diagnostic information useful for debugging. Includes: opened cells: Amount of opened cells. Affects reward. steps: The amount of steps taken in this episode. unnecessary steps: The amount of steps that had no effect. game over: If a mine has been opened died this turn: If a mine has been opened this turn. mine locations: The location of all the mines. opened cell: The (x, y) coordinates of the cell that was opened this step. Official evaluations of your agent are not allowed to use this for learning. """ first_move = False if self.steps == 0: first_move = True assert self._get_reward() == 0 if self._get_reward() == 0: assert self.steps == 0 self.steps += 1 x, y = self._parse_action(action) self._open_cell(x, y) if first_move and self._game_over() and self.first_move_safe: self.reset() self.step(action) if self.debug and self._game_over(): print("game over") if self.debug: self._assert_invariants() return self._get_state(action) def _get_state(self, action): observation = self._get_observation() reward = self._get_reward() done = self._is_done() info = self._get_info(action) return observation, reward, done, info def reset(self): self.open_cells = np.zeros((self.width, self.height)) self.mines = self._generate_mines() self.steps = 0 self.unnecessary_steps = 0 if self.debug: self._assert_invariants() return self._get_observation() def legal_actions(self): return np.flatnonzero(((self.open_cells - 1) * -1).T) def render(self, mode='human'): if self.debug: self._assert_invariants() if mode == "ansi": row_strings = [] for row in self._get_observation().T: row_string = "" for cell in row: if cell == -1: character = "x" elif cell == 0: character = "." elif cell == -2: character = "B" else: character = str(int(cell)) row_string += character row_strings.append(row_string) return "\n".join(row_strings) elif mode == 'human' and not self.window: from gym_minesweeper.window import Window print("Showing MineSweeper board in own window.\n" "PyCharm users might want to " "disable \"Show plots in tool window\".") self.window = Window('gym_minigrid') self.window.reg_event("button_press_event", self._onclick) self.window.show(block=True) elif mode == 'human': img = [[COLORS[cell] for cell in row] for row in self._get_observation()] self.window.set_caption( "reward:" + str(np.round(self._get_reward(), 4))) self.window.show_img(img) elif mode == "rgb_array": img = [[COLORS[cell] for cell in row] for row in self._get_observation()] img = np.array(img, dtype=np.uint8) zoom = 20 img = cv2.resize(img, dsize=(0, 0), fx=zoom, fy=zoom, interpolation=cv2.INTER_NEAREST) return img else: print("Did not understand rendering mode. Use any of mode=", self.metadata["render.modes"]) def _onclick(self, event): x = round(event.ydata) y = round(event.xdata) current_action = y * self.width + x self.step(current_action) self.render(mode="human") def close(self): if self.window: self.window.close() def _parse_action(self, action): x = action % self.width y = action // self.width return x, y def _open_cell(self, x, y): if self.open_cells[x, y]: self.unnecessary_steps += 1 else: if self.debug: print("opening cell ({},{})".format(x, y)) self.open_cells[x, y] = 1 if self._get_neighbor_mines(x, y) == 0 and self.flood_fill: for dx, dy in self.NEIGHBORS: ix, iy = (dx + x, dy + y) if (0 <= ix <= self.width - 1 and 0 <= iy <= self.height - 1): # self.open_cells[ix, iy] = 1 if (self._get_neighbor_mines(ix, iy) == 0 and not self.open_cells[ix, iy]): self._open_cell(ix, iy) else: self.open_cells[ix, iy] = 1 def _get_reward(self): openable = self.width * self.height - self.mines_count open_cells = np.count_nonzero(self.open_cells) open_mine = self._game_over() punishment = self.unnecessary_steps * self.punishment open_cells_reward = (open_cells - punishment) / openable return open_cells_reward - open_mine - open_mine / openable def _generate_mines(self): mines = np.zeros((self.width, self.height)) print("using seed") mines1d = random.sample(range(self.width * self.height), self.mines_count) for coord in mines1d: x = coord % self.width y = coord // self.width mines[x, y] = 1 return mines def _get_observation(self): self.open_cells observation = np.zeros(self.open_cells.shape) for ix, iy in np.ndindex(self.open_cells.shape): is_open = self.open_cells[ix, iy] is_mine = self.mines[ix, iy] if not is_open: observation[ix, iy] = -1 elif is_open and is_mine: observation[ix, iy] = -2 elif is_open: observation[ix, iy] = self._get_neighbor_mines(ix, iy) return observation def _game_over(self): logical_and = np.logical_and(self.open_cells, self.mines) return np.any(logical_and) def _get_neighbor_mines(self, x, y): mine_count = 0 for dx, dy in self.NEIGHBORS: ix, iy = (dx + x, dy + y) if 0 <= ix <= self.width - 1 and \ 0 <= iy <= self.height - 1 and \ self.mines[ix, iy]: mine_count += 1 return mine_count def _get_info(self, action=None): return { "opened cells": np.count_nonzero(self.open_cells), "steps": self.steps, "unnecessary steps": self.unnecessary_steps, "game over": self._game_over(), "mine locations": self.mines.astype(int), "opened cell": self._parse_action(action) } def _assert_invariants(self): assert self._get_observation().shape == self.observation_space.shape if self._game_over(): assert ( -1 <= self._get_reward() < 0, "Game is over, but score is {}".format(self._get_reward()) ) assert ( np.count_nonzero(np.logical_and(self.open_cells, self.mines)) == 1, "Game is over, but opened cells is {}".format( np.count_nonzero(np.logical_and(self.open_cells, self.mines)) ) ) else: assert ( 0 <= self._get_reward() < 1, "Game is not over, but score is {}".format(self._get_reward())) assert ( np.count_nonzero(np.logical_and(self.open_cells, self.mines)) == 0, "Game is not over, but opened mines: {}".format( np.count_nonzero(np.logical_and(self.open_cells, self.mines)) ) ) assert ( (np.count_nonzero(self.open_cells) == 1 and self._game_over()) == (self._get_reward() == -1), "Game over: {}, mines opened: {}, but score is {}".format( self._game_over(), np.count_nonzero(self.open_cells), self._get_reward() ) ) assert ( (np.count_nonzero(self.open_cells) == self.width * self.height) == (self._get_reward() == 1), "The game is won ({}), and the score should be 1, " "but the score is {}".format( np.count_nonzero(self.open_cells) == self.width * self.height, self._get_reward() ) ) assert ( (np.count_nonzero(self.open_cells) == 0) == (self._get_reward() == 0), "The game has just started, but the reward is not zero. " "reward:{}".format(self._get_reward()) ) def _is_done(self): openable = self.width * self.height - self.mines_count opened = np.count_nonzero(self.open_cells) all_opened = opened == openable return self._game_over() or all_opened COLORS = { -2: [255, 0, 255], -1: [128, 128, 128], 0: [255, 255, 255], 1: [0, 0, 255], 2: [0, 128, 0], 3: [255, 0, 0], 4: [0, 0, 128], 5: [128, 0, 0], 6: [0, 128, 128], 7: [255, 255, 0], 8: [255, 0, 255] }
## need this every time... i think? from unittest import TestCase ## import py file in the directory import area class TestShapeAreas(TestCase): def test_triangle_area(self): # a trianlge with a heaight of 4 and a base of 5 should have an area of 10 self.assertEqual(10, area.triangle_area(4,5))
import matplotlib.image as mpimg import os import sys sys.path.append('H:\programingProject\Python\TextBox\\') from ssd_test import visualization def save_detected_pic(img_dir,rclasses, rscores, rbboxes): img = mpimg.imread(img_dir) visualization.plt_bboxes(img, rclasses, rscores, rbboxes, "./static/result/complete/%s" % (os.path.basename(img_dir).split('.')[0])) visualization.crop_by_bboxes(img, rclasses, rscores, rbboxes, "./static/result/clip/%s" % (os.path.basename(img_dir).split('.')[0])) return "../static/result/complete/%s" % (os.path.basename(img_dir).split('.')[0])
import cv2 import matplotlib.pyplot as plt import matplotlib.patches as patches import os import math import settings import torch from torchvision.transforms import Normalize from torchvision.ops import nms from PIL import ImageDraw, Image import numpy as np from jinja2 import Template from settings import BASE_DIR from utils.data import from_yolo_target, thr_confidence # import pdfkit mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] inv_normalize = Normalize( mean=[-m / s for m, s in zip(mean, std)], std=[1 / s for s in std] ) TEMPLATE_PATH = os.path.join(BASE_DIR, 'utils', 'template.html') def render_report(images_path, title='', report_name=None): if report_name is not None: html_path = os.path.join(os.getcwd(), f'{report_name}.html') pdf_path = os.path.join(os.getcwd(), f'{report_name}.pdf') else: html_path = os.path.join(os.getcwd(), 'report.html') pdf_path = os.path.join(os.getcwd(), 'report.pdf') images = [ os.path.join(images_path, image) for image in os.listdir(images_path) ] context = { 'title': title, 'images': images } with open(TEMPLATE_PATH, 'r') as html: template = Template(html.read()) rendered_template = template.render(context) with open(html_path, 'w') as result_html: result_html.write(rendered_template) pdfkit.from_file(html_path, pdf_path) def show_annotation_by_id(ann_id, coco, path=None): if path is None: path = settings.COCO_TRAIN_PATH ann = coco.loadAnns([ann_id]) image_meta = coco.loadImgs(ann[0]['image_id'])[0] im = cv2.imread(os.path.join(path, image_meta['file_name'])) plt.imshow(im); plt.axis('off') plt.gca() coco.showAnns(ann) plt.show() def show_image_by_id(image_id, coco, show_ann=False, path=None): if path is None: path = settings.COCO_TRAIN_PATH image_meta = coco.loadImgs(image_id)[0] im = cv2.imread(os.path.join(path, image_meta['file_name'])) plt.imshow(im) plt.axis('off') if show_ann: ann_ids = coco.getAnnIds(imgIds=[image_id]) anns = coco.loadAnns(ann_ids) plt.gca() coco.showAnns(anns) plt.show() def vis_bboxes(img, bboxes): if not isinstance(bboxes[0], list) and not isinstance(bboxes[0], tuple): bboxes = [bboxes] fig, ax = plt.subplots() ax.imshow(img) for bbox in bboxes: x, y, w, h = bbox # [x_l, y_t, w, h] -> [x_l, y_b, w, h] (matplotlib считает началом координат левый нижний угол) rect = patches.Rectangle((x, y), w, h, linewidth=1, edgecolor='r', facecolor='none') ax.add_patch(rect) plt.show() def draw_batch(imgs, outputs, targets, show=False): fig = plt.figure(figsize=(14, 14)) axes = [] tile_side = math.ceil(math.sqrt(len(imgs))) for i, (img, output, target) in enumerate(zip(imgs, outputs, targets)): ax = fig.add_subplot(tile_side, tile_side, i + 1) fig, ax = draw_sample(img, output, target, fig=fig, ax=ax) axes.append(ax) if show: plt.show() return fig, axes def draw_sample(img, output, target, fig=None, ax=None, show=False): img_size = img.shape[1:] grid_size = target.shape[:2] pred = torch.sigmoid(output) pred = thr_confidence(pred, 0.5) pred_bboxes = from_yolo_target(pred, img_size, grid_size) target_bboxes = from_yolo_target(target, img_size, grid_size) img = inv_normalize(img) img = img.permute(1, 2, 0).cpu().numpy() img = (img * 255 / np.max(img)).astype('uint8') if fig is None: fig = plt.figure(figsize=(8, 8)) if ax is None: ax = fig.add_subplot(111) ax.imshow(img) for pred_bbox in pred_bboxes: pred_rect = patches.Rectangle((pred_bbox[0], pred_bbox[1]), pred_bbox[2], pred_bbox[3], linewidth=2, edgecolor='g', facecolor='none') ax.add_patch(pred_rect) for target_bbox in target_bboxes: target_rect = patches.Rectangle((target_bbox[0], target_bbox[1]), target_bbox[2], target_bbox[3], linewidth=2, edgecolor='r', facecolor='none') ax.add_patch(target_rect) if show: plt.show() return fig, ax def yet_another_draw_sample(img, output): img_size = img.shape[1:] grid_size = output.shape[:2] pred = torch.sigmoid(output) pred = thr_confidence(pred, 0.5) pred_bboxes = from_yolo_target(pred, img_size, grid_size) # pred_bboxes_inds = nms(boxes=pred_bboxes[..., 1:], scores=pred_bboxes[..., 0]) img = inv_normalize(img) img = img.permute(1, 2, 0).cpu().numpy() img = (img * 255 / np.max(img)).astype('uint8') rects = [] for pred_bbox in pred_bboxes: x, y, w, h = list(map(int, pred_bbox)) shapes = [(x, y), (x + w, y + h)] rects.append(shapes) img_pil = Image.fromarray(img) img_d = ImageDraw.Draw(img_pil) for rect in rects: img_d.rectangle(rect, outline=(255, 0, 0), width=3) img_pil.save('save.png') return img_pil def image_grid(images, titles=None): num_images = images.shape[0] if titles is None: titles = [''] * num_images grid_size = math.ceil(math.sqrt(num_images)) figure = plt.figure(figsize=(14, 14)) for i in range(num_images): plt.subplot(grid_size, grid_size, i + 1, title=titles[i]) plt.xticks([]) plt.yticks([]) plt.grid(False) plt.imshow(images[i]) return figure