file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
cfg_simulator.py
For the categorical model, this limits the upper bound of the learned throttle #it's very IMPORTANT that this value is matched from the training PC config.py and the robot.py #and ideally wouldn't change once set. MODEL_CATEGORICAL_MAX_THROTTLE_RANGE = 0.8 #RNN or 3D SEQUENCE_LENGTH = 3 #some models use a number of images over time. This controls how many. #IMU HAVE_IMU = False #when true, this add a Mpu6050 part and records the data. Can be used with a IMU_SENSOR = 'mpu6050' # (mpu6050|mpu9250) IMU_DLP_CONFIG = 0 # Digital Lowpass Filter setting (0:250Hz, 1:184Hz, 2:92Hz, 3:41Hz, 4:20Hz, 5:10Hz, 6:5Hz) #SOMBRERO HAVE_SOMBRERO = False #set to true when using the sombrero hat from the Donkeycar store. This will enable pwm on the hat. #ROBOHAT MM1 HAVE_ROBOHAT = False # set to true when using the Robo HAT MM1 from Robotics Masters. This will change to RC Control. MM1_STEERING_MID = 1500 # Adjust this value if your car cannot run in a straight line MM1_MAX_FORWARD = 2000 # Max throttle to go fowrward. The bigger the faster MM1_STOPPED_PWM = 1500 MM1_MAX_REVERSE = 1000 # Max throttle to go reverse. The smaller the faster MM1_SHOW_STEERING_VALUE = False # Serial port # -- Default Pi: '/dev/ttyS0' # -- Jetson Nano: '/dev/ttyTHS1' # -- Google coral: '/dev/ttymxc0' # -- Windows: 'COM3', Arduino: '/dev/ttyACM0' # -- MacOS/Linux:please use 'ls /dev/tty.*' to find the correct serial port for mm1 # eg.'/dev/tty.usbmodemXXXXXX' and replace the port accordingly MM1_SERIAL_PORT = '/dev/ttyS0' # Serial Port for reading and sending MM1 data. #RECORD OPTIONS RECORD_DURING_AI = False #normally we do not record during ai mode. Set this to true to get image and steering records for your Ai. Be careful not to use them to train. AUTO_CREATE_NEW_TUB = False #create a new tub (tub_YY_MM_DD) directory when recording or append records to data directory directly #LED HAVE_RGB_LED = False #do you have an RGB LED like https://www.amazon.com/dp/B07BNRZWNF LED_INVERT = False #COMMON ANODE? Some RGB LED use common anode. like https://www.amazon.com/Xia-Fly-Tri-Color-Emitting-Diffused/dp/B07MYJQP8B #LED board pin number for pwm outputs #These are physical pinouts. See: https://www.raspberrypi-spy.co.uk/2012/06/simple-guide-to-the-rpi-gpio-header-and-pins/ LED_PIN_R = 12 LED_PIN_G = 10 LED_PIN_B = 16 #LED status color, 0-100 LED_R = 0 LED_G = 0 LED_B = 1 #LED Color for record count indicator REC_COUNT_ALERT = 1000 #how many records before blinking alert REC_COUNT_ALERT_CYC = 15 #how many cycles of 1/20 of a second to blink per REC_COUNT_ALERT records REC_COUNT_ALERT_BLINK_RATE = 0.4 #how fast to blink the led in seconds on/off #first number is record count, second tuple is color ( r, g, b) (0-100) #when record count exceeds that number, the color will be used RECORD_ALERT_COLOR_ARR = [ (0, (1, 1, 1)), (3000, (5, 5, 5)), (5000, (5, 2, 0)), (10000, (0, 5, 0)), (15000, (0, 5, 5)), (20000, (0, 0, 5)), ] #LED status color, 0-100, for model reloaded alert MODEL_RELOADED_LED_R = 100 MODEL_RELOADED_LED_G = 0 MODEL_RELOADED_LED_B = 0 #BEHAVIORS #When training the Behavioral Neural Network model, make a list of the behaviors, #Set the TRAIN_BEHAVIORS = True, and use the BEHAVIOR_LED_COLORS to give each behavior a color TRAIN_BEHAVIORS = False BEHAVIOR_LIST = ['Left_Lane', "Right_Lane"] BEHAVIOR_LED_COLORS =[ (0, 10, 0), (10, 0, 0) ] #RGB tuples 0-100 per chanel #Localizer #The localizer is a neural network that can learn to predice it's location on the track. #This is an experimental feature that needs more developement. But it can currently be used #to predict the segement of the course, where the course is divided into NUM_LOCATIONS segments. TRAIN_LOCALIZER = False NUM_LOCATIONS = 10 BUTTON_PRESS_NEW_TUB = False #when enabled, makes it easier to divide our data into one tub per track length if we make a new tub on each X button press. #DonkeyGym #Only on Ubuntu linux, you can use the simulator as a virtual donkey and #issue the same python manage.py drive command as usual, but have them control a virtual car. #This enables that, and sets the path to the simualator and the environment. #You will want to download the simulator binary from: https://github.com/tawnkramer/donkey_gym/releases/download/v18.9/DonkeySimLinux.zip #then extract that and modify DONKEY_SIM_PATH. DONKEY_GYM = True DONKEY_SIM_PATH = "path to sim" #"/home/tkramer/projects/sdsandbox/sdsim/build/DonkeySimLinux/donkey_sim.x86_64" when racing on virtual-race-league use "remote", or user "remote" when you want to start the sim manually first. DONKEY_GYM_ENV_NAME = "donkey-generated-track-v0" # ("donkey-generated-track-v0"|"donkey-generated-roads-v0"|"donkey-warehouse-v0"|"donkey-avc-sparkfun-v0") GYM_CONF = { "img_h" : IMAGE_H, "img_w" : IMAGE_W, "body_style" : "donkey", "body_rgb" : (128, 128, 128), "car_name" : "car", "font_size" : 100 } # body style(donkey|bare|car01) body rgb 0-255 GYM_CONF["racer_name"] = "Your Name" GYM_CONF["country"] = "Place" GYM_CONF["bio"] = "I race robots." SIM_HOST = "127.0.0.1" # when racing on virtual-race-league use host "trainmydonkey.com" SIM_ARTIFICIAL_LATENCY = 0 # this is the millisecond latency in controls. Can use useful in emulating the delay when useing a remote server. values of 100 to 400 probably reasonable. #publish camera over network #This is used to create a tcp service to pushlish the camera feed PUB_CAMERA_IMAGES = False #When racing, to give the ai a boost, configure these values. AI_LAUNCH_DURATION = 0.0 # the ai will output throttle for this many seconds AI_LAUNCH_THROTTLE = 0.0 # the ai will output this throttle value AI_LAUNCH_ENABLE_BUTTON = 'R2' # this keypress will enable this boost. It must be enabled before each use to prevent accidental trigger. AI_LAUNCH_KEEP_ENABLED = False # when False ( default) you will need to hit the AI_LAUNCH_ENABLE_BUTTON for each use. This is safest. When this True, is active on each trip into "local" ai mode. #Scale the output of the throttle of the ai pilot for all model types. AI_THROTTLE_MULT = 1.0 # this multiplier will scale every throttle value for all output from NN models
#Path following PATH_FILENAME = "donkey_path.pkl" # the path will be saved to this filename PATH_SCALE = 5.0 # the path display will be scaled by this factor in the web page PATH_OFFSET = (0, 0) # 255, 255 is the center of the map. This offset controls where the origin is displayed. PATH_MIN_DIST = 0.3 # after travelling this distance (m), save a path point
random_line_split
index.js
// console.log(part.itemId, item.stItemInfo); // 反查完成的成就小id let achiReqList = achiReqTable.filter(o => o.fashionId === part.fashionId); // todo 有空的 // todo 保存6464小icon let hash = getHash(`DATA\\IMAGESETS\\ICONS\\ITEMTIPSICON\\${item.szTIPS2D}.TGA`); let fullPath = `${imgSrcPath}${hash}.tga`; if(fs.existsSync(fullPath)) { fs.createReadStream(fullPath).pipe(fs.createWriteStream(`${imgDesPath}${item.szTIPS2D}.tga`)); } else { console.log('文件不存在:', item.szTIPS2D, hash); } partRes[part.fashionId] = { pos: part.position, // 主表 suiyin: part.suiyin, // 主表 weight: part.weight, // 主表 itemId: part.itemId, // 主表 equipData: { name: item.stItemInfo, gender: (item.enumSexDemandArray + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat), menpai: item.JobDemandArray[0], // todo UseCondition 还分门派! // 身份、盟会职务不关键,全部显示 explain: item.szExplain, des: item.szBackground, icon: item.szTIPS2D, // icon是只有男的 todo 不是!男女都有! type: item.ddCatDesc, }, achiId: achiReqList.length === 1 ? achiReqList[0].achievementId : null, // 反查achievement request表,收集了该物品可以达成的成就小Id }; }); // 构造套装表 setTable.forEach(set => { // todo 保存三体型卡片 [set.iconM, set.iconF, set.iconZ, set.cardM, set.cardF, set.cardZ].forEach(filename => { let hash = getHash(`DATA\\IMAGESETS\\ICONS\\FASHION\\${filename}.TGA`); let fullPath = `${imgSrcPath}${hash}.tga`; if(fs.existsSync(fullPath)) { fs.createReadStream(fullPath).pipe(fs.createWriteStream(`${imgDesPath}${filename}.tga`)); } else { console.log('文件不存在:', filename, hash); } }); // 保存数据 setRes[set.setId] = { name: set.setName, idList: (set.idList + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat), origin: set.origin, // 在表最右边 originDes: set.originDes, card: [set.cardM, set.cardF, set.cardZ], weight: set.weight, // 排序权重,最右边 }; }); // 构造魅力值表 achiTable.forEach(achi => { // 通用属性构建 let res = { name: achi.name, //条件名称 originDes: achi.originDes, type: achi.type, // 还有累计成就之类的 typeIcon: achi.typeIcon, // 看需求,就是花花Icon meili: achi.meili, logic: achi.logic ? 'or' : 'and', // 成就条件逻辑,and或者or,全部完成还是一个就行 }; // 特殊属性构建 if(achi.name.startsWith('万色')) { // 普通染色魅力值 // 强行找出对应套装 todo let setName = achi.originDes.split(':')[0]; let set = setTable.filter(o => (o.setName + '').includes(setName))[0]; // todo shuzi id let base = parseInt(achi.originDes.match(/基础(\d*)/)[1]); let advance; let matchRes = achi.originDes.match(/进阶(\d*)/); if(matchRes) advance = matchRes[1]; else advance = null; res = { ...res, // 特殊判定 setId: set.setId, // 用于显示 partList: (set.idList + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat), // 需要达成的部位,直接遍历这个表的posList检查是否符合就行,构造时查set表拿id // 满足特殊属性 isSpecial: false, base: base, // 基础染色的值,根据字符串识别 todo advance: advance, specialType: null, }; // 保存 dyeRes[achi.achievementId] = res; } else if(achi.name.startsWith('一染')) { // 定制染色魅力值 // 强行找出对应套装 todo let setName = achi.originDes.split(':')[0]; let set = setTable.filter(o => (o.setName + '').includes(setName))[0]; // todo shuzi id let type = achi.originDes.match(/点染·(.*)/)[1]; res = { ...res, // 特殊判定 setId: set.setId, // 用于显示 partList: (set.idList + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat), // 需要达成的部位,直接遍历这个表的posList检查是否符合就行,构造时查set表拿id // 满足特殊属性 isSpecial: true, base: null, advance: null, specialType: type, }; // 保存 dyeRes[achi.achievementId] = res; } else if(achi.name.startsWith('丰彩染料累计')) { res = { ...res, // 特殊判定 item: '丰彩', // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白的原名 // 满足特殊属性 count: achi.count, // 程序里特殊逻辑处理 }; dyesumRes[achi.achievementId] = res; } else if(achi.name.startsWith('瑶光颜料累计')) { res = { ...res, // 特殊判定 item: '瑶光', // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白的原名 // 满足特殊属性 count: achi.count, // 程序里特殊逻辑处理 }; dyesumRes[achi.achievementId] = res; } else if(achi.name.startsWith('点染')) { let item; if(achi.name.includes('蓝瓷')) item = '蓝瓷'; else if(achi.name.includes('竹青')) item = '蓝瓷'; else if(achi.name.includes('红烬')) item = '红烬'; else if(achi.name.includes('金莹')) item = '金莹'; else if(achi.name.includes('雪练')) item = '雪练'; else if(achi.name.includes('玄夜')) item = '玄夜'; res = { ...res, // 特殊判定 item: item, // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白的原名 // 满足特殊属性 count: achi.count, // 程序里特殊逻辑处理 }; dyesumRes[achi.achievementId] = res; } else { // 普通收集类型 // 从aId1 到aId12 let idList = []; for (let i = 1; i < 12; i++) { if(achi['aId' + i] > 0) { idList.push(achi['aId' + i]); } } res = { ...res, // 通用成就完成表 achiIdList: idList, // 需求Id }; glamourRes[achi.achievementId] = res; } }); console.log('1'); // 写入文件 fs.writeFileSync('./
data[1]; itemTable = data[2]; achiReqTable = data[3]; achiTable = data[4]; // 新增坐骑 itemTable = itemTable.concat(data[5]); // todo 是否可以染色 let partRes = {}; let setRes = {}; let glamourRes = {}; let dyeRes = {}; let dyesumRes = {}; // 以主表开始遍历 fashionTable.forEach(part => { // 查item表提数据 let item = itemTable.filter(o => o.iId === part.itemId)[0];
identifier_body
index.js
Table = data[1]; itemTable = data[2]; achiReqTable = data[3]; achiTable = data[4]; // 新增坐骑 itemTable = itemTable.concat(data[5]); // todo 是否可以染色 let partRes = {}; let setRes = {}; let glamourRes = {}; let dyeRes = {}; let dyesumRes = {}; // 以主表开始遍历 fashionTable.forEach(part => { // 查item表提数据 let item = itemTable.filter(o => o.iId === part.itemId)[0]; // console.log(part.itemId, item.stItemInfo); // 反查完成的成就小id let achiReqList = achiReqTable.filter(o => o.fashionId === part.fashionId); // todo 有空的 // todo 保存6464小icon let hash = getHash(`DATA\\IMAGESETS\\ICONS\\ITEMTIPSICON\\${item.szTIPS2D}.TGA`); let fullPath = `${imgSrcPath}${hash}.tga`; if(fs.existsSync(fullPath)) { fs.createReadStream(fullPath).pipe(fs.createWriteStream(`${imgDesPath}${item.szTIPS2D}.tga`)); } else { console.log('文件不存在:', item.szTIPS2D, hash); } partRes[part.fashionId] = { pos: part.position, // 主表 suiyin: part.suiyin, // 主表 weight: part.weight, // 主表 itemId: part.itemId, // 主表 equipData: { name: item.stItemInfo, gender: (item.enumSexDemandArray + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat), menpai: item.JobDemandArray[0], // todo UseCondition 还分门派! // 身份、盟会职务不关键,全部显示 explain: item.szExplain, des: item.szBackground, icon: item.szTIPS2D, // icon是只有男的 todo 不是!男女都有! type: item.ddCatDesc, }, achiId: achiReqList.length === 1 ? achiReqList[0].achievementId : null, // 反查achievement request表,收集了该物品可以达成的成就小Id }; }); // 构造套装表 setTable.forEach(set => { // todo 保存三体型卡片 [set.iconM, set.iconF, set.iconZ, set.cardM, set.cardF, set.cardZ].forEach(filename => { let hash = getHash(`DATA\\IMAGESETS\\ICONS\\FASHION\\${filename}.TGA`); let fullPath = `${imgSrcPath}${hash}.tga`; if(fs.existsSync(fullPath)) { fs.createReadStream(fullPath).pipe(fs.createWriteStream(`${imgDesPath}${filename}.tga`)); } else { console.log('文件不存在:', filename, hash); } }); // 保存数据 setRes[set.setId] = { name: set.setName, idList: (set.idList + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat), origin: set.origin, // 在表最右边 originDes: set.originDes, card: [set.cardM, set.cardF, set.cardZ], weight: set.weight, // 排序权重,最右边 }; }); // 构造魅力值表 achiTable.forEach(achi => { // 通用属性构建 let res = { name: achi.name, //条件名称 originDes: achi.originDes, type: achi.type, // 还有累计成就之类的 typeIcon: achi.typeIcon, // 看需求,就是花花Icon meili: achi.meili, logic: achi.logic ? 'or' : 'and', // 成就条件逻辑,and或者or,全部完成还是一个就行 }; // 特殊属性构建 if(achi.name.startsWith('万色')) { // 普通染色魅力值 // 强行找出对应套装 todo let setName = achi.originDes.split(':')[0]; let set = setTable.filter(o => (o.setName + '').includes(setName))[0]; // todo shuzi id let base = parseInt(achi.originDes.match(/基础(\d*)/)[1]); let advance; let matchRes = achi.originDes.match(/进阶(\d*)/); if(matchRes) advance = matchRes[1]; else advance = null; res = { ...res, // 特殊判定 setId: set.setId, // 用于显示 partList: (set.idList + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat), // 需要达成的部位,直接遍历这个表的posList检查是否符合就行,构造时查set表拿id // 满足特殊属性 isSpecial: false, base: base, // 基础染色的值,根据字符串识别 todo advance: advance, specialType: null, }; // 保存 dyeRes[achi.achievementId] = res; } else if(achi.name.startsWith('一染')) { // 定制染色魅力值 // 强行找出对应套装 todo let setName = achi.originDes.split(':')[0]; let set = setTable.filter(o => (o.setName + '').includes(setName))[0]; // todo shuzi id let type = achi.originDes.match(/点染·(.*)/)[1]; res = { ...res, // 特殊判定 setId: set.setId, // 用于显示 partList: (set.idList + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat), // 需要达成的部位,直接遍历这个表的posList检查是否符合就行,构造时查set表拿id // 满足特殊属性 isSpecial: true, base: null, advance: null, specialType: type, }; // 保存 dyeRes[achi.achievementId] = res; } else if(achi.name.startsWith('丰彩染料累计')) { res = { ...res, // 特殊判定 item: '丰彩', // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白的原名 // 满足特殊属性 count: achi.count, // 程序里特殊逻辑处理 }; dyesumRes[achi.achievementId] = res; } else if(achi.name.startsWith('瑶光颜料累计')) { res = { ...res, // 特殊判定 item: '瑶光', // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白的原名 // 满足特殊属性 count: achi.count, // 程序里特殊逻辑处理 }; dyesumRes[achi.achievementId] = res; } else if(achi.name.startsWith('点染')) { let item; if(achi.name.includes('蓝瓷')) item = '蓝瓷'; else if(achi.name.includes('竹青')) item = '蓝瓷'; else if(achi.name.includes('红烬')) item = '红烬'; else if(achi.name.includes('金莹')) item = '金莹'; else if(achi.name.includes('雪练')) item = '雪练'; else if(achi.name.includes('玄夜')) item = '玄夜'; res = { ...res, // 特殊判定 item: item, // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白的原名 // 满足特殊属性 count: achi.count, // 程序里特殊逻辑处理 }; dyesumRes[achi.achievementId] = res; } else { // 普通收集类型 // 从aId1 到aId12 let idList = []; for (let i = 1; i < 12; i++) { if(achi['aId' + i] > 0) { idList.push(achi['aId' + i]); } } res = { ...res, // 通用成就完成表 achiIdList: idList, // 需求Id }; glamourRes[achi.achievementId] = res; } }); console.log('1'); // 写入文件
set
identifier_name
index.js
] = { pos: part.position, // 主表 suiyin: part.suiyin, // 主表 weight: part.weight, // 主表 itemId: part.itemId, // 主表 equipData: { name: item.stItemInfo, gender: (item.enumSexDemandArray + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat), menpai: item.JobDemandArray[0], // todo UseCondition 还分门派! // 身份、盟会职务不关键,全部显示 explain: item.szExplain, des: item.szBackground, icon: item.szTIPS2D, // icon是只有男的 todo 不是!男女都有! type: item.ddCatDesc, }, achiId: achiReqList.length === 1 ? achiReqList[0].achievementId : null, // 反查achievement request表,收集了该物品可以达成的成就小Id }; });
// 构造套装表 setTable.forEach(set => { // todo 保存三体型卡片 [set.iconM, set.iconF, set.iconZ, set.cardM, set.cardF, set.cardZ].forEach(filename => { let hash = getHash(`DATA\\IMAGESETS\\ICONS\\FASHION\\${filename}.TGA`); let fullPath = `${imgSrcPath}${hash}.tga`; if(fs.existsSync(fullPath)) { fs.createReadStream(fullPath).pipe(fs.createWriteStream(`${imgDesPath}${filename}.tga`)); } else { console.log('文件不存在:', filename, hash); } }); // 保存数据 setRes[set.setId] = { name: set.setName, idList: (set.idList + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat), origin: set.origin, // 在表最右边 originDes: set.originDes, card: [set.cardM, set.cardF, set.cardZ], weight: set.weight, // 排序权重,最右边 }; }); // 构造魅力值表 achiTable.forEach(achi => { // 通用属性构建 let res = { name: achi.name, //条件名称 originDes: achi.originDes, type: achi.type, // 还有累计成就之类的 typeIcon: achi.typeIcon, // 看需求,就是花花Icon meili: achi.meili, logic: achi.logic ? 'or' : 'and', // 成就条件逻辑,and或者or,全部完成还是一个就行 }; // 特殊属性构建 if(achi.name.startsWith('万色')) { // 普通染色魅力值 // 强行找出对应套装 todo let setName = achi.originDes.split(':')[0]; let set = setTable.filter(o => (o.setName + '').includes(setName))[0]; // todo shuzi id let base = parseInt(achi.originDes.match(/基础(\d*)/)[1]); let advance; let matchRes = achi.originDes.match(/进阶(\d*)/); if(matchRes) advance = matchRes[1]; else advance = null; res = { ...res, // 特殊判定 setId: set.setId, // 用于显示 partList: (set.idList + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat), // 需要达成的部位,直接遍历这个表的posList检查是否符合就行,构造时查set表拿id // 满足特殊属性 isSpecial: false, base: base, // 基础染色的值,根据字符串识别 todo advance: advance, specialType: null, }; // 保存 dyeRes[achi.achievementId] = res; } else if(achi.name.startsWith('一染')) { // 定制染色魅力值 // 强行找出对应套装 todo let setName = achi.originDes.split(':')[0]; let set = setTable.filter(o => (o.setName + '').includes(setName))[0]; // todo shuzi id let type = achi.originDes.match(/点染·(.*)/)[1]; res = { ...res, // 特殊判定 setId: set.setId, // 用于显示 partList: (set.idList + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat), // 需要达成的部位,直接遍历这个表的posList检查是否符合就行,构造时查set表拿id // 满足特殊属性 isSpecial: true, base: null, advance: null, specialType: type, }; // 保存 dyeRes[achi.achievementId] = res; } else if(achi.name.startsWith('丰彩染料累计')) { res = { ...res, // 特殊判定 item: '丰彩', // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白的原名 // 满足特殊属性 count: achi.count, // 程序里特殊逻辑处理 }; dyesumRes[achi.achievementId] = res; } else if(achi.name.startsWith('瑶光颜料累计')) { res = { ...res, // 特殊判定 item: '瑶光', // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白的原名 // 满足特殊属性 count: achi.count, // 程序里特殊逻辑处理 }; dyesumRes[achi.achievementId] = res; } else if(achi.name.startsWith('点染')) { let item; if(achi.name.includes('蓝瓷')) item = '蓝瓷'; else if(achi.name.includes('竹青')) item = '蓝瓷'; else if(achi.name.includes('红烬')) item = '红烬'; else if(achi.name.includes('金莹')) item = '金莹'; else if(achi.name.includes('雪练')) item = '雪练'; else if(achi.name.includes('玄夜')) item = '玄夜'; res = { ...res, // 特殊判定 item: item, // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白的原名 // 满足特殊属性 count: achi.count, // 程序里特殊逻辑处理 }; dyesumRes[achi.achievementId] = res; } else { // 普通收集类型 // 从aId1 到aId12 let idList = []; for (let i = 1; i < 12; i++) { if(achi['aId' + i] > 0) { idList.push(achi['aId' + i]); } } res = { ...res, // 通用成就完成表 achiIdList: idList, // 需求Id }; glamourRes[achi.achievementId] = res; } }); console.log('1'); // 写入文件 fs.writeFileSync('./output/part.json', JSON.stringify(partRes, null, 4)); fs.writeFileSync('./output/set.json', JSON.stringify(setRes, null, 4)); fs.writeFileSync('./output/common_glamour.json', JSON.stringify(glamourRes, null, 4)); fs.writeFileSync('./output/dye.json', JSON.stringify(dyeRes, null, 4)); fs.writeFileSync('./output/dye_sum.json', JSON.stringify(dyesumRes, null, 4)); } /************************************/ /***************数据分析**************/ /************************************/ // 全部散件(Fashion主表) let exampleParts = { 4037: { // 心王影冠Fashion id pos: 'head', // 主表 suiyin: 0, // 主表 weight: 2227, // 主表 itemId: 6100920, // 主表 equipData: { name: '心王·影冠', gender: [true, true, true], menpai: -1, // 身份、盟会职务不关键,全部显示 explain: '使用后获得“心王·影冠”外装外形', des: '露凝香,玉笼烟。\\n谁共我,醉明月?', icon: 'ICON_60_equip_Head_M_M_TY_3103', // icon是
random_line_split
index.js
还分门派! // 身份、盟会职务不关键,全部显示 explain: item.szExplain, des: item.szBackground, icon: item.szTIPS2D, // icon是只有男的 todo 不是!男女都有! type: item.ddCatDesc, }, achiId: achiReqList.length === 1 ? achiReqList[0].achievementId : null, // 反查achievement request表,收集了该物品可以达成的成就小Id }; }); // 构造套装表 setTable.forEach(set => { // todo 保存三体型卡片 [set.iconM, set.iconF, set.iconZ, set.cardM, set.cardF, set.cardZ].forEach(filename => { let hash = getHash(`DATA\\IMAGESETS\\ICONS\\FASHION\\${filename}.TGA`); let fullPath = `${imgSrcPath}${hash}.tga`; if(fs.existsSync(fullPath)) { fs.createReadStream(fullPath).pipe(fs.createWriteStream(`${imgDesPath}${filename}.tga`)); } else { console.log('文件不存在:', filename, hash); } }); // 保存数据 setRes[set.setId] = { name: set.setName, idList: (set.idList + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat), origin: set.origin, // 在表最右边 originDes: set.originDes, card: [set.cardM, set.cardF, set.cardZ], weight: set.weight, // 排序权重,最右边 }; }); // 构造魅力值表 achiTable.forEach(achi => { // 通用属性构建 let res = { name: achi.name, //条件名称 originDes: achi.originDes, type: achi.type, // 还有累计成就之类的 typeIcon: achi.typeIcon, // 看需求,就是花花Icon meili: achi.meili, logic: achi.logic ? 'or' : 'and', // 成就条件逻辑,and或者or,全部完成还是一个就行 }; // 特殊属性构建 if(achi.name.startsWith('万色')) { // 普通染色魅力值 // 强行找出对应套装 todo let setName = achi.originDes.split(':')[0]; let set = setTable.filter(o => (o.setName + '').includes(setName))[0]; // todo shuzi id let base = parseInt(achi.originDes.match(/基础(\d*)/)[1]); let advance; let matchRes = achi.originDes.match(/进阶(\d*)/); if(matchRes) advance = matchRes[1]; else advance = null; res = { ...res, // 特殊判定 setId: set.setId, // 用于显示 partList: (set.idList + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat), // 需要达成的部位,直接遍历这个表的posList检查是否符合就行,构造时查set表拿id // 满足特殊属性 isSpecial: false, base: base, // 基础染色的值,根据字符串识别 todo advance: advance, specialType: null, }; // 保存 dyeRes[achi.achievementId] = res; } else if(achi.name.startsWith('一染')) { // 定制染色魅力值 // 强行找出对应套装 todo let setName = achi.originDes.split(':')[0]; let set = setTable.filter(o => (o.setName + '').includes(setName))[0]; // todo shuzi id let type = achi.originDes.match(/点染·(.*)/)[1]; res = { ...res, // 特殊判定 setId: set.setId, // 用于显示 partList: (set.idList + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat), // 需要达成的部位,直接遍历这个表的posList检查是否符合就行,构造时查set表拿id // 满足特殊属性 isSpecial: true, base: null, advance: null, specialType: type, }; // 保存 dyeRes[achi.achievementId] = res; } else if(achi.name.startsWith('丰彩染料累计')) { res = { ...res, // 特殊判定 item: '丰彩', // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白的原名 // 满足特殊属性 count: achi.count, // 程序里特殊逻辑处理 }; dyesumRes[achi.achievementId] = res; } else if(achi.name.startsWith('瑶光颜料累计')) { res = { ...res, // 特殊判定 item: '瑶光', // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白的原名 // 满足特殊属性 count: achi.count, // 程序里特殊逻辑处理 }; dyesumRes[achi.achievementId] = res; } else if(achi.name.startsWith('点染')) { let item; if(achi.name.includes('蓝瓷')) item = '蓝瓷'; else if(achi.name.includes('竹青')) item = '蓝瓷'; else if(achi.name.includes('红烬')) item = '红烬'; else if(achi.name.includes('金莹')) item = '金莹'; else if(achi.name.includes('雪练')) item = '雪练'; else if(achi.name.includes('玄夜')) item = '玄夜'; res = { ...res, // 特殊判定 item: item, // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白的原名 // 满足特殊属性 count: achi.count, // 程序里特殊逻辑处理 }; dyesumRes[achi.achievementId] = res; } else { // 普通收集类型 // 从aId1 到aId12 let idList = []; for (let i = 1; i < 12; i++) { if(achi['aId' + i] > 0) { idList.push(achi['aId' + i]); } } res = { ...res, // 通用成就完成表 achiIdList: idList, // 需求Id }; glamourRes[achi.achievementId] = res; } }); console.log('1'); // 写入文件 fs.writeFileSync('./output/part.json', JSON.stringify(partRes, null, 4)); fs.writeFileSync('./output/set.json', JSON.stringify(setRes, null, 4)); fs.writeFileSync('./output/common_glamour.json', JSON.stringify(glamourRes, null, 4)); fs.writeFileSync('./output/dye.json', JSON.stringify(dyeRes, null, 4)); fs.writeFileSync('./output/dye_sum.json', JSON.stringify(dyesumRes, null, 4)); } /************************************/ /***************数据分析**************/ /************************************/ // 全部散件(Fashion主表) let exampleParts = { 4037: { // 心王影冠Fashion id pos: 'head', // 主表 suiyin: 0, // 主表 weight: 2227, // 主表 itemId: 6100920, // 主表 equipData: { name: '心王·影冠', gender: [true, true, true],
menpai: -1, // 身份、盟会职务不关键,全部显示 explain: '使用后获得“心王·影冠”外装外形', des: '露凝香,玉笼烟。\\n谁共我,醉明月?', icon: 'ICON_60_equip_Head_M_M_TY_3103', // icon是只有男的 type: '外装', }, achiId: 24749, // 反查achievement request表,收集了该物品可以达成的成就小Id } }; // 全部套装 let exampleSets = { 328: { // 心王影套装id name: 'setName', idList: [4037, 4038, 4039, 4040],
conditional_block
main.rs
device.get_device_queue(queue_family_index, 0) }; let mut events_loop = winit::EventsLoop::new(); let window = winit::WindowBuilder::new() .with_title("Ash - Example") .with_dimensions(winit::dpi::LogicalSize { width: WIDTH, height: HEIGHT, }) .build(&events_loop) .unwrap(); let (swapchain_loader, swapchain) = unsafe { create_swapchain(&entry, &instance, &window, physical_device, &device).unwrap() }; let present_images = unsafe { get_present_images(&swapchain_loader, swapchain).unwrap() }; let present_complete_semaphore = unsafe { create_semaphore(&device).unwrap() }; let rendering_complete_semaphore = unsafe { create_semaphore(&device).unwrap() }; let mut closed = false; while !closed { events_loop.poll_events(|event| match event { winit::Event::WindowEvent { event, .. } => match event { winit::WindowEvent::CloseRequested => closed = true, _ => {} }, _ => {} }); let present_index = unsafe { swapchain_loader .acquire_next_image_khr( swapchain, std::u64::MAX, present_complete_semaphore, vk::Fence::null(), ) .unwrap() }; let present_info = vk::PresentInfoKHR { s_type: vk::StructureType::PresentInfoKhr, p_next: ptr::null(), wait_semaphore_count: 0, // p_wait_semaphores: &rendering_complete_semaphore, p_wait_semaphores: ptr::null(), swapchain_count: 1, p_swapchains: &swapchain, p_image_indices: &present_index, p_results: ptr::null_mut(), }; unsafe { swapchain_loader .queue_present_khr(present_queue, &present_info) .unwrap(); } } } fn create_entry() -> Entry<V1_0> { Entry::new().unwrap() } fn create_instance(entry: &Entry<V1_0>) -> Instance<V1_0> { let app_name = CString::new("Niagara-rs").unwrap(); let raw_name = app_name.as_ptr(); let appinfo = vk::ApplicationInfo { s_type: vk::StructureType::ApplicationInfo, api_version: vk_make_version!(1, 0, 36), p_application_name: raw_name, p_engine_name: raw_name, application_version: 0, engine_version: 0, p_next: ptr::null(), }; let layer_names = [CString::new("VK_LAYER_LUNARG_standard_validation").unwrap()]; let layers_names_raw: Vec<*const i8> = layer_names .iter() .map(|raw_name| raw_name.as_ptr()) .collect(); let extension_names_raw = extension_names(); let create_info = vk::InstanceCreateInfo { s_type: vk::StructureType::InstanceCreateInfo, p_next: ptr::null(), flags: Default::default(), p_application_info: &appinfo, pp_enabled_layer_names: layers_names_raw.as_ptr(), enabled_layer_count: layers_names_raw.len() as u32, pp_enabled_extension_names: extension_names_raw.as_ptr(), enabled_extension_count: extension_names_raw.len() as u32, }; unsafe { let instance = entry .create_instance(&create_info, None) .expect("Instance creation error"); let debug_info = vk::DebugReportCallbackCreateInfoEXT { s_type: vk::StructureType::DebugReportCallbackCreateInfoExt, p_next: ptr::null(), flags: vk::DEBUG_REPORT_ERROR_BIT_EXT | vk::DEBUG_REPORT_WARNING_BIT_EXT | vk::DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, pfn_callback: vulkan_debug_callback, p_user_data: ptr::null_mut(), }; let debug_report_loader = DebugReport::new(entry, &instance).expect("Unable to load debug report"); let _debug_call_back = debug_report_loader .create_debug_report_callback_ext(&debug_info, None) .unwrap(); return instance; } } fn pick_physical_device(instance: &Instance<V1_0>) -> vk::PhysicalDevice { let physical_devices = instance .enumerate_physical_devices() .expect("Physical device error"); if physical_devices.len() == 0 { panic!("No GPU found!"); } let physical_device = physical_devices .iter() .max_by_key(|physical_device| { let props = instance.get_physical_device_properties(**physical_device); match props.device_type { vk::PhysicalDeviceType::DiscreteGpu => 2, vk::PhysicalDeviceType::IntegratedGpu => 1, _ => 0, } }) .expect("No suitable device found!"); return *physical_device; } #[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))] fn extension_names() -> Vec<*const i8> { vec![ Surface::name().as_ptr(), XlibSurface::name().as_ptr(), DebugReport::name().as_ptr(), ] } fn create_device(instance: &Instance<V1_0>, physical_device: &vk::PhysicalDevice) -> Device<V1_0> { let queue_family_index = 0 as u32; let priorities = [1.0]; let queue_info = vk::types::DeviceQueueCreateInfo { s_type: vk::StructureType::DeviceQueueCreateInfo, p_next: ptr::null(), flags: Default::default(), queue_family_index: queue_family_index as u32, p_queue_priorities: priorities.as_ptr(), queue_count: priorities.len() as u32, }; let device_extension_names_raw = [Swapchain::name().as_ptr()]; let features = vk::PhysicalDeviceFeatures { shader_clip_distance: 1, ..Default::default() }; let device_create_info = vk::DeviceCreateInfo { s_type: vk::StructureType::DeviceCreateInfo, p_next: ptr::null(), flags: Default::default(), p_queue_create_infos: &queue_info, queue_create_info_count: 1, pp_enabled_layer_names: ptr::null(), enabled_layer_count: 0, pp_enabled_extension_names: device_extension_names_raw.as_ptr(), enabled_extension_count: device_extension_names_raw.len() as u32, p_enabled_features: &features, }; unsafe { let device: Device<V1_0> = instance .create_device(*physical_device, &device_create_info, None) .unwrap(); return device; } } #[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))] unsafe fn create_surface<E: EntryV1_0, I: InstanceV1_0>( entry: &E, instance: &I, window: &winit::Window, ) -> Result<vk::SurfaceKHR, vk::Result> { use winit::os::unix::WindowExt; let x11_display = window.get_xlib_display().unwrap(); let x11_window = window.get_xlib_window().unwrap(); let x11_create_info = vk::XlibSurfaceCreateInfoKHR { s_type: vk::StructureType::XlibSurfaceCreateInfoKhr, p_next: ptr::null(), flags: Default::default(), window: x11_window as vk::Window, dpy: x11_display as *mut vk::Display, }; let xlib_surface_loader = XlibSurface::new(entry, instance).expect("Unable to load xlib surface"); xlib_surface_loader.create_xlib_surface_khr(&x11_create_info, None) } unsafe fn
( entry: &Entry<V1_0>, instance: &Instance<V1_0>, window: &winit::Window, physical_device: PhysicalDevice, device: &Device<V1_0>, ) -> Result<(Swapchain, SwapchainKHR), vk::Result> { let surface = create_surface(entry, instance, window).unwrap(); let surface_loader = Surface::new(entry, instance).expect("Unable to load the Surface extension"); let surface_formats = surface_loader .get_physical_device_surface_formats_khr(physical_device, surface) .unwrap(); let surface_format = surface_formats .iter() .map(|sfmt| match sfmt.format { vk::Format::Undefined => vk::SurfaceFormatKHR { format: vk::Format::B8g8r8Unorm, color_space: sfmt.color_space, }, _ => sfmt.clone(), }) .nth(0) .expect("Unable to find suitable surface format."); let surface_capabilities = surface_loader .get_physical_device_surface_capabilities_khr(physical_device, surface) .unwrap(); let mut desired_image_count = surface_capabilities.min_image_count + 1; if surface_capabilities.max_image_count > 0 && desired_image_count > surface_capabilities.max_image_count { desired_image_count = surface_capabilities.max_image_count; } let surface_resolution = match surface_capabilities.current_extent.width { std::u32::MAX => vk::Extent2D { width: WIDTH as u32, height: HEIGHT
create_swapchain
identifier_name
main.rs
app_name = CString::new("Niagara-rs").unwrap(); let raw_name = app_name.as_ptr(); let appinfo = vk::ApplicationInfo { s_type: vk::StructureType::ApplicationInfo, api_version: vk_make_version!(1, 0, 36), p_application_name: raw_name, p_engine_name: raw_name, application_version: 0, engine_version: 0, p_next: ptr::null(), }; let layer_names = [CString::new("VK_LAYER_LUNARG_standard_validation").unwrap()]; let layers_names_raw: Vec<*const i8> = layer_names .iter() .map(|raw_name| raw_name.as_ptr()) .collect(); let extension_names_raw = extension_names(); let create_info = vk::InstanceCreateInfo { s_type: vk::StructureType::InstanceCreateInfo, p_next: ptr::null(), flags: Default::default(), p_application_info: &appinfo, pp_enabled_layer_names: layers_names_raw.as_ptr(), enabled_layer_count: layers_names_raw.len() as u32, pp_enabled_extension_names: extension_names_raw.as_ptr(), enabled_extension_count: extension_names_raw.len() as u32, }; unsafe { let instance = entry .create_instance(&create_info, None) .expect("Instance creation error"); let debug_info = vk::DebugReportCallbackCreateInfoEXT { s_type: vk::StructureType::DebugReportCallbackCreateInfoExt, p_next: ptr::null(), flags: vk::DEBUG_REPORT_ERROR_BIT_EXT | vk::DEBUG_REPORT_WARNING_BIT_EXT | vk::DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, pfn_callback: vulkan_debug_callback, p_user_data: ptr::null_mut(), }; let debug_report_loader = DebugReport::new(entry, &instance).expect("Unable to load debug report"); let _debug_call_back = debug_report_loader .create_debug_report_callback_ext(&debug_info, None) .unwrap(); return instance; } } fn pick_physical_device(instance: &Instance<V1_0>) -> vk::PhysicalDevice { let physical_devices = instance .enumerate_physical_devices() .expect("Physical device error"); if physical_devices.len() == 0 { panic!("No GPU found!"); } let physical_device = physical_devices .iter() .max_by_key(|physical_device| { let props = instance.get_physical_device_properties(**physical_device); match props.device_type { vk::PhysicalDeviceType::DiscreteGpu => 2, vk::PhysicalDeviceType::IntegratedGpu => 1, _ => 0, } }) .expect("No suitable device found!"); return *physical_device; } #[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))] fn extension_names() -> Vec<*const i8> { vec![ Surface::name().as_ptr(), XlibSurface::name().as_ptr(), DebugReport::name().as_ptr(), ] } fn create_device(instance: &Instance<V1_0>, physical_device: &vk::PhysicalDevice) -> Device<V1_0> { let queue_family_index = 0 as u32; let priorities = [1.0]; let queue_info = vk::types::DeviceQueueCreateInfo { s_type: vk::StructureType::DeviceQueueCreateInfo, p_next: ptr::null(), flags: Default::default(), queue_family_index: queue_family_index as u32, p_queue_priorities: priorities.as_ptr(), queue_count: priorities.len() as u32, }; let device_extension_names_raw = [Swapchain::name().as_ptr()]; let features = vk::PhysicalDeviceFeatures { shader_clip_distance: 1, ..Default::default() }; let device_create_info = vk::DeviceCreateInfo { s_type: vk::StructureType::DeviceCreateInfo, p_next: ptr::null(), flags: Default::default(), p_queue_create_infos: &queue_info, queue_create_info_count: 1, pp_enabled_layer_names: ptr::null(), enabled_layer_count: 0, pp_enabled_extension_names: device_extension_names_raw.as_ptr(), enabled_extension_count: device_extension_names_raw.len() as u32, p_enabled_features: &features, }; unsafe { let device: Device<V1_0> = instance .create_device(*physical_device, &device_create_info, None) .unwrap(); return device; } } #[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))] unsafe fn create_surface<E: EntryV1_0, I: InstanceV1_0>( entry: &E, instance: &I, window: &winit::Window, ) -> Result<vk::SurfaceKHR, vk::Result> { use winit::os::unix::WindowExt; let x11_display = window.get_xlib_display().unwrap(); let x11_window = window.get_xlib_window().unwrap(); let x11_create_info = vk::XlibSurfaceCreateInfoKHR { s_type: vk::StructureType::XlibSurfaceCreateInfoKhr, p_next: ptr::null(), flags: Default::default(), window: x11_window as vk::Window, dpy: x11_display as *mut vk::Display, }; let xlib_surface_loader = XlibSurface::new(entry, instance).expect("Unable to load xlib surface"); xlib_surface_loader.create_xlib_surface_khr(&x11_create_info, None) } unsafe fn create_swapchain( entry: &Entry<V1_0>, instance: &Instance<V1_0>, window: &winit::Window, physical_device: PhysicalDevice, device: &Device<V1_0>, ) -> Result<(Swapchain, SwapchainKHR), vk::Result> { let surface = create_surface(entry, instance, window).unwrap(); let surface_loader = Surface::new(entry, instance).expect("Unable to load the Surface extension"); let surface_formats = surface_loader .get_physical_device_surface_formats_khr(physical_device, surface) .unwrap(); let surface_format = surface_formats .iter() .map(|sfmt| match sfmt.format { vk::Format::Undefined => vk::SurfaceFormatKHR { format: vk::Format::B8g8r8Unorm, color_space: sfmt.color_space, }, _ => sfmt.clone(), }) .nth(0) .expect("Unable to find suitable surface format."); let surface_capabilities = surface_loader .get_physical_device_surface_capabilities_khr(physical_device, surface) .unwrap(); let mut desired_image_count = surface_capabilities.min_image_count + 1; if surface_capabilities.max_image_count > 0 && desired_image_count > surface_capabilities.max_image_count { desired_image_count = surface_capabilities.max_image_count; } let surface_resolution = match surface_capabilities.current_extent.width { std::u32::MAX => vk::Extent2D { width: WIDTH as u32, height: HEIGHT as u32, }, _ => surface_capabilities.current_extent, }; let pre_transform = if surface_capabilities .supported_transforms .subset(vk::SURFACE_TRANSFORM_IDENTITY_BIT_KHR) { vk::SURFACE_TRANSFORM_IDENTITY_BIT_KHR } else { surface_capabilities.current_transform }; let present_modes = surface_loader .get_physical_device_surface_present_modes_khr(physical_device, surface) .unwrap(); let present_mode = present_modes .iter() .cloned() .find(|&mode| mode == vk::PresentModeKHR::Mailbox) .unwrap_or(vk::PresentModeKHR::Fifo); let swapchain_create_info = vk::SwapchainCreateInfoKHR { s_type: vk::StructureType::SwapchainCreateInfoKhr, p_next: ptr::null(), flags: Default::default(), surface: surface, min_image_count: desired_image_count, image_color_space: surface_format.color_space, image_format: surface_format.format, image_extent: surface_resolution.clone(), image_usage: vk::IMAGE_USAGE_COLOR_ATTACHMENT_BIT, image_sharing_mode: vk::SharingMode::Exclusive, pre_transform: pre_transform, composite_alpha: vk::COMPOSITE_ALPHA_OPAQUE_BIT_KHR, present_mode: present_mode, clipped: 1, old_swapchain: vk::SwapchainKHR::null(), image_array_layers: 1, p_queue_family_indices: ptr::null(), queue_family_index_count: 0, }; let swapchain_loader = Swapchain::new(instance, device).expect("Unable to load swapchain"); let swapchain = swapchain_loader .create_swapchain_khr(&swapchain_create_info, None) .unwrap(); Ok((swapchain_loader, swapchain)) } unsafe fn get_present_images( swapchain_loader: &Swapchain, swapchain: SwapchainKHR, ) -> Result<Vec<Image>, vk::Result> { swapchain_loader.get_swapchain_images_khr(swapchain) } unsafe fn create_semaphore(device: &Device<V1_0>) -> Result<Semaphore, vk::Result> {
random_line_split
main.rs
device.get_device_queue(queue_family_index, 0) }; let mut events_loop = winit::EventsLoop::new(); let window = winit::WindowBuilder::new() .with_title("Ash - Example") .with_dimensions(winit::dpi::LogicalSize { width: WIDTH, height: HEIGHT, }) .build(&events_loop) .unwrap(); let (swapchain_loader, swapchain) = unsafe { create_swapchain(&entry, &instance, &window, physical_device, &device).unwrap() }; let present_images = unsafe { get_present_images(&swapchain_loader, swapchain).unwrap() }; let present_complete_semaphore = unsafe { create_semaphore(&device).unwrap() }; let rendering_complete_semaphore = unsafe { create_semaphore(&device).unwrap() }; let mut closed = false; while !closed { events_loop.poll_events(|event| match event { winit::Event::WindowEvent { event, .. } => match event { winit::WindowEvent::CloseRequested => closed = true, _ => {} }, _ => {} }); let present_index = unsafe { swapchain_loader .acquire_next_image_khr( swapchain, std::u64::MAX, present_complete_semaphore, vk::Fence::null(), ) .unwrap() }; let present_info = vk::PresentInfoKHR { s_type: vk::StructureType::PresentInfoKhr, p_next: ptr::null(), wait_semaphore_count: 0, // p_wait_semaphores: &rendering_complete_semaphore, p_wait_semaphores: ptr::null(), swapchain_count: 1, p_swapchains: &swapchain, p_image_indices: &present_index, p_results: ptr::null_mut(), }; unsafe { swapchain_loader .queue_present_khr(present_queue, &present_info) .unwrap(); } } } fn create_entry() -> Entry<V1_0>
fn create_instance(entry: &Entry<V1_0>) -> Instance<V1_0> { let app_name = CString::new("Niagara-rs").unwrap(); let raw_name = app_name.as_ptr(); let appinfo = vk::ApplicationInfo { s_type: vk::StructureType::ApplicationInfo, api_version: vk_make_version!(1, 0, 36), p_application_name: raw_name, p_engine_name: raw_name, application_version: 0, engine_version: 0, p_next: ptr::null(), }; let layer_names = [CString::new("VK_LAYER_LUNARG_standard_validation").unwrap()]; let layers_names_raw: Vec<*const i8> = layer_names .iter() .map(|raw_name| raw_name.as_ptr()) .collect(); let extension_names_raw = extension_names(); let create_info = vk::InstanceCreateInfo { s_type: vk::StructureType::InstanceCreateInfo, p_next: ptr::null(), flags: Default::default(), p_application_info: &appinfo, pp_enabled_layer_names: layers_names_raw.as_ptr(), enabled_layer_count: layers_names_raw.len() as u32, pp_enabled_extension_names: extension_names_raw.as_ptr(), enabled_extension_count: extension_names_raw.len() as u32, }; unsafe { let instance = entry .create_instance(&create_info, None) .expect("Instance creation error"); let debug_info = vk::DebugReportCallbackCreateInfoEXT { s_type: vk::StructureType::DebugReportCallbackCreateInfoExt, p_next: ptr::null(), flags: vk::DEBUG_REPORT_ERROR_BIT_EXT | vk::DEBUG_REPORT_WARNING_BIT_EXT | vk::DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, pfn_callback: vulkan_debug_callback, p_user_data: ptr::null_mut(), }; let debug_report_loader = DebugReport::new(entry, &instance).expect("Unable to load debug report"); let _debug_call_back = debug_report_loader .create_debug_report_callback_ext(&debug_info, None) .unwrap(); return instance; } } fn pick_physical_device(instance: &Instance<V1_0>) -> vk::PhysicalDevice { let physical_devices = instance .enumerate_physical_devices() .expect("Physical device error"); if physical_devices.len() == 0 { panic!("No GPU found!"); } let physical_device = physical_devices .iter() .max_by_key(|physical_device| { let props = instance.get_physical_device_properties(**physical_device); match props.device_type { vk::PhysicalDeviceType::DiscreteGpu => 2, vk::PhysicalDeviceType::IntegratedGpu => 1, _ => 0, } }) .expect("No suitable device found!"); return *physical_device; } #[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))] fn extension_names() -> Vec<*const i8> { vec![ Surface::name().as_ptr(), XlibSurface::name().as_ptr(), DebugReport::name().as_ptr(), ] } fn create_device(instance: &Instance<V1_0>, physical_device: &vk::PhysicalDevice) -> Device<V1_0> { let queue_family_index = 0 as u32; let priorities = [1.0]; let queue_info = vk::types::DeviceQueueCreateInfo { s_type: vk::StructureType::DeviceQueueCreateInfo, p_next: ptr::null(), flags: Default::default(), queue_family_index: queue_family_index as u32, p_queue_priorities: priorities.as_ptr(), queue_count: priorities.len() as u32, }; let device_extension_names_raw = [Swapchain::name().as_ptr()]; let features = vk::PhysicalDeviceFeatures { shader_clip_distance: 1, ..Default::default() }; let device_create_info = vk::DeviceCreateInfo { s_type: vk::StructureType::DeviceCreateInfo, p_next: ptr::null(), flags: Default::default(), p_queue_create_infos: &queue_info, queue_create_info_count: 1, pp_enabled_layer_names: ptr::null(), enabled_layer_count: 0, pp_enabled_extension_names: device_extension_names_raw.as_ptr(), enabled_extension_count: device_extension_names_raw.len() as u32, p_enabled_features: &features, }; unsafe { let device: Device<V1_0> = instance .create_device(*physical_device, &device_create_info, None) .unwrap(); return device; } } #[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))] unsafe fn create_surface<E: EntryV1_0, I: InstanceV1_0>( entry: &E, instance: &I, window: &winit::Window, ) -> Result<vk::SurfaceKHR, vk::Result> { use winit::os::unix::WindowExt; let x11_display = window.get_xlib_display().unwrap(); let x11_window = window.get_xlib_window().unwrap(); let x11_create_info = vk::XlibSurfaceCreateInfoKHR { s_type: vk::StructureType::XlibSurfaceCreateInfoKhr, p_next: ptr::null(), flags: Default::default(), window: x11_window as vk::Window, dpy: x11_display as *mut vk::Display, }; let xlib_surface_loader = XlibSurface::new(entry, instance).expect("Unable to load xlib surface"); xlib_surface_loader.create_xlib_surface_khr(&x11_create_info, None) } unsafe fn create_swapchain( entry: &Entry<V1_0>, instance: &Instance<V1_0>, window: &winit::Window, physical_device: PhysicalDevice, device: &Device<V1_0>, ) -> Result<(Swapchain, SwapchainKHR), vk::Result> { let surface = create_surface(entry, instance, window).unwrap(); let surface_loader = Surface::new(entry, instance).expect("Unable to load the Surface extension"); let surface_formats = surface_loader .get_physical_device_surface_formats_khr(physical_device, surface) .unwrap(); let surface_format = surface_formats .iter() .map(|sfmt| match sfmt.format { vk::Format::Undefined => vk::SurfaceFormatKHR { format: vk::Format::B8g8r8Unorm, color_space: sfmt.color_space, }, _ => sfmt.clone(), }) .nth(0) .expect("Unable to find suitable surface format."); let surface_capabilities = surface_loader .get_physical_device_surface_capabilities_khr(physical_device, surface) .unwrap(); let mut desired_image_count = surface_capabilities.min_image_count + 1; if surface_capabilities.max_image_count > 0 && desired_image_count > surface_capabilities.max_image_count { desired_image_count = surface_capabilities.max_image_count; } let surface_resolution = match surface_capabilities.current_extent.width { std::u32::MAX => vk::Extent2D { width: WIDTH as u32, height:
{ Entry::new().unwrap() }
identifier_body
tweetnacl.rs
(a: &mut Self, b: &mut Self, choice: Choice) { // what TweetNacl originally does // let mask: i64 = !(b - 1); // TweetNacl translated to Choice language // let mask: i64 = !(choice.unwrap_u8() as i64) - 1); // `subtle` definition, which is equivalent // let mask: i64 = -(choice.unwrap_u8() as i64); for (ai, bi) in a.0.iter_mut().zip(b.0.iter_mut()) { // let t = mask & (*ai ^ *bi); // *ai ^= t; // *bi ^= t; i64::conditional_swap(ai, bi, choice); } } } impl FieldImplementation for FieldElement { type Limbs = Limbs; const ZERO: Self = Self([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); const ONE: Self = Self([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); const D: Self = Self([ 0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203, ]); const D2: Self = Self([ 0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406, ]); const EDWARDS_BASEPOINT_X: Self = Self([ 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169, ]); const EDWARDS_BASEPOINT_Y: Self = Self([ 0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, ]); const I: Self = Self([ 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83, ]); const APLUS2_OVER_FOUR: Self = Self([121666, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); const MONTGOMERY_BASEPOINT_U: Self = Self([9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); fn to_bytes(&self) -> [u8; 32] { // make our own private copy let mut fe = *self; // three times' the charm?? // TODO: figure out why :) fe.carry(); fe.carry(); fe.carry(); // let m_buf: FieldElementBuffer = Default::default(); // let mut m: FieldElement = FieldElement(m_buf); let mut m: Limbs = Default::default(); for _j in 0..2 { m[0] = fe.0[0] - 0xffed; for i in 1..15 { m[i] = fe.0[i] - 0xffff - ((m[i - 1] >> 16) & 1); m[i - 1] &= 0xffff; } m[15] = fe.0[15] - 0x7fff - ((m[14] >> 16) & 1); let b = (m[15] >> 16) & 1; m[14] &= 0xffff; FieldElement::conditional_swap(&mut fe, &mut FieldElement(m), ((1 - b) as u8).into()); } let mut bytes: [u8; 32] = Default::default(); for i in 0..16 { bytes[2 * i] = fe.0[i] as u8; //& 0xff; bytes[2 * i + 1] = (fe.0[i] >> 8) as u8; } bytes } fn from_bytes_unchecked(bytes: &[u8; 32]) -> FieldElement { let mut limbs = Limbs::default(); for i in 0..16 { limbs[i] = (bytes[2 * i] as i64) + ((bytes[2 * i + 1] as i64) << 8); } // some kind of safety check // but: also clears the x-coordinate sign bit limbs[15] &= 0x7fff; FieldElement(limbs) } // sv inv25519(gf o,const gf i) // { // // want: o = 1/i in base field // gf c; // int a; // FOR(a,16) c[a]=i[a]; // // exponentiate with 2^255 - 21 // // same as inversion by Fermat's little theorem // for(a=253;a>=0;a--) { // S(c,c); // if(a!=2&&a!=4) M(c,c,i); // } // FOR(a,16) o[a]=c[a]; // } fn inverse(&self) -> FieldElement { // TODO: possibly assert! that fe != 0? // make our own private copy let mut inverse = *self; // exponentiate with 2**255 - 21, // which by Fermat's little theorem is the same as inversion for i in (0..=253).rev() { inverse = inverse.squared(); if i != 2 && i != 4 { inverse = &inverse * self; } } inverse } // sv pow2523(gf o,const gf i) // // the naming here means "to the power of 2^252 - 3 // // again by Fermat's little theorem, this is the same // // as taking the square root, which is needed for // // point decompression // { // gf c; // int a; // FOR(a,16) c[a]=i[a]; // for(a=250;a>=0;a--) { // S(c,c); // if(a!=1) M(c,c,i); // } // FOR(a,16) o[a]=c[a]; // } /// TODO: figure out why this doesn't pass the test at the end fn pow2523(&self) -> FieldElement { let mut
conditional_swap
identifier_name
tweetnacl.rs
!=4) M(c,c,i); // } // FOR(a,16) o[a]=c[a]; // } fn inverse(&self) -> FieldElement { // TODO: possibly assert! that fe != 0? // make our own private copy let mut inverse = *self; // exponentiate with 2**255 - 21, // which by Fermat's little theorem is the same as inversion for i in (0..=253).rev() { inverse = inverse.squared(); if i != 2 && i != 4 { inverse = &inverse * self; } } inverse } // sv pow2523(gf o,const gf i) // // the naming here means "to the power of 2^252 - 3 // // again by Fermat's little theorem, this is the same // // as taking the square root, which is needed for // // point decompression // { // gf c; // int a; // FOR(a,16) c[a]=i[a]; // for(a=250;a>=0;a--) { // S(c,c); // if(a!=1) M(c,c,i); // } // FOR(a,16) o[a]=c[a]; // } /// TODO: figure out why this doesn't pass the test at the end fn pow2523(&self) -> FieldElement { let mut sqrt = *self; for i in (0..=250).rev() { sqrt = sqrt.squared(); if i != 1 { sqrt = &sqrt * self; } } sqrt } } impl ConstantTimeEq for FieldElement { fn ct_eq(&self, other: &Self) -> Choice { let canonical_self = self.to_bytes(); let canonical_other = other.to_bytes(); canonical_self.ct_eq(&canonical_other) } } impl PartialEq for FieldElement { fn eq(&self, other: &Self) -> bool { bool::from(self.ct_eq(other)) } } impl<'a, 'b> Add<&'b FieldElement> for &'a FieldElement { type Output = FieldElement; // TODO: TweetNaCl doesn't do any reduction here, why not? /// Addition of field elements fn add(self, other: &'b FieldElement) -> FieldElement { let mut sum = *self; sum += other; sum } } impl<'b> AddAssign<&'b FieldElement> for FieldElement { fn add_assign(&mut self, other: &'b FieldElement) { for (x, y) in self.0.iter_mut().zip(other.0.iter()) { *x += y; } } } impl<'a> Neg for &'a FieldElement { type Output = FieldElement; /// Subition of field elements fn neg(self) -> FieldElement { let mut negation = *self; for (i, xi) in self.0.iter().enumerate() { negation.0[i] = -xi; } negation } } impl<'a, 'b> Sub<&'b FieldElement> for &'a FieldElement { type Output = FieldElement; // TODO: TweetNaCl doesn't do any reduction here, why not? /// Subition of field elements fn sub(self, other: &'b FieldElement) -> FieldElement { let mut difference = *self; difference -= other; difference } } impl<'b> SubAssign<&'b FieldElement> for FieldElement { fn sub_assign(&mut self, other: &'b FieldElement) { for (x, y) in self.0.iter_mut().zip(other.0.iter()) { *x -= y; } } } impl<'a, 'b> Mul<&'b FieldElement> for &'a FieldElement { type Output = FieldElement; fn mul(self, other: &'b FieldElement) -> FieldElement { // start with so-called "schoolbook multiplication" // TODO: nicer way to do this with iterators? let mut pre_product: [i64; 31] = Default::default(); for i in 0..16 { for j in 0..16 { pre_product[i + j] += self.0[i] * other.0[j]; } } // reduce modulo 2**256 - 38 // (en route to reduction modulo 2**255 - 19) for i in 0..15 { pre_product[i] += 38 * pre_product[i + 16]; } // ble, would prefer to call pre_product just product, // but the two-step initialize then copy doesn't seem // to work syntactically. // also: really hope the initialization of `product` // is optimized away... let mut product: Limbs = Default::default(); product.copy_from_slice(&pre_product[..16]); let mut fe = FieldElement(product); // normalize such that all limbs lie in [0, 2^16) // TODO: why twice? why is twice enough? fe.carry(); fe.carry(); fe } } impl<'b> MulAssign<&'b FieldElement> for FieldElement { fn mul_assign(&mut self, other: &'b FieldElement) { let result = (self as &FieldElement) * other; self.0 = result.0; } } impl FieldElement { fn carry(&mut self) { // TODO: multiplication calls this twice!! // TODO: to_bytes calls this thrice!!! // // What exactly are the guarantees here? // Why don't we do this twice or thrice if it's needed? for i in 0..16 { // add 2**16 self.0[i] += 1 << 16; // "carry" part, everything over radix 2**16 let carry = self.0[i] >> 16; // a) i < 15: add carry bit, subtract 1 to compensate addition of 2^16 // --> o[i + 1] += c - 1 // add carry bit, subtract // b) i == 15: wraps around to index 0 via 2^256 = 38 // --> o[0] += 38 * (c - 1) self.0[(i + 1) * ((i < 15) as usize)] += carry - 1 + 37 * (carry - 1) * ((i == 15) as i64); // get rid of carry bit // TODO: why not get rid of it immediately. kinda clearer self.0[i] -= carry << 16; } } } #[cfg(test)] mod tests { use super::FieldElement; use crate::field::FieldImplementation; use subtle::ConstantTimeEq; #[test] fn test_one_plus_one() { let one = FieldElement::ONE; let two = &one + &one; let expected = FieldElement([2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); // TODO: Implement PartialEq (hopefully in constant time!) assert_eq!(two.0, expected.0); assert!(bool::from(two.ct_eq(&expected))) } #[test] fn test_one_times_zero() { let one = FieldElement::ONE; let zero = FieldElement::ZERO; let result = &one * &zero; // TODO: Implement PartialEq (hopefully in constant time!) assert_eq!(result.0, zero.0); assert!(bool::from(result.ct_eq(&zero))) } #[test] fn test_two_times_three_is_six() { let one = FieldElement::ONE; let two = &one + &one; let three = &two + &one; let two_times_three = &two * &three; // no multiplications, just sum up ONEs let six = (1..=6).fold(FieldElement::ZERO, |partial_sum, _| { &partial_sum + &FieldElement::ONE }); assert_eq!(two_times_three.to_bytes(), six.to_bytes()); assert!(bool::from(two_times_three.ct_eq(&six))); } #[test] fn test_negation() { let d2 = FieldElement::D2; let minus_d2 = -&d2; let maybe_zero = &d2 + &minus_d2; assert_eq!(FieldElement::ZERO.to_bytes(), maybe_zero.to_bytes()); } #[test] fn test_inversion() { let d2 = FieldElement::D2; let maybe_inverse = d2.inverse(); let maybe_one = &d2 * &maybe_inverse;
assert_eq!(maybe_one.to_bytes(), FieldElement::ONE.to_bytes());
random_line_split
tweetnacl.rs
xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406, ]); const EDWARDS_BASEPOINT_X: Self = Self([ 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169, ]); const EDWARDS_BASEPOINT_Y: Self = Self([ 0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, ]); const I: Self = Self([ 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83, ]); const APLUS2_OVER_FOUR: Self = Self([121666, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); const MONTGOMERY_BASEPOINT_U: Self = Self([9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); fn to_bytes(&self) -> [u8; 32] { // make our own private copy let mut fe = *self; // three times' the charm?? // TODO: figure out why :) fe.carry(); fe.carry(); fe.carry(); // let m_buf: FieldElementBuffer = Default::default(); // let mut m: FieldElement = FieldElement(m_buf); let mut m: Limbs = Default::default(); for _j in 0..2 { m[0] = fe.0[0] - 0xffed; for i in 1..15 { m[i] = fe.0[i] - 0xffff - ((m[i - 1] >> 16) & 1); m[i - 1] &= 0xffff; } m[15] = fe.0[15] - 0x7fff - ((m[14] >> 16) & 1); let b = (m[15] >> 16) & 1; m[14] &= 0xffff; FieldElement::conditional_swap(&mut fe, &mut FieldElement(m), ((1 - b) as u8).into()); } let mut bytes: [u8; 32] = Default::default(); for i in 0..16 { bytes[2 * i] = fe.0[i] as u8; //& 0xff; bytes[2 * i + 1] = (fe.0[i] >> 8) as u8; } bytes } fn from_bytes_unchecked(bytes: &[u8; 32]) -> FieldElement { let mut limbs = Limbs::default(); for i in 0..16 { limbs[i] = (bytes[2 * i] as i64) + ((bytes[2 * i + 1] as i64) << 8); } // some kind of safety check // but: also clears the x-coordinate sign bit limbs[15] &= 0x7fff; FieldElement(limbs) } // sv inv25519(gf o,const gf i) // { // // want: o = 1/i in base field // gf c; // int a; // FOR(a,16) c[a]=i[a]; // // exponentiate with 2^255 - 21 // // same as inversion by Fermat's little theorem // for(a=253;a>=0;a--) { // S(c,c); // if(a!=2&&a!=4) M(c,c,i); // } // FOR(a,16) o[a]=c[a]; // } fn inverse(&self) -> FieldElement { // TODO: possibly assert! that fe != 0? // make our own private copy let mut inverse = *self; // exponentiate with 2**255 - 21, // which by Fermat's little theorem is the same as inversion for i in (0..=253).rev() { inverse = inverse.squared(); if i != 2 && i != 4 { inverse = &inverse * self; } } inverse } // sv pow2523(gf o,const gf i) // // the naming here means "to the power of 2^252 - 3 // // again by Fermat's little theorem, this is the same // // as taking the square root, which is needed for // // point decompression // { // gf c; // int a; // FOR(a,16) c[a]=i[a]; // for(a=250;a>=0;a--) { // S(c,c); // if(a!=1) M(c,c,i); // } // FOR(a,16) o[a]=c[a]; // } /// TODO: figure out why this doesn't pass the test at the end fn pow2523(&self) -> FieldElement { let mut sqrt = *self; for i in (0..=250).rev() { sqrt = sqrt.squared(); if i != 1
} sqrt } } impl ConstantTimeEq for FieldElement { fn ct_eq(&self, other: &Self) -> Choice { let canonical_self = self.to_bytes(); let canonical_other = other.to_bytes(); canonical_self.ct_eq(&canonical_other) } } impl PartialEq for FieldElement { fn eq(&self, other: &Self) -> bool { bool::from(self.ct_eq(other)) } } impl<'a, 'b> Add<&'b FieldElement> for &'a FieldElement { type Output = FieldElement; // TODO: TweetNaCl doesn't do any reduction here, why not? /// Addition of field elements fn add(self, other: &'b FieldElement) -> FieldElement { let mut sum = *self; sum += other; sum } } impl<'b> AddAssign<&'b FieldElement> for FieldElement { fn add_assign(&mut self, other: &'b FieldElement) { for (x, y) in self.0.iter_mut().zip(other.0.iter()) { *x += y; } } } impl<'a> Neg for &'a FieldElement { type Output = FieldElement; /// Subition of field elements fn neg(self) -> FieldElement { let mut negation = *self; for (i, xi) in self.0.iter().enumerate() { negation.0[i] = -xi; } negation } } impl<'a, 'b> Sub<&'b FieldElement> for &'a FieldElement { type Output = FieldElement; // TODO: TweetNaCl doesn't do any reduction here, why not? /// Subition of field elements fn sub(self, other: &'b FieldElement) -> FieldElement { let mut difference = *self; difference -= other; difference } } impl<'b> SubAssign<&'b Field
{ sqrt = &sqrt * self; }
conditional_block
tweetnacl.rs
0f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406, ]); const EDWARDS_BASEPOINT_X: Self = Self([ 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169, ]); const EDWARDS_BASEPOINT_Y: Self = Self([ 0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, ]); const I: Self = Self([ 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83, ]); const APLUS2_OVER_FOUR: Self = Self([121666, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); const MONTGOMERY_BASEPOINT_U: Self = Self([9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); fn to_bytes(&self) -> [u8; 32] { // make our own private copy let mut fe = *self; // three times' the charm?? // TODO: figure out why :) fe.carry(); fe.carry(); fe.carry(); // let m_buf: FieldElementBuffer = Default::default(); // let mut m: FieldElement = FieldElement(m_buf); let mut m: Limbs = Default::default(); for _j in 0..2 { m[0] = fe.0[0] - 0xffed; for i in 1..15 { m[i] = fe.0[i] - 0xffff - ((m[i - 1] >> 16) & 1); m[i - 1] &= 0xffff; } m[15] = fe.0[15] - 0x7fff - ((m[14] >> 16) & 1); let b = (m[15] >> 16) & 1; m[14] &= 0xffff; FieldElement::conditional_swap(&mut fe, &mut FieldElement(m), ((1 - b) as u8).into()); } let mut bytes: [u8; 32] = Default::default(); for i in 0..16 { bytes[2 * i] = fe.0[i] as u8; //& 0xff; bytes[2 * i + 1] = (fe.0[i] >> 8) as u8; } bytes } fn from_bytes_unchecked(bytes: &[u8; 32]) -> FieldElement { let mut limbs = Limbs::default(); for i in 0..16 { limbs[i] = (bytes[2 * i] as i64) + ((bytes[2 * i + 1] as i64) << 8); } // some kind of safety check // but: also clears the x-coordinate sign bit limbs[15] &= 0x7fff; FieldElement(limbs) } // sv inv25519(gf o,const gf i) // { // // want: o = 1/i in base field // gf c; // int a; // FOR(a,16) c[a]=i[a]; // // exponentiate with 2^255 - 21 // // same as inversion by Fermat's little theorem // for(a=253;a>=0;a--) { // S(c,c); // if(a!=2&&a!=4) M(c,c,i); // } // FOR(a,16) o[a]=c[a]; // } fn inverse(&self) -> FieldElement { // TODO: possibly assert! that fe != 0? // make our own private copy let mut inverse = *self; // exponentiate with 2**255 - 21, // which by Fermat's little theorem is the same as inversion for i in (0..=253).rev() { inverse = inverse.squared(); if i != 2 && i != 4 { inverse = &inverse * self; } } inverse } // sv pow2523(gf o,const gf i) // // the naming here means "to the power of 2^252 - 3 // // again by Fermat's little theorem, this is the same // // as taking the square root, which is needed for // // point decompression // { // gf c; // int a; // FOR(a,16) c[a]=i[a]; // for(a=250;a>=0;a--) { // S(c,c); // if(a!=1) M(c,c,i); // } // FOR(a,16) o[a]=c[a]; // } /// TODO: figure out why this doesn't pass the test at the end fn pow2523(&self) -> FieldElement { let mut sqrt = *self; for i in (0..=250).rev() { sqrt = sqrt.squared(); if i != 1 { sqrt = &sqrt * self; } } sqrt } } impl ConstantTimeEq for FieldElement { fn ct_eq(&self, other: &Self) -> Choice { let canonical_self = self.to_bytes(); let canonical_other = other.to_bytes(); canonical_self.ct_eq(&canonical_other) } } impl PartialEq for FieldElement { fn eq(&self, other: &Self) -> bool { bool::from(self.ct_eq(other)) } } impl<'a, 'b> Add<&'b FieldElement> for &'a FieldElement { type Output = FieldElement; // TODO: TweetNaCl doesn't do any reduction here, why not? /// Addition of field elements fn add(self, other: &'b FieldElement) -> FieldElement { let mut sum = *self; sum += other; sum } } impl<'b> AddAssign<&'b FieldElement> for FieldElement { fn add_assign(&mut self, other: &'b FieldElement) { for (x, y) in self.0.iter_mut().zip(other.0.iter()) { *x += y; } } } impl<'a> Neg for &'a FieldElement { type Output = FieldElement; /// Subition of field elements fn neg(self) -> FieldElement { let mut negation = *self; for (i, xi) in self.0.iter().enumerate() { negation.0[i] = -xi; } negation } } impl<'a, 'b> Sub<&'b FieldElement> for &'a FieldElement { type Output = FieldElement; // TODO: TweetNaCl doesn't do any reduction here, why not? /// Subition of field elements fn sub(self, other: &'b FieldElement) -> FieldElement { let mut difference = *self; difference -= other; difference } } impl<'b> SubAssign<&'b FieldElement> for FieldElement { fn sub_assign(&mut self, other: &'b FieldElement)
{ for (x, y) in self.0.iter_mut().zip(other.0.iter()) { *x -= y; } }
identifier_body
control.rs
= loop { let q = view.event_proc(cross); view = match q { // delegate to top-level control loop DelegateEvent::Quit | DelegateEvent::OpenDialog(_) => { quit = match &mut view { HexView::Aligned(v, _, _) => !v.process_escape(cross), HexView::Unaligned(v) => !v.process_escape(cross), } .then_some(q); view } DelegateEvent::SwitchToAlign => { quit = None; let select = view.selection(); view.into_aligned(&settings.algo, select) } DelegateEvent::SwitchToUnalign => { quit = None; view.into_unaligned() } }; if let Some(q) = quit { break q; } }; (view, quit_reason) } /// Setup a cursive instance and shows a dialog constructed through the callback given in `dialog`. /// /// Note that the settings are placed into the user_data of the cursive instace and can be modified /// by the callback. fn show_dialog(self, dialog: CursiveCallback, settings: Settings) -> (Self, Settings) { let mut siv = cursive::default(); // this theme is the default theme except that the background color is black siv.set_theme(cursiv_theme()); siv.add_global_callback(Key::Esc, dialog::close_top_maybe_quit); siv.set_user_data(settings); match self { HexView::Aligned(a, send, mut recv) => { siv.add_fullscreen_layer(a.with_name("aligned").full_screen()); let mut sink = siv.cb_sink().clone(); // we create a new thread that converts the `AlignedMessage`s coming from // the alignment threads to callbacks on the cursive instance, so this case // is a bit more complicated than the unaligned one. scope(|s| { let join_handle = s.spawn(|_| cursiv_align_relay(&mut recv, &mut sink)); dialog(&mut siv); siv.try_run_with(|| { // use the buffered backend as it involves way less flickering crossterm::Backend::init() .map(|x| Box::new(BufferedBackend::new(x)) as Box<dyn CursiveBackend>) }) .expect("Could not run"); // misuse the Action::Quit as a signal for the thread to exit send.send(AlignedMessage::UserEvent(Action::Quit)) .expect("Could not tell align relay thread to quit"); join_handle .join() .expect("Could not join align relay thread"); }) .expect("Could not join align relay thread"); // extract the view from the cursive instance match peel_onion(&mut siv) { Some(x) => ( HexView::Aligned(x, send, recv), siv.take_user_data().unwrap(), ), None => panic!("Internal error, could not downcast view"), } } HexView::Unaligned(u) => { siv.add_fullscreen_layer(u.with_name("unaligned").full_screen()); dialog(&mut siv); siv.try_run_with(|| { crossterm::Backend::init() .map(|x| Box::new(BufferedBackend::new(x)) as Box<dyn CursiveBackend>) }) .expect("Could not run"); // extract the view from the cursive instance match peel_onion(&mut siv) { Some(v) => (HexView::Unaligned(v), siv.take_user_data().unwrap()), None => panic!("Internal error, could not downcast view"), } } } } } // this one causes tears to come from my eyes fn peel_onion<V: View>(siv: &mut Cursive) -> Option<V> { siv.screen_mut() .remove_layer(LayerPosition::FromBack(0)) .downcast::<ResizedView<NamedView<V>>>() .ok() .and_then(|view| view.into_inner().ok()) .and_then(|view| view.into_inner().ok()) } /// Default Cursive theme except that the background color is black fn cursiv_theme() -> cursive::theme::Theme { use cursive::theme::{BaseColor::*, Color::*, PaletteColor::*}; let mut cursiv_theme = cursive::theme::load_default(); cursiv_theme.palette[Background] = Dark(Black); cursiv_theme } /// Forwards `AlignedMessage`s from the alignment thread into callbacks for the cursive instance fn cursiv_align_relay(recv: &mut Receiver<AlignedMessage>, sink: &mut cursive::CbSink) { for ev in recv.iter() { match ev { AlignedMessage::UserEvent(Action::Quit) => break, otherwise => { sink.send(Box::new(|siv: &mut Cursive| { siv.call_on_name("aligned", |view: &mut Aligned| { view.process_action(&mut Dummy, otherwise); }) .expect("Could not send new data to view"); })) .expect("Could not send event to view"); } } } } /// This enum is used for delegating actions to higher level event loops. enum DelegateEvent { Quit, SwitchToAlign, SwitchToUnalign, OpenDialog(CursiveCallback), } /// Converts an event to a delegation fn delegate_action(action: Action) -> Option<DelegateEvent> { match action { Action::Quit => Some(DelegateEvent::Quit), Action::Align => Some(DelegateEvent::SwitchToAlign), Action::Unalign => Some(DelegateEvent::SwitchToUnalign), Action::Algorithm => Some(DelegateEvent::OpenDialog(Box::new(dialog::settings))), Action::Goto => Some(DelegateEvent::OpenDialog(Box::new(dialog::goto))), Action::Search => Some(DelegateEvent::OpenDialog(Box::new(dialog::search))), Action::SetOffset => Some(DelegateEvent::OpenDialog(Box::new(dialog::set_offset))), Action::Help => Some(DelegateEvent::OpenDialog(Box::new(dialog::help_window( dialog::MAIN_HELP, )))), _otherwise => None, } } /// This function is the one that processes actions sent by the event reader loop /// setup in `unaligned_cross`. Note that the event reader loop has to stay in the same /// thread, so this process is chosen to not be in the main thread instead. fn unaligned_cross_recv( unaligned: &mut view::Unaligned, cross: &mut Cross, recv: Receiver<Action>, ) -> DelegateEvent { unaligned.refresh(cross); for action in recv.iter() { if let Some(q) = delegate_action(action) { return q; } unaligned.process_action(cross, action); } DelegateEvent::Quit } /// This setups the event processing thread for the crossterm backend and reads crossterm's events fn unaligned_cross(unaligned: &mut view::Unaligned, cross: &mut Cross) -> DelegateEvent { unaligned.refresh(cross); let (mut send, recv) = channel(); let mut quit = DelegateEvent::Quit; scope(|s| { // both this thread and the send_cross_actions function determine when to quit by // checking the output of delegate_action, so make sure this is the same let receiver_thread = s.spawn(|_| unaligned_cross_recv(unaligned, cross, recv)); send_cross_actions(|action| delegate_action(action).is_some(), &mut send); quit = receiver_thread.join().unwrap(); }) .unwrap(); quit } /// This function is the one that processes actions sent by the event reader loop /// setup in `aligned_cross`, and also the ones sent by the alignment process. /// Note that the event reader loop has to stay in the same thread, so this /// process is chosen to not be in the main thread instead. fn aligned_cross_recv( aligned: &mut view::Aligned, cross: &mut Cross, recv: &mut Receiver<AlignedMessage>, ) -> DelegateEvent { for msg in recv.iter() { let msg = match msg { AlignedMessage::UserEvent(action) => { if let Some(q) = delegate_action(action) { return q; } msg } _ => msg, }; aligned.process_action(cross, msg); } DelegateEvent::Quit } /// Using the existing message channel (send, recv), setup a thread that /// processes the messages and also read the crossterm events in the main thread. /// The channel should be the same one used when setting up the Aligned view. fn aligned_cross( aligned: &mut view::Aligned, cross: &mut Cross, send: &mut Sender<AlignedMessage>, recv: &mut Receiver<AlignedMessage>, ) -> DelegateEvent { aligned.refresh(cross); let mut quit = DelegateEvent::Quit; scope(|s| { // both the thread and the send_cross_actions function determine when to quit by // checking the output of delegate_action, so make sure this is the same. let receiver_thread = s.spawn(|_| aligned_cross_recv(aligned, cross, recv)); send_cross_actions(|action| delegate_action(action).is_some(), send); quit = receiver_thread.join().unwrap(); }) .unwrap(); quit
random_line_split
control.rs
= read_to_string(Self::settings_file().ok()?).ok()?; serde_json::from_str(&config).ok() } pub fn save_config(&self) -> Result<(), Box<dyn Error + 'static>> { let config = serde_json::to_string(self)?; let r = std::fs::create_dir_all(Self::config_path()?); if let Err(ref e) = r { match e.kind() { std::io::ErrorKind::AlreadyExists => (), _ => r?, } } std::fs::write(Self::settings_file()?, config)?; Ok(()) } } /// An enum containing either an aligned or unaligned hexview, without /// a backend for painting. /// The aligned view also contains a channel for messages, as the alignment /// algorithms need to dynamically append/prepend new blocks to the view /// and the crossbeam backend also sends user events over that. pub enum HexView { Aligned( view::Aligned, Sender<AlignedMessage>, Receiver<AlignedMessage>, ), Unaligned(view::Unaligned), } impl HexView { /// Creates a new unaligned view from two files with given indexes and cursor /// size 16x16. pub fn new(left: FileState, right: FileState) -> Self { HexView::Unaligned(view::Unaligned::new( left, right, DoubleHexContext::new((16, 16)), )) } /// Turns a hexview into an aligned view using the given algorithm parameters fn into_aligned(self, algo: &AlignAlgorithm, select: [Option<Range<usize>>; 2]) -> HexView { let (send, recv) = channel(); match match self { // first destruct our old hexview into its parts HexView::Aligned(a, send, recv) => { a.destruct().map_err(|a| HexView::Aligned(a, send, recv)) } HexView::Unaligned(u) => u.destruct().map_err(HexView::Unaligned), } { // if the cursor was not placed on any index, we currently do nothing // maybe one could think up some better values to align at here or something Err(hv) => hv, Ok((left, right, mut dh)) => { if matches!(algo.mode, AlignMode::Local | AlignMode::Global) { dh.cursor = CursorState::new((dh.cursor.get_size_x(), dh.cursor.get_size_y())) }; HexView::Aligned( view::Aligned::new(left, right, dh, algo, select, send.clone()), send, recv, ) } } } /// Turns a hexview into an unaligned view at the current cursor fn into_unaligned(self) -> HexView { match self { HexView::Aligned(a, send, recv) => match a.destruct() { Ok((left, right, cursor)) => { HexView::Unaligned(view::Unaligned::new(left, right, cursor)) } Err(a) => HexView::Aligned(a, send, recv), }, // we don't need to change anything for unaligned views HexView::Unaligned(_) => self, } } /// Call the relevant event processing functions for the crossterm backend fn event_proc(&mut self, cross: &mut Cross) -> DelegateEvent { match self { HexView::Aligned(ref mut a, ref mut send, ref mut recv) => { aligned_cross(a, cross, send, recv) } HexView::Unaligned(ref mut u) => unaligned_cross(u, cross), } } fn selection(&self) -> [Option<Range<usize>>; 2] { match self { HexView::Aligned(a, _, _) => a.selection_file_ranges(), HexView::Unaligned(u) => u.selection_file_ranges(), } } /// control loop for crossbeam backend, switches the view between aligned and unaligned when /// requested and runs event loops fn process_cross(self, cross: &mut Cross, settings: &Settings) -> (Self, DelegateEvent) { let mut view = self; let mut quit; let quit_reason = loop { let q = view.event_proc(cross); view = match q { // delegate to top-level control loop DelegateEvent::Quit | DelegateEvent::OpenDialog(_) => { quit = match &mut view { HexView::Aligned(v, _, _) => !v.process_escape(cross), HexView::Unaligned(v) => !v.process_escape(cross), } .then_some(q); view } DelegateEvent::SwitchToAlign => { quit = None; let select = view.selection(); view.into_aligned(&settings.algo, select) } DelegateEvent::SwitchToUnalign => { quit = None; view.into_unaligned() } }; if let Some(q) = quit { break q; } }; (view, quit_reason) } /// Setup a cursive instance and shows a dialog constructed through the callback given in `dialog`. /// /// Note that the settings are placed into the user_data of the cursive instace and can be modified /// by the callback. fn show_dialog(self, dialog: CursiveCallback, settings: Settings) -> (Self, Settings) { let mut siv = cursive::default(); // this theme is the default theme except that the background color is black siv.set_theme(cursiv_theme()); siv.add_global_callback(Key::Esc, dialog::close_top_maybe_quit); siv.set_user_data(settings); match self { HexView::Aligned(a, send, mut recv) => { siv.add_fullscreen_layer(a.with_name("aligned").full_screen()); let mut sink = siv.cb_sink().clone(); // we create a new thread that converts the `AlignedMessage`s coming from // the alignment threads to callbacks on the cursive instance, so this case // is a bit more complicated than the unaligned one. scope(|s| { let join_handle = s.spawn(|_| cursiv_align_relay(&mut recv, &mut sink)); dialog(&mut siv); siv.try_run_with(|| { // use the buffered backend as it involves way less flickering crossterm::Backend::init() .map(|x| Box::new(BufferedBackend::new(x)) as Box<dyn CursiveBackend>) }) .expect("Could not run"); // misuse the Action::Quit as a signal for the thread to exit send.send(AlignedMessage::UserEvent(Action::Quit)) .expect("Could not tell align relay thread to quit"); join_handle .join() .expect("Could not join align relay thread"); }) .expect("Could not join align relay thread"); // extract the view from the cursive instance match peel_onion(&mut siv) { Some(x) => ( HexView::Aligned(x, send, recv), siv.take_user_data().unwrap(), ), None => panic!("Internal error, could not downcast view"), } } HexView::Unaligned(u) => { siv.add_fullscreen_layer(u.with_name("unaligned").full_screen()); dialog(&mut siv); siv.try_run_with(|| { crossterm::Backend::init() .map(|x| Box::new(BufferedBackend::new(x)) as Box<dyn CursiveBackend>) }) .expect("Could not run"); // extract the view from the cursive instance match peel_onion(&mut siv) { Some(v) => (HexView::Unaligned(v), siv.take_user_data().unwrap()), None => panic!("Internal error, could not downcast view"), } } } } } // this one causes tears to come from my eyes fn peel_onion<V: View>(siv: &mut Cursive) -> Option<V> { siv.screen_mut() .remove_layer(LayerPosition::FromBack(0)) .downcast::<ResizedView<NamedView<V>>>() .ok() .and_then(|view| view.into_inner().ok()) .and_then(|view| view.into_inner().ok()) } /// Default Cursive theme except that the background color is black fn cursiv_theme() -> cursive::theme::Theme { use cursive::theme::{BaseColor::*, Color::*, PaletteColor::*}; let mut cursiv_theme = cursive::theme::load_default(); cursiv_theme.palette[Background] = Dark(Black); cursiv_theme } /// Forwards `AlignedMessage`s from the alignment thread into callbacks for the cursive instance fn cursiv_align_relay(recv: &mut Receiver<AlignedMessage>, sink: &mut cursive::CbSink) { for ev in recv.iter() { match ev { AlignedMessage::UserEvent(Action::Quit) => break, otherwise =>
{ sink.send(Box::new(|siv: &mut Cursive| { siv.call_on_name("aligned", |view: &mut Aligned| { view.process_action(&mut Dummy, otherwise); }) .expect("Could not send new data to view"); })) .expect("Could not send event to view"); }
conditional_block
control.rs
settings = settings_new; } } #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct Settings { pub algo: AlignAlgorithm, pub style: Style, } impl Settings { fn config_path() -> Result<PathBuf, std::io::Error> { match std::env::var_os("BIODIFF_CONFIG_DIR") { Some(p) => Ok(PathBuf::from(p)), None => match config_dir() { Some(mut p) => { p.push("biodiff"); Ok(p) } None => Err(std::io::Error::new( std::io::ErrorKind::NotFound, "Could not find configuration directory", )), }, } } fn settings_file() -> Result<PathBuf, std::io::Error> { let mut path = Self::config_path()?; path.push("config.json"); Ok(path) } pub fn from_config() -> Option<Self> { let config = read_to_string(Self::settings_file().ok()?).ok()?; serde_json::from_str(&config).ok() } pub fn save_config(&self) -> Result<(), Box<dyn Error + 'static>> { let config = serde_json::to_string(self)?; let r = std::fs::create_dir_all(Self::config_path()?); if let Err(ref e) = r { match e.kind() { std::io::ErrorKind::AlreadyExists => (), _ => r?, } } std::fs::write(Self::settings_file()?, config)?; Ok(()) } } /// An enum containing either an aligned or unaligned hexview, without /// a backend for painting. /// The aligned view also contains a channel for messages, as the alignment /// algorithms need to dynamically append/prepend new blocks to the view /// and the crossbeam backend also sends user events over that. pub enum HexView { Aligned( view::Aligned, Sender<AlignedMessage>, Receiver<AlignedMessage>, ), Unaligned(view::Unaligned), } impl HexView { /// Creates a new unaligned view from two files with given indexes and cursor /// size 16x16. pub fn new(left: FileState, right: FileState) -> Self { HexView::Unaligned(view::Unaligned::new( left, right, DoubleHexContext::new((16, 16)), )) } /// Turns a hexview into an aligned view using the given algorithm parameters fn into_aligned(self, algo: &AlignAlgorithm, select: [Option<Range<usize>>; 2]) -> HexView { let (send, recv) = channel(); match match self { // first destruct our old hexview into its parts HexView::Aligned(a, send, recv) => { a.destruct().map_err(|a| HexView::Aligned(a, send, recv)) } HexView::Unaligned(u) => u.destruct().map_err(HexView::Unaligned), } { // if the cursor was not placed on any index, we currently do nothing // maybe one could think up some better values to align at here or something Err(hv) => hv, Ok((left, right, mut dh)) => { if matches!(algo.mode, AlignMode::Local | AlignMode::Global) { dh.cursor = CursorState::new((dh.cursor.get_size_x(), dh.cursor.get_size_y())) }; HexView::Aligned( view::Aligned::new(left, right, dh, algo, select, send.clone()), send, recv, ) } } } /// Turns a hexview into an unaligned view at the current cursor fn into_unaligned(self) -> HexView { match self { HexView::Aligned(a, send, recv) => match a.destruct() { Ok((left, right, cursor)) => { HexView::Unaligned(view::Unaligned::new(left, right, cursor)) } Err(a) => HexView::Aligned(a, send, recv), }, // we don't need to change anything for unaligned views HexView::Unaligned(_) => self, } } /// Call the relevant event processing functions for the crossterm backend fn event_proc(&mut self, cross: &mut Cross) -> DelegateEvent { match self { HexView::Aligned(ref mut a, ref mut send, ref mut recv) => { aligned_cross(a, cross, send, recv) } HexView::Unaligned(ref mut u) => unaligned_cross(u, cross), } } fn selection(&self) -> [Option<Range<usize>>; 2] { match self { HexView::Aligned(a, _, _) => a.selection_file_ranges(), HexView::Unaligned(u) => u.selection_file_ranges(), } } /// control loop for crossbeam backend, switches the view between aligned and unaligned when /// requested and runs event loops fn process_cross(self, cross: &mut Cross, settings: &Settings) -> (Self, DelegateEvent) { let mut view = self; let mut quit; let quit_reason = loop { let q = view.event_proc(cross); view = match q { // delegate to top-level control loop DelegateEvent::Quit | DelegateEvent::OpenDialog(_) => { quit = match &mut view { HexView::Aligned(v, _, _) => !v.process_escape(cross), HexView::Unaligned(v) => !v.process_escape(cross), } .then_some(q); view } DelegateEvent::SwitchToAlign => { quit = None; let select = view.selection(); view.into_aligned(&settings.algo, select) } DelegateEvent::SwitchToUnalign => { quit = None; view.into_unaligned() } }; if let Some(q) = quit { break q; } }; (view, quit_reason) } /// Setup a cursive instance and shows a dialog constructed through the callback given in `dialog`. /// /// Note that the settings are placed into the user_data of the cursive instace and can be modified /// by the callback. fn show_dialog(self, dialog: CursiveCallback, settings: Settings) -> (Self, Settings) { let mut siv = cursive::default(); // this theme is the default theme except that the background color is black siv.set_theme(cursiv_theme()); siv.add_global_callback(Key::Esc, dialog::close_top_maybe_quit); siv.set_user_data(settings); match self { HexView::Aligned(a, send, mut recv) => { siv.add_fullscreen_layer(a.with_name("aligned").full_screen()); let mut sink = siv.cb_sink().clone(); // we create a new thread that converts the `AlignedMessage`s coming from // the alignment threads to callbacks on the cursive instance, so this case // is a bit more complicated than the unaligned one. scope(|s| { let join_handle = s.spawn(|_| cursiv_align_relay(&mut recv, &mut sink)); dialog(&mut siv); siv.try_run_with(|| { // use the buffered backend as it involves way less flickering crossterm::Backend::init() .map(|x| Box::new(BufferedBackend::new(x)) as Box<dyn CursiveBackend>) }) .expect("Could not run"); // misuse the Action::Quit as a signal for the thread to exit send.send(AlignedMessage::UserEvent(Action::Quit)) .expect("Could not tell align relay thread to quit"); join_handle .join() .expect("Could not join align relay thread"); }) .expect("Could not join align relay thread"); // extract the view from the cursive instance match peel_onion(&mut siv) { Some(x) => ( HexView::Aligned(x, send, recv), siv.take_user_data().unwrap(), ), None => panic!("Internal error, could not downcast view"), } } HexView::Unaligned(u) => { siv.add_fullscreen_layer(u.with_name("unaligned").full_screen()); dialog(&mut siv); siv.try_run_with(|| { crossterm::Backend::init() .map(|x| Box::new(BufferedBackend::new(x)) as Box<dyn CursiveBackend>) }) .expect("Could not run"); // extract the view from the cursive instance match peel_onion(&mut siv) { Some(v) => (HexView::Unaligned(v), siv.take_user_data().unwrap()), None => panic!("Internal error, could not downcast view"), } } } } } // this one causes tears to come from my eyes fn peel_onion<V: View>(siv: &mut Cursive) -> Option<V> { siv.screen_mut() .remove_layer(LayerPosition::FromBack(0)) .downcast::<ResizedView<NamedView<V>>>() .ok() .and_then(|view| view.into_inner().ok()) .and_then(|view| view.into_inner().ok()) } /// Default Cursive theme except that the background color is black fn
cursiv_theme
identifier_name
print_test.py
D tensor after being normalized ''' mean, varience = tf.nn.moments(input_layer, axes=[0, 1, 2]) beta = tf.get_variable('beta', dimension, tf.float32, initializer=tf.constant_initializer(0.0, tf.float32)) gamma = tf.get_variable('gamma', dimension, tf.float32, initializer=tf.constant_initializer(1.0, tf.float32)) bn_layer = tf.nn.batch_normalization(input_layer, mean, varience, beta, gamma, BN_EPSILON) return bn_layer # 在这里进行相应的修改操作吧? def conv_bn_relu_layer(input_layer, filter_shape, stride, dilation=1): ''' A helper function to conv, batch normalize and relu the input tensor sequentially :param input_layer: 4D tensor :param filter_shape: list. [filter_height, filter_width, filter_depth, filter_number] :param stride: stride size for conv :return: 4D tensor. Y = Relu(batch_normalize(conv(X))) ''' out_channel = filter_shape[-1] filter = create_variables(name='conv', shape=filter_shape) if dilation == 1: conv_layer = tf.nn.conv2d(input_layer, filter, strides=[1, stride, stride, 1], padding='SAME') elif dilation == 2: conv_layer = tf.nn.atrous_conv2d(value=input_layer, filters=filter, rate=2, padding='SAME') elif dilation == 4: conv_layer = tf.nn.atrous_conv2d(value=input_layer, filters=filter, rate=4, padding='SAME') else: raise ValueError('no dilation is choosen!!!') bn_layer = batch_normalization_layer(conv_layer, out_channel) output = tf.nn.relu(bn_layer) return output # 我们采用这个基础网络结构 def bn_relu_conv_layer(input_layer, filter_shape, stride=1, dilation=1): ''' A helper function to batch normalize, relu and conv the input layer sequentially :param input_layer: 4D tensor :param filter_shape: list. [filter_height, filter_width, filter_depth, filter_number] :param stride: stride size for conv :return: 4D tensor. Y = conv(Relu(batch_normalize(X))) ''' in_channel = input_layer.get_shape().as_list()[-1] bn_layer = batch_normalization_layer(input_layer, in_channel) relu_layer = tf.nn.relu(bn_layer) filter = create_variables(name='conv', shape=filter_shape) # 这里进行卷积操作的一个很重要的部分,选择卷积的方式是什么,其中有1,2,4 if dilation == 1: conv_layer = tf.nn.conv2d(relu_layer, filter, strides=[1, stride, stride, 1], padding='SAME') elif dilation == 2: conv_layer = tf.nn.atrous_conv2d(value=relu_layer, filters=filter, rate=2, padding='SAME') elif dilation == 4: conv_layer = tf.nn.atrous_conv2d(value=relu_layer, filters=filter, rate=4, padding='SAME') else: raise ValueError('no dilation is choosen!!!') return conv_layer # 开始构造block的结构过程 def residual_block(input_layer, output_channel, dilation=1, stride=1, first_block=False): ''' Defines a residual block in ResNet :param input_layer: 4D tensor :param output_channel: int. return_tensor.get_shape().as_list()[-1] = output_channel :param first_block: if this is the first residual block of the whole network :return: 4D tensor. ''' input_channel = input_layer.get_shape().as_list()[-1] # 按照正常的网络结构 # 我们选择先bath 然后进行卷积和relu的操作 # Y = conv(Relu(batch_normalize(X))) # bn_relu_conv_layer(input_layer,filter_shape,stride,dilation=1) ''' 设置残差网络的模板的第一层 ''' # 这里进行查看输入输出维度以及深度是否相同,这里没考虑网络卷积之后的大小是否跟原始大小一样的! with tf.variable_scope('conv1_in_block'): if first_block: filter = create_variables(name='conv', shape=[3, 3, input_channel, output_channel]) conv1 = tf.nn.conv2d(input_layer, filter, strides=[1, stride, stride, 1], padding='SAME') else: conv1 = bn_relu_conv_layer(input_layer, [3, 3, input_channel, output_channel], stride, dilation) with tf.variable_scope('conv2_in_block'): conv2 = bn_relu_conv_layer(conv1, [3, 3, output_channel, output_channel], stride, dilation) # mid_layer=bn_relu_conv_layer(input_layer,[3,3],stride,dilation=dilation) # out_layer=bn_relu_conv_layer(mid_layer,[3,3],stride,dilation=dilation) if input_channel != output_channel: filter = create_variables(name='Unichannel', shape=[1, 1, input_channel, output_channel]) input_layer = tf.nn.conv2d(input_layer, filter, strides=[1, 1, 1, 1], padding='SAME') result = tf.add(input_layer, conv2) return result def inference(input_layer): #下面按照那个结构进行相应的搭建框架的结构如下所示:[batch,h,w,3]出去的时候也应该是[batch,h,w,3] """ 这下面的数字以后会改的 """ input_channel=input_layer.get_shape().as_list()[-1] input_w=input_layer.get_shape().as_list()[2] input_h=input_layer.get_shape().as_list()[1] #[7,7,16] with tf.variable_scope('DRN_1'): filter=create_variables(name='DRN_1_va',shape=[7,7,input_channel,16]) DRN_1=tf.nn.conv2d(input_layer,filter,strides=[1,1,1,1],padding='SAME') DRN_1=tf.nn.relu(DRN_1) with tf.variable_scope('DRN_2'): DRN_2=residual_block(DRN_1,16,dilation=1,stride=1,first_block=False) # [3,3,32]+[3,3,32]的残差网络的设,stride设计为2相当于进行了降采样的操作 with tf.variable_scope('DRN_3'):
DRN_5=residual_block(DRN_4,128,dilation=1,stride=1,first_block=False) with tf.variable_scope('DRN_5_2'): DRN_5=residual_block(DRN_5,128,dilation=1,stride=1,first_block=False) # [3,3,256]+[3,3,256]的残差网络的设,stride设计为2相当于进行了降采样的操作 with tf.variable_scope('DRN_6_1'): DRN_6 = residual_block(DRN_5, 256, dilation=2, stride=1, first_block=False) with tf.variable_scope('DRN_6_2'): DRN_6 = residual_block(DRN_5, 256, dilation=2, stride=1, first_block=False) #DRN_6=tf.nn.sigmoid(DRN_6) return DRN_6 # -*- coding: utf-8 -*- """ Created on Fri Aug 10 21:39:20 2018 @author: dell """ tf.reset_default_graph() # image_path = r'D:/Deeplearning_Demo/image/IMG_1_0.jpg'#绝对路径 # label_path=r'IMG_output_1_0.npy' # xia_path="ddddd" Image_File_dir = "D:/Deeplearning_Demo/image" Label_File_dir = "D:/Deeplearning_Demo/label" """ Image_File_dir = "D:/Deeplearning_Demo/TensorFlow_demo/Ours_crowd_counting/output/crop_image" Label_File_dir = "D:/Deeplearning_Demo/TensorFlow_demo/Ours_crowd_counting/output/crop_groundtruth" """ Image_list = [] Label_list = [] learning_rate = 0.01 # 这里为什么会出问题? # batch_size=2 each_step = 10 # 定义存储路径 ckpt_dir = "./model" if not os.path.exists(ckpt_dir): os.makedirs(ckpt_dir) # 得到了一些相应的文件名称,便于下一次调用 def get_files(file_dir, label_dir): for file in os.listdir(file_dir): Image_list
DRN_3 = residual_block(DRN_2, 32, dilation=1, stride=1, first_block=False) with tf.variable_scope('DRN_4_2'): DRN_4 = residual_block(DRN_3, 64, dilation=1, stride=1, first_block=False) with tf.variable_scope('DRN_5_1'):
random_line_split
print_test.py
_channel, output_channel]) conv1 = tf.nn.conv2d(input_layer, filter, strides=[1, stride, stride, 1], padding='SAME') else: conv1 = bn_relu_conv_layer(input_layer, [3, 3, input_channel, output_channel], stride, dilation) with tf.variable_scope('conv2_in_block'): conv2 = bn_relu_conv_layer(conv1, [3, 3, output_channel, output_channel], stride, dilation) # mid_layer=bn_relu_conv_layer(input_layer,[3,3],stride,dilation=dilation) # out_layer=bn_relu_conv_layer(mid_layer,[3,3],stride,dilation=dilation) if input_channel != output_channel: filter = create_variables(name='Unichannel', shape=[1, 1, input_channel, output_channel]) input_layer = tf.nn.conv2d(input_layer, filter, strides=[1, 1, 1, 1], padding='SAME') result = tf.add(input_layer, conv2) return result def inference(input_layer): #下面按照那个结构进行相应的搭建框架的结构如下所示:[batch,h,w,3]出去的时候也应该是[batch,h,w,3] """ 这下面的数字以后会改的 """ input_channel=input_layer.get_shape().as_list()[-1] input_w=input_layer.get_shape().as_list()[2] input_h=input_layer.get_shape().as_list()[1] #[7,7,16] with tf.variable_scope('DRN_1'): filter=create_variables(name='DRN_1_va',shape=[7,7,input_channel,16]) DRN_1=tf.nn.conv2d(input_layer,filter,strides=[1,1,1,1],padding='SAME') DRN_1=tf.nn.relu(DRN_1) with tf.variable_scope('DRN_2'): DRN_2=residual_block(DRN_1,16,dilation=1,stride=1,first_block=False) # [3,3,32]+[3,3,32]的残差网络的设,stride设计为2相当于进行了降采样的操作 with tf.variable_scope('DRN_3'): DRN_3 = residual_block(DRN_2, 32, dilation=1, stride=1, first_block=False) with tf.variable_scope('DRN_4_2'): DRN_4 = residual_block(DRN_3, 64, dilation=1, stride=1, first_block=False) with tf.variable_scope('DRN_5_1'): DRN_5=residual_block(DRN_4,128,dilation=1,stride=1,first_block=False) with tf.variable_scope('DRN_5_2'): DRN_5=residual_block(DRN_5,128,dilation=1,stride=1,first_block=False) # [3,3,256]+[3,3,256]的残差网络的设,stride设计为2相当于进行了降采样的操作 with tf.variable_scope('DRN_6_1'): DRN_6 = residual_block(DRN_5, 256, dilation=2, stride=1, first_block=False) with tf.variable_scope('DRN_6_2'): DRN_6 = residual_block(DRN_5, 256, dilation=2, stride=1, first_block=False) #DRN_6=tf.nn.sigmoid(DRN_6) return DRN_6 # -*- coding: utf-8 -*- """ Created on Fri Aug 10 21:39:20 2018 @author: dell """ tf.reset_default_graph() # image_path = r'D:/Deeplearning_Demo/image/IMG_1_0.jpg'#绝对路径 # label_path=r'IMG_output_1_0.npy' # xia_path="ddddd" Image_File_dir = "D:/Deeplearning_Demo/image" Label_File_dir = "D:/Deeplearning_Demo/label" """ Image_File_dir = "D:/Deeplearning_Demo/TensorFlow_demo/Ours_crowd_counting/output/crop_image" Label_File_dir = "D:/Deeplearning_Demo/TensorFlow_demo/Ours_crowd_counting/output/crop_groundtruth" """ Image_list = [] Label_list = [] learning_rate = 0.01 # 这里为什么会出问题? # batch_size=2 each_step = 10 # 定义存储路径 ckpt_dir = "./model" if not os.path.exists(ckpt_dir): os.makedirs(ckpt_dir) # 得到了一些相应的文件名称,便于下一次调用 def get_files(file_dir, label_dir): for file in os.listdir(file_dir): Image_list.append(file_dir + '/' + file) print(Image_list) for file in os.listdir(label_dir): Label_list.append(label_dir + '/' + file) # 损失函数的计算方法是什么,这里我们进行相应的改进比如可以改进成一些方差的计算方法等等 def loss(y, pred_y): loss = tf.reduce_sum(tf.square(y - pred_y)) return loss get_files(Image_File_dir, Label_File_dir) image_path = tf.convert_to_tensor(Image_list) label_path = tf.convert_to_tensor(Label_list) print("start") # file_queue = tf.train.string_input_producer([image_path]) #创建输入队列 file_queue = tf.train.slice_input_producer([image_path, label_path], shuffle=False) # image = tf.train.slice_input_producer([[image_path] ]) file_queue = tf.convert_to_tensor(file_queue) # file_queue[0]= tf.convert_to_tensor(file_queue[0]) # reader = tf.WholeFileReader() # key,image = reader.read(file_queue) """ 图像数据 """ image = tf.read_file(file_queue[0]) # reader读取序列 image = tf.image.decode_jpeg(image, channels=3) # 解码,tensor image = tf.image.resize_images(image, [240, 240]) image = tf.image.per_image_standardization(image) """ 标签数据 """ label = tf.read_file(file_queue[1]) # reader读取序列 # 读出的 value 是 string,现在转换为 uint8 型的向量 record_bytes = tf.decode_raw(label, tf.float32) depth_major = tf.reshape(tf.slice(record_bytes, [20], [240 * 240 * 1]), [1, 240, 240]) # depth, height, width print("done") uint8image = tf.transpose(depth_major, [1, 2, 0]) label = tf.cast(uint8image, tf.float32)/30000 """这里需要用参数进行设计""" image_batch, label_batch = tf.train.batch([image, label], batch_size=batch_size, num_threads=1, capacity=10000) predict_map= inference(image_batch) print("验证的结果:", predict_map, label_batch) # saving and loading networks # 保存模型的参数等等 with tf.Session() as sess: sess.run(tf.local_variables_initializer()) sess.run(tf.global_variables_initializer()) coord = tf.train.Coordinator() # 协同启动的线程 threads = tf.train.start_queue_runners(sess=sess, coord=coord) # 启动线程运行队列 # 保存模型 # 下面开始循环的过程 for i in range(100): # 应用到的网络结构 print("i的数字为:", i) #losses = sess.run(loss_result) # saver.save(sess, ckpt_dir+"/my-model.ckpt", global_step=i) # 接下来显示训练一段时间的测试结果如何,来判断这种方法是否应该用的 [image, label] = sess.run([image_batch, label_batch]) print(image.shape) print(label.shape) print("jieguo:", label[:, 1:10, 1:10, :]) print(type(image)) # tensor # 转换了图片的类型 image = tf.squeeze(image[0:1, :, :, :]).eval() print("image_type", type(image)) # ndarray print("image:", image) print(image.shape) # 240×320×3 image = tf.cast(image, tf.uint8).eval() print("image.dtype:", image.dtype) # uint8 plt.figure(i) plt.imshow(image) plt.show() # 现在要转换原始的label以及生成的结果 label = tf.squeeze(label[0:1, :, :, :]).eval() print("label_type", type(label)) # ndarray print(label.shape) #
240×320×3 # label = tf.cast(label, tf.float32).eval() # print("label.dtype:", label.dtype) # uint8 # 开始转换一下生成结果 # 显示原始数据的分布是什么 i0 = Image.fromarray(label) # plt.figure(i+1) result = i0.show()
conditional_block
print_test.py
) if dilation == 1: conv_layer = tf.nn.conv2d(input_layer, filter, strides=[1, stride, stride, 1], padding='SAME') elif dilation == 2: conv_layer = tf.nn.atrous_conv2d(value=input_layer, filters=filter, rate=2, padding='SAME') elif dilation == 4: conv_layer = tf.nn.atrous_conv2d(value=input_layer, filters=filter, rate=4, padding='SAME') else: raise ValueError('no dilation is choosen!!!') bn_layer = batch_normalization_layer(conv_layer, out_channel) output = tf.nn.relu(bn_layer) return output # 我们采用这个基础网络结构 def bn_relu_conv_layer(input_layer, filter_shape, stride=1, dilation=1): ''' A helper function to batch normalize, relu and conv the input layer sequentially :param input_layer: 4D tensor :param filter_shape: list. [filter_height, filter_width, filter_depth, filter_number] :param stride: stride size for conv :return: 4D tensor. Y = conv(Relu(batch_normalize(X))) ''' in_channel = input_layer.get_shape().as_list()[-1] bn_layer = batch_normalization_layer(input_layer, in_channel) relu_layer = tf.nn.relu(bn_layer) filter = create_variables(name='conv', shape=filter_shape) # 这里进行卷积操作的一个很重要的部分,选择卷积的方式是什么,其中有1,2,4 if dilation == 1: conv_layer = tf.nn.conv2d(relu_layer, filter, strides=[1, stride, stride, 1], padding='SAME') elif dilation == 2: conv_layer = tf.nn.atrous_conv2d(value=relu_layer, filters=filter, rate=2, padding='SAME') elif dilation == 4: conv_layer = tf.nn.atrous_conv2d(value=relu_layer, filters=filter, rate=4, padding='SAME') else: raise ValueError('no dilation is choosen!!!') return conv_layer # 开始构造block的结构过程 def residual_block(input_layer, output_channel, dilation=1, stride=1, first_block=False): ''' Defines a residual block in ResNet :param input_layer: 4D tensor :param output_channel: int. return_tensor.get_shape().as_list()[-1] = output_channel :param first_block: if this is the first residual block of the whole network :return: 4D tensor. ''' input_channel = input_layer.get_shape().as_list()[-1] # 按照正常的网络结构 # 我们选择先bath 然后进行卷积和relu的操作 # Y = conv(Relu(batch_normalize(X))) # bn_relu_conv_layer(input_layer,filter_shape,stride,dilation=1) ''' 设置残差网络的模板的第一层 ''' # 这里进行查看输入输出维度以及深度是否相同,这里没考虑网络卷积之后的大小是否跟原始大小一样的! with tf.variable_scope('conv1_in_block'): if first_block: filter = create_variables(name='conv', shape=[3, 3, input_channel, output_channel]) conv1 = tf.nn.conv2d(input_layer, filter, strides=[1, stride, stride, 1], padding='SAME') else: conv1 = bn_relu_conv_layer(input_layer, [3, 3, input_channel, output_channel], stride, dilation) with tf.variable_scope('conv2_in_block'): conv2 = bn_relu_conv_layer(conv1, [3, 3, output_channel, output_channel], stride, dilation) # mid_layer=bn_relu_conv_layer(input_layer,[3,3],stride,dilation=dilation) # out_layer=bn_relu_conv_layer(mid_layer,[3,3],stride,dilation=dilation) if input_channel != output_channel: filter = create_variables(name='Unichannel', shape=[1, 1, input_channel, output_channel]) input_layer = tf.nn.conv2d(input_layer, filter, strides=[1, 1, 1, 1], padding='SAME') result = tf.add(input_layer, conv2) return result def inference(input_layer): #下面按照那个结构进行相应的搭建框架的结构如下所示:[batch,h,w,3]出去的时候也应该是[batch,h,w,3] """ 这下面的数字以后会改的 """ input_channel=input_layer.get_shape().as_list()[-1] input_w=input_layer.get_shape().as_list()[2] input_h=input_layer.get_shape().as_list()[1] #[7,7,16] with tf.variable_scope('DRN_1'): filter=create_variables(name='DRN_1_va',shape=[7,7,input_channel,16]) DRN_1=tf.nn.conv2d(input_layer,filter,strides=[1,1,1,1],padding='SAME') DRN_1=tf.nn.relu(DRN_1) with tf.variable_scope('DRN_2'): DRN_2=residual_block(DRN_1,16,dilation=1,stride=1,first_block=False) # [3,3,32]+[3,3,32]的残差网络的设,stride设计为2相当于进行了降采样的操作 with tf.variable_scope('DRN_3'): DRN_3 = residual_block(DRN_2, 32, dilation=1, stride=1, first_block=False) with tf.variable_scope('DRN_4_2'): DRN_4 = residual_block(DRN_3, 64, dilation=1, stride=1, first_block=False) with tf.variable_scope('DRN_5_1'): DRN_5=residual_block(DRN_4,128,dilation=1,stride=1,first_block=False) with tf.variable_scope('DRN_5_2'): DRN_5=residual_block(DRN_5,128,dilation=1,stride=1,first_block=False) # [3,3,256]+[3,3,256]的残差网络的设,stride设计为2相当于进行了降采样的操作 with tf.variable_scope('DRN_6_1'): DRN_6 = residual_block(DRN_5, 256, dilation=2, stride=1, first_block=False) with tf.variable_scope('DRN_6_2'): DRN_6 = residual_block(DRN_5, 256, dilation=2, stride=1, first_block=False) #DRN_6=tf.nn.sigmoid(DRN_6) return DRN_6 # -*- coding: utf-8 -*- """ Created on Fri Aug 10 21:39:20 2018 @author: dell """ tf.reset_default_graph() # image_path = r'D:/Deeplearning_Demo/image/IMG_1_0.jpg'#绝对路径 # label_path=r'IMG_output_1_0.npy' # xia_path="ddddd" Image_File_dir = "D:/Deeplearning_Demo/image" Label_File_dir = "D:/Deeplearning_Demo/label" """ Image_File_dir = "D:/Deeplearning_Demo/TensorFlow_demo/Ours_crowd_counting/output/crop_image" Label_File_dir = "D:/Deeplearning_Demo/TensorFlow_demo/Ours_crowd_counting/output/crop_groundtruth" """ Image_list = [] Label_list = [] learning_rate = 0.01 # 这里为什么会出问题? # batch_size=2 each_step = 10 # 定义存储路径 ckpt_dir = "./model" if not os.path.exists(ckpt_dir): os.makedirs(ckpt_dir) # 得到了一些相应的文件名称,便于下一次调用 def get_files(file_dir, label_dir): for file in os.listdir(file_dir): Image_list.append(file_dir + '/' + file) print(Image_list) for file in os.listdir(label_dir): Label_list.append(label_dir + '/' + file) # 损失函数的计算方法是什么,这里我们进行相应的改进比如可以改进成一些方差的计算方法等等 def loss(y, pred_y): loss = tf.reduce_sum(tf.square(y - pred_y)) return loss get_files(Image_File_dir, Label_File_dir) image_path = tf.convert_to_tensor(Image_list) label_path = tf.convert_to_tensor(Label_list) print("start") # file_queue = tf.train.string_input_producer([image_path]) #创建输入队列 file_queue = tf.train.slice_input_producer([image_path, label_path], shuffle=False) # image = tf.train.slice_input_producer([[image_path] ]) file_queue = tf.convert_to_tensor(file_queue) # file_queue[0]= tf.convert_to_tensor(file_queue[0]) # reader = tf.WholeFileReader() # key,image = reader.read(file_queue) """ 图像数据 """ image = tf.read_file(file_queue[0]) # reader读取序列 image = tf.image.decode_jpeg(image, channels=3)
# 解码
identifier_name
print_test.py
D tensor after being normalized ''' mean, varience = tf.nn.moments(input_layer, axes=[0, 1, 2]) beta = tf.get_variable('beta', dimension, tf.float32, initializer=tf.constant_initializer(0.0, tf.float32)) gamma = tf.get_variable('gamma', dimension, tf.float32, initializer=tf.constant_initializer(1.0, tf.float32)) bn_layer = tf.nn.batch_normalization(input_layer, mean, varience, beta, gamma, BN_EPSILON) return bn_layer # 在这里进行相应的修改操作吧? def conv_bn_relu_layer(input_layer, filter_shape, stride, dilation=1): ''' A helper function to conv, batch normalize and relu the input tensor sequentially :param input_layer: 4D tensor :param filter_shape: list. [filter_height, filter_width, filter_depth, filter_number] :param stride: stride size for conv :return: 4D tensor. Y = Relu(batch_normalize(conv(X))) ''' out_channel = filter_shape[-1] filter = create_variables(name='conv', shape=filter_shape) if dilation == 1: conv_layer = tf.nn.conv2d(input_layer, filter, strides=[1, stride, stride, 1], padding='SAME') elif dilation == 2: conv_layer = tf.nn.atrous_conv2d(value=input_layer, filters=filter, rate=2, padding='SAME') elif dilation == 4: conv_layer = tf.nn.atrous_conv2d(value=input_layer, filters=filter, rate=4, padding='SAME') else: raise ValueError('no dilation is choosen!!!') bn_layer = batch_normalization_layer(conv_layer, out_channel) output = tf.nn.relu(bn_layer) return output # 我们采用这个基础网络结构 def bn_relu_conv_layer(input_layer, filter_shape, stride=1, dilation=1): ''' A helper function to batch normalize, relu and conv the input layer sequentially :param input_layer: 4D tensor :param filter_shape: list. [filter_height, filter_width, filter_depth, filter_number] :param stride: stride size for conv :return: 4D tensor. Y = conv(Relu(batch_normalize(X))) ''' in_channel = input_layer.get_shape().as_list()[-1] bn_layer = batch_normalization_layer(input_layer, in_channel) relu_layer = tf.nn.relu(bn_layer) filter = create_variables(name='conv', shape=filter_shape) # 这里进行卷积操作的一个很重要的部分,选择卷积的方式是什么,其中有1,2,4 if dilation == 1: conv_layer = tf.nn.conv2d(relu_layer, filter, strides=[1, stride, stride, 1], padding='SAME') elif dilation == 2: conv_layer = tf.nn.atrous_conv2d(value=relu_layer, filters=filter, rate=2, padding='SAME') elif dilation == 4: conv_layer = tf.nn.atrous_conv2d(value=relu_layer, filters=filter, rate=4, padding='SAME') else: raise ValueError('no dilation is choosen!!!') return conv_layer # 开始构造block的结构过程 def residual_block(input_layer, output_channel, dilation=1, stride=1, first_block=False): ''' Defines a residual block in ResNet :param input_layer: 4D tensor :param output_channel: int. return_tensor.get_shape().as_list()[-1] = output_channel :param first_block: if this is the first residual block of the whole n
conv1 = tf.nn.conv2d(input_layer, filter, strides=[1, stride, stride, 1], padding='SAME') else: conv1 = bn_relu_conv_layer(input_layer, [3, 3, input_channel, output_channel], stride, dilation) with tf.variable_scope('conv2_in_block'): conv2 = bn_relu_conv_layer(conv1, [3, 3, output_channel, output_channel], stride, dilation) # mid_layer=bn_relu_conv_layer(input_layer,[3,3],stride,dilation=dilation) # out_layer=bn_relu_conv_layer(mid_layer,[3,3],stride,dilation=dilation) if input_channel != output_channel: filter = create_variables(name='Unichannel', shape=[1, 1, input_channel, output_channel]) input_layer = tf.nn.conv2d(input_layer, filter, strides=[1, 1, 1, 1], padding='SAME') result = tf.add(input_layer, conv2) return result def inference(input_layer): #下面按照那个结构进行相应的搭建框架的结构如下所示:[batch,h,w,3]出去的时候也应该是[batch,h,w,3] """ 这下面的数字以后会改的 """ input_channel=input_layer.get_shape().as_list()[-1] input_w=input_layer.get_shape().as_list()[2] input_h=input_layer.get_shape().as_list()[1] #[7,7,16] with tf.variable_scope('DRN_1'): filter=create_variables(name='DRN_1_va',shape=[7, 7,input_channel,16]) DRN_1=tf.nn.conv2d(input_layer,filter,strides=[1,1,1,1],padding='SAME') DRN_1=tf.nn.relu(DRN_1) with tf.variable_scope('DRN_2'): DRN_2=residual_block(DRN_1,16,dilation=1,stride=1,first_block=False) # [3,3,32]+[3,3,32]的残差网络的设,stride设计为2相当于进行了降采样的操作 with tf.variable_scope('DRN_3'): DRN_3 = residual_block(DRN_2, 32, dilation=1, stride=1, first_block=False) with tf.variable_scope('DRN_4_2'): DRN_4 = residual_block(DRN_3, 64, dilation=1, stride=1, first_block=False) with tf.variable_scope('DRN_5_1'): DRN_5=residual_block(DRN_4,128,dilation=1,stride=1,first_block=False) with tf.variable_scope('DRN_5_2'): DRN_5=residual_block(DRN_5,128,dilation=1,stride=1,first_block=False) # [3,3,256]+[3,3,256]的残差网络的设,stride设计为2相当于进行了降采样的操作 with tf.variable_scope('DRN_6_1'): DRN_6 = residual_block(DRN_5, 256, dilation=2, stride=1, first_block=False) with tf.variable_scope('DRN_6_2'): DRN_6 = residual_block(DRN_5, 256, dilation=2, stride=1, first_block=False) #DRN_6=tf.nn.sigmoid(DRN_6) return DRN_6 # -*- coding: utf-8 -*- """ Created on Fri Aug 10 21:39:20 2018 @author: dell """ tf.reset_default_graph() # image_path = r'D:/Deeplearning_Demo/image/IMG_1_0.jpg'#绝对路径 # label_path=r'IMG_output_1_0.npy' # xia_path="ddddd" Image_File_dir = "D:/Deeplearning_Demo/image" Label_File_dir = "D:/Deeplearning_Demo/label" """ Image_File_dir = "D:/Deeplearning_Demo/TensorFlow_demo/Ours_crowd_counting/output/crop_image" Label_File_dir = "D:/Deeplearning_Demo/TensorFlow_demo/Ours_crowd_counting/output/crop_groundtruth" """ Image_list = [] Label_list = [] learning_rate = 0.01 # 这里为什么会出问题? # batch_size=2 each_step = 10 # 定义存储路径 ckpt_dir = "./model" if not os.path.exists(ckpt_dir): os.makedirs(ckpt_dir) # 得到了一些相应的文件名称,便于下一次调用 def get_files(file_dir, label_dir): for file in os.listdir(file_dir): Image_list
etwork :return: 4D tensor. ''' input_channel = input_layer.get_shape().as_list()[-1] # 按照正常的网络结构 # 我们选择先bath 然后进行卷积和relu的操作 # Y = conv(Relu(batch_normalize(X))) # bn_relu_conv_layer(input_layer,filter_shape,stride,dilation=1) ''' 设置残差网络的模板的第一层 ''' # 这里进行查看输入输出维度以及深度是否相同,这里没考虑网络卷积之后的大小是否跟原始大小一样的! with tf.variable_scope('conv1_in_block'): if first_block: filter = create_variables(name='conv', shape=[3, 3, input_channel, output_channel])
identifier_body
push_active_set.rs
: &Pubkey, // This node. node: &Pubkey, // Gossip node. origins: &[Pubkey], // CRDS value owners. stakes: &HashMap<Pubkey, u64>, ) { let stake = stakes.get(pubkey); for origin in origins { if origin == pubkey { continue; } let stake = stake.min(stakes.get(origin)); self.get_entry(stake).prune(node, origin) } } pub(crate) fn rotate<R: Rng>( &mut self, rng: &mut R, size: usize, // Number of nodes to retain in each active-set entry. cluster_size: usize, // Gossip nodes to be sampled for each push active set. nodes: &[Pubkey], stakes: &HashMap<Pubkey, u64>, ) { let num_bloom_filter_items = cluster_size.max(Self::MIN_NUM_BLOOM_ITEMS); // Active set of nodes to push to are sampled from these gossip nodes, // using sampling probabilities obtained from the stake bucket of each // node. let buckets: Vec<_> = nodes .iter() .map(|node| get_stake_bucket(stakes.get(node))) .collect(); // (k, entry) represents push active set where the stake bucket of // min stake of {this node, crds value owner} // is equal to `k`. The `entry` maintains set of gossip nodes to // actively push to for crds values belonging to this bucket. for (k, entry) in self.0.iter_mut().enumerate() { let weights: Vec<u64> = buckets .iter() .map(|&bucket| { // bucket <- get_stake_bucket(min stake of { // this node, crds value owner and gossip peer // }) // weight <- (bucket + 1)^2 // min stake of {...} is a proxy for how much we care about // the link, and tries to mirror similar logic on the // receiving end when pruning incoming links: // https://github.com/solana-labs/solana/blob/81394cf92/gossip/src/received_cache.rs#L100-L105 let bucket = bucket.min(k) as u64; bucket.saturating_add(1).saturating_pow(2) }) .collect(); entry.rotate(rng, size, num_bloom_filter_items, nodes, &weights); } } fn get_entry(&self, stake: Option<&u64>) -> &PushActiveSetEntry
} impl PushActiveSetEntry { const BLOOM_FALSE_RATE: f64 = 0.1; const BLOOM_MAX_BITS: usize = 1024 * 8 * 4; fn get_nodes<'a>( &'a self, origin: &'a Pubkey, // If true forces gossip push even if the node has pruned the origin. mut should_force_push: impl FnMut(&Pubkey) -> bool + 'a, ) -> impl Iterator<Item = &Pubkey> + 'a { self.0 .iter() .filter(move |(node, bloom_filter)| { !bloom_filter.contains(origin) || should_force_push(node) }) .map(|(node, _bloom_filter)| node) } fn prune( &self, node: &Pubkey, // Gossip node. origin: &Pubkey, // CRDS value owner ) { if let Some(bloom_filter) = self.0.get(node) { bloom_filter.add(origin); } } fn rotate<R: Rng>( &mut self, rng: &mut R, size: usize, // Number of nodes to retain. num_bloom_filter_items: usize, nodes: &[Pubkey], weights: &[u64], ) { debug_assert_eq!(nodes.len(), weights.len()); debug_assert!(weights.iter().all(|&weight| weight != 0u64)); let shuffle = WeightedShuffle::new("rotate-active-set", weights).shuffle(rng); for node in shuffle.map(|k| &nodes[k]) { // We intend to discard the oldest/first entry in the index-map. if self.0.len() > size { break; } if self.0.contains_key(node) { continue; } let bloom = AtomicBloom::from(Bloom::random( num_bloom_filter_items, Self::BLOOM_FALSE_RATE, Self::BLOOM_MAX_BITS, )); bloom.add(node); self.0.insert(*node, bloom); } // Drop the oldest entry while preserving the ordering of others. while self.0.len() > size { self.0.shift_remove_index(0); } } } // Maps stake to bucket index. fn get_stake_bucket(stake: Option<&u64>) -> usize { let stake = stake.copied().unwrap_or_default() / LAMPORTS_PER_SOL; let bucket = u64::BITS - stake.leading_zeros(); (bucket as usize).min(NUM_PUSH_ACTIVE_SET_ENTRIES - 1) } #[cfg(test)] mod tests { use {super::*, rand::SeedableRng, rand_chacha::ChaChaRng, std::iter::repeat_with}; #[test] fn test_get_stake_bucket() { assert_eq!(get_stake_bucket(None), 0); let buckets = [0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5]; for (k, bucket) in buckets.into_iter().enumerate() { let stake = (k as u64) * LAMPORTS_PER_SOL; assert_eq!(get_stake_bucket(Some(&stake)), bucket); } for (stake, bucket) in [ (4_194_303, 22), (4_194_304, 23), (8_388_607, 23), (8_388_608, 24), ] { let stake = stake * LAMPORTS_PER_SOL; assert_eq!(get_stake_bucket(Some(&stake)), bucket); } assert_eq!( get_stake_bucket(Some(&u64::MAX)), NUM_PUSH_ACTIVE_SET_ENTRIES - 1 ); } #[test] fn test_push_active_set() { const CLUSTER_SIZE: usize = 117; const MAX_STAKE: u64 = (1 << 20) * LAMPORTS_PER_SOL; let mut rng = ChaChaRng::from_seed([189u8; 32]); let pubkey = Pubkey::new_unique(); let nodes: Vec<_> = repeat_with(Pubkey::new_unique).take(20).collect(); let stakes = repeat_with(|| rng.gen_range(1..MAX_STAKE)); let mut stakes: HashMap<_, _> = nodes.iter().copied().zip(stakes).collect(); stakes.insert(pubkey, rng.gen_range(1..MAX_STAKE)); let mut active_set = PushActiveSet::default(); assert!(active_set.0.iter().all(|entry| entry.0.is_empty())); active_set.rotate(&mut rng, 5, CLUSTER_SIZE, &nodes, &stakes); assert!(active_set.0.iter().all(|entry| entry.0.len() == 5)); // Assert that for all entries, each filter already prunes the key. for entry in &active_set.0 { for (node, filter) in entry.0.iter() { assert!(filter.contains(node)); } } let other = &nodes[5]; let origin = &nodes[17]; assert!(active_set .get_nodes(&pubkey, origin, |_| false, &stakes) .eq([13, 5, 18, 16, 0].into_iter().map(|k| &nodes[k]))); assert!(active_set .get_nodes(&pubkey, other, |_| false, &stakes) .eq([13, 18, 16, 0].into_iter().map(|k| &nodes[k]))); active_set.prune(&pubkey, &nodes[5], &[*origin], &stakes); active_set.prune(&pubkey, &nodes[3], &[*origin], &stakes); active_set.prune(&pubkey, &nodes[16], &[*origin], &stakes); assert!(active_set .get_nodes(&pubkey, origin, |_| false, &stakes) .eq([13, 18, 0].into_iter().map(|k| &nodes[k]))); assert!(active_set .get_nodes(&pubkey, other, |_| false, &stakes) .eq([13, 18, 16, 0].into_iter
{ &self.0[get_stake_bucket(stake)] }
identifier_body
push_active_set.rs
: &Pubkey, // This node. node: &Pubkey, // Gossip node. origins: &[Pubkey], // CRDS value owners. stakes: &HashMap<Pubkey, u64>, ) { let stake = stakes.get(pubkey); for origin in origins { if origin == pubkey { continue; } let stake = stake.min(stakes.get(origin)); self.get_entry(stake).prune(node, origin) } } pub(crate) fn rotate<R: Rng>( &mut self, rng: &mut R, size: usize, // Number of nodes to retain in each active-set entry. cluster_size: usize, // Gossip nodes to be sampled for each push active set. nodes: &[Pubkey], stakes: &HashMap<Pubkey, u64>, ) { let num_bloom_filter_items = cluster_size.max(Self::MIN_NUM_BLOOM_ITEMS); // Active set of nodes to push to are sampled from these gossip nodes, // using sampling probabilities obtained from the stake bucket of each // node. let buckets: Vec<_> = nodes .iter() .map(|node| get_stake_bucket(stakes.get(node))) .collect(); // (k, entry) represents push active set where the stake bucket of // min stake of {this node, crds value owner} // is equal to `k`. The `entry` maintains set of gossip nodes to // actively push to for crds values belonging to this bucket. for (k, entry) in self.0.iter_mut().enumerate() { let weights: Vec<u64> = buckets .iter() .map(|&bucket| { // bucket <- get_stake_bucket(min stake of { // this node, crds value owner and gossip peer // }) // weight <- (bucket + 1)^2 // min stake of {...} is a proxy for how much we care about // the link, and tries to mirror similar logic on the // receiving end when pruning incoming links: // https://github.com/solana-labs/solana/blob/81394cf92/gossip/src/received_cache.rs#L100-L105 let bucket = bucket.min(k) as u64; bucket.saturating_add(1).saturating_pow(2) }) .collect(); entry.rotate(rng, size, num_bloom_filter_items, nodes, &weights); } } fn get_entry(&self, stake: Option<&u64>) -> &PushActiveSetEntry { &self.0[get_stake_bucket(stake)] } } impl PushActiveSetEntry { const BLOOM_FALSE_RATE: f64 = 0.1; const BLOOM_MAX_BITS: usize = 1024 * 8 * 4; fn get_nodes<'a>( &'a self, origin: &'a Pubkey, // If true forces gossip push even if the node has pruned the origin. mut should_force_push: impl FnMut(&Pubkey) -> bool + 'a, ) -> impl Iterator<Item = &Pubkey> + 'a { self.0 .iter() .filter(move |(node, bloom_filter)| { !bloom_filter.contains(origin) || should_force_push(node) }) .map(|(node, _bloom_filter)| node) } fn
( &self, node: &Pubkey, // Gossip node. origin: &Pubkey, // CRDS value owner ) { if let Some(bloom_filter) = self.0.get(node) { bloom_filter.add(origin); } } fn rotate<R: Rng>( &mut self, rng: &mut R, size: usize, // Number of nodes to retain. num_bloom_filter_items: usize, nodes: &[Pubkey], weights: &[u64], ) { debug_assert_eq!(nodes.len(), weights.len()); debug_assert!(weights.iter().all(|&weight| weight != 0u64)); let shuffle = WeightedShuffle::new("rotate-active-set", weights).shuffle(rng); for node in shuffle.map(|k| &nodes[k]) { // We intend to discard the oldest/first entry in the index-map. if self.0.len() > size { break; } if self.0.contains_key(node) { continue; } let bloom = AtomicBloom::from(Bloom::random( num_bloom_filter_items, Self::BLOOM_FALSE_RATE, Self::BLOOM_MAX_BITS, )); bloom.add(node); self.0.insert(*node, bloom); } // Drop the oldest entry while preserving the ordering of others. while self.0.len() > size { self.0.shift_remove_index(0); } } } // Maps stake to bucket index. fn get_stake_bucket(stake: Option<&u64>) -> usize { let stake = stake.copied().unwrap_or_default() / LAMPORTS_PER_SOL; let bucket = u64::BITS - stake.leading_zeros(); (bucket as usize).min(NUM_PUSH_ACTIVE_SET_ENTRIES - 1) } #[cfg(test)] mod tests { use {super::*, rand::SeedableRng, rand_chacha::ChaChaRng, std::iter::repeat_with}; #[test] fn test_get_stake_bucket() { assert_eq!(get_stake_bucket(None), 0); let buckets = [0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5]; for (k, bucket) in buckets.into_iter().enumerate() { let stake = (k as u64) * LAMPORTS_PER_SOL; assert_eq!(get_stake_bucket(Some(&stake)), bucket); } for (stake, bucket) in [ (4_194_303, 22), (4_194_304, 23), (8_388_607, 23), (8_388_608, 24), ] { let stake = stake * LAMPORTS_PER_SOL; assert_eq!(get_stake_bucket(Some(&stake)), bucket); } assert_eq!( get_stake_bucket(Some(&u64::MAX)), NUM_PUSH_ACTIVE_SET_ENTRIES - 1 ); } #[test] fn test_push_active_set() { const CLUSTER_SIZE: usize = 117; const MAX_STAKE: u64 = (1 << 20) * LAMPORTS_PER_SOL; let mut rng = ChaChaRng::from_seed([189u8; 32]); let pubkey = Pubkey::new_unique(); let nodes: Vec<_> = repeat_with(Pubkey::new_unique).take(20).collect(); let stakes = repeat_with(|| rng.gen_range(1..MAX_STAKE)); let mut stakes: HashMap<_, _> = nodes.iter().copied().zip(stakes).collect(); stakes.insert(pubkey, rng.gen_range(1..MAX_STAKE)); let mut active_set = PushActiveSet::default(); assert!(active_set.0.iter().all(|entry| entry.0.is_empty())); active_set.rotate(&mut rng, 5, CLUSTER_SIZE, &nodes, &stakes); assert!(active_set.0.iter().all(|entry| entry.0.len() == 5)); // Assert that for all entries, each filter already prunes the key. for entry in &active_set.0 { for (node, filter) in entry.0.iter() { assert!(filter.contains(node)); } } let other = &nodes[5]; let origin = &nodes[17]; assert!(active_set .get_nodes(&pubkey, origin, |_| false, &stakes) .eq([13, 5, 18, 16, 0].into_iter().map(|k| &nodes[k]))); assert!(active_set .get_nodes(&pubkey, other, |_| false, &stakes) .eq([13, 18, 16, 0].into_iter().map(|k| &nodes[k]))); active_set.prune(&pubkey, &nodes[5], &[*origin], &stakes); active_set.prune(&pubkey, &nodes[3], &[*origin], &stakes); active_set.prune(&pubkey, &nodes[16], &[*origin], &stakes); assert!(active_set .get_nodes(&pubkey, origin, |_| false, &stakes) .eq([13, 18, 0].into_iter().map(|k| &nodes[k]))); assert!(active_set .get_nodes(&pubkey, other, |_| false, &stakes) .eq([13, 18, 16, 0].into_iter
prune
identifier_name
push_active_set.rs
push to for crds values belonging to this bucket. for (k, entry) in self.0.iter_mut().enumerate() { let weights: Vec<u64> = buckets .iter() .map(|&bucket| { // bucket <- get_stake_bucket(min stake of { // this node, crds value owner and gossip peer // }) // weight <- (bucket + 1)^2 // min stake of {...} is a proxy for how much we care about // the link, and tries to mirror similar logic on the // receiving end when pruning incoming links: // https://github.com/solana-labs/solana/blob/81394cf92/gossip/src/received_cache.rs#L100-L105 let bucket = bucket.min(k) as u64; bucket.saturating_add(1).saturating_pow(2) }) .collect(); entry.rotate(rng, size, num_bloom_filter_items, nodes, &weights); } } fn get_entry(&self, stake: Option<&u64>) -> &PushActiveSetEntry { &self.0[get_stake_bucket(stake)] } } impl PushActiveSetEntry { const BLOOM_FALSE_RATE: f64 = 0.1; const BLOOM_MAX_BITS: usize = 1024 * 8 * 4; fn get_nodes<'a>( &'a self, origin: &'a Pubkey, // If true forces gossip push even if the node has pruned the origin. mut should_force_push: impl FnMut(&Pubkey) -> bool + 'a, ) -> impl Iterator<Item = &Pubkey> + 'a { self.0 .iter() .filter(move |(node, bloom_filter)| { !bloom_filter.contains(origin) || should_force_push(node) }) .map(|(node, _bloom_filter)| node) } fn prune( &self, node: &Pubkey, // Gossip node. origin: &Pubkey, // CRDS value owner ) { if let Some(bloom_filter) = self.0.get(node) { bloom_filter.add(origin); } } fn rotate<R: Rng>( &mut self, rng: &mut R, size: usize, // Number of nodes to retain. num_bloom_filter_items: usize, nodes: &[Pubkey], weights: &[u64], ) { debug_assert_eq!(nodes.len(), weights.len()); debug_assert!(weights.iter().all(|&weight| weight != 0u64)); let shuffle = WeightedShuffle::new("rotate-active-set", weights).shuffle(rng); for node in shuffle.map(|k| &nodes[k]) { // We intend to discard the oldest/first entry in the index-map. if self.0.len() > size { break; } if self.0.contains_key(node) { continue; } let bloom = AtomicBloom::from(Bloom::random( num_bloom_filter_items, Self::BLOOM_FALSE_RATE, Self::BLOOM_MAX_BITS, )); bloom.add(node); self.0.insert(*node, bloom); } // Drop the oldest entry while preserving the ordering of others. while self.0.len() > size { self.0.shift_remove_index(0); } } } // Maps stake to bucket index. fn get_stake_bucket(stake: Option<&u64>) -> usize { let stake = stake.copied().unwrap_or_default() / LAMPORTS_PER_SOL; let bucket = u64::BITS - stake.leading_zeros(); (bucket as usize).min(NUM_PUSH_ACTIVE_SET_ENTRIES - 1) } #[cfg(test)] mod tests { use {super::*, rand::SeedableRng, rand_chacha::ChaChaRng, std::iter::repeat_with}; #[test] fn test_get_stake_bucket() { assert_eq!(get_stake_bucket(None), 0); let buckets = [0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5]; for (k, bucket) in buckets.into_iter().enumerate() { let stake = (k as u64) * LAMPORTS_PER_SOL; assert_eq!(get_stake_bucket(Some(&stake)), bucket); } for (stake, bucket) in [ (4_194_303, 22), (4_194_304, 23), (8_388_607, 23), (8_388_608, 24), ] { let stake = stake * LAMPORTS_PER_SOL; assert_eq!(get_stake_bucket(Some(&stake)), bucket); } assert_eq!( get_stake_bucket(Some(&u64::MAX)), NUM_PUSH_ACTIVE_SET_ENTRIES - 1 ); } #[test] fn test_push_active_set() { const CLUSTER_SIZE: usize = 117; const MAX_STAKE: u64 = (1 << 20) * LAMPORTS_PER_SOL; let mut rng = ChaChaRng::from_seed([189u8; 32]); let pubkey = Pubkey::new_unique(); let nodes: Vec<_> = repeat_with(Pubkey::new_unique).take(20).collect(); let stakes = repeat_with(|| rng.gen_range(1..MAX_STAKE)); let mut stakes: HashMap<_, _> = nodes.iter().copied().zip(stakes).collect(); stakes.insert(pubkey, rng.gen_range(1..MAX_STAKE)); let mut active_set = PushActiveSet::default(); assert!(active_set.0.iter().all(|entry| entry.0.is_empty())); active_set.rotate(&mut rng, 5, CLUSTER_SIZE, &nodes, &stakes); assert!(active_set.0.iter().all(|entry| entry.0.len() == 5)); // Assert that for all entries, each filter already prunes the key. for entry in &active_set.0 { for (node, filter) in entry.0.iter() { assert!(filter.contains(node)); } } let other = &nodes[5]; let origin = &nodes[17]; assert!(active_set .get_nodes(&pubkey, origin, |_| false, &stakes) .eq([13, 5, 18, 16, 0].into_iter().map(|k| &nodes[k]))); assert!(active_set .get_nodes(&pubkey, other, |_| false, &stakes) .eq([13, 18, 16, 0].into_iter().map(|k| &nodes[k]))); active_set.prune(&pubkey, &nodes[5], &[*origin], &stakes); active_set.prune(&pubkey, &nodes[3], &[*origin], &stakes); active_set.prune(&pubkey, &nodes[16], &[*origin], &stakes); assert!(active_set .get_nodes(&pubkey, origin, |_| false, &stakes) .eq([13, 18, 0].into_iter().map(|k| &nodes[k]))); assert!(active_set .get_nodes(&pubkey, other, |_| false, &stakes) .eq([13, 18, 16, 0].into_iter().map(|k| &nodes[k]))); active_set.rotate(&mut rng, 7, CLUSTER_SIZE, &nodes, &stakes); assert!(active_set.0.iter().all(|entry| entry.0.len() == 7)); assert!(active_set .get_nodes(&pubkey, origin, |_| false, &stakes) .eq([18, 0, 7, 15, 11].into_iter().map(|k| &nodes[k]))); assert!(active_set .get_nodes(&pubkey, other, |_| false, &stakes) .eq([18, 16, 0, 7, 15, 11].into_iter().map(|k| &nodes[k]))); let origins = [*origin, *other]; active_set.prune(&pubkey, &nodes[18], &origins, &stakes); active_set.prune(&pubkey, &nodes[0], &origins, &stakes); active_set.prune(&pubkey, &nodes[15], &origins, &stakes); assert!(active_set .get_nodes(&pubkey, origin, |_| false, &stakes) .eq([7, 11].into_iter().map(|k| &nodes[k]))); assert!(active_set .get_nodes(&pubkey, other, |_| false, &stakes) .eq([16, 7, 11].into_iter().map(|k| &nodes[k]))); }
random_line_split
push_active_set.rs
Option<&u64>) -> &PushActiveSetEntry { &self.0[get_stake_bucket(stake)] } } impl PushActiveSetEntry { const BLOOM_FALSE_RATE: f64 = 0.1; const BLOOM_MAX_BITS: usize = 1024 * 8 * 4; fn get_nodes<'a>( &'a self, origin: &'a Pubkey, // If true forces gossip push even if the node has pruned the origin. mut should_force_push: impl FnMut(&Pubkey) -> bool + 'a, ) -> impl Iterator<Item = &Pubkey> + 'a { self.0 .iter() .filter(move |(node, bloom_filter)| { !bloom_filter.contains(origin) || should_force_push(node) }) .map(|(node, _bloom_filter)| node) } fn prune( &self, node: &Pubkey, // Gossip node. origin: &Pubkey, // CRDS value owner ) { if let Some(bloom_filter) = self.0.get(node) { bloom_filter.add(origin); } } fn rotate<R: Rng>( &mut self, rng: &mut R, size: usize, // Number of nodes to retain. num_bloom_filter_items: usize, nodes: &[Pubkey], weights: &[u64], ) { debug_assert_eq!(nodes.len(), weights.len()); debug_assert!(weights.iter().all(|&weight| weight != 0u64)); let shuffle = WeightedShuffle::new("rotate-active-set", weights).shuffle(rng); for node in shuffle.map(|k| &nodes[k]) { // We intend to discard the oldest/first entry in the index-map. if self.0.len() > size { break; } if self.0.contains_key(node) { continue; } let bloom = AtomicBloom::from(Bloom::random( num_bloom_filter_items, Self::BLOOM_FALSE_RATE, Self::BLOOM_MAX_BITS, )); bloom.add(node); self.0.insert(*node, bloom); } // Drop the oldest entry while preserving the ordering of others. while self.0.len() > size { self.0.shift_remove_index(0); } } } // Maps stake to bucket index. fn get_stake_bucket(stake: Option<&u64>) -> usize { let stake = stake.copied().unwrap_or_default() / LAMPORTS_PER_SOL; let bucket = u64::BITS - stake.leading_zeros(); (bucket as usize).min(NUM_PUSH_ACTIVE_SET_ENTRIES - 1) } #[cfg(test)] mod tests { use {super::*, rand::SeedableRng, rand_chacha::ChaChaRng, std::iter::repeat_with}; #[test] fn test_get_stake_bucket() { assert_eq!(get_stake_bucket(None), 0); let buckets = [0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5]; for (k, bucket) in buckets.into_iter().enumerate() { let stake = (k as u64) * LAMPORTS_PER_SOL; assert_eq!(get_stake_bucket(Some(&stake)), bucket); } for (stake, bucket) in [ (4_194_303, 22), (4_194_304, 23), (8_388_607, 23), (8_388_608, 24), ] { let stake = stake * LAMPORTS_PER_SOL; assert_eq!(get_stake_bucket(Some(&stake)), bucket); } assert_eq!( get_stake_bucket(Some(&u64::MAX)), NUM_PUSH_ACTIVE_SET_ENTRIES - 1 ); } #[test] fn test_push_active_set() { const CLUSTER_SIZE: usize = 117; const MAX_STAKE: u64 = (1 << 20) * LAMPORTS_PER_SOL; let mut rng = ChaChaRng::from_seed([189u8; 32]); let pubkey = Pubkey::new_unique(); let nodes: Vec<_> = repeat_with(Pubkey::new_unique).take(20).collect(); let stakes = repeat_with(|| rng.gen_range(1..MAX_STAKE)); let mut stakes: HashMap<_, _> = nodes.iter().copied().zip(stakes).collect(); stakes.insert(pubkey, rng.gen_range(1..MAX_STAKE)); let mut active_set = PushActiveSet::default(); assert!(active_set.0.iter().all(|entry| entry.0.is_empty())); active_set.rotate(&mut rng, 5, CLUSTER_SIZE, &nodes, &stakes); assert!(active_set.0.iter().all(|entry| entry.0.len() == 5)); // Assert that for all entries, each filter already prunes the key. for entry in &active_set.0 { for (node, filter) in entry.0.iter() { assert!(filter.contains(node)); } } let other = &nodes[5]; let origin = &nodes[17]; assert!(active_set .get_nodes(&pubkey, origin, |_| false, &stakes) .eq([13, 5, 18, 16, 0].into_iter().map(|k| &nodes[k]))); assert!(active_set .get_nodes(&pubkey, other, |_| false, &stakes) .eq([13, 18, 16, 0].into_iter().map(|k| &nodes[k]))); active_set.prune(&pubkey, &nodes[5], &[*origin], &stakes); active_set.prune(&pubkey, &nodes[3], &[*origin], &stakes); active_set.prune(&pubkey, &nodes[16], &[*origin], &stakes); assert!(active_set .get_nodes(&pubkey, origin, |_| false, &stakes) .eq([13, 18, 0].into_iter().map(|k| &nodes[k]))); assert!(active_set .get_nodes(&pubkey, other, |_| false, &stakes) .eq([13, 18, 16, 0].into_iter().map(|k| &nodes[k]))); active_set.rotate(&mut rng, 7, CLUSTER_SIZE, &nodes, &stakes); assert!(active_set.0.iter().all(|entry| entry.0.len() == 7)); assert!(active_set .get_nodes(&pubkey, origin, |_| false, &stakes) .eq([18, 0, 7, 15, 11].into_iter().map(|k| &nodes[k]))); assert!(active_set .get_nodes(&pubkey, other, |_| false, &stakes) .eq([18, 16, 0, 7, 15, 11].into_iter().map(|k| &nodes[k]))); let origins = [*origin, *other]; active_set.prune(&pubkey, &nodes[18], &origins, &stakes); active_set.prune(&pubkey, &nodes[0], &origins, &stakes); active_set.prune(&pubkey, &nodes[15], &origins, &stakes); assert!(active_set .get_nodes(&pubkey, origin, |_| false, &stakes) .eq([7, 11].into_iter().map(|k| &nodes[k]))); assert!(active_set .get_nodes(&pubkey, other, |_| false, &stakes) .eq([16, 7, 11].into_iter().map(|k| &nodes[k]))); } #[test] fn test_push_active_set_entry() { const NUM_BLOOM_FILTER_ITEMS: usize = 100; let mut rng = ChaChaRng::from_seed([147u8; 32]); let nodes: Vec<_> = repeat_with(Pubkey::new_unique).take(20).collect(); let weights: Vec<_> = repeat_with(|| rng.gen_range(1..1000)).take(20).collect(); let mut entry = PushActiveSetEntry::default(); entry.rotate( &mut rng, 5, // size NUM_BLOOM_FILTER_ITEMS, &nodes, &weights, ); assert_eq!(entry.0.len(), 5); let keys = [&nodes[16], &nodes[11], &nodes[17], &nodes[14], &nodes[5]]; assert!(entry.0.keys().eq(keys)); for origin in &nodes { if !keys.contains(&origin)
{ assert!(entry.get_nodes(origin, |_| false).eq(keys)); }
conditional_block
tag_tweets_py2.py
regex so that we can preserve case for # them as needed: EMOTICON_RE = re.compile(EMOTICONS, re.VERBOSE | re.I | re.UNICODE) # These regex are added EMOJI_RE = re.compile(EMOJIS, re.UNICODE) URLS_RE = re.compile(URLS, re.VERBOSE | re.I | re.UNICODE) PHONUM_RE = re.compile(Phone_numbers, re.VERBOSE | re.I | re.UNICODE) USERNAME_RE = re.compile(Username, re.VERBOSE | re.I | re.UNICODE) HASHTAG_RE = re.compile(Hashtags, re.VERBOSE | re.I | re.UNICODE) EMAIL_RE = re.compile(Email, re.VERBOSE | re.I | re.UNICODE) NORMAL_RE = re.compile(r"""(%s)""" % "|".join(NormWords), re.VERBOSE | re.I | re.UNICODE) class MyTweetTokenizer: r""" Modified from nltk TweetTokenizer If type argument is set to be True, Return a tuple for each token, with the token and its type. Otherwise, Return the original nltk TweetTokenizer results. Type codes: N: normal words E: emoticons or emojis U: urls or emails PN: phone number USR: user names H: hashtags S: stopwords PUNC: punctuations """ def __init__(self, type_include=True): self.type_include = type_include def clean(self, text): if not self.type_include:
# Fix HTML character entities: text = NLTK._replace_html_entities(text) # Shorten problematic sequences of characters safe_text = NLTK.HANG_RE.sub(r'\1\1\1', text) # Tokenize: words = WORD_RE.findall(safe_text) clean_text = text # # Possibly alter the case, but avoid changing emoticons like :D into :d: for i, x in enumerate(words[:]): # if EMOTICON_RE.match(x) or EMOJI_RE.match(x): # text.decode('utf8') if URLS_RE.match(x) or EMAIL_RE.match(x): # print "url" clean_text = clean_text.replace(x, '') elif USERNAME_RE.match(x): # print "Username" clean_text = clean_text.replace(x, '') elif HASHTAG_RE.match(x): # print "tag" clean_text = clean_text.replace(x, '') elif PHONUM_RE.match(x): # print "phone" clean_text = clean_text.replace(x, '') # elif x.lower() in STOP: # print "stop" # clean_text = clean_text.replace(x, '') # elif EMOJI_RE.match(x): # clean_text = clean_text.replace(x, '') else: continue return clean_text emoji_pattern = re.compile( u"(\ud83d[\ude00-\ude4f])|" # emoticons u"(\ud83d[\u0000-\uddff])|" # symbols & pictographs (2 of 2) u"(\ud83d[\ude80-\udeff])|" # transport & map symbols u"(\uD83E[\uDD00-\uDDFF])|" u"(\ud83c[\udf00-\uffff])|" # symbols & pictographs (1 of 2) u"(\ud83c[\udde0-\uddff])|" # flags (iOS) u"([\u2934\u2935]\uFE0F?)|" u"([\u3030\u303D]\uFE0F?)|" u"([\u3297\u3299]\uFE0F?)|" u"([\u203C\u2049]\uFE0F?)|" u"([\u00A9\u00AE]\uFE0F?)|" u"([\u2122\u2139]\uFE0F?)|" u"(\uD83C\uDC04\uFE0F?)|" u"(\uD83C\uDCCF\uFE0F?)|" u"([\u0023\u002A\u0030-\u0039]\uFE0F?\u20E3)|" u"(\u24C2\uFE0F?|[\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55]\uFE0F?)|" u"([\u2600-\u26FF]\uFE0F?)|" u"([\u2700-\u27BF]\uFE0F?)" "+", flags=re.UNICODE) # input_file: str # output_file: str def read_tweets(input_file): happy_emoji = [' :‑) ', ' :) ', ' :))', ' :)))', ' :-] ', ' :]', ' :-3', ':->', ':>', ' 8-)', ':-}', ':}', ' :o)', ' :c)', ' :^)', ' =]', ' =)', ' :‑D', ' :D', ' 8‑D', ' 8D ', ' x‑D', ' xD ', ' X‑D ', ' XD ', ' =D ', ' =3', ':-))', ':-)))', ':\'‑)', ':\')', ' :-*', ':*', ' :×', ' ;‑)', ' ;)', ' *-)', ' *)', ';‑]', ' ;]', ' ;^)', ' :‑,', ' ;D', ' :‑P', ' :P', ' X‑P', ' x‑p', ' :‑p', ' :p ', ' :b', ' d:', ' =p', '^_^', '^^', '^ ^', '(^_^)/', '(^O^)/', '(^o^)/', '(^^)/', '>^_^<', '^/^', '(*^_^*)', '(^.^)', '(^·^)', '(^.^)', '(^_^)', '(^^)', '^_^', '(*^.^*)', '(#^.^#)', '(*^0^*)', '\(^o^)/', '!(^^)!', '(^v^)', '(^u^)', '( ^)o(^ )', '(^O^)', '(^o^)', ')^o^(', 'ヽ(´▽`)/', '≧∇≦', '^ω^', '^▽^', '\xF0\x9F\x98\x81', '\xF0\x9F\x98\x82', '\xF0\x9F\x98\x83', '\xF0\x9F\x98\x84', '\xF0\x9F\x98\x86', '\xF0\x9F\x98\x89', '\xF0\x9F\x98\x8A', '\xF0\x9F\x98\x8B', '\xF0\x9F\x98\x8C', '\xF0\x9F\x98\x8D', '\xF0\x9F\x98\x8F', '\xF0\x9F\x98\x97', '\xF0\x9F\x98\x98', '\xF0\x9F\x98\x99', '\xF0\x9F\x98\x9A', '\xF0\x9F\x98\x9B', '\xF0\x9F\x98\x9C', '\xF0\x9F\x98\x9D', '\xF0\x9F\x98\xB8', '\xF0\x9F\x98\xB9', '\xF0\x9F\x98\xBA', '\xF0\x9F\x98\xBB', '\xF0\x9F\x98\xBD', '\xF0\x9F\x99\x8B', '\xF0\x9F\x99\x8C', '\xF0\x9F\x98\x80', '\xF0\x9F\x98\x87', '\xF0\x9F\x98\x88', '\xF0\x9F\x98\x8E', '\xF0\x9F\x92\x8B', '\xF0\x9F\x92\x8F', '\xF0\x9F\x92\x91', '\xF0\x9F\x92\x95', '\xF0\x9F\x92\x96', '\xF0\x9F\x92\x97', '\xF0\x9F\x92\x98', '\xF0\x9F\x92\x9D', '\xF0\x9F\x8C\xB9', '\xF0\x9F\x8E\x80', '\xF0\x9F\x8E\x81', '\xF0\x9F\x8E\x82', '\
tknzr = NLTK.TweetTokenizer() return tknzr.tokenize(text)
conditional_block
tag_tweets_py2.py
;D', ' :‑P', ' :P', ' X‑P', ' x‑p', ' :‑p', ' :p ', ' :b', ' d:', ' =p', '^_^', '^^', '^ ^', '(^_^)/', '(^O^)/', '(^o^)/', '(^^)/', '>^_^<', '^/^', '(*^_^*)', '(^.^)', '(^·^)', '(^.^)', '(^_^)', '(^^)', '^_^', '(*^.^*)', '(#^.^#)', '(*^0^*)', '\(^o^)/', '!(^^)!', '(^v^)', '(^u^)', '( ^)o(^ )', '(^O^)', '(^o^)', ')^o^(', 'ヽ(´▽`)/', '≧∇≦', '^ω^', '^▽^', '\xF0\x9F\x98\x81', '\xF0\x9F\x98\x82', '\xF0\x9F\x98\x83', '\xF0\x9F\x98\x84', '\xF0\x9F\x98\x86', '\xF0\x9F\x98\x89', '\xF0\x9F\x98\x8A', '\xF0\x9F\x98\x8B', '\xF0\x9F\x98\x8C', '\xF0\x9F\x98\x8D', '\xF0\x9F\x98\x8F', '\xF0\x9F\x98\x97', '\xF0\x9F\x98\x98', '\xF0\x9F\x98\x99', '\xF0\x9F\x98\x9A', '\xF0\x9F\x98\x9B', '\xF0\x9F\x98\x9C', '\xF0\x9F\x98\x9D', '\xF0\x9F\x98\xB8', '\xF0\x9F\x98\xB9', '\xF0\x9F\x98\xBA', '\xF0\x9F\x98\xBB', '\xF0\x9F\x98\xBD', '\xF0\x9F\x99\x8B', '\xF0\x9F\x99\x8C', '\xF0\x9F\x98\x80', '\xF0\x9F\x98\x87', '\xF0\x9F\x98\x88', '\xF0\x9F\x98\x8E', '\xF0\x9F\x92\x8B', '\xF0\x9F\x92\x8F', '\xF0\x9F\x92\x91', '\xF0\x9F\x92\x95', '\xF0\x9F\x92\x96', '\xF0\x9F\x92\x97', '\xF0\x9F\x92\x98', '\xF0\x9F\x92\x9D', '\xF0\x9F\x8C\xB9', '\xF0\x9F\x8E\x80', '\xF0\x9F\x8E\x81', '\xF0\x9F\x8E\x82', '\xF0\x9F\x8E\x86', '\xF0\x9F\x8E\x87', '\xF0\x9F\x8E\x89', '\xF0\x9F\x8E\x8A', '\xE2\x9C\x8C', '\xE2\x9D\xA4', '\xE2\x98\xBA', '\xE2\x99\xA5', '\xE3\x8A\x97'] sad_emoji = [' :‑(', ' :(', ' :‑c', ' :c', ' :‑<', ' :<', ' :‑[', ' :[', ' :-||', ' >:[', ' :{', ' :@', ' >:(', ' :\'‑(', ' :\'(', ' DX ', ' D= ', ' D; ', ' D: ', ' D:<', ' D‑\':', ' >:O', ' :-0', ' :‑o', ' :o ', ' :‑O', ' :O ', ' :‑/', ' :‑.', ' >:\\', ' >:/', ' :\\', ' =/', ' =\\', ' :L', ' =L', ' :S', ' :‑|', ' :|', ' :$ ', '(-_-;)', ' Q_Q', ' TnT', 'T.T', 'Q.Q', ';;', ' ;n;', ' ;-;', ' ;_;', '(T_T)', '(;_:)', '(ToT)', '(ー_ー)!!', '(-.-)', '(-_-)', '(=_=)', '(-"-)', '(ーー;)', '(* ̄m ̄)', '(#゚Д゚)', '(´;ω;`)', 'ヽ(`Д´)ノ', '( ´,_ゝ`)', '\xF0\x9F\x98\x91', '\xF0\x9F\x98\x92', '\xF0\x9F\x98\x93', '\xF0\x9F\x98\x94', '\xF0\x9F\x98\x95', '\xF0\x9F\x98\x96', '\xF0\x9F\x98\x9E', '\xF0\x9F\x98\x9F', '\xF0\x9F\x98\xA0', '\xF0\x9F\x98\xA1', '\xF0\x9F\x98\xA2', '\xF0\x9F\x98\xA3', '\xF0\x9F\x98\xA4', '\xF0\x9F\x98\xA5', '\xF0\x9F\x98\xA6', '\xF0\x9F\x98\xA7', '\xF0\x9F\x98\xA8', '\xF0\x9F\x98\xA9', '\xF0\x9F\x98\xAB', '\xF0\x9F\x98\xAD', '\xF0\x9F\x98\xB1', '\xF0\x9F\x98\xBE', '\xF0\x9F\x99\x8D', '\xF0\x9F\x92\x94', '\xF0\x9F\x92\xA2' ] output = {} print("input_file: {}".format(input_file)) with open(input_file, 'r') as inf: tweets = MyTweetTokenizer() output_file = "tagged/{}.txt".format(input_file.split("/")[-1]) with open(output_file, 'w', 100) as outf: for line in inf: if is_json(line): record = json.loads(line) if u'text' in record: unicode_text = record[u'text'] if len(unicode_text) < 20: continue utf8text = unicode_text.encode("utf-8") is_happy, happy_tag, happy_clean_text = find_emoji(utf8text, happy_emoji) is_sad, sad_tag, sad_clean_text = find_emoji(utf8text, sad_emoji) if is_happy and not is_sad: clean_emoji_text = remove_emoji(happy_clean_text) # remove emoji clean_text = tweets.clean(clean_emoji_text) # remove others clean_text = clean_text.replace("http://","").replace("https://","") if len(clean_text) >= 20: output = {'text': clean_text, 'label': '1', 'emoji': happy_tag} outf.write(json.dumps(output) + '\n') else: continue elif not is_happy and is_sad: clean_emoji_text = remove_emoji(sad_clean_text) clean_text = tweets.clean(clean_emoji_text) clean_text = clean_text.replace("http://","").replace("https://","") if len(clean_text) >= 20: output = {'text': clean_text, 'label': '0', 'emoji': sad_tag} outf.write(json.dumps(output) + '\n') else: continue else: continue # text: str # emoji: list # return: bool def find_emoji(text, emoji): flag = False flag_emoji = [] clean_text = text for e in emoji: if e in text: clean_text = clean_text.replace(e, '') flag = True flag_emoji.append(e) return flag, flag_emoji, clean_text def remove_emoji(text): # print type(text), "first" # str text = text.decode('utf8') # print type(text), "second" # unicode text = emoji_pattern.sub(r'', text).encode('utf8')
return def is_json(myjson): try: json_object = json.loads(myjson) except ValueError, e: return False return True de
identifier_body
tag_tweets_py2.py
# WORD_RE performs poorly on these patterns: HANG_RE = re.compile(r"""([^a-zA-Z0-9])\1{3,}""") # The emoticon string gets its own regex so that we can preserve case for # them as needed: EMOTICON_RE = re.compile(EMOTICONS, re.VERBOSE | re.I | re.UNICODE) # These regex are added EMOJI_RE = re.compile(EMOJIS, re.UNICODE) URLS_RE = re.compile(URLS, re.VERBOSE | re.I | re.UNICODE) PHONUM_RE = re.compile(Phone_numbers, re.VERBOSE | re.I | re.UNICODE) USERNAME_RE = re.compile(Username, re.VERBOSE | re.I | re.UNICODE) HASHTAG_RE = re.compile(Hashtags, re.VERBOSE | re.I | re.UNICODE) EMAIL_RE = re.compile(Email, re.VERBOSE | re.I | re.UNICODE) NORMAL_RE = re.compile(r"""(%s)""" % "|".join(NormWords), re.VERBOSE | re.I | re.UNICODE) class MyTweetTokenizer: r""" Modified from nltk TweetTokenizer If type argument is set to be True, Return a tuple for each token, with the token and its type. Otherwise, Return the original nltk TweetTokenizer results. Type codes: N: normal words E: emoticons or emojis U: urls or emails PN: phone number USR: user names H: hashtags S: stopwords PUNC: punctuations """ def __init__(self, type_include=True): self.type_include = type_include def clean(self, text): if not self.type_include: tknzr = NLTK.TweetTokenizer() return tknzr.tokenize(text) # Fix HTML character entities: text = NLTK._replace_html_entities(text) # Shorten problematic sequences of characters safe_text = NLTK.HANG_RE.sub(r'\1\1\1', text) # Tokenize: words = WORD_RE.findall(safe_text) clean_text = text # # Possibly alter the case, but avoid changing emoticons like :D into :d: for i, x in enumerate(words[:]): # if EMOTICON_RE.match(x) or EMOJI_RE.match(x): # text.decode('utf8') if URLS_RE.match(x) or EMAIL_RE.match(x): # print "url" clean_text = clean_text.replace(x, '') elif USERNAME_RE.match(x): # print "Username" clean_text = clean_text.replace(x, '') elif HASHTAG_RE.match(x): # print "tag" clean_text = clean_text.replace(x, '') elif PHONUM_RE.match(x): # print "phone" clean_text = clean_text.replace(x, '') # elif x.lower() in STOP: # print "stop" # clean_text = clean_text.replace(x, '') # elif EMOJI_RE.match(x): # clean_text = clean_text.replace(x, '') else: continue return clean_text emoji_pattern = re.compile( u"(\ud83d[\ude00-\ude4f])|" # emoticons u"(\ud83d[\u0000-\uddff])|" # symbols & pictographs (2 of 2) u"(\ud83d[\ude80-\udeff])|" # transport & map symbols u"(\uD83E[\uDD00-\uDDFF])|" u"(\ud83c[\udf00-\uffff])|" # symbols & pictographs (1 of 2) u"(\ud83c[\udde0-\uddff])|" # flags (iOS) u"([\u2934\u2935]\uFE0F?)|" u"([\u3030\u303D]\uFE0F?)|" u"([\u3297\u3299]\uFE0F?)|" u"([\u203C\u2049]\uFE0F?)|" u"([\u00A9\u00AE]\uFE0F?)|" u"([\u2122\u2139]\uFE0F?)|" u"(\uD83C\uDC04\uFE0F?)|" u"(\uD83C\uDCCF\uFE0F?)|" u"([\u0023\u002A\u0030-\u0039]\uFE0F?\u20E3)|" u"(\u24C2\uFE0F?|[\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55]\uFE0F?)|" u"([\u2600-\u26FF]\uFE0F?)|" u"([\u2700-\u27BF]\uFE0F?)" "+", flags=re.UNICODE) # input_file: str # output_file: str def read_tweets(input_file): happy_emoji = [' :‑) ', ' :) ', ' :))', ' :)))', ' :-] ', ' :]', ' :-3', ':->', ':>', ' 8-)', ':-}', ':}', ' :o)', ' :c)', ' :^)', ' =]', ' =)', ' :‑D', ' :D', ' 8‑D', ' 8D ', ' x‑D', ' xD ', ' X‑D ', ' XD ', ' =D ', ' =3', ':-))', ':-)))', ':\'‑)', ':\')', ' :-*', ':*', ' :×', ' ;‑)', ' ;)', ' *-)', ' *)', ';‑]', ' ;]', ' ;^)', ' :‑,', ' ;D', ' :‑P', ' :P', ' X‑P', ' x‑p', ' :‑p', ' :p ', ' :b', ' d:', ' =p', '^_^', '^^', '^ ^', '(^_^)/', '(^O^)/', '(^o^)/', '(^^)/', '>^_^<', '^/^', '(*^_^*)', '(^.^)', '(^·^)', '(^.^)', '(^_^)', '(^^)', '^_^', '(*^.^*)', '(#^.^#)', '(*^0^*)', '\(^o^)/', '!(^^)!', '(^v^)', '(^u^)', '( ^)o(^ )', '(^O^)', '(^o^)', ')^o^(', 'ヽ(´▽`)/', '≧∇≦', '^ω^', '^▽^', '\xF0\x9F\x98\x81', '\xF0\x9F\x98\x82', '\xF0\x9F\x98\x83', '\xF0\x9F\x98\x84', '\xF0\x9F\x98\x86', '\xF0\x9F\x98\x89', '\xF0\x9F\x98\x8A', '\xF0\x9F\x98\x8B', '\xF0\x9F\x98\x8C', '\xF0\x9F\x98\x8D', '\xF0\x9F\x98\x8F', '\xF0\x9F\x98\x97', '\xF0\x9F\x98\x98', '\xF0\x9F\x98\x99', '\xF0\x9F\x98\x9A', '\xF0\x9F\x98\x9B', '\xF0\x9F\x98\x9C', '\xF0\x9F\x98\x9D', '\xF0\x9F\x98\xB8', '\xF0\x9F\x98\xB9', '\xF0\x9F\x98\xBA', '\xF0\x9F\x98\xBB', '\xF0\x9F\x98\xBD', '\xF0\x9F\x99\x8B', '\xF0\x9F\x99\x8C', '\xF0\x9F\x98\x80', '\xF0\x9F\x98\x87', '\xF0\x9F\x98\x88', '\xF0\x9F\x98\x8E', '\xF0\x9F\x92\x8B', '\xF0\x9F\x92\x8F', '\xF0\x9F\x92\x91', '\xF0\x9F\x92\x95', '\xF0\x9F\x92\x96', '\xF0\x9F\x92\x97', '\xF0\x9F\x92\x
WORD_RE = re.compile(r"""(%s)""" % "|".join(REGEXPS), re.VERBOSE | re.I | re.UNICODE)
random_line_split
tag_tweets_py2.py
':\'‑)', ':\')', ' :-*', ':*', ' :×', ' ;‑)', ' ;)', ' *-)', ' *)', ';‑]', ' ;]', ' ;^)', ' :‑,', ' ;D', ' :‑P', ' :P', ' X‑P', ' x‑p', ' :‑p', ' :p ', ' :b', ' d:', ' =p', '^_^', '^^', '^ ^', '(^_^)/', '(^O^)/', '(^o^)/', '(^^)/', '>^_^<', '^/^', '(*^_^*)', '(^.^)', '(^·^)', '(^.^)', '(^_^)', '(^^)', '^_^', '(*^.^*)', '(#^.^#)', '(*^0^*)', '\(^o^)/', '!(^^)!', '(^v^)', '(^u^)', '( ^)o(^ )', '(^O^)', '(^o^)', ')^o^(', 'ヽ(´▽`)/', '≧∇≦', '^ω^', '^▽^', '\xF0\x9F\x98\x81', '\xF0\x9F\x98\x82', '\xF0\x9F\x98\x83', '\xF0\x9F\x98\x84', '\xF0\x9F\x98\x86', '\xF0\x9F\x98\x89', '\xF0\x9F\x98\x8A', '\xF0\x9F\x98\x8B', '\xF0\x9F\x98\x8C', '\xF0\x9F\x98\x8D', '\xF0\x9F\x98\x8F', '\xF0\x9F\x98\x97', '\xF0\x9F\x98\x98', '\xF0\x9F\x98\x99', '\xF0\x9F\x98\x9A', '\xF0\x9F\x98\x9B', '\xF0\x9F\x98\x9C', '\xF0\x9F\x98\x9D', '\xF0\x9F\x98\xB8', '\xF0\x9F\x98\xB9', '\xF0\x9F\x98\xBA', '\xF0\x9F\x98\xBB', '\xF0\x9F\x98\xBD', '\xF0\x9F\x99\x8B', '\xF0\x9F\x99\x8C', '\xF0\x9F\x98\x80', '\xF0\x9F\x98\x87', '\xF0\x9F\x98\x88', '\xF0\x9F\x98\x8E', '\xF0\x9F\x92\x8B', '\xF0\x9F\x92\x8F', '\xF0\x9F\x92\x91', '\xF0\x9F\x92\x95', '\xF0\x9F\x92\x96', '\xF0\x9F\x92\x97', '\xF0\x9F\x92\x98', '\xF0\x9F\x92\x9D', '\xF0\x9F\x8C\xB9', '\xF0\x9F\x8E\x80', '\xF0\x9F\x8E\x81', '\xF0\x9F\x8E\x82', '\xF0\x9F\x8E\x86', '\xF0\x9F\x8E\x87', '\xF0\x9F\x8E\x89', '\xF0\x9F\x8E\x8A', '\xE2\x9C\x8C', '\xE2\x9D\xA4', '\xE2\x98\xBA', '\xE2\x99\xA5', '\xE3\x8A\x97'] sad_emoji = [' :‑(', ' :(', ' :‑c', ' :c', ' :‑<', ' :<', ' :‑[', ' :[', ' :-||', ' >:[', ' :{', ' :@', ' >:(', ' :\'‑(', ' :\'(', ' DX ', ' D= ', ' D; ', ' D: ', ' D:<', ' D‑\':', ' >:O', ' :-0', ' :‑o', ' :o ', ' :‑O', ' :O ', ' :‑/', ' :‑.', ' >:\\', ' >:/', ' :\\', ' =/', ' =\\', ' :L', ' =L', ' :S', ' :‑|', ' :|', ' :$ ', '(-_-;)', ' Q_Q', ' TnT', 'T.T', 'Q.Q', ';;', ' ;n;', ' ;-;', ' ;_;', '(T_T)', '(;_:)', '(ToT)', '(ー_ー)!!', '(-.-)', '(-_-)', '(=_=)', '(-"-)', '(ーー;)', '(* ̄m ̄)', '(#゚Д゚)', '(´;ω;`)', 'ヽ(`Д´)ノ', '( ´,_ゝ`)', '\xF0\x9F\x98\x91', '\xF0\x9F\x98\x92', '\xF0\x9F\x98\x93', '\xF0\x9F\x98\x94', '\xF0\x9F\x98\x95', '\xF0\x9F\x98\x96', '\xF0\x9F\x98\x9E', '\xF0\x9F\x98\x9F', '\xF0\x9F\x98\xA0', '\xF0\x9F\x98\xA1', '\xF0\x9F\x98\xA2', '\xF0\x9F\x98\xA3', '\xF0\x9F\x98\xA4', '\xF0\x9F\x98\xA5', '\xF0\x9F\x98\xA6', '\xF0\x9F\x98\xA7', '\xF0\x9F\x98\xA8', '\xF0\x9F\x98\xA9', '\xF0\x9F\x98\xAB', '\xF0\x9F\x98\xAD', '\xF0\x9F\x98\xB1', '\xF0\x9F\x98\xBE', '\xF0\x9F\x99\x8D', '\xF0\x9F\x92\x94', '\xF0\x9F\x92\xA2' ] output = {} print("input_file: {}".format(input_file)) with open(input_file, 'r') as inf: tweets = MyTweetTokenizer() output_file = "tagged/{}.txt".format(input_file.split("/")[-1]) with open(output_file, 'w', 100) as outf: for line in inf: if is_json(line): record = json.loads(line) if u'text' in record: unicode_text = record[u'text'] if len(unicode_text) < 20: continue utf8text = unicode_text.encode("utf-8") is_happy, happy_tag, happy_clean_text = find_emoji(utf8text, happy_emoji) is_sad, sad_tag, sad_clean_text = find_emoji(utf8text, sad_emoji) if is_happy and not is_sad: clean_emoji_text = remove_emoji(happy_clean_text) # remove emoji clean_text = tweets.clean(clean_emoji_text) # remove others clean_text = clean_text.replace("http://","").replace("https://","") if len(clean_text) >= 20: output = {'text': clean_text, 'label': '1', 'emoji': happy_tag} outf.write(json.dumps(output) + '\n') else: continue elif not is_happy and is_sad: clean_emoji_text = remove_emoji(sad_clean_text) clean_text = tweets.clean(clean_emoji_text) clean_text = clean_text.replace("http://","").replace("https://","") if len(clean_text) >= 20: output = {'text': clean_text, 'label': '0', 'emoji': sad_tag} outf.write(json.dumps(output) + '\n') else: continue else: continue # text: str # emoji: list # return: bool def find_emoji(text, emoji): flag = False flag_emoji = [] clean_text = text for e in emoji: if e in text: clean_text = clean_text.replace(e, '') flag = True flag_emoji.append(e) return flag, flag_emoji, clean_text def remove_emoji(text): # print type(text), "first" # str text = text.decode('utf8') # print type(text), "second" # un
icode te
identifier_name
Conv_layer.py
, height, depth, weight_init='undefined'): self.width = width self.height = height self.depth = depth n_weight_vals = self.height * self.width * self.depth self.data_mtx = np.reshape(np.zeros(n_weight_vals), newshape=(self.depth, self.height, self.width)) self.delta_data_mtx = np.reshape(np.zeros(n_weight_vals), newshape=(self.depth, self.height, self.width)) self.vectorized_rand_norm = np.vectorize(self.generate_normal_rand, otypes=[np.float]) # weight initialization # if weight initialization not set then use Xavier method for initializing weights 'TODO: provide link' if weight_init != 'undefined': weight_std = np.sqrt(n_weight_vals) self.data_mtx = self.vectorized_rand_norm(self.data_mtx) def get_data(self, width_indx, heigh_indx, depth_indx): pass # weight_patch= def get_shape(self): return self.data_mtx.shape def set_data_elmt(self, i, j, depth, val): self.data_mtx[depth, i, j] = val def set_padded_mtx(self,input_mtx): self.padded_mtx = input_mtx self.depth , self.width,self.height = input_mtx.shape self.delta_data_mtx = np.reshape(np.zeros(self.depth*self.height*self.width), newshape=(self.depth, self.height, self.width)) def set_data_mtx(self,input_mtx): self.data_mtx = input_mtx self.depth , self.width,self.height = input_mtx.shape self.delta_data_mtx = np.reshape(np.zeros(self.depth*self.height*self.width), newshape=(self.depth, self.height, self.width)) def get_gradient(self, x, y, depth): return self.delta_data_mtx[depth, x, y] def set_gradient(self, x, y, depth, grad_val): self.delta_data_mtx[depth, x, y] = grad_val def add_gradient(self, x, y, depth, grad_val): self.delta_data_mtx += grad_val def generate_normal_rand(self, matx_elmt): n_weight_vals = self.height * self.depth * self.depth return np.float(matx_elmt + np.random.normal(loc=0, scale=np.sqrt(n_weight_vals), size=1)) class Naive_Conv_NeuralNet_Layer(object): """ A numpy based, naive implementation of a vanilla convolutional neural net layer. Multiple Conv layers + pooling(optional) + some final output transformations define a full Conv Net Details of the mathematics can be found at the from textbook 'Deep Learning' by Goodman, Bengio et al. Implementation based also on stanford convolutional networks course work: http://cs231n.github.io/convolutional-networks/#conv Code is inspired by karpathy's javascript implementation of a different deep learning layers. Its amazing. So check it out. All(most since I looked at alot of different code in coming to try understand this stuff) goes to ya. Thanks for making your code public dude https://github.com/karpathy/convnetjs """ def __init__(self, input_volume, no_filters, filter_map_dim=3, stride_len=1, zero_padding=1,weight_init='False'): """ :param input_feature_map_dim: :param no_filters: :param filter_map_dim: :param stride_len: :param zero_padding: :return: """ self.num_channels_D, self.width_X, self.height_Y= input_volume.get_shape() self.n_filters = no_filters self.input_vol = input_volume # need to change this to a copy of the input in the future .copy() self.filter_size = filter_map_dim self.stride_len = stride_len self.zero_padding = zero_padding self.filter_map = [Data(width=self.filter_size, height=self.filter_size, depth=self.input_vol.depth,weight_init='normal') for i in range(self.n_filters)] self.bias_vol = [Data(width=1, height=1, depth=1) for i in range(self.n_filters)] self.zero_pad_image() # zero pad once since zero pad parm > 0 # Initialize weights to be applied to input_feature_map. Sample from N(0,1) as intialization weights if weight_init == 'True': pass # Output volume sizes # TODO: write a function to check if output dim are int types. If not adjust with appropriate zero padding while (self.width_X-self.filter_size+ 2 * self.zero_padding)/self.stride_len % 1 != 0.0: print('yay') self.zero_pad_image() else: self.Output_Width = int((self.width_X - self.filter_size + 2 * self.zero_padding) / (self.stride_len) + 1) self.Output_Height = int((self.height_Y - self.filter_size + 2 * self.zero_padding) / (self.stride_len) + 1) self.output_Tensor = Data(width=self.Output_Width, height=self.Output_Height, depth=self.n_filters) def filter_val_init(self,filter_vol): for filter_indx in range(len(self.filter_map)): self.filter_map[filter_indx].set_data_mtx(filter_vol[filter_indx,:,:])
def im2col(self, X): """ :param X: filter_dim X filter_dim area of current image to be converted to 1 X filter_dim^2 vector :param filter_dim: :return: vector of dimension 1 by filter_dim^2 """ flat_vect = np.reshape(X, -1) return flat_vect def convolution_op(self, image_col, filter_col): conv_result = np.sum(np.dot(image_col, filter_col)) return conv_result def zero_pad(self,x): return np.pad(x,pad_width=(1,1),mode='constant',constant_values=0) def zero_pad_image(self): input_img =self.input_vol.data_mtx.copy() input_img_list = input_img.tolist() padded = False while self.zero_padding < self.filter_size and padded==False: if (self.width_X-self.filter_size+ 2 * self.zero_padding)/self.stride_len % 1 == 0.0 : for j in range(0,input_img.shape[0]): input_img_list[j] = self.zero_pad(input_img_list[j]) print(input_img_list) padded = True else: self.zero_padding += 1 self.input_vol.set_padded_mtx(np.asarray(input_img_list)) def set_weights(self,input_vol): for j in range(len(self.filter_map)): self.filter_map[j].set_data_mtx(input_vol[j,:,:,:]) def Naive_forwardpass(self): """ Forward pass of conv net implementing output map generating function. Returns an tensor of self.Output_Width X self.Output_Height X self.n_filters. Which is happily sent off to the next poor bugger layer of the CNN architecture Not happy too(livid actually) with the efficiency and endless loops but c'est la vie. This is for education purposes. :param X: Image/feature map from previous layer/(just the picture I guess) :return: tensor of vol : self.Output_Width X self.Output_Height X self.n_filters """ for filter_k in range(0, self.n_filters): filter_col = self.im2col(self.filter_map[filter_k].data_mtx) for hgt_indx in range(0, self.Output_Height): for wdth_indx in range(0, self.Output_Width): wdth_start_index = wdth_indx * self.stride_len wdth_end_index= wdth_start_index + self.filter_size hgt_start_index = hgt_indx * self.stride_len hgt_end_index = hgt_start_index + self.filter_size trn_img_area = self.input_vol.padded_mtx[:, wdth_start_index:wdth_end_index, hgt_start_index:hgt_end_index] trn_img_col = self.im2col(trn_img_area) self.output_Tensor.data_mtx[filter_k,wdth_indx , hgt_indx] = self.convolution_op(trn_img_col, filter_col) + np.sum(self.bias_vol[filter_k].data_mtx) return self.output_Tensor # hopefully correct implementation of conv back prop def Naive_backwardpass(self): """ :param X: :return: """ # this fucking backward pass ...sigh # need to make two backward pass gradient calculations # gradient w.r.t filter weights which will be used for weight updates. # gradient w.r.t current image representation/ current layer which will be used as gradient flow to lower layers for filter_j in range(0, len(self.filter_map)): filter_vol = self.filter_map[ filter_j] # fix a single filter,reference to a class object. Make sure that changes are inplace and not new copy object for height_indx in range(0, self.Output_Height): for width_indx in range(0,self.Output_Width): # fixes a single pixel , pixel i,j in layer L the output vol upstream_grad = np.full(shape=(filter_vol.depth, self.filter_size, self.filter_size), fill_value=self.output_Tensor.delta_data_mtx[ filter_j, width_indx, height_indx]) # get dE/d(x_{i,j}) . derivative of error w.r.t fixed pixel w,h
random_line_split
Conv_layer.py
height, depth, weight_init='undefined'): self.width = width self.height = height self.depth = depth n_weight_vals = self.height * self.width * self.depth self.data_mtx = np.reshape(np.zeros(n_weight_vals), newshape=(self.depth, self.height, self.width)) self.delta_data_mtx = np.reshape(np.zeros(n_weight_vals), newshape=(self.depth, self.height, self.width)) self.vectorized_rand_norm = np.vectorize(self.generate_normal_rand, otypes=[np.float]) # weight initialization # if weight initialization not set then use Xavier method for initializing weights 'TODO: provide link' if weight_init != 'undefined': weight_std = np.sqrt(n_weight_vals) self.data_mtx = self.vectorized_rand_norm(self.data_mtx) def get_data(self, width_indx, heigh_indx, depth_indx): pass # weight_patch= def get_shape(self): return self.data_mtx.shape def set_data_elmt(self, i, j, depth, val): self.data_mtx[depth, i, j] = val def set_padded_mtx(self,input_mtx):
def set_data_mtx(self,input_mtx): self.data_mtx = input_mtx self.depth , self.width,self.height = input_mtx.shape self.delta_data_mtx = np.reshape(np.zeros(self.depth*self.height*self.width), newshape=(self.depth, self.height, self.width)) def get_gradient(self, x, y, depth): return self.delta_data_mtx[depth, x, y] def set_gradient(self, x, y, depth, grad_val): self.delta_data_mtx[depth, x, y] = grad_val def add_gradient(self, x, y, depth, grad_val): self.delta_data_mtx += grad_val def generate_normal_rand(self, matx_elmt): n_weight_vals = self.height * self.depth * self.depth return np.float(matx_elmt + np.random.normal(loc=0, scale=np.sqrt(n_weight_vals), size=1)) class Naive_Conv_NeuralNet_Layer(object): """ A numpy based, naive implementation of a vanilla convolutional neural net layer. Multiple Conv layers + pooling(optional) + some final output transformations define a full Conv Net Details of the mathematics can be found at the from textbook 'Deep Learning' by Goodman, Bengio et al. Implementation based also on stanford convolutional networks course work: http://cs231n.github.io/convolutional-networks/#conv Code is inspired by karpathy's javascript implementation of a different deep learning layers. Its amazing. So check it out. All(most since I looked at alot of different code in coming to try understand this stuff) goes to ya. Thanks for making your code public dude https://github.com/karpathy/convnetjs """ def __init__(self, input_volume, no_filters, filter_map_dim=3, stride_len=1, zero_padding=1,weight_init='False'): """ :param input_feature_map_dim: :param no_filters: :param filter_map_dim: :param stride_len: :param zero_padding: :return: """ self.num_channels_D, self.width_X, self.height_Y= input_volume.get_shape() self.n_filters = no_filters self.input_vol = input_volume # need to change this to a copy of the input in the future .copy() self.filter_size = filter_map_dim self.stride_len = stride_len self.zero_padding = zero_padding self.filter_map = [Data(width=self.filter_size, height=self.filter_size, depth=self.input_vol.depth,weight_init='normal') for i in range(self.n_filters)] self.bias_vol = [Data(width=1, height=1, depth=1) for i in range(self.n_filters)] self.zero_pad_image() # zero pad once since zero pad parm > 0 # Initialize weights to be applied to input_feature_map. Sample from N(0,1) as intialization weights if weight_init == 'True': pass # Output volume sizes # TODO: write a function to check if output dim are int types. If not adjust with appropriate zero padding while (self.width_X-self.filter_size+ 2 * self.zero_padding)/self.stride_len % 1 != 0.0: print('yay') self.zero_pad_image() else: self.Output_Width = int((self.width_X - self.filter_size + 2 * self.zero_padding) / (self.stride_len) + 1) self.Output_Height = int((self.height_Y - self.filter_size + 2 * self.zero_padding) / (self.stride_len) + 1) self.output_Tensor = Data(width=self.Output_Width, height=self.Output_Height, depth=self.n_filters) def filter_val_init(self,filter_vol): for filter_indx in range(len(self.filter_map)): self.filter_map[filter_indx].set_data_mtx(filter_vol[filter_indx,:,:]) def im2col(self, X): """ :param X: filter_dim X filter_dim area of current image to be converted to 1 X filter_dim^2 vector :param filter_dim: :return: vector of dimension 1 by filter_dim^2 """ flat_vect = np.reshape(X, -1) return flat_vect def convolution_op(self, image_col, filter_col): conv_result = np.sum(np.dot(image_col, filter_col)) return conv_result def zero_pad(self,x): return np.pad(x,pad_width=(1,1),mode='constant',constant_values=0) def zero_pad_image(self): input_img =self.input_vol.data_mtx.copy() input_img_list = input_img.tolist() padded = False while self.zero_padding < self.filter_size and padded==False: if (self.width_X-self.filter_size+ 2 * self.zero_padding)/self.stride_len % 1 == 0.0 : for j in range(0,input_img.shape[0]): input_img_list[j] = self.zero_pad(input_img_list[j]) print(input_img_list) padded = True else: self.zero_padding += 1 self.input_vol.set_padded_mtx(np.asarray(input_img_list)) def set_weights(self,input_vol): for j in range(len(self.filter_map)): self.filter_map[j].set_data_mtx(input_vol[j,:,:,:]) def Naive_forwardpass(self): """ Forward pass of conv net implementing output map generating function. Returns an tensor of self.Output_Width X self.Output_Height X self.n_filters. Which is happily sent off to the next poor bugger layer of the CNN architecture Not happy too(livid actually) with the efficiency and endless loops but c'est la vie. This is for education purposes. :param X: Image/feature map from previous layer/(just the picture I guess) :return: tensor of vol : self.Output_Width X self.Output_Height X self.n_filters """ for filter_k in range(0, self.n_filters): filter_col = self.im2col(self.filter_map[filter_k].data_mtx) for hgt_indx in range(0, self.Output_Height): for wdth_indx in range(0, self.Output_Width): wdth_start_index = wdth_indx * self.stride_len wdth_end_index= wdth_start_index + self.filter_size hgt_start_index = hgt_indx * self.stride_len hgt_end_index = hgt_start_index + self.filter_size trn_img_area = self.input_vol.padded_mtx[:, wdth_start_index:wdth_end_index, hgt_start_index:hgt_end_index] trn_img_col = self.im2col(trn_img_area) self.output_Tensor.data_mtx[filter_k,wdth_indx , hgt_indx] = self.convolution_op(trn_img_col, filter_col) + np.sum(self.bias_vol[filter_k].data_mtx) return self.output_Tensor # hopefully correct implementation of conv back prop def Naive_backwardpass(self): """ :param X: :return: """ # this fucking backward pass ...sigh # need to make two backward pass gradient calculations # gradient w.r.t filter weights which will be used for weight updates. # gradient w.r.t current image representation/ current layer which will be used as gradient flow to lower layers for filter_j in range(0, len(self.filter_map)): filter_vol = self.filter_map[ filter_j] # fix a single filter,reference to a class object. Make sure that changes are inplace and not new copy object for height_indx in range(0, self.Output_Height): for width_indx in range(0,self.Output_Width): # fixes a single pixel , pixel i,j in layer L the output vol upstream_grad = np.full(shape=(filter_vol.depth, self.filter_size, self.filter_size), fill_value=self.output_Tensor.delta_data_mtx[ filter_j, width_indx, height_indx]) # get dE/d(x_{i,j}) . derivative of error w.r.t fixed pixel w,h
self.padded_mtx = input_mtx self.depth , self.width,self.height = input_mtx.shape self.delta_data_mtx = np.reshape(np.zeros(self.depth*self.height*self.width), newshape=(self.depth, self.height, self.width))
identifier_body
Conv_layer.py
height, depth, weight_init='undefined'): self.width = width self.height = height self.depth = depth n_weight_vals = self.height * self.width * self.depth self.data_mtx = np.reshape(np.zeros(n_weight_vals), newshape=(self.depth, self.height, self.width)) self.delta_data_mtx = np.reshape(np.zeros(n_weight_vals), newshape=(self.depth, self.height, self.width)) self.vectorized_rand_norm = np.vectorize(self.generate_normal_rand, otypes=[np.float]) # weight initialization # if weight initialization not set then use Xavier method for initializing weights 'TODO: provide link' if weight_init != 'undefined': weight_std = np.sqrt(n_weight_vals) self.data_mtx = self.vectorized_rand_norm(self.data_mtx) def get_data(self, width_indx, heigh_indx, depth_indx): pass # weight_patch= def get_shape(self): return self.data_mtx.shape def set_data_elmt(self, i, j, depth, val): self.data_mtx[depth, i, j] = val def set_padded_mtx(self,input_mtx): self.padded_mtx = input_mtx self.depth , self.width,self.height = input_mtx.shape self.delta_data_mtx = np.reshape(np.zeros(self.depth*self.height*self.width), newshape=(self.depth, self.height, self.width)) def set_data_mtx(self,input_mtx): self.data_mtx = input_mtx self.depth , self.width,self.height = input_mtx.shape self.delta_data_mtx = np.reshape(np.zeros(self.depth*self.height*self.width), newshape=(self.depth, self.height, self.width)) def get_gradient(self, x, y, depth): return self.delta_data_mtx[depth, x, y] def set_gradient(self, x, y, depth, grad_val): self.delta_data_mtx[depth, x, y] = grad_val def add_gradient(self, x, y, depth, grad_val): self.delta_data_mtx += grad_val def generate_normal_rand(self, matx_elmt): n_weight_vals = self.height * self.depth * self.depth return np.float(matx_elmt + np.random.normal(loc=0, scale=np.sqrt(n_weight_vals), size=1)) class Naive_Conv_NeuralNet_Layer(object): """ A numpy based, naive implementation of a vanilla convolutional neural net layer. Multiple Conv layers + pooling(optional) + some final output transformations define a full Conv Net Details of the mathematics can be found at the from textbook 'Deep Learning' by Goodman, Bengio et al. Implementation based also on stanford convolutional networks course work: http://cs231n.github.io/convolutional-networks/#conv Code is inspired by karpathy's javascript implementation of a different deep learning layers. Its amazing. So check it out. All(most since I looked at alot of different code in coming to try understand this stuff) goes to ya. Thanks for making your code public dude https://github.com/karpathy/convnetjs """ def __init__(self, input_volume, no_filters, filter_map_dim=3, stride_len=1, zero_padding=1,weight_init='False'): """ :param input_feature_map_dim: :param no_filters: :param filter_map_dim: :param stride_len: :param zero_padding: :return: """ self.num_channels_D, self.width_X, self.height_Y= input_volume.get_shape() self.n_filters = no_filters self.input_vol = input_volume # need to change this to a copy of the input in the future .copy() self.filter_size = filter_map_dim self.stride_len = stride_len self.zero_padding = zero_padding self.filter_map = [Data(width=self.filter_size, height=self.filter_size, depth=self.input_vol.depth,weight_init='normal') for i in range(self.n_filters)] self.bias_vol = [Data(width=1, height=1, depth=1) for i in range(self.n_filters)] self.zero_pad_image() # zero pad once since zero pad parm > 0 # Initialize weights to be applied to input_feature_map. Sample from N(0,1) as intialization weights if weight_init == 'True': pass # Output volume sizes # TODO: write a function to check if output dim are int types. If not adjust with appropriate zero padding while (self.width_X-self.filter_size+ 2 * self.zero_padding)/self.stride_len % 1 != 0.0: print('yay') self.zero_pad_image() else: self.Output_Width = int((self.width_X - self.filter_size + 2 * self.zero_padding) / (self.stride_len) + 1) self.Output_Height = int((self.height_Y - self.filter_size + 2 * self.zero_padding) / (self.stride_len) + 1) self.output_Tensor = Data(width=self.Output_Width, height=self.Output_Height, depth=self.n_filters) def filter_val_init(self,filter_vol): for filter_indx in range(len(self.filter_map)): self.filter_map[filter_indx].set_data_mtx(filter_vol[filter_indx,:,:]) def im2col(self, X): """ :param X: filter_dim X filter_dim area of current image to be converted to 1 X filter_dim^2 vector :param filter_dim: :return: vector of dimension 1 by filter_dim^2 """ flat_vect = np.reshape(X, -1) return flat_vect def convolution_op(self, image_col, filter_col): conv_result = np.sum(np.dot(image_col, filter_col)) return conv_result def zero_pad(self,x): return np.pad(x,pad_width=(1,1),mode='constant',constant_values=0) def zero_pad_image(self): input_img =self.input_vol.data_mtx.copy() input_img_list = input_img.tolist() padded = False while self.zero_padding < self.filter_size and padded==False:
self.input_vol.set_padded_mtx(np.asarray(input_img_list)) def set_weights(self,input_vol): for j in range(len(self.filter_map)): self.filter_map[j].set_data_mtx(input_vol[j,:,:,:]) def Naive_forwardpass(self): """ Forward pass of conv net implementing output map generating function. Returns an tensor of self.Output_Width X self.Output_Height X self.n_filters. Which is happily sent off to the next poor bugger layer of the CNN architecture Not happy too(livid actually) with the efficiency and endless loops but c'est la vie. This is for education purposes. :param X: Image/feature map from previous layer/(just the picture I guess) :return: tensor of vol : self.Output_Width X self.Output_Height X self.n_filters """ for filter_k in range(0, self.n_filters): filter_col = self.im2col(self.filter_map[filter_k].data_mtx) for hgt_indx in range(0, self.Output_Height): for wdth_indx in range(0, self.Output_Width): wdth_start_index = wdth_indx * self.stride_len wdth_end_index= wdth_start_index + self.filter_size hgt_start_index = hgt_indx * self.stride_len hgt_end_index = hgt_start_index + self.filter_size trn_img_area = self.input_vol.padded_mtx[:, wdth_start_index:wdth_end_index, hgt_start_index:hgt_end_index] trn_img_col = self.im2col(trn_img_area) self.output_Tensor.data_mtx[filter_k,wdth_indx , hgt_indx] = self.convolution_op(trn_img_col, filter_col) + np.sum(self.bias_vol[filter_k].data_mtx) return self.output_Tensor # hopefully correct implementation of conv back prop def Naive_backwardpass(self): """ :param X: :return: """ # this fucking backward pass ...sigh # need to make two backward pass gradient calculations # gradient w.r.t filter weights which will be used for weight updates. # gradient w.r.t current image representation/ current layer which will be used as gradient flow to lower layers for filter_j in range(0, len(self.filter_map)): filter_vol = self.filter_map[ filter_j] # fix a single filter,reference to a class object. Make sure that changes are inplace and not new copy object for height_indx in range(0, self.Output_Height): for width_indx in range(0,self.Output_Width): # fixes a single pixel , pixel i,j in layer L the output vol upstream_grad = np.full(shape=(filter_vol.depth, self.filter_size, self.filter_size), fill_value=self.output_Tensor.delta_data_mtx[ filter_j, width_indx, height_indx]) # get dE/d(x_{i,j}) . derivative of error w.r.t fixed pixel w,h,s
if (self.width_X-self.filter_size+ 2 * self.zero_padding)/self.stride_len % 1 == 0.0 : for j in range(0,input_img.shape[0]): input_img_list[j] = self.zero_pad(input_img_list[j]) print(input_img_list) padded = True else: self.zero_padding += 1
conditional_block
Conv_layer.py
height, depth, weight_init='undefined'): self.width = width self.height = height self.depth = depth n_weight_vals = self.height * self.width * self.depth self.data_mtx = np.reshape(np.zeros(n_weight_vals), newshape=(self.depth, self.height, self.width)) self.delta_data_mtx = np.reshape(np.zeros(n_weight_vals), newshape=(self.depth, self.height, self.width)) self.vectorized_rand_norm = np.vectorize(self.generate_normal_rand, otypes=[np.float]) # weight initialization # if weight initialization not set then use Xavier method for initializing weights 'TODO: provide link' if weight_init != 'undefined': weight_std = np.sqrt(n_weight_vals) self.data_mtx = self.vectorized_rand_norm(self.data_mtx) def get_data(self, width_indx, heigh_indx, depth_indx): pass # weight_patch= def get_shape(self): return self.data_mtx.shape def set_data_elmt(self, i, j, depth, val): self.data_mtx[depth, i, j] = val def set_padded_mtx(self,input_mtx): self.padded_mtx = input_mtx self.depth , self.width,self.height = input_mtx.shape self.delta_data_mtx = np.reshape(np.zeros(self.depth*self.height*self.width), newshape=(self.depth, self.height, self.width)) def set_data_mtx(self,input_mtx): self.data_mtx = input_mtx self.depth , self.width,self.height = input_mtx.shape self.delta_data_mtx = np.reshape(np.zeros(self.depth*self.height*self.width), newshape=(self.depth, self.height, self.width)) def get_gradient(self, x, y, depth): return self.delta_data_mtx[depth, x, y] def set_gradient(self, x, y, depth, grad_val): self.delta_data_mtx[depth, x, y] = grad_val def add_gradient(self, x, y, depth, grad_val): self.delta_data_mtx += grad_val def generate_normal_rand(self, matx_elmt): n_weight_vals = self.height * self.depth * self.depth return np.float(matx_elmt + np.random.normal(loc=0, scale=np.sqrt(n_weight_vals), size=1)) class Naive_Conv_NeuralNet_Layer(object): """ A numpy based, naive implementation of a vanilla convolutional neural net layer. Multiple Conv layers + pooling(optional) + some final output transformations define a full Conv Net Details of the mathematics can be found at the from textbook 'Deep Learning' by Goodman, Bengio et al. Implementation based also on stanford convolutional networks course work: http://cs231n.github.io/convolutional-networks/#conv Code is inspired by karpathy's javascript implementation of a different deep learning layers. Its amazing. So check it out. All(most since I looked at alot of different code in coming to try understand this stuff) goes to ya. Thanks for making your code public dude https://github.com/karpathy/convnetjs """ def __init__(self, input_volume, no_filters, filter_map_dim=3, stride_len=1, zero_padding=1,weight_init='False'): """ :param input_feature_map_dim: :param no_filters: :param filter_map_dim: :param stride_len: :param zero_padding: :return: """ self.num_channels_D, self.width_X, self.height_Y= input_volume.get_shape() self.n_filters = no_filters self.input_vol = input_volume # need to change this to a copy of the input in the future .copy() self.filter_size = filter_map_dim self.stride_len = stride_len self.zero_padding = zero_padding self.filter_map = [Data(width=self.filter_size, height=self.filter_size, depth=self.input_vol.depth,weight_init='normal') for i in range(self.n_filters)] self.bias_vol = [Data(width=1, height=1, depth=1) for i in range(self.n_filters)] self.zero_pad_image() # zero pad once since zero pad parm > 0 # Initialize weights to be applied to input_feature_map. Sample from N(0,1) as intialization weights if weight_init == 'True': pass # Output volume sizes # TODO: write a function to check if output dim are int types. If not adjust with appropriate zero padding while (self.width_X-self.filter_size+ 2 * self.zero_padding)/self.stride_len % 1 != 0.0: print('yay') self.zero_pad_image() else: self.Output_Width = int((self.width_X - self.filter_size + 2 * self.zero_padding) / (self.stride_len) + 1) self.Output_Height = int((self.height_Y - self.filter_size + 2 * self.zero_padding) / (self.stride_len) + 1) self.output_Tensor = Data(width=self.Output_Width, height=self.Output_Height, depth=self.n_filters) def filter_val_init(self,filter_vol): for filter_indx in range(len(self.filter_map)): self.filter_map[filter_indx].set_data_mtx(filter_vol[filter_indx,:,:]) def im2col(self, X): """ :param X: filter_dim X filter_dim area of current image to be converted to 1 X filter_dim^2 vector :param filter_dim: :return: vector of dimension 1 by filter_dim^2 """ flat_vect = np.reshape(X, -1) return flat_vect def
(self, image_col, filter_col): conv_result = np.sum(np.dot(image_col, filter_col)) return conv_result def zero_pad(self,x): return np.pad(x,pad_width=(1,1),mode='constant',constant_values=0) def zero_pad_image(self): input_img =self.input_vol.data_mtx.copy() input_img_list = input_img.tolist() padded = False while self.zero_padding < self.filter_size and padded==False: if (self.width_X-self.filter_size+ 2 * self.zero_padding)/self.stride_len % 1 == 0.0 : for j in range(0,input_img.shape[0]): input_img_list[j] = self.zero_pad(input_img_list[j]) print(input_img_list) padded = True else: self.zero_padding += 1 self.input_vol.set_padded_mtx(np.asarray(input_img_list)) def set_weights(self,input_vol): for j in range(len(self.filter_map)): self.filter_map[j].set_data_mtx(input_vol[j,:,:,:]) def Naive_forwardpass(self): """ Forward pass of conv net implementing output map generating function. Returns an tensor of self.Output_Width X self.Output_Height X self.n_filters. Which is happily sent off to the next poor bugger layer of the CNN architecture Not happy too(livid actually) with the efficiency and endless loops but c'est la vie. This is for education purposes. :param X: Image/feature map from previous layer/(just the picture I guess) :return: tensor of vol : self.Output_Width X self.Output_Height X self.n_filters """ for filter_k in range(0, self.n_filters): filter_col = self.im2col(self.filter_map[filter_k].data_mtx) for hgt_indx in range(0, self.Output_Height): for wdth_indx in range(0, self.Output_Width): wdth_start_index = wdth_indx * self.stride_len wdth_end_index= wdth_start_index + self.filter_size hgt_start_index = hgt_indx * self.stride_len hgt_end_index = hgt_start_index + self.filter_size trn_img_area = self.input_vol.padded_mtx[:, wdth_start_index:wdth_end_index, hgt_start_index:hgt_end_index] trn_img_col = self.im2col(trn_img_area) self.output_Tensor.data_mtx[filter_k,wdth_indx , hgt_indx] = self.convolution_op(trn_img_col, filter_col) + np.sum(self.bias_vol[filter_k].data_mtx) return self.output_Tensor # hopefully correct implementation of conv back prop def Naive_backwardpass(self): """ :param X: :return: """ # this fucking backward pass ...sigh # need to make two backward pass gradient calculations # gradient w.r.t filter weights which will be used for weight updates. # gradient w.r.t current image representation/ current layer which will be used as gradient flow to lower layers for filter_j in range(0, len(self.filter_map)): filter_vol = self.filter_map[ filter_j] # fix a single filter,reference to a class object. Make sure that changes are inplace and not new copy object for height_indx in range(0, self.Output_Height): for width_indx in range(0,self.Output_Width): # fixes a single pixel , pixel i,j in layer L the output vol upstream_grad = np.full(shape=(filter_vol.depth, self.filter_size, self.filter_size), fill_value=self.output_Tensor.delta_data_mtx[ filter_j, width_indx, height_indx]) # get dE/d(x_{i,j}) . derivative of error w.r.t fixed pixel w
convolution_op
identifier_name
forms.py
.template.defaultfilters import slugify from django.utils.translation import ugettext_lazy as _ from django.utils.safestring import mark_safe from common.models import Block, MenuItem, Theme, ConfigData, Comment from common.widgets import SelectMultiple, SelectDateTimeWidget from common import util from recaptcha_django import ReCaptchaField from users.models import User, UserDoesNotExist from beautifulsoup.BeautifulSoup import BeautifulSoup class ReCaptchaField(ReCaptchaField): __metaclass__ = djangoforms.monkey_patch def widget_attrs(self, widget): return {'theme':'clean'} class SelectDateTimeField(forms.DateTimeField): widget = SelectDateTimeWidget class BlobWidget(forms.FileInput): pass class BlobField(forms.FileField): widget = BlobWidget class DateTimeProperty(djangoforms.DateTimeProperty): __metaclass__ = djangoforms.monkey_patch def
(self, **kwargs): if self.name == 'deleted_at' or self.auto_now or self.auto_now_add: return None defaults = {'form_class': SelectDateTimeField} defaults.update(kwargs) return super(DateTimeProperty, self).get_form_field(**defaults) class StringListProperty(djangoforms.StringListProperty): __metaclass__ = djangoforms.monkey_patch def get_form_field(self, **kwargs): defaults = {'widget': forms.Textarea, 'initial': '', 'required':False} defaults.update(kwargs) return super(StringListProperty, self).get_form_field(**defaults) def get_value_for_form(self, instance): value = super(StringListProperty, self).get_value_for_form(instance) if not value: return None if isinstance(value, list): value = ', '.join(value) return value def make_value_from_form(self, value): if not value: return [] if isinstance(value, basestring): value = util.get_tags(value.lower()) return value class MultiEmailField(forms.Field): def to_python(self, value): if not value: return [] return util.get_tags(value.lower()) def validate(self, value): super(MultiEmailField, self).validate(value) for email in value: validate_email(email) class Input(forms.widgets.Input): __metaclass__ = djangoforms.monkey_patch def build_attrs(self, extra_attrs=None, **kwargs): attrs = super(Input, self).build_attrs(extra_attrs=extra_attrs, **kwargs) _class = attrs.get('class', '') if _class: _class = "%s %s" % (_class, self.input_type) else: _class = self.input_type attrs.update({'class':_class}) return attrs class Form(forms.Form): __metaclass__ = djangoforms.monkey_patch class ModelForm(djangoforms.ModelForm): __metaclass__ = djangoforms.monkey_patch class Meta: exclude = ['uuid', 'slug', 'created_at', 'updated_at', 'deleted_at'] class CategoryForm(ModelForm): def save(self): if self.instance is None: params = {'slug':unicode(slugify(self.cleaned_data['name']))} self.cleaned_data.update(params) return super(CategoryForm, self).save() class BaseForm(ModelForm): def __init__(self, *args, **kwargs): ModelForm.__init__(self, *args, **kwargs) def clean(self): data = self.cleaned_data if 'name' in data: data['slug'] = unicode(slugify(data['name'])) else: raise forms.ValidationError(_("Name is required")) return data def save(self): if self.instance is None: params = {'uuid':util.generate_uuid()} self.cleaned_data.update(params) return super(BaseForm, self).save() class BaseContentForm(BaseForm): class Meta: exclude = BaseForm.Meta.exclude + ['plain_description'] def __init__(self, *args, **kwargs): BaseForm.__init__(self, *args, **kwargs) self.fields['tags'].widget = forms.TextInput() self.fields['meta_desc'].widget = forms.Textarea(attrs={'class':'ckexclude'}) def save(self): plain_description = '' if 'description' in self.cleaned_data: plain_description = mark_safe(''.join(BeautifulSoup(self.cleaned_data['description']).findAll(text=True))) params = {"plain_description":plain_description} self.cleaned_data.update(params) return BaseForm.save(self) class CommentForm(ModelForm): class Meta: model = Comment exclude = ModelForm.Meta.exclude + ['author', 'owner', 'content', 'content_type'] def __init__(self, *args, **kwargs): self.extra_params = {} if "extra_params" in kwargs: self.extra_params = kwargs.pop("extra_params") super(CommentForm, self).__init__(*args, **kwargs) def save(self): self.cleaned_data.update(self.extra_params) return ModelForm.save(self) class UnloggedCommentForm(CommentForm): class Meta(CommentForm.Meta): pass captcha = ReCaptchaField() class BlockNewForm(BaseForm): class Meta: model = Block exclude = ['uuid', 'slug', 'args', 'deleted_at', 'params'] def __init__(self, *args, **kwargs): super(BlockNewForm, self).__init__(*args, **kwargs) self.fields['menus'].widget = forms.RadioSelect(choices=settings.BLOCK_MENUS_OPTION.items(), attrs={'class':'radioselect'}) attrs={'disabled':'disabled'} self.fields['visibility'].widget = SelectMultiple(choices=MenuItem.get_choices(), attrs=attrs) self.fields['model'].widget = forms.Select(choices=Block.get_models_choices()) def save(self): if not self.cleaned_data['visibility'] == '[]': self.cleaned_data['visibility'] = util.get_tags(self.cleaned_data['visibility']) else: self.cleaned_data['visibility'] = [] return super(BlockNewForm, self).save() class BlockForm(BaseForm): class Meta: model = Block exclude = ['uuid', 'slug', 'model', 'args', 'deleted_at', 'params'] def __init__(self, *args, **kwargs): super(BlockForm, self).__init__(*args, **kwargs) self.fields['menus'].widget = forms.RadioSelect(choices=settings.BLOCK_MENUS_OPTION.items(), attrs={'class':'radioselect'}) attrs = {} if self.instance.menus == 'all' or self.instance.menus == 'none': attrs={'disabled':'disabled'} self.fields['visibility'].widget = SelectMultiple(choices=MenuItem.get_choices(), attrs=attrs) def save(self): if not self.cleaned_data['visibility'] == '[]': self.cleaned_data['visibility'] = util.get_tags(self.cleaned_data['visibility']) else: self.cleaned_data['visibility'] = [] return super(BlockForm, self).save() class StaticBlockForm(BlockForm): static_content = forms.CharField(widget=forms.Textarea, label=_("Static Content")) class Meta: model = Block exclude = ['uuid', 'slug', 'model', 'args', 'deleted_at'] def __init__(self, *args, **kwargs): logging.info("****** common.forms.StaticBlockForm") super(StaticBlockForm, self).__init__(*args, **kwargs) logging.info(" instance: %s " % self.instance) logging.info(" params: %s " % self.instance.params) self.fields['static_content'].initial = self.instance.params.get('content', '') self.fields.keyOrder = ['name', 'position', 'menus', 'visibility', 'order', 'static_content'] def save(self): logging.info("** common.forms.StaticBlockForm") block_ref = super(StaticBlockForm, self).save() block_ref.params['content'] = self.cleaned_data['static_content'] block_ref.put() return block_ref class AdminSiteForm(Form): site_name = forms.CharField() meta_description = forms.CharField(widget=forms.Textarea) meta_keywords = forms.CharField(widget=forms.Textarea) theme = forms.ChoiceField(choices=Theme.get_choices()) def __init__(self, *args, **kwargs): logging.info(">> AdminSiteForm") super(AdminSiteForm, self).__init__(*args, **kwargs) self.fields['site_name'].initial = ConfigData.get_configdata('SITE_NAME') self.fields['meta_description'].initial = ConfigData.get_configdata('SITE_DESCRIPTION') self.fields['meta_keywords'].initial = ConfigData.get_configdata('SITE_KEYWORDS') self.fields['theme'].choices = Theme.get_choices() self.fields['theme'].widget = forms.Select(choices=Theme.get_choices()) self.fields['theme'].initial = Theme.get_active().uuid def save(self): ConfigData.set_configdata('SITE_NAME', self.cleaned_data['site_name']) ConfigData.set_configdata('SITE_DESCRIPTION', self.cleaned_data['meta_description']) ConfigData.set_configdata('SITE_KEYWORDS', self.cleaned_data['meta_keywords']) Theme.check_for_duplicated_active_themes(self.cleaned_data['theme']) return True class InstallForm(AdminSiteForm): username = forms.RegexField(label=_("Admin Username"), max_length=30, regex=r'^\w+$', error_message = _("This value must contain only letters, numbers and underscores.")) first_name = forms.CharField(label=_("First Name")) last_name =
get_form_field
identifier_name
forms.py
from django import forms from django.conf import settings from django.core.validators import validate_email from django.template.defaultfilters import slugify from django.utils.translation import ugettext_lazy as _ from django.utils.safestring import mark_safe from common.models import Block, MenuItem, Theme, ConfigData, Comment from common.widgets import SelectMultiple, SelectDateTimeWidget from common import util from recaptcha_django import ReCaptchaField from users.models import User, UserDoesNotExist from beautifulsoup.BeautifulSoup import BeautifulSoup class ReCaptchaField(ReCaptchaField): __metaclass__ = djangoforms.monkey_patch def widget_attrs(self, widget): return {'theme':'clean'} class SelectDateTimeField(forms.DateTimeField): widget = SelectDateTimeWidget class BlobWidget(forms.FileInput): pass class BlobField(forms.FileField): widget = BlobWidget class DateTimeProperty(djangoforms.DateTimeProperty): __metaclass__ = djangoforms.monkey_patch def get_form_field(self, **kwargs): if self.name == 'deleted_at' or self.auto_now or self.auto_now_add: return None defaults = {'form_class': SelectDateTimeField} defaults.update(kwargs) return super(DateTimeProperty, self).get_form_field(**defaults) class StringListProperty(djangoforms.StringListProperty): __metaclass__ = djangoforms.monkey_patch def get_form_field(self, **kwargs): defaults = {'widget': forms.Textarea, 'initial': '', 'required':False} defaults.update(kwargs) return super(StringListProperty, self).get_form_field(**defaults) def get_value_for_form(self, instance): value = super(StringListProperty, self).get_value_for_form(instance) if not value: return None if isinstance(value, list): value = ', '.join(value) return value def make_value_from_form(self, value): if not value: return [] if isinstance(value, basestring): value = util.get_tags(value.lower()) return value class MultiEmailField(forms.Field): def to_python(self, value): if not value: return [] return util.get_tags(value.lower()) def validate(self, value): super(MultiEmailField, self).validate(value) for email in value: validate_email(email) class Input(forms.widgets.Input): __metaclass__ = djangoforms.monkey_patch def build_attrs(self, extra_attrs=None, **kwargs): attrs = super(Input, self).build_attrs(extra_attrs=extra_attrs, **kwargs) _class = attrs.get('class', '') if _class: _class = "%s %s" % (_class, self.input_type) else: _class = self.input_type attrs.update({'class':_class}) return attrs class Form(forms.Form): __metaclass__ = djangoforms.monkey_patch class ModelForm(djangoforms.ModelForm): __metaclass__ = djangoforms.monkey_patch class Meta: exclude = ['uuid', 'slug', 'created_at', 'updated_at', 'deleted_at'] class CategoryForm(ModelForm): def save(self): if self.instance is None: params = {'slug':unicode(slugify(self.cleaned_data['name']))} self.cleaned_data.update(params) return super(CategoryForm, self).save() class BaseForm(ModelForm): def __init__(self, *args, **kwargs): ModelForm.__init__(self, *args, **kwargs) def clean(self): data = self.cleaned_data if 'name' in data: data['slug'] = unicode(slugify(data['name'])) else: raise forms.ValidationError(_("Name is required")) return data def save(self): if self.instance is None: params = {'uuid':util.generate_uuid()} self.cleaned_data.update(params) return super(BaseForm, self).save() class BaseContentForm(BaseForm): class Meta: exclude = BaseForm.Meta.exclude + ['plain_description'] def __init__(self, *args, **kwargs): BaseForm.__init__(self, *args, **kwargs) self.fields['tags'].widget = forms.TextInput() self.fields['meta_desc'].widget = forms.Textarea(attrs={'class':'ckexclude'}) def save(self): plain_description = '' if 'description' in self.cleaned_data: plain_description = mark_safe(''.join(BeautifulSoup(self.cleaned_data['description']).findAll(text=True))) params = {"plain_description":plain_description} self.cleaned_data.update(params) return BaseForm.save(self) class CommentForm(ModelForm): class Meta: model = Comment exclude = ModelForm.Meta.exclude + ['author', 'owner', 'content', 'content_type'] def __init__(self, *args, **kwargs): self.extra_params = {} if "extra_params" in kwargs: self.extra_params = kwargs.pop("extra_params") super(CommentForm, self).__init__(*args, **kwargs) def save(self): self.cleaned_data.update(self.extra_params) return ModelForm.save(self) class UnloggedCommentForm(CommentForm): class Meta(CommentForm.Meta): pass captcha = ReCaptchaField() class BlockNewForm(BaseForm): class Meta: model = Block exclude = ['uuid', 'slug', 'args', 'deleted_at', 'params'] def __init__(self, *args, **kwargs): super(BlockNewForm, self).__init__(*args, **kwargs) self.fields['menus'].widget = forms.RadioSelect(choices=settings.BLOCK_MENUS_OPTION.items(), attrs={'class':'radioselect'}) attrs={'disabled':'disabled'} self.fields['visibility'].widget = SelectMultiple(choices=MenuItem.get_choices(), attrs=attrs) self.fields['model'].widget = forms.Select(choices=Block.get_models_choices()) def save(self): if not self.cleaned_data['visibility'] == '[]': self.cleaned_data['visibility'] = util.get_tags(self.cleaned_data['visibility']) else: self.cleaned_data['visibility'] = [] return super(BlockNewForm, self).save() class BlockForm(BaseForm): class Meta: model = Block exclude = ['uuid', 'slug', 'model', 'args', 'deleted_at', 'params'] def __init__(self, *args, **kwargs): super(BlockForm, self).__init__(*args, **kwargs) self.fields['menus'].widget = forms.RadioSelect(choices=settings.BLOCK_MENUS_OPTION.items(), attrs={'class':'radioselect'}) attrs = {} if self.instance.menus == 'all' or self.instance.menus == 'none': attrs={'disabled':'disabled'} self.fields['visibility'].widget = SelectMultiple(choices=MenuItem.get_choices(), attrs=attrs) def save(self): if not self.cleaned_data['visibility'] == '[]': self.cleaned_data['visibility'] = util.get_tags(self.cleaned_data['visibility']) else: self.cleaned_data['visibility'] = [] return super(BlockForm, self).save() class StaticBlockForm(BlockForm): static_content = forms.CharField(widget=forms.Textarea, label=_("Static Content")) class Meta: model = Block exclude = ['uuid', 'slug', 'model', 'args', 'deleted_at'] def __init__(self, *args, **kwargs): logging.info("****** common.forms.StaticBlockForm") super(StaticBlockForm, self).__init__(*args, **kwargs) logging.info(" instance: %s " % self.instance) logging.info(" params: %s " % self.instance.params) self.fields['static_content'].initial = self.instance.params.get('content', '') self.fields.keyOrder = ['name', 'position', 'menus', 'visibility', 'order', 'static_content'] def save(self): logging.info("** common.forms.StaticBlockForm") block_ref = super(StaticBlockForm, self).save() block_ref.params['content'] = self.cleaned_data['static_content'] block_ref.put() return block_ref class AdminSiteForm(Form): site_name = forms.CharField() meta_description = forms.CharField(widget=forms.Textarea) meta_keywords = forms.CharField(widget=forms.Textarea) theme = forms.ChoiceField(choices=Theme.get_choices()) def __init__(self, *args, **kwargs): logging.info(">> AdminSiteForm") super(AdminSiteForm, self).__init__(*args, **kwargs) self.fields['site_name'].initial = ConfigData.get_configdata('SITE_NAME') self.fields['meta_description'].initial = ConfigData.get_configdata('SITE_DESCRIPTION') self.fields['meta_keywords'].initial = ConfigData.get_configdata('SITE_KEYWORDS') self.fields['theme'].choices = Theme.get_choices() self.fields['theme'].widget = forms.Select(choices=Theme.get_choices()) self.fields['theme'].initial = Theme.get_active().uuid def save(self): ConfigData.set_configdata('SITE_NAME', self.cleaned_data['site_name']) ConfigData.set_configdata('SITE_DESCRIPTION', self.cleaned_data['meta_description']) ConfigData.set_configdata('SITE_KEYWORDS', self.cleaned_data['meta_keywords']) Theme.check_for_duplicated_active_themes(self.cleaned_data['theme']) return True class InstallForm(AdminSiteForm): username = forms.RegexField(label=_("Admin Username"), max_length=30, regex=r'^\w+$', error_message = _("This value must
import logging
random_line_split
forms.py
.template.defaultfilters import slugify from django.utils.translation import ugettext_lazy as _ from django.utils.safestring import mark_safe from common.models import Block, MenuItem, Theme, ConfigData, Comment from common.widgets import SelectMultiple, SelectDateTimeWidget from common import util from recaptcha_django import ReCaptchaField from users.models import User, UserDoesNotExist from beautifulsoup.BeautifulSoup import BeautifulSoup class ReCaptchaField(ReCaptchaField): __metaclass__ = djangoforms.monkey_patch def widget_attrs(self, widget): return {'theme':'clean'} class SelectDateTimeField(forms.DateTimeField): widget = SelectDateTimeWidget class BlobWidget(forms.FileInput): pass class BlobField(forms.FileField): widget = BlobWidget class DateTimeProperty(djangoforms.DateTimeProperty): __metaclass__ = djangoforms.monkey_patch def get_form_field(self, **kwargs): if self.name == 'deleted_at' or self.auto_now or self.auto_now_add: return None defaults = {'form_class': SelectDateTimeField} defaults.update(kwargs) return super(DateTimeProperty, self).get_form_field(**defaults) class StringListProperty(djangoforms.StringListProperty): __metaclass__ = djangoforms.monkey_patch def get_form_field(self, **kwargs): defaults = {'widget': forms.Textarea, 'initial': '', 'required':False} defaults.update(kwargs) return super(StringListProperty, self).get_form_field(**defaults) def get_value_for_form(self, instance): value = super(StringListProperty, self).get_value_for_form(instance) if not value: return None if isinstance(value, list): value = ', '.join(value) return value def make_value_from_form(self, value): if not value: return [] if isinstance(value, basestring): value = util.get_tags(value.lower()) return value class MultiEmailField(forms.Field): def to_python(self, value): if not value: return [] return util.get_tags(value.lower()) def validate(self, value): super(MultiEmailField, self).validate(value) for email in value: validate_email(email) class Input(forms.widgets.Input): __metaclass__ = djangoforms.monkey_patch def build_attrs(self, extra_attrs=None, **kwargs): attrs = super(Input, self).build_attrs(extra_attrs=extra_attrs, **kwargs) _class = attrs.get('class', '') if _class: _class = "%s %s" % (_class, self.input_type) else: _class = self.input_type attrs.update({'class':_class}) return attrs class Form(forms.Form): __metaclass__ = djangoforms.monkey_patch class ModelForm(djangoforms.ModelForm): __metaclass__ = djangoforms.monkey_patch class Meta: exclude = ['uuid', 'slug', 'created_at', 'updated_at', 'deleted_at'] class CategoryForm(ModelForm): def save(self): if self.instance is None: params = {'slug':unicode(slugify(self.cleaned_data['name']))} self.cleaned_data.update(params) return super(CategoryForm, self).save() class BaseForm(ModelForm): def __init__(self, *args, **kwargs): ModelForm.__init__(self, *args, **kwargs) def clean(self): data = self.cleaned_data if 'name' in data: data['slug'] = unicode(slugify(data['name'])) else: raise forms.ValidationError(_("Name is required")) return data def save(self): if self.instance is None: params = {'uuid':util.generate_uuid()} self.cleaned_data.update(params) return super(BaseForm, self).save() class BaseContentForm(BaseForm): class Meta: exclude = BaseForm.Meta.exclude + ['plain_description'] def __init__(self, *args, **kwargs): BaseForm.__init__(self, *args, **kwargs) self.fields['tags'].widget = forms.TextInput() self.fields['meta_desc'].widget = forms.Textarea(attrs={'class':'ckexclude'}) def save(self): plain_description = '' if 'description' in self.cleaned_data: plain_description = mark_safe(''.join(BeautifulSoup(self.cleaned_data['description']).findAll(text=True))) params = {"plain_description":plain_description} self.cleaned_data.update(params) return BaseForm.save(self) class CommentForm(ModelForm):
class UnloggedCommentForm(CommentForm): class Meta(CommentForm.Meta): pass captcha = ReCaptchaField() class BlockNewForm(BaseForm): class Meta: model = Block exclude = ['uuid', 'slug', 'args', 'deleted_at', 'params'] def __init__(self, *args, **kwargs): super(BlockNewForm, self).__init__(*args, **kwargs) self.fields['menus'].widget = forms.RadioSelect(choices=settings.BLOCK_MENUS_OPTION.items(), attrs={'class':'radioselect'}) attrs={'disabled':'disabled'} self.fields['visibility'].widget = SelectMultiple(choices=MenuItem.get_choices(), attrs=attrs) self.fields['model'].widget = forms.Select(choices=Block.get_models_choices()) def save(self): if not self.cleaned_data['visibility'] == '[]': self.cleaned_data['visibility'] = util.get_tags(self.cleaned_data['visibility']) else: self.cleaned_data['visibility'] = [] return super(BlockNewForm, self).save() class BlockForm(BaseForm): class Meta: model = Block exclude = ['uuid', 'slug', 'model', 'args', 'deleted_at', 'params'] def __init__(self, *args, **kwargs): super(BlockForm, self).__init__(*args, **kwargs) self.fields['menus'].widget = forms.RadioSelect(choices=settings.BLOCK_MENUS_OPTION.items(), attrs={'class':'radioselect'}) attrs = {} if self.instance.menus == 'all' or self.instance.menus == 'none': attrs={'disabled':'disabled'} self.fields['visibility'].widget = SelectMultiple(choices=MenuItem.get_choices(), attrs=attrs) def save(self): if not self.cleaned_data['visibility'] == '[]': self.cleaned_data['visibility'] = util.get_tags(self.cleaned_data['visibility']) else: self.cleaned_data['visibility'] = [] return super(BlockForm, self).save() class StaticBlockForm(BlockForm): static_content = forms.CharField(widget=forms.Textarea, label=_("Static Content")) class Meta: model = Block exclude = ['uuid', 'slug', 'model', 'args', 'deleted_at'] def __init__(self, *args, **kwargs): logging.info("****** common.forms.StaticBlockForm") super(StaticBlockForm, self).__init__(*args, **kwargs) logging.info(" instance: %s " % self.instance) logging.info(" params: %s " % self.instance.params) self.fields['static_content'].initial = self.instance.params.get('content', '') self.fields.keyOrder = ['name', 'position', 'menus', 'visibility', 'order', 'static_content'] def save(self): logging.info("** common.forms.StaticBlockForm") block_ref = super(StaticBlockForm, self).save() block_ref.params['content'] = self.cleaned_data['static_content'] block_ref.put() return block_ref class AdminSiteForm(Form): site_name = forms.CharField() meta_description = forms.CharField(widget=forms.Textarea) meta_keywords = forms.CharField(widget=forms.Textarea) theme = forms.ChoiceField(choices=Theme.get_choices()) def __init__(self, *args, **kwargs): logging.info(">> AdminSiteForm") super(AdminSiteForm, self).__init__(*args, **kwargs) self.fields['site_name'].initial = ConfigData.get_configdata('SITE_NAME') self.fields['meta_description'].initial = ConfigData.get_configdata('SITE_DESCRIPTION') self.fields['meta_keywords'].initial = ConfigData.get_configdata('SITE_KEYWORDS') self.fields['theme'].choices = Theme.get_choices() self.fields['theme'].widget = forms.Select(choices=Theme.get_choices()) self.fields['theme'].initial = Theme.get_active().uuid def save(self): ConfigData.set_configdata('SITE_NAME', self.cleaned_data['site_name']) ConfigData.set_configdata('SITE_DESCRIPTION', self.cleaned_data['meta_description']) ConfigData.set_configdata('SITE_KEYWORDS', self.cleaned_data['meta_keywords']) Theme.check_for_duplicated_active_themes(self.cleaned_data['theme']) return True class InstallForm(AdminSiteForm): username = forms.RegexField(label=_("Admin Username"), max_length=30, regex=r'^\w+$', error_message = _("This value must contain only letters, numbers and underscores.")) first_name = forms.CharField(label=_("First Name")) last_name =
class Meta: model = Comment exclude = ModelForm.Meta.exclude + ['author', 'owner', 'content', 'content_type'] def __init__(self, *args, **kwargs): self.extra_params = {} if "extra_params" in kwargs: self.extra_params = kwargs.pop("extra_params") super(CommentForm, self).__init__(*args, **kwargs) def save(self): self.cleaned_data.update(self.extra_params) return ModelForm.save(self)
identifier_body
forms.py
.template.defaultfilters import slugify from django.utils.translation import ugettext_lazy as _ from django.utils.safestring import mark_safe from common.models import Block, MenuItem, Theme, ConfigData, Comment from common.widgets import SelectMultiple, SelectDateTimeWidget from common import util from recaptcha_django import ReCaptchaField from users.models import User, UserDoesNotExist from beautifulsoup.BeautifulSoup import BeautifulSoup class ReCaptchaField(ReCaptchaField): __metaclass__ = djangoforms.monkey_patch def widget_attrs(self, widget): return {'theme':'clean'} class SelectDateTimeField(forms.DateTimeField): widget = SelectDateTimeWidget class BlobWidget(forms.FileInput): pass class BlobField(forms.FileField): widget = BlobWidget class DateTimeProperty(djangoforms.DateTimeProperty): __metaclass__ = djangoforms.monkey_patch def get_form_field(self, **kwargs): if self.name == 'deleted_at' or self.auto_now or self.auto_now_add: return None defaults = {'form_class': SelectDateTimeField} defaults.update(kwargs) return super(DateTimeProperty, self).get_form_field(**defaults) class StringListProperty(djangoforms.StringListProperty): __metaclass__ = djangoforms.monkey_patch def get_form_field(self, **kwargs): defaults = {'widget': forms.Textarea, 'initial': '', 'required':False} defaults.update(kwargs) return super(StringListProperty, self).get_form_field(**defaults) def get_value_for_form(self, instance): value = super(StringListProperty, self).get_value_for_form(instance) if not value: return None if isinstance(value, list): value = ', '.join(value) return value def make_value_from_form(self, value): if not value:
if isinstance(value, basestring): value = util.get_tags(value.lower()) return value class MultiEmailField(forms.Field): def to_python(self, value): if not value: return [] return util.get_tags(value.lower()) def validate(self, value): super(MultiEmailField, self).validate(value) for email in value: validate_email(email) class Input(forms.widgets.Input): __metaclass__ = djangoforms.monkey_patch def build_attrs(self, extra_attrs=None, **kwargs): attrs = super(Input, self).build_attrs(extra_attrs=extra_attrs, **kwargs) _class = attrs.get('class', '') if _class: _class = "%s %s" % (_class, self.input_type) else: _class = self.input_type attrs.update({'class':_class}) return attrs class Form(forms.Form): __metaclass__ = djangoforms.monkey_patch class ModelForm(djangoforms.ModelForm): __metaclass__ = djangoforms.monkey_patch class Meta: exclude = ['uuid', 'slug', 'created_at', 'updated_at', 'deleted_at'] class CategoryForm(ModelForm): def save(self): if self.instance is None: params = {'slug':unicode(slugify(self.cleaned_data['name']))} self.cleaned_data.update(params) return super(CategoryForm, self).save() class BaseForm(ModelForm): def __init__(self, *args, **kwargs): ModelForm.__init__(self, *args, **kwargs) def clean(self): data = self.cleaned_data if 'name' in data: data['slug'] = unicode(slugify(data['name'])) else: raise forms.ValidationError(_("Name is required")) return data def save(self): if self.instance is None: params = {'uuid':util.generate_uuid()} self.cleaned_data.update(params) return super(BaseForm, self).save() class BaseContentForm(BaseForm): class Meta: exclude = BaseForm.Meta.exclude + ['plain_description'] def __init__(self, *args, **kwargs): BaseForm.__init__(self, *args, **kwargs) self.fields['tags'].widget = forms.TextInput() self.fields['meta_desc'].widget = forms.Textarea(attrs={'class':'ckexclude'}) def save(self): plain_description = '' if 'description' in self.cleaned_data: plain_description = mark_safe(''.join(BeautifulSoup(self.cleaned_data['description']).findAll(text=True))) params = {"plain_description":plain_description} self.cleaned_data.update(params) return BaseForm.save(self) class CommentForm(ModelForm): class Meta: model = Comment exclude = ModelForm.Meta.exclude + ['author', 'owner', 'content', 'content_type'] def __init__(self, *args, **kwargs): self.extra_params = {} if "extra_params" in kwargs: self.extra_params = kwargs.pop("extra_params") super(CommentForm, self).__init__(*args, **kwargs) def save(self): self.cleaned_data.update(self.extra_params) return ModelForm.save(self) class UnloggedCommentForm(CommentForm): class Meta(CommentForm.Meta): pass captcha = ReCaptchaField() class BlockNewForm(BaseForm): class Meta: model = Block exclude = ['uuid', 'slug', 'args', 'deleted_at', 'params'] def __init__(self, *args, **kwargs): super(BlockNewForm, self).__init__(*args, **kwargs) self.fields['menus'].widget = forms.RadioSelect(choices=settings.BLOCK_MENUS_OPTION.items(), attrs={'class':'radioselect'}) attrs={'disabled':'disabled'} self.fields['visibility'].widget = SelectMultiple(choices=MenuItem.get_choices(), attrs=attrs) self.fields['model'].widget = forms.Select(choices=Block.get_models_choices()) def save(self): if not self.cleaned_data['visibility'] == '[]': self.cleaned_data['visibility'] = util.get_tags(self.cleaned_data['visibility']) else: self.cleaned_data['visibility'] = [] return super(BlockNewForm, self).save() class BlockForm(BaseForm): class Meta: model = Block exclude = ['uuid', 'slug', 'model', 'args', 'deleted_at', 'params'] def __init__(self, *args, **kwargs): super(BlockForm, self).__init__(*args, **kwargs) self.fields['menus'].widget = forms.RadioSelect(choices=settings.BLOCK_MENUS_OPTION.items(), attrs={'class':'radioselect'}) attrs = {} if self.instance.menus == 'all' or self.instance.menus == 'none': attrs={'disabled':'disabled'} self.fields['visibility'].widget = SelectMultiple(choices=MenuItem.get_choices(), attrs=attrs) def save(self): if not self.cleaned_data['visibility'] == '[]': self.cleaned_data['visibility'] = util.get_tags(self.cleaned_data['visibility']) else: self.cleaned_data['visibility'] = [] return super(BlockForm, self).save() class StaticBlockForm(BlockForm): static_content = forms.CharField(widget=forms.Textarea, label=_("Static Content")) class Meta: model = Block exclude = ['uuid', 'slug', 'model', 'args', 'deleted_at'] def __init__(self, *args, **kwargs): logging.info("****** common.forms.StaticBlockForm") super(StaticBlockForm, self).__init__(*args, **kwargs) logging.info(" instance: %s " % self.instance) logging.info(" params: %s " % self.instance.params) self.fields['static_content'].initial = self.instance.params.get('content', '') self.fields.keyOrder = ['name', 'position', 'menus', 'visibility', 'order', 'static_content'] def save(self): logging.info("** common.forms.StaticBlockForm") block_ref = super(StaticBlockForm, self).save() block_ref.params['content'] = self.cleaned_data['static_content'] block_ref.put() return block_ref class AdminSiteForm(Form): site_name = forms.CharField() meta_description = forms.CharField(widget=forms.Textarea) meta_keywords = forms.CharField(widget=forms.Textarea) theme = forms.ChoiceField(choices=Theme.get_choices()) def __init__(self, *args, **kwargs): logging.info(">> AdminSiteForm") super(AdminSiteForm, self).__init__(*args, **kwargs) self.fields['site_name'].initial = ConfigData.get_configdata('SITE_NAME') self.fields['meta_description'].initial = ConfigData.get_configdata('SITE_DESCRIPTION') self.fields['meta_keywords'].initial = ConfigData.get_configdata('SITE_KEYWORDS') self.fields['theme'].choices = Theme.get_choices() self.fields['theme'].widget = forms.Select(choices=Theme.get_choices()) self.fields['theme'].initial = Theme.get_active().uuid def save(self): ConfigData.set_configdata('SITE_NAME', self.cleaned_data['site_name']) ConfigData.set_configdata('SITE_DESCRIPTION', self.cleaned_data['meta_description']) ConfigData.set_configdata('SITE_KEYWORDS', self.cleaned_data['meta_keywords']) Theme.check_for_duplicated_active_themes(self.cleaned_data['theme']) return True class InstallForm(AdminSiteForm): username = forms.RegexField(label=_("Admin Username"), max_length=30, regex=r'^\w+$', error_message = _("This value must contain only letters, numbers and underscores.")) first_name = forms.CharField(label=_("First Name")) last_name =
return []
conditional_block
mod.rs
i: usize, world: &'a World, } impl<'a> Iterator for ForceIterator<'a> { type Item = Vector3<f32>; fn next(&mut self) -> Option<Vector3<f32>> { if self.i < self.world.objects.len() { let force = self.world.force_on(self.i); self.i += 1; Some(force) } else { None } } } /// These errors can be thrown when validating a world. #[derive(Debug, Snafu)] pub enum WorldError { /// An error indicating that one of the shapes is too close too the edge, causing the bounding /// box to cross the boundary. #[snafu(display("shape {} too close to edge", index))] ShapeTooCloseToEdge { /// The index of the violating object. index: usize, }, /// An error indicating that the bounding boxes of two objects in this world intersect and /// and therefore this world is invalid. #[snafu(display("bounding boxes of shapes {} and {} intersect", index_1, index_2))] ShapesIntersect { /// The index of the first object intersecting with the second. index_1: usize, /// The index of the second object intersecting with the first. index_2: usize, }, } impl World { /// Enable or disable the progress bar for the simulation. pub fn set_progress_bar(&mut self, enable: bool) { self.use_progress_bar = enable; } /// Obtain a force iterator for all objects in this world. pub fn forces(&self) -> ForceIterator<'_> { ForceIterator { i: 0, world: &self } } /// Compute the force on the `i`'th object. pub fn force_on(&self, i: usize) -> Vector3<f32>
start_freq, end_freq, start_force, end_force, start_force.norm(), ) } /// This function validates the geometry of the world. The function should be called, because it /// guarantees overflows later on in the simulation. /// /// # Errors /// - If any of the shapes is too close to the world border, the simulation can't be run and a /// `WorldError::ShapeTooCloseToEdge` will be returned. To fix this, move the object or increase /// the grid size. /// /// - If any of the objects are too close too eachother, their boundingboxes might intersect and /// the results will be invalid. If this is the case, a `WorldError::ShapesIntersect` will be /// returned. The violating shape indexes will be contained within. To fix this, move one or /// both of the objects. pub fn validate(&self) -> Result<(), WorldError> { let bbox_world = BoundingBox::new(0, 0, 0, self.size.x, self.size.y, self.size.z); let expanded_boxes = self .objects .iter() .enumerate() .map(|(index, obj)| { obj.bbox() .expanded(2) .map_err(|_| WorldError::ShapeTooCloseToEdge { index }) }) .collect::<Result<Vec<_>, _>>()?; for (i, bbox_1) in expanded_boxes.iter().enumerate() { // Check for intersection with world if !bbox_1.inside(&bbox_world) { return Err(WorldError::ShapeTooCloseToEdge { index: i }); } // Check for intersection with other objects for (j, bbox_2) in expanded_boxes.iter().enumerate() { if i < j && bbox_1.intersects(&bbox_2) { return Err(WorldError::ShapesIntersect { index_1: i, index_2: j, }); } } } Ok(()) } /// Performs a recursive integration between two frequencies. If the difference between the /// midpoint force and the linear interpolation is too large, both sides of the domain will use /// this function recursively to integrate the force. pub fn integrate_force_between_frequencies( &self, i: usize, start_frequency: f32, end_frequency: f32, start_value: Vector3<f32>, end_value: Vector3<f32>, max: f32, ) -> Vector3<f32> { // Do a recursive integration. The function should be smooth. let middle_frequency = 0.5 * (start_frequency + end_frequency); let middle_value = self.force_on_for_freq(i, middle_frequency); let average = (start_value + end_value) / 2.0; if (average - middle_value).norm() * (end_frequency - start_frequency) < self.simulation_config.frequency_threshold * max { // The change in area from the middle value vs extrapolation is less than the threshold 0.5 * (start_value + 2.0 * middle_value + end_value) * (end_frequency - start_frequency) } else { self.integrate_force_between_frequencies( i, start_frequency, middle_frequency, start_value, middle_value, max, ) + self.integrate_force_between_frequencies( i, middle_frequency, end_frequency, middle_value, end_value, max, ) } } /// Compute the force on object `i` for a certain `frequency`. This method will also subtract /// the error forces due to quantization by subtracting the force due to single objects. fn force_on_for_freq(&self, i: usize, frequency: f32) -> Vector3<f32> { // Progress bar let bbox = &self.objects[i].bbox(); let dx = bbox.x1 - bbox.x0 + 4; let dy = bbox.y1 - bbox.y0 + 4; let dz = bbox.z1 - bbox.z0 + 4; let count = 2 * (dx * dy + dy * dz + dz * dx) * (1 + self.objects.len()); let progress_bar = if self.use_progress_bar { let progress_bar = Arc::new(Mutex::new(ProgressBar::new(count as u64))); progress_bar.lock().unwrap().format("[=>~]"); progress_bar.lock().unwrap().tick(); Some(progress_bar) } else { None }; let perm_all_geom = &self.permittivity_field_all_geometry(frequency); let mut total_force = self.force_on_for_freq_and_geometry(frequency, perm_all_geom, bbox, &progress_bar); // Discretization gives rise to forces of an object on itself. Removing these gives more // accurate results. for other in &self.objects { let perm = &self.permittivity_field(frequency, &[*other]); total_force -= self.force_on_for_freq_and_geometry(frequency, perm, bbox, &progress_bar); } if let Some(progress_bar) = progress_bar { progress_bar.lock().unwrap().finish_println(""); } println!( "Force for frequency {}: ({}, {}, {})", frequency, total_force.x, total_force.y, total_force.z ); total_force } /// Compute the force on the geometry inside `BoundingBox`, for the given permittivity field /// `perm` and `BoundingBox` `bbox`. fn force_on_for_freq_and_geometry( &self, frequency: f32, perm: &ScalarField, bbox: &BoundingBox, progress_bar: &Option<Arc<Mutex<ProgressBar<Stdout>>>>, ) -> Vector3<f32> { (0..6) .into_par_iter() .map(|face| { (match face { 0 => CosineBasis::new( Point3::new(bbox.x0 - 2, bbox.y0 - 2, bbox.z0 - 2), Point3::new(bbox.x1 + 2, bbox.y1 + 2, bbox.z0 - 2), frequency, perm, &self.simulation_config, Direction::NegZ, ), 1 => CosineBasis::new( Point3::new(bbox.x0 - 2, bbox.y0 - 2, bbox.z1 + 2), Point3::new(bbox.x1 + 2, bbox.y1 + 2, bbox.z1 + 2), frequency, perm, &self.simulation_config, Direction::Z, ), 2 => CosineBasis::new( Point
{ println!("Geometry:"); println!( "\tWorld size: ({}, {}, {})", self.size.x, self.size.y, self.size.z ); for (i, bbox) in self.objects.iter().enumerate() { println!("\t{}: {}", i, bbox); } println!("{}", self.simulation_config); // The maximum frequency is given by (speed of light) / (grid element size) let start_freq = self.simulation_config.frequency_range[0]; let end_freq = self.simulation_config.frequency_range[1]; let start_force = self.force_on_for_freq(i, start_freq); let end_force = self.force_on_for_freq(i, end_freq); self.integrate_force_between_frequencies( i,
identifier_body
mod.rs
i: usize, world: &'a World, } impl<'a> Iterator for ForceIterator<'a> { type Item = Vector3<f32>; fn next(&mut self) -> Option<Vector3<f32>> { if self.i < self.world.objects.len() { let force = self.world.force_on(self.i); self.i += 1; Some(force) } else { None } } } /// These errors can be thrown when validating a world. #[derive(Debug, Snafu)] pub enum WorldError { /// An error indicating that one of the shapes is too close too the edge, causing the bounding /// box to cross the boundary. #[snafu(display("shape {} too close to edge", index))] ShapeTooCloseToEdge { /// The index of the violating object. index: usize, }, /// An error indicating that the bounding boxes of two objects in this world intersect and /// and therefore this world is invalid. #[snafu(display("bounding boxes of shapes {} and {} intersect", index_1, index_2))] ShapesIntersect { /// The index of the first object intersecting with the second. index_1: usize, /// The index of the second object intersecting with the first. index_2: usize, }, } impl World { /// Enable or disable the progress bar for the simulation. pub fn set_progress_bar(&mut self, enable: bool) { self.use_progress_bar = enable; } /// Obtain a force iterator for all objects in this world. pub fn forces(&self) -> ForceIterator<'_> { ForceIterator { i: 0, world: &self } } /// Compute the force on the `i`'th object. pub fn force_on(&self, i: usize) -> Vector3<f32> { println!("Geometry:"); println!( "\tWorld size: ({}, {}, {})", self.size.x, self.size.y, self.size.z ); for (i, bbox) in self.objects.iter().enumerate() { println!("\t{}: {}", i, bbox); } println!("{}", self.simulation_config); // The maximum frequency is given by (speed of light) / (grid element size) let start_freq = self.simulation_config.frequency_range[0]; let end_freq = self.simulation_config.frequency_range[1]; let start_force = self.force_on_for_freq(i, start_freq); let end_force = self.force_on_for_freq(i, end_freq); self.integrate_force_between_frequencies( i, start_freq, end_freq, start_force, end_force, start_force.norm(), ) } /// This function validates the geometry of the world. The function should be called, because it /// guarantees overflows later on in the simulation. /// /// # Errors /// - If any of the shapes is too close to the world border, the simulation can't be run and a /// `WorldError::ShapeTooCloseToEdge` will be returned. To fix this, move the object or increase /// the grid size. /// /// - If any of the objects are too close too eachother, their boundingboxes might intersect and /// the results will be invalid. If this is the case, a `WorldError::ShapesIntersect` will be /// returned. The violating shape indexes will be contained within. To fix this, move one or /// both of the objects. pub fn validate(&self) -> Result<(), WorldError> { let bbox_world = BoundingBox::new(0, 0, 0, self.size.x, self.size.y, self.size.z); let expanded_boxes = self .objects .iter() .enumerate() .map(|(index, obj)| { obj.bbox() .expanded(2) .map_err(|_| WorldError::ShapeTooCloseToEdge { index }) }) .collect::<Result<Vec<_>, _>>()?; for (i, bbox_1) in expanded_boxes.iter().enumerate() { // Check for intersection with world if !bbox_1.inside(&bbox_world) { return Err(WorldError::ShapeTooCloseToEdge { index: i }); } // Check for intersection with other objects for (j, bbox_2) in expanded_boxes.iter().enumerate() { if i < j && bbox_1.intersects(&bbox_2) { return Err(WorldError::ShapesIntersect { index_1: i, index_2: j, }); } } } Ok(()) } /// Performs a recursive integration between two frequencies. If the difference between the /// midpoint force and the linear interpolation is too large, both sides of the domain will use /// this function recursively to integrate the force. pub fn integrate_force_between_frequencies( &self, i: usize, start_frequency: f32, end_frequency: f32, start_value: Vector3<f32>, end_value: Vector3<f32>, max: f32, ) -> Vector3<f32> { // Do a recursive integration. The function should be smooth. let middle_frequency = 0.5 * (start_frequency + end_frequency); let middle_value = self.force_on_for_freq(i, middle_frequency); let average = (start_value + end_value) / 2.0; if (average - middle_value).norm() * (end_frequency - start_frequency) < self.simulation_config.frequency_threshold * max { // The change in area from the middle value vs extrapolation is less than the threshold 0.5 * (start_value + 2.0 * middle_value + end_value) * (end_frequency - start_frequency) } else { self.integrate_force_between_frequencies( i, start_frequency, middle_frequency, start_value, middle_value, max, ) + self.integrate_force_between_frequencies( i, middle_frequency, end_frequency, middle_value, end_value, max, ) } } /// Compute the force on object `i` for a certain `frequency`. This method will also subtract /// the error forces due to quantization by subtracting the force due to single objects. fn
(&self, i: usize, frequency: f32) -> Vector3<f32> { // Progress bar let bbox = &self.objects[i].bbox(); let dx = bbox.x1 - bbox.x0 + 4; let dy = bbox.y1 - bbox.y0 + 4; let dz = bbox.z1 - bbox.z0 + 4; let count = 2 * (dx * dy + dy * dz + dz * dx) * (1 + self.objects.len()); let progress_bar = if self.use_progress_bar { let progress_bar = Arc::new(Mutex::new(ProgressBar::new(count as u64))); progress_bar.lock().unwrap().format("[=>~]"); progress_bar.lock().unwrap().tick(); Some(progress_bar) } else { None }; let perm_all_geom = &self.permittivity_field_all_geometry(frequency); let mut total_force = self.force_on_for_freq_and_geometry(frequency, perm_all_geom, bbox, &progress_bar); // Discretization gives rise to forces of an object on itself. Removing these gives more // accurate results. for other in &self.objects { let perm = &self.permittivity_field(frequency, &[*other]); total_force -= self.force_on_for_freq_and_geometry(frequency, perm, bbox, &progress_bar); } if let Some(progress_bar) = progress_bar { progress_bar.lock().unwrap().finish_println(""); } println!( "Force for frequency {}: ({}, {}, {})", frequency, total_force.x, total_force.y, total_force.z ); total_force } /// Compute the force on the geometry inside `BoundingBox`, for the given permittivity field /// `perm` and `BoundingBox` `bbox`. fn force_on_for_freq_and_geometry( &self, frequency: f32, perm: &ScalarField, bbox: &BoundingBox, progress_bar: &Option<Arc<Mutex<ProgressBar<Stdout>>>>, ) -> Vector3<f32> { (0..6) .into_par_iter() .map(|face| { (match face { 0 => CosineBasis::new( Point3::new(bbox.x0 - 2, bbox.y0 - 2, bbox.z0 - 2), Point3::new(bbox.x1 + 2, bbox.y1 + 2, bbox.z0 - 2), frequency, perm, &self.simulation_config, Direction::NegZ, ), 1 => CosineBasis::new( Point3::new(bbox.x0 - 2, bbox.y0 - 2, bbox.z1 + 2), Point3::new(bbox.x1 + 2, bbox.y1 + 2, bbox.z1 + 2), frequency, perm, &self.simulation_config, Direction::Z, ), 2 => CosineBasis::new( Point
force_on_for_freq
identifier_name
mod.rs
i: usize, world: &'a World, } impl<'a> Iterator for ForceIterator<'a> { type Item = Vector3<f32>; fn next(&mut self) -> Option<Vector3<f32>> { if self.i < self.world.objects.len() { let force = self.world.force_on(self.i); self.i += 1; Some(force) } else { None } } } /// These errors can be thrown when validating a world. #[derive(Debug, Snafu)] pub enum WorldError { /// An error indicating that one of the shapes is too close too the edge, causing the bounding /// box to cross the boundary. #[snafu(display("shape {} too close to edge", index))] ShapeTooCloseToEdge { /// The index of the violating object. index: usize, }, /// An error indicating that the bounding boxes of two objects in this world intersect and /// and therefore this world is invalid. #[snafu(display("bounding boxes of shapes {} and {} intersect", index_1, index_2))] ShapesIntersect { /// The index of the first object intersecting with the second. index_1: usize, /// The index of the second object intersecting with the first. index_2: usize, }, } impl World { /// Enable or disable the progress bar for the simulation. pub fn set_progress_bar(&mut self, enable: bool) { self.use_progress_bar = enable; } /// Obtain a force iterator for all objects in this world. pub fn forces(&self) -> ForceIterator<'_> { ForceIterator { i: 0, world: &self } } /// Compute the force on the `i`'th object. pub fn force_on(&self, i: usize) -> Vector3<f32> { println!("Geometry:"); println!( "\tWorld size: ({}, {}, {})", self.size.x, self.size.y, self.size.z ); for (i, bbox) in self.objects.iter().enumerate() { println!("\t{}: {}", i, bbox); } println!("{}", self.simulation_config); // The maximum frequency is given by (speed of light) / (grid element size) let start_freq = self.simulation_config.frequency_range[0]; let end_freq = self.simulation_config.frequency_range[1]; let start_force = self.force_on_for_freq(i, start_freq); let end_force = self.force_on_for_freq(i, end_freq); self.integrate_force_between_frequencies( i, start_freq, end_freq, start_force, end_force, start_force.norm(), ) } /// This function validates the geometry of the world. The function should be called, because it /// guarantees overflows later on in the simulation. /// /// # Errors /// - If any of the shapes is too close to the world border, the simulation can't be run and a /// `WorldError::ShapeTooCloseToEdge` will be returned. To fix this, move the object or increase /// the grid size. /// /// - If any of the objects are too close too eachother, their boundingboxes might intersect and /// the results will be invalid. If this is the case, a `WorldError::ShapesIntersect` will be /// returned. The violating shape indexes will be contained within. To fix this, move one or /// both of the objects. pub fn validate(&self) -> Result<(), WorldError> { let bbox_world = BoundingBox::new(0, 0, 0, self.size.x, self.size.y, self.size.z); let expanded_boxes = self .objects .iter() .enumerate() .map(|(index, obj)| { obj.bbox() .expanded(2) .map_err(|_| WorldError::ShapeTooCloseToEdge { index }) }) .collect::<Result<Vec<_>, _>>()?; for (i, bbox_1) in expanded_boxes.iter().enumerate() { // Check for intersection with world if !bbox_1.inside(&bbox_world) { return Err(WorldError::ShapeTooCloseToEdge { index: i }); }
// Check for intersection with other objects for (j, bbox_2) in expanded_boxes.iter().enumerate() { if i < j && bbox_1.intersects(&bbox_2) { return Err(WorldError::ShapesIntersect { index_1: i, index_2: j, }); } } } Ok(()) } /// Performs a recursive integration between two frequencies. If the difference between the /// midpoint force and the linear interpolation is too large, both sides of the domain will use /// this function recursively to integrate the force. pub fn integrate_force_between_frequencies( &self, i: usize, start_frequency: f32, end_frequency: f32, start_value: Vector3<f32>, end_value: Vector3<f32>, max: f32, ) -> Vector3<f32> { // Do a recursive integration. The function should be smooth. let middle_frequency = 0.5 * (start_frequency + end_frequency); let middle_value = self.force_on_for_freq(i, middle_frequency); let average = (start_value + end_value) / 2.0; if (average - middle_value).norm() * (end_frequency - start_frequency) < self.simulation_config.frequency_threshold * max { // The change in area from the middle value vs extrapolation is less than the threshold 0.5 * (start_value + 2.0 * middle_value + end_value) * (end_frequency - start_frequency) } else { self.integrate_force_between_frequencies( i, start_frequency, middle_frequency, start_value, middle_value, max, ) + self.integrate_force_between_frequencies( i, middle_frequency, end_frequency, middle_value, end_value, max, ) } } /// Compute the force on object `i` for a certain `frequency`. This method will also subtract /// the error forces due to quantization by subtracting the force due to single objects. fn force_on_for_freq(&self, i: usize, frequency: f32) -> Vector3<f32> { // Progress bar let bbox = &self.objects[i].bbox(); let dx = bbox.x1 - bbox.x0 + 4; let dy = bbox.y1 - bbox.y0 + 4; let dz = bbox.z1 - bbox.z0 + 4; let count = 2 * (dx * dy + dy * dz + dz * dx) * (1 + self.objects.len()); let progress_bar = if self.use_progress_bar { let progress_bar = Arc::new(Mutex::new(ProgressBar::new(count as u64))); progress_bar.lock().unwrap().format("[=>~]"); progress_bar.lock().unwrap().tick(); Some(progress_bar) } else { None }; let perm_all_geom = &self.permittivity_field_all_geometry(frequency); let mut total_force = self.force_on_for_freq_and_geometry(frequency, perm_all_geom, bbox, &progress_bar); // Discretization gives rise to forces of an object on itself. Removing these gives more // accurate results. for other in &self.objects { let perm = &self.permittivity_field(frequency, &[*other]); total_force -= self.force_on_for_freq_and_geometry(frequency, perm, bbox, &progress_bar); } if let Some(progress_bar) = progress_bar { progress_bar.lock().unwrap().finish_println(""); } println!( "Force for frequency {}: ({}, {}, {})", frequency, total_force.x, total_force.y, total_force.z ); total_force } /// Compute the force on the geometry inside `BoundingBox`, for the given permittivity field /// `perm` and `BoundingBox` `bbox`. fn force_on_for_freq_and_geometry( &self, frequency: f32, perm: &ScalarField, bbox: &BoundingBox, progress_bar: &Option<Arc<Mutex<ProgressBar<Stdout>>>>, ) -> Vector3<f32> { (0..6) .into_par_iter() .map(|face| { (match face { 0 => CosineBasis::new( Point3::new(bbox.x0 - 2, bbox.y0 - 2, bbox.z0 - 2), Point3::new(bbox.x1 + 2, bbox.y1 + 2, bbox.z0 - 2), frequency, perm, &self.simulation_config, Direction::NegZ, ), 1 => CosineBasis::new( Point3::new(bbox.x0 - 2, bbox.y0 - 2, bbox.z1 + 2), Point3::new(bbox.x1 + 2, bbox.y1 + 2, bbox.z1 + 2), frequency, perm, &self.simulation_config, Direction::Z, ), 2 => CosineBasis::new( Point3
random_line_split
algorithm.rs
pub walks: RandomWalks<I>, } fn walks<'a, L, G: 'a, RNG>( starting_nodes: impl Iterator<Item = &'a Id<G::Node>>, network: &G, ledger_view: &L, mut rng: RNG, get_weight: &dyn Fn(&<G::Edge as GraphObject>::Metadata) -> f64, ) -> RandomWalks<Id<G::Node>> where L: LedgerView, G: Graph, Id<G::Node>: Clone + Eq + Hash, RNG: Rng + SeedableRng, { let mut walks = RandomWalks::new(); for i in starting_nodes { for _ in 0..(*ledger_view.get_random_walks_num()) { let mut walk = RandomWalk::new(i.clone()); let mut current_node = i; // TODO distinguish account/project // TODO Should there be a safeguard so this doesn't run forever? while rng.gen::<f64>() < ledger_view.get_damping_factors().project { let neighbors = network.neighbours(&current_node); match neighbors.choose_weighted(&mut rng, |item| { network .lookup_edge_metadata(&item.id) .and_then(|m| Some(get_weight(m))) .unwrap() }) { Ok(next_edge) => { walk.add_next(next_edge.target.clone()); current_node = next_edge.target; } Err(WeightedError::NoItem) => break, Err(error) => panic!("Problem with the neighbors: {:?}", error), } } walks.add_walk(walk); } } walks } // FIXME(adn) It should be possible to make this code parametric over // Dependency<W>, for I have ran into a cryptic error about the SampleBorrow // trait not be implemented, and wasn't able to immediately make the code // typecheck. pub fn random_walk<L, G, RNG>( seed_set: Option<SeedSet<Id<G::Node>>>, network: &G, ledger_view: &L, rng: RNG, get_weight: &dyn Fn(&<G::Edge as GraphObject>::Metadata) -> f64, ) -> Result<WalkResult<G, <G::Node as GraphObject>::Id>, OsrankError> where L: LedgerView, G: Graph + Clone, Id<G::Node>: Clone + Eq + Hash, RNG: Rng + SeedableRng, { match seed_set { Some(seeds) => { let walks = walks(seeds.seedset_iter(), network, ledger_view, rng, get_weight); let mut trusted_node_ids: Vec<&Id<G::Node>> = Vec::new(); for node in network.nodes() { if rank_node::<L, G>(&walks, node.id().clone(), ledger_view) > Osrank::zero() { trusted_node_ids.push(&node.id()); } } Ok(WalkResult { network_view: network.subgraph_by_nodes(trusted_node_ids), walks, }) } None => { let whole_network = (*network).clone(); // FIXME, terrible. let all_node_ids = network.nodes().map(|n| n.id()); let res = WalkResult { network_view: whole_network, walks: walks(all_node_ids, network, ledger_view, rng, get_weight), }; Ok(res) } } } /// Naive version of the algorithm that given a full Network and a precomputed /// set W of random walks, iterates over each edge of the Network and computes /// the osrank. pub fn osrank_naive<L, G, RNG>( seed_set: Option<SeedSet<Id<G::Node>>>, network: &mut G, ledger_view: &L, initial_seed: <RNG as SeedableRng>::Seed, get_weight: Box<dyn Fn(&<G::Edge as GraphObject>::Metadata) -> f64>, from_osrank: Box<dyn Fn(&G::Node, Osrank) -> Metadata<G::Node>>, ) -> Result<(), OsrankError> where L: LedgerView, G: Graph + Clone, Id<G::Node>: Clone + Eq + Hash, RNG: Rng + SeedableRng, <RNG as SeedableRng>::Seed: Clone, { //NOTE(adn) The fact we are creating a new RNG every time we call // `random_walk` is deliberate and something to think about. We probably // want to "restart" the randomness from the initial seed every call to // `random_walk`, which means this function has to consume the RNG. match seed_set { Some(_) => { // Phase1, rank the network and produce a NetworkView. let phase1 = random_walk( seed_set, &*network, ledger_view, RNG::from_seed(initial_seed.clone()), &get_weight, )?; // Phase2, compute the osrank only on the NetworkView let phase2 = random_walk( None, &phase1.network_view, ledger_view, RNG::from_seed(initial_seed.clone()), &get_weight, )?; rank_network(&phase2.walks, &mut *network, ledger_view, &from_osrank) } None => { // Compute osrank on the full NetworkView let create_walks = random_walk( None, &*network, ledger_view, RNG::from_seed(initial_seed.clone()), &get_weight, )?; rank_network( &create_walks.walks, &mut *network, ledger_view, &from_osrank, ) } } } fn rank_node<L, G>( random_walks: &RandomWalks<Id<G::Node>>,
ledger_view: &L, ) -> Osrank where L: LedgerView, G: Graph, <G::Node as GraphObject>::Id: Eq + Clone + Hash, { let total_walks = random_walks.len(); let node_visits = random_walks.count_visits(&node_id); Fraction::from(1.0 - ledger_view.get_damping_factors().project) * Osrank::new(node_visits as u32, total_walks as u32) } pub fn rank_network<'a, L, G: 'a>( random_walks: &RandomWalks<Id<G::Node>>, network_view: &'a mut G, ledger_view: &L, from_osrank: &dyn Fn(&G::Node, Osrank) -> Metadata<G::Node>, ) -> Result<(), OsrankError> where L: LedgerView, G: Graph, <G::Node as GraphObject>::Id: Eq + Clone + Hash, { for node in network_view.nodes_mut() { let rank = rank_node::<L, G>(&random_walks, node.id().clone(), ledger_view); node.set_metadata(from_osrank(&node, rank)) } Ok(()) } #[cfg(test)] mod tests { extern crate rand; extern crate rand_xorshift; use super::*; use crate::protocol_traits::ledger::MockLedger; use crate::types::network::{Artifact, ArtifactType, DependencyType, Network}; use crate::types::Weight; use num_traits::Zero; use rand_xorshift::XorShiftRng; type MockNetwork = Network<f64>; #[test] fn everything_ok() { // build the example network let mut network = Network::default(); for node in &["p1", "p2", "p3"] { network.add_node( node.to_string(), ArtifactType::Project { osrank: Zero::zero(), }, ) } // Create the seed set from all projects let seed_set = SeedSet::from(vec!["p1".to_string(), "p2".to_string(), "p3".to_string()]); for node in &["a1", "a2", "a3", "isle"] { network.add_node( node.to_string(), ArtifactType::Account { osrank: Zero::zero(), }, ) } let edges = [ ("p1", "a1", Weight::new(3, 7)), ("a1", "p1", Weight::new(1, 1)), ("p1", "p2", Weight::new(4, 7)), ("p2", "a2", Weight::new(1, 1)), ("a2", "p2", Weight::new(1, 3)), ("a2", "p3", Weight::new(2, 3)), ("p3", "a2", Weight::new(11, 28)), ("p3", "a3", Weight::new(1, 28)), ("p3", "p1", Weight::new(2, 7)), ("p3", "p2", Weight::new(2, 7)), ("a3", "p3", Weight::new(1, 1)), ]; for edge in &edges { network.add_edge( &edge.0.to_string(), &edge.1.to_string(), 2, DependencyType::Influence(edge.2
node_id: Id<G::Node>,
random_line_split
algorithm.rs
<G, I> where I: Eq + Hash, { network_view: G, pub walks: RandomWalks<I>, } fn walks<'a, L, G: 'a, RNG>( starting_nodes: impl Iterator<Item = &'a Id<G::Node>>, network: &G, ledger_view: &L, mut rng: RNG, get_weight: &dyn Fn(&<G::Edge as GraphObject>::Metadata) -> f64, ) -> RandomWalks<Id<G::Node>> where L: LedgerView, G: Graph, Id<G::Node>: Clone + Eq + Hash, RNG: Rng + SeedableRng, { let mut walks = RandomWalks::new(); for i in starting_nodes { for _ in 0..(*ledger_view.get_random_walks_num()) { let mut walk = RandomWalk::new(i.clone()); let mut current_node = i; // TODO distinguish account/project // TODO Should there be a safeguard so this doesn't run forever? while rng.gen::<f64>() < ledger_view.get_damping_factors().project { let neighbors = network.neighbours(&current_node); match neighbors.choose_weighted(&mut rng, |item| { network .lookup_edge_metadata(&item.id) .and_then(|m| Some(get_weight(m))) .unwrap() }) { Ok(next_edge) => { walk.add_next(next_edge.target.clone()); current_node = next_edge.target; } Err(WeightedError::NoItem) => break, Err(error) => panic!("Problem with the neighbors: {:?}", error), } } walks.add_walk(walk); } } walks } // FIXME(adn) It should be possible to make this code parametric over // Dependency<W>, for I have ran into a cryptic error about the SampleBorrow // trait not be implemented, and wasn't able to immediately make the code // typecheck. pub fn random_walk<L, G, RNG>( seed_set: Option<SeedSet<Id<G::Node>>>, network: &G, ledger_view: &L, rng: RNG, get_weight: &dyn Fn(&<G::Edge as GraphObject>::Metadata) -> f64, ) -> Result<WalkResult<G, <G::Node as GraphObject>::Id>, OsrankError> where L: LedgerView, G: Graph + Clone, Id<G::Node>: Clone + Eq + Hash, RNG: Rng + SeedableRng, { match seed_set { Some(seeds) => { let walks = walks(seeds.seedset_iter(), network, ledger_view, rng, get_weight); let mut trusted_node_ids: Vec<&Id<G::Node>> = Vec::new(); for node in network.nodes() { if rank_node::<L, G>(&walks, node.id().clone(), ledger_view) > Osrank::zero() { trusted_node_ids.push(&node.id()); } } Ok(WalkResult { network_view: network.subgraph_by_nodes(trusted_node_ids), walks, }) } None => { let whole_network = (*network).clone(); // FIXME, terrible. let all_node_ids = network.nodes().map(|n| n.id()); let res = WalkResult { network_view: whole_network, walks: walks(all_node_ids, network, ledger_view, rng, get_weight), }; Ok(res) } } } /// Naive version of the algorithm that given a full Network and a precomputed /// set W of random walks, iterates over each edge of the Network and computes /// the osrank. pub fn osrank_naive<L, G, RNG>( seed_set: Option<SeedSet<Id<G::Node>>>, network: &mut G, ledger_view: &L, initial_seed: <RNG as SeedableRng>::Seed, get_weight: Box<dyn Fn(&<G::Edge as GraphObject>::Metadata) -> f64>, from_osrank: Box<dyn Fn(&G::Node, Osrank) -> Metadata<G::Node>>, ) -> Result<(), OsrankError> where L: LedgerView, G: Graph + Clone, Id<G::Node>: Clone + Eq + Hash, RNG: Rng + SeedableRng, <RNG as SeedableRng>::Seed: Clone, { //NOTE(adn) The fact we are creating a new RNG every time we call // `random_walk` is deliberate and something to think about. We probably // want to "restart" the randomness from the initial seed every call to // `random_walk`, which means this function has to consume the RNG. match seed_set { Some(_) => { // Phase1, rank the network and produce a NetworkView. let phase1 = random_walk( seed_set, &*network, ledger_view, RNG::from_seed(initial_seed.clone()), &get_weight, )?; // Phase2, compute the osrank only on the NetworkView let phase2 = random_walk( None, &phase1.network_view, ledger_view, RNG::from_seed(initial_seed.clone()), &get_weight, )?; rank_network(&phase2.walks, &mut *network, ledger_view, &from_osrank) } None => { // Compute osrank on the full NetworkView let create_walks = random_walk( None, &*network, ledger_view, RNG::from_seed(initial_seed.clone()), &get_weight, )?; rank_network( &create_walks.walks, &mut *network, ledger_view, &from_osrank, ) } } } fn rank_node<L, G>( random_walks: &RandomWalks<Id<G::Node>>, node_id: Id<G::Node>, ledger_view: &L, ) -> Osrank where L: LedgerView, G: Graph, <G::Node as GraphObject>::Id: Eq + Clone + Hash, { let total_walks = random_walks.len(); let node_visits = random_walks.count_visits(&node_id); Fraction::from(1.0 - ledger_view.get_damping_factors().project) * Osrank::new(node_visits as u32, total_walks as u32) } pub fn rank_network<'a, L, G: 'a>( random_walks: &RandomWalks<Id<G::Node>>, network_view: &'a mut G, ledger_view: &L, from_osrank: &dyn Fn(&G::Node, Osrank) -> Metadata<G::Node>, ) -> Result<(), OsrankError> where L: LedgerView, G: Graph, <G::Node as GraphObject>::Id: Eq + Clone + Hash, { for node in network_view.nodes_mut() { let rank = rank_node::<L, G>(&random_walks, node.id().clone(), ledger_view); node.set_metadata(from_osrank(&node, rank)) } Ok(()) } #[cfg(test)] mod tests { extern crate rand; extern crate rand_xorshift; use super::*; use crate::protocol_traits::ledger::MockLedger; use crate::types::network::{Artifact, ArtifactType, DependencyType, Network}; use crate::types::Weight; use num_traits::Zero; use rand_xorshift::XorShiftRng; type MockNetwork = Network<f64>; #[test] fn everything_ok() { // build the example network let mut network = Network::default(); for node in &["p1", "p2", "p3"] { network.add_node( node.to_string(), ArtifactType::Project { osrank: Zero::zero(), }, ) } // Create the seed set from all projects let seed_set = SeedSet::from(vec!["p1".to_string(), "p2".to_string(), "p3".to_string()]); for node in &["a1", "a2", "a3", "isle"] { network.add_node( node.to_string(), ArtifactType::Account { osrank: Zero::zero(), }, ) } let edges = [ ("p1", "a1", Weight::new(3, 7)), ("a1", "p1", Weight::new(1, 1)), ("p1", "p2", Weight::new(4, 7)), ("p2", "a2", Weight::new(1, 1)), ("a2", "p2", Weight::new(1, 3)), ("a2", "p3", Weight::new(2, 3)), ("p3", "a2", Weight::new(11, 28)), ("p3", "a3", Weight::new(1, 28)), ("p3", "p1", Weight::new(2, 7)), ("p3", "p2", Weight::new(2, 7)), ("a3", "p3", Weight::new(1, 1)), ]; for edge in &edges { network.add_edge( &edge.0.to_string
WalkResult
identifier_name
channel.rs
: &Thread) -> ArcType { let symbol = vm .global_env() .get_env() .find_type_info("Receiver") .unwrap() .name .clone(); Type::app(Type::ident(symbol), collect![T::make_type(vm)]) } } field_decl!{ sender, receiver } pub type ChannelRecord<S, R> = record_type!(sender => S, receiver => R); /// FIXME The dummy `a` argument should not be needed to ensure that the channel can only be used /// with a single type fn channel( WithVM { vm, .. }: WithVM<Generic<A>>, ) -> ChannelRecord<Sender<Generic<A>>, Receiver<Generic<A>>> { let sender = Sender { thread: unsafe { GcPtr::from_raw(vm) }, queue: Arc::new(Mutex::new(VecDeque::new())), }; let receiver = Receiver { queue: sender.queue.clone(), }; record_no_decl!(sender => sender, receiver => receiver) } fn recv(receiver: &Receiver<Generic<A>>) -> Result<Generic<A>, ()> { receiver.try_recv().map_err(|_| ()) } fn send(sender: &Sender<Generic<A>>, value: Generic<A>) -> Result<(), ()> { unsafe { let value = sender .thread .deep_clone_value(&sender.thread, value.get_value()) .map_err(|_| ())?; Ok(sender.send(Generic::from(value))) } } extern "C" fn resume(vm: &Thread) -> Status { let mut context = vm.context(); let value = StackFrame::current(&mut context.stack)[0].get_repr(); match value { ValueRepr::Thread(child) => { let lock = StackFrame::current(&mut context.stack).into_lock(); drop(context); let result = child.resume(); context = vm.context(); context.stack.release_lock(lock); match result { Ok(child_context) => { // Prevent dead lock if the following status_push call allocates drop(child_context); let value: Result<(), &str> = Ok(()); value.status_push(vm, &mut context) } Err(Error::Dead) => { let value: Result<(), &str> = Err("Attempted to resume a dead thread"); value.status_push(vm, &mut context) } Err(err) => { let fmt = format!("{}", err); let result = unsafe { ValueRepr::String(GcStr::from_utf8_unchecked( context.alloc_ignore_limit(fmt.as_bytes()), )) }; context.stack.push(result); Status::Error } } } _ => unreachable!(), } } extern "C" fn yield_(_vm: &Thread) -> Status { Status::Yield } fn spawn<'vm>( value: WithVM<'vm, Function<&'vm Thread, fn(())>>, ) -> RuntimeResult<RootedThread, Error> { spawn_(value).into() } fn spawn_<'vm>(value: WithVM<'vm, Function<&'vm Thread, fn(())>>) -> VmResult<RootedThread> { let thread = value.vm.new_thread()?; { let mut context = thread.context(); let callable = match value.value.get_variant().0 { ValueRepr::Closure(c) => State::Closure(c), ValueRepr::Function(c) => State::Extern(c), _ => State::Unknown, }; value.value.push(value.vm, &mut context)?; context.stack.push(ValueRepr::Int(0)); StackFrame::current(&mut context.stack).enter_scope(1, callable); } Ok(thread) } type Action = fn(()) -> OpaqueValue<RootedThread, IO<Generic<A>>>; #[cfg(target_arch = "wasm32")] fn spawn_on<'vm>( _thread: RootedThread, _action: WithVM<'vm, FunctionRef<Action>>, ) -> IO<OpaqueValue<&'vm Thread, IO<Generic<A>>>> { IO::Exception("spawn_on requires the `tokio_core` crate".to_string()) } #[cfg(not(target_arch = "wasm32"))] fn spawn_on<'vm>( thread: RootedThread, action: WithVM<'vm, FunctionRef<Action>>, ) -> IO<OpaqueValue<&'vm Thread, IO<Generic<A>>>> { struct SpawnFuture<F>(Mutex<Option<F>>); impl<F> fmt::Debug for SpawnFuture<F> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Future") } } impl<F> Userdata for SpawnFuture<F> where F: Send + 'static, { } impl<F> Traverseable for SpawnFuture<F> { fn traverse(&self, _: &mut Gc) {} } impl<F> VmType for SpawnFuture<F> { type Type = Generic<A>; } fn push_future_wrapper<G>(vm: &Thread, context: &mut OwnedContext, _: &G) where G: Future<Item = OpaqueValue<RootedThread, IO<Generic<A>>>, Error = Error> + Send + 'static, { extern "C" fn future_wrapper<F>(vm: &Thread) -> Status where F: Future<Item = OpaqueValue<RootedThread, IO<Generic<A>>>, Error = Error> + Send + 'static, { let mut context = vm.context(); let value = StackFrame::current(&mut context.stack)[0].get_repr(); match value { ValueRepr::Userdata(data) => { let data = data.downcast_ref::<SpawnFuture<F>>().unwrap(); let future = data.0.lock().unwrap().take().unwrap(); let lock = StackFrame::current(&mut context.stack).insert_lock(); AsyncPushable::async_status_push( FutureResult::new(future), vm, &mut context, lock, ) } _ => unreachable!(), } } type FutureArg = (); primitive::<fn(FutureArg) -> IO<Generic<A>>>("unknown", future_wrapper::<G>) .push(vm, context) .unwrap(); } use value::PartialApplicationDataDef; let WithVM { vm, value: action } = action; let mut action = OwnedFunction::<Action>::from_value(&thread, action.get_variant()); let future = oneshot::spawn_fn( move || action.call_async(()), &vm.global_env().get_event_loop().expect("event loop"), ); let mut context = vm.context(); push_future_wrapper(vm, &mut context, &future); let callable = match context.stack[context.stack.len() - 1].get_repr() { ValueRepr::Function(ext) => Callable::Extern(ext), _ => unreachable!(), }; SpawnFuture(Mutex::new(Some(future))) .push(vm, &mut context) .unwrap(); let fields = [context.stack.get_values().last().unwrap().clone()]; let def = PartialApplicationDataDef(callable, &fields); let value = ValueRepr::PartialApplication(context.alloc_with(vm, def).unwrap()).into(); context.stack.pop_many(2); // TODO Remove rooting here IO::Value(OpaqueValue::from_value(vm.root_value(value))) } fn new_thread(WithVM { vm, .. }: WithVM<()>) -> IO<RootedThread> { match vm.new_thread() { Ok(thread) => IO::Value(thread), Err(err) => IO::Exception(err.to_string()), } } fn sleep(ms: VmInt) -> IO<()> { use std::time::Duration; ::std::thread::sleep(Duration::from_millis(ms as u64)); IO::Value(()) } fn interrupt(thread: RootedThread) -> IO<()> { thread.interrupt(); IO::Value(()) } mod std { pub use channel; pub mod thread { pub use channel as prim; } } pub fn load_channel<'vm>(vm: &'vm Thread) -> VmResult<ExternModule> { let _ = vm.register_type::<Sender<A>>("Sender", &["a"]); let _ = vm.register_type::<Receiver<A>>("Receiver", &["a"]); ExternModule::new( vm, record!{ type Sender a => Sender<A>, type Receiver a => Sender<A>, channel => primitive!(1 std::channel::channel), recv => primitive!(1 std::channel::recv), send => primitive!(2 std::channel::send), }, ) } pub fn load_thread<'vm>(vm: &'vm Thread) -> VmResult<ExternModule>
{ ExternModule::new( vm, record!{ resume => primitive::<fn(&'vm Thread) -> Result<(), String>>("std.thread.prim.resume", resume), (yield_ "yield") => primitive::<fn(())>("std.thread.prim.yield", yield_), spawn => primitive!(1 std::thread::prim::spawn), spawn_on => primitive!(2 std::thread::prim::spawn_on), new_thread => primitive!(1 std::thread::prim::new_thread), interrupt => primitive!(1 std::thread::prim::interrupt), sleep => primitive!(1 std::thread::prim::sleep) }, ) }
identifier_body
channel.rs
the `Thread` thread: GcPtr<Thread>, queue: Arc<Mutex<VecDeque<T>>>, } impl<T> Userdata for Sender<T> where T: Any + Send + Sync + fmt::Debug + Traverseable, { } impl<T> fmt::Debug for Sender<T> where T: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", *self.queue.lock().unwrap()) } } impl<T> Traverseable for Sender<T> { fn traverse(&self, _gc: &mut Gc) { // No need to traverse in Sender as values can only be accessed through Receiver } } impl<T> Sender<T> { fn send(&self, value: T) { self.queue.lock().unwrap().push_back(value); } } impl<T: Traverseable> Traverseable for Receiver<T> { fn traverse(&self, gc: &mut Gc) { self.queue.lock().unwrap().traverse(gc); } } pub struct Receiver<T> { queue: Arc<Mutex<VecDeque<T>>>, } impl<T> Userdata for Receiver<T> where T: Any + Send + Sync + fmt::Debug + Traverseable, { } impl<T> fmt::Debug for Receiver<T> where T: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", *self.queue.lock().unwrap()) } } impl<T> Receiver<T> { fn try_recv(&self) -> Result<T, ()> { self.queue.lock().unwrap().pop_front().ok_or(()) } } impl<T: VmType> VmType for Sender<T> where T::Type: Sized, { type Type = Sender<T::Type>; fn make_type(vm: &Thread) -> ArcType { let symbol = vm .global_env() .get_env() .find_type_info("Sender") .unwrap() .name .clone(); Type::app(Type::ident(symbol), collect![T::make_type(vm)]) } } impl<T: VmType> VmType for Receiver<T> where T::Type: Sized, { type Type = Receiver<T::Type>; fn make_type(vm: &Thread) -> ArcType { let symbol = vm .global_env() .get_env() .find_type_info("Receiver") .unwrap() .name .clone(); Type::app(Type::ident(symbol), collect![T::make_type(vm)]) } } field_decl!{ sender, receiver } pub type ChannelRecord<S, R> = record_type!(sender => S, receiver => R); /// FIXME The dummy `a` argument should not be needed to ensure that the channel can only be used /// with a single type fn channel( WithVM { vm, .. }: WithVM<Generic<A>>, ) -> ChannelRecord<Sender<Generic<A>>, Receiver<Generic<A>>> { let sender = Sender { thread: unsafe { GcPtr::from_raw(vm) }, queue: Arc::new(Mutex::new(VecDeque::new())), }; let receiver = Receiver { queue: sender.queue.clone(), }; record_no_decl!(sender => sender, receiver => receiver) } fn recv(receiver: &Receiver<Generic<A>>) -> Result<Generic<A>, ()> { receiver.try_recv().map_err(|_| ()) } fn send(sender: &Sender<Generic<A>>, value: Generic<A>) -> Result<(), ()> { unsafe { let value = sender .thread .deep_clone_value(&sender.thread, value.get_value()) .map_err(|_| ())?; Ok(sender.send(Generic::from(value))) } } extern "C" fn resume(vm: &Thread) -> Status { let mut context = vm.context(); let value = StackFrame::current(&mut context.stack)[0].get_repr(); match value { ValueRepr::Thread(child) => { let lock = StackFrame::current(&mut context.stack).into_lock(); drop(context); let result = child.resume(); context = vm.context(); context.stack.release_lock(lock); match result { Ok(child_context) => { // Prevent dead lock if the following status_push call allocates drop(child_context); let value: Result<(), &str> = Ok(()); value.status_push(vm, &mut context) } Err(Error::Dead) => { let value: Result<(), &str> = Err("Attempted to resume a dead thread"); value.status_push(vm, &mut context) } Err(err) => { let fmt = format!("{}", err); let result = unsafe { ValueRepr::String(GcStr::from_utf8_unchecked( context.alloc_ignore_limit(fmt.as_bytes()), )) }; context.stack.push(result); Status::Error } } } _ => unreachable!(), } } extern "C" fn yield_(_vm: &Thread) -> Status { Status::Yield } fn spawn<'vm>( value: WithVM<'vm, Function<&'vm Thread, fn(())>>, ) -> RuntimeResult<RootedThread, Error> { spawn_(value).into() } fn spawn_<'vm>(value: WithVM<'vm, Function<&'vm Thread, fn(())>>) -> VmResult<RootedThread> { let thread = value.vm.new_thread()?; { let mut context = thread.context(); let callable = match value.value.get_variant().0 { ValueRepr::Closure(c) => State::Closure(c), ValueRepr::Function(c) => State::Extern(c), _ => State::Unknown, }; value.value.push(value.vm, &mut context)?; context.stack.push(ValueRepr::Int(0)); StackFrame::current(&mut context.stack).enter_scope(1, callable); } Ok(thread) } type Action = fn(()) -> OpaqueValue<RootedThread, IO<Generic<A>>>; #[cfg(target_arch = "wasm32")] fn spawn_on<'vm>( _thread: RootedThread, _action: WithVM<'vm, FunctionRef<Action>>, ) -> IO<OpaqueValue<&'vm Thread, IO<Generic<A>>>> { IO::Exception("spawn_on requires the `tokio_core` crate".to_string()) }
thread: RootedThread, action: WithVM<'vm, FunctionRef<Action>>, ) -> IO<OpaqueValue<&'vm Thread, IO<Generic<A>>>> { struct SpawnFuture<F>(Mutex<Option<F>>); impl<F> fmt::Debug for SpawnFuture<F> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Future") } } impl<F> Userdata for SpawnFuture<F> where F: Send + 'static, { } impl<F> Traverseable for SpawnFuture<F> { fn traverse(&self, _: &mut Gc) {} } impl<F> VmType for SpawnFuture<F> { type Type = Generic<A>; } fn push_future_wrapper<G>(vm: &Thread, context: &mut OwnedContext, _: &G) where G: Future<Item = OpaqueValue<RootedThread, IO<Generic<A>>>, Error = Error> + Send + 'static, { extern "C" fn future_wrapper<F>(vm: &Thread) -> Status where F: Future<Item = OpaqueValue<RootedThread, IO<Generic<A>>>, Error = Error> + Send + 'static, { let mut context = vm.context(); let value = StackFrame::current(&mut context.stack)[0].get_repr(); match value { ValueRepr::Userdata(data) => { let data = data.downcast_ref::<SpawnFuture<F>>().unwrap(); let future = data.0.lock().unwrap().take().unwrap(); let lock = StackFrame::current(&mut context.stack).insert_lock(); AsyncPushable::async_status_push( FutureResult::new(future), vm, &mut context, lock, ) } _ => unreachable!(), } } type FutureArg = (); primitive::<fn(FutureArg) -> IO<Generic<A>>>("unknown", future_wrapper::<G>) .push(vm, context) .unwrap(); } use value::PartialApplicationDataDef; let WithVM { vm, value: action } = action; let mut action = OwnedFunction::<Action>::from_value(&thread, action.get_variant()); let future = oneshot::spawn_fn( move || action.call_async(()), &vm.global_env().get_event_loop().expect("event loop"), ); let mut context = vm.context(); push_future_wrapper(vm, &mut context, &future); let callable = match context.stack[context.stack.len() - 1].get_repr() { ValueRepr::Function(ext) => Callable::Extern(ext), _ => unreachable!(), }; SpawnFuture(Mutex::new(Some(future))) .push(vm, &mut context) .unwrap(); let fields = [context.stack.get_values().last
#[cfg(not(target_arch = "wasm32"))] fn spawn_on<'vm>(
random_line_split
channel.rs
the `Thread` thread: GcPtr<Thread>, queue: Arc<Mutex<VecDeque<T>>>, } impl<T> Userdata for Sender<T> where T: Any + Send + Sync + fmt::Debug + Traverseable, { } impl<T> fmt::Debug for Sender<T> where T: fmt::Debug, { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", *self.queue.lock().unwrap()) } } impl<T> Traverseable for Sender<T> { fn traverse(&self, _gc: &mut Gc) { // No need to traverse in Sender as values can only be accessed through Receiver } } impl<T> Sender<T> { fn send(&self, value: T) { self.queue.lock().unwrap().push_back(value); } } impl<T: Traverseable> Traverseable for Receiver<T> { fn traverse(&self, gc: &mut Gc) { self.queue.lock().unwrap().traverse(gc); } } pub struct Receiver<T> { queue: Arc<Mutex<VecDeque<T>>>, } impl<T> Userdata for Receiver<T> where T: Any + Send + Sync + fmt::Debug + Traverseable, { } impl<T> fmt::Debug for Receiver<T> where T: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", *self.queue.lock().unwrap()) } } impl<T> Receiver<T> { fn try_recv(&self) -> Result<T, ()> { self.queue.lock().unwrap().pop_front().ok_or(()) } } impl<T: VmType> VmType for Sender<T> where T::Type: Sized, { type Type = Sender<T::Type>; fn make_type(vm: &Thread) -> ArcType { let symbol = vm .global_env() .get_env() .find_type_info("Sender") .unwrap() .name .clone(); Type::app(Type::ident(symbol), collect![T::make_type(vm)]) } } impl<T: VmType> VmType for Receiver<T> where T::Type: Sized, { type Type = Receiver<T::Type>; fn make_type(vm: &Thread) -> ArcType { let symbol = vm .global_env() .get_env() .find_type_info("Receiver") .unwrap() .name .clone(); Type::app(Type::ident(symbol), collect![T::make_type(vm)]) } } field_decl!{ sender, receiver } pub type ChannelRecord<S, R> = record_type!(sender => S, receiver => R); /// FIXME The dummy `a` argument should not be needed to ensure that the channel can only be used /// with a single type fn channel( WithVM { vm, .. }: WithVM<Generic<A>>, ) -> ChannelRecord<Sender<Generic<A>>, Receiver<Generic<A>>> { let sender = Sender { thread: unsafe { GcPtr::from_raw(vm) }, queue: Arc::new(Mutex::new(VecDeque::new())), }; let receiver = Receiver { queue: sender.queue.clone(), }; record_no_decl!(sender => sender, receiver => receiver) } fn recv(receiver: &Receiver<Generic<A>>) -> Result<Generic<A>, ()> { receiver.try_recv().map_err(|_| ()) } fn send(sender: &Sender<Generic<A>>, value: Generic<A>) -> Result<(), ()> { unsafe { let value = sender .thread .deep_clone_value(&sender.thread, value.get_value()) .map_err(|_| ())?; Ok(sender.send(Generic::from(value))) } } extern "C" fn resume(vm: &Thread) -> Status { let mut context = vm.context(); let value = StackFrame::current(&mut context.stack)[0].get_repr(); match value { ValueRepr::Thread(child) => { let lock = StackFrame::current(&mut context.stack).into_lock(); drop(context); let result = child.resume(); context = vm.context(); context.stack.release_lock(lock); match result { Ok(child_context) => { // Prevent dead lock if the following status_push call allocates drop(child_context); let value: Result<(), &str> = Ok(()); value.status_push(vm, &mut context) } Err(Error::Dead) => { let value: Result<(), &str> = Err("Attempted to resume a dead thread"); value.status_push(vm, &mut context) } Err(err) => { let fmt = format!("{}", err); let result = unsafe { ValueRepr::String(GcStr::from_utf8_unchecked( context.alloc_ignore_limit(fmt.as_bytes()), )) }; context.stack.push(result); Status::Error } } } _ => unreachable!(), } } extern "C" fn yield_(_vm: &Thread) -> Status { Status::Yield } fn spawn<'vm>( value: WithVM<'vm, Function<&'vm Thread, fn(())>>, ) -> RuntimeResult<RootedThread, Error> { spawn_(value).into() } fn spawn_<'vm>(value: WithVM<'vm, Function<&'vm Thread, fn(())>>) -> VmResult<RootedThread> { let thread = value.vm.new_thread()?; { let mut context = thread.context(); let callable = match value.value.get_variant().0 { ValueRepr::Closure(c) => State::Closure(c), ValueRepr::Function(c) => State::Extern(c), _ => State::Unknown, }; value.value.push(value.vm, &mut context)?; context.stack.push(ValueRepr::Int(0)); StackFrame::current(&mut context.stack).enter_scope(1, callable); } Ok(thread) } type Action = fn(()) -> OpaqueValue<RootedThread, IO<Generic<A>>>; #[cfg(target_arch = "wasm32")] fn spawn_on<'vm>( _thread: RootedThread, _action: WithVM<'vm, FunctionRef<Action>>, ) -> IO<OpaqueValue<&'vm Thread, IO<Generic<A>>>> { IO::Exception("spawn_on requires the `tokio_core` crate".to_string()) } #[cfg(not(target_arch = "wasm32"))] fn spawn_on<'vm>( thread: RootedThread, action: WithVM<'vm, FunctionRef<Action>>, ) -> IO<OpaqueValue<&'vm Thread, IO<Generic<A>>>> { struct SpawnFuture<F>(Mutex<Option<F>>); impl<F> fmt::Debug for SpawnFuture<F> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Future") } } impl<F> Userdata for SpawnFuture<F> where F: Send + 'static, { } impl<F> Traverseable for SpawnFuture<F> { fn traverse(&self, _: &mut Gc) {} } impl<F> VmType for SpawnFuture<F> { type Type = Generic<A>; } fn push_future_wrapper<G>(vm: &Thread, context: &mut OwnedContext, _: &G) where G: Future<Item = OpaqueValue<RootedThread, IO<Generic<A>>>, Error = Error> + Send + 'static, { extern "C" fn future_wrapper<F>(vm: &Thread) -> Status where F: Future<Item = OpaqueValue<RootedThread, IO<Generic<A>>>, Error = Error> + Send + 'static, { let mut context = vm.context(); let value = StackFrame::current(&mut context.stack)[0].get_repr(); match value { ValueRepr::Userdata(data) => { let data = data.downcast_ref::<SpawnFuture<F>>().unwrap(); let future = data.0.lock().unwrap().take().unwrap(); let lock = StackFrame::current(&mut context.stack).insert_lock(); AsyncPushable::async_status_push( FutureResult::new(future), vm, &mut context, lock, ) } _ => unreachable!(), } } type FutureArg = (); primitive::<fn(FutureArg) -> IO<Generic<A>>>("unknown", future_wrapper::<G>) .push(vm, context) .unwrap(); } use value::PartialApplicationDataDef; let WithVM { vm, value: action } = action; let mut action = OwnedFunction::<Action>::from_value(&thread, action.get_variant()); let future = oneshot::spawn_fn( move || action.call_async(()), &vm.global_env().get_event_loop().expect("event loop"), ); let mut context = vm.context(); push_future_wrapper(vm, &mut context, &future); let callable = match context.stack[context.stack.len() - 1].get_repr() { ValueRepr::Function(ext) => Callable::Extern(ext), _ => unreachable!(), }; SpawnFuture(Mutex::new(Some(future))) .push(vm, &mut context) .unwrap(); let fields = [context.stack.get_values().last
fmt
identifier_name
devices.js
\___ \ | | | | |__| | |__| | |____| |____ ____) | |_| |_|\____/|_____/|______|______|_____/ */ /* _____ _____ /\ | __ \_ _| / \ | |__) || | / /\ \ | ___/ | | / ____ \| | _| |_ /_/ \_\_| |_____| */ const auth ={ auth:{ username: 'admin', password: process.env.EMQX_DEFAULT_APPLICATION_SECRET } } //GET DEVICES router.get("/device", checkAuth, async (req, res) =>{ try { const userId = req.userData._id //get devices var devices = await Device.find({userId: userId}) //descoupling devices = JSON.parse(JSON.stringify(devices)) //get saver rules const saverRules = await getSaverRules(userId) //get templates const templates = await getTemplate(userId) // get alarm rule const alarmRules = await getAlarmRules(userId) //saver rules to -> devices devices.forEach((device, index) => { devices[index].saverRule = saverRules.filter( saverRule => saverRule.dId == device.dId)[0] devices[index].template = templates.filter( template => template._id == device.templateId)[0] devices[index].alarmRules = alarmRules.filter(alarmRule => alarmRule.dId == device.dId) }) const toSend = { status: "success", data: devices } res.json(toSend) } catch (error) { console.log("ERROR GETTING DEVICES") console.log(error) const toSend = { status: "error", error: error } return res.status(500).json(toSend) } }) //NEW DEVICE router.post("/device", checkAuth, async (req, res) =>{ try { const userId = req.userData._id var newDevice = req.body.newDevice newDevice.userId = userId newDevice.createdTime = Date.now() newDevice.password = makeid(10) await createSaverRule(userId, newDevice.dId, true) const device = await Device.create(newDevice) await selectDevice(userId, newDevice.dId) const toSend = { status: "success" } return res.json(toSend) } catch (error) { console.log("ERROR CREATING NEW DEVICE") console.log(error) const toSend = { status: "error", error: error } return res.status(500).json(toSend) } }) //DELETE DEVICE router.delete("/device", checkAuth, async (req, res) =>{ try { const userId = req.userData._id const dId = req.query.dId await deleteSaverRule(dId) //deleting all posible alarm rules await deleteAllAlarmRules(userId, dId); //deleting all posible mqtt device credentials await deleteMqttDeviceCredentials(dId); //deleting data mqtt await deleteMqttDataDevices(dId) const result = await Device.deleteOne({userId: userId, dId: dId}) const toSend = { status: "success", data: result } return res.json(toSend) } catch (error) { console.log("ERROR DELETING DEVICE") console.log(error) const toSend = { status: "error" } return res.json(toSend) } }) //UPDATE DEVICE (SELECTOR) router.put("/device", checkAuth, async (req, res) =>{ const dId = req.body.dId const userId = req.userData._id if(await selectDevice(userId,dId)){ const toSend = { status: "success" } return res.json(toSend) }else{ const toSend = { status: "error" } return res.json(toSend) } }) //SAVER-RULE STATUS UPDATER router.put('/saver-rule', checkAuth, async(req, res) => { const rule = req.body.rule await updateSaverRuleStatus(rule.emqxRuleId, rule.status) const toSend = { status: "success" } res.json(toSend) }) /* ______ _ _ _ _ _______ _____ ____ _ _ _____ | ____| | | | \ | |__ __|_ _/ __ \| \ | |/ ____| | |__ | | | | \| | | | | || | | | \| | (___ | __| | | | | . ` | | | | || | | | . ` |\___ \ | | | |__| | |\ | | | _| || |__| | |\ |____) | |_| \____/|_| \_| |_| |_____\____/|_| \_|_____/ */ async function
(userId) { try { const rules = await AlarmRule.find({userId}) return rules } catch (error) { return "error" } } async function selectDevice(userId, dId){ try { const result = await Device.updateMany({userId: userId}, {selected: false}) const result2 = await Device.updateOne({dId: dId, userId: userId},{selected:true}) return true } catch (error) { console.log("ERROR IN 'selectedDevice' FUNCTION") console.log(error) return false } } /* //SAVER RULES FUNCTION */ //get templates async function getTemplate(userId) { try { const templates = await Template.find({ userId: userId}) return templates } catch (error) { return false } } //get saver rules async function getSaverRules(userId) { try { const rules = await SaverRule.find({ userId: userId}) return rules } catch (error) { console.log("Error enviando RULES") console.log(error) return false } } //Create saver rule async function createSaverRule(userId, dId, status) { try { const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules" const topic = userId + "/" + dId + "/+/sdata" const rawsql = "SELECT topic, payload FROM \"" + topic + "\" WHERE payload.save = 1" var newRule = { rawsql: rawsql, actions: [ { name: "data_to_webserver", params: { $resource: global.saverResource.id, payload_tmpl: '{"userId":"' + userId + '","payload":${payload},"topic":"${topic}"}' } } ], description: "SAVER-RULE", enabled: status } //save rule in emqx - grabamos regla en emqx const res = await axios.post(url, newRule, auth) if (res.status === 200 && res.data.data) { console.log(res.data.data) await SaverRule.create({ userId: userId, dId: dId, emqxRuleId: res.data.data.id, status: status }) return true }else { console.log("Aqui esta el error ERRROR") return false } } catch (error) { console.log("Error creating SAVER RULE") console.log(error) return false } } //Update saver rule async function updateSaverRuleStatus(emqxRuleId, status) { const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + emqxRuleId const newRule = { enabled: status } const res = await axios.put(url, newRule, auth) if (res.status === 200 && res.data.data) { await SaverRule.updateOne({ emqxRuleId: emqxRuleId}, {status: status}) console.log("Saver Rule Status Update...".green) return { status: "success", action: "update" } } } //delete saver rule async function deleteSaverRule(dId) { try { const mongoRule = await SaverRule.findOne({dId: dId}) const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + mongoRule.emqxRuleId const emqxRule = await axios.delete(url, auth) const deleted = await SaverRule.deleteOne({dId: dId}) return true } catch (error) { console.log("Error Deleting Saver Rule") console.log(error) return false } } //delete ALL alarm Rules... async function deleteAllAlarmRules(userId, dId) { try { const rules = await AlarmRule.find({ userId: userId, dId: dId }); if
getAlarmRules
identifier_name
devices.js
:{ username: 'admin', password: process.env.EMQX_DEFAULT_APPLICATION_SECRET } } //GET DEVICES router.get("/device", checkAuth, async (req, res) =>{ try { const userId = req.userData._id //get devices var devices = await Device.find({userId: userId}) //descoupling devices = JSON.parse(JSON.stringify(devices)) //get saver rules const saverRules = await getSaverRules(userId) //get templates const templates = await getTemplate(userId) // get alarm rule const alarmRules = await getAlarmRules(userId) //saver rules to -> devices devices.forEach((device, index) => { devices[index].saverRule = saverRules.filter( saverRule => saverRule.dId == device.dId)[0] devices[index].template = templates.filter( template => template._id == device.templateId)[0] devices[index].alarmRules = alarmRules.filter(alarmRule => alarmRule.dId == device.dId) }) const toSend = { status: "success", data: devices } res.json(toSend) } catch (error) { console.log("ERROR GETTING DEVICES") console.log(error) const toSend = { status: "error", error: error } return res.status(500).json(toSend) } }) //NEW DEVICE router.post("/device", checkAuth, async (req, res) =>{ try { const userId = req.userData._id var newDevice = req.body.newDevice newDevice.userId = userId newDevice.createdTime = Date.now() newDevice.password = makeid(10) await createSaverRule(userId, newDevice.dId, true) const device = await Device.create(newDevice) await selectDevice(userId, newDevice.dId) const toSend = { status: "success" } return res.json(toSend) } catch (error) { console.log("ERROR CREATING NEW DEVICE") console.log(error) const toSend = { status: "error", error: error } return res.status(500).json(toSend) } }) //DELETE DEVICE router.delete("/device", checkAuth, async (req, res) =>{ try { const userId = req.userData._id const dId = req.query.dId await deleteSaverRule(dId) //deleting all posible alarm rules await deleteAllAlarmRules(userId, dId); //deleting all posible mqtt device credentials await deleteMqttDeviceCredentials(dId); //deleting data mqtt await deleteMqttDataDevices(dId) const result = await Device.deleteOne({userId: userId, dId: dId}) const toSend = { status: "success", data: result } return res.json(toSend) } catch (error) { console.log("ERROR DELETING DEVICE") console.log(error) const toSend = { status: "error" } return res.json(toSend) } }) //UPDATE DEVICE (SELECTOR) router.put("/device", checkAuth, async (req, res) =>{ const dId = req.body.dId const userId = req.userData._id if(await selectDevice(userId,dId)){ const toSend = { status: "success" } return res.json(toSend) }else{ const toSend = { status: "error" } return res.json(toSend) } }) //SAVER-RULE STATUS UPDATER router.put('/saver-rule', checkAuth, async(req, res) => { const rule = req.body.rule await updateSaverRuleStatus(rule.emqxRuleId, rule.status) const toSend = { status: "success" } res.json(toSend) }) /* ______ _ _ _ _ _______ _____ ____ _ _ _____ | ____| | | | \ | |__ __|_ _/ __ \| \ | |/ ____| | |__ | | | | \| | | | | || | | | \| | (___ | __| | | | | . ` | | | | || | | | . ` |\___ \ | | | |__| | |\ | | | _| || |__| | |\ |____) | |_| \____/|_| \_| |_| |_____\____/|_| \_|_____/ */ async function getAlarmRules(userId) { try { const rules = await AlarmRule.find({userId}) return rules } catch (error) { return "error" } } async function selectDevice(userId, dId){ try { const result = await Device.updateMany({userId: userId}, {selected: false}) const result2 = await Device.updateOne({dId: dId, userId: userId},{selected:true}) return true } catch (error) { console.log("ERROR IN 'selectedDevice' FUNCTION") console.log(error) return false } } /* //SAVER RULES FUNCTION */ //get templates async function getTemplate(userId) { try { const templates = await Template.find({ userId: userId}) return templates } catch (error) { return false } } //get saver rules async function getSaverRules(userId) { try { const rules = await SaverRule.find({ userId: userId}) return rules } catch (error) { console.log("Error enviando RULES") console.log(error) return false } } //Create saver rule async function createSaverRule(userId, dId, status) { try { const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules" const topic = userId + "/" + dId + "/+/sdata" const rawsql = "SELECT topic, payload FROM \"" + topic + "\" WHERE payload.save = 1" var newRule = { rawsql: rawsql, actions: [ { name: "data_to_webserver", params: { $resource: global.saverResource.id, payload_tmpl: '{"userId":"' + userId + '","payload":${payload},"topic":"${topic}"}' } } ], description: "SAVER-RULE", enabled: status } //save rule in emqx - grabamos regla en emqx const res = await axios.post(url, newRule, auth) if (res.status === 200 && res.data.data) { console.log(res.data.data) await SaverRule.create({ userId: userId, dId: dId, emqxRuleId: res.data.data.id, status: status }) return true }else { console.log("Aqui esta el error ERRROR") return false } } catch (error) { console.log("Error creating SAVER RULE") console.log(error) return false } } //Update saver rule async function updateSaverRuleStatus(emqxRuleId, status) { const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + emqxRuleId const newRule = { enabled: status } const res = await axios.put(url, newRule, auth) if (res.status === 200 && res.data.data) { await SaverRule.updateOne({ emqxRuleId: emqxRuleId}, {status: status}) console.log("Saver Rule Status Update...".green) return { status: "success", action: "update" } } } //delete saver rule async function deleteSaverRule(dId) { try { const mongoRule = await SaverRule.findOne({dId: dId}) const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + mongoRule.emqxRuleId const emqxRule = await axios.delete(url, auth) const deleted = await SaverRule.deleteOne({dId: dId}) return true } catch (error) { console.log("Error Deleting Saver Rule") console.log(error) return false } } //delete ALL alarm Rules... async function deleteAllAlarmRules(userId, dId)
{ try { const rules = await AlarmRule.find({ userId: userId, dId: dId }); if (rules.length > 0) { asyncForEach(rules, async rule => { const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + rule.emqxRuleId; const res = await axios.delete(url, auth); }); await AlarmRule.deleteMany({ userId: userId, dId: dId }); } return true; } catch (error) { console.log(error); return "error"; } }
identifier_body
devices.js
\___ \ | | | | |__| | |__| | |____| |____ ____) | |_| |_|\____/|_____/|______|______|_____/ */ /* _____ _____ /\ | __ \_ _| / \ | |__) || | / /\ \ | ___/ | | / ____ \| | _| |_ /_/ \_\_| |_____| */ const auth ={ auth:{ username: 'admin', password: process.env.EMQX_DEFAULT_APPLICATION_SECRET } } //GET DEVICES router.get("/device", checkAuth, async (req, res) =>{ try { const userId = req.userData._id //get devices var devices = await Device.find({userId: userId}) //descoupling devices = JSON.parse(JSON.stringify(devices)) //get saver rules const saverRules = await getSaverRules(userId) //get templates const templates = await getTemplate(userId) // get alarm rule const alarmRules = await getAlarmRules(userId) //saver rules to -> devices devices.forEach((device, index) => { devices[index].saverRule = saverRules.filter( saverRule => saverRule.dId == device.dId)[0] devices[index].template = templates.filter( template => template._id == device.templateId)[0] devices[index].alarmRules = alarmRules.filter(alarmRule => alarmRule.dId == device.dId) }) const toSend = { status: "success", data: devices } res.json(toSend) } catch (error) { console.log("ERROR GETTING DEVICES") console.log(error) const toSend = { status: "error", error: error } return res.status(500).json(toSend) } }) //NEW DEVICE router.post("/device", checkAuth, async (req, res) =>{ try { const userId = req.userData._id var newDevice = req.body.newDevice newDevice.userId = userId newDevice.createdTime = Date.now() newDevice.password = makeid(10) await createSaverRule(userId, newDevice.dId, true) const device = await Device.create(newDevice) await selectDevice(userId, newDevice.dId) const toSend = { status: "success" } return res.json(toSend) } catch (error) { console.log("ERROR CREATING NEW DEVICE") console.log(error) const toSend = { status: "error", error: error } return res.status(500).json(toSend) } }) //DELETE DEVICE router.delete("/device", checkAuth, async (req, res) =>{ try { const userId = req.userData._id const dId = req.query.dId await deleteSaverRule(dId) //deleting all posible alarm rules await deleteAllAlarmRules(userId, dId); //deleting all posible mqtt device credentials await deleteMqttDeviceCredentials(dId); //deleting data mqtt await deleteMqttDataDevices(dId) const result = await Device.deleteOne({userId: userId, dId: dId}) const toSend = { status: "success", data: result } return res.json(toSend) } catch (error) { console.log("ERROR DELETING DEVICE") console.log(error) const toSend = { status: "error" } return res.json(toSend) } }) //UPDATE DEVICE (SELECTOR) router.put("/device", checkAuth, async (req, res) =>{ const dId = req.body.dId const userId = req.userData._id if(await selectDevice(userId,dId)){ const toSend = { status: "success" } return res.json(toSend) }else{ const toSend = { status: "error" } return res.json(toSend) } }) //SAVER-RULE STATUS UPDATER router.put('/saver-rule', checkAuth, async(req, res) => { const rule = req.body.rule await updateSaverRuleStatus(rule.emqxRuleId, rule.status) const toSend = { status: "success" } res.json(toSend) }) /* ______ _ _ _ _ _______ _____ ____ _ _ _____ | ____| | | | \ | |__ __|_ _/ __ \| \ | |/ ____| | |__ | | | | \| | | | | || | | | \| | (___ | __| | | | | . ` | | | | || | | | . ` |\___ \ | | | |__| | |\ | | | _| || |__| | |\ |____) | |_| \____/|_| \_| |_| |_____\____/|_| \_|_____/ */ async function getAlarmRules(userId) { try { const rules = await AlarmRule.find({userId}) return rules } catch (error) { return "error" } } async function selectDevice(userId, dId){ try { const result = await Device.updateMany({userId: userId}, {selected: false}) const result2 = await Device.updateOne({dId: dId, userId: userId},{selected:true}) return true } catch (error) { console.log("ERROR IN 'selectedDevice' FUNCTION") console.log(error) return false } } /* //SAVER RULES FUNCTION */ //get templates async function getTemplate(userId) { try { const templates = await Template.find({ userId: userId}) return templates } catch (error) { return false } } //get saver rules async function getSaverRules(userId) { try { const rules = await SaverRule.find({ userId: userId}) return rules } catch (error) { console.log("Error enviando RULES") console.log(error) return false } } //Create saver rule async function createSaverRule(userId, dId, status) { try { const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules" const topic = userId + "/" + dId + "/+/sdata" const rawsql = "SELECT topic, payload FROM \"" + topic + "\" WHERE payload.save = 1" var newRule = { rawsql: rawsql, actions: [ { name: "data_to_webserver", params: { $resource: global.saverResource.id, payload_tmpl: '{"userId":"' + userId + '","payload":${payload},"topic":"${topic}"}' } } ], description: "SAVER-RULE", enabled: status } //save rule in emqx - grabamos regla en emqx const res = await axios.post(url, newRule, auth) if (res.status === 200 && res.data.data) { console.log(res.data.data) await SaverRule.create({ userId: userId, dId: dId, emqxRuleId: res.data.data.id, status: status }) return true }else { console.log("Aqui esta el error ERRROR") return false } } catch (error) { console.log("Error creating SAVER RULE") console.log(error) return false } } //Update saver rule async function updateSaverRuleStatus(emqxRuleId, status) {
} const res = await axios.put(url, newRule, auth) if (res.status === 200 && res.data.data) { await SaverRule.updateOne({ emqxRuleId: emqxRuleId}, {status: status}) console.log("Saver Rule Status Update...".green) return { status: "success", action: "update" } } } //delete saver rule async function deleteSaverRule(dId) { try { const mongoRule = await SaverRule.findOne({dId: dId}) const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + mongoRule.emqxRuleId const emqxRule = await axios.delete(url, auth) const deleted = await SaverRule.deleteOne({dId: dId}) return true } catch (error) { console.log("Error Deleting Saver Rule") console.log(error) return false } } //delete ALL alarm Rules... async function deleteAllAlarmRules(userId, dId) { try { const rules = await AlarmRule.find({ userId: userId, dId: dId }); if (
const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + emqxRuleId const newRule = { enabled: status
random_line_split
devices.js
const toSend = { status: "error", error: error } return res.status(500).json(toSend) } }) //NEW DEVICE router.post("/device", checkAuth, async (req, res) =>{ try { const userId = req.userData._id var newDevice = req.body.newDevice newDevice.userId = userId newDevice.createdTime = Date.now() newDevice.password = makeid(10) await createSaverRule(userId, newDevice.dId, true) const device = await Device.create(newDevice) await selectDevice(userId, newDevice.dId) const toSend = { status: "success" } return res.json(toSend) } catch (error) { console.log("ERROR CREATING NEW DEVICE") console.log(error) const toSend = { status: "error", error: error } return res.status(500).json(toSend) } }) //DELETE DEVICE router.delete("/device", checkAuth, async (req, res) =>{ try { const userId = req.userData._id const dId = req.query.dId await deleteSaverRule(dId) //deleting all posible alarm rules await deleteAllAlarmRules(userId, dId); //deleting all posible mqtt device credentials await deleteMqttDeviceCredentials(dId); //deleting data mqtt await deleteMqttDataDevices(dId) const result = await Device.deleteOne({userId: userId, dId: dId}) const toSend = { status: "success", data: result } return res.json(toSend) } catch (error) { console.log("ERROR DELETING DEVICE") console.log(error) const toSend = { status: "error" } return res.json(toSend) } }) //UPDATE DEVICE (SELECTOR) router.put("/device", checkAuth, async (req, res) =>{ const dId = req.body.dId const userId = req.userData._id if(await selectDevice(userId,dId)){ const toSend = { status: "success" } return res.json(toSend) }else{ const toSend = { status: "error" } return res.json(toSend) } }) //SAVER-RULE STATUS UPDATER router.put('/saver-rule', checkAuth, async(req, res) => { const rule = req.body.rule await updateSaverRuleStatus(rule.emqxRuleId, rule.status) const toSend = { status: "success" } res.json(toSend) }) /* ______ _ _ _ _ _______ _____ ____ _ _ _____ | ____| | | | \ | |__ __|_ _/ __ \| \ | |/ ____| | |__ | | | | \| | | | | || | | | \| | (___ | __| | | | | . ` | | | | || | | | . ` |\___ \ | | | |__| | |\ | | | _| || |__| | |\ |____) | |_| \____/|_| \_| |_| |_____\____/|_| \_|_____/ */ async function getAlarmRules(userId) { try { const rules = await AlarmRule.find({userId}) return rules } catch (error) { return "error" } } async function selectDevice(userId, dId){ try { const result = await Device.updateMany({userId: userId}, {selected: false}) const result2 = await Device.updateOne({dId: dId, userId: userId},{selected:true}) return true } catch (error) { console.log("ERROR IN 'selectedDevice' FUNCTION") console.log(error) return false } } /* //SAVER RULES FUNCTION */ //get templates async function getTemplate(userId) { try { const templates = await Template.find({ userId: userId}) return templates } catch (error) { return false } } //get saver rules async function getSaverRules(userId) { try { const rules = await SaverRule.find({ userId: userId}) return rules } catch (error) { console.log("Error enviando RULES") console.log(error) return false } } //Create saver rule async function createSaverRule(userId, dId, status) { try { const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules" const topic = userId + "/" + dId + "/+/sdata" const rawsql = "SELECT topic, payload FROM \"" + topic + "\" WHERE payload.save = 1" var newRule = { rawsql: rawsql, actions: [ { name: "data_to_webserver", params: { $resource: global.saverResource.id, payload_tmpl: '{"userId":"' + userId + '","payload":${payload},"topic":"${topic}"}' } } ], description: "SAVER-RULE", enabled: status } //save rule in emqx - grabamos regla en emqx const res = await axios.post(url, newRule, auth) if (res.status === 200 && res.data.data) { console.log(res.data.data) await SaverRule.create({ userId: userId, dId: dId, emqxRuleId: res.data.data.id, status: status }) return true }else { console.log("Aqui esta el error ERRROR") return false } } catch (error) { console.log("Error creating SAVER RULE") console.log(error) return false } } //Update saver rule async function updateSaverRuleStatus(emqxRuleId, status) { const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + emqxRuleId const newRule = { enabled: status } const res = await axios.put(url, newRule, auth) if (res.status === 200 && res.data.data) { await SaverRule.updateOne({ emqxRuleId: emqxRuleId}, {status: status}) console.log("Saver Rule Status Update...".green) return { status: "success", action: "update" } } } //delete saver rule async function deleteSaverRule(dId) { try { const mongoRule = await SaverRule.findOne({dId: dId}) const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + mongoRule.emqxRuleId const emqxRule = await axios.delete(url, auth) const deleted = await SaverRule.deleteOne({dId: dId}) return true } catch (error) { console.log("Error Deleting Saver Rule") console.log(error) return false } } //delete ALL alarm Rules... async function deleteAllAlarmRules(userId, dId) { try { const rules = await AlarmRule.find({ userId: userId, dId: dId }); if (rules.length > 0) { asyncForEach(rules, async rule => { const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + rule.emqxRuleId; const res = await axios.delete(url, auth); }); await AlarmRule.deleteMany({ userId: userId, dId: dId }); } return true; } catch (error) { console.log(error); return "error"; } } // We can solve this by creating our own asyncForEach() method: // thanks to Sebastien Chopin - Nuxt Creator :) // https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404 async function asyncForEach(array, callback) { for (let index = 0; index < array.length; index++) { await callback(array[index], index, array); } } //delete ALL emqx device auth rules async function deleteMqttDeviceCredentials(dId) { try { await EmqxAuthRule.deleteMany({ dId: dId, type: "device" }); return true; } catch (error) { console.log(error); return false; } } async function deleteMqttDataDevices(dId) { try { await Data.deleteMany({dId: dId}); return true; } catch (error) { console.log(error); return false; } } function makeid(length) { var result ='' var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" var charactersLength = characters.length for (var i = 0; i < length; i ++)
{ result += characters.charAt ( Math.floor(Math.random() * charactersLength) ) }
conditional_block
compare-table.ts
= new Set(); fields.forEach(function(field) { if (field.source) { sources.add(field.source); } }); return Array.from(sources).join(","); } export function init(table, fields, options) { // TODO: use of jQuery disabled to support compile return undefined; /* jQuery(table).DataTable({ data: [], rowId: "run.id", columns: columns(fields), order: [[2, 'desc']], scrollY: (options && options.height) || "360px", scrollCollapse: true, paging: false, language: { info: "_TOTAL_ runs", infoFiltered: " (filtered from _MAX_)", infoEmpty: "_TOTAL_ runs", search: "", searchPlaceholder: "Filter", zeroRecords: "Waiting for data" }, dom: "<'row'<'col-12'f>>" + "<'row'<'col-12'tr>>" + "<'row'<'col-12'i>>" }); */ } function columns(fields) { return baseCols().concat(fieldCols(fields)); } function baseCols() { return [ selectedCol(), statusCol(), timeCol(), modelCol() ]; } function selectedCol() { return { title: "<guild-compare-table-select header></guild-compare-table-select>", data: null, orderable: false, width: "18px", render: function(item, type) { if (type == "display") { return tableSelect(); } else { return item.value; } } } } function tableSelect() { return "<guild-compare-table-select></guild-compare-table-select>"; } function statusCol() { return { title: statusTitle(), data: "status", width: "20px", render: function(item, type) { if (type == "display") { return statusIcon(item); } else if (type == "sort") { return "sort"; } else if (type == "filter") { return "label"; } else { return item.value; } } } } function statusTitle() { return "<span class='header-title status-title'></span>"; } function statusIcon(status) { return "<fa-awesome class='" + status.iconClass + "'" + maybeSpinAttr(status.spin) + " icon='" + status.icon + "' size='22'></fa-awesome>" + "<paper-tooltip position='right'" + " animation-delay='250' offset='0'>" + status.label + "</paper-tooltip>"; } function maybeSpinAttr(spin) { return spin ? " spin" : ""; } function timeCol() { return { title: headerTitle("Time"), data: "time", orderSequence: ["desc", "asc"], width: "8em", render: function(item, type, row) { if (type == "display")
else if (type == "sort") { return "sort"; } else if (type == "filter") { return "label"; } else { return item.value; } } } } function headerTitle(title) { return "<span class='header-title'>" + title + "</span>"; } function runLink(val, run) { var link = "/train?run=" + run.id; return "<a href='" + link + "' class='date'>" + val + "</a>"; } function modelCol() { return { title: headerTitle("Model"), data: "run", render: { _: "model" } } } function fieldCols(fields) { return fields.map(function(field, index) { return { title: headerTitle(field.label), data: "f" + index, orderSequence: ["desc", "asc"], type: fieldType(field), render: function(field, type, _row, _meta) { if (type == "sort") { return field.sort; } else { return field.value; } } } }); } function fieldType(field) { // Infer numeric type by reduce function return field.reduce ? "num" : "string"; } export function refresh(dt, data, fields) { var items = formatItems(data, fields); deleteMissingRows(dt, items); addOrUpdateRows(dt, items); } function formatItems(data, fields) { return data.map(function(item, index) { return Object.assign( itemBase(item, index), itemFields(item, fields)); }); } function itemBase(item, index) { return { run: item.run, time: formatTime(item.run.started), status: runStatus(item.run), index: index, selected: false } } function runStatus(run) { var status = runStatus(run); status.sort = statusSort(status); return status; } function statusSort(status) { var label = status.label; if (label == "Running") { return 0; } else if (label == "Completed") { return 1; } else if (label == "Terminated") { return 2; } else if (label == "Error") { return 3; } else { return 4; } } function formatTime(epoch) { return { value: formatShortDate(new Date(epoch)), sort: epoch } } function itemFields(item, fieldDefs) { var fields = {} fieldDefs.forEach(function(field, index) { var data = item[field.source]; var name = "f" + index; fields[name] = fieldValue(data, field); }); return fields; } function fieldValue(data, field) { var raw = fieldRawValue(data, field); var sort = raw == undefined ? null: raw; var formatted = fieldFormattedValue(raw, field) || ""; return {sort: sort, value: formatted} } function fieldRawValue(data, field) { if (field.attribute) { return data[field.attribute]; } else if (field.reduce) { var reduce = reduceFunctions[field.reduce]; if (reduce) { var reduced = reduce(data); return reduced[Object.keys(reduced)[0]]; } } return undefined; } function fieldFormattedValue(raw, field) { return field.format ? tryFormat(raw, field.format) : raw; } function deleteMissingRows(dt, items) { var itemIds = itemIdLookup(items); var missing = []; dt.rows().every(function(index) { if (!itemIds.has(dt.row(index).data().run.id)) { missing.push(index); } }); if (missing.length > 0) { dt.rows(missing).remove().draw(); } } function itemIdLookup(items) { var ids = items.map(function(item) { return item.run.id; }); return new Set(ids); } function addOrUpdateRows(dt, items) { var added = false; items.forEach(function(item, index) { var curRow = findRow(dt, item); if (curRow != null) { updateRow(dt, curRow, item); } else { addRow(dt, item); added = true; } }); if (added) { dt.columns.adjust(); } } function findRow(dt, target) { var row = dt.row("#" + target.run.id); return row.data() != undefined ? row : null; } function updateRow(dt, row, newItem) { var curItem = row.data(); dt.columns().every(function(colIndex) { var property = dt.column(colIndex).dataSrc(); var curVal = curItem[property]; var newVal = newItem[property]; if (itemValChanged(curVal, newVal)) { dt.cell(row, colIndex).data(newVal); } }); } function itemValChanged(a, b) { return JSON.stringify(a) != JSON.stringify(b); } function rowCellChanged(index, curVal, newVal) { if (index == 0) { return curVal.status != newVal.status; } else { return curVal != newVal; } } function addRow(dt, item) { var row = dt.row.add(item); row.draw(); } export function refreshRowsForSelected(dt) { dt.rows().every(function(index) { var tr = dt.row(index).node(); var item = dt.row(index).data(); var select = tr.querySelector("guild-compare-table-select"); if (select.value == "true") { item.selected = true; // TODO: use of $ disabled to support compile //$(tr).addClass("highlight"); } else { item.selected = false; // TODO: use of $ disabled to support compile //$(tr).removeClass("highlight"); } }); } export function refreshSelectHeader(dt) { var header = headerSelectForTable(dt); var selects = selectsForTable(dt); header.value = headerValueForSelects(selects); } function headerSelectForTable(dt) { return dt.table().header().querySelector("guild-compare-table-select"); } function selectsForTable(dt) { return dt.table().body().querySelectorAll("guild-compare-table-select"); } function headerValueForSelects(selects) { var first
{ return runLink(item.value, row.run); }
conditional_block
compare-table.ts
= new Set(); fields.forEach(function(field) { if (field.source) { sources.add(field.source); } }); return Array.from(sources).join(","); } export function init(table, fields, options) { // TODO: use of jQuery disabled to support compile return undefined; /* jQuery(table).DataTable({ data: [], rowId: "run.id", columns: columns(fields), order: [[2, 'desc']], scrollY: (options && options.height) || "360px", scrollCollapse: true, paging: false, language: { info: "_TOTAL_ runs", infoFiltered: " (filtered from _MAX_)", infoEmpty: "_TOTAL_ runs", search: "", searchPlaceholder: "Filter", zeroRecords: "Waiting for data" }, dom: "<'row'<'col-12'f>>" + "<'row'<'col-12'tr>>" + "<'row'<'col-12'i>>" }); */ } function columns(fields) { return baseCols().concat(fieldCols(fields)); } function baseCols() { return [ selectedCol(), statusCol(), timeCol(), modelCol() ]; } function selectedCol() { return { title: "<guild-compare-table-select header></guild-compare-table-select>", data: null, orderable: false, width: "18px", render: function(item, type) { if (type == "display") { return tableSelect(); } else { return item.value; } } } } function tableSelect() { return "<guild-compare-table-select></guild-compare-table-select>"; } function statusCol() { return { title: statusTitle(), data: "status", width: "20px", render: function(item, type) { if (type == "display") { return statusIcon(item); } else if (type == "sort") { return "sort"; } else if (type == "filter") { return "label"; } else { return item.value; } } } } function statusTitle() { return "<span class='header-title status-title'></span>"; } function statusIcon(status) { return "<fa-awesome class='" + status.iconClass + "'" + maybeSpinAttr(status.spin) + " icon='" + status.icon + "' size='22'></fa-awesome>" + "<paper-tooltip position='right'" + " animation-delay='250' offset='0'>" + status.label + "</paper-tooltip>"; } function maybeSpinAttr(spin) { return spin ? " spin" : ""; } function timeCol() { return { title: headerTitle("Time"), data: "time", orderSequence: ["desc", "asc"], width: "8em", render: function(item, type, row) { if (type == "display") { return runLink(item.value, row.run); } else if (type == "sort") { return "sort"; } else if (type == "filter") { return "label"; } else { return item.value; } } } } function headerTitle(title) { return "<span class='header-title'>" + title + "</span>"; } function runLink(val, run) { var link = "/train?run=" + run.id; return "<a href='" + link + "' class='date'>" + val + "</a>"; } function modelCol() { return { title: headerTitle("Model"), data: "run", render: { _: "model" } } } function fieldCols(fields) { return fields.map(function(field, index) { return { title: headerTitle(field.label), data: "f" + index, orderSequence: ["desc", "asc"], type: fieldType(field), render: function(field, type, _row, _meta) { if (type == "sort") { return field.sort; } else { return field.value; } } } }); } function fieldType(field) { // Infer numeric type by reduce function return field.reduce ? "num" : "string"; } export function refresh(dt, data, fields) { var items = formatItems(data, fields); deleteMissingRows(dt, items); addOrUpdateRows(dt, items); } function formatItems(data, fields) { return data.map(function(item, index) { return Object.assign( itemBase(item, index), itemFields(item, fields)); }); } function itemBase(item, index) { return { run: item.run, time: formatTime(item.run.started), status: runStatus(item.run), index: index, selected: false } } function runStatus(run) { var status = runStatus(run); status.sort = statusSort(status); return status; } function statusSort(status) { var label = status.label; if (label == "Running") { return 0; } else if (label == "Completed") { return 1; } else if (label == "Terminated") { return 2; } else if (label == "Error") { return 3; } else { return 4; } } function formatTime(epoch) { return { value: formatShortDate(new Date(epoch)), sort: epoch } } function itemFields(item, fieldDefs) { var fields = {} fieldDefs.forEach(function(field, index) { var data = item[field.source]; var name = "f" + index; fields[name] = fieldValue(data, field); }); return fields; } function fieldValue(data, field) { var raw = fieldRawValue(data, field); var sort = raw == undefined ? null: raw; var formatted = fieldFormattedValue(raw, field) || ""; return {sort: sort, value: formatted} } function fieldRawValue(data, field) { if (field.attribute) { return data[field.attribute]; } else if (field.reduce) { var reduce = reduceFunctions[field.reduce]; if (reduce) { var reduced = reduce(data); return reduced[Object.keys(reduced)[0]]; } } return undefined; } function fieldFormattedValue(raw, field) { return field.format ? tryFormat(raw, field.format) : raw; } function deleteMissingRows(dt, items) { var itemIds = itemIdLookup(items); var missing = []; dt.rows().every(function(index) { if (!itemIds.has(dt.row(index).data().run.id)) { missing.push(index); } }); if (missing.length > 0) { dt.rows(missing).remove().draw(); } } function itemIdLookup(items)
function addOrUpdateRows(dt, items) { var added = false; items.forEach(function(item, index) { var curRow = findRow(dt, item); if (curRow != null) { updateRow(dt, curRow, item); } else { addRow(dt, item); added = true; } }); if (added) { dt.columns.adjust(); } } function findRow(dt, target) { var row = dt.row("#" + target.run.id); return row.data() != undefined ? row : null; } function updateRow(dt, row, newItem) { var curItem = row.data(); dt.columns().every(function(colIndex) { var property = dt.column(colIndex).dataSrc(); var curVal = curItem[property]; var newVal = newItem[property]; if (itemValChanged(curVal, newVal)) { dt.cell(row, colIndex).data(newVal); } }); } function itemValChanged(a, b) { return JSON.stringify(a) != JSON.stringify(b); } function rowCellChanged(index, curVal, newVal) { if (index == 0) { return curVal.status != newVal.status; } else { return curVal != newVal; } } function addRow(dt, item) { var row = dt.row.add(item); row.draw(); } export function refreshRowsForSelected(dt) { dt.rows().every(function(index) { var tr = dt.row(index).node(); var item = dt.row(index).data(); var select = tr.querySelector("guild-compare-table-select"); if (select.value == "true") { item.selected = true; // TODO: use of $ disabled to support compile //$(tr).addClass("highlight"); } else { item.selected = false; // TODO: use of $ disabled to support compile //$(tr).removeClass("highlight"); } }); } export function refreshSelectHeader(dt) { var header = headerSelectForTable(dt); var selects = selectsForTable(dt); header.value = headerValueForSelects(selects); } function headerSelectForTable(dt) { return dt.table().header().querySelector("guild-compare-table-select"); } function selectsForTable(dt) { return dt.table().body().querySelectorAll("guild-compare-table-select"); } function headerValueForSelects(selects) { var
{ var ids = items.map(function(item) { return item.run.id; }); return new Set(ids); }
identifier_body
compare-table.ts
= new Set(); fields.forEach(function(field) { if (field.source) { sources.add(field.source); } }); return Array.from(sources).join(","); } export function init(table, fields, options) { // TODO: use of jQuery disabled to support compile return undefined; /* jQuery(table).DataTable({ data: [], rowId: "run.id", columns: columns(fields), order: [[2, 'desc']], scrollY: (options && options.height) || "360px", scrollCollapse: true, paging: false, language: { info: "_TOTAL_ runs", infoFiltered: " (filtered from _MAX_)", infoEmpty: "_TOTAL_ runs", search: "", searchPlaceholder: "Filter", zeroRecords: "Waiting for data" }, dom: "<'row'<'col-12'f>>" + "<'row'<'col-12'tr>>" + "<'row'<'col-12'i>>" }); */ } function columns(fields) { return baseCols().concat(fieldCols(fields)); } function baseCols() { return [ selectedCol(), statusCol(), timeCol(), modelCol() ]; } function selectedCol() { return { title: "<guild-compare-table-select header></guild-compare-table-select>", data: null, orderable: false, width: "18px", render: function(item, type) { if (type == "display") { return tableSelect(); } else { return item.value; } } } } function tableSelect() { return "<guild-compare-table-select></guild-compare-table-select>"; } function statusCol() { return { title: statusTitle(), data: "status", width: "20px", render: function(item, type) { if (type == "display") { return statusIcon(item); } else if (type == "sort") { return "sort"; } else if (type == "filter") { return "label"; } else { return item.value; } } } } function statusTitle() { return "<span class='header-title status-title'></span>"; } function statusIcon(status) { return "<fa-awesome class='" + status.iconClass + "'" + maybeSpinAttr(status.spin) + " icon='" + status.icon + "' size='22'></fa-awesome>" + "<paper-tooltip position='right'" + " animation-delay='250' offset='0'>" + status.label + "</paper-tooltip>"; } function maybeSpinAttr(spin) { return spin ? " spin" : ""; } function timeCol() { return { title: headerTitle("Time"), data: "time", orderSequence: ["desc", "asc"], width: "8em", render: function(item, type, row) { if (type == "display") { return runLink(item.value, row.run); } else if (type == "sort") { return "sort"; } else if (type == "filter") { return "label"; } else { return item.value; } } } } function headerTitle(title) { return "<span class='header-title'>" + title + "</span>"; } function runLink(val, run) { var link = "/train?run=" + run.id; return "<a href='" + link + "' class='date'>" + val + "</a>"; } function modelCol() { return { title: headerTitle("Model"), data: "run", render: { _: "model" } } } function fieldCols(fields) { return fields.map(function(field, index) { return { title: headerTitle(field.label), data: "f" + index, orderSequence: ["desc", "asc"], type: fieldType(field), render: function(field, type, _row, _meta) { if (type == "sort") { return field.sort; } else { return field.value; } } } }); } function fieldType(field) { // Infer numeric type by reduce function return field.reduce ? "num" : "string"; } export function refresh(dt, data, fields) { var items = formatItems(data, fields); deleteMissingRows(dt, items); addOrUpdateRows(dt, items); } function formatItems(data, fields) { return data.map(function(item, index) { return Object.assign( itemBase(item, index), itemFields(item, fields)); }); } function itemBase(item, index) { return { run: item.run, time: formatTime(item.run.started), status: runStatus(item.run), index: index, selected: false } } function runStatus(run) { var status = runStatus(run); status.sort = statusSort(status); return status; } function statusSort(status) { var label = status.label; if (label == "Running") { return 0; } else if (label == "Completed") { return 1; } else if (label == "Terminated") { return 2; } else if (label == "Error") { return 3; } else { return 4; } } function formatTime(epoch) { return { value: formatShortDate(new Date(epoch)), sort: epoch } } function itemFields(item, fieldDefs) { var fields = {} fieldDefs.forEach(function(field, index) { var data = item[field.source]; var name = "f" + index; fields[name] = fieldValue(data, field); }); return fields; } function fieldValue(data, field) { var raw = fieldRawValue(data, field); var sort = raw == undefined ? null: raw; var formatted = fieldFormattedValue(raw, field) || ""; return {sort: sort, value: formatted} } function fieldRawValue(data, field) { if (field.attribute) { return data[field.attribute]; } else if (field.reduce) { var reduce = reduceFunctions[field.reduce]; if (reduce) { var reduced = reduce(data); return reduced[Object.keys(reduced)[0]]; } } return undefined; } function fieldFormattedValue(raw, field) { return field.format ? tryFormat(raw, field.format) : raw; } function deleteMissingRows(dt, items) { var itemIds = itemIdLookup(items); var missing = []; dt.rows().every(function(index) { if (!itemIds.has(dt.row(index).data().run.id)) { missing.push(index); } }); if (missing.length > 0) { dt.rows(missing).remove().draw(); } } function itemIdLookup(items) { var ids = items.map(function(item) { return item.run.id; });
return new Set(ids); } function addOrUpdateRows(dt, items) { var added = false; items.forEach(function(item, index) { var curRow = findRow(dt, item); if (curRow != null) { updateRow(dt, curRow, item); } else { addRow(dt, item); added = true; } }); if (added) { dt.columns.adjust(); } } function findRow(dt, target) { var row = dt.row("#" + target.run.id); return row.data() != undefined ? row : null; } function updateRow(dt, row, newItem) { var curItem = row.data(); dt.columns().every(function(colIndex) { var property = dt.column(colIndex).dataSrc(); var curVal = curItem[property]; var newVal = newItem[property]; if (itemValChanged(curVal, newVal)) { dt.cell(row, colIndex).data(newVal); } }); } function itemValChanged(a, b) { return JSON.stringify(a) != JSON.stringify(b); } function rowCellChanged(index, curVal, newVal) { if (index == 0) { return curVal.status != newVal.status; } else { return curVal != newVal; } } function addRow(dt, item) { var row = dt.row.add(item); row.draw(); } export function refreshRowsForSelected(dt) { dt.rows().every(function(index) { var tr = dt.row(index).node(); var item = dt.row(index).data(); var select = tr.querySelector("guild-compare-table-select"); if (select.value == "true") { item.selected = true; // TODO: use of $ disabled to support compile //$(tr).addClass("highlight"); } else { item.selected = false; // TODO: use of $ disabled to support compile //$(tr).removeClass("highlight"); } }); } export function refreshSelectHeader(dt) { var header = headerSelectForTable(dt); var selects = selectsForTable(dt); header.value = headerValueForSelects(selects); } function headerSelectForTable(dt) { return dt.table().header().querySelector("guild-compare-table-select"); } function selectsForTable(dt) { return dt.table().body().querySelectorAll("guild-compare-table-select"); } function headerValueForSelects(selects) { var first =
random_line_split
compare-table.ts
= new Set(); fields.forEach(function(field) { if (field.source) { sources.add(field.source); } }); return Array.from(sources).join(","); } export function init(table, fields, options) { // TODO: use of jQuery disabled to support compile return undefined; /* jQuery(table).DataTable({ data: [], rowId: "run.id", columns: columns(fields), order: [[2, 'desc']], scrollY: (options && options.height) || "360px", scrollCollapse: true, paging: false, language: { info: "_TOTAL_ runs", infoFiltered: " (filtered from _MAX_)", infoEmpty: "_TOTAL_ runs", search: "", searchPlaceholder: "Filter", zeroRecords: "Waiting for data" }, dom: "<'row'<'col-12'f>>" + "<'row'<'col-12'tr>>" + "<'row'<'col-12'i>>" }); */ } function columns(fields) { return baseCols().concat(fieldCols(fields)); } function baseCols() { return [ selectedCol(), statusCol(), timeCol(), modelCol() ]; } function selectedCol() { return { title: "<guild-compare-table-select header></guild-compare-table-select>", data: null, orderable: false, width: "18px", render: function(item, type) { if (type == "display") { return tableSelect(); } else { return item.value; } } } } function tableSelect() { return "<guild-compare-table-select></guild-compare-table-select>"; } function statusCol() { return { title: statusTitle(), data: "status", width: "20px", render: function(item, type) { if (type == "display") { return statusIcon(item); } else if (type == "sort") { return "sort"; } else if (type == "filter") { return "label"; } else { return item.value; } } } } function statusTitle() { return "<span class='header-title status-title'></span>"; } function statusIcon(status) { return "<fa-awesome class='" + status.iconClass + "'" + maybeSpinAttr(status.spin) + " icon='" + status.icon + "' size='22'></fa-awesome>" + "<paper-tooltip position='right'" + " animation-delay='250' offset='0'>" + status.label + "</paper-tooltip>"; } function maybeSpinAttr(spin) { return spin ? " spin" : ""; } function timeCol() { return { title: headerTitle("Time"), data: "time", orderSequence: ["desc", "asc"], width: "8em", render: function(item, type, row) { if (type == "display") { return runLink(item.value, row.run); } else if (type == "sort") { return "sort"; } else if (type == "filter") { return "label"; } else { return item.value; } } } } function headerTitle(title) { return "<span class='header-title'>" + title + "</span>"; } function runLink(val, run) { var link = "/train?run=" + run.id; return "<a href='" + link + "' class='date'>" + val + "</a>"; } function modelCol() { return { title: headerTitle("Model"), data: "run", render: { _: "model" } } } function fieldCols(fields) { return fields.map(function(field, index) { return { title: headerTitle(field.label), data: "f" + index, orderSequence: ["desc", "asc"], type: fieldType(field), render: function(field, type, _row, _meta) { if (type == "sort") { return field.sort; } else { return field.value; } } } }); } function fieldType(field) { // Infer numeric type by reduce function return field.reduce ? "num" : "string"; } export function refresh(dt, data, fields) { var items = formatItems(data, fields); deleteMissingRows(dt, items); addOrUpdateRows(dt, items); } function formatItems(data, fields) { return data.map(function(item, index) { return Object.assign( itemBase(item, index), itemFields(item, fields)); }); } function itemBase(item, index) { return { run: item.run, time: formatTime(item.run.started), status: runStatus(item.run), index: index, selected: false } } function runStatus(run) { var status = runStatus(run); status.sort = statusSort(status); return status; } function statusSort(status) { var label = status.label; if (label == "Running") { return 0; } else if (label == "Completed") { return 1; } else if (label == "Terminated") { return 2; } else if (label == "Error") { return 3; } else { return 4; } } function formatTime(epoch) { return { value: formatShortDate(new Date(epoch)), sort: epoch } } function itemFields(item, fieldDefs) { var fields = {} fieldDefs.forEach(function(field, index) { var data = item[field.source]; var name = "f" + index; fields[name] = fieldValue(data, field); }); return fields; } function fieldValue(data, field) { var raw = fieldRawValue(data, field); var sort = raw == undefined ? null: raw; var formatted = fieldFormattedValue(raw, field) || ""; return {sort: sort, value: formatted} } function fieldRawValue(data, field) { if (field.attribute) { return data[field.attribute]; } else if (field.reduce) { var reduce = reduceFunctions[field.reduce]; if (reduce) { var reduced = reduce(data); return reduced[Object.keys(reduced)[0]]; } } return undefined; } function fieldFormattedValue(raw, field) { return field.format ? tryFormat(raw, field.format) : raw; } function deleteMissingRows(dt, items) { var itemIds = itemIdLookup(items); var missing = []; dt.rows().every(function(index) { if (!itemIds.has(dt.row(index).data().run.id)) { missing.push(index); } }); if (missing.length > 0) { dt.rows(missing).remove().draw(); } } function itemIdLookup(items) { var ids = items.map(function(item) { return item.run.id; }); return new Set(ids); } function addOrUpdateRows(dt, items) { var added = false; items.forEach(function(item, index) { var curRow = findRow(dt, item); if (curRow != null) { updateRow(dt, curRow, item); } else { addRow(dt, item); added = true; } }); if (added) { dt.columns.adjust(); } } function
(dt, target) { var row = dt.row("#" + target.run.id); return row.data() != undefined ? row : null; } function updateRow(dt, row, newItem) { var curItem = row.data(); dt.columns().every(function(colIndex) { var property = dt.column(colIndex).dataSrc(); var curVal = curItem[property]; var newVal = newItem[property]; if (itemValChanged(curVal, newVal)) { dt.cell(row, colIndex).data(newVal); } }); } function itemValChanged(a, b) { return JSON.stringify(a) != JSON.stringify(b); } function rowCellChanged(index, curVal, newVal) { if (index == 0) { return curVal.status != newVal.status; } else { return curVal != newVal; } } function addRow(dt, item) { var row = dt.row.add(item); row.draw(); } export function refreshRowsForSelected(dt) { dt.rows().every(function(index) { var tr = dt.row(index).node(); var item = dt.row(index).data(); var select = tr.querySelector("guild-compare-table-select"); if (select.value == "true") { item.selected = true; // TODO: use of $ disabled to support compile //$(tr).addClass("highlight"); } else { item.selected = false; // TODO: use of $ disabled to support compile //$(tr).removeClass("highlight"); } }); } export function refreshSelectHeader(dt) { var header = headerSelectForTable(dt); var selects = selectsForTable(dt); header.value = headerValueForSelects(selects); } function headerSelectForTable(dt) { return dt.table().header().querySelector("guild-compare-table-select"); } function selectsForTable(dt) { return dt.table().body().querySelectorAll("guild-compare-table-select"); } function headerValueForSelects(selects) { var first
findRow
identifier_name
tree.go
[1:], aUrl[:idx]}) return h } } } *aParams = append(*aParams, param{aNode.Text[1:], aUrl}) return aNode } else if aNode.Type == VariantNode { // 变量节点 // # 消除path like /abc 的'/' idx := strings.IndexByte(aUrl, r.DelimitChar) //fmt.Println("D态", aUrl, " | ", aNode.Text[1:], idx) if idx == 0 { // #fix错误if idx > -1 { for _, c := range aNode.Children { h := r.matchNode(c, aUrl[idx:], aParams) if h != nil { /*fmt.Println("类型1", aUrl[:idx], aNode.ContentType) if !validType(aUrl[:idx], aNode.ContentType) { fmt.Println("错误类型", aUrl[:idx], aNode.ContentType) return nil } */ *aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]}) return h } } return nil } // 最底层Node //if len(aNode.Children) == 0 { // *aParams = append(*aParams, param{aNode.Text[1:], aUrl}) // return aNode //} //fmt.Println("Index", idx) for _, c := range aNode.Children { idx := strings.Index(aUrl, c.Text) // #匹配前面检索到的/之前的字符串 //fmt.Println("Index", idx, aUrl, c.Text, aUrl[:idx]) if idx > -1 { if len(aUrl[:idx]) > 1 && strings.IndexByte(aUrl[:idx], r.DelimitChar) > -1 { retnil = true continue } //fmt.Println("类型2", aUrl[:idx], aNode.ContentType) if !validType(aUrl[:idx], aNode.ContentType) { //fmt.Println("错误类型", aUrl[:idx], aNode.ContentType) return nil //continue } h := r.matchNode(c, aUrl[idx:], aParams) if h != nil { *aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]}) return h } retnil = true } } if retnil { return nil } //fmt.Printf("动态", aUrl, aNode.Text[1:]) *aParams = append(*aParams, param{aNode.Text[1:], aUrl}) return aNode } else if aNode.Type == RegexpNode { // 正则节点 //if len(aNode.Children) == 0 && aNode.regexp.MatchString(aUrl) { // *aParams = append(*aParams, param{aNode.Text[1:], aUrl}) // return aNode //} idx := strings.IndexByte(aUrl, r.DelimitChar) if idx > -1 { if aNode.regexp.MatchString(aUrl[:idx]) { for _, c := range aNode.Children { h := r.matchNode(c, aUrl[idx:], aParams) if h != nil { *aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]}) return h } } } return nil } for _, c := range aNode.Children { idx := strings.Index(aUrl, c.Text) if idx > -1 && aNode.regexp.MatchString(aUrl[:idx]) { h := r.matchNode(c, aUrl[idx:], aParams) if h != nil { *aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]}) return h } } } if aNode.regexp.MatchString(aUrl) { *aParams = append(*aParams, param{aNode.Text[1:], aUrl}) return aNode } } return nil } func (r *TTree) Match(method string, url string) (*TRoute, Params) { lRoot := r.Root[method] var lParams = make(Params, 0, strings.Count(url, string(r.DelimitChar))) for _, n := range lRoot.Children { e := r.matchNode(n, url, &lParams) if e != nil { return e.Route, lParams } } return nil, nil } func validType(content string, typ ContentType) bool { switch typ { case NumberType: for i := 0; i < len(content); i++ { if !utils.IsDigitByte(content[i]) { return false } } case CharType: for i := 0; i < len(content); i++ { if !utils.IsAlphaByte(content[i]) { return false } } default: } return true } // validate parsed nodes, all non-static route should have static route children. func validNodes(nodes []*TNode) bool { if len(nodes) == 0 { return false } var lastTp = nodes[0] for _, node := range nodes[1:] { if lastTp.Type != StaticNode && node.Type != StaticNode { return false } lastTp = node } return true } // 添加路由到Tree func (self *TTree) AddRoute(aMethod, path string, aRoute *TRoute) { // 解析并创建为Nodes的List形式 lNodes, lIsDyn := self.parsePath(path) // 标记为动态路由 aRoute.isDynRoute = lIsDyn // 即将Hook的新Route是动态地址 // 绑定Route到最后一个Node lNode := lNodes[len(lNodes)-1] aRoute.Action = lNode.Text // 赋值Action lNode.Route = aRoute lNode.Path = path // 验证合法性 if !validNodes(lNodes) { logger.Panic("express %s is not supported", path) } // 插入该节点到Tree self.addnodes(aMethod, lNodes, false) } // conbine 2 node together func (self *TTree) conbine(aDes, aSrc *TNode) { var lNode *TNode // 是否目标Node有该Node for _, node := range aDes.Children { if node.Equal(aSrc) { lNode = node } } // 如果:无该Node直接添加完成所有工作 // 或者:遍历添加所有没有的新Node if lNode == nil { aDes.Children = append(aDes.Children, aSrc) return } else { if lNode.Type == RegexpNode { } if aSrc.Route != nil { if lNode.Route == nil { lNode.Route = aSrc.Route } else { // 叠加合并Controller lNode.Route.CombineController(aSrc.Route) } } // 合并子节点 for _, _node := range aSrc.Children { self.conbine(lNode, _node) } } } // conbine 2 tree together func (self *TTree) Conbine(aTree *TTree) *TTree { for method, snode := range aTree.Root { // 如果主树没有该方法叉则直接移植 if _, has := self.Root[method]; !has { self.Root[method] = snode } else { // 采用逐个添加 for _, node := range self.Root[method].Children { self.conbine(node, snode) } } } return self } // add node nodes[i] to parent node p func (self *TNode) addnode(aParent *TNode, aNodes []*TNode, i int, aIsHook bool) *TNode { if len(aParent.Children) == 0 { aParent.Children = make([]*TNode, 0) } // 如果:找到[已经注册]的分支节点则从该节继续[查找/添加]下一个节点 for _, n := range aParent.Children { if n.Equal(aNodes[i]) { // 如果:插入的节点层级已经到末尾,则为该节点注册路由 if i == len(aNodes)-1 { // 原始路由会被替换 if aIsHook { n.Route.CombineController(aNodes[i].Route) } else { n.Route = aNodes[i].Route } } return n } } // 如果:该节点没有对应分支则插入同级的aNodes为新的分支 aParent.Children = append(aParent.Children, aNodes[i]) sort.Sort(aParent.Children) return aNodes[i] } // add nodes to trees func (self *TTree) addnodes(aMethod string, aNodes []*TNode, aIsHook bool) { //fmt.Println("self.R
oot", s
identifier_name
tree.go
// two static route, content longer is first. func (self TSubNodes) Less(i, j int) bool { if self[i].Type == StaticNode { if self[j].Type == StaticNode { return len(self[i].Text) > len(self[j].Text) } return true } if self[j].Type == StaticNode { return false } else { return self[i].Level > self[j].Level } return i < j } func NewRouteTree(config_fn ...ConfigOption) *TTree { lTree := &TTree{ Root: make(map[string]*TNode), DelimitChar:'/', } /* for _, m := range HttpMethods { lTree.Root[m] = &TNode{ Children: TSubNodes{}, } }*/ for _,cfg:=range config_fn{ cfg(lTree) } return lTree } // 解析Path为Node /* /:name1/:name2 /:name1-:name2 /(:name1)sss(:name2) /(*name) /(:name[0-9]+) /(type:name[a-z]+) Result: @ Nodes List @ is it dyn route */ func (r *TTree) parsePath(path string) (nodes []*TNode, isDyn bool) { if path == "" { panic("echo: path cannot be empty") } if r.DelimitChar=='/' && path[0] != '/' { path = "/" + path } var ( i, j int // i 游标 J 上次标记 bracket int level int // #Node的 排序等级 target *TNode // 记录等级的Node 一般为/ 开始的第一个动态 node *TNode ) // 默认 nodes = make([]*TNode, 0) isDyn = false l := len(path) //j = i - 1 // 当i==0时J必须小于它 for ; i < l; i++ { switch path[i] { case r.DelimitChar: //case '/': { // 创建Text:'/' Node if bracket == 0 && i > j { //if path[j] == '/' { // nodes = append(nodes, &TNode{Type: StaticNode, Text: string(path[j])}) //} //j++ nodes = append(nodes, &TNode{Type: StaticNode, Text: path[j:i]}) j = i } //fmt.Println("/") // # 重置计数 target = nil level = 0 // #开始计数 } case '(': { //fmt.Println("(") bracket = 1 } case ':': { //fmt.Println(":") var typ ContentType = AllType //fmt.Println(":", bracket, path[j:i-bracket]) if path[i-1] == '(' { //#like (:var) nodes = append(nodes, &TNode{Type: StaticNode, Text: path[j : i-bracket]}) bracket = 1 } else { // #为变量区分数据类型 str := path[j : i-bracket] // #like /abc1(string|upper:var) idx := strings.Index(str, "(") if idx == -1 { panic(fmt.Sprintf("expect a '(' near position %d~%d", j, i)) } nodes = append(nodes, &TNode{Type: StaticNode, Text: str[:idx]}) str = str[idx+1:] switch str { case "int": typ = NumberType case "string": typ = CharType default: typ = AllType } //fmt.Println("type:", typ) bracket = 1 } j = i var ( regex string start = -1 ) if bracket == 1 { // 开始记录Pos for ; i < l && ')' != path[i]; i++ { // 移动Pos到) 遇到正则字符标记起 if start == -1 && utils.IsSpecialByte(path[i]) { // 如果是正则 start = i } } if path[i] != ')' { panic("lack of )") } if start > -1 { regex = path[start:i] //正则内容 } } else { i = i + 1 for ; i < l && utils.IsAlnumByte(path[i]); i++ { } } if len(regex) > 0 { // 正则 node = &TNode{Type: RegexpNode, regexp: regexp.MustCompile("(" + regex + ")"), Text: path[j : i-len(regex)]} nodes = append(nodes, node) } else { // 变量 node = &TNode{Type: VariantNode, ContentType: typ, Text: path[j:i]} nodes = append(nodes, node) } isDyn = true // #标记 Route 为动态 i = i + bracket // #剔除")"字符 bracket=len(“)”) j = i // 当计数器遇到/或者Url末尾时将记录保存于Node中 if target != nil && ((i == l) || (i != l && path[j+1] == r.DelimitChar)) { level++ target.Level = level //fmt.Println("ok:", node.Text, target.Text, level) // # 重置计数 target = nil level = 0 } if i == l { return //nodes, isDyn } // #计数滴答 // 放置在 i == l 后 确保表达式2比1多一个层级 // @/(int:id1)-(:unique2) // @/(:id3)-(:unique3)/(:filename) if (i != l && path[j] != r.DelimitChar) || level != 0 { if level == 0 { target = node } level++ //fmt.Println("leve:", node.Text, target.Text, level) } } case '*': { nodes = append(nodes, &TNode{Type: StaticNode, Text: path[j : i-bracket]}) j = i //if bracket == 1 { // for ; i < l && ')' == path[i]; i++ { // } //} else { i = i + 1 for ; i < l && utils.IsAlnumByte(path[i]); i++ { } //} nodes = append(nodes, &TNode{Type: AnyNode, Text: path[j:i]}) isDyn = true // 标记 Route 为动态 i = i + bracket // bracket=len(“)”) j = i if i == l { return //nodes, isDyn } } default: { bracket = 0 } } } nodes = append(nodes, &TNode{ Type: StaticNode, Text: path[j:i], }) //fmt.Println("lNodes", len(lNodes)) return //nodes, isDyn } func (r *TTree) matchNode(aNode *TNode, aUrl string, aParams *Params) *TNode { var retnil bool if aNode.Type == StaticNode { // 静态节点 if strings.HasPrefix(aUrl, aNode.Text) { //fmt.Println("J态", aUrl, " | ", aNode.Text[1:]) if len(aUrl) == len(aNode.Text) { return aNode } for _, c := range aNode.Children { e := r.matchNode(c, aUrl[len(aNode.Text):], aParams) if e != nil { return e } } } } else if aNode.Type == AnyNode { // 全匹配节点 //if len(aNode.Children) == 0 { // *aParams = append(*aParams, param{aNode.Text[1:], aUrl}) // return aNode //} //fmt.Println("Any态", aUrl, " | ", aNode.Text[1:]) for _, c := range aNode.Children { idx := strings.LastIndex(aUrl, c.Text) //fmt.Println("LastIndex", aUrl, c.Text) if idx > -1 { h := r.matchNode(c, aUrl[idx:], aParams) if h != nil { *aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]}) return h } } } *aParams = append(*aParams, param{aNode.Text[1
// static route will be put the first, so it will be match first.
random_line_split
tree.go
self[i], self[j] = self[j], self[i] } // static route will be put the first, so it will be match first. // two static route, content longer is first. func (self TSubNodes) Less(i, j int) bool { if self[i].Type == StaticNode { if self[j].Type == StaticNode { return len(self[i].Text) > len(self[j].Text) } return true } if self[j].Type == StaticNode { return false } else { return self[i].Level > self[j].Level } return i < j } func NewRouteTree(config_fn ...ConfigOption) *TTree { lTree := &TTree{ Root: make(map[string]*TNode), DelimitChar:'/', } /* for _, m := range HttpMethods { lTree.Root[m] = &TNode{ Children: TSubNodes{}, } }*/ for _,cfg:=range config_fn{ cfg(lTree) } return lTree } // 解析Path为Node /* /:name1/:name2 /:name1-:name2 /(:name1)sss(:name2) /(*name) /(:name[0-9]+) /(type:name[a-z]+) Result: @ Nodes List @ is it dyn route */ func (r *TTree) parsePath(path string) (nodes []*TNode, isDyn bool) { if path == "" { panic("echo: path cannot be empty") } if r.DelimitChar=='/' && path[0] != '/' { path = "/" + path } var ( i, j int // i 游标 J 上次标记 bracket int level int // #Node的 排序等级 target *TNode // 记录等级的Node 一般为/ 开始的第一个动态 node *TNode ) // 默认 nodes = make([]*TNode, 0) isDyn = false l := len(path) //j = i - 1 // 当i==0时J必须小于它 for ; i < l; i++ { switch path[i] { case r.DelimitChar: //case '/': { // 创建Text:'/' Node if bracket == 0 && i > j { //if path[j] == '/' { // nodes = append(nodes, &TNode{Type: StaticNode, Text: string(path[j])}) //} //j++ nodes = append(nodes, &TNode{Type: StaticNode, Text: path[j:i]}) j = i } //fmt.Println("/") // # 重置计数 target = nil level = 0 // #开始计数 } case '(': { //fmt.Println("(") bracket = 1 } case ':': { //fmt.Println(":") var typ ContentType = AllType //fmt.Println(":", bracket, path[j:i-bracket]) if path[i-1] == '(' { //#like (:var) nodes = append(nodes, &TNode{Type: StaticNode, Text: path[j : i-bracket]}) bracket = 1 } else { // #为变量区分数据类型 str := path[j : i-bracket] // #like /abc1(string|upper:var) idx := strings.Index(str, "(") if idx == -1 { panic(fmt.Sprintf("expect a '(' near position %d~%d", j, i)) } nodes = append(nodes, &TNode{Type: StaticNode, Text: str[:idx]}) str = str[idx+1:] switch str { case "int": typ = NumberType case "string": typ = CharType default: typ = AllType } //fmt.Println("type:", typ) bracket = 1 } j = i var ( regex string start = -1 ) if bracket == 1 { // 开始记录Pos for ; i < l && ')' != path[i]; i++ { // 移动Pos到) 遇到正则字符标记起 if start == -1 && utils.IsSpecialByte(path[i]) { // 如果是正则 start = i } } if path[i] != ')' { panic("lack of )") } if start > -1 { regex = path[start:i] //正则内容 } } else { i = i + 1 for ; i < l && utils.IsAlnumByte(path[i]); i++ { } } if len(regex) > 0 { // 正则 node = &TNode{Type: RegexpNode, regexp: regexp.MustCompile("(" + regex + ")"), Text: path[j : i-len(regex)]} nodes = append(nodes, node) } else { // 变量 node = &TNode{Type: VariantNode, ContentType: typ, Text: path[j:i]} nodes = append(nodes, node) } isDyn = true // #标记 Route 为动态 i = i + bracket // #剔除")"字符 bracket=len(“)”) j = i // 当计数器遇到/或者Url末尾时将记录保存于Node中 if target != nil && ((i == l) || (i != l && path[j+1] == r.DelimitChar)) { level++ target.Level = level //fmt.Println("ok:", node.Text, target.Text, level) // # 重置计数 target = nil level = 0 } if i == l { return //nodes, isDyn } // #计数滴答 // 放置在 i == l 后 确保表达式2比1多一个层级 // @/(int:id1)-(:unique2) // @/(:id3)-(:unique3)/(:filename) if (i != l && path[j] != r.DelimitChar) || level != 0 { if level == 0 { target = node } level++ //fmt.Println("leve:", node.Text, target.Text, level) } } case '*': { nodes = append(nodes, &TNode{Type: StaticNode, Text: path[j : i-bracket]}) j = i //if bracket == 1 { // for ; i < l && ')' == path[i]; i++ { // } //} else { i = i + 1 for ; i < l && utils.IsAlnumByte(path[i]); i++ { } //} nodes = append(nodes, &TNode{Type: AnyNode, Text: path[j:i]}) isDyn = true // 标记 Route 为动态 i = i + bracket // bracket=len(“)”) j = i if i == l { return //nodes, isDyn } } default: { bracket = 0 } } } nodes = append(nodes, &TNode{ Type: StaticNode, Text: path[j:i], }) //fmt.Println("lNodes", len(lNodes)) return //nodes, isDyn } func (r *TTree) matchNode(aNode *TNode, aUrl string, aParams *Params) *TNode { var retnil bool if aNode.Type == StaticNode { // 静态节点 if strings.HasPrefix(aUrl, aNode.Text) { //fmt.Println("J态", aUrl, " | ", aNode.Text[1:]) if len(aUrl) == len(aNode.Text) { return aNode } for _, c := range aNode.Children { e := r.matchNode(c, aUrl[len(aNode.Text):], aParams) if e != nil { return e } } } } else if aNode.Type == AnyNode { // 全匹配节点 //if len(aNode.Children) == 0 { // *aParams = append(*aParams, param{aNode.Text[1:], aUrl}) // return aNode //} //fmt.Println("Any态", aUrl, " | ", aNode.Text[1:]) for _, c := range aNode.Children { idx := strings.LastIndex(aUrl, c.Text) //fmt.Println("LastIndex", aUrl, c.Text) if idx > -1 { h := r.matchNode(c, aUrl[idx:], aParams) if h != nil { *aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]}) return h }
wap(i, j int) {
identifier_body
tree.go
(aUrl[:idx]) > 1 && strings.IndexByte(aUrl[:idx], r.DelimitChar) > -1 { retnil = true continue } //fmt.Println("类型2", aUrl[:idx], aNode.ContentType) if !validType(aUrl[:idx], aNode.ContentType) { //fmt.Println("错误类型", aUrl[:idx], aNode.ContentType) return nil //continue } h := r.matchNode(c, aUrl[idx:], aParams) if h != nil { *aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]}) return h } retnil = true } } if retnil { return nil } //fmt.Printf("动态", aUrl, aNode.Text[1:]) *aParams = append(*aParams, param{aNode.Text[1:], aUrl}) return aNode } else if aNode.Type == RegexpNode { // 正则节点 //if len(aNode.Children) == 0 && aNode.regexp.MatchString(aUrl) { // *aParams = append(*aParams, param{aNode.Text[1:], aUrl}) // return aNode //} idx := strings.IndexByte(aUrl, r.DelimitChar) if idx > -1 { if aNode.regexp.MatchString(aUrl[:idx]) { for _, c := range aNode.Children { h := r.matchNode(c, aUrl[idx:], aParams) if h != nil { *aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]}) return h } } } return nil } for _, c := range aNode.Children { idx := strings.Index(aUrl, c.Text) if idx > -1 && aNode.regexp.MatchString(aUrl[:idx]) { h := r.matchNode(c, aUrl[idx:], aParams) if h != nil { *aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]}) return h } } } if aNode.regexp.MatchString(aUrl) { *aParams = append(*aParams, param{aNode.Text[1:], aUrl}) return aNode } } return nil } func (r *TTree) Match(method string, url string) (*TRoute, Params) { lRoot := r.Root[method] var lParams = make(Params, 0, strings.Count(url, string(r.DelimitChar))) for _, n := range lRoot.Children { e := r.matchNode(n, url, &lParams) if e != nil { return e.Route, lParams } } return nil, nil } func validType(content string, typ ContentType) bool { switch typ { case NumberType: for i := 0; i < len(content); i++ { if !utils.IsDigitByte(content[i]) { return false } } case CharType: for i := 0; i < len(content); i++ { if !utils.IsAlphaByte(content[i]) { return false } } default: } return true } // validate parsed nodes, all non-static route should have static route children. func validNodes(nodes []*TNode) bool { if len(nodes) == 0 { return false } var lastTp = nodes[0] for _, node := range nodes[1:] { if lastTp.Type != StaticNode && node.Type != StaticNode { return false } lastTp = node } return true } // 添加路由到Tree func (self *TTree) AddRoute(aMethod, path string, aRoute *TRoute) { // 解析并创建为Nodes的List形式 lNodes, lIsDyn := self.parsePath(path) // 标记为动态路由 aRoute.isDynRoute = lIsDyn // 即将Hook的新Route是动态地址 // 绑定Route到最后一个Node lNode := lNodes[len(lNodes)-1] aRoute.Action = lNode.Text // 赋值Action lNode.Route = aRoute lNode.Path = path // 验证合法性 if !validNodes(lNodes) { logger.Panic("express %s is not supported", path) } // 插入该节点到Tree self.addnodes(aMethod, lNodes, false) } // conbine 2 node together func (self *TTree) conbine(aDes, aSrc *TNode) { var lNode *TNode // 是否目标Node有该Node for _, node := range aDes.Children { if node.Equal(aSrc) { lNode = node } } // 如果:无该Node直接添加完成所有工作 // 或者:遍历添加所有没有的新Node if lNode == nil { aDes.Children = append(aDes.Children, aSrc) return } else { if lNode.Type == RegexpNode { } if aSrc.Route != nil { if lNode.Route == nil { lNode.Route = aSrc.Route } else { // 叠加合并Controller lNode.Route.CombineController(aSrc.Route) } } // 合并子节点 for _, _node := range aSrc.Children { self.conbine(lNode, _node) } } } // conbine 2 tree together func (self *TTree) Conbine(aTree *TTree) *TTree { for method, snode := range aTree.Root { // 如果主树没有该方法叉则直接移植 if _, has := self.Root[method]; !has { self.Root[method] = snode } else { // 采用逐个添加 for _, node := range self.Root[method].Children { self.conbine(node, snode) } } } return self } // add node nodes[i] to parent node p func (self *TNode) addnode(aParent *TNode, aNodes []*TNode, i int, aIsHook bool) *TNode { if len(aParent.Children) == 0 { aParent.Children = make([]*TNode, 0) } // 如果:找到[已经注册]的分支节点则从该节继续[查找/添加]下一个节点 for _, n := range aParent.Children { if n.Equal(aNodes[i]) { // 如果:插入的节点层级已经到末尾,则为该节点注册路由 if i == len(aNodes)-1 { // 原始路由会被替换 if aIsHook { n.Route.CombineController(aNodes[i].Route) } else { n.Route = aNodes[i].Route } } return n } } // 如果:该节点没有对应分支则插入同级的aNodes为新的分支 aParent.Children = append(aParent.Children, aNodes[i]) sort.Sort(aParent.Children) return aNodes[i] } // add nodes to trees func (self *TTree) addnodes(aMethod string, aNodes []*TNode, aIsHook bool) { //fmt.Println("self.Root", self.Root) // 获得对应方法[POST,GET...] cn := self.Root[aMethod] if cn == nil { // 初始化Root node cn = &TNode{ Children: TSubNodes{}, } self.Root[aMethod] = cn } var p *TNode = cn // 复制方法对应的Root // 层级插入Nodes的Node到Root for idx, _ := range aNodes { p = cn.addnode(p, aNodes, idx, aIsHook) } } func printNode(i int, node *TNode) { for _, c := range node.Children { for j := 0; j < i; j++ { // 空格距离ss fmt.Print(" ") } if i > 1 { fmt.Print("┗", " ") } fmt.Printf(`%s<lv:%d,%v>`, c.Text, c.Level, c.ContentType) if c.Route != nil { fmt.Print("<*>") } //if !reflect.DeepEqual(c.Route, TRoute{}) { if c.Route != nil { //fmt.Print(" ", c.Route.HandleType.String()) //fmt.Printf(" %p", c.handle.method.Interface()) } fmt.Println() printNode(i+1, c) } } func (self *TTree) PrintTrees() { for method, node := range self.Root { if len(node.Children) > 0 { fmt.Println(method) printNode(1, node) fmt.Println() } } } func (self *TNode) Equal(o *TNode) bool { if self.Type != o.Type || self.Text != o.Text { return false } return true }
conditional_block
builder.py
scan = _op(ops.scan) zip = _op(ops.zip) allpairs = _op(ops.allpairs) flatten = _op(ops.flatten) print = _op(ops.print) concat = _op(ops.concat) length = _op(ops.length) contains = _op(ops.contains) list_append = _op(ops.list_append) list_pop = _op(ops.list_pop) set_add = _op(ops.set_add) set_remove = _op(ops.set_remove) dict_add = _op(ops.dict_add) dict_remove = _op(ops.dict_remove) dict_keys = _op(ops.dict_keys) dict_values = _op(ops.dict_values) dict_items = _op(ops.dict_items) box = _op(ops.box) unbox = _op(ops.unbox) convert = _op(ops.convert) new_list = _op(ops.new_list) new_tuple = _op(ops.new_tuple) new_dict = _op(ops.new_dict) new_set = _op(ops.new_set) new_struct = _op(ops.new_struct) new_data = _op(ops.new_data) new_exc = _op(ops.new_exc) phi = _op(ops.phi) exc_setup = _op(ops.exc_setup) exc_catch = _op(ops.exc_catch) jump = _op(ops.jump) cbranch = _op(ops.cbranch) exc_throw = _op(ops.exc_throw) ret = _op(ops.ret) function = _op(ops.function) call = _op(ops.call) call_math = _op(ops.call_math) ptradd = _op(ops.ptradd) ptrload = _op(ops.ptrload) ptrstore = _op(ops.ptrstore) ptrcast = _op(ops.ptrcast) ptr_isnull = _op(ops.ptr_isnull) getfield = _op(ops.getfield) setfield = _op(ops.setfield) getindex = _op(ops.getindex) setindex = _op(ops.setindex) getslice = _op(ops.getslice) setslice = _op(ops.setslice) slice = _op(ops.slice) add = _op(ops.add) sub = _op(ops.sub) mul = _op(ops.mul) div = _op(ops.div) mod = _op(ops.mod) lshift = _op(ops.lshift) rshift = _op(ops.rshift) bitand = _op(ops.bitand) bitor = _op(ops.bitor) bitxor = _op(ops.bitxor) invert = _op(ops.invert) not_ = _op(ops.not_) uadd = _op(ops.uadd) usub = _op(ops.usub) eq = _op(ops.eq) noteq = _op(ops.noteq) lt = _op(ops.lt) lte = _op(ops.lte) gt = _op(ops.gt) gte = _op(ops.gte) is_ = _op(ops.is_) threadpool_start = _op(ops.threadpool_start) threadpool_submit = _op(ops.threadpool_submit) threadpool_join = _op(ops.threadpool_join) threadpool_close = _op(ops.threadpool_close) thread_start = _op(ops.thread_start) thread_join = _op(ops.thread_join) check_overflow = _op(ops.check_overflow) check_error = _op(ops.check_error) addressof = _op(ops.addressof) exc_matches = _op(ops.exc_matches) store_tl_exc = _op(ops.store_tl_exc) load_tl_exc = _op(ops.load_tl_exc) gc_gotref = _op(ops.gc_gotref) gc_giveref = _op(ops.gc_giveref) gc_incref = _op(ops.gc_incref) gc_decref = _op(ops.gc_decref) gc_alloc = _op(ops.gc_alloc) gc_dealloc = _op(ops.gc_dealloc) def convert(self, type, args, result=None, buildop=convert): if type == args[0].type: return args[0] return buildop(self, type, args, result) class Builder(OpBuilder): """ I build Operations and emit them into the function. Also provides convenience operations, such as loops, guards, etc. """ def __init__(self, func): self.func = func self.module = func.module self._curblock = None self._lastop = None def emit(self, op): """ Emit an Operation at the current position. Sets result register if not set already. """ assert self._curblock, "Builder is not positioned!" if op.result is None: op.result = self.func.temp() if self._lastop == 'head' and self._curblock.ops.head: op.insert_before(self._curblock.ops.head) elif self._lastop in ('head', 'tail'): self._curblock.append(op) else: op.insert_after(self._lastop) self._lastop = op def _insert_op(self, op): if self._curblock: self.emit(op) # __________________________________________________________________ # Positioning @property def basic_block(self): return self._curblock def position_at_beginning(self, block): """Position the builder at the beginning of the given block.""" self._curblock = block self._lastop = 'head' def position_at_end(self, block): """Position the builder at the end of the given block.""" self._curblock = block self._lastop = block.tail or 'tail' def position_before(self, op): """Position the builder before the given op.""" if isinstance(op, FuncArg): raise error.PositioningError( "Cannot place builder before function argument") self._curblock = op.block self._lastop = op._prev def position_after(self, op): """Position the builder after the given op.""" if isinstance(op, FuncArg): self.position_at_beginning(op.parent.startblock) else: self._curblock = op.block self._lastop = op @contextmanager def _position(self, block, position): curblock, lastop = self._curblock, self._lastop position(block) yield self._curblock, self._lastop = curblock, lastop at_front = lambda self, b: self._position(b, self.position_at_beginning) at_end = lambda self, b: self._position(b, self.position_at_end) # __________________________________________________________________ # Convenience def gen_call_external(self, fname, args, result=None): """Generate call to external function (which must be declared""" gv = self.module.get_global(fname) assert gv is not None, "Global %s not declared" % fname assert gv.type.is_function, gv assert gv.type.argtypes == [arg.type for arg in args] op = self.call(gv.type.res, [Const(fname), args]) op.result = result or op.result return op def _find_handler(self, exc, exc_setup): """ Given an exception and an exception setup clause, generate exc_matches() checks """ catch_sites = [findop(block, 'exc_catch') for block in exc_setup.args] for exc_catch in catch_sites: for exc_type in exc_catch.args: with self.if_(self.exc_matches(types.Bool, [exc, exc_type])): self.jump(exc_catch.block) block = self._curblock self.position_at_end(block) def gen_error_propagation(self, exc=None): """ Propagate an exception. If `exc` is not given it will be loaded to match in 'except' clauses. """ assert self._curblock block = self._curblock exc_setup = findop(block.leaders, 'exc_setup') if exc_setup: exc = exc or self.load_tl_exc(types.Exception) self._find_handler(exc, exc_setup) else: self.gen_ret_undef() def gen_ret_undef(self): """Generate a return with undefined value""" type = self.func.type.restype if type.is_void: self.ret(None) else: self.ret(Undef(type)) def splitblock(self, name=None, terminate=False):
"""Split the current block, returning (old_block, new_block)""" # ------------------------------------------------- # Sanity check
random_line_split
builder.py
self._insert_op(result) return result def _process_void(self, *args, **kwds): result = kwds.pop('result', None) op = _process(self, types.Void, list(args), result) if kwds: op.add_metadata(kwds) return op if ops.is_void(op): build_op = _process_void else: build_op = _process if config.op_verify: build_op = op_verifier(build_op) return build_op def _insert_op(self, op): """Implement in subclass that emits Operations""" _const = lambda val: Const(val, types.Void) # __________________________________________________________________ # IR constructors # Generated by pykit.utils._generate Sin = _const(ops.Sin) Asin = _const(ops.Asin) Sinh = _const(ops.Sinh) Asinh = _const(ops.Asinh) Cos = _const(ops.Cos) Acos = _const(ops.Acos) Cosh = _const(ops.Cosh) Acosh = _const(ops.Acosh) Tan = _const(ops.Tan) Atan = _const(ops.Atan) Atan2 = _const(ops.Atan2) Tanh = _const(ops.Tanh) Atanh = _const(ops.Atanh) Log = _const(ops.Log) Log2 = _const(ops.Log2) Log10 = _const(ops.Log10) Log1p = _const(ops.Log1p) Exp = _const(ops.Exp) Exp2 = _const(ops.Exp2) Expm1 = _const(ops.Expm1) Floor = _const(ops.Floor) Ceil = _const(ops.Ceil) Abs = _const(ops.Abs) Erfc = _const(ops.Erfc) Rint = _const(ops.Rint) Pow = _const(ops.Pow) Round = _const(ops.Round) alloca = _op(ops.alloca) load = _op(ops.load) store = _op(ops.store) map = _op(ops.map) reduce = _op(ops.reduce) filter = _op(ops.filter) scan = _op(ops.scan) zip = _op(ops.zip) allpairs = _op(ops.allpairs) flatten = _op(ops.flatten) print = _op(ops.print) concat = _op(ops.concat) length = _op(ops.length) contains = _op(ops.contains) list_append = _op(ops.list_append) list_pop = _op(ops.list_pop) set_add = _op(ops.set_add) set_remove = _op(ops.set_remove) dict_add = _op(ops.dict_add) dict_remove = _op(ops.dict_remove) dict_keys = _op(ops.dict_keys) dict_values = _op(ops.dict_values) dict_items = _op(ops.dict_items) box = _op(ops.box) unbox = _op(ops.unbox) convert = _op(ops.convert) new_list = _op(ops.new_list) new_tuple = _op(ops.new_tuple) new_dict = _op(ops.new_dict) new_set = _op(ops.new_set) new_struct = _op(ops.new_struct) new_data = _op(ops.new_data) new_exc = _op(ops.new_exc) phi = _op(ops.phi) exc_setup = _op(ops.exc_setup) exc_catch = _op(ops.exc_catch) jump = _op(ops.jump) cbranch = _op(ops.cbranch) exc_throw = _op(ops.exc_throw) ret = _op(ops.ret) function = _op(ops.function) call = _op(ops.call) call_math = _op(ops.call_math) ptradd = _op(ops.ptradd) ptrload = _op(ops.ptrload) ptrstore = _op(ops.ptrstore) ptrcast = _op(ops.ptrcast) ptr_isnull = _op(ops.ptr_isnull) getfield = _op(ops.getfield) setfield = _op(ops.setfield) getindex = _op(ops.getindex) setindex = _op(ops.setindex) getslice = _op(ops.getslice) setslice = _op(ops.setslice) slice = _op(ops.slice) add = _op(ops.add) sub = _op(ops.sub) mul = _op(ops.mul) div = _op(ops.div) mod = _op(ops.mod) lshift = _op(ops.lshift) rshift = _op(ops.rshift) bitand = _op(ops.bitand) bitor = _op(ops.bitor) bitxor = _op(ops.bitxor) invert = _op(ops.invert) not_ = _op(ops.not_) uadd = _op(ops.uadd) usub = _op(ops.usub) eq = _op(ops.eq) noteq = _op(ops.noteq) lt = _op(ops.lt) lte = _op(ops.lte) gt = _op(ops.gt) gte = _op(ops.gte) is_ = _op(ops.is_) threadpool_start = _op(ops.threadpool_start) threadpool_submit = _op(ops.threadpool_submit) threadpool_join = _op(ops.threadpool_join) threadpool_close = _op(ops.threadpool_close) thread_start = _op(ops.thread_start) thread_join = _op(ops.thread_join) check_overflow = _op(ops.check_overflow) check_error = _op(ops.check_error) addressof = _op(ops.addressof) exc_matches = _op(ops.exc_matches) store_tl_exc = _op(ops.store_tl_exc) load_tl_exc = _op(ops.load_tl_exc) gc_gotref = _op(ops.gc_gotref) gc_giveref = _op(ops.gc_giveref) gc_incref = _op(ops.gc_incref) gc_decref = _op(ops.gc_decref) gc_alloc = _op(ops.gc_alloc) gc_dealloc = _op(ops.gc_dealloc) def convert(self, type, args, result=None, buildop=convert): if type == args[0].type: return args[0] return buildop(self, type, args, result) class Builder(OpBuilder): """ I build Operations and emit them into the function. Also provides convenience operations, such as loops, guards, etc. """ def __init__(self, func): self.func = func self.module = func.module self._curblock = None self._lastop = None def emit(self, op): """ Emit an Operation at the current position. Sets result register if not set already. """ assert self._curblock, "Builder is not positioned!" if op.result is None: op.result = self.func.temp() if self._lastop == 'head' and self._curblock.ops.head: op.insert_before(self._curblock.ops.head) elif self._lastop in ('head', 'tail'): self._curblock.append(op) else: op.insert_after(self._lastop) self._lastop = op def _insert_op(self, op): if self._curblock: self.emit(op) # __________________________________________________________________ # Positioning @property def basic_block(self): return self._curblock def position_at_beginning(self, block): """Position the builder at the beginning of the given block.""" self._curblock = block self._lastop = 'head' def position_at_end(self, block): """Position the builder at the end of the given block.""" self._curblock = block self._lastop = block.tail or 'tail' def position_before(self, op): """Position the builder before the given op.""" if isinstance(op, FuncArg): raise error.PositioningError( "Cannot place builder before function argument") self._curblock = op.block self._lastop = op._prev def position_after(self, op): """Position the builder after the given op.""" if isinstance
result.add_metadata(metadata)
conditional_block
builder.py
Acosh = _const(ops.Acosh) Tan = _const(ops.Tan) Atan = _const(ops.Atan) Atan2 = _const(ops.Atan2) Tanh = _const(ops.Tanh) Atanh = _const(ops.Atanh) Log = _const(ops.Log) Log2 = _const(ops.Log2) Log10 = _const(ops.Log10) Log1p = _const(ops.Log1p) Exp = _const(ops.Exp) Exp2 = _const(ops.Exp2) Expm1 = _const(ops.Expm1) Floor = _const(ops.Floor) Ceil = _const(ops.Ceil) Abs = _const(ops.Abs) Erfc = _const(ops.Erfc) Rint = _const(ops.Rint) Pow = _const(ops.Pow) Round = _const(ops.Round) alloca = _op(ops.alloca) load = _op(ops.load) store = _op(ops.store) map = _op(ops.map) reduce = _op(ops.reduce) filter = _op(ops.filter) scan = _op(ops.scan) zip = _op(ops.zip) allpairs = _op(ops.allpairs) flatten = _op(ops.flatten) print = _op(ops.print) concat = _op(ops.concat) length = _op(ops.length) contains = _op(ops.contains) list_append = _op(ops.list_append) list_pop = _op(ops.list_pop) set_add = _op(ops.set_add) set_remove = _op(ops.set_remove) dict_add = _op(ops.dict_add) dict_remove = _op(ops.dict_remove) dict_keys = _op(ops.dict_keys) dict_values = _op(ops.dict_values) dict_items = _op(ops.dict_items) box = _op(ops.box) unbox = _op(ops.unbox) convert = _op(ops.convert) new_list = _op(ops.new_list) new_tuple = _op(ops.new_tuple) new_dict = _op(ops.new_dict) new_set = _op(ops.new_set) new_struct = _op(ops.new_struct) new_data = _op(ops.new_data) new_exc = _op(ops.new_exc) phi = _op(ops.phi) exc_setup = _op(ops.exc_setup) exc_catch = _op(ops.exc_catch) jump = _op(ops.jump) cbranch = _op(ops.cbranch) exc_throw = _op(ops.exc_throw) ret = _op(ops.ret) function = _op(ops.function) call = _op(ops.call) call_math = _op(ops.call_math) ptradd = _op(ops.ptradd) ptrload = _op(ops.ptrload) ptrstore = _op(ops.ptrstore) ptrcast = _op(ops.ptrcast) ptr_isnull = _op(ops.ptr_isnull) getfield = _op(ops.getfield) setfield = _op(ops.setfield) getindex = _op(ops.getindex) setindex = _op(ops.setindex) getslice = _op(ops.getslice) setslice = _op(ops.setslice) slice = _op(ops.slice) add = _op(ops.add) sub = _op(ops.sub) mul = _op(ops.mul) div = _op(ops.div) mod = _op(ops.mod) lshift = _op(ops.lshift) rshift = _op(ops.rshift) bitand = _op(ops.bitand) bitor = _op(ops.bitor) bitxor = _op(ops.bitxor) invert = _op(ops.invert) not_ = _op(ops.not_) uadd = _op(ops.uadd) usub = _op(ops.usub) eq = _op(ops.eq) noteq = _op(ops.noteq) lt = _op(ops.lt) lte = _op(ops.lte) gt = _op(ops.gt) gte = _op(ops.gte) is_ = _op(ops.is_) threadpool_start = _op(ops.threadpool_start) threadpool_submit = _op(ops.threadpool_submit) threadpool_join = _op(ops.threadpool_join) threadpool_close = _op(ops.threadpool_close) thread_start = _op(ops.thread_start) thread_join = _op(ops.thread_join) check_overflow = _op(ops.check_overflow) check_error = _op(ops.check_error) addressof = _op(ops.addressof) exc_matches = _op(ops.exc_matches) store_tl_exc = _op(ops.store_tl_exc) load_tl_exc = _op(ops.load_tl_exc) gc_gotref = _op(ops.gc_gotref) gc_giveref = _op(ops.gc_giveref) gc_incref = _op(ops.gc_incref) gc_decref = _op(ops.gc_decref) gc_alloc = _op(ops.gc_alloc) gc_dealloc = _op(ops.gc_dealloc) def convert(self, type, args, result=None, buildop=convert):
class Builder(OpBuilder): """ I build Operations and emit them into the function. Also provides convenience operations, such as loops, guards, etc. """ def __init__(self, func): self.func = func self.module = func.module self._curblock = None self._lastop = None def emit(self, op): """ Emit an Operation at the current position. Sets result register if not set already. """ assert self._curblock, "Builder is not positioned!" if op.result is None: op.result = self.func.temp() if self._lastop == 'head' and self._curblock.ops.head: op.insert_before(self._curblock.ops.head) elif self._lastop in ('head', 'tail'): self._curblock.append(op) else: op.insert_after(self._lastop) self._lastop = op def _insert_op(self, op): if self._curblock: self.emit(op) # __________________________________________________________________ # Positioning @property def basic_block(self): return self._curblock def position_at_beginning(self, block): """Position the builder at the beginning of the given block.""" self._curblock = block self._lastop = 'head' def position_at_end(self, block): """Position the builder at the end of the given block.""" self._curblock = block self._lastop = block.tail or 'tail' def position_before(self, op): """Position the builder before the given op.""" if isinstance(op, FuncArg): raise error.PositioningError( "Cannot place builder before function argument") self._curblock = op.block self._lastop = op._prev def position_after(self, op): """Position the builder after the given op.""" if isinstance(op, FuncArg): self.position_at_beginning(op.parent.startblock) else: self._curblock = op.block self._lastop = op @contextmanager def _position(self, block, position): curblock, lastop = self._curblock, self._lastop position(block) yield self._curblock, self._lastop = curblock, lastop at_front = lambda self, b: self._position(b, self.position_at_beginning) at_end = lambda self, b: self._position(b, self.position_at_end) # __________________________________________________________________ # Convenience def gen_call_external(self, fname, args, result=None): """Generate call to external function (which must be declared""" gv = self.module.get_global(fname) assert gv is not None, "Global %s not declared" % fname assert gv.type.is_function, gv assert gv.type.argtypes == [arg.type for arg in args] op = self.call(gv.type.res, [Const(fname), args]) op.result = result or op.result return op def _find_handler
if type == args[0].type: return args[0] return buildop(self, type, args, result)
identifier_body
builder.py
Acosh = _const(ops.Acosh) Tan = _const(ops.Tan) Atan = _const(ops.Atan) Atan2 = _const(ops.Atan2) Tanh = _const(ops.Tanh) Atanh = _const(ops.Atanh) Log = _const(ops.Log) Log2 = _const(ops.Log2) Log10 = _const(ops.Log10) Log1p = _const(ops.Log1p) Exp = _const(ops.Exp) Exp2 = _const(ops.Exp2) Expm1 = _const(ops.Expm1) Floor = _const(ops.Floor) Ceil = _const(ops.Ceil) Abs = _const(ops.Abs) Erfc = _const(ops.Erfc) Rint = _const(ops.Rint) Pow = _const(ops.Pow) Round = _const(ops.Round) alloca = _op(ops.alloca) load = _op(ops.load) store = _op(ops.store) map = _op(ops.map) reduce = _op(ops.reduce) filter = _op(ops.filter) scan = _op(ops.scan) zip = _op(ops.zip) allpairs = _op(ops.allpairs) flatten = _op(ops.flatten) print = _op(ops.print) concat = _op(ops.concat) length = _op(ops.length) contains = _op(ops.contains) list_append = _op(ops.list_append) list_pop = _op(ops.list_pop) set_add = _op(ops.set_add) set_remove = _op(ops.set_remove) dict_add = _op(ops.dict_add) dict_remove = _op(ops.dict_remove) dict_keys = _op(ops.dict_keys) dict_values = _op(ops.dict_values) dict_items = _op(ops.dict_items) box = _op(ops.box) unbox = _op(ops.unbox) convert = _op(ops.convert) new_list = _op(ops.new_list) new_tuple = _op(ops.new_tuple) new_dict = _op(ops.new_dict) new_set = _op(ops.new_set) new_struct = _op(ops.new_struct) new_data = _op(ops.new_data) new_exc = _op(ops.new_exc) phi = _op(ops.phi) exc_setup = _op(ops.exc_setup) exc_catch = _op(ops.exc_catch) jump = _op(ops.jump) cbranch = _op(ops.cbranch) exc_throw = _op(ops.exc_throw) ret = _op(ops.ret) function = _op(ops.function) call = _op(ops.call) call_math = _op(ops.call_math) ptradd = _op(ops.ptradd) ptrload = _op(ops.ptrload) ptrstore = _op(ops.ptrstore) ptrcast = _op(ops.ptrcast) ptr_isnull = _op(ops.ptr_isnull) getfield = _op(ops.getfield) setfield = _op(ops.setfield) getindex = _op(ops.getindex) setindex = _op(ops.setindex) getslice = _op(ops.getslice) setslice = _op(ops.setslice) slice = _op(ops.slice) add = _op(ops.add) sub = _op(ops.sub) mul = _op(ops.mul) div = _op(ops.div) mod = _op(ops.mod) lshift = _op(ops.lshift) rshift = _op(ops.rshift) bitand = _op(ops.bitand) bitor = _op(ops.bitor) bitxor = _op(ops.bitxor) invert = _op(ops.invert) not_ = _op(ops.not_) uadd = _op(ops.uadd) usub = _op(ops.usub) eq = _op(ops.eq) noteq = _op(ops.noteq) lt = _op(ops.lt) lte = _op(ops.lte) gt = _op(ops.gt) gte = _op(ops.gte) is_ = _op(ops.is_) threadpool_start = _op(ops.threadpool_start) threadpool_submit = _op(ops.threadpool_submit) threadpool_join = _op(ops.threadpool_join) threadpool_close = _op(ops.threadpool_close) thread_start = _op(ops.thread_start) thread_join = _op(ops.thread_join) check_overflow = _op(ops.check_overflow) check_error = _op(ops.check_error) addressof = _op(ops.addressof) exc_matches = _op(ops.exc_matches) store_tl_exc = _op(ops.store_tl_exc) load_tl_exc = _op(ops.load_tl_exc) gc_gotref = _op(ops.gc_gotref) gc_giveref = _op(ops.gc_giveref) gc_incref = _op(ops.gc_incref) gc_decref = _op(ops.gc_decref) gc_alloc = _op(ops.gc_alloc) gc_dealloc = _op(ops.gc_dealloc) def
(self, type, args, result=None, buildop=convert): if type == args[0].type: return args[0] return buildop(self, type, args, result) class Builder(OpBuilder): """ I build Operations and emit them into the function. Also provides convenience operations, such as loops, guards, etc. """ def __init__(self, func): self.func = func self.module = func.module self._curblock = None self._lastop = None def emit(self, op): """ Emit an Operation at the current position. Sets result register if not set already. """ assert self._curblock, "Builder is not positioned!" if op.result is None: op.result = self.func.temp() if self._lastop == 'head' and self._curblock.ops.head: op.insert_before(self._curblock.ops.head) elif self._lastop in ('head', 'tail'): self._curblock.append(op) else: op.insert_after(self._lastop) self._lastop = op def _insert_op(self, op): if self._curblock: self.emit(op) # __________________________________________________________________ # Positioning @property def basic_block(self): return self._curblock def position_at_beginning(self, block): """Position the builder at the beginning of the given block.""" self._curblock = block self._lastop = 'head' def position_at_end(self, block): """Position the builder at the end of the given block.""" self._curblock = block self._lastop = block.tail or 'tail' def position_before(self, op): """Position the builder before the given op.""" if isinstance(op, FuncArg): raise error.PositioningError( "Cannot place builder before function argument") self._curblock = op.block self._lastop = op._prev def position_after(self, op): """Position the builder after the given op.""" if isinstance(op, FuncArg): self.position_at_beginning(op.parent.startblock) else: self._curblock = op.block self._lastop = op @contextmanager def _position(self, block, position): curblock, lastop = self._curblock, self._lastop position(block) yield self._curblock, self._lastop = curblock, lastop at_front = lambda self, b: self._position(b, self.position_at_beginning) at_end = lambda self, b: self._position(b, self.position_at_end) # __________________________________________________________________ # Convenience def gen_call_external(self, fname, args, result=None): """Generate call to external function (which must be declared""" gv = self.module.get_global(fname) assert gv is not None, "Global %s not declared" % fname assert gv.type.is_function, gv assert gv.type.argtypes == [arg.type for arg in args] op = self.call(gv.type.res, [Const(fname), args]) op.result = result or op.result return op def _find_handler
convert
identifier_name
gdbstub.rs
1..]; let mut out = String::new(); ctx.dbg.pause(); match ty { 'g' => { let hw = ctx.dbg.hw(); for reg in 0..15 { out += &format!("{:08X}", hw.read_reg(reg).swap_bytes()); } out += &format!("{:08X}", hw.pause_addr().swap_bytes()); for _ in 0..8 { out += "xxxxxxxxxxxxxxxxxxxxxxxx"; // fX registers (12 bytes each) } out += "xxxxxxxx"; // fps register out += &format!("{:08X}", hw.read_cpsr().swap_bytes()); } 'G' => { let mut hw = ctx.dbg.hw(); let mut regs = params; let next_reg = |regstr: &str| -> Result<u32> { let val = utils::from_hex(&regstr[..8])?; Ok(val.swap_bytes()) }; for reg in 0..15 { hw.write_reg(reg, next_reg(regs)?); regs = &regs[8..]; } // register at 15: PC hw.branch_to(next_reg(regs)?); regs = &regs[8..]; // Skip 8 fX registers regs = &regs[8 * 24..]; // Skip fps register regs = &regs[8..]; // register at 25: CPSR hw.write_cpsr(next_reg(regs)?); out += "OK"; } 'H' => { out += "OK"; } 'm' => { let mut hw = ctx.dbg.hw(); let mut params = params.split(','); let addr = parse_next_hex(&mut params)?; let size = parse_next_hex(&mut params)?; let mut buf = [0u8]; for b in 0..size { if let Err(_) = hw.read_mem(addr+b, &mut buf) { out += "00"; } else { out += &format!("{:02X}", buf[0]); } } } 'M' => { let mut hw = ctx.dbg.hw(); let mut params = params.split(|c| c == ',' || c == ':'); let addr = parse_next_hex(&mut params)?; let size = parse_next_hex(&mut params)?; let data = parse_next(&mut params)?; for b in 0..size { let data_byte_range = 2*(b as usize)..2*((b as usize)+1); let byte = utils::from_hex(&data[data_byte_range])? as u8; hw.write_mem(addr+b, &[byte]); } out += "OK"; } 'p' => { let hw = ctx.dbg.hw(); let reg = utils::from_hex(&params)? as usize; let regval = match reg { 0 ..= 14 => hw.read_reg(reg), 15 => hw.pause_addr(), 25 => hw.read_cpsr(), n => { warn!("GDB requested bad register value {}", n); 0 } }; out += &format!("{:08X}", regval.swap_bytes()); } 'q' => { return handle_gdb_cmd_q(params, ctx); } 's' => { return cmd_step(ctx); } 'c' => { return cmd_continue(ctx); } 'v' => { return handle_gdb_cmd_v(params, ctx); } 'z' | 'Z' => { let mut hw = ctx.dbg.hw(); let mut params = params.split(','); let brk_ty = parse_next(&mut params)?; let addr = parse_next_hex(&mut params)?; let _kind = parse_next(&mut params)?; assert!(brk_ty == "0"); if ty == 'Z' { hw.set_breakpoint(addr); } else { hw.del_breakpoint(addr); } out += "OK"; } '?' => { out += &ctx.last_halt.to_signal(); } x => { warn!("GDB client tried to run unsupported command {}", x); } } Ok(out) } #[derive(Clone, Copy)] struct Checksum(pub u32); impl Add<u8> for Checksum { type Output = Checksum; fn add(self, b: u8) -> Checksum { Checksum((self.0 + (b as u32)) % 256) } } impl AddAssign<u8> for Checksum { fn add_assign(&mut self, b: u8) { self.0 = (*self + b).0; } } enum PacketType { Command(String), CtrlC, AckOk, AckErr, EndOfPacket, Malformed, } fn load_packet<I: Iterator<Item = u8>>(it: &mut I) -> PacketType { let mut it = it.skip_while(|b| *b != 0x03 && *b != b'$' && *b != b'-' && *b != b'+'); match it.next() { Some(0x3) => return PacketType::CtrlC, Some(b'$') => {} Some(b'+') => return PacketType::AckOk, Some(b'-') => return PacketType::AckErr, None => return PacketType::EndOfPacket, _ => return PacketType::Malformed } let mut string = String::new(); let mut checksum = Checksum(0); for b in it.by_ref().take_while(|b| *b != b'#') { string.push(b as char); checksum += b; } if let (Some(top), Some(bot)) = (it.next(), it.next()) { let packet_checksum = str::from_utf8(&[top, bot]).ok() .and_then(|s| utils::from_hex(s).ok()); if Some(checksum.0) == packet_checksum { return PacketType::Command(string) } } return PacketType::Malformed } fn write_gdb_packet(data: &str, stream: &mut TcpStream) -> Result<()> { let checksum = data.bytes().fold(Checksum(0), |checksum, b| checksum + b); trace!("Replying with GDB packet: ${}#{:02X}", data, checksum.0); write!(stream, "${}#{:02X}", data, checksum.0)?; stream.flush()?; Ok(()) } fn handle_gdb_packet(data: &[u8], stream: &mut TcpStream, ctx: &mut GdbCtx) -> Result<()> { trace!("Recieving GDB packet: {}", str::from_utf8(data).unwrap()); let mut it = data.iter().cloned(); loop { match load_packet(&mut it) { PacketType::Command(cmd) => { stream.write(b"+")?; stream.flush()?; match handle_gdb_cmd(&cmd, ctx) { Ok(out) => write_gdb_packet(&out, stream)?, Err(e) => { if let ErrorKind::NoResponse = e {} else { return Err(e) } } } } PacketType::CtrlC => { ctx.dbg.pause(); trace!("Recieved GDB packet with CTRL-C signal!"); } PacketType::AckOk => {}, PacketType::AckErr => error!("GDB client replied with error packet!"), PacketType::EndOfPacket => { return Ok(()) } PacketType::Malformed => { trace!("Recieved malformed data {:?}", data); stream.write(b"-")?; stream.flush()?; return Ok(()) } } } } struct GdbCtx<'a, 'b: 'a> { dbg: &'a mut dbgcore::DbgContext<'b>, last_halt: &'a mut BreakData, } const TOKEN_LISTENER: mio::Token = mio::Token(1024); const TOKEN_CLIENT: mio::Token = mio::Token(1025); pub struct GdbStub { debugger: dbgcore::DbgCore, gdb_thread: Option<thread::JoinHandle<msgs::Client<Message>>> } impl GdbStub { pub fn new(msg_client: msgs::Client<Message>, debugger: dbgcore::DbgCore) -> GdbStub { let mut stub = GdbStub { debugger: debugger, gdb_thread: None }; stub.start(msg_client); stub } pub fn start(&mut self, msg_client: msgs::Client<Message>) { let mut debugger = self.debugger.clone(); self.gdb_thread = Some(thread::Builder::new().name("GDBStub".to_owned()).spawn(move || { use mio::Events; let poll = mio::Poll::new() .expect("Could not create mio polling instance!"); let listener = TcpListener::bind(&"127.0.0.1:4567".parse().unwrap()) .expect("Could not bind TcpListener to port!"); poll.register(&listener, TOKEN_LISTENER, mio::Ready::readable(), mio::PollOpt::edge()) .expect("Could not register TcpListener to mio!");
let mut connection = Connection { listener: &listener,
random_line_split
gdbstub.rs
= cmd.splitn(2, |c| c == ',' || c == ':' || c == ';'); let ty = parse_next(&mut s)?; let mut out = String::new(); match ty { "Cont" => { let params = parse_next(&mut s)?; let threads = params.split(';'); for thread in threads { let mut thread_data = thread.split(':'); let action = parse_next(&mut thread_data)?; let thread_name = thread_data.next(); if let Some(name) = thread_name { match (name, utils::from_hex(name)) { | ("-1", _) | (_, Ok(0)) | (_, Ok(1)) => {} | (s, _) => panic!("Attempted to issue command on invalid thread id {}", s) } } match action { "c" => return cmd_continue(ctx), "s" => return cmd_step(ctx), _ => warn!("GDB client tried to run unsupported `vCont` action {}", action) } } } "Cont?" => { let supported = ["c", "s"]; out += "vCont"; for ty in supported.iter() { out += ";"; out += ty; } } _ => warn!("GDB client tried to run unsupported `v` command {}", ty) } Ok(out) } fn handle_gdb_cmd(cmd: &str, ctx: &mut GdbCtx) -> Result<String> { let ty = parse_next(&mut cmd.chars())?; let params = &cmd[1..]; let mut out = String::new(); ctx.dbg.pause(); match ty { 'g' => { let hw = ctx.dbg.hw(); for reg in 0..15 { out += &format!("{:08X}", hw.read_reg(reg).swap_bytes()); } out += &format!("{:08X}", hw.pause_addr().swap_bytes()); for _ in 0..8 { out += "xxxxxxxxxxxxxxxxxxxxxxxx"; // fX registers (12 bytes each) } out += "xxxxxxxx"; // fps register out += &format!("{:08X}", hw.read_cpsr().swap_bytes()); } 'G' => { let mut hw = ctx.dbg.hw(); let mut regs = params; let next_reg = |regstr: &str| -> Result<u32> { let val = utils::from_hex(&regstr[..8])?; Ok(val.swap_bytes()) }; for reg in 0..15 { hw.write_reg(reg, next_reg(regs)?); regs = &regs[8..]; } // register at 15: PC hw.branch_to(next_reg(regs)?); regs = &regs[8..]; // Skip 8 fX registers regs = &regs[8 * 24..]; // Skip fps register regs = &regs[8..]; // register at 25: CPSR hw.write_cpsr(next_reg(regs)?); out += "OK"; } 'H' => { out += "OK"; } 'm' => { let mut hw = ctx.dbg.hw(); let mut params = params.split(','); let addr = parse_next_hex(&mut params)?; let size = parse_next_hex(&mut params)?; let mut buf = [0u8]; for b in 0..size { if let Err(_) = hw.read_mem(addr+b, &mut buf) { out += "00"; } else { out += &format!("{:02X}", buf[0]); } } } 'M' => { let mut hw = ctx.dbg.hw(); let mut params = params.split(|c| c == ',' || c == ':'); let addr = parse_next_hex(&mut params)?; let size = parse_next_hex(&mut params)?; let data = parse_next(&mut params)?; for b in 0..size { let data_byte_range = 2*(b as usize)..2*((b as usize)+1); let byte = utils::from_hex(&data[data_byte_range])? as u8; hw.write_mem(addr+b, &[byte]); } out += "OK"; } 'p' => { let hw = ctx.dbg.hw(); let reg = utils::from_hex(&params)? as usize; let regval = match reg { 0 ..= 14 => hw.read_reg(reg), 15 => hw.pause_addr(), 25 => hw.read_cpsr(), n => { warn!("GDB requested bad register value {}", n); 0 } }; out += &format!("{:08X}", regval.swap_bytes()); } 'q' => { return handle_gdb_cmd_q(params, ctx); } 's' => { return cmd_step(ctx); } 'c' => { return cmd_continue(ctx); } 'v' => { return handle_gdb_cmd_v(params, ctx); } 'z' | 'Z' => { let mut hw = ctx.dbg.hw(); let mut params = params.split(','); let brk_ty = parse_next(&mut params)?; let addr = parse_next_hex(&mut params)?; let _kind = parse_next(&mut params)?; assert!(brk_ty == "0"); if ty == 'Z' { hw.set_breakpoint(addr); } else { hw.del_breakpoint(addr); } out += "OK"; } '?' => { out += &ctx.last_halt.to_signal(); } x => { warn!("GDB client tried to run unsupported command {}", x); } } Ok(out) } #[derive(Clone, Copy)] struct Checksum(pub u32); impl Add<u8> for Checksum { type Output = Checksum; fn add(self, b: u8) -> Checksum { Checksum((self.0 + (b as u32)) % 256) } } impl AddAssign<u8> for Checksum { fn add_assign(&mut self, b: u8) { self.0 = (*self + b).0; } } enum PacketType { Command(String), CtrlC, AckOk, AckErr, EndOfPacket, Malformed, } fn load_packet<I: Iterator<Item = u8>>(it: &mut I) -> PacketType { let mut it = it.skip_while(|b| *b != 0x03 && *b != b'$' && *b != b'-' && *b != b'+'); match it.next() { Some(0x3) => return PacketType::CtrlC, Some(b'$') => {} Some(b'+') => return PacketType::AckOk, Some(b'-') => return PacketType::AckErr, None => return PacketType::EndOfPacket, _ => return PacketType::Malformed } let mut string = String::new(); let mut checksum = Checksum(0); for b in it.by_ref().take_while(|b| *b != b'#') { string.push(b as char); checksum += b; } if let (Some(top), Some(bot)) = (it.next(), it.next()) { let packet_checksum = str::from_utf8(&[top, bot]).ok() .and_then(|s| utils::from_hex(s).ok()); if Some(checksum.0) == packet_checksum { return PacketType::Command(string) } } return PacketType::Malformed } fn write_gdb_packet(data: &str, stream: &mut TcpStream) -> Result<()> { let checksum = data.bytes().fold(Checksum(0), |checksum, b| checksum + b); trace!("Replying with GDB packet: ${}#{:02X}", data, checksum.0); write!(stream, "${}#{:02X}", data, checksum.0)?; stream.flush()?; Ok(()) } fn handle_gdb_packet(data: &[u8], stream: &mut TcpStream, ctx: &mut GdbCtx) -> Result<()> { trace!("Recieving GDB packet: {}", str::from_utf8(data).unwrap()); let mut it = data.iter().cloned(); loop { match load_packet(&mut it) { PacketType::Command(cmd) => { stream.write(b"+")?; stream.flush()?; match handle_gdb_cmd(&cmd, ctx) { Ok(out) => write_gdb_packet(&out, stream)?, Err(e) => { if let ErrorKind::NoResponse = e {} else { return Err(e) } } } } PacketType::CtrlC => { ctx.dbg.pause(); trace!("Recieved GDB packet with CTRL-C signal!"); } PacketType::AckOk => {}, PacketType::AckErr => error!("GDB client replied with error packet!"), PacketType::EndOfPacket => { return Ok(()) } PacketType::Malformed => { trace!("Recieved malformed data {:?}", data); stream.write(b"-")?; stream.flush()?; return Ok(()) } } } } struct
GdbCtx
identifier_name
gdbstub.rs
} fn handle_gdb_cmd_q(cmd: &str, _ctx: &mut GdbCtx) -> Result<String> { let mut s = cmd.splitn(2, ':'); let ty = parse_next(&mut s)?; let mut out = String::new(); match ty { "fThreadInfo" => out += "m0000000000000001", "sThreadInfo" => out += "l", "C" => out += "QC0000000000000001", "Attached" => out += "1", "Supported" => { out += "PacketSize=400;BreakpointCommands+;swbreak+;vContSupported+"; } _ => warn!("GDB client tried to run unsupported `q` command {}", ty) } Ok(out) } fn handle_gdb_cmd_v(cmd: &str, ctx: &mut GdbCtx) -> Result<String> { let mut s = cmd.splitn(2, |c| c == ',' || c == ':' || c == ';'); let ty = parse_next(&mut s)?; let mut out = String::new(); match ty { "Cont" => { let params = parse_next(&mut s)?; let threads = params.split(';'); for thread in threads { let mut thread_data = thread.split(':'); let action = parse_next(&mut thread_data)?; let thread_name = thread_data.next(); if let Some(name) = thread_name { match (name, utils::from_hex(name)) { | ("-1", _) | (_, Ok(0)) | (_, Ok(1)) => {} | (s, _) => panic!("Attempted to issue command on invalid thread id {}", s) } } match action { "c" => return cmd_continue(ctx), "s" => return cmd_step(ctx), _ => warn!("GDB client tried to run unsupported `vCont` action {}", action) } } } "Cont?" => { let supported = ["c", "s"]; out += "vCont"; for ty in supported.iter() { out += ";"; out += ty; } } _ => warn!("GDB client tried to run unsupported `v` command {}", ty) } Ok(out) } fn handle_gdb_cmd(cmd: &str, ctx: &mut GdbCtx) -> Result<String> { let ty = parse_next(&mut cmd.chars())?; let params = &cmd[1..]; let mut out = String::new(); ctx.dbg.pause(); match ty { 'g' => { let hw = ctx.dbg.hw(); for reg in 0..15 { out += &format!("{:08X}", hw.read_reg(reg).swap_bytes()); } out += &format!("{:08X}", hw.pause_addr().swap_bytes()); for _ in 0..8 { out += "xxxxxxxxxxxxxxxxxxxxxxxx"; // fX registers (12 bytes each) } out += "xxxxxxxx"; // fps register out += &format!("{:08X}", hw.read_cpsr().swap_bytes()); } 'G' => { let mut hw = ctx.dbg.hw(); let mut regs = params; let next_reg = |regstr: &str| -> Result<u32> { let val = utils::from_hex(&regstr[..8])?; Ok(val.swap_bytes()) }; for reg in 0..15 { hw.write_reg(reg, next_reg(regs)?); regs = &regs[8..]; } // register at 15: PC hw.branch_to(next_reg(regs)?); regs = &regs[8..]; // Skip 8 fX registers regs = &regs[8 * 24..]; // Skip fps register regs = &regs[8..]; // register at 25: CPSR hw.write_cpsr(next_reg(regs)?); out += "OK"; } 'H' => { out += "OK"; } 'm' => { let mut hw = ctx.dbg.hw(); let mut params = params.split(','); let addr = parse_next_hex(&mut params)?; let size = parse_next_hex(&mut params)?; let mut buf = [0u8]; for b in 0..size { if let Err(_) = hw.read_mem(addr+b, &mut buf) { out += "00"; } else { out += &format!("{:02X}", buf[0]); } } } 'M' => { let mut hw = ctx.dbg.hw(); let mut params = params.split(|c| c == ',' || c == ':'); let addr = parse_next_hex(&mut params)?; let size = parse_next_hex(&mut params)?; let data = parse_next(&mut params)?; for b in 0..size { let data_byte_range = 2*(b as usize)..2*((b as usize)+1); let byte = utils::from_hex(&data[data_byte_range])? as u8; hw.write_mem(addr+b, &[byte]); } out += "OK"; } 'p' => { let hw = ctx.dbg.hw(); let reg = utils::from_hex(&params)? as usize; let regval = match reg { 0 ..= 14 => hw.read_reg(reg), 15 => hw.pause_addr(), 25 => hw.read_cpsr(), n => { warn!("GDB requested bad register value {}", n); 0 } }; out += &format!("{:08X}", regval.swap_bytes()); } 'q' => { return handle_gdb_cmd_q(params, ctx); } 's' => { return cmd_step(ctx); } 'c' => { return cmd_continue(ctx); } 'v' => { return handle_gdb_cmd_v(params, ctx); } 'z' | 'Z' => { let mut hw = ctx.dbg.hw(); let mut params = params.split(','); let brk_ty = parse_next(&mut params)?; let addr = parse_next_hex(&mut params)?; let _kind = parse_next(&mut params)?; assert!(brk_ty == "0"); if ty == 'Z' { hw.set_breakpoint(addr); } else { hw.del_breakpoint(addr); } out += "OK"; } '?' => { out += &ctx.last_halt.to_signal(); } x => { warn!("GDB client tried to run unsupported command {}", x); } } Ok(out) } #[derive(Clone, Copy)] struct Checksum(pub u32); impl Add<u8> for Checksum { type Output = Checksum; fn add(self, b: u8) -> Checksum { Checksum((self.0 + (b as u32)) % 256) } } impl AddAssign<u8> for Checksum { fn add_assign(&mut self, b: u8) { self.0 = (*self + b).0; } } enum PacketType { Command(String), CtrlC, AckOk, AckErr, EndOfPacket, Malformed, } fn load_packet<I: Iterator<Item = u8>>(it: &mut I) -> PacketType { let mut it = it.skip_while(|b| *b != 0x03 && *b != b'$' && *b != b'-' && *b != b'+'); match it.next() { Some(0x3) => return PacketType::CtrlC, Some(b'$') => {} Some(b'+') => return PacketType::AckOk, Some(b'-') => return PacketType::AckErr, None => return PacketType::EndOfPacket, _ => return PacketType::Malformed } let mut string = String::new(); let mut checksum = Checksum(0); for b in it.by_ref().take_while(|b| *b != b'#') { string.push(b as char); checksum += b; } if let (Some(top), Some(bot)) = (it.next(), it.next()) { let packet_checksum = str::from_utf8(&[top, bot]).ok() .and_then(|s| utils::from_hex(s).ok()); if Some(checksum.0) == packet_checksum { return PacketType::Command(string) } } return PacketType::Malformed } fn write_gdb_packet(data: &str, stream: &mut TcpStream) -> Result<()> { let checksum = data.bytes().fold(Checksum(0), |checksum, b| checksum +
{ let reason_str = match self.reason { BreakReason::Breakpoint => format!(";{}:", "swbreak"), _ => String::new(), }; format!("T05{:02X}:{:08X};{:02X}:{:08X}{};", 15, self.r15.swap_bytes(), 13, self.r13.swap_bytes(), reason_str) }
identifier_body
spinning_square.rs
fn handle_toggle_rounded_message(&mut self, _msg: &ToggleRoundedMessage) { self.rounded = !self.rounded; self.square_path = None; } fn handle_toggle_direction_message(&mut self, _msg: &ToggleDirectionMessage) { self.direction = self.direction.toggle(); } fn handle_other_message(&mut self, _msg: &carnelian::Message) { println!("handle_other_message"); } } impl Facet for SpinningSquareFacet { fn update_layers( &mut self, size: Size, layer_group: &mut dyn LayerGroup, render_context: &mut RenderContext, view_context: &ViewAssistantContext, ) -> Result<(), Error> { const SPEED: f32 = 0.25; const SECONDS_PER_NANOSECOND: f32 = 1e-9; const SQUARE_PATH_SIZE: Coord = 1.0; const SQUARE_PATH_SIZE_2: Coord = SQUARE_PATH_SIZE / 2.0; const CORNER_RADIUS: Coord = SQUARE_PATH_SIZE / 4.0; let center_x = size.width * 0.5; let center_y = size.height * 0.5; self.size = size; let square_size = size.width.min(size.height) * 0.6; let presentation_time = view_context.presentation_time; let t = ((presentation_time.into_nanos() - self.start.into_nanos()) as f32 * SECONDS_PER_NANOSECOND * SPEED) % 1.0; let angle = t * PI * 2.0 * if self.direction == Direction::CounterClockwise { -1.0 } else { 1.0 }; if self.square_path.is_none() { let top_left = point2(-SQUARE_PATH_SIZE_2, -SQUARE_PATH_SIZE_2); let square = Rect::new(top_left, size2(SQUARE_PATH_SIZE, SQUARE_PATH_SIZE)); let square_path = if self.rounded { path_for_rounded_rectangle(&square, CORNER_RADIUS, render_context) } else { path_for_rectangle(&square, render_context) }; self.square_path.replace(square_path); } let transformation = Transform2D::rotation(Angle::radians(angle)) .then_scale(square_size, square_size) .then_translate(vec2(center_x, center_y)); let mut raster_builder = render_context.raster_builder().expect("raster_builder"); raster_builder.add(&self.clone_square_path(), Some(&transformation)); let square_raster = raster_builder.build(); layer_group.insert( SceneOrder::default(), Layer { raster: square_raster, clip: None, style: Style { fill_rule: FillRule::NonZero, fill: Fill::Solid(self.square_color), blend_mode: BlendMode::Over, }, }, ); Ok(()) } derive_handle_message_with_default!(handle_other_message, ToggleRoundedMessage => handle_toggle_rounded_message, ToggleDirectionMessage => handle_toggle_direction_message ); fn calculate_size(&self, _available: Size) -> Size { self.size } } struct SpinningSquareViewAssistant { direction: Direction, view_key: ViewKey, background_color: Color, square_color: Color, start: Time, app_sender: AppSender, scene_details: Option<SceneDetails>, face: FontFace, additional: bool, } impl SpinningSquareViewAssistant { fn new( view_key: ViewKey, direction: Direction, app_sender: AppSender, additional: bool, ) -> Result<ViewAssistantPtr, Error> { let square_color = Color { r: 0xbb, g: 0x00, b: 0xff, a: 0xbb }; let background_color = Color { r: 0x3f, g: 0x8a, b: 0x99, a: 0xff }; let start = Time::get_monotonic(); let face = load_font(PathBuf::from("/pkg/data/fonts/RobotoSlab-Regular.ttf"))?; Ok(Box::new(SpinningSquareViewAssistant { direction, view_key, background_color, square_color, start, scene_details: None, app_sender, face, additional, })) } fn ensure_scene_built(&mut self, size: Size) { if self.scene_details.is_none() { let min_dimension = size.width.min(size.height); let font_size = (min_dimension / 5.0).ceil().min(64.0); let mut builder = SceneBuilder::new().background_color(self.background_color).animated(true); let mut square = None; builder.group().stack().center().contents(|builder| { if self.additional { let key_text = format!("{}", self.view_key); let _ = builder.text( self.face.clone(), &key_text, font_size, Point::zero(), TextFacetOptions::default(), ); } let square_facet = SpinningSquareFacet::new(self.square_color, self.start, size, self.direction); square = Some(builder.facet(Box::new(square_facet))); const STRIPE_COUNT: usize = 5; let stripe_height = size.height / (STRIPE_COUNT * 2 + 1) as f32; const STRIPE_WIDTH_RATIO: f32 = 0.8; let stripe_size = size2(size.width * STRIPE_WIDTH_RATIO, stripe_height); builder.group().column().max_size().space_evenly().contents(|builder| { for _ in 0..STRIPE_COUNT { builder.rectangle(stripe_size, Color::white()); } }); }); let square = square.expect("square"); let scene = builder.build(); self.scene_details = Some(SceneDetails { scene, square }); } } fn toggle_rounded(&mut self) { if let Some(scene_details) = self.scene_details.as_mut() { // since we have the scene, we could call send_message directly, // but this lets us demonstrate facet-targeted messages. self.app_sender.queue_message( MessageTarget::Facet(self.view_key, scene_details.square), Box::new(ToggleRoundedMessage {}), ); self.app_sender.request_render(self.view_key); } } fn move_backward(&mut self) { if let Some(scene_details) = self.scene_details.as_mut() { scene_details .scene .move_facet_backward(scene_details.square) .unwrap_or_else(|e| println!("error in move_facet_backward: {}", e)); self.app_sender.request_render(self.view_key); } } fn move_forward(&mut self) { if let Some(scene_details) = self.scene_details.as_mut() { scene_details .scene .move_facet_forward(scene_details.square) .unwrap_or_else(|e| println!("error in move_facet_forward: {}", e)); self.app_sender.request_render(self.view_key); } } fn toggle_direction(&mut self) { if let Some(scene_details) = self.scene_details.as_mut() { self.app_sender.queue_message( MessageTarget::Facet(self.view_key, scene_details.square), Box::new(ToggleDirectionMessage {}), ); self.app_sender.request_render(self.view_key); } } fn make_new_view(&mut self) { let direction = self.direction.toggle(); self.app_sender.create_additional_view(Some(Box::new(direction))); } fn close_additional_view(&mut self) { if self.additional { self.app_sender.close_additional_view(self.view_key); } else { println!("Cannot close initial window"); } } } impl ViewAssistant for SpinningSquareViewAssistant { fn resize(&mut self, new_size: &Size) -> Result<(), Error> { self.scene_details = None; self.ensure_scene_built(*new_size); Ok(()) } fn get_scene(&mut self, size: Size) -> Option<&mut Scene> { self.ensure_scene_built(size); Some(&mut self.scene_details.as_mut().unwrap().scene) } fn handle_keyboard_event( &mut self, _context: &mut ViewAssistantContext, _event: &input::Event, keyboard_event: &input::keyboard::Event, ) -> Result<(), Error> { const SPACE: u32 = ' ' as u32; const B: u32 = 'b' as u32; const F: u32 = 'f' as u32; const D: u32 = 'd' as u32; const V: u32 = 'v' as u32; const C: u32 = 'c' as u32; if let Some(code_point) = keyboard_event.code_point
{ if keyboard_event.phase == input::keyboard::Phase::Pressed || keyboard_event.phase == input::keyboard::Phase::Repeat { match code_point { SPACE => self.toggle_rounded(), B => self.move_backward(), F => self.move_forward(), D => self.toggle_direction(), V => self.make_new_view(), C => self.close_additional_view(), _ => println!("code_point = {}", code_point), } } }
conditional_block
spinning_square.rs
Error> { Ok(()) } fn create_view_assistant_with_parameters( &mut self, params: ViewCreationParameters, ) -> Result<ViewAssistantPtr, Error> { let additional = params.options.is_some(); let direction = params .options .and_then(|options| options.downcast_ref::<Direction>().map(|direction| *direction)) .unwrap_or(Direction::CounterClockwise); SpinningSquareViewAssistant::new( params.view_key, direction, self.app_sender.clone(), additional, ) } /// Return the list of names of services this app wants to provide fn outgoing_services_names(&self) -> Vec<&'static str> { [EchoMarker::PROTOCOL_NAME].to_vec() } /// Handle a request to connect to a service provided by this app fn handle_service_connection_request( &mut self, _service_name: &str, channel: fasync::Channel, ) -> Result<(), Error> { Self::create_echo_server(channel, false); Ok(()) } fn filter_config(&mut self, config: &mut Config) { config.display_resource_release_delay = std::time::Duration::new(0, 0); } } impl SpinningSquareAppAssistant { fn create_echo_server(channel: fasync::Channel, quiet: bool) { fasync::Task::local( async move { let mut stream = EchoRequestStream::from_channel(channel); while let Some(EchoRequest::EchoString { value, responder }) = stream.try_next().await.context("error running echo server")? { if !quiet { println!("Spinning Square received echo request for string {:?}", value); } responder .send(value.as_ref().map(|s| &**s)) .context("error sending response")?; if !quiet { println!("echo response sent successfully"); } } Ok(()) } .unwrap_or_else(|e: anyhow::Error| eprintln!("{:?}", e)), ) .detach(); } } struct SceneDetails { scene: Scene, square: FacetId, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Direction { Clockwise, CounterClockwise, } impl Direction { pub fn toggle(self) -> Self {
} #[derive(Debug)] pub struct ToggleRoundedMessage {} #[derive(Debug)] pub struct ToggleDirectionMessage {} struct SpinningSquareFacet { direction: Direction, square_color: Color, rounded: bool, start: Time, square_path: Option<Path>, size: Size, } impl SpinningSquareFacet { fn new(square_color: Color, start: Time, size: Size, direction: Direction) -> Self { Self { direction, square_color, rounded: false, start, square_path: None, size } } fn clone_square_path(&self) -> Path { self.square_path.as_ref().expect("square_path").clone() } fn handle_toggle_rounded_message(&mut self, _msg: &ToggleRoundedMessage) { self.rounded = !self.rounded; self.square_path = None; } fn handle_toggle_direction_message(&mut self, _msg: &ToggleDirectionMessage) { self.direction = self.direction.toggle(); } fn handle_other_message(&mut self, _msg: &carnelian::Message) { println!("handle_other_message"); } } impl Facet for SpinningSquareFacet { fn update_layers( &mut self, size: Size, layer_group: &mut dyn LayerGroup, render_context: &mut RenderContext, view_context: &ViewAssistantContext, ) -> Result<(), Error> { const SPEED: f32 = 0.25; const SECONDS_PER_NANOSECOND: f32 = 1e-9; const SQUARE_PATH_SIZE: Coord = 1.0; const SQUARE_PATH_SIZE_2: Coord = SQUARE_PATH_SIZE / 2.0; const CORNER_RADIUS: Coord = SQUARE_PATH_SIZE / 4.0; let center_x = size.width * 0.5; let center_y = size.height * 0.5; self.size = size; let square_size = size.width.min(size.height) * 0.6; let presentation_time = view_context.presentation_time; let t = ((presentation_time.into_nanos() - self.start.into_nanos()) as f32 * SECONDS_PER_NANOSECOND * SPEED) % 1.0; let angle = t * PI * 2.0 * if self.direction == Direction::CounterClockwise { -1.0 } else { 1.0 }; if self.square_path.is_none() { let top_left = point2(-SQUARE_PATH_SIZE_2, -SQUARE_PATH_SIZE_2); let square = Rect::new(top_left, size2(SQUARE_PATH_SIZE, SQUARE_PATH_SIZE)); let square_path = if self.rounded { path_for_rounded_rectangle(&square, CORNER_RADIUS, render_context) } else { path_for_rectangle(&square, render_context) }; self.square_path.replace(square_path); } let transformation = Transform2D::rotation(Angle::radians(angle)) .then_scale(square_size, square_size) .then_translate(vec2(center_x, center_y)); let mut raster_builder = render_context.raster_builder().expect("raster_builder"); raster_builder.add(&self.clone_square_path(), Some(&transformation)); let square_raster = raster_builder.build(); layer_group.insert( SceneOrder::default(), Layer { raster: square_raster, clip: None, style: Style { fill_rule: FillRule::NonZero, fill: Fill::Solid(self.square_color), blend_mode: BlendMode::Over, }, }, ); Ok(()) } derive_handle_message_with_default!(handle_other_message, ToggleRoundedMessage => handle_toggle_rounded_message, ToggleDirectionMessage => handle_toggle_direction_message ); fn calculate_size(&self, _available: Size) -> Size { self.size } } struct SpinningSquareViewAssistant { direction: Direction, view_key: ViewKey, background_color: Color, square_color: Color, start: Time, app_sender: AppSender, scene_details: Option<SceneDetails>, face: FontFace, additional: bool, } impl SpinningSquareViewAssistant { fn new( view_key: ViewKey, direction: Direction, app_sender: AppSender, additional: bool, ) -> Result<ViewAssistantPtr, Error> { let square_color = Color { r: 0xbb, g: 0x00, b: 0xff, a: 0xbb }; let background_color = Color { r: 0x3f, g: 0x8a, b: 0x99, a: 0xff }; let start = Time::get_monotonic(); let face = load_font(PathBuf::from("/pkg/data/fonts/RobotoSlab-Regular.ttf"))?; Ok(Box::new(SpinningSquareViewAssistant { direction, view_key, background_color, square_color, start, scene_details: None, app_sender, face, additional, })) } fn ensure_scene_built(&mut self, size: Size) { if self.scene_details.is_none() { let min_dimension = size.width.min(size.height); let font_size = (min_dimension / 5.0).ceil().min(64.0); let mut builder = SceneBuilder::new().background_color(self.background_color).animated(true); let mut square = None; builder.group().stack().center().contents(|builder| { if self.additional { let key_text = format!("{}", self.view_key); let _ = builder.text( self.face.clone(), &key_text, font_size, Point::zero(), TextFacetOptions::default(), ); } let square_facet = SpinningSquareFacet::new(self.square_color, self.start, size, self.direction); square = Some(builder.facet(Box::new(square_facet))); const STRIPE_COUNT: usize = 5; let stripe_height = size.height / (STRIPE_COUNT * 2 + 1) as f32; const STRIPE_WIDTH_RATIO: f32 = 0.8; let stripe_size = size2(size.width * STRIPE_WIDTH_RATIO, stripe_height); builder.group().column().max_size().space_evenly().contents(|builder| { for _ in 0..STRIPE_COUNT { builder.rectangle(stripe_size, Color::white()); } }); }); let square = square.expect("square"); let scene = builder.build(); self.scene_details = Some(SceneDetails { scene, square }); } } fn toggle_rounded(&mut self) { if let Some(scene_details) = self.scene_details.as_mut() { // since we have the scene, we could call send_message directly, // but this lets us demonstrate facet-targeted messages. self.app_sender.queue_message( MessageTarget::Facet(self.view_key,
match self { Self::Clockwise => Self::CounterClockwise, Self::CounterClockwise => Self::Clockwise, } }
random_line_split
spinning_square.rs
error running echo server")? { if !quiet { println!("Spinning Square received echo request for string {:?}", value); } responder .send(value.as_ref().map(|s| &**s)) .context("error sending response")?; if !quiet { println!("echo response sent successfully"); } } Ok(()) } .unwrap_or_else(|e: anyhow::Error| eprintln!("{:?}", e)), ) .detach(); } } struct SceneDetails { scene: Scene, square: FacetId, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Direction { Clockwise, CounterClockwise, } impl Direction { pub fn toggle(self) -> Self { match self { Self::Clockwise => Self::CounterClockwise, Self::CounterClockwise => Self::Clockwise, } } } #[derive(Debug)] pub struct ToggleRoundedMessage {} #[derive(Debug)] pub struct ToggleDirectionMessage {} struct SpinningSquareFacet { direction: Direction, square_color: Color, rounded: bool, start: Time, square_path: Option<Path>, size: Size, } impl SpinningSquareFacet { fn new(square_color: Color, start: Time, size: Size, direction: Direction) -> Self { Self { direction, square_color, rounded: false, start, square_path: None, size } } fn clone_square_path(&self) -> Path { self.square_path.as_ref().expect("square_path").clone() } fn handle_toggle_rounded_message(&mut self, _msg: &ToggleRoundedMessage) { self.rounded = !self.rounded; self.square_path = None; } fn handle_toggle_direction_message(&mut self, _msg: &ToggleDirectionMessage) { self.direction = self.direction.toggle(); } fn handle_other_message(&mut self, _msg: &carnelian::Message) { println!("handle_other_message"); } } impl Facet for SpinningSquareFacet { fn update_layers( &mut self, size: Size, layer_group: &mut dyn LayerGroup, render_context: &mut RenderContext, view_context: &ViewAssistantContext, ) -> Result<(), Error> { const SPEED: f32 = 0.25; const SECONDS_PER_NANOSECOND: f32 = 1e-9; const SQUARE_PATH_SIZE: Coord = 1.0; const SQUARE_PATH_SIZE_2: Coord = SQUARE_PATH_SIZE / 2.0; const CORNER_RADIUS: Coord = SQUARE_PATH_SIZE / 4.0; let center_x = size.width * 0.5; let center_y = size.height * 0.5; self.size = size; let square_size = size.width.min(size.height) * 0.6; let presentation_time = view_context.presentation_time; let t = ((presentation_time.into_nanos() - self.start.into_nanos()) as f32 * SECONDS_PER_NANOSECOND * SPEED) % 1.0; let angle = t * PI * 2.0 * if self.direction == Direction::CounterClockwise { -1.0 } else { 1.0 }; if self.square_path.is_none() { let top_left = point2(-SQUARE_PATH_SIZE_2, -SQUARE_PATH_SIZE_2); let square = Rect::new(top_left, size2(SQUARE_PATH_SIZE, SQUARE_PATH_SIZE)); let square_path = if self.rounded { path_for_rounded_rectangle(&square, CORNER_RADIUS, render_context) } else { path_for_rectangle(&square, render_context) }; self.square_path.replace(square_path); } let transformation = Transform2D::rotation(Angle::radians(angle)) .then_scale(square_size, square_size) .then_translate(vec2(center_x, center_y)); let mut raster_builder = render_context.raster_builder().expect("raster_builder"); raster_builder.add(&self.clone_square_path(), Some(&transformation)); let square_raster = raster_builder.build(); layer_group.insert( SceneOrder::default(), Layer { raster: square_raster, clip: None, style: Style { fill_rule: FillRule::NonZero, fill: Fill::Solid(self.square_color), blend_mode: BlendMode::Over, }, }, ); Ok(()) } derive_handle_message_with_default!(handle_other_message, ToggleRoundedMessage => handle_toggle_rounded_message, ToggleDirectionMessage => handle_toggle_direction_message ); fn calculate_size(&self, _available: Size) -> Size { self.size } } struct SpinningSquareViewAssistant { direction: Direction, view_key: ViewKey, background_color: Color, square_color: Color, start: Time, app_sender: AppSender, scene_details: Option<SceneDetails>, face: FontFace, additional: bool, } impl SpinningSquareViewAssistant { fn new( view_key: ViewKey, direction: Direction, app_sender: AppSender, additional: bool, ) -> Result<ViewAssistantPtr, Error> { let square_color = Color { r: 0xbb, g: 0x00, b: 0xff, a: 0xbb }; let background_color = Color { r: 0x3f, g: 0x8a, b: 0x99, a: 0xff }; let start = Time::get_monotonic(); let face = load_font(PathBuf::from("/pkg/data/fonts/RobotoSlab-Regular.ttf"))?; Ok(Box::new(SpinningSquareViewAssistant { direction, view_key, background_color, square_color, start, scene_details: None, app_sender, face, additional, })) } fn ensure_scene_built(&mut self, size: Size) { if self.scene_details.is_none() { let min_dimension = size.width.min(size.height); let font_size = (min_dimension / 5.0).ceil().min(64.0); let mut builder = SceneBuilder::new().background_color(self.background_color).animated(true); let mut square = None; builder.group().stack().center().contents(|builder| { if self.additional { let key_text = format!("{}", self.view_key); let _ = builder.text( self.face.clone(), &key_text, font_size, Point::zero(), TextFacetOptions::default(), ); } let square_facet = SpinningSquareFacet::new(self.square_color, self.start, size, self.direction); square = Some(builder.facet(Box::new(square_facet))); const STRIPE_COUNT: usize = 5; let stripe_height = size.height / (STRIPE_COUNT * 2 + 1) as f32; const STRIPE_WIDTH_RATIO: f32 = 0.8; let stripe_size = size2(size.width * STRIPE_WIDTH_RATIO, stripe_height); builder.group().column().max_size().space_evenly().contents(|builder| { for _ in 0..STRIPE_COUNT { builder.rectangle(stripe_size, Color::white()); } }); }); let square = square.expect("square"); let scene = builder.build(); self.scene_details = Some(SceneDetails { scene, square }); } } fn toggle_rounded(&mut self) { if let Some(scene_details) = self.scene_details.as_mut() { // since we have the scene, we could call send_message directly, // but this lets us demonstrate facet-targeted messages. self.app_sender.queue_message( MessageTarget::Facet(self.view_key, scene_details.square), Box::new(ToggleRoundedMessage {}), ); self.app_sender.request_render(self.view_key); } } fn move_backward(&mut self) { if let Some(scene_details) = self.scene_details.as_mut() { scene_details .scene .move_facet_backward(scene_details.square) .unwrap_or_else(|e| println!("error in move_facet_backward: {}", e)); self.app_sender.request_render(self.view_key); } } fn move_forward(&mut self) { if let Some(scene_details) = self.scene_details.as_mut() { scene_details .scene .move_facet_forward(scene_details.square) .unwrap_or_else(|e| println!("error in move_facet_forward: {}", e)); self.app_sender.request_render(self.view_key); } } fn toggle_direction(&mut self) { if let Some(scene_details) = self.scene_details.as_mut() { self.app_sender.queue_message( MessageTarget::Facet(self.view_key, scene_details.square), Box::new(ToggleDirectionMessage {}), ); self.app_sender.request_render(self.view_key); } } fn make_new_view(&mut self) { let direction = self.direction.toggle(); self.app_sender.create_additional_view(Some(Box::new(direction))); } fn close_additional_view(&mut self) { if self.additional { self.app_sender.close_additional_view(self.view_key); } else { println!("Cannot close initial window"); } } } impl ViewAssistant for SpinningSquareViewAssistant { fn
resize
identifier_name
aup2rpp.py
WavWriter(f, au['sample_rate'], nchannels, 16) elif w.sample_rate != au['sample_rate']: print("ERROR: sample rate differs in one of the .au files I wanted to concatenate into one .wav") # TODO Resample, or return multiple files and split the clip... break samples_by_channel.append(samples) w.append_multichannel_samples(samples_by_channel) w.finalize() return 0 if w is None else w.samples_count def load_audacity_project(fpath): root = ET.parse(fpath).getroot() rate = int(float(root.attrib["rate"])) name = root.attrib['projname'] ns = { 'ns': 'http://audacity.sourceforge.net/xml/' } data_dir = os.path.splitext(fpath)[0] + '_data' if not os.path.isdir(data_dir): data_dir = "" def unescape(s): return html.unescape(s) output = { 'rate': rate, 'name': unescape(name), 'data_dir': data_dir, 'tracks': [] } for project_item in root: tag = project_item.tag.split('}')[1] if tag == 'wavetrack': o_track = { 'name': unescape(project_item.attrib['name']), 'channel': int(project_item.attrib['channel']), 'linked': True if project_item.attrib['linked'] == '1' else False, 'mute': True if project_item.attrib['mute'] == '1' else False, 'solo': True if project_item.attrib['solo'] == '1' else False, 'rate': int(project_item.attrib['rate']), 'gain': float(project_item.attrib['gain']), 'pan': float(project_item.attrib['pan']), 'color_index': int(project_item.attrib['colorindex']), 'clips': [] } output['tracks'].append(o_track) waveclips = project_item.findall('ns:waveclip', ns) for waveclip in waveclips: o_clip = { 'offset': float(waveclip.attrib['offset']), 'color_index': int(waveclip.attrib['colorindex']), } o_track['clips'].append(o_clip) sequence = waveclip.findall('ns:sequence', ns)[0] o_sequence = { 'max_samples': int(sequence.attrib['maxsamples']), 'sample_format': int(sequence.attrib['sampleformat']), 'numsamples': int(sequence.attrib['numsamples']), 'blocks': [] } o_clip['sequence'] = o_sequence for waveblock in sequence.findall('ns:waveblock', ns): waveblock_start = int(waveblock.attrib['start']) for block in waveblock: btag = block.tag.split('}')[1] if btag == 'simpleblockfile': o_sequence['blocks'].append({ 'type': btag, 'start': waveblock_start, 'len': int(block.attrib['len']), 'filename': unescape(block.attrib['filename']), 'min': float(block.attrib['min']), 'max': float(block.attrib['max']), 'rms': float(block.attrib['rms']), }) elif btag == 'pcmaliasblockfile': o_sequence['blocks'].append({ 'type': btag, 'start': waveblock_start, 'len': int(block.attrib['aliaslen']), 'file_start': int(block.attrib['aliasstart']), 'filename': unescape(block.attrib['aliasfile']), 'summary_file': block.attrib['summaryfile'], 'channel': int(block.attrib['aliaschannel']), 'min': float(block.attrib['min']), 'max': float(block.attrib['max']), 'rms': float(block.attrib['rms']) }) elif btag == 'silentblockfile': o_sequence['blocks'].append({ 'type': btag, 'len': int(block.attrib['len']) }) else: print("WARNING: Unknown block type: '{0}'".format(btag)) envelope = waveclip.findall('ns:envelope', ns)[0] points = [] for point in envelope.findall('ns:controlpoint', ns): points.append({ 't': float(point.attrib['t']), 'val': float(point.attrib['val']) }) o_clip['envelope'] = { 'points': points } return output def convert_au_files_from_audacity_project(project, target_dir): # This is where most of the conversion happens. indexed_files = {} if project['data_dir'] != "": # Audacity saves its media files under a nested hierarchy, # I don't quite understand why since files seem to have unique names for root, dirs, files in os.walk(project['data_dir']): for name in files: indexed_files[name] = os.path.join(root, name) if not os.path.isdir(target_dir): os.makedirs(target_dir) tracks = project['tracks'] # TODO Eventually just make an entirely new project dictionary rather than modifying the input one converted_tracks = [] project['converted_tracks'] = converted_tracks for track_index, track in enumerate(tracks): previous_track = None if track_index == 0 else tracks[track_index - 1] next_track = None if track_index + 1 == len(tracks) else tracks[track_index + 1] is_stereo_track = False if track['channel'] == 1: if previous_track is not None and previous_track['linked']: # Ignore second channel of a linked stereo track, # should be handled both in the previous iteration. # This means a converted project may have less tracks. continue elif track['channel'] == 0 and track['linked']: is_stereo_track = True converted_track = { 'name': track['name'], 'mute': track['mute'], 'solo': track['solo'], 'rate': track['rate'], 'gain': track['gain'], 'pan': track['pan'], 'color_index': track['color_index'], } converted_tracks.append(converted_track) converted_clips = [] converted_track['converted_clips'] = converted_clips for clip_index, clip in enumerate(track['clips']): sequence = clip['sequence'] au_fpaths = [[], []] converted_numsamples = 0 converted_clip_start = clip['offset'] # In seconds blocks = sequence['blocks'] clip2 = None if is_stereo_track: clip2 = next_track['clips'][clip_index] if clip2['offset'] != clip['offset']: print("WARNING: Stereo track has non-aligned clips??") # Okayyy clip2 = None # Convert clip-wise envelopes into a track-wise one if len(clip['envelope']['points']) > 0: if 'envelope' not in converted_track: converted_envelope = { 'points': [] } converted_track['envelope'] = converted_envelope else: converted_envelope = converted_track['envelope'] # Note: points will be sorted once we have gone through all clips points = clip['envelope']['points'] for p in points: converted_envelope['points'].append({ 't': p['t'], 'val': p['val'] }) # A clip can be made of many different blocks. # The goal is to process them in order to get one file per clip, # and then possibly splitting the clip or ignoring blocks. # Another fun part is joining stereo tracks, # because they are saved separately for block_index, block in enumerate(blocks): btype = block['type'] is_last = block_index + 1 == len(blocks) is_next_different = not is_last and btype != blocks[block_index + 1]['type'] if btype == 'simpleblockfile' or btype == 'pcmaliasblockfile': if converted_numsamples == 0: converted_clip_start = clip['offset'] + block['start'] / project['rate'] converted_numsamples += block['len'] if btype == 'simpleblockfile': # This is mostly because I assume this rather than knowing it
assert block['filename'].endswith('.au') block2 = None if is_stereo_track and clip2 is not None: for b in clip2['sequence']['blocks']: if b['start'] == block['start'] and b['len'] == block['len']: block2 = b break if block2 is not None: src_fpath = indexed_files[block['filename']] au_fpaths[0].append(src_fpath) src_fpath2 = indexed_files[block2['filename']] au_fpaths[1].append(src_fpath2) else: src_fpath = indexed_files[block['filename']] au_fpaths[0].append(src_fpath) if is_last or is_next_different:
conditional_block
aup2rpp.py
f = self.f for v in sample_data: f.write(struct.pack(sfc, v)) self.samples_count += nsamples def finalize(self): assert not self.finalized f = self.f end = f.tell() data_chunk_size = f.tell() - self.data_fpos f.seek(self.initial_fpos) assert data_chunk_size == (self.samples_count * self.channels * self.bits_per_sample // 8) # "WAVE" letters + two FourCC+size headers and their chunk size. # Does not include the size of the top-level header "RIFF"+size. riff_chunk_size = 4 + (8 + self.fmt_chunk_size) + (8 + data_chunk_size) f.write(b'RIFF') f.write(struct.pack('I', riff_chunk_size)) f.write(b'WAVE') #wave_chunk_size = ??? #f.write(struct.pack('I', wave_chunk_size)) # ---------- f.write(b'fmt ') f.write(struct.pack('I', self.fmt_chunk_size)) # Format # PCM = 1 (i.e. Linear quantization) Values other than 1 indicate some form of compression. f.write(struct.pack('H', 1)) f.write(struct.pack('H', self.channels)) f.write(struct.pack('I', self.sample_rate)) # SampleRate * NumChannels * BitsPerSample/8 byte_rate = self.sample_rate * self.channels * self.bits_per_sample // 8 f.write(struct.pack('I', byte_rate)) # NumChannels * BitsPerSample/8 block_align = self.channels * self.bits_per_sample // 8 f.write(struct.pack('H', block_align)) # 8 bits = 8, 16 bits = 16, etc. f.write(struct.pack('H', self.bits_per_sample)) f.write(b'data') f.write(struct.pack('I', data_chunk_size)) # And what follows is what we wrote before self.finalized = True # Legacy shortcut # def write_wav_file(fpath, sample_rate, channels, bits_per_sample, sample_data): # with open(fpath, 'wb') as f: # w = WavWriter(f, sample_rate, channels, bits_per_sample) # w.append_samples(sample_data) # w.finalize() def convert_au_files_to_wav(src_paths_by_channel, dst_path): if len(src_paths_by_channel) == 0: return # Eliminate channels with no blocks temp = [] for c in src_paths_by_channel: if len(c) != 0: temp.append(c) src_paths_by_channel = temp print("Converting blocks ", src_paths_by_channel) # Concatenate a bunch of .au block files into a single WAV file with open(dst_path, 'wb') as f: w = None nchannels = len(src_paths_by_channel) # For each block for block_index in range(len(src_paths_by_channel[0])): samples_by_channel = [] # Process each corrsponding channel for that block for channel in range(nchannels): src_paths = src_paths_by_channel[channel] if block_index >= len(src_paths): # That block doesn't have data on each channel... samples_by_channel.append([]) continue au = load_au_file(src_paths[block_index]) samples = au['sample_data'] if au['channels'] != 1: # TODO Deal with this eventually... # As far as I've seen, Audacity actually saves stereo blocks as separate mono .au files. WHY?? print("ERROR: I didn't expect .au files to have 2 channels " "(at least my experience so far has shown they were always mono)") return 0 # Make sure it ends up in the encoding we want if au['encoding'] == AU_SAMPLE_FORMAT_FLOAT: for i, v in enumerate(samples): # We want 16-bit PCM samples[i] = int(v * 32767.0) elif au['encoding'] == AU_SAMPLE_FORMAT_24: print("ERROR: 24 bits not supported") return elif au['encoding'] == AU_SAMPLE_FORMAT_16: pass # Already OK else: print("ERROR: Unknown .au encoding: ", au['encoding']) return 0 if w is None: w = WavWriter(f, au['sample_rate'], nchannels, 16) elif w.sample_rate != au['sample_rate']: print("ERROR: sample rate differs in one of the .au files I wanted to concatenate into one .wav") # TODO Resample, or return multiple files and split the clip... break samples_by_channel.append(samples) w.append_multichannel_samples(samples_by_channel) w.finalize() return 0 if w is None else w.samples_count def load_audacity_project(fpath): root = ET.parse(fpath).getroot() rate = int(float(root.attrib["rate"])) name = root.attrib['projname'] ns = { 'ns': 'http://audacity.sourceforge.net/xml/' } data_dir = os.path.splitext(fpath)[0] + '_data' if not os.path.isdir(data_dir): data_dir = "" def unescape(s):
output = { 'rate': rate, 'name': unescape(name), 'data_dir': data_dir, 'tracks': [] } for project_item in root: tag = project_item.tag.split('}')[1] if tag == 'wavetrack': o_track = { 'name': unescape(project_item.attrib['name']), 'channel': int(project_item.attrib['channel']), 'linked': True if project_item.attrib['linked'] == '1' else False, 'mute': True if project_item.attrib['mute'] == '1' else False, 'solo': True if project_item.attrib['solo'] == '1' else False, 'rate': int(project_item.attrib['rate']), 'gain': float(project_item.attrib['gain']), 'pan': float(project_item.attrib['pan']), 'color_index': int(project_item.attrib['colorindex']), 'clips': [] } output['tracks'].append(o_track) waveclips = project_item.findall('ns:waveclip', ns) for waveclip in waveclips: o_clip = { 'offset': float(waveclip.attrib['offset']), 'color_index': int(waveclip.attrib['colorindex']), } o_track['clips'].append(o_clip) sequence = waveclip.findall('ns:sequence', ns)[0] o_sequence = { 'max_samples': int(sequence.attrib['maxsamples']), 'sample_format': int(sequence.attrib['sampleformat']), 'numsamples': int(sequence.attrib['numsamples']), 'blocks': [] } o_clip['sequence'] = o_sequence for waveblock in sequence.findall('ns:waveblock', ns): waveblock_start = int(waveblock.attrib['start']) for block in waveblock: btag = block.tag.split('}')[1] if btag == 'simpleblockfile': o_sequence['blocks'].append({ 'type': btag, 'start': waveblock_start, 'len': int(block.attrib['len']), 'filename': unescape(block.attrib['filename']), 'min': float(block.attrib['min']), 'max': float(block.attrib['max']), 'rms': float(block.attrib['rms']), }) elif btag == 'pcmaliasblockfile': o_sequence['blocks'].append({ 'type': btag, 'start': waveblock_start, 'len': int(block.attrib['aliaslen']), 'file_start': int(block.attrib['aliasstart']), 'filename': unescape(block.attrib['aliasfile']), 'summary_file': block.attrib['summaryfile'], 'channel': int(block.attrib['aliaschannel']), 'min': float(block.attrib['min']), 'max': float(block.attrib['max']), 'rms': float(block.attrib['rms']) }) elif btag == 'silentblockfile': o_sequence['blocks'].append({ 'type': btag, 'len': int(block.attrib['len']) }) else: print("WARNING: Unknown block type: '{0}'".format(btag)) envelope = waveclip.findall('ns:envelope', ns)[0] points = [] for point in envelope.findall('ns:controlpoint', ns): points.append({ 't': float(point.attrib['t']), 'val': float(point.attrib['val']) }) o_clip['envelope'] = { 'points': points } return output def convert_au_files_from_audacity_project(project, target_dir): # This is where most of the conversion happens. indexed_files = {} if project['data_dir'] != "": # Audacity saves its media files under a nested hierarchy,
return html.unescape(s)
identifier_body
aup2rpp.py
f = self.f for v in sample_data: f.write(struct.pack(sfc, v)) self.samples_count += nsamples def finalize(self): assert not self.finalized f = self.f end = f.tell() data_chunk_size = f.tell() - self.data_fpos f.seek(self.initial_fpos) assert data_chunk_size == (self.samples_count * self.channels * self.bits_per_sample // 8) # "WAVE" letters + two FourCC+size headers and their chunk size. # Does not include the size of the top-level header "RIFF"+size. riff_chunk_size = 4 + (8 + self.fmt_chunk_size) + (8 + data_chunk_size) f.write(b'RIFF') f.write(struct.pack('I', riff_chunk_size)) f.write(b'WAVE') #wave_chunk_size = ??? #f.write(struct.pack('I', wave_chunk_size)) # ---------- f.write(b'fmt ') f.write(struct.pack('I', self.fmt_chunk_size)) # Format # PCM = 1 (i.e. Linear quantization) Values other than 1 indicate some form of compression. f.write(struct.pack('H', 1)) f.write(struct.pack('H', self.channels)) f.write(struct.pack('I', self.sample_rate)) # SampleRate * NumChannels * BitsPerSample/8 byte_rate = self.sample_rate * self.channels * self.bits_per_sample // 8 f.write(struct.pack('I', byte_rate)) # NumChannels * BitsPerSample/8 block_align = self.channels * self.bits_per_sample // 8 f.write(struct.pack('H', block_align)) # 8 bits = 8, 16 bits = 16, etc. f.write(struct.pack('H', self.bits_per_sample)) f.write(b'data') f.write(struct.pack('I', data_chunk_size)) # And what follows is what we wrote before self.finalized = True # Legacy shortcut # def write_wav_file(fpath, sample_rate, channels, bits_per_sample, sample_data): # with open(fpath, 'wb') as f: # w = WavWriter(f, sample_rate, channels, bits_per_sample) # w.append_samples(sample_data) # w.finalize() def convert_au_files_to_wav(src_paths_by_channel, dst_path): if len(src_paths_by_channel) == 0: return # Eliminate channels with no blocks temp = [] for c in src_paths_by_channel: if len(c) != 0: temp.append(c) src_paths_by_channel = temp print("Converting blocks ", src_paths_by_channel) # Concatenate a bunch of .au block files into a single WAV file with open(dst_path, 'wb') as f: w = None nchannels = len(src_paths_by_channel) # For each block for block_index in range(len(src_paths_by_channel[0])): samples_by_channel = [] # Process each corrsponding channel for that block for channel in range(nchannels): src_paths = src_paths_by_channel[channel] if block_index >= len(src_paths): # That block doesn't have data on each channel... samples_by_channel.append([]) continue au = load_au_file(src_paths[block_index]) samples = au['sample_data'] if au['channels'] != 1: # TODO Deal with this eventually... # As far as I've seen, Audacity actually saves stereo blocks as separate mono .au files. WHY?? print("ERROR: I didn't expect .au files to have 2 channels " "(at least my experience so far has shown they were always mono)") return 0 # Make sure it ends up in the encoding we want if au['encoding'] == AU_SAMPLE_FORMAT_FLOAT: for i, v in enumerate(samples): # We want 16-bit PCM samples[i] = int(v * 32767.0) elif au['encoding'] == AU_SAMPLE_FORMAT_24: print("ERROR: 24 bits not supported") return elif au['encoding'] == AU_SAMPLE_FORMAT_16: pass # Already OK else: print("ERROR: Unknown .au encoding: ", au['encoding']) return 0 if w is None: w = WavWriter(f, au['sample_rate'], nchannels, 16) elif w.sample_rate != au['sample_rate']: print("ERROR: sample rate differs in one of the .au files I wanted to concatenate into one .wav") # TODO Resample, or return multiple files and split the clip... break
samples_by_channel.append(samples) w.append_multichannel_samples(samples_by_channel) w.finalize() return 0 if w is None else w.samples_count def load_audacity_project(fpath): root = ET.parse(fpath).getroot() rate = int(float(root.attrib["rate"])) name = root.attrib['projname'] ns = { 'ns': 'http://audacity.sourceforge.net/xml/' } data_dir = os.path.splitext(fpath)[0] + '_data' if not os.path.isdir(data_dir): data_dir = "" def unescape(s): return html.unescape(s) output = { 'rate': rate, 'name': unescape(name), 'data_dir': data_dir, 'tracks': [] } for project_item in root: tag = project_item.tag.split('}')[1] if tag == 'wavetrack': o_track = { 'name': unescape(project_item.attrib['name']), 'channel': int(project_item.attrib['channel']), 'linked': True if project_item.attrib['linked'] == '1' else False, 'mute': True if project_item.attrib['mute'] == '1' else False, 'solo': True if project_item.attrib['solo'] == '1' else False, 'rate': int(project_item.attrib['rate']), 'gain': float(project_item.attrib['gain']), 'pan': float(project_item.attrib['pan']), 'color_index': int(project_item.attrib['colorindex']), 'clips': [] } output['tracks'].append(o_track) waveclips = project_item.findall('ns:waveclip', ns) for waveclip in waveclips: o_clip = { 'offset': float(waveclip.attrib['offset']), 'color_index': int(waveclip.attrib['colorindex']), } o_track['clips'].append(o_clip) sequence = waveclip.findall('ns:sequence', ns)[0] o_sequence = { 'max_samples': int(sequence.attrib['maxsamples']), 'sample_format': int(sequence.attrib['sampleformat']), 'numsamples': int(sequence.attrib['numsamples']), 'blocks': [] } o_clip['sequence'] = o_sequence for waveblock in sequence.findall('ns:waveblock', ns): waveblock_start = int(waveblock.attrib['start']) for block in waveblock: btag = block.tag.split('}')[1] if btag == 'simpleblockfile': o_sequence['blocks'].append({ 'type': btag, 'start': waveblock_start, 'len': int(block.attrib['len']), 'filename': unescape(block.attrib['filename']), 'min': float(block.attrib['min']), 'max': float(block.attrib['max']), 'rms': float(block.attrib['rms']), }) elif btag == 'pcmaliasblockfile': o_sequence['blocks'].append({ 'type': btag, 'start': waveblock_start, 'len': int(block.attrib['aliaslen']), 'file_start': int(block.attrib['aliasstart']), 'filename': unescape(block.attrib['aliasfile']), 'summary_file': block.attrib['summaryfile'], 'channel': int(block.attrib['aliaschannel']), 'min': float(block.attrib['min']), 'max': float(block.attrib['max']), 'rms': float(block.attrib['rms']) }) elif btag == 'silentblockfile': o_sequence['blocks'].append({ 'type': btag, 'len': int(block.attrib['len']) }) else: print("WARNING: Unknown block type: '{0}'".format(btag)) envelope = waveclip.findall('ns:envelope', ns)[0] points = [] for point in envelope.findall('ns:controlpoint', ns): points.append({ 't': float(point.attrib['t']), 'val': float(point.attrib['val']) }) o_clip['envelope'] = { 'points': points } return output def convert_au_files_from_audacity_project(project, target_dir): # This is where most of the conversion happens. indexed_files = {} if project['data_dir'] != "": # Audacity saves its media files under a nested hierarchy,
random_line_split
aup2rpp.py
: def __init__(self, f, sample_rate, channels, bits_per_sample): self.f = f self.sample_rate = sample_rate self.channels = channels self.bits_per_sample = bits_per_sample self.finalized = False self.samples_count = 0 self.fmt_chunk_size = 2 + 2 + 4 + 4 + 2 + 2 self.initial_fpos = f.tell() # Leave blank header size, we'll write it once all audio has been written. # Go straight to the offset where we will write samples riff_header_size = 8 riff_chunk_size_without_data = 4 + (8 + self.fmt_chunk_size) + 8 + 0 f.write(bytearray(riff_header_size + riff_chunk_size_without_data)) self.data_fpos = f.tell() def append_multichannel_samples(self, sample_data_per_channel): assert not self.finalized assert self.channels == len(sample_data_per_channel) nchannels = self.channels if nchannels == 1: # We can take a shortcut interleaved_sample_data = sample_data_per_channel[0] max_sample_count = len(interleaved_sample_data) else: # Get max channel length max_sample_count = 0 for sample_data in sample_data_per_channel: if len(sample_data) > max_sample_count: if max_sample_count != 0: # Ew, we had to adjust maximum twice print("WARNING: appending multichannel sample data with different amount of samples!") max_sample_count = len(sample_data) # Make sure all channels have the same size for sample_data in sample_data_per_channel: if len(sample_data) > max_sample_count: # Damn, where is resize(n)? del sample_data[-(len(sample_data) - max_sample_count):] else: while len(sample_data) < max_sample_count: sample_data.append(0) # Interleave interleaved_sample_data = [0] * (max_sample_count * nchannels) for channel, sample_data in enumerate(sample_data_per_channel): i = channel for v in sample_data: interleaved_sample_data[i] = v i += nchannels self.append_interleaved_samples(interleaved_sample_data) def append_interleaved_samples(self, sample_data): assert not self.finalized nsamples = len(sample_data) // self.channels assert nsamples * self.channels == len(sample_data) sfc = 'h' if self.bits_per_sample == 32: sfc = 'i' f = self.f for v in sample_data: f.write(struct.pack(sfc, v)) self.samples_count += nsamples def finalize(self): assert not self.finalized f = self.f end = f.tell() data_chunk_size = f.tell() - self.data_fpos f.seek(self.initial_fpos) assert data_chunk_size == (self.samples_count * self.channels * self.bits_per_sample // 8) # "WAVE" letters + two FourCC+size headers and their chunk size. # Does not include the size of the top-level header "RIFF"+size. riff_chunk_size = 4 + (8 + self.fmt_chunk_size) + (8 + data_chunk_size) f.write(b'RIFF') f.write(struct.pack('I', riff_chunk_size)) f.write(b'WAVE') #wave_chunk_size = ??? #f.write(struct.pack('I', wave_chunk_size)) # ---------- f.write(b'fmt ') f.write(struct.pack('I', self.fmt_chunk_size)) # Format # PCM = 1 (i.e. Linear quantization) Values other than 1 indicate some form of compression. f.write(struct.pack('H', 1)) f.write(struct.pack('H', self.channels)) f.write(struct.pack('I', self.sample_rate)) # SampleRate * NumChannels * BitsPerSample/8 byte_rate = self.sample_rate * self.channels * self.bits_per_sample // 8 f.write(struct.pack('I', byte_rate)) # NumChannels * BitsPerSample/8 block_align = self.channels * self.bits_per_sample // 8 f.write(struct.pack('H', block_align)) # 8 bits = 8, 16 bits = 16, etc. f.write(struct.pack('H', self.bits_per_sample)) f.write(b'data') f.write(struct.pack('I', data_chunk_size)) # And what follows is what we wrote before self.finalized = True # Legacy shortcut # def write_wav_file(fpath, sample_rate, channels, bits_per_sample, sample_data): # with open(fpath, 'wb') as f: # w = WavWriter(f, sample_rate, channels, bits_per_sample) # w.append_samples(sample_data) # w.finalize() def convert_au_files_to_wav(src_paths_by_channel, dst_path): if len(src_paths_by_channel) == 0: return # Eliminate channels with no blocks temp = [] for c in src_paths_by_channel: if len(c) != 0: temp.append(c) src_paths_by_channel = temp print("Converting blocks ", src_paths_by_channel) # Concatenate a bunch of .au block files into a single WAV file with open(dst_path, 'wb') as f: w = None nchannels = len(src_paths_by_channel) # For each block for block_index in range(len(src_paths_by_channel[0])): samples_by_channel = [] # Process each corrsponding channel for that block for channel in range(nchannels): src_paths = src_paths_by_channel[channel] if block_index >= len(src_paths): # That block doesn't have data on each channel... samples_by_channel.append([]) continue au = load_au_file(src_paths[block_index]) samples = au['sample_data'] if au['channels'] != 1: # TODO Deal with this eventually... # As far as I've seen, Audacity actually saves stereo blocks as separate mono .au files. WHY?? print("ERROR: I didn't expect .au files to have 2 channels " "(at least my experience so far has shown they were always mono)") return 0 # Make sure it ends up in the encoding we want if au['encoding'] == AU_SAMPLE_FORMAT_FLOAT: for i, v in enumerate(samples): # We want 16-bit PCM samples[i] = int(v * 32767.0) elif au['encoding'] == AU_SAMPLE_FORMAT_24: print("ERROR: 24 bits not supported") return elif au['encoding'] == AU_SAMPLE_FORMAT_16: pass # Already OK else: print("ERROR: Unknown .au encoding: ", au['encoding']) return 0 if w is None: w = WavWriter(f, au['sample_rate'], nchannels, 16) elif w.sample_rate != au['sample_rate']: print("ERROR: sample rate differs in one of the .au files I wanted to concatenate into one .wav") # TODO Resample, or return multiple files and split the clip... break samples_by_channel.append(samples) w.append_multichannel_samples(samples_by_channel) w.finalize() return 0 if w is None else w.samples_count def load_audacity_project(fpath): root = ET.parse(fpath).getroot() rate = int(float(root.attrib["rate"])) name = root.attrib['projname'] ns = { 'ns': 'http://audacity.sourceforge.net/xml/' } data_dir = os.path.splitext(fpath)[0] + '_data' if not os.path.isdir(data_dir): data_dir = "" def unescape(s): return html.unescape(s) output = { 'rate': rate, 'name': unescape(name), 'data_dir': data_dir, 'tracks': [] } for project_item in root: tag = project_item.tag.split('}')[1] if tag == 'wavetrack': o_track = { 'name': unescape(project_item.attrib['name']), 'channel': int(project_item.attrib['channel']), 'linked': True if project_item.attrib['linked'] == '1' else False, 'mute': True if project_item.attrib['mute'] == '1' else False, 'solo': True if project_item.attrib['solo'] == '1' else False, 'rate': int(project_item.attrib['rate']), 'gain': float(project_item.attrib['gain']), 'pan': float(project_item.attrib['pan']), 'color_index': int(project_item.attrib['colorindex']), 'clips': [] } output['tracks'].append(o_track) waveclips = project_item.findall('ns:waveclip', ns) for waveclip in waveclips: o_clip = { 'offset': float(w
WavWriter
identifier_name
ipfs.go
() operation TempDir string `json:"temp_dir,omitempty"` // Datastore config DataStore json.RawMessage `json:"datastore,omitempty"` // Address config - same format as ipfs addresses config Addresses json.RawMessage `json:"addresses,omitempty"` // Private network flag, indicates will have to generate swarm.key and // put it into the repo path // TODO should this be the actual swarm key, or could be a file to load // or the key used to access vault or some other kind of secret store. // The key should be writen to file swarm.key in the ipfs repo path PrivateNetwork bool `json:"private_network,omitempty"` // The storage strategy 'fs' (filesystem) or 'os' (object store) // defaults to 'os' object store. //StorageType string `json:"store,omitempty"` // TODO other raw message types for ipfs specific configuration, eg. Addresses } // Ipfs provides storage interface using IPFS type Ipfs struct { // ipfs core api coreAPI icore.CoreAPI // Configuration config *Config // ipfs node ipfsNode *core.IpfsNode } // New creates a new Ipfs instance func New(cfg *Config) (*Ipfs, error) { ipfs := &Ipfs{config: cfg} // Check root path if err := ensureDir(cfg.RootPath); err != nil { return nil, err } // Check temp dir path if err := ensureDir(cfg.TempDir); err != nil { return nil, err } // Create ipfs node base on configuration if err := ipfs.setupPlugins(cfg.RootPath); err != nil { return nil, err } // Initialize the default ipfs config // Create a config with default options and a 2048 bit key defaultCfg, err := config.Init(ioutil.Discard, 2048) if err != nil { return nil, err } ctx := context.Background() defaultCfg.Bootstrap = cfg.Peers // Addressess if ipfs.config.Addresses != nil { // Parse any overrides for datastore var addr config.Addresses err = json.Unmarshal(ipfs.config.Addresses, &addr) if err != nil { return nil, err } defaultCfg.Addresses = addr } // Write swarm key to repo path // Create a Temporary Repo err = ipfs.createRepo(ctx, cfg.RootPath, defaultCfg) if err != nil { return nil, fmt.Errorf("failed to create ipfs repo: %s", err) } // Create the IPFS node api, err := ipfs.createNode(ctx, cfg.RootPath) if err != nil { return nil, fmt.Errorf("failed to create ipfs node: %s", err) } ipfs.coreAPI = api // connect to configured peers /** err = ipfs.connectToPeers(ctx, defaultCfg) // TODO should only log err if err != nil { return nil, fmt.Errorf("failed to connect to bootstrap peers: %v", err) } */ // Create the storage strategy return ipfs, nil } // NodeAddr formats and returns the node identifier for the ipfs node func (fs *Ipfs) NodeAddr() string { p := peer.AddrInfo{ ID: fs.ipfsNode.Identity, Addrs: fs.ipfsNode.PeerHost.Addrs(), } addr, err := peer.AddrInfoToP2pAddrs(&p) if err != nil { return "" } if len(addr) <= 0 { return "" } return addr[0].String() } // ensureDir ensures directory at path exist if not creates it. func ensureDir(path string) (err error) { if _, err = os.Stat(path); os.IsNotExist(err)
return err } // StorageInterface impl // Get retrieves object at path and returns as a os.File instance // path should be ipfs cid. Caller should close file when done func (fs *Ipfs) Get(path string) (f *os.File, err error) { // Create output filename from the CID path string var fname string fname, err = fs.makeFilename(path) if err != nil { return } // Return file if exist since content is same if _, err = os.Stat(fname); os.IsExist(err) { return os.Open(fname) } p := ipath.New(path) unixfs := fs.coreAPI.Unixfs() node, err := unixfs.Get(context.Background(), p) if err != nil { return nil, err } // Write content to filesystem if err = files.WriteTo(node, fname); err != nil { return nil, err } return os.Open(fname) } // GetStream provides a stream for the file at path which should be CID string func (fs *Ipfs) GetStream(path string) (io.ReadCloser, error) { p := ipath.New(path) unixfs := fs.coreAPI.Unixfs() node, err := unixfs.Get(context.Background(), p) if err != nil { return nil, err } // node should be files.File file, ok := node.(files.File) if !ok { return nil, fmt.Errorf("path is not a file: '%s'", path) } return file, nil } // Put implies adding file to ipfs. If reader is nil then assume path references // the file or directory to add. The file is pinned to prevent GC, when deleted the // pin is removed. func (fs *Ipfs) Put(path string, reader io.Reader) (*oss.Object, error) { // The ipfs file var node files.Node if reader == nil { st, err := os.Stat(path) if err != nil { return nil, err } node, err = files.NewSerialFile(path, false, st) if err != nil { return nil, err } } else { node = files.NewReaderFile(reader) } res, err := fs.coreAPI.Unixfs().Add(context.Background(), node) if err != nil { return nil, err } // Pin the file p := res.String() now := time.Now() ipath := ipath.New(p) err = fs.coreAPI.Pin().Add(context.Background(), ipath) return &oss.Object{ Path: p, Name: strings.Split(p, "/")[2], LastModified: &now, StorageInterface: fs, }, err } // Delete removes pinned path so it maybe GC. path should be the // CID to remove func (fs *Ipfs) Delete(path string) error { // Remoe file if on disk and unpinn if fname, err := fs.makeFilename(path); err == nil { os.Remove(fname) } ipath := ipath.New(path) return fs.coreAPI.Pin().Rm(context.Background(), ipath) } // List the files at directory path (path should be ipfs cid for directory) func (fs *Ipfs) List(path string) ([]*oss.Object, error) { dir := ipath.New(path) entries, err := fs.coreAPI.Unixfs().Ls(context.Background(), dir) if err != nil { return nil, err } dl := make([]*oss.Object, 0) now := time.Now() loop: for { select { case entry, ok := <-entries: if !ok { break loop } var n string p := entry.Cid.String() if strings.HasPrefix(p, "/ipfs/") { n = strings.Split(p, "/")[2] } else { n = p p = "/ipfs/" + p } dl = append(dl, &oss.Object{ Path: p, Name: n, LastModified: &now, StorageInterface: fs, }) } } return dl, nil } // GetURL no-op func (fs *Ipfs) GetURL(path string) (string, error) { return path, nil } // GetEndpoint no-op func (fs *Ipfs) GetEndpoint() string { return "/ipfs" } // Creates an IPFS node and returns its coreAPI func (fs *Ipfs) createNode(ctx context.Context, repoPath string) (icore.CoreAPI, error) { // Open the repo repo, err := fsrepo.Open(repoPath) if err != nil { return nil, err } // Construct the node nodeOptions := &core.BuildCfg{ Online: true, // This option sets the node to be a full DHT node // (both fetching and storing DHT Records) Routing: libp2p.DHTOption, // Routing: libp2p.DHTClientOption, // This option sets the node to be a client DHT node (only fetching records) Repo: repo, } node, err := core.NewNode(ctx
{ // Try to make 0700 if err = os.MkdirAll(path, os.ModePerm); err != nil { return fmt.Errorf("failed to create root dir: %s", path) } }
conditional_block
ipfs.go
Get() operation TempDir string `json:"temp_dir,omitempty"` // Datastore config DataStore json.RawMessage `json:"datastore,omitempty"` // Address config - same format as ipfs addresses config Addresses json.RawMessage `json:"addresses,omitempty"` // Private network flag, indicates will have to generate swarm.key and // put it into the repo path // TODO should this be the actual swarm key, or could be a file to load // or the key used to access vault or some other kind of secret store. // The key should be writen to file swarm.key in the ipfs repo path PrivateNetwork bool `json:"private_network,omitempty"` // The storage strategy 'fs' (filesystem) or 'os' (object store) // defaults to 'os' object store. //StorageType string `json:"store,omitempty"` // TODO other raw message types for ipfs specific configuration, eg. Addresses } // Ipfs provides storage interface using IPFS type Ipfs struct { // ipfs core api coreAPI icore.CoreAPI // Configuration config *Config // ipfs node ipfsNode *core.IpfsNode } // New creates a new Ipfs instance func New(cfg *Config) (*Ipfs, error) { ipfs := &Ipfs{config: cfg}
} // Check temp dir path if err := ensureDir(cfg.TempDir); err != nil { return nil, err } // Create ipfs node base on configuration if err := ipfs.setupPlugins(cfg.RootPath); err != nil { return nil, err } // Initialize the default ipfs config // Create a config with default options and a 2048 bit key defaultCfg, err := config.Init(ioutil.Discard, 2048) if err != nil { return nil, err } ctx := context.Background() defaultCfg.Bootstrap = cfg.Peers // Addressess if ipfs.config.Addresses != nil { // Parse any overrides for datastore var addr config.Addresses err = json.Unmarshal(ipfs.config.Addresses, &addr) if err != nil { return nil, err } defaultCfg.Addresses = addr } // Write swarm key to repo path // Create a Temporary Repo err = ipfs.createRepo(ctx, cfg.RootPath, defaultCfg) if err != nil { return nil, fmt.Errorf("failed to create ipfs repo: %s", err) } // Create the IPFS node api, err := ipfs.createNode(ctx, cfg.RootPath) if err != nil { return nil, fmt.Errorf("failed to create ipfs node: %s", err) } ipfs.coreAPI = api // connect to configured peers /** err = ipfs.connectToPeers(ctx, defaultCfg) // TODO should only log err if err != nil { return nil, fmt.Errorf("failed to connect to bootstrap peers: %v", err) } */ // Create the storage strategy return ipfs, nil } // NodeAddr formats and returns the node identifier for the ipfs node func (fs *Ipfs) NodeAddr() string { p := peer.AddrInfo{ ID: fs.ipfsNode.Identity, Addrs: fs.ipfsNode.PeerHost.Addrs(), } addr, err := peer.AddrInfoToP2pAddrs(&p) if err != nil { return "" } if len(addr) <= 0 { return "" } return addr[0].String() } // ensureDir ensures directory at path exist if not creates it. func ensureDir(path string) (err error) { if _, err = os.Stat(path); os.IsNotExist(err) { // Try to make 0700 if err = os.MkdirAll(path, os.ModePerm); err != nil { return fmt.Errorf("failed to create root dir: %s", path) } } return err } // StorageInterface impl // Get retrieves object at path and returns as a os.File instance // path should be ipfs cid. Caller should close file when done func (fs *Ipfs) Get(path string) (f *os.File, err error) { // Create output filename from the CID path string var fname string fname, err = fs.makeFilename(path) if err != nil { return } // Return file if exist since content is same if _, err = os.Stat(fname); os.IsExist(err) { return os.Open(fname) } p := ipath.New(path) unixfs := fs.coreAPI.Unixfs() node, err := unixfs.Get(context.Background(), p) if err != nil { return nil, err } // Write content to filesystem if err = files.WriteTo(node, fname); err != nil { return nil, err } return os.Open(fname) } // GetStream provides a stream for the file at path which should be CID string func (fs *Ipfs) GetStream(path string) (io.ReadCloser, error) { p := ipath.New(path) unixfs := fs.coreAPI.Unixfs() node, err := unixfs.Get(context.Background(), p) if err != nil { return nil, err } // node should be files.File file, ok := node.(files.File) if !ok { return nil, fmt.Errorf("path is not a file: '%s'", path) } return file, nil } // Put implies adding file to ipfs. If reader is nil then assume path references // the file or directory to add. The file is pinned to prevent GC, when deleted the // pin is removed. func (fs *Ipfs) Put(path string, reader io.Reader) (*oss.Object, error) { // The ipfs file var node files.Node if reader == nil { st, err := os.Stat(path) if err != nil { return nil, err } node, err = files.NewSerialFile(path, false, st) if err != nil { return nil, err } } else { node = files.NewReaderFile(reader) } res, err := fs.coreAPI.Unixfs().Add(context.Background(), node) if err != nil { return nil, err } // Pin the file p := res.String() now := time.Now() ipath := ipath.New(p) err = fs.coreAPI.Pin().Add(context.Background(), ipath) return &oss.Object{ Path: p, Name: strings.Split(p, "/")[2], LastModified: &now, StorageInterface: fs, }, err } // Delete removes pinned path so it maybe GC. path should be the // CID to remove func (fs *Ipfs) Delete(path string) error { // Remoe file if on disk and unpinn if fname, err := fs.makeFilename(path); err == nil { os.Remove(fname) } ipath := ipath.New(path) return fs.coreAPI.Pin().Rm(context.Background(), ipath) } // List the files at directory path (path should be ipfs cid for directory) func (fs *Ipfs) List(path string) ([]*oss.Object, error) { dir := ipath.New(path) entries, err := fs.coreAPI.Unixfs().Ls(context.Background(), dir) if err != nil { return nil, err } dl := make([]*oss.Object, 0) now := time.Now() loop: for { select { case entry, ok := <-entries: if !ok { break loop } var n string p := entry.Cid.String() if strings.HasPrefix(p, "/ipfs/") { n = strings.Split(p, "/")[2] } else { n = p p = "/ipfs/" + p } dl = append(dl, &oss.Object{ Path: p, Name: n, LastModified: &now, StorageInterface: fs, }) } } return dl, nil } // GetURL no-op func (fs *Ipfs) GetURL(path string) (string, error) { return path, nil } // GetEndpoint no-op func (fs *Ipfs) GetEndpoint() string { return "/ipfs" } // Creates an IPFS node and returns its coreAPI func (fs *Ipfs) createNode(ctx context.Context, repoPath string) (icore.CoreAPI, error) { // Open the repo repo, err := fsrepo.Open(repoPath) if err != nil { return nil, err } // Construct the node nodeOptions := &core.BuildCfg{ Online: true, // This option sets the node to be a full DHT node // (both fetching and storing DHT Records) Routing: libp2p.DHTOption, // Routing: libp2p.DHTClientOption, // This option sets the node to be a client DHT node (only fetching records) Repo: repo, } node, err := core.NewNode(ctx, node
// Check root path if err := ensureDir(cfg.RootPath); err != nil { return nil, err
random_line_split
ipfs.go
. //StorageType string `json:"store,omitempty"` // TODO other raw message types for ipfs specific configuration, eg. Addresses } // Ipfs provides storage interface using IPFS type Ipfs struct { // ipfs core api coreAPI icore.CoreAPI // Configuration config *Config // ipfs node ipfsNode *core.IpfsNode } // New creates a new Ipfs instance func New(cfg *Config) (*Ipfs, error) { ipfs := &Ipfs{config: cfg} // Check root path if err := ensureDir(cfg.RootPath); err != nil { return nil, err } // Check temp dir path if err := ensureDir(cfg.TempDir); err != nil { return nil, err } // Create ipfs node base on configuration if err := ipfs.setupPlugins(cfg.RootPath); err != nil { return nil, err } // Initialize the default ipfs config // Create a config with default options and a 2048 bit key defaultCfg, err := config.Init(ioutil.Discard, 2048) if err != nil { return nil, err } ctx := context.Background() defaultCfg.Bootstrap = cfg.Peers // Addressess if ipfs.config.Addresses != nil { // Parse any overrides for datastore var addr config.Addresses err = json.Unmarshal(ipfs.config.Addresses, &addr) if err != nil { return nil, err } defaultCfg.Addresses = addr } // Write swarm key to repo path // Create a Temporary Repo err = ipfs.createRepo(ctx, cfg.RootPath, defaultCfg) if err != nil { return nil, fmt.Errorf("failed to create ipfs repo: %s", err) } // Create the IPFS node api, err := ipfs.createNode(ctx, cfg.RootPath) if err != nil { return nil, fmt.Errorf("failed to create ipfs node: %s", err) } ipfs.coreAPI = api // connect to configured peers /** err = ipfs.connectToPeers(ctx, defaultCfg) // TODO should only log err if err != nil { return nil, fmt.Errorf("failed to connect to bootstrap peers: %v", err) } */ // Create the storage strategy return ipfs, nil } // NodeAddr formats and returns the node identifier for the ipfs node func (fs *Ipfs) NodeAddr() string { p := peer.AddrInfo{ ID: fs.ipfsNode.Identity, Addrs: fs.ipfsNode.PeerHost.Addrs(), } addr, err := peer.AddrInfoToP2pAddrs(&p) if err != nil { return "" } if len(addr) <= 0 { return "" } return addr[0].String() } // ensureDir ensures directory at path exist if not creates it. func ensureDir(path string) (err error) { if _, err = os.Stat(path); os.IsNotExist(err) { // Try to make 0700 if err = os.MkdirAll(path, os.ModePerm); err != nil { return fmt.Errorf("failed to create root dir: %s", path) } } return err } // StorageInterface impl // Get retrieves object at path and returns as a os.File instance // path should be ipfs cid. Caller should close file when done func (fs *Ipfs) Get(path string) (f *os.File, err error) { // Create output filename from the CID path string var fname string fname, err = fs.makeFilename(path) if err != nil { return } // Return file if exist since content is same if _, err = os.Stat(fname); os.IsExist(err) { return os.Open(fname) } p := ipath.New(path) unixfs := fs.coreAPI.Unixfs() node, err := unixfs.Get(context.Background(), p) if err != nil { return nil, err } // Write content to filesystem if err = files.WriteTo(node, fname); err != nil { return nil, err } return os.Open(fname) } // GetStream provides a stream for the file at path which should be CID string func (fs *Ipfs) GetStream(path string) (io.ReadCloser, error) { p := ipath.New(path) unixfs := fs.coreAPI.Unixfs() node, err := unixfs.Get(context.Background(), p) if err != nil { return nil, err } // node should be files.File file, ok := node.(files.File) if !ok { return nil, fmt.Errorf("path is not a file: '%s'", path) } return file, nil } // Put implies adding file to ipfs. If reader is nil then assume path references // the file or directory to add. The file is pinned to prevent GC, when deleted the // pin is removed. func (fs *Ipfs) Put(path string, reader io.Reader) (*oss.Object, error) { // The ipfs file var node files.Node if reader == nil { st, err := os.Stat(path) if err != nil { return nil, err } node, err = files.NewSerialFile(path, false, st) if err != nil { return nil, err } } else { node = files.NewReaderFile(reader) } res, err := fs.coreAPI.Unixfs().Add(context.Background(), node) if err != nil { return nil, err } // Pin the file p := res.String() now := time.Now() ipath := ipath.New(p) err = fs.coreAPI.Pin().Add(context.Background(), ipath) return &oss.Object{ Path: p, Name: strings.Split(p, "/")[2], LastModified: &now, StorageInterface: fs, }, err } // Delete removes pinned path so it maybe GC. path should be the // CID to remove func (fs *Ipfs) Delete(path string) error { // Remoe file if on disk and unpinn if fname, err := fs.makeFilename(path); err == nil { os.Remove(fname) } ipath := ipath.New(path) return fs.coreAPI.Pin().Rm(context.Background(), ipath) } // List the files at directory path (path should be ipfs cid for directory) func (fs *Ipfs) List(path string) ([]*oss.Object, error) { dir := ipath.New(path) entries, err := fs.coreAPI.Unixfs().Ls(context.Background(), dir) if err != nil { return nil, err } dl := make([]*oss.Object, 0) now := time.Now() loop: for { select { case entry, ok := <-entries: if !ok { break loop } var n string p := entry.Cid.String() if strings.HasPrefix(p, "/ipfs/") { n = strings.Split(p, "/")[2] } else { n = p p = "/ipfs/" + p } dl = append(dl, &oss.Object{ Path: p, Name: n, LastModified: &now, StorageInterface: fs, }) } } return dl, nil } // GetURL no-op func (fs *Ipfs) GetURL(path string) (string, error) { return path, nil } // GetEndpoint no-op func (fs *Ipfs) GetEndpoint() string { return "/ipfs" } // Creates an IPFS node and returns its coreAPI func (fs *Ipfs) createNode(ctx context.Context, repoPath string) (icore.CoreAPI, error) { // Open the repo repo, err := fsrepo.Open(repoPath) if err != nil { return nil, err } // Construct the node nodeOptions := &core.BuildCfg{ Online: true, // This option sets the node to be a full DHT node // (both fetching and storing DHT Records) Routing: libp2p.DHTOption, // Routing: libp2p.DHTClientOption, // This option sets the node to be a client DHT node (only fetching records) Repo: repo, } node, err := core.NewNode(ctx, nodeOptions) if err != nil { return nil, err } fs.ipfsNode = node // Attach the Core API to the constructed node return coreapi.NewCoreAPI(node) } func (fs *Ipfs) setupPlugins(path string) error
{ // Load any external plugins if available plugins, err := loader.NewPluginLoader(path) if err != nil { return fmt.Errorf("error loading plugins: %s", err) } // Load preloaded and external plugins if err := plugins.Initialize(); err != nil { return fmt.Errorf("error initializing plugins: %s", err) } if err := plugins.Inject(); err != nil { // Dont fail on Inject() // return fmt.Errorf("error initializing plugins: %s", err) } return nil }
identifier_body
ipfs.go
Get() operation TempDir string `json:"temp_dir,omitempty"` // Datastore config DataStore json.RawMessage `json:"datastore,omitempty"` // Address config - same format as ipfs addresses config Addresses json.RawMessage `json:"addresses,omitempty"` // Private network flag, indicates will have to generate swarm.key and // put it into the repo path // TODO should this be the actual swarm key, or could be a file to load // or the key used to access vault or some other kind of secret store. // The key should be writen to file swarm.key in the ipfs repo path PrivateNetwork bool `json:"private_network,omitempty"` // The storage strategy 'fs' (filesystem) or 'os' (object store) // defaults to 'os' object store. //StorageType string `json:"store,omitempty"` // TODO other raw message types for ipfs specific configuration, eg. Addresses } // Ipfs provides storage interface using IPFS type Ipfs struct { // ipfs core api coreAPI icore.CoreAPI // Configuration config *Config // ipfs node ipfsNode *core.IpfsNode } // New creates a new Ipfs instance func New(cfg *Config) (*Ipfs, error) { ipfs := &Ipfs{config: cfg} // Check root path if err := ensureDir(cfg.RootPath); err != nil { return nil, err } // Check temp dir path if err := ensureDir(cfg.TempDir); err != nil { return nil, err } // Create ipfs node base on configuration if err := ipfs.setupPlugins(cfg.RootPath); err != nil { return nil, err } // Initialize the default ipfs config // Create a config with default options and a 2048 bit key defaultCfg, err := config.Init(ioutil.Discard, 2048) if err != nil { return nil, err } ctx := context.Background() defaultCfg.Bootstrap = cfg.Peers // Addressess if ipfs.config.Addresses != nil { // Parse any overrides for datastore var addr config.Addresses err = json.Unmarshal(ipfs.config.Addresses, &addr) if err != nil { return nil, err } defaultCfg.Addresses = addr } // Write swarm key to repo path // Create a Temporary Repo err = ipfs.createRepo(ctx, cfg.RootPath, defaultCfg) if err != nil { return nil, fmt.Errorf("failed to create ipfs repo: %s", err) } // Create the IPFS node api, err := ipfs.createNode(ctx, cfg.RootPath) if err != nil { return nil, fmt.Errorf("failed to create ipfs node: %s", err) } ipfs.coreAPI = api // connect to configured peers /** err = ipfs.connectToPeers(ctx, defaultCfg) // TODO should only log err if err != nil { return nil, fmt.Errorf("failed to connect to bootstrap peers: %v", err) } */ // Create the storage strategy return ipfs, nil } // NodeAddr formats and returns the node identifier for the ipfs node func (fs *Ipfs) NodeAddr() string { p := peer.AddrInfo{ ID: fs.ipfsNode.Identity, Addrs: fs.ipfsNode.PeerHost.Addrs(), } addr, err := peer.AddrInfoToP2pAddrs(&p) if err != nil { return "" } if len(addr) <= 0 { return "" } return addr[0].String() } // ensureDir ensures directory at path exist if not creates it. func ensureDir(path string) (err error) { if _, err = os.Stat(path); os.IsNotExist(err) { // Try to make 0700 if err = os.MkdirAll(path, os.ModePerm); err != nil { return fmt.Errorf("failed to create root dir: %s", path) } } return err } // StorageInterface impl // Get retrieves object at path and returns as a os.File instance // path should be ipfs cid. Caller should close file when done func (fs *Ipfs) Get(path string) (f *os.File, err error) { // Create output filename from the CID path string var fname string fname, err = fs.makeFilename(path) if err != nil { return } // Return file if exist since content is same if _, err = os.Stat(fname); os.IsExist(err) { return os.Open(fname) } p := ipath.New(path) unixfs := fs.coreAPI.Unixfs() node, err := unixfs.Get(context.Background(), p) if err != nil { return nil, err } // Write content to filesystem if err = files.WriteTo(node, fname); err != nil { return nil, err } return os.Open(fname) } // GetStream provides a stream for the file at path which should be CID string func (fs *Ipfs) GetStream(path string) (io.ReadCloser, error) { p := ipath.New(path) unixfs := fs.coreAPI.Unixfs() node, err := unixfs.Get(context.Background(), p) if err != nil { return nil, err } // node should be files.File file, ok := node.(files.File) if !ok { return nil, fmt.Errorf("path is not a file: '%s'", path) } return file, nil } // Put implies adding file to ipfs. If reader is nil then assume path references // the file or directory to add. The file is pinned to prevent GC, when deleted the // pin is removed. func (fs *Ipfs) Put(path string, reader io.Reader) (*oss.Object, error) { // The ipfs file var node files.Node if reader == nil { st, err := os.Stat(path) if err != nil { return nil, err } node, err = files.NewSerialFile(path, false, st) if err != nil { return nil, err } } else { node = files.NewReaderFile(reader) } res, err := fs.coreAPI.Unixfs().Add(context.Background(), node) if err != nil { return nil, err } // Pin the file p := res.String() now := time.Now() ipath := ipath.New(p) err = fs.coreAPI.Pin().Add(context.Background(), ipath) return &oss.Object{ Path: p, Name: strings.Split(p, "/")[2], LastModified: &now, StorageInterface: fs, }, err } // Delete removes pinned path so it maybe GC. path should be the // CID to remove func (fs *Ipfs) Delete(path string) error { // Remoe file if on disk and unpinn if fname, err := fs.makeFilename(path); err == nil { os.Remove(fname) } ipath := ipath.New(path) return fs.coreAPI.Pin().Rm(context.Background(), ipath) } // List the files at directory path (path should be ipfs cid for directory) func (fs *Ipfs) List(path string) ([]*oss.Object, error) { dir := ipath.New(path) entries, err := fs.coreAPI.Unixfs().Ls(context.Background(), dir) if err != nil { return nil, err } dl := make([]*oss.Object, 0) now := time.Now() loop: for { select { case entry, ok := <-entries: if !ok { break loop } var n string p := entry.Cid.String() if strings.HasPrefix(p, "/ipfs/") { n = strings.Split(p, "/")[2] } else { n = p p = "/ipfs/" + p } dl = append(dl, &oss.Object{ Path: p, Name: n, LastModified: &now, StorageInterface: fs, }) } } return dl, nil } // GetURL no-op func (fs *Ipfs)
(path string) (string, error) { return path, nil } // GetEndpoint no-op func (fs *Ipfs) GetEndpoint() string { return "/ipfs" } // Creates an IPFS node and returns its coreAPI func (fs *Ipfs) createNode(ctx context.Context, repoPath string) (icore.CoreAPI, error) { // Open the repo repo, err := fsrepo.Open(repoPath) if err != nil { return nil, err } // Construct the node nodeOptions := &core.BuildCfg{ Online: true, // This option sets the node to be a full DHT node // (both fetching and storing DHT Records) Routing: libp2p.DHTOption, // Routing: libp2p.DHTClientOption, // This option sets the node to be a client DHT node (only fetching records) Repo: repo, } node, err := core.NewNode(ctx
GetURL
identifier_name
tree.py
(self, nodes: List[str]=None, root: bool=True): if nodes is None: nodes = [] if root: nodes = self.tree Tree.print_node(nodes) if nodes['class'] == -1: self._print(nodes=nodes['l_node'], root=False) self._print(nodes=nodes['r_node'], root=False) @staticmethod def print_node(node): bs =' ' * node['depth'] * 2 bs2 = '-' * 2 print(bs+'|'+bs2+'*' * 50) print(bs+'|'+bs+node['node_str']) print(bs+'|'+bs+'Depth:', node['depth']) print(bs+'|'+bs+'n samples:', node['n']) if not node['terminal']: print(bs+'|'+bs+'Name: '+node['name']) print(bs+'|'+bs+'Split Value:', node['split_val']) print(bs+'|'+bs+'Gini coeff:', node['gini']) print(bs+'|'+bs+'Class prop requirement:', node['bias'], '('+node['biasMode']+')') print(bs+'|'+bs+'Prop L:', node['prop_l']) print(bs+'|'+bs+'Prop R:', node['prop_r']) else: print(bs+'|'+bs+'Leaf') print(bs+'|'+bs+node['note']) def fit(self, x, y, debug=False): """ Convert data to matrix if dataframe Recursively create nodes using tree.buildNodes() """ # Set feature names self.set_names(x) # Convert to mats if not x = self.strip_df(x) y = self.strip_df(y) self.tree = Tree.build_nodes(x, y, max_depth=self.params['max_depth'], min_data=self.params['min_data'], dynamic_bias=self.params['dynamic_bias'], debug=debug, names=self.feature_names) return self @staticmethod def build_nodes(x, y, names: List[str], max_depth: int=2, min_data: int=2, dynamic_bias: bool=False, depth: int=0, nom_class: int=-777, bias: float=0.5, d_str: str= 'Root', debug: bool=False): """ Recursively all branches of nodes. Each branch continues adding nodes until a terminal condition is met. :param x: Features. :param y: Labels. :param names: Feature column names. :param max_depth: Max branch depth. Default=2. :param min_data: Min number of observations left to build another node. Default=2. :param dynamic_bias: :param depth: Current depth. :param nom_class: :param bias: :param d_str: String name for node. :param debug: :return: """ if dynamic_bias: bias = Tree.prop(y) ds = 'dynamic' else: if bias == '': ds = 'highest' else: ds = 'static' # Add terminal checks here # If a terminal node, return a node (dict) containing just the class label # This label is set by highest represented label in subset if depth > max_depth: # Too deep: Terminal cla = Tree.high_class(y, bias) node = {'class': cla, 'depth': depth, 'note': 'Max depth reached, class is: '+ str(cla), 'terminal': True, 'n': len(x), 'node_str': d_str} elif x.shape[0] < min_data: if x.shape[0] == 0: # Too few data points: Terminal cla = nom_class else: cla = Tree.high_class(y, bias) node = {'class': cla, 'depth': depth, 'note': f'Too few data points, class is: {cla}', 'terminal': True, 'n': len(x), 'node_str': d_str} # In this case, y will be empty # So use nominal class that will be the opposite of the other side node elif x.shape[1] < 1: # Too few features: Terminal cla = Tree.high_class(y, bias) node = {'class': cla, 'depth': depth, 'note': f'No features remaining, class is: {cla}', 'terminal': True, 'n': len(x), 'node_str': d_str} elif len(np.unique(y)) == 1: # Only one class: Terminal cla = Tree.high_class(y, bias) node = {'class': cla, 'depth': depth, 'note': f'One class at depth, class is: {cla}', 'terminal': True, 'n': len(x), 'node_str': d_str} else: # Not terminal. Build next node. # First find best split to run col_idx, best_x, gini = Tree.get_best_split_all(x, y) # Split into left and right subsets l_idx = (x[:, col_idx] < best_x).squeeze() r_idx = (x[:, col_idx] >= best_x).squeeze() nom_class_l = -999 nom_class_r = -999 if np.sum(l_idx) == 0: nom_class_l = np.int8(not Tree.high_class(y[r_idx], bias)) if np.sum(r_idx) == 0: nom_class_r = np.int8(not Tree.high_class(y[l_idx], bias)) # Build next node, leaving out used feature and data not in this split l_node = Tree.build_nodes(x[l_idx][:, ~col_idx], y[l_idx], max_depth=max_depth, min_data=min_data, depth=depth + 1, nom_class=nom_class_l, dynamic_bias=dynamic_bias, bias=bias, d_str=d_str + '->L', names=[n for ni, n in enumerate(names) if ni != np.argmax(col_idx)]) r_node = Tree.build_nodes(x[r_idx][:, ~col_idx], y[r_idx], max_depth=max_depth, min_data=min_data, depth=depth + 1, nom_class=nom_class_r, dynamic_bias=dynamic_bias, bias=bias, d_str=d_str + '->R', names=[n for ni, n in enumerate(names) if ni != np.argmax(col_idx)]) # Return a full node containing meta/debug data # As this isn't a leaf/terminal node, set class to -1 node = {'name': names[np.argmax(col_idx)], 'n': len(x), 'n_l': np.sum(l_idx), 'n_r': np.sum(r_idx), 'l_idx': l_idx, 'r_idx': r_idx, 'split_val': best_x.squeeze(), 'gini': gini.squeeze(), 'depth': depth, 'l_node': l_node, 'r_node': r_node, 'class': -1, 'prop_l': Tree.prop(y[l_idx]), 'prop_r': Tree.prop(y[r_idx]), 'biasMode': ds, 'bias': bias, 'node_str' : d_str, 'terminal': False} if debug: Tree.print_node(node) return node def predict(self, x) -> np.ndarray: """Predict from tree.""" y_pred = x.apply(Tree._predict, args=(self.tree,), axis=1) return y_pred @staticmethod def _predict(x, mod) -> np.ndarray: # If this is a leaf node, return class if mod['class'] > -1: return mod['class'] # If this isn't a leaf node, check X against split value # and follow tree if x.loc[mod['name']] < mod['split_val']: # If less than split val, go left y_pred = Tree._predict(x, mod['l_node']) else: # If greater than split val, go right y_pred = Tree._predict(x, mod['r_node']) return y_pred @staticmethod def gi(groups: Union[List[int], np.array], classes: Union[List[int], np.array]) -> float: """Calculate Gini.""" groups = np.array(groups) classes = np.array(classes) # For each group sum_p = 0.0 for g in np.unique(groups): # print('G:',g) g_idx = groups == g # Calculate and sum class proportions p = 0.0 # For each class for c in np.unique(classes): # print('C:',c) c_idx = classes[g_idx] == c # Get proportions and square # And sum across classes p += (np.sum(c_idx) / np.sum(g_idx)) ** 2 # print('P:',P) # Weight by size of group # And sum across groups sum_p += (1 - p) * sum(g_idx) / len(g_idx) return sum_p @staticmethod def split(x, y, split
_print
identifier_name
tree.py
def fit(self, x, y, debug=False): """ Convert data to matrix if dataframe Recursively create nodes using tree.buildNodes() """ # Set feature names self.set_names(x) # Convert to mats if not x = self.strip_df(x) y = self.strip_df(y) self.tree = Tree.build_nodes(x, y, max_depth=self.params['max_depth'], min_data=self.params['min_data'], dynamic_bias=self.params['dynamic_bias'], debug=debug, names=self.feature_names) return self @staticmethod def build_nodes(x, y, names: List[str], max_depth: int=2, min_data: int=2, dynamic_bias: bool=False, depth: int=0, nom_class: int=-777, bias: float=0.5, d_str: str= 'Root', debug: bool=False): """ Recursively all branches of nodes. Each branch continues adding nodes until a terminal condition is met. :param x: Features. :param y: Labels. :param names: Feature column names. :param max_depth: Max branch depth. Default=2. :param min_data: Min number of observations left to build another node. Default=2. :param dynamic_bias: :param depth: Current depth. :param nom_class: :param bias: :param d_str: String name for node. :param debug: :return: """ if dynamic_bias: bias = Tree.prop(y) ds = 'dynamic' else: if bias == '': ds = 'highest' else: ds = 'static' # Add terminal checks here # If a terminal node, return a node (dict) containing just the class label # This label is set by highest represented label in subset if depth > max_depth: # Too deep: Terminal cla = Tree.high_class(y, bias) node = {'class': cla, 'depth': depth, 'note': 'Max depth reached, class is: '+ str(cla), 'terminal': True, 'n': len(x), 'node_str': d_str} elif x.shape[0] < min_data: if x.shape[0] == 0: # Too few data points: Terminal cla = nom_class else: cla = Tree.high_class(y, bias) node = {'class': cla, 'depth': depth, 'note': f'Too few data points, class is: {cla}', 'terminal': True, 'n': len(x), 'node_str': d_str} # In this case, y will be empty # So use nominal class that will be the opposite of the other side node elif x.shape[1] < 1: # Too few features: Terminal cla = Tree.high_class(y, bias) node = {'class': cla, 'depth': depth, 'note': f'No features remaining, class is: {cla}', 'terminal': True, 'n': len(x), 'node_str': d_str} elif len(np.unique(y)) == 1: # Only one class: Terminal cla = Tree.high_class(y, bias) node = {'class': cla, 'depth': depth, 'note': f'One class at depth, class is: {cla}', 'terminal': True, 'n': len(x), 'node_str': d_str} else: # Not terminal. Build next node. # First find best split to run col_idx, best_x, gini = Tree.get_best_split_all(x, y) # Split into left and right subsets l_idx = (x[:, col_idx] < best_x).squeeze() r_idx = (x[:, col_idx] >= best_x).squeeze() nom_class_l = -999 nom_class_r = -999 if np.sum(l_idx) == 0: nom_class_l = np.int8(not Tree.high_class(y[r_idx], bias)) if np.sum(r_idx) == 0: nom_class_r = np.int8(not Tree.high_class(y[l_idx], bias)) # Build next node, leaving out used feature and data not in this split l_node = Tree.build_nodes(x[l_idx][:, ~col_idx], y[l_idx], max_depth=max_depth, min_data=min_data, depth=depth + 1, nom_class=nom_class_l, dynamic_bias=dynamic_bias, bias=bias, d_str=d_str + '->L', names=[n for ni, n in enumerate(names) if ni != np.argmax(col_idx)]) r_node = Tree.build_nodes(x[r_idx][:, ~col_idx], y[r_idx], max_depth=max_depth, min_data=min_data, depth=depth + 1, nom_class=nom_class_r, dynamic_bias=dynamic_bias, bias=bias, d_str=d_str + '->R', names=[n for ni, n in enumerate(names) if ni != np.argmax(col_idx)]) # Return a full node containing meta/debug data # As this isn't a leaf/terminal node, set class to -1 node = {'name': names[np.argmax(col_idx)], 'n': len(x), 'n_l': np.sum(l_idx), 'n_r': np.sum(r_idx), 'l_idx': l_idx, 'r_idx': r_idx, 'split_val': best_x.squeeze(), 'gini': gini.squeeze(), 'depth': depth, 'l_node': l_node, 'r_node': r_node, 'class': -1, 'prop_l': Tree.prop(y[l_idx]), 'prop_r': Tree.prop(y[r_idx]), 'biasMode': ds, 'bias': bias, 'node_str' : d_str, 'terminal': False} if debug: Tree.print_node(node) return node def predict(self, x) -> np.ndarray: """Predict from tree.""" y_pred = x.apply(Tree._predict, args=(self.tree,), axis=1) return y_pred @staticmethod def _predict(x, mod) -> np.ndarray: # If this is a leaf node, return class if mod['class'] > -1: return mod['class'] # If this isn't a leaf node, check X against split value # and follow tree if x.loc[mod['name']] < mod['split_val']: # If less than split val, go left y_pred = Tree._predict(x, mod['l_node']) else: # If greater than split val, go right y_pred = Tree._predict(x, mod['r_node']) return y_pred @staticmethod def gi(groups: Union[List[int], np.array], classes: Union[List[int], np.array]) -> float: """Calculate Gini.""" groups = np.array(groups) classes = np.array(classes) # For each group sum_p = 0.0 for g in np.unique(groups): # print('G:',g) g_idx = groups == g # Calculate and sum class proportions p = 0.0 # For each class for c in np.unique(classes): # print('C:',c) c_idx = classes[g_idx] == c # Get proportions and square # And sum across classes p += (np.sum(c_idx) / np.sum(g_idx)) ** 2 # print('P:',P) # Weight by size of group # And sum across groups sum_p += (1 - p) * sum(g_idx) / len(g_idx) return sum_p @staticmethod def split(x, y, split_val) -> float: groups = np.int8(x < split_val) return Tree.gi(groups, y) @staticmethod def get_best_split_all(x, y) -> Tuple[int, float, float]: """ This function calculates all splits on all columns Returns the column index with best split and the values to use """ m = x.shape[1] col_best_gin = np.ones(shape=m
bs =' ' * node['depth'] * 2 bs2 = '-' * 2 print(bs+'|'+bs2+'*' * 50) print(bs+'|'+bs+node['node_str']) print(bs+'|'+bs+'Depth:', node['depth']) print(bs+'|'+bs+'n samples:', node['n']) if not node['terminal']: print(bs+'|'+bs+'Name: '+node['name']) print(bs+'|'+bs+'Split Value:', node['split_val']) print(bs+'|'+bs+'Gini coeff:', node['gini']) print(bs+'|'+bs+'Class prop requirement:', node['bias'], '('+node['biasMode']+')') print(bs+'|'+bs+'Prop L:', node['prop_l']) print(bs+'|'+bs+'Prop R:', node['prop_r']) else: print(bs+'|'+bs+'Leaf') print(bs+'|'+bs+node['note'])
identifier_body
tree.py
bs2 = '-' * 2 print(bs+'|'+bs2+'*' * 50) print(bs+'|'+bs+node['node_str']) print(bs+'|'+bs+'Depth:', node['depth']) print(bs+'|'+bs+'n samples:', node['n']) if not node['terminal']: print(bs+'|'+bs+'Name: '+node['name']) print(bs+'|'+bs+'Split Value:', node['split_val']) print(bs+'|'+bs+'Gini coeff:', node['gini']) print(bs+'|'+bs+'Class prop requirement:', node['bias'], '('+node['biasMode']+')') print(bs+'|'+bs+'Prop L:', node['prop_l']) print(bs+'|'+bs+'Prop R:', node['prop_r']) else: print(bs+'|'+bs+'Leaf') print(bs+'|'+bs+node['note']) def fit(self, x, y, debug=False): """ Convert data to matrix if dataframe Recursively create nodes using tree.buildNodes() """ # Set feature names self.set_names(x) # Convert to mats if not x = self.strip_df(x) y = self.strip_df(y) self.tree = Tree.build_nodes(x, y, max_depth=self.params['max_depth'], min_data=self.params['min_data'], dynamic_bias=self.params['dynamic_bias'], debug=debug, names=self.feature_names) return self @staticmethod def build_nodes(x, y, names: List[str], max_depth: int=2, min_data: int=2, dynamic_bias: bool=False, depth: int=0, nom_class: int=-777, bias: float=0.5, d_str: str= 'Root', debug: bool=False): """ Recursively all branches of nodes. Each branch continues adding nodes until a terminal condition is met. :param x: Features. :param y: Labels. :param names: Feature column names. :param max_depth: Max branch depth. Default=2. :param min_data: Min number of observations left to build another node. Default=2. :param dynamic_bias: :param depth: Current depth. :param nom_class: :param bias: :param d_str: String name for node. :param debug: :return: """ if dynamic_bias: bias = Tree.prop(y) ds = 'dynamic' else: if bias == '': ds = 'highest' else: ds = 'static' # Add terminal checks here # If a terminal node, return a node (dict) containing just the class label # This label is set by highest represented label in subset if depth > max_depth: # Too deep: Terminal cla = Tree.high_class(y, bias) node = {'class': cla, 'depth': depth, 'note': 'Max depth reached, class is: '+ str(cla), 'terminal': True, 'n': len(x), 'node_str': d_str} elif x.shape[0] < min_data: if x.shape[0] == 0: # Too few data points: Terminal cla = nom_class else: cla = Tree.high_class(y, bias) node = {'class': cla, 'depth': depth, 'note': f'Too few data points, class is: {cla}', 'terminal': True, 'n': len(x), 'node_str': d_str} # In this case, y will be empty # So use nominal class that will be the opposite of the other side node elif x.shape[1] < 1: # Too few features: Terminal cla = Tree.high_class(y, bias) node = {'class': cla, 'depth': depth, 'note': f'No features remaining, class is: {cla}', 'terminal': True, 'n': len(x), 'node_str': d_str} elif len(np.unique(y)) == 1: # Only one class: Terminal
'note': f'One class at depth, class is: {cla}', 'terminal': True, 'n': len(x), 'node_str': d_str} else: # Not terminal. Build next node. # First find best split to run col_idx, best_x, gini = Tree.get_best_split_all(x, y) # Split into left and right subsets l_idx = (x[:, col_idx] < best_x).squeeze() r_idx = (x[:, col_idx] >= best_x).squeeze() nom_class_l = -999 nom_class_r = -999 if np.sum(l_idx) == 0: nom_class_l = np.int8(not Tree.high_class(y[r_idx], bias)) if np.sum(r_idx) == 0: nom_class_r = np.int8(not Tree.high_class(y[l_idx], bias)) # Build next node, leaving out used feature and data not in this split l_node = Tree.build_nodes(x[l_idx][:, ~col_idx], y[l_idx], max_depth=max_depth, min_data=min_data, depth=depth + 1, nom_class=nom_class_l, dynamic_bias=dynamic_bias, bias=bias, d_str=d_str + '->L', names=[n for ni, n in enumerate(names) if ni != np.argmax(col_idx)]) r_node = Tree.build_nodes(x[r_idx][:, ~col_idx], y[r_idx], max_depth=max_depth, min_data=min_data, depth=depth + 1, nom_class=nom_class_r, dynamic_bias=dynamic_bias, bias=bias, d_str=d_str + '->R', names=[n for ni, n in enumerate(names) if ni != np.argmax(col_idx)]) # Return a full node containing meta/debug data # As this isn't a leaf/terminal node, set class to -1 node = {'name': names[np.argmax(col_idx)], 'n': len(x), 'n_l': np.sum(l_idx), 'n_r': np.sum(r_idx), 'l_idx': l_idx, 'r_idx': r_idx, 'split_val': best_x.squeeze(), 'gini': gini.squeeze(), 'depth': depth, 'l_node': l_node, 'r_node': r_node, 'class': -1, 'prop_l': Tree.prop(y[l_idx]), 'prop_r': Tree.prop(y[r_idx]), 'biasMode': ds, 'bias': bias, 'node_str' : d_str, 'terminal': False} if debug: Tree.print_node(node) return node def predict(self, x) -> np.ndarray: """Predict from tree.""" y_pred = x.apply(Tree._predict, args=(self.tree,), axis=1) return y_pred @staticmethod def _predict(x, mod) -> np.ndarray: # If this is a leaf node, return class if mod['class'] > -1: return mod['class'] # If this isn't a leaf node, check X against split value # and follow tree if x.loc[mod['name']] < mod['split_val']: # If less than split val, go left y_pred = Tree._predict(x, mod['l_node']) else: # If greater than split val, go right y_pred = Tree._predict(x, mod['r_node']) return y_pred @staticmethod def gi(groups: Union[List[int], np.array], classes: Union[List[int], np.array]) -> float: """Calculate Gini.""" groups = np.array(groups) classes = np.array(classes) # For each group sum_p = 0.0 for g in np.unique(groups): # print('G:',g) g_idx = groups == g # Calculate and sum class proportions p = 0.0 # For each class for c in np.unique(classes): # print('C:',c) c_idx = classes[g_idx] == c # Get proportions and square # And sum across classes p += (np.sum(c_idx) / np.sum(g_idx)) ** 2 # print('P:',P) # Weight by size of group # And sum across groups sum_p += (1 - p) * sum(g_idx) / len(g_idx) return sum_p @staticmethod def split(x, y, split_val) -> float: groups = np.int8(x < split_val) return Tree.gi(groups, y) @staticmethod def get_best_split_all(x, y) -> Tuple[int, float, float]: """ This function calculates all splits on all columns Returns the column index with best split and the values to use """ m = x.shape[1] col_best_gin = np.ones(shape=m) col_best_val = np.ones(shape=m) for c in
cla = Tree.high_class(y, bias) node = {'class': cla, 'depth': depth,
random_line_split
tree.py
2 = '-' * 2 print(bs+'|'+bs2+'*' * 50) print(bs+'|'+bs+node['node_str']) print(bs+'|'+bs+'Depth:', node['depth']) print(bs+'|'+bs+'n samples:', node['n']) if not node['terminal']: print(bs+'|'+bs+'Name: '+node['name']) print(bs+'|'+bs+'Split Value:', node['split_val']) print(bs+'|'+bs+'Gini coeff:', node['gini']) print(bs+'|'+bs+'Class prop requirement:', node['bias'], '('+node['biasMode']+')') print(bs+'|'+bs+'Prop L:', node['prop_l']) print(bs+'|'+bs+'Prop R:', node['prop_r']) else: print(bs+'|'+bs+'Leaf') print(bs+'|'+bs+node['note']) def fit(self, x, y, debug=False): """ Convert data to matrix if dataframe Recursively create nodes using tree.buildNodes() """ # Set feature names self.set_names(x) # Convert to mats if not x = self.strip_df(x) y = self.strip_df(y) self.tree = Tree.build_nodes(x, y, max_depth=self.params['max_depth'], min_data=self.params['min_data'], dynamic_bias=self.params['dynamic_bias'], debug=debug, names=self.feature_names) return self @staticmethod def build_nodes(x, y, names: List[str], max_depth: int=2, min_data: int=2, dynamic_bias: bool=False, depth: int=0, nom_class: int=-777, bias: float=0.5, d_str: str= 'Root', debug: bool=False): """ Recursively all branches of nodes. Each branch continues adding nodes until a terminal condition is met. :param x: Features. :param y: Labels. :param names: Feature column names. :param max_depth: Max branch depth. Default=2. :param min_data: Min number of observations left to build another node. Default=2. :param dynamic_bias: :param depth: Current depth. :param nom_class: :param bias: :param d_str: String name for node. :param debug: :return: """ if dynamic_bias: bias = Tree.prop(y) ds = 'dynamic' else: if bias == '': ds = 'highest' else: ds = 'static' # Add terminal checks here # If a terminal node, return a node (dict) containing just the class label # This label is set by highest represented label in subset if depth > max_depth: # Too deep: Terminal cla = Tree.high_class(y, bias) node = {'class': cla, 'depth': depth, 'note': 'Max depth reached, class is: '+ str(cla), 'terminal': True, 'n': len(x), 'node_str': d_str} elif x.shape[0] < min_data: if x.shape[0] == 0: # Too few data points: Terminal
else: cla = Tree.high_class(y, bias) node = {'class': cla, 'depth': depth, 'note': f'Too few data points, class is: {cla}', 'terminal': True, 'n': len(x), 'node_str': d_str} # In this case, y will be empty # So use nominal class that will be the opposite of the other side node elif x.shape[1] < 1: # Too few features: Terminal cla = Tree.high_class(y, bias) node = {'class': cla, 'depth': depth, 'note': f'No features remaining, class is: {cla}', 'terminal': True, 'n': len(x), 'node_str': d_str} elif len(np.unique(y)) == 1: # Only one class: Terminal cla = Tree.high_class(y, bias) node = {'class': cla, 'depth': depth, 'note': f'One class at depth, class is: {cla}', 'terminal': True, 'n': len(x), 'node_str': d_str} else: # Not terminal. Build next node. # First find best split to run col_idx, best_x, gini = Tree.get_best_split_all(x, y) # Split into left and right subsets l_idx = (x[:, col_idx] < best_x).squeeze() r_idx = (x[:, col_idx] >= best_x).squeeze() nom_class_l = -999 nom_class_r = -999 if np.sum(l_idx) == 0: nom_class_l = np.int8(not Tree.high_class(y[r_idx], bias)) if np.sum(r_idx) == 0: nom_class_r = np.int8(not Tree.high_class(y[l_idx], bias)) # Build next node, leaving out used feature and data not in this split l_node = Tree.build_nodes(x[l_idx][:, ~col_idx], y[l_idx], max_depth=max_depth, min_data=min_data, depth=depth + 1, nom_class=nom_class_l, dynamic_bias=dynamic_bias, bias=bias, d_str=d_str + '->L', names=[n for ni, n in enumerate(names) if ni != np.argmax(col_idx)]) r_node = Tree.build_nodes(x[r_idx][:, ~col_idx], y[r_idx], max_depth=max_depth, min_data=min_data, depth=depth + 1, nom_class=nom_class_r, dynamic_bias=dynamic_bias, bias=bias, d_str=d_str + '->R', names=[n for ni, n in enumerate(names) if ni != np.argmax(col_idx)]) # Return a full node containing meta/debug data # As this isn't a leaf/terminal node, set class to -1 node = {'name': names[np.argmax(col_idx)], 'n': len(x), 'n_l': np.sum(l_idx), 'n_r': np.sum(r_idx), 'l_idx': l_idx, 'r_idx': r_idx, 'split_val': best_x.squeeze(), 'gini': gini.squeeze(), 'depth': depth, 'l_node': l_node, 'r_node': r_node, 'class': -1, 'prop_l': Tree.prop(y[l_idx]), 'prop_r': Tree.prop(y[r_idx]), 'biasMode': ds, 'bias': bias, 'node_str' : d_str, 'terminal': False} if debug: Tree.print_node(node) return node def predict(self, x) -> np.ndarray: """Predict from tree.""" y_pred = x.apply(Tree._predict, args=(self.tree,), axis=1) return y_pred @staticmethod def _predict(x, mod) -> np.ndarray: # If this is a leaf node, return class if mod['class'] > -1: return mod['class'] # If this isn't a leaf node, check X against split value # and follow tree if x.loc[mod['name']] < mod['split_val']: # If less than split val, go left y_pred = Tree._predict(x, mod['l_node']) else: # If greater than split val, go right y_pred = Tree._predict(x, mod['r_node']) return y_pred @staticmethod def gi(groups: Union[List[int], np.array], classes: Union[List[int], np.array]) -> float: """Calculate Gini.""" groups = np.array(groups) classes = np.array(classes) # For each group sum_p = 0.0 for g in np.unique(groups): # print('G:',g) g_idx = groups == g # Calculate and sum class proportions p = 0.0 # For each class for c in np.unique(classes): # print('C:',c) c_idx = classes[g_idx] == c # Get proportions and square # And sum across classes p += (np.sum(c_idx) / np.sum(g_idx)) ** 2 # print('P:',P) # Weight by size of group # And sum across groups sum_p += (1 - p) * sum(g_idx) / len(g_idx) return sum_p @staticmethod def split(x, y, split_val) -> float: groups = np.int8(x < split_val) return Tree.gi(groups, y) @staticmethod def get_best_split_all(x, y) -> Tuple[int, float, float]: """ This function calculates all splits on all columns Returns the column index with best split and the values to use """ m = x.shape[1] col_best_gin = np.ones(shape=m) col_best_val = np.ones(shape=m) for c in
cla = nom_class
conditional_block
opt.rs
recommended) Time Profiler." )] Instruments(AppConfig), } #[derive(Debug, StructOpt)] #[structopt(setting = structopt::clap::AppSettings::TrailingVarArg)] pub(crate) struct AppConfig { /// List available templates #[structopt(short = "l", long)] pub(crate) list_templates: bool, /// Specify the instruments template to run /// /// To see available templates, pass `--list-templates`. #[structopt( short = "t", long = "template", value_name = "TEMPLATE", required_unless = "list-templates" )] pub(crate) template_name: Option<String>, /// Specify package for example/bin/bench /// /// For package that has only one bin, it's the same as `--bin PACKAGE_NAME` #[structopt(short = "p", long, value_name = "NAME")] package: Option<String>, /// Example binary to run #[structopt(long, group = "target", value_name = "NAME")] example: Option<String>, /// Binary to run #[structopt(long, group = "target", value_name = "NAME")] bin: Option<String>, /// Benchmark target to run #[structopt(long, group = "target", value_name = "NAME")] bench: Option<String>, /// Pass --release to cargo #[structopt(long, conflicts_with = "profile")] release: bool, /// Pass --profile NAME to cargo #[structopt(long, value_name = "NAME")] profile: Option<String>, /// Output .trace file to the given path /// /// Defaults to `target/instruments/{name}_{template-name}_{date}.trace`. /// /// If the file already exists, a new Run will be added. #[structopt(short = "o", long = "output", value_name = "PATH", parse(from_os_str))] pub(crate) trace_filepath: Option<PathBuf>, /// Limit recording time to the specified value (in milliseconds) /// /// The program will be terminated after this limit is exceeded. #[structopt(long, value_name = "MILLIS")] pub(crate) time_limit: Option<usize>, /// Open the generated .trace file after profiling /// /// The trace file will open in Xcode Instruments. #[structopt(long, hidden = true)] pub(crate) open: bool, /// Do not open the generated trace file in Instruments.app. #[structopt(long)] pub(crate) no_open: bool, /// Features to pass to cargo. #[structopt(long, value_name = "CARGO-FEATURES")] pub(crate) features: Option<String>, /// Path to Cargo.toml #[structopt(long, value_name = "PATH")] pub(crate) manifest_path: Option<PathBuf>, /// Activate all features for the selected target. #[structopt(long, display_order = 1001)] pub(crate) all_features: bool, /// Do not activate the default features for the selected target #[structopt(long, display_order = 1001)] pub(crate) no_default_features: bool, /// Arguments passed to the target binary. /// /// To pass flags, precede child args with `--`, /// e.g. `cargo instruments -- -t test1.txt --slow-mode`. #[structopt(value_name = "ARGS")] pub(crate) target_args: Vec<String>, } /// Represents the kind of target to profile. #[derive(Debug, PartialEq)] pub(crate) enum Target { Main, Example(String), Bin(String), Bench(String), } /// The package in which to look for the specified target (example/bin/bench) #[derive(Clone, Debug, PartialEq)] pub(crate) enum Package { Default, Package(String), } impl From<Package> for Packages { fn from(p: Package) -> Self { match p { Package::Default => Packages::Default, Package::Package(s) => Packages::Packages(vec![s]), } } } impl fmt::Display for Package { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Package::Default => { write!(f, "Default: search all packages for example/bin/bench") } Package::Package(s) => write!(f, "{}", s), } } } impl fmt::Display for Target { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Target::Main => write!(f, "src/main.rs"), Target::Example(bin) => write!(f, "examples/{}.rs", bin), Target::Bin(bin) => write!(f, "bin/{}.rs", bin), Target::Bench(bench) => write!(f, "bench {}", bench), } } } /// Cargo-specific options pub(crate) struct CargoOpts { pub(crate) package: Package, pub(crate) target: Target, pub(crate) profile: String, pub(crate) features: CliFeatures, } impl AppConfig { pub(crate) fn to_cargo_opts(&self) -> Result<CargoOpts> { let package = self.get_package(); let target = self.get_target(); let features = self.features.clone().map(|s| vec![s]).unwrap_or_default(); let features = CliFeatures::from_command_line( &features, self.all_features, !self.no_default_features, )?; let profile = self .profile .clone() .unwrap_or_else(|| (if self.release { "release" } else { "dev" }).to_owned()); Ok(CargoOpts { package, target, profile, features }) } fn
(&self) -> Package { if let Some(ref package) = self.package { Package::Package(package.clone()) } else { Package::Default } } // valid target: --example, --bin, --bench fn get_target(&self) -> Target { if let Some(ref example) = self.example { Target::Example(example.clone()) } else if let Some(ref bin) = self.bin { Target::Bin(bin.clone()) } else if let Some(ref bench) = self.bench { Target::Bench(bench.clone()) } else { Target::Main } } } #[cfg(test)] mod tests { use super::*; #[test] fn defaults() { let opts = AppConfig::from_iter(&["instruments", "-t", "template"]); assert!(opts.example.is_none()); assert!(opts.bin.is_none()); assert!(!opts.release); assert!(opts.trace_filepath.is_none()); assert!(opts.package.is_none()); assert!(opts.manifest_path.is_none()); } #[test] fn package_is_given() { let opts = AppConfig::from_iter(&["instruments", "--package", "foo", "--template", "alloc"]); assert!(opts.example.is_none()); assert!(opts.bin.is_none()); assert!(opts.bench.is_none()); assert_eq!(opts.package.unwrap().as_str(), "foo"); let opts = AppConfig::from_iter(&[ "instruments", "--package", "foo", "--template", "alloc", "--bin", "bin_arg", ]); assert!(opts.example.is_none()); assert!(opts.bench.is_none()); assert_eq!(opts.bin.unwrap().as_str(), "bin_arg"); assert_eq!(opts.package.unwrap().as_str(), "foo"); } #[test] #[should_panic(expected = "cannot be used with one or more of the other")] fn group_is_exclusive() { let opts = AppConfig::from_iter(&["instruments", "-t", "time", "--bin", "bin_arg"]); assert!(opts.example.is_none()); assert_eq!(opts.bin.unwrap().as_str(), "bin_arg"); let opts = AppConfig::from_iter(&["instruments", "-t", "time", "--example", "example_binary"]); assert!(opts.bin.is_none()); assert_eq!(opts.example.unwrap().as_str(), "example_binary"); let _opts = AppConfig::from_iter_safe(&[ "instruments", "-t", "time", "--bin", "thing", "--example", "other", ]) .unwrap(); } #[test] fn limit_millis() { let opts = AppConfig::from_iter(&["instruments", "-t", "time", "--time-limit", "42000"]); assert_eq!(opts.time_limit, Some(42000)); let opts = AppConfig::from_iter(&["instruments", "-t", "time", "--time-limit", "808"]); assert_eq!(opts.time_limit, Some(808)); let opts = AppConfig::from_iter(&["instruments", "-t", "time"]); assert_eq!(opts.time_limit, None); } #[test] fn features() { let opts = &[ "instruments", "--template", "time", "--example", "hello", "--features", "svg im", "--", "hi", ]; let opts = AppConfig::from_iter(opts); assert_eq!(opts.template_name, Some("time".into())); assert_eq!(opts.example, Some("hello
get_package
identifier_name
opt.rs
) Time Profiler." )] Instruments(AppConfig), } #[derive(Debug, StructOpt)] #[structopt(setting = structopt::clap::AppSettings::TrailingVarArg)] pub(crate) struct AppConfig { /// List available templates #[structopt(short = "l", long)] pub(crate) list_templates: bool, /// Specify the instruments template to run /// /// To see available templates, pass `--list-templates`. #[structopt( short = "t", long = "template", value_name = "TEMPLATE", required_unless = "list-templates" )] pub(crate) template_name: Option<String>, /// Specify package for example/bin/bench /// /// For package that has only one bin, it's the same as `--bin PACKAGE_NAME` #[structopt(short = "p", long, value_name = "NAME")] package: Option<String>, /// Example binary to run #[structopt(long, group = "target", value_name = "NAME")] example: Option<String>, /// Binary to run #[structopt(long, group = "target", value_name = "NAME")] bin: Option<String>, /// Benchmark target to run #[structopt(long, group = "target", value_name = "NAME")] bench: Option<String>, /// Pass --release to cargo #[structopt(long, conflicts_with = "profile")] release: bool, /// Pass --profile NAME to cargo #[structopt(long, value_name = "NAME")] profile: Option<String>, /// Output .trace file to the given path /// /// Defaults to `target/instruments/{name}_{template-name}_{date}.trace`. /// /// If the file already exists, a new Run will be added. #[structopt(short = "o", long = "output", value_name = "PATH", parse(from_os_str))] pub(crate) trace_filepath: Option<PathBuf>, /// Limit recording time to the specified value (in milliseconds) /// /// The program will be terminated after this limit is exceeded. #[structopt(long, value_name = "MILLIS")] pub(crate) time_limit: Option<usize>, /// Open the generated .trace file after profiling /// /// The trace file will open in Xcode Instruments. #[structopt(long, hidden = true)] pub(crate) open: bool, /// Do not open the generated trace file in Instruments.app. #[structopt(long)] pub(crate) no_open: bool, /// Features to pass to cargo. #[structopt(long, value_name = "CARGO-FEATURES")] pub(crate) features: Option<String>, /// Path to Cargo.toml #[structopt(long, value_name = "PATH")] pub(crate) manifest_path: Option<PathBuf>, /// Activate all features for the selected target. #[structopt(long, display_order = 1001)] pub(crate) all_features: bool, /// Do not activate the default features for the selected target #[structopt(long, display_order = 1001)] pub(crate) no_default_features: bool, /// Arguments passed to the target binary. /// /// To pass flags, precede child args with `--`, /// e.g. `cargo instruments -- -t test1.txt --slow-mode`. #[structopt(value_name = "ARGS")] pub(crate) target_args: Vec<String>, } /// Represents the kind of target to profile. #[derive(Debug, PartialEq)] pub(crate) enum Target { Main, Example(String), Bin(String), Bench(String), } /// The package in which to look for the specified target (example/bin/bench) #[derive(Clone, Debug, PartialEq)] pub(crate) enum Package { Default, Package(String), } impl From<Package> for Packages { fn from(p: Package) -> Self
} impl fmt::Display for Package { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Package::Default => { write!(f, "Default: search all packages for example/bin/bench") } Package::Package(s) => write!(f, "{}", s), } } } impl fmt::Display for Target { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Target::Main => write!(f, "src/main.rs"), Target::Example(bin) => write!(f, "examples/{}.rs", bin), Target::Bin(bin) => write!(f, "bin/{}.rs", bin), Target::Bench(bench) => write!(f, "bench {}", bench), } } } /// Cargo-specific options pub(crate) struct CargoOpts { pub(crate) package: Package, pub(crate) target: Target, pub(crate) profile: String, pub(crate) features: CliFeatures, } impl AppConfig { pub(crate) fn to_cargo_opts(&self) -> Result<CargoOpts> { let package = self.get_package(); let target = self.get_target(); let features = self.features.clone().map(|s| vec![s]).unwrap_or_default(); let features = CliFeatures::from_command_line( &features, self.all_features, !self.no_default_features, )?; let profile = self .profile .clone() .unwrap_or_else(|| (if self.release { "release" } else { "dev" }).to_owned()); Ok(CargoOpts { package, target, profile, features }) } fn get_package(&self) -> Package { if let Some(ref package) = self.package { Package::Package(package.clone()) } else { Package::Default } } // valid target: --example, --bin, --bench fn get_target(&self) -> Target { if let Some(ref example) = self.example { Target::Example(example.clone()) } else if let Some(ref bin) = self.bin { Target::Bin(bin.clone()) } else if let Some(ref bench) = self.bench { Target::Bench(bench.clone()) } else { Target::Main } } } #[cfg(test)] mod tests { use super::*; #[test] fn defaults() { let opts = AppConfig::from_iter(&["instruments", "-t", "template"]); assert!(opts.example.is_none()); assert!(opts.bin.is_none()); assert!(!opts.release); assert!(opts.trace_filepath.is_none()); assert!(opts.package.is_none()); assert!(opts.manifest_path.is_none()); } #[test] fn package_is_given() { let opts = AppConfig::from_iter(&["instruments", "--package", "foo", "--template", "alloc"]); assert!(opts.example.is_none()); assert!(opts.bin.is_none()); assert!(opts.bench.is_none()); assert_eq!(opts.package.unwrap().as_str(), "foo"); let opts = AppConfig::from_iter(&[ "instruments", "--package", "foo", "--template", "alloc", "--bin", "bin_arg", ]); assert!(opts.example.is_none()); assert!(opts.bench.is_none()); assert_eq!(opts.bin.unwrap().as_str(), "bin_arg"); assert_eq!(opts.package.unwrap().as_str(), "foo"); } #[test] #[should_panic(expected = "cannot be used with one or more of the other")] fn group_is_exclusive() { let opts = AppConfig::from_iter(&["instruments", "-t", "time", "--bin", "bin_arg"]); assert!(opts.example.is_none()); assert_eq!(opts.bin.unwrap().as_str(), "bin_arg"); let opts = AppConfig::from_iter(&["instruments", "-t", "time", "--example", "example_binary"]); assert!(opts.bin.is_none()); assert_eq!(opts.example.unwrap().as_str(), "example_binary"); let _opts = AppConfig::from_iter_safe(&[ "instruments", "-t", "time", "--bin", "thing", "--example", "other", ]) .unwrap(); } #[test] fn limit_millis() { let opts = AppConfig::from_iter(&["instruments", "-t", "time", "--time-limit", "42000"]); assert_eq!(opts.time_limit, Some(42000)); let opts = AppConfig::from_iter(&["instruments", "-t", "time", "--time-limit", "808"]); assert_eq!(opts.time_limit, Some(808)); let opts = AppConfig::from_iter(&["instruments", "-t", "time"]); assert_eq!(opts.time_limit, None); } #[test] fn features() { let opts = &[ "instruments", "--template", "time", "--example", "hello", "--features", "svg im", "--", "hi", ]; let opts = AppConfig::from_iter(opts); assert_eq!(opts.template_name, Some("time".into())); assert_eq!(opts.example, Some("hello
{ match p { Package::Default => Packages::Default, Package::Package(s) => Packages::Packages(vec![s]), } }
identifier_body
opt.rs
recommended) Time Profiler."
#[derive(Debug, StructOpt)] #[structopt(setting = structopt::clap::AppSettings::TrailingVarArg)] pub(crate) struct AppConfig { /// List available templates #[structopt(short = "l", long)] pub(crate) list_templates: bool, /// Specify the instruments template to run /// /// To see available templates, pass `--list-templates`. #[structopt( short = "t", long = "template", value_name = "TEMPLATE", required_unless = "list-templates" )] pub(crate) template_name: Option<String>, /// Specify package for example/bin/bench /// /// For package that has only one bin, it's the same as `--bin PACKAGE_NAME` #[structopt(short = "p", long, value_name = "NAME")] package: Option<String>, /// Example binary to run #[structopt(long, group = "target", value_name = "NAME")] example: Option<String>, /// Binary to run #[structopt(long, group = "target", value_name = "NAME")] bin: Option<String>, /// Benchmark target to run #[structopt(long, group = "target", value_name = "NAME")] bench: Option<String>, /// Pass --release to cargo #[structopt(long, conflicts_with = "profile")] release: bool, /// Pass --profile NAME to cargo #[structopt(long, value_name = "NAME")] profile: Option<String>, /// Output .trace file to the given path /// /// Defaults to `target/instruments/{name}_{template-name}_{date}.trace`. /// /// If the file already exists, a new Run will be added. #[structopt(short = "o", long = "output", value_name = "PATH", parse(from_os_str))] pub(crate) trace_filepath: Option<PathBuf>, /// Limit recording time to the specified value (in milliseconds) /// /// The program will be terminated after this limit is exceeded. #[structopt(long, value_name = "MILLIS")] pub(crate) time_limit: Option<usize>, /// Open the generated .trace file after profiling /// /// The trace file will open in Xcode Instruments. #[structopt(long, hidden = true)] pub(crate) open: bool, /// Do not open the generated trace file in Instruments.app. #[structopt(long)] pub(crate) no_open: bool, /// Features to pass to cargo. #[structopt(long, value_name = "CARGO-FEATURES")] pub(crate) features: Option<String>, /// Path to Cargo.toml #[structopt(long, value_name = "PATH")] pub(crate) manifest_path: Option<PathBuf>, /// Activate all features for the selected target. #[structopt(long, display_order = 1001)] pub(crate) all_features: bool, /// Do not activate the default features for the selected target #[structopt(long, display_order = 1001)] pub(crate) no_default_features: bool, /// Arguments passed to the target binary. /// /// To pass flags, precede child args with `--`, /// e.g. `cargo instruments -- -t test1.txt --slow-mode`. #[structopt(value_name = "ARGS")] pub(crate) target_args: Vec<String>, } /// Represents the kind of target to profile. #[derive(Debug, PartialEq)] pub(crate) enum Target { Main, Example(String), Bin(String), Bench(String), } /// The package in which to look for the specified target (example/bin/bench) #[derive(Clone, Debug, PartialEq)] pub(crate) enum Package { Default, Package(String), } impl From<Package> for Packages { fn from(p: Package) -> Self { match p { Package::Default => Packages::Default, Package::Package(s) => Packages::Packages(vec![s]), } } } impl fmt::Display for Package { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Package::Default => { write!(f, "Default: search all packages for example/bin/bench") } Package::Package(s) => write!(f, "{}", s), } } } impl fmt::Display for Target { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Target::Main => write!(f, "src/main.rs"), Target::Example(bin) => write!(f, "examples/{}.rs", bin), Target::Bin(bin) => write!(f, "bin/{}.rs", bin), Target::Bench(bench) => write!(f, "bench {}", bench), } } } /// Cargo-specific options pub(crate) struct CargoOpts { pub(crate) package: Package, pub(crate) target: Target, pub(crate) profile: String, pub(crate) features: CliFeatures, } impl AppConfig { pub(crate) fn to_cargo_opts(&self) -> Result<CargoOpts> { let package = self.get_package(); let target = self.get_target(); let features = self.features.clone().map(|s| vec![s]).unwrap_or_default(); let features = CliFeatures::from_command_line( &features, self.all_features, !self.no_default_features, )?; let profile = self .profile .clone() .unwrap_or_else(|| (if self.release { "release" } else { "dev" }).to_owned()); Ok(CargoOpts { package, target, profile, features }) } fn get_package(&self) -> Package { if let Some(ref package) = self.package { Package::Package(package.clone()) } else { Package::Default } } // valid target: --example, --bin, --bench fn get_target(&self) -> Target { if let Some(ref example) = self.example { Target::Example(example.clone()) } else if let Some(ref bin) = self.bin { Target::Bin(bin.clone()) } else if let Some(ref bench) = self.bench { Target::Bench(bench.clone()) } else { Target::Main } } } #[cfg(test)] mod tests { use super::*; #[test] fn defaults() { let opts = AppConfig::from_iter(&["instruments", "-t", "template"]); assert!(opts.example.is_none()); assert!(opts.bin.is_none()); assert!(!opts.release); assert!(opts.trace_filepath.is_none()); assert!(opts.package.is_none()); assert!(opts.manifest_path.is_none()); } #[test] fn package_is_given() { let opts = AppConfig::from_iter(&["instruments", "--package", "foo", "--template", "alloc"]); assert!(opts.example.is_none()); assert!(opts.bin.is_none()); assert!(opts.bench.is_none()); assert_eq!(opts.package.unwrap().as_str(), "foo"); let opts = AppConfig::from_iter(&[ "instruments", "--package", "foo", "--template", "alloc", "--bin", "bin_arg", ]); assert!(opts.example.is_none()); assert!(opts.bench.is_none()); assert_eq!(opts.bin.unwrap().as_str(), "bin_arg"); assert_eq!(opts.package.unwrap().as_str(), "foo"); } #[test] #[should_panic(expected = "cannot be used with one or more of the other")] fn group_is_exclusive() { let opts = AppConfig::from_iter(&["instruments", "-t", "time", "--bin", "bin_arg"]); assert!(opts.example.is_none()); assert_eq!(opts.bin.unwrap().as_str(), "bin_arg"); let opts = AppConfig::from_iter(&["instruments", "-t", "time", "--example", "example_binary"]); assert!(opts.bin.is_none()); assert_eq!(opts.example.unwrap().as_str(), "example_binary"); let _opts = AppConfig::from_iter_safe(&[ "instruments", "-t", "time", "--bin", "thing", "--example", "other", ]) .unwrap(); } #[test] fn limit_millis() { let opts = AppConfig::from_iter(&["instruments", "-t", "time", "--time-limit", "42000"]); assert_eq!(opts.time_limit, Some(42000)); let opts = AppConfig::from_iter(&["instruments", "-t", "time", "--time-limit", "808"]); assert_eq!(opts.time_limit, Some(808)); let opts = AppConfig::from_iter(&["instruments", "-t", "time"]); assert_eq!(opts.time_limit, None); } #[test] fn features() { let opts = &[ "instruments", "--template", "time", "--example", "hello", "--features", "svg im", "--", "hi", ]; let opts = AppConfig::from_iter(opts); assert_eq!(opts.template_name, Some("time".into())); assert_eq!(opts.example, Some("hello
)] Instruments(AppConfig), }
random_line_split
quotes.py
for the price quote. Name, price and as-of date and time are retrieved from Yahoo! Finance. fields: status, source, ticker, name, price, quoteTime, pclose, pchange """ def __init__(self, item): #item = {"ticker":TickerSym, 'm':multiplier, 's':symbol} # TickerSym = symbol to grab from Yahoo # m = multiplier for quote # s = symbol to pass to Money self.ticker = item['ticker'] self.multiplier = item['m'] self.symbol = item['s'] self.status = True socket.setdefaulttimeout(10) #default socket timeout for server read, secs def _removeIllegalChars(self, inputString): pattern = re.compile("[^a-zA-Z0-9 ,.-]+") return pattern.sub("", inputString) def getQuote(self): #Yahoo! Finance: # name (n), lastprice (l1), date (d1), time(t1), previous close (p), %change (p2) if Debug: print "Getting quote for:", self.ticker self.status=False self.source='Y' #note: each try for a quote sets self.status=true if successful if eYahoo: csvtxt = self.getYahooQuote() quote = self.csvparse(csvtxt) if self.status: self.source='Y' if not self.status and eGoogle: # try screen scrape csvtxt = self.getGoogleQuote() quote = self.csvparse(csvtxt) if self.status: self.source='G' if not self.status: print "** ", self.ticker, ': invalid quote response. Skipping...' self.name = '*InvalidSymbol*' else: #show/save what we got rlc*2010 # example: "Amazon.com, Inc.",78.46,"9/3/2009","4:00pm", 80.00, "-1.96%" # Security names may have embedded commas, so use CSV utility to parse (rlc*2010) if Debug: print "Quote result string:", csvtxt self.name = quote[0] self.price = quote[1] self.date = quote[2] self.time = quote[3] self.pclose = quote[4] self.pchange = quote[5] #clean things up, format datetime str, and apply multiplier # if security name is null, replace name with symbol if self.name.strip()=='': self.name = self.ticker self.price = str(float2(self.price)*self.multiplier) #adjust price by multiplier self.date = self.date.lstrip('0 ') self.datetime = datetime.strptime(self.date + " " + self.time, "%m/%d/%Y %H:%M%p") self.quoteTime = self.datetime.strftime("%Y%m%d%H%M%S") + '[' + YahooTimeZone + ']' if '?' not in self.pclose and 'N/A' not in self.pclose: #adjust last close price by multiplier self.pclose = str(float2(self.pclose)*self.multiplier) #previous close name = self.ticker if self.symbol <> self.ticker: name = self.ticker + '(' + self.symbol + ')' print self.source+':' , name, self.price, self.date, self.time, self.pchange def csvparse(self, csvtxt): quote=[] self.status=True csvlst = [csvtxt] # csv.reader reads lists the same as files reader = csv.reader(csvlst) for row in reader: # we only have one row... so read it into a quote list quote = row # quote[]= [name, price, quoteTime, pclose, pchange], all as strings if len(quote) < 6: self.status=False elif quote[1] == '0.00' or quote[2] == 'N/A': self.status=False return quote def getYahooQuote(self): #read Yahoo json data api, and return csv url = YahooURL + "?symbols=%s" % self.ticker csvtxt="" self.status=True try: ht=urllib2.urlopen(url).read() self.quoteURL = 'https://finance.yahoo.com/quote/%s' % self.ticker #html link except: if Debug: print "** Error reading " + url + "\n" self.status = False if self.status: try: j = json.loads(ht) #parse json to dict jd = j['quoteResponse']['result'][0] #inside response pkg #use longName if available, otherwise use shortName field try: name = jd['longName'] except: name = jd['shortName'] price = jd['regularMarketPrice'] mtime = jd['regularMarketTime'] lastPrice = jd['regularMarketPreviousClose'] changePer = jd['regularMarketChangePercent'] qtime = time.localtime(mtime) qdateS = time.strftime("%m/%d/%Y", qtime) qtimeS = time.strftime("%I:%M%p", qtime) changeS = '{0:.2}%'.format(changePer) name = '"' + self._removeIllegalChars(name) + '"' #cleanup foreign chars and quote csvtxt = ','.join([name, str(price), qdateS, qtimeS, str(lastPrice), changeS]) if Debug: print "Yahoo csvtxt=",csvtxt except: #not formatted as expected? if Debug: print "An error occured by parsing the Yahoo Finance reponse for: ", self.ticker self.status=False return csvtxt def getGoogleQuote(self): #New screen scrape function: 19-Jan-2014*rlc # This function creates a csvtxt string with the same format as the Yahoo csv interface # Example return: "Amazon.com, Inc.","78.46","9/3/2009","4:00pm", 80.00, "-1.96%" # Gets data from Google Finance self.status = True # fresh start csvtxt = "" if Debug: print "Trying Google Finance for: ", self.ticker #Example url: https://www.google.com/finance?q=msft url = GoogleURL + "?q=" + self.ticker try: ht=urllib2.urlopen(url).read() self.quoteURL = url except: print "** error reading " + url + "\n" self.status = False ticker = self.ticker.replace("^","\^") #use literal regex character if self.status: try: #Name t1 = '(<meta itemprop="name".*?content=")(.*?)(")' p = re.compile(t1, re.IGNORECASE | re.DOTALL) rslt = p.findall(ht) name= rslt[0][1] #price t1 = '(<meta itemprop="price".*?content=")(.*?)(")' p = re.compile(t1, re.IGNORECASE | re.DOTALL) rslt = p.findall(ht) price= rslt[0][1] #Price change% t1 = '(<meta itemprop="priceChangePercent".*?content=")(.*?)(")' p = re.compile(t1, re.IGNORECASE | re.DOTALL) rslt = p.findall(ht) pchange= rslt[0][1] + '%' #Google date/time format= "yyyy-mm-ddThh:mm:ssZ" # Example = "2014-01-10T21:30:00Z" t1 = '(<meta itemprop="quoteTime".*?content=")(.*?)(")' p = re.compile(t1, re.IGNORECASE | re.DOTALL | re.MULTILINE) rslt = p.findall(ht) date1= rslt[0][1] qdate = datetime.strptime(date1, "%Y-%m-%dT%H:%M:%SZ") date2 = qdate.strftime("%m/%d/%Y").lstrip('0 ') #mm/dd/yyyy, but no leading zero or spaces #name may contain commas and illegal chars, so clenaup & enclose in quotes name = '"' + self._removeIllegalChars(name) + '"' #price may contain commas, but we don't want them price = ''.join([c for c in price if c in '1234567890.']) csvtxt = ','.join([name, price, date2, '04:00PM', '?', pchange]) if Debug: print "Google csvtxt=",csvtxt except: self.status=False if Debug: print "An error occured by parsing the Google Finance reponse for: ", self.ticker return csvtxt class
OfxWriter
identifier_name
quotes.py
09Nov2017*rlc # -Replace Yahoo quotes csv w/ json # -Removed yahooScrape option # 24Mar2018*rlc # -Use longName when available for Yahoo quotes. Mutual fund *family* name is sometimes given as shortName (see vhcox as example) import os, sys, time, urllib2, socket, shlex, re, csv, uuid, json import site_cfg from control2 import * from rlib1 import * from datetime import datetime join = str.join class Security: """ Encapsulate a stock or mutual fund. A Security has a ticker, a name, a price quote, and the as-of date and time for the price quote. Name, price and as-of date and time are retrieved from Yahoo! Finance. fields: status, source, ticker, name, price, quoteTime, pclose, pchange """ def __init__(self, item): #item = {"ticker":TickerSym, 'm':multiplier, 's':symbol} # TickerSym = symbol to grab from Yahoo # m = multiplier for quote # s = symbol to pass to Money self.ticker = item['ticker'] self.multiplier = item['m'] self.symbol = item['s'] self.status = True socket.setdefaulttimeout(10) #default socket timeout for server read, secs def _removeIllegalChars(self, inputString): pattern = re.compile("[^a-zA-Z0-9 ,.-]+") return pattern.sub("", inputString) def getQuote(self): #Yahoo! Finance: # name (n), lastprice (l1), date (d1), time(t1), previous close (p), %change (p2) if Debug:
self.status=False self.source='Y' #note: each try for a quote sets self.status=true if successful if eYahoo: csvtxt = self.getYahooQuote() quote = self.csvparse(csvtxt) if self.status: self.source='Y' if not self.status and eGoogle: # try screen scrape csvtxt = self.getGoogleQuote() quote = self.csvparse(csvtxt) if self.status: self.source='G' if not self.status: print "** ", self.ticker, ': invalid quote response. Skipping...' self.name = '*InvalidSymbol*' else: #show/save what we got rlc*2010 # example: "Amazon.com, Inc.",78.46,"9/3/2009","4:00pm", 80.00, "-1.96%" # Security names may have embedded commas, so use CSV utility to parse (rlc*2010) if Debug: print "Quote result string:", csvtxt self.name = quote[0] self.price = quote[1] self.date = quote[2] self.time = quote[3] self.pclose = quote[4] self.pchange = quote[5] #clean things up, format datetime str, and apply multiplier # if security name is null, replace name with symbol if self.name.strip()=='': self.name = self.ticker self.price = str(float2(self.price)*self.multiplier) #adjust price by multiplier self.date = self.date.lstrip('0 ') self.datetime = datetime.strptime(self.date + " " + self.time, "%m/%d/%Y %H:%M%p") self.quoteTime = self.datetime.strftime("%Y%m%d%H%M%S") + '[' + YahooTimeZone + ']' if '?' not in self.pclose and 'N/A' not in self.pclose: #adjust last close price by multiplier self.pclose = str(float2(self.pclose)*self.multiplier) #previous close name = self.ticker if self.symbol <> self.ticker: name = self.ticker + '(' + self.symbol + ')' print self.source+':' , name, self.price, self.date, self.time, self.pchange def csvparse(self, csvtxt): quote=[] self.status=True csvlst = [csvtxt] # csv.reader reads lists the same as files reader = csv.reader(csvlst) for row in reader: # we only have one row... so read it into a quote list quote = row # quote[]= [name, price, quoteTime, pclose, pchange], all as strings if len(quote) < 6: self.status=False elif quote[1] == '0.00' or quote[2] == 'N/A': self.status=False return quote def getYahooQuote(self): #read Yahoo json data api, and return csv url = YahooURL + "?symbols=%s" % self.ticker csvtxt="" self.status=True try: ht=urllib2.urlopen(url).read() self.quoteURL = 'https://finance.yahoo.com/quote/%s' % self.ticker #html link except: if Debug: print "** Error reading " + url + "\n" self.status = False if self.status: try: j = json.loads(ht) #parse json to dict jd = j['quoteResponse']['result'][0] #inside response pkg #use longName if available, otherwise use shortName field try: name = jd['longName'] except: name = jd['shortName'] price = jd['regularMarketPrice'] mtime = jd['regularMarketTime'] lastPrice = jd['regularMarketPreviousClose'] changePer = jd['regularMarketChangePercent'] qtime = time.localtime(mtime) qdateS = time.strftime("%m/%d/%Y", qtime) qtimeS = time.strftime("%I:%M%p", qtime) changeS = '{0:.2}%'.format(changePer) name = '"' + self._removeIllegalChars(name) + '"' #cleanup foreign chars and quote csvtxt = ','.join([name, str(price), qdateS, qtimeS, str(lastPrice), changeS]) if Debug: print "Yahoo csvtxt=",csvtxt except: #not formatted as expected? if Debug: print "An error occured by parsing the Yahoo Finance reponse for: ", self.ticker self.status=False return csvtxt def getGoogleQuote(self): #New screen scrape function: 19-Jan-2014*rlc # This function creates a csvtxt string with the same format as the Yahoo csv interface # Example return: "Amazon.com, Inc.","78.46","9/3/2009","4:00pm", 80.00, "-1.96%" # Gets data from Google Finance self.status = True # fresh start csvtxt = "" if Debug: print "Trying Google Finance for: ", self.ticker #Example url: https://www.google.com/finance?q=msft url = GoogleURL + "?q=" + self.ticker try: ht=urllib2.urlopen(url).read() self.quoteURL = url except: print "** error reading " + url + "\n" self.status = False ticker = self.ticker.replace("^","\^") #use literal regex character if self.status: try: #Name t1 = '(<meta itemprop="name".*?content=")(.*?)(")' p = re.compile(t1, re.IGNORECASE | re.DOTALL) rslt = p.findall(ht) name= rslt[0][1] #price t1 = '(<meta itemprop="price".*?content=")(.*?)(")' p = re.compile(t1, re.IGNORECASE | re.DOTALL) rslt = p.findall(ht) price= rslt[0][1] #Price change% t1 = '(<meta itemprop="priceChangePercent".*?content=")(.*?)(")' p = re.compile(t1, re.IGNORECASE | re.DOTALL) rslt = p.findall(ht) pchange= rslt[0][1] + '%' #Google date/time format= "yyyy-mm-ddThh:mm:ssZ" # Example = "2014-01-10T21:30:00Z" t1 = '(<meta itemprop="quoteTime".*?content=")(.*?)(")' p = re.compile(t1, re.IGNORECASE | re.DOTALL | re.MULTILINE) rslt = p.findall(ht) date1= rslt[0][1] qdate = datetime.strptime(date1, "%Y-%m-%dT%H:%M:%SZ") date2 = qdate.strftime("%m/%d/%Y").lstrip('0 ') #mm/dd/yyyy, but no
print "Getting quote for:", self.ticker
conditional_block
quotes.py
! Finance: # name (n), lastprice (l1), date (d1), time(t1), previous close (p), %change (p2) if Debug: print "Getting quote for:", self.ticker self.status=False self.source='Y' #note: each try for a quote sets self.status=true if successful if eYahoo: csvtxt = self.getYahooQuote() quote = self.csvparse(csvtxt) if self.status: self.source='Y' if not self.status and eGoogle: # try screen scrape csvtxt = self.getGoogleQuote() quote = self.csvparse(csvtxt) if self.status: self.source='G' if not self.status: print "** ", self.ticker, ': invalid quote response. Skipping...' self.name = '*InvalidSymbol*' else: #show/save what we got rlc*2010 # example: "Amazon.com, Inc.",78.46,"9/3/2009","4:00pm", 80.00, "-1.96%" # Security names may have embedded commas, so use CSV utility to parse (rlc*2010) if Debug: print "Quote result string:", csvtxt self.name = quote[0] self.price = quote[1] self.date = quote[2] self.time = quote[3] self.pclose = quote[4] self.pchange = quote[5] #clean things up, format datetime str, and apply multiplier # if security name is null, replace name with symbol if self.name.strip()=='': self.name = self.ticker self.price = str(float2(self.price)*self.multiplier) #adjust price by multiplier self.date = self.date.lstrip('0 ') self.datetime = datetime.strptime(self.date + " " + self.time, "%m/%d/%Y %H:%M%p") self.quoteTime = self.datetime.strftime("%Y%m%d%H%M%S") + '[' + YahooTimeZone + ']' if '?' not in self.pclose and 'N/A' not in self.pclose: #adjust last close price by multiplier self.pclose = str(float2(self.pclose)*self.multiplier) #previous close name = self.ticker if self.symbol <> self.ticker: name = self.ticker + '(' + self.symbol + ')' print self.source+':' , name, self.price, self.date, self.time, self.pchange def csvparse(self, csvtxt): quote=[] self.status=True csvlst = [csvtxt] # csv.reader reads lists the same as files reader = csv.reader(csvlst) for row in reader: # we only have one row... so read it into a quote list quote = row # quote[]= [name, price, quoteTime, pclose, pchange], all as strings if len(quote) < 6: self.status=False elif quote[1] == '0.00' or quote[2] == 'N/A': self.status=False return quote def getYahooQuote(self): #read Yahoo json data api, and return csv url = YahooURL + "?symbols=%s" % self.ticker csvtxt="" self.status=True try: ht=urllib2.urlopen(url).read() self.quoteURL = 'https://finance.yahoo.com/quote/%s' % self.ticker #html link except: if Debug: print "** Error reading " + url + "\n" self.status = False if self.status: try: j = json.loads(ht) #parse json to dict jd = j['quoteResponse']['result'][0] #inside response pkg #use longName if available, otherwise use shortName field try: name = jd['longName'] except: name = jd['shortName'] price = jd['regularMarketPrice'] mtime = jd['regularMarketTime'] lastPrice = jd['regularMarketPreviousClose'] changePer = jd['regularMarketChangePercent'] qtime = time.localtime(mtime) qdateS = time.strftime("%m/%d/%Y", qtime) qtimeS = time.strftime("%I:%M%p", qtime) changeS = '{0:.2}%'.format(changePer) name = '"' + self._removeIllegalChars(name) + '"' #cleanup foreign chars and quote csvtxt = ','.join([name, str(price), qdateS, qtimeS, str(lastPrice), changeS]) if Debug: print "Yahoo csvtxt=",csvtxt except: #not formatted as expected? if Debug: print "An error occured by parsing the Yahoo Finance reponse for: ", self.ticker self.status=False return csvtxt def getGoogleQuote(self): #New screen scrape function: 19-Jan-2014*rlc # This function creates a csvtxt string with the same format as the Yahoo csv interface # Example return: "Amazon.com, Inc.","78.46","9/3/2009","4:00pm", 80.00, "-1.96%" # Gets data from Google Finance self.status = True # fresh start csvtxt = "" if Debug: print "Trying Google Finance for: ", self.ticker #Example url: https://www.google.com/finance?q=msft url = GoogleURL + "?q=" + self.ticker try: ht=urllib2.urlopen(url).read() self.quoteURL = url except: print "** error reading " + url + "\n" self.status = False ticker = self.ticker.replace("^","\^") #use literal regex character if self.status: try: #Name t1 = '(<meta itemprop="name".*?content=")(.*?)(")' p = re.compile(t1, re.IGNORECASE | re.DOTALL) rslt = p.findall(ht) name= rslt[0][1] #price t1 = '(<meta itemprop="price".*?content=")(.*?)(")' p = re.compile(t1, re.IGNORECASE | re.DOTALL) rslt = p.findall(ht) price= rslt[0][1] #Price change% t1 = '(<meta itemprop="priceChangePercent".*?content=")(.*?)(")' p = re.compile(t1, re.IGNORECASE | re.DOTALL) rslt = p.findall(ht) pchange= rslt[0][1] + '%' #Google date/time format= "yyyy-mm-ddThh:mm:ssZ" # Example = "2014-01-10T21:30:00Z" t1 = '(<meta itemprop="quoteTime".*?content=")(.*?)(")' p = re.compile(t1, re.IGNORECASE | re.DOTALL | re.MULTILINE) rslt = p.findall(ht) date1= rslt[0][1] qdate = datetime.strptime(date1, "%Y-%m-%dT%H:%M:%SZ") date2 = qdate.strftime("%m/%d/%Y").lstrip('0 ') #mm/dd/yyyy, but no leading zero or spaces #name may contain commas and illegal chars, so clenaup & enclose in quotes name = '"' + self._removeIllegalChars(name) + '"' #price may contain commas, but we don't want them price = ''.join([c for c in price if c in '1234567890.']) csvtxt = ','.join([name, price, date2, '04:00PM', '?', pchange]) if Debug: print "Google csvtxt=",csvtxt except: self.status=False if Debug: print "An error occured by parsing the Google Finance reponse for: ", self.ticker return csvtxt class OfxWriter:
""" Create an OFX file based on a list of stocks and mutual funds. """ def __init__(self, currency, account, shares, stockList, mfList): self.currency = currency self.account = account self.shares = shares self.stockList = stockList self.mfList = mfList self.dtasof = self.get_dtasof() def get_dtasof(self): #15-Feb-2011: Use the latest quote date/time for the statement today = datetime.today() dtasof = today.strftime("%Y%m%d")+'120000' #default to today @ noon lastdate = datetime(1,1,1) #but compare actual dates to long, long ago... for ticker in self.stockList + self.mfList: if ticker.datetime > lastdate and not ticker.datetime > today: lastdate = ticker.datetime
identifier_body
quotes.py
0) if Debug: print "Quote result string:", csvtxt self.name = quote[0] self.price = quote[1] self.date = quote[2] self.time = quote[3] self.pclose = quote[4] self.pchange = quote[5] #clean things up, format datetime str, and apply multiplier # if security name is null, replace name with symbol if self.name.strip()=='': self.name = self.ticker self.price = str(float2(self.price)*self.multiplier) #adjust price by multiplier self.date = self.date.lstrip('0 ') self.datetime = datetime.strptime(self.date + " " + self.time, "%m/%d/%Y %H:%M%p") self.quoteTime = self.datetime.strftime("%Y%m%d%H%M%S") + '[' + YahooTimeZone + ']' if '?' not in self.pclose and 'N/A' not in self.pclose: #adjust last close price by multiplier self.pclose = str(float2(self.pclose)*self.multiplier) #previous close name = self.ticker if self.symbol <> self.ticker: name = self.ticker + '(' + self.symbol + ')' print self.source+':' , name, self.price, self.date, self.time, self.pchange def csvparse(self, csvtxt): quote=[] self.status=True csvlst = [csvtxt] # csv.reader reads lists the same as files reader = csv.reader(csvlst) for row in reader: # we only have one row... so read it into a quote list quote = row # quote[]= [name, price, quoteTime, pclose, pchange], all as strings if len(quote) < 6: self.status=False elif quote[1] == '0.00' or quote[2] == 'N/A': self.status=False return quote def getYahooQuote(self): #read Yahoo json data api, and return csv url = YahooURL + "?symbols=%s" % self.ticker csvtxt="" self.status=True try: ht=urllib2.urlopen(url).read() self.quoteURL = 'https://finance.yahoo.com/quote/%s' % self.ticker #html link except: if Debug: print "** Error reading " + url + "\n" self.status = False if self.status: try: j = json.loads(ht) #parse json to dict jd = j['quoteResponse']['result'][0] #inside response pkg #use longName if available, otherwise use shortName field try: name = jd['longName'] except: name = jd['shortName'] price = jd['regularMarketPrice'] mtime = jd['regularMarketTime'] lastPrice = jd['regularMarketPreviousClose'] changePer = jd['regularMarketChangePercent'] qtime = time.localtime(mtime) qdateS = time.strftime("%m/%d/%Y", qtime) qtimeS = time.strftime("%I:%M%p", qtime) changeS = '{0:.2}%'.format(changePer) name = '"' + self._removeIllegalChars(name) + '"' #cleanup foreign chars and quote csvtxt = ','.join([name, str(price), qdateS, qtimeS, str(lastPrice), changeS]) if Debug: print "Yahoo csvtxt=",csvtxt except: #not formatted as expected? if Debug: print "An error occured by parsing the Yahoo Finance reponse for: ", self.ticker self.status=False return csvtxt def getGoogleQuote(self): #New screen scrape function: 19-Jan-2014*rlc # This function creates a csvtxt string with the same format as the Yahoo csv interface # Example return: "Amazon.com, Inc.","78.46","9/3/2009","4:00pm", 80.00, "-1.96%" # Gets data from Google Finance self.status = True # fresh start csvtxt = "" if Debug: print "Trying Google Finance for: ", self.ticker #Example url: https://www.google.com/finance?q=msft url = GoogleURL + "?q=" + self.ticker try: ht=urllib2.urlopen(url).read() self.quoteURL = url except: print "** error reading " + url + "\n" self.status = False ticker = self.ticker.replace("^","\^") #use literal regex character if self.status: try: #Name t1 = '(<meta itemprop="name".*?content=")(.*?)(")' p = re.compile(t1, re.IGNORECASE | re.DOTALL) rslt = p.findall(ht) name= rslt[0][1] #price t1 = '(<meta itemprop="price".*?content=")(.*?)(")' p = re.compile(t1, re.IGNORECASE | re.DOTALL) rslt = p.findall(ht) price= rslt[0][1] #Price change% t1 = '(<meta itemprop="priceChangePercent".*?content=")(.*?)(")' p = re.compile(t1, re.IGNORECASE | re.DOTALL) rslt = p.findall(ht) pchange= rslt[0][1] + '%' #Google date/time format= "yyyy-mm-ddThh:mm:ssZ" # Example = "2014-01-10T21:30:00Z" t1 = '(<meta itemprop="quoteTime".*?content=")(.*?)(")' p = re.compile(t1, re.IGNORECASE | re.DOTALL | re.MULTILINE) rslt = p.findall(ht) date1= rslt[0][1] qdate = datetime.strptime(date1, "%Y-%m-%dT%H:%M:%SZ") date2 = qdate.strftime("%m/%d/%Y").lstrip('0 ') #mm/dd/yyyy, but no leading zero or spaces #name may contain commas and illegal chars, so clenaup & enclose in quotes name = '"' + self._removeIllegalChars(name) + '"' #price may contain commas, but we don't want them price = ''.join([c for c in price if c in '1234567890.']) csvtxt = ','.join([name, price, date2, '04:00PM', '?', pchange]) if Debug: print "Google csvtxt=",csvtxt except: self.status=False if Debug: print "An error occured by parsing the Google Finance reponse for: ", self.ticker return csvtxt class OfxWriter: """ Create an OFX file based on a list of stocks and mutual funds. """ def __init__(self, currency, account, shares, stockList, mfList): self.currency = currency self.account = account self.shares = shares self.stockList = stockList self.mfList = mfList self.dtasof = self.get_dtasof() def get_dtasof(self): #15-Feb-2011: Use the latest quote date/time for the statement today = datetime.today() dtasof = today.strftime("%Y%m%d")+'120000' #default to today @ noon lastdate = datetime(1,1,1) #but compare actual dates to long, long ago... for ticker in self.stockList + self.mfList: if ticker.datetime > lastdate and not ticker.datetime > today: lastdate = ticker.datetime dtasof = ticker.quoteTime return dtasof def _signOn(self): """Generate server signon response message""" return OfxTag("SIGNONMSGSRSV1", OfxTag("SONRS", OfxTag("STATUS", OfxField("CODE", "0"), OfxField("SEVERITY", "INFO"), OfxField("MESSAGE","Successful Sign On") ), OfxField("DTSERVER", OfxDate()), OfxField("LANGUAGE", "ENG"), OfxField("DTPROFUP", "20010918083000"), OfxTag("FI", OfxField("ORG", "PocketSense")) ) ) def invPosList(self): # create INVPOSLIST section, including all stock and MF symbols posstock = [] for stock in self.stockList: posstock.append(self._pos("stock", stock.symbol, stock.price, stock.quoteTime)) posmf = []
for mf in self.mfList: posmf.append(self._pos("mf", mf.symbol, mf.price, mf.quoteTime)) return OfxTag("INVPOSLIST",
random_line_split
init.rs
884 fn ensure_procfs(path: &Path) -> Result<()> { let procfs_fd = fs::File::open(path)?; let fstat_info = sys::statfs::fstatfs(&procfs_fd.as_raw_fd())?; if fstat_info.filesystem_type() != sys::statfs::PROC_SUPER_MAGIC { bail!(format!("{:?} is not on the procfs", path)); } Ok(()) } // Get a list of open fds for the calling process. fn get_open_fds() -> Result<Vec<i32>> { const PROCFS_FD_PATH: &str = "/proc/self/fd"; ensure_procfs(Path::new(PROCFS_FD_PATH)) .with_context(|| format!("{} is not the actual procfs", PROCFS_FD_PATH))?; let fds: Vec<i32> = fs::read_dir(PROCFS_FD_PATH)? .filter_map(|entry| match entry { Ok(entry) => Some(entry.path()), Err(_) => None, }) .filter_map(|path| path.file_name().map(|file_name| file_name.to_owned())) .filter_map(|file_name| file_name.to_str().map(String::from)) .filter_map(|file_name| -> Option<i32> { // Convert the file name from string into i32. Since we are looking // at /proc/<pid>/fd, anything that's not a number (i32) can be // ignored. We are only interested in opened fds. match file_name.parse() { Ok(fd) => Some(fd), Err(_) => None, } }) .collect(); Ok(fds) } // Cleanup any extra file descriptors, so the new container process will not // leak a file descriptor from before execve gets executed. The first 3 fd will // stay open: stdio, stdout, and stderr. We would further preserve the next // "preserve_fds" number of fds. Set the rest of fd with CLOEXEC flag, so they // will be closed after execve into the container payload. We can't close the // fds immediatly since we at least still need it for the pipe used to wait on // starting the container. fn cleanup_file_descriptors(preserve_fds: i32) -> Result<()> { let open_fds = get_open_fds().with_context(|| "Failed to obtain opened fds")?; // Include stdin, stdout, and stderr for fd 0, 1, and 2 respectively. let min_fd = preserve_fds + 3; let to_be_cleaned_up_fds: Vec<i32> = open_fds .iter() .filter_map(|&fd| if fd >= min_fd { Some(fd) } else { None }) .collect(); to_be_cleaned_up_fds.iter().for_each(|&fd| { // Intentionally ignore errors here -- the cases where this might fail // are basically file descriptors that have already been closed. let _ = fcntl::fcntl(fd, fcntl::F_SETFD(fcntl::FdFlag::FD_CLOEXEC)); }); Ok(()) } pub struct ContainerInitArgs { /// Flag indicating if an init or a tenant container should be created pub init: bool, /// Interface to operating system primitives pub syscall: LinuxSyscall, /// OCI complient runtime spec pub spec: Spec, /// Root filesystem of the container pub rootfs: PathBuf, /// Socket to communicate the file descriptor of the ptty pub console_socket: Option<FileDescriptor>, /// Options for rootless containers pub rootless: Option<Rootless>, /// Path to the Unix Domain Socket to communicate container start pub notify_path: PathBuf, /// File descriptos preserved/passed to the container init process. pub preserve_fds: i32, /// Pipe used to communicate with the child process pub child: child::ChildProcess, } pub fn container_init(args: ContainerInitArgs) -> Result<()> { let command = &args.syscall; let spec = &args.spec; let linux = &spec.linux.as_ref().context("no linux in spec")?; let namespaces: Namespaces = linux.namespaces.clone().into(); // need to create the notify socket before we pivot root, since the unix // domain socket used here is outside of the rootfs of container let mut notify_socket: NotifyListener = NotifyListener::new(&args.notify_path)?; let proc = &spec.process.as_ref().context("no process in spec")?; let mut envs: Vec<String> = proc.env.clone(); let rootfs = &args.rootfs; let mut child = args.child; // if Out-of-memory score adjustment is set in specification. set the score // value for the current process check // https://dev.to/rrampage/surviving-the-linux-oom-killer-2ki9 for some more // information if let Some(ref resource) = linux.resources { if let Some(oom_score_adj) = resource.oom_score_adj { let mut f = fs::File::create("/proc/self/oom_score_adj")?; f.write_all(oom_score_adj.to_string().as_bytes())?; } } // if new user is specified in specification, this will be true and new // namespace will be created, check // https://man7.org/linux/man-pages/man7/user_namespaces.7.html for more // information if args.rootless.is_some() { // child needs to be dumpable, otherwise the non root parent is not // allowed to write the uid/gid maps prctl::set_dumpable(true).unwrap(); child.request_identifier_mapping()?; child.wait_for_mapping_ack()?; prctl::set_dumpable(false).unwrap(); } // set limits and namespaces to the process for rlimit in proc.rlimits.iter() { command.set_rlimit(rlimit).context("failed to set rlimit")?; } command .set_id(Uid::from_raw(0), Gid::from_raw(0)) .context("failed to become root")?; // set up tty if specified if let Some(csocketfd) = args.console_socket { tty::setup_console(&csocketfd)?; } // join existing namespaces namespaces.apply_setns()?; command.set_hostname(spec.hostname.as_ref().context("no hostname in spec")?)?; if proc.no_new_privileges { let _ = prctl::set_no_new_privileges(true); } if args.init
command.set_id(Uid::from_raw(proc.user.uid), Gid::from_raw(proc.user.gid))?; capabilities::reset_effective(command)?; if let Some(caps) = &proc.capabilities { capabilities::drop_privileges(caps, command)?; } // Take care of LISTEN_FDS used for systemd-active-socket. If the value is // not 0, then we have to preserve those fds as well, and set up the correct // environment variables. let preserve_fds: i32 = match env::var("LISTEN_FDS") { Ok(listen_fds_str) => { let listen_fds = match listen_fds_str.parse::<i32>() { Ok(v) => v, Err(error) => { log::warn!( "LISTEN_FDS entered is not a fd. Ignore the value. {:?}", error ); 0 } }; // The LISTEN_FDS will have to be passed to container init process. // The LISTEN_PID will be set to PID 1. Based on the spec, if // LISTEN_FDS is 0, the variable should be unset, so we just ignore // it here, if it is 0. if listen_fds > 0 { envs.append(&mut vec![ format!("LISTEN_FDS={}", listen_fds), "LISTEN_PID=1".to_string(), ]); } args.preserve_fds + listen_fds } Err(env::VarError::NotPresent) => args.preserve_fds, Err(env::VarError::NotUnicode(value)) => { log::warn!( "LISTEN_FDS entered is malformed: {:?}. Ignore the value.", &value ); args.preserve_fds } }; // clean up and handle perserved fds. cleanup_file_descriptors(preserve_fds).with_context(|| "Failed to clean up extra fds")?; // notify parents that the init process is ready to execute the payload. child.notify_parent()?; // listing on the notify socket for container start command notify_socket.wait_for_container_start()?; let args: &Vec<String> = &proc.args; utils::do_exec(&args[0], args, &envs)?; // After do_exec is called, the process is replaced with the container // payload through execvp, so
{ rootfs::prepare_rootfs( spec, rootfs, namespaces .clone_flags .contains(sched::CloneFlags::CLONE_NEWUSER), ) .with_context(|| "Failed to prepare rootfs")?; // change the root of filesystem of the process to the rootfs command .pivot_rootfs(rootfs) .with_context(|| format!("Failed to pivot root to {:?}", rootfs))?; }
conditional_block
init.rs
6884 fn ensure_procfs(path: &Path) -> Result<()> { let procfs_fd = fs::File::open(path)?; let fstat_info = sys::statfs::fstatfs(&procfs_fd.as_raw_fd())?; if fstat_info.filesystem_type() != sys::statfs::PROC_SUPER_MAGIC { bail!(format!("{:?} is not on the procfs", path)); } Ok(()) } // Get a list of open fds for the calling process. fn get_open_fds() -> Result<Vec<i32>> { const PROCFS_FD_PATH: &str = "/proc/self/fd"; ensure_procfs(Path::new(PROCFS_FD_PATH)) .with_context(|| format!("{} is not the actual procfs", PROCFS_FD_PATH))?; let fds: Vec<i32> = fs::read_dir(PROCFS_FD_PATH)? .filter_map(|entry| match entry { Ok(entry) => Some(entry.path()), Err(_) => None, }) .filter_map(|path| path.file_name().map(|file_name| file_name.to_owned())) .filter_map(|file_name| file_name.to_str().map(String::from)) .filter_map(|file_name| -> Option<i32> { // Convert the file name from string into i32. Since we are looking // at /proc/<pid>/fd, anything that's not a number (i32) can be // ignored. We are only interested in opened fds. match file_name.parse() { Ok(fd) => Some(fd), Err(_) => None, } }) .collect(); Ok(fds) } // Cleanup any extra file descriptors, so the new container process will not // leak a file descriptor from before execve gets executed. The first 3 fd will // stay open: stdio, stdout, and stderr. We would further preserve the next // "preserve_fds" number of fds. Set the rest of fd with CLOEXEC flag, so they // will be closed after execve into the container payload. We can't close the // fds immediatly since we at least still need it for the pipe used to wait on // starting the container. fn cleanup_file_descriptors(preserve_fds: i32) -> Result<()> { let open_fds = get_open_fds().with_context(|| "Failed to obtain opened fds")?; // Include stdin, stdout, and stderr for fd 0, 1, and 2 respectively. let min_fd = preserve_fds + 3; let to_be_cleaned_up_fds: Vec<i32> = open_fds .iter() .filter_map(|&fd| if fd >= min_fd { Some(fd) } else { None }) .collect(); to_be_cleaned_up_fds.iter().for_each(|&fd| { // Intentionally ignore errors here -- the cases where this might fail // are basically file descriptors that have already been closed. let _ = fcntl::fcntl(fd, fcntl::F_SETFD(fcntl::FdFlag::FD_CLOEXEC)); }); Ok(()) } pub struct ContainerInitArgs { /// Flag indicating if an init or a tenant container should be created pub init: bool, /// Interface to operating system primitives pub syscall: LinuxSyscall, /// OCI complient runtime spec pub spec: Spec, /// Root filesystem of the container pub rootfs: PathBuf, /// Socket to communicate the file descriptor of the ptty pub console_socket: Option<FileDescriptor>, /// Options for rootless containers pub rootless: Option<Rootless>, /// Path to the Unix Domain Socket to communicate container start pub notify_path: PathBuf, /// File descriptos preserved/passed to the container init process. pub preserve_fds: i32, /// Pipe used to communicate with the child process pub child: child::ChildProcess, } pub fn container_init(args: ContainerInitArgs) -> Result<()> { let command = &args.syscall; let spec = &args.spec; let linux = &spec.linux.as_ref().context("no linux in spec")?; let namespaces: Namespaces = linux.namespaces.clone().into(); // need to create the notify socket before we pivot root, since the unix // domain socket used here is outside of the rootfs of container let mut notify_socket: NotifyListener = NotifyListener::new(&args.notify_path)?; let proc = &spec.process.as_ref().context("no process in spec")?; let mut envs: Vec<String> = proc.env.clone(); let rootfs = &args.rootfs; let mut child = args.child; // if Out-of-memory score adjustment is set in specification. set the score // value for the current process check // https://dev.to/rrampage/surviving-the-linux-oom-killer-2ki9 for some more // information if let Some(ref resource) = linux.resources { if let Some(oom_score_adj) = resource.oom_score_adj { let mut f = fs::File::create("/proc/self/oom_score_adj")?; f.write_all(oom_score_adj.to_string().as_bytes())?; } } // if new user is specified in specification, this will be true and new // namespace will be created, check // https://man7.org/linux/man-pages/man7/user_namespaces.7.html for more // information if args.rootless.is_some() { // child needs to be dumpable, otherwise the non root parent is not // allowed to write the uid/gid maps prctl::set_dumpable(true).unwrap(); child.request_identifier_mapping()?; child.wait_for_mapping_ack()?; prctl::set_dumpable(false).unwrap(); } // set limits and namespaces to the process for rlimit in proc.rlimits.iter() { command.set_rlimit(rlimit).context("failed to set rlimit")?; } command .set_id(Uid::from_raw(0), Gid::from_raw(0)) .context("failed to become root")?; // set up tty if specified if let Some(csocketfd) = args.console_socket { tty::setup_console(&csocketfd)?; } // join existing namespaces namespaces.apply_setns()?; command.set_hostname(spec.hostname.as_ref().context("no hostname in spec")?)?; if proc.no_new_privileges { let _ = prctl::set_no_new_privileges(true); } if args.init { rootfs::prepare_rootfs( spec, rootfs, namespaces .clone_flags .contains(sched::CloneFlags::CLONE_NEWUSER), ) .with_context(|| "Failed to prepare rootfs")?; // change the root of filesystem of the process to the rootfs command .pivot_rootfs(rootfs) .with_context(|| format!("Failed to pivot root to {:?}", rootfs))?; } command.set_id(Uid::from_raw(proc.user.uid), Gid::from_raw(proc.user.gid))?; capabilities::reset_effective(command)?; if let Some(caps) = &proc.capabilities { capabilities::drop_privileges(caps, command)?; } // Take care of LISTEN_FDS used for systemd-active-socket. If the value is // not 0, then we have to preserve those fds as well, and set up the correct // environment variables. let preserve_fds: i32 = match env::var("LISTEN_FDS") { Ok(listen_fds_str) => { let listen_fds = match listen_fds_str.parse::<i32>() { Ok(v) => v, Err(error) => { log::warn!( "LISTEN_FDS entered is not a fd. Ignore the value. {:?}", error ); 0 } }; // The LISTEN_FDS will have to be passed to container init process. // The LISTEN_PID will be set to PID 1. Based on the spec, if // LISTEN_FDS is 0, the variable should be unset, so we just ignore // it here, if it is 0. if listen_fds > 0 { envs.append(&mut vec![ format!("LISTEN_FDS={}", listen_fds), "LISTEN_PID=1".to_string(), ]); } args.preserve_fds + listen_fds } Err(env::VarError::NotPresent) => args.preserve_fds, Err(env::VarError::NotUnicode(value)) => {
"LISTEN_FDS entered is malformed: {:?}. Ignore the value.", &value ); args.preserve_fds } }; // clean up and handle perserved fds. cleanup_file_descriptors(preserve_fds).with_context(|| "Failed to clean up extra fds")?; // notify parents that the init process is ready to execute the payload. child.notify_parent()?; // listing on the notify socket for container start command notify_socket.wait_for_container_start()?; let args: &Vec<String> = &proc.args; utils::do_exec(&args[0], args, &envs)?; // After do_exec is called, the process is replaced with the container // payload through execvp, so it
log::warn!(
random_line_split
init.rs
| file_name.to_str().map(String::from)) .filter_map(|file_name| -> Option<i32> { // Convert the file name from string into i32. Since we are looking // at /proc/<pid>/fd, anything that's not a number (i32) can be // ignored. We are only interested in opened fds. match file_name.parse() { Ok(fd) => Some(fd), Err(_) => None, } }) .collect(); Ok(fds) } // Cleanup any extra file descriptors, so the new container process will not // leak a file descriptor from before execve gets executed. The first 3 fd will // stay open: stdio, stdout, and stderr. We would further preserve the next // "preserve_fds" number of fds. Set the rest of fd with CLOEXEC flag, so they // will be closed after execve into the container payload. We can't close the // fds immediatly since we at least still need it for the pipe used to wait on // starting the container. fn cleanup_file_descriptors(preserve_fds: i32) -> Result<()> { let open_fds = get_open_fds().with_context(|| "Failed to obtain opened fds")?; // Include stdin, stdout, and stderr for fd 0, 1, and 2 respectively. let min_fd = preserve_fds + 3; let to_be_cleaned_up_fds: Vec<i32> = open_fds .iter() .filter_map(|&fd| if fd >= min_fd { Some(fd) } else { None }) .collect(); to_be_cleaned_up_fds.iter().for_each(|&fd| { // Intentionally ignore errors here -- the cases where this might fail // are basically file descriptors that have already been closed. let _ = fcntl::fcntl(fd, fcntl::F_SETFD(fcntl::FdFlag::FD_CLOEXEC)); }); Ok(()) } pub struct ContainerInitArgs { /// Flag indicating if an init or a tenant container should be created pub init: bool, /// Interface to operating system primitives pub syscall: LinuxSyscall, /// OCI complient runtime spec pub spec: Spec, /// Root filesystem of the container pub rootfs: PathBuf, /// Socket to communicate the file descriptor of the ptty pub console_socket: Option<FileDescriptor>, /// Options for rootless containers pub rootless: Option<Rootless>, /// Path to the Unix Domain Socket to communicate container start pub notify_path: PathBuf, /// File descriptos preserved/passed to the container init process. pub preserve_fds: i32, /// Pipe used to communicate with the child process pub child: child::ChildProcess, } pub fn container_init(args: ContainerInitArgs) -> Result<()> { let command = &args.syscall; let spec = &args.spec; let linux = &spec.linux.as_ref().context("no linux in spec")?; let namespaces: Namespaces = linux.namespaces.clone().into(); // need to create the notify socket before we pivot root, since the unix // domain socket used here is outside of the rootfs of container let mut notify_socket: NotifyListener = NotifyListener::new(&args.notify_path)?; let proc = &spec.process.as_ref().context("no process in spec")?; let mut envs: Vec<String> = proc.env.clone(); let rootfs = &args.rootfs; let mut child = args.child; // if Out-of-memory score adjustment is set in specification. set the score // value for the current process check // https://dev.to/rrampage/surviving-the-linux-oom-killer-2ki9 for some more // information if let Some(ref resource) = linux.resources { if let Some(oom_score_adj) = resource.oom_score_adj { let mut f = fs::File::create("/proc/self/oom_score_adj")?; f.write_all(oom_score_adj.to_string().as_bytes())?; } } // if new user is specified in specification, this will be true and new // namespace will be created, check // https://man7.org/linux/man-pages/man7/user_namespaces.7.html for more // information if args.rootless.is_some() { // child needs to be dumpable, otherwise the non root parent is not // allowed to write the uid/gid maps prctl::set_dumpable(true).unwrap(); child.request_identifier_mapping()?; child.wait_for_mapping_ack()?; prctl::set_dumpable(false).unwrap(); } // set limits and namespaces to the process for rlimit in proc.rlimits.iter() { command.set_rlimit(rlimit).context("failed to set rlimit")?; } command .set_id(Uid::from_raw(0), Gid::from_raw(0)) .context("failed to become root")?; // set up tty if specified if let Some(csocketfd) = args.console_socket { tty::setup_console(&csocketfd)?; } // join existing namespaces namespaces.apply_setns()?; command.set_hostname(spec.hostname.as_ref().context("no hostname in spec")?)?; if proc.no_new_privileges { let _ = prctl::set_no_new_privileges(true); } if args.init { rootfs::prepare_rootfs( spec, rootfs, namespaces .clone_flags .contains(sched::CloneFlags::CLONE_NEWUSER), ) .with_context(|| "Failed to prepare rootfs")?; // change the root of filesystem of the process to the rootfs command .pivot_rootfs(rootfs) .with_context(|| format!("Failed to pivot root to {:?}", rootfs))?; } command.set_id(Uid::from_raw(proc.user.uid), Gid::from_raw(proc.user.gid))?; capabilities::reset_effective(command)?; if let Some(caps) = &proc.capabilities { capabilities::drop_privileges(caps, command)?; } // Take care of LISTEN_FDS used for systemd-active-socket. If the value is // not 0, then we have to preserve those fds as well, and set up the correct // environment variables. let preserve_fds: i32 = match env::var("LISTEN_FDS") { Ok(listen_fds_str) => { let listen_fds = match listen_fds_str.parse::<i32>() { Ok(v) => v, Err(error) => { log::warn!( "LISTEN_FDS entered is not a fd. Ignore the value. {:?}", error ); 0 } }; // The LISTEN_FDS will have to be passed to container init process. // The LISTEN_PID will be set to PID 1. Based on the spec, if // LISTEN_FDS is 0, the variable should be unset, so we just ignore // it here, if it is 0. if listen_fds > 0 { envs.append(&mut vec![ format!("LISTEN_FDS={}", listen_fds), "LISTEN_PID=1".to_string(), ]); } args.preserve_fds + listen_fds } Err(env::VarError::NotPresent) => args.preserve_fds, Err(env::VarError::NotUnicode(value)) => { log::warn!( "LISTEN_FDS entered is malformed: {:?}. Ignore the value.", &value ); args.preserve_fds } }; // clean up and handle perserved fds. cleanup_file_descriptors(preserve_fds).with_context(|| "Failed to clean up extra fds")?; // notify parents that the init process is ready to execute the payload. child.notify_parent()?; // listing on the notify socket for container start command notify_socket.wait_for_container_start()?; let args: &Vec<String> = &proc.args; utils::do_exec(&args[0], args, &envs)?; // After do_exec is called, the process is replaced with the container // payload through execvp, so it should never reach here. unreachable!(); } #[cfg(test)] mod tests { use super::*; use anyhow::{bail, Result}; use nix::{fcntl, sys, unistd}; use std::fs; #[test] fn test_get_open_fds() -> Result<()> { let file = fs::File::open("/dev/null")?; let fd = file.as_raw_fd(); let open_fds = super::get_open_fds()?; if !open_fds.iter().any(|&v| v == fd) { bail!("Failed to find the opened dev null fds: {:?}", open_fds); } // explicitly close the file before the test case returns. drop(file); // The stdio fds should also be contained in the list of opened fds. if !vec![0, 1, 2] .iter() .all(|&stdio_fd| open_fds.iter().any(|&open_fd| open_fd == stdio_fd)) { bail!("Failed to find the stdio fds: {:?}", open_fds); } Ok(()) } #[test] fn
test_cleanup_file_descriptors
identifier_name
init.rs
6884 fn ensure_procfs(path: &Path) -> Result<()> { let procfs_fd = fs::File::open(path)?; let fstat_info = sys::statfs::fstatfs(&procfs_fd.as_raw_fd())?; if fstat_info.filesystem_type() != sys::statfs::PROC_SUPER_MAGIC { bail!(format!("{:?} is not on the procfs", path)); } Ok(()) } // Get a list of open fds for the calling process. fn get_open_fds() -> Result<Vec<i32>>
}) .collect(); Ok(fds) } // Cleanup any extra file descriptors, so the new container process will not // leak a file descriptor from before execve gets executed. The first 3 fd will // stay open: stdio, stdout, and stderr. We would further preserve the next // "preserve_fds" number of fds. Set the rest of fd with CLOEXEC flag, so they // will be closed after execve into the container payload. We can't close the // fds immediatly since we at least still need it for the pipe used to wait on // starting the container. fn cleanup_file_descriptors(preserve_fds: i32) -> Result<()> { let open_fds = get_open_fds().with_context(|| "Failed to obtain opened fds")?; // Include stdin, stdout, and stderr for fd 0, 1, and 2 respectively. let min_fd = preserve_fds + 3; let to_be_cleaned_up_fds: Vec<i32> = open_fds .iter() .filter_map(|&fd| if fd >= min_fd { Some(fd) } else { None }) .collect(); to_be_cleaned_up_fds.iter().for_each(|&fd| { // Intentionally ignore errors here -- the cases where this might fail // are basically file descriptors that have already been closed. let _ = fcntl::fcntl(fd, fcntl::F_SETFD(fcntl::FdFlag::FD_CLOEXEC)); }); Ok(()) } pub struct ContainerInitArgs { /// Flag indicating if an init or a tenant container should be created pub init: bool, /// Interface to operating system primitives pub syscall: LinuxSyscall, /// OCI complient runtime spec pub spec: Spec, /// Root filesystem of the container pub rootfs: PathBuf, /// Socket to communicate the file descriptor of the ptty pub console_socket: Option<FileDescriptor>, /// Options for rootless containers pub rootless: Option<Rootless>, /// Path to the Unix Domain Socket to communicate container start pub notify_path: PathBuf, /// File descriptos preserved/passed to the container init process. pub preserve_fds: i32, /// Pipe used to communicate with the child process pub child: child::ChildProcess, } pub fn container_init(args: ContainerInitArgs) -> Result<()> { let command = &args.syscall; let spec = &args.spec; let linux = &spec.linux.as_ref().context("no linux in spec")?; let namespaces: Namespaces = linux.namespaces.clone().into(); // need to create the notify socket before we pivot root, since the unix // domain socket used here is outside of the rootfs of container let mut notify_socket: NotifyListener = NotifyListener::new(&args.notify_path)?; let proc = &spec.process.as_ref().context("no process in spec")?; let mut envs: Vec<String> = proc.env.clone(); let rootfs = &args.rootfs; let mut child = args.child; // if Out-of-memory score adjustment is set in specification. set the score // value for the current process check // https://dev.to/rrampage/surviving-the-linux-oom-killer-2ki9 for some more // information if let Some(ref resource) = linux.resources { if let Some(oom_score_adj) = resource.oom_score_adj { let mut f = fs::File::create("/proc/self/oom_score_adj")?; f.write_all(oom_score_adj.to_string().as_bytes())?; } } // if new user is specified in specification, this will be true and new // namespace will be created, check // https://man7.org/linux/man-pages/man7/user_namespaces.7.html for more // information if args.rootless.is_some() { // child needs to be dumpable, otherwise the non root parent is not // allowed to write the uid/gid maps prctl::set_dumpable(true).unwrap(); child.request_identifier_mapping()?; child.wait_for_mapping_ack()?; prctl::set_dumpable(false).unwrap(); } // set limits and namespaces to the process for rlimit in proc.rlimits.iter() { command.set_rlimit(rlimit).context("failed to set rlimit")?; } command .set_id(Uid::from_raw(0), Gid::from_raw(0)) .context("failed to become root")?; // set up tty if specified if let Some(csocketfd) = args.console_socket { tty::setup_console(&csocketfd)?; } // join existing namespaces namespaces.apply_setns()?; command.set_hostname(spec.hostname.as_ref().context("no hostname in spec")?)?; if proc.no_new_privileges { let _ = prctl::set_no_new_privileges(true); } if args.init { rootfs::prepare_rootfs( spec, rootfs, namespaces .clone_flags .contains(sched::CloneFlags::CLONE_NEWUSER), ) .with_context(|| "Failed to prepare rootfs")?; // change the root of filesystem of the process to the rootfs command .pivot_rootfs(rootfs) .with_context(|| format!("Failed to pivot root to {:?}", rootfs))?; } command.set_id(Uid::from_raw(proc.user.uid), Gid::from_raw(proc.user.gid))?; capabilities::reset_effective(command)?; if let Some(caps) = &proc.capabilities { capabilities::drop_privileges(caps, command)?; } // Take care of LISTEN_FDS used for systemd-active-socket. If the value is // not 0, then we have to preserve those fds as well, and set up the correct // environment variables. let preserve_fds: i32 = match env::var("LISTEN_FDS") { Ok(listen_fds_str) => { let listen_fds = match listen_fds_str.parse::<i32>() { Ok(v) => v, Err(error) => { log::warn!( "LISTEN_FDS entered is not a fd. Ignore the value. {:?}", error ); 0 } }; // The LISTEN_FDS will have to be passed to container init process. // The LISTEN_PID will be set to PID 1. Based on the spec, if // LISTEN_FDS is 0, the variable should be unset, so we just ignore // it here, if it is 0. if listen_fds > 0 { envs.append(&mut vec![ format!("LISTEN_FDS={}", listen_fds), "LISTEN_PID=1".to_string(), ]); } args.preserve_fds + listen_fds } Err(env::VarError::NotPresent) => args.preserve_fds, Err(env::VarError::NotUnicode(value)) => { log::warn!( "LISTEN_FDS entered is malformed: {:?}. Ignore the value.", &value ); args.preserve_fds } }; // clean up and handle perserved fds. cleanup_file_descriptors(preserve_fds).with_context(|| "Failed to clean up extra fds")?; // notify parents that the init process is ready to execute the payload. child.notify_parent()?; // listing on the notify socket for container start command notify_socket.wait_for_container_start()?; let args: &Vec<String> = &proc.args; utils::do_exec(&args[0], args, &envs)?; // After do_exec is called, the process is replaced with the container // payload through execvp, so
{ const PROCFS_FD_PATH: &str = "/proc/self/fd"; ensure_procfs(Path::new(PROCFS_FD_PATH)) .with_context(|| format!("{} is not the actual procfs", PROCFS_FD_PATH))?; let fds: Vec<i32> = fs::read_dir(PROCFS_FD_PATH)? .filter_map(|entry| match entry { Ok(entry) => Some(entry.path()), Err(_) => None, }) .filter_map(|path| path.file_name().map(|file_name| file_name.to_owned())) .filter_map(|file_name| file_name.to_str().map(String::from)) .filter_map(|file_name| -> Option<i32> { // Convert the file name from string into i32. Since we are looking // at /proc/<pid>/fd, anything that's not a number (i32) can be // ignored. We are only interested in opened fds. match file_name.parse() { Ok(fd) => Some(fd), Err(_) => None, }
identifier_body
batch-rotate.go
exported // BatchKeyRotateKV is a datatype that holds key and values for filtering of objects // used by metadata filter as well as tags based filtering. type BatchKeyRotateKV struct { Key string `yaml:"key" json:"key"` Value string `yaml:"value" json:"value"` } // Validate returns an error if key is empty func (kv BatchKeyRotateKV) Validate() error
// Empty indicates if kv is not set func (kv BatchKeyRotateKV) Empty() bool { return kv.Key == "" && kv.Value == "" } // Match matches input kv with kv, value will be wildcard matched depending on the user input func (kv BatchKeyRotateKV) Match(ikv BatchKeyRotateKV) bool { if kv.Empty() { return true } if strings.EqualFold(kv.Key, ikv.Key) { return wildcard.Match(kv.Value, ikv.Value) } return false } // BatchKeyRotateRetry datatype represents total retry attempts and delay between each retries. type BatchKeyRotateRetry struct { Attempts int `yaml:"attempts" json:"attempts"` // number of retry attempts Delay time.Duration `yaml:"delay" json:"delay"` // delay between each retries } // Validate validates input replicate retries. func (r BatchKeyRotateRetry) Validate() error { if r.Attempts < 0 { return errInvalidArgument } if r.Delay < 0 { return errInvalidArgument } return nil } // BatchKeyRotationType defines key rotation type type BatchKeyRotationType string const ( sses3 BatchKeyRotationType = "sse-s3" ssekms BatchKeyRotationType = "sse-kms" ) // BatchJobKeyRotateEncryption defines key rotation encryption options passed type BatchJobKeyRotateEncryption struct { Type BatchKeyRotationType `yaml:"type" json:"type"` Key string `yaml:"key" json:"key"` Context string `yaml:"context" json:"context"` kmsContext kms.Context `msg:"-"` } // Validate validates input key rotation encryption options. func (e BatchJobKeyRotateEncryption) Validate() error { if e.Type != sses3 && e.Type != ssekms { return errInvalidArgument } spaces := strings.HasPrefix(e.Key, " ") || strings.HasSuffix(e.Key, " ") if e.Type == ssekms && spaces { return crypto.ErrInvalidEncryptionKeyID } if e.Type == ssekms && GlobalKMS != nil { ctx := kms.Context{} if e.Context != "" { b, err := base64.StdEncoding.DecodeString(e.Context) if err != nil { return err } json := jsoniter.ConfigCompatibleWithStandardLibrary if err := json.Unmarshal(b, &ctx); err != nil { return err } } e.kmsContext = kms.Context{} for k, v := range ctx { e.kmsContext[k] = v } ctx["MinIO batch API"] = "batchrotate" // Context for a test key operation if _, err := GlobalKMS.GenerateKey(GlobalContext, e.Key, ctx); err != nil { return err } } return nil } // BatchKeyRotateFilter holds all the filters currently supported for batch replication type BatchKeyRotateFilter struct { NewerThan time.Duration `yaml:"newerThan,omitempty" json:"newerThan"` OlderThan time.Duration `yaml:"olderThan,omitempty" json:"olderThan"` CreatedAfter time.Time `yaml:"createdAfter,omitempty" json:"createdAfter"` CreatedBefore time.Time `yaml:"createdBefore,omitempty" json:"createdBefore"` Tags []BatchKeyRotateKV `yaml:"tags,omitempty" json:"tags"` Metadata []BatchKeyRotateKV `yaml:"metadata,omitempty" json:"metadata"` KMSKeyID string `yaml:"kmskeyid" json:"kmskey"` } // BatchKeyRotateNotification success or failure notification endpoint for each job attempts type BatchKeyRotateNotification struct { Endpoint string `yaml:"endpoint" json:"endpoint"` Token string `yaml:"token" json:"token"` } // BatchJobKeyRotateFlags various configurations for replication job definition currently includes // - filter // - notify // - retry type BatchJobKeyRotateFlags struct { Filter BatchKeyRotateFilter `yaml:"filter" json:"filter"` Notify BatchKeyRotateNotification `yaml:"notify" json:"notify"` Retry BatchKeyRotateRetry `yaml:"retry" json:"retry"` } // BatchJobKeyRotateV1 v1 of batch key rotation job type BatchJobKeyRotateV1 struct { APIVersion string `yaml:"apiVersion" json:"apiVersion"` Flags BatchJobKeyRotateFlags `yaml:"flags" json:"flags"` Bucket string `yaml:"bucket" json:"bucket"` Prefix string `yaml:"prefix" json:"prefix"` Endpoint string `yaml:"endpoint" json:"endpoint"` Encryption BatchJobKeyRotateEncryption `yaml:"encryption" json:"encryption"` } // Notify notifies notification endpoint if configured regarding job failure or success. func (r BatchJobKeyRotateV1) Notify(ctx context.Context, body io.Reader) error { if r.Flags.Notify.Endpoint == "" { return nil } ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.Flags.Notify.Endpoint, body) if err != nil { return err } if r.Flags.Notify.Token != "" { req.Header.Set("Authorization", r.Flags.Notify.Token) } clnt := http.Client{Transport: getRemoteInstanceTransport} resp, err := clnt.Do(req) if err != nil { return err } xhttp.DrainBody(resp.Body) if resp.StatusCode != http.StatusOK { return errors.New(resp.Status) } return nil } // KeyRotate rotates encryption key of an object func (r *BatchJobKeyRotateV1) KeyRotate(ctx context.Context, api ObjectLayer, objInfo ObjectInfo) error { srcBucket := r.Bucket srcObject := objInfo.Name if objInfo.DeleteMarker || !objInfo.VersionPurgeStatus.Empty() { return nil } sseKMS := crypto.S3KMS.IsEncrypted(objInfo.UserDefined) sseS3 := crypto.S3.IsEncrypted(objInfo.UserDefined) if !sseKMS && !sseS3 { // neither sse-s3 nor sse-kms disallowed return errInvalidEncryptionParameters } if sseKMS && r.Encryption.Type == sses3 { // previously encrypted with sse-kms, now sse-s3 disallowed return errInvalidEncryptionParameters } versioned := globalBucketVersioningSys.PrefixEnabled(srcBucket, srcObject) versionSuspended := globalBucketVersioningSys.PrefixSuspended(srcBucket, srcObject) lock := api.NewNSLock(r.Bucket, objInfo.Name) lkctx, err := lock.GetLock(ctx, globalOperationTimeout) if err != nil { return err } ctx = lkctx.Context() defer lock.Unlock(lkctx) opts := ObjectOptions{ VersionID: objInfo.VersionID, Versioned: versioned, VersionSuspended: versionSuspended, NoLock: true, } obj, err := api.GetObjectInfo(ctx, r.Bucket, objInfo.Name, opts) if err != nil { return err } oi := obj.Clone() var ( newKeyID string newKeyContext kms.Context ) encMetadata := make(map[string]string) for k, v := range oi.UserDefined { if strings.HasPrefix(strings.ToLower(k), ReservedMetadataPrefixLower) { encMetadata[k] = v } } if (sseKMS || sseS3) && r.Encryption.Type == ssekms { if err = r.Encryption.Validate(); err != nil { return err } newKeyID = strings.TrimPrefix(r.Encryption.Key, crypto.ARNPrefix) newKeyContext = r.Encryption.kmsContext } if err = rotateKey(ctx, []byte{}, newKeyID, []byte{}, r.Bucket, oi.Name, encMetadata, newKeyContext); err != nil { return err } // Since we are rotating the keys, make sure to update the metadata. oi.metadataOnly = true oi.keyRotation = true for k, v := range encMetadata { oi.UserDefined[k] = v } if _, err := api.CopyObject(ctx, r.Bucket, oi.Name, r.Bucket, oi.Name, oi, ObjectOptions{ VersionID: oi.VersionID, }, ObjectOptions{ VersionID: oi.VersionID, NoLock: true, }); err != nil { return err } return nil } const ( batchKeyRotationName = "batch-rotate.bin" batchKeyRotationFormat = 1 batchKeyRotateVersionV1 = 1 batchKeyRotateVersion = batchKeyRotateVersionV1 batchKeyRotateAPIVersion = "v1" batchKeyRotateJobDefaultRetries = 3 batchKeyRotateJobDefaultRetryDelay = 250 * time.Millisecond
{ if kv.Key == "" { return errInvalidArgument } return nil }
identifier_body
batch-rotate.go
exported // BatchKeyRotateKV is a datatype that holds key and values for filtering of objects // used by metadata filter as well as tags based filtering. type BatchKeyRotateKV struct { Key string `yaml:"key" json:"key"` Value string `yaml:"value" json:"value"` } // Validate returns an error if key is empty func (kv BatchKeyRotateKV) Validate() error { if kv.Key == "" { return errInvalidArgument } return nil } // Empty indicates if kv is not set func (kv BatchKeyRotateKV) Empty() bool { return kv.Key == "" && kv.Value == "" } // Match matches input kv with kv, value will be wildcard matched depending on the user input func (kv BatchKeyRotateKV) Match(ikv BatchKeyRotateKV) bool { if kv.Empty() { return true } if strings.EqualFold(kv.Key, ikv.Key) { return wildcard.Match(kv.Value, ikv.Value) } return false } // BatchKeyRotateRetry datatype represents total retry attempts and delay between each retries. type BatchKeyRotateRetry struct { Attempts int `yaml:"attempts" json:"attempts"` // number of retry attempts Delay time.Duration `yaml:"delay" json:"delay"` // delay between each retries } // Validate validates input replicate retries. func (r BatchKeyRotateRetry)
() error { if r.Attempts < 0 { return errInvalidArgument } if r.Delay < 0 { return errInvalidArgument } return nil } // BatchKeyRotationType defines key rotation type type BatchKeyRotationType string const ( sses3 BatchKeyRotationType = "sse-s3" ssekms BatchKeyRotationType = "sse-kms" ) // BatchJobKeyRotateEncryption defines key rotation encryption options passed type BatchJobKeyRotateEncryption struct { Type BatchKeyRotationType `yaml:"type" json:"type"` Key string `yaml:"key" json:"key"` Context string `yaml:"context" json:"context"` kmsContext kms.Context `msg:"-"` } // Validate validates input key rotation encryption options. func (e BatchJobKeyRotateEncryption) Validate() error { if e.Type != sses3 && e.Type != ssekms { return errInvalidArgument } spaces := strings.HasPrefix(e.Key, " ") || strings.HasSuffix(e.Key, " ") if e.Type == ssekms && spaces { return crypto.ErrInvalidEncryptionKeyID } if e.Type == ssekms && GlobalKMS != nil { ctx := kms.Context{} if e.Context != "" { b, err := base64.StdEncoding.DecodeString(e.Context) if err != nil { return err } json := jsoniter.ConfigCompatibleWithStandardLibrary if err := json.Unmarshal(b, &ctx); err != nil { return err } } e.kmsContext = kms.Context{} for k, v := range ctx { e.kmsContext[k] = v } ctx["MinIO batch API"] = "batchrotate" // Context for a test key operation if _, err := GlobalKMS.GenerateKey(GlobalContext, e.Key, ctx); err != nil { return err } } return nil } // BatchKeyRotateFilter holds all the filters currently supported for batch replication type BatchKeyRotateFilter struct { NewerThan time.Duration `yaml:"newerThan,omitempty" json:"newerThan"` OlderThan time.Duration `yaml:"olderThan,omitempty" json:"olderThan"` CreatedAfter time.Time `yaml:"createdAfter,omitempty" json:"createdAfter"` CreatedBefore time.Time `yaml:"createdBefore,omitempty" json:"createdBefore"` Tags []BatchKeyRotateKV `yaml:"tags,omitempty" json:"tags"` Metadata []BatchKeyRotateKV `yaml:"metadata,omitempty" json:"metadata"` KMSKeyID string `yaml:"kmskeyid" json:"kmskey"` } // BatchKeyRotateNotification success or failure notification endpoint for each job attempts type BatchKeyRotateNotification struct { Endpoint string `yaml:"endpoint" json:"endpoint"` Token string `yaml:"token" json:"token"` } // BatchJobKeyRotateFlags various configurations for replication job definition currently includes // - filter // - notify // - retry type BatchJobKeyRotateFlags struct { Filter BatchKeyRotateFilter `yaml:"filter" json:"filter"` Notify BatchKeyRotateNotification `yaml:"notify" json:"notify"` Retry BatchKeyRotateRetry `yaml:"retry" json:"retry"` } // BatchJobKeyRotateV1 v1 of batch key rotation job type BatchJobKeyRotateV1 struct { APIVersion string `yaml:"apiVersion" json:"apiVersion"` Flags BatchJobKeyRotateFlags `yaml:"flags" json:"flags"` Bucket string `yaml:"bucket" json:"bucket"` Prefix string `yaml:"prefix" json:"prefix"` Endpoint string `yaml:"endpoint" json:"endpoint"` Encryption BatchJobKeyRotateEncryption `yaml:"encryption" json:"encryption"` } // Notify notifies notification endpoint if configured regarding job failure or success. func (r BatchJobKeyRotateV1) Notify(ctx context.Context, body io.Reader) error { if r.Flags.Notify.Endpoint == "" { return nil } ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.Flags.Notify.Endpoint, body) if err != nil { return err } if r.Flags.Notify.Token != "" { req.Header.Set("Authorization", r.Flags.Notify.Token) } clnt := http.Client{Transport: getRemoteInstanceTransport} resp, err := clnt.Do(req) if err != nil { return err } xhttp.DrainBody(resp.Body) if resp.StatusCode != http.StatusOK { return errors.New(resp.Status) } return nil } // KeyRotate rotates encryption key of an object func (r *BatchJobKeyRotateV1) KeyRotate(ctx context.Context, api ObjectLayer, objInfo ObjectInfo) error { srcBucket := r.Bucket srcObject := objInfo.Name if objInfo.DeleteMarker || !objInfo.VersionPurgeStatus.Empty() { return nil } sseKMS := crypto.S3KMS.IsEncrypted(objInfo.UserDefined) sseS3 := crypto.S3.IsEncrypted(objInfo.UserDefined) if !sseKMS && !sseS3 { // neither sse-s3 nor sse-kms disallowed return errInvalidEncryptionParameters } if sseKMS && r.Encryption.Type == sses3 { // previously encrypted with sse-kms, now sse-s3 disallowed return errInvalidEncryptionParameters } versioned := globalBucketVersioningSys.PrefixEnabled(srcBucket, srcObject) versionSuspended := globalBucketVersioningSys.PrefixSuspended(srcBucket, srcObject) lock := api.NewNSLock(r.Bucket, objInfo.Name) lkctx, err := lock.GetLock(ctx, globalOperationTimeout) if err != nil { return err } ctx = lkctx.Context() defer lock.Unlock(lkctx) opts := ObjectOptions{ VersionID: objInfo.VersionID, Versioned: versioned, VersionSuspended: versionSuspended, NoLock: true, } obj, err := api.GetObjectInfo(ctx, r.Bucket, objInfo.Name, opts) if err != nil { return err } oi := obj.Clone() var ( newKeyID string newKeyContext kms.Context ) encMetadata := make(map[string]string) for k, v := range oi.UserDefined { if strings.HasPrefix(strings.ToLower(k), ReservedMetadataPrefixLower) { encMetadata[k] = v } } if (sseKMS || sseS3) && r.Encryption.Type == ssekms { if err = r.Encryption.Validate(); err != nil { return err } newKeyID = strings.TrimPrefix(r.Encryption.Key, crypto.ARNPrefix) newKeyContext = r.Encryption.kmsContext } if err = rotateKey(ctx, []byte{}, newKeyID, []byte{}, r.Bucket, oi.Name, encMetadata, newKeyContext); err != nil { return err } // Since we are rotating the keys, make sure to update the metadata. oi.metadataOnly = true oi.keyRotation = true for k, v := range encMetadata { oi.UserDefined[k] = v } if _, err := api.CopyObject(ctx, r.Bucket, oi.Name, r.Bucket, oi.Name, oi, ObjectOptions{ VersionID: oi.VersionID, }, ObjectOptions{ VersionID: oi.VersionID, NoLock: true, }); err != nil { return err } return nil } const ( batchKeyRotationName = "batch-rotate.bin" batchKeyRotationFormat = 1 batchKeyRotateVersionV1 = 1 batchKeyRotateVersion = batchKeyRotateVersionV1 batchKeyRotateAPIVersion = "v1" batchKeyRotateJobDefaultRetries = 3 batchKeyRotateJobDefaultRetryDelay = 250 * time.Millisecond
Validate
identifier_name
batch-rotate.go
unexported // BatchKeyRotateKV is a datatype that holds key and values for filtering of objects // used by metadata filter as well as tags based filtering. type BatchKeyRotateKV struct { Key string `yaml:"key" json:"key"` Value string `yaml:"value" json:"value"` } // Validate returns an error if key is empty func (kv BatchKeyRotateKV) Validate() error { if kv.Key == "" { return errInvalidArgument } return nil } // Empty indicates if kv is not set func (kv BatchKeyRotateKV) Empty() bool { return kv.Key == "" && kv.Value == "" } // Match matches input kv with kv, value will be wildcard matched depending on the user input func (kv BatchKeyRotateKV) Match(ikv BatchKeyRotateKV) bool { if kv.Empty() { return true } if strings.EqualFold(kv.Key, ikv.Key) { return wildcard.Match(kv.Value, ikv.Value) } return false } // BatchKeyRotateRetry datatype represents total retry attempts and delay between each retries. type BatchKeyRotateRetry struct { Attempts int `yaml:"attempts" json:"attempts"` // number of retry attempts Delay time.Duration `yaml:"delay" json:"delay"` // delay between each retries } // Validate validates input replicate retries. func (r BatchKeyRotateRetry) Validate() error { if r.Attempts < 0 { return errInvalidArgument } if r.Delay < 0 { return errInvalidArgument } return nil } // BatchKeyRotationType defines key rotation type type BatchKeyRotationType string const ( sses3 BatchKeyRotationType = "sse-s3" ssekms BatchKeyRotationType = "sse-kms" ) // BatchJobKeyRotateEncryption defines key rotation encryption options passed type BatchJobKeyRotateEncryption struct { Type BatchKeyRotationType `yaml:"type" json:"type"` Key string `yaml:"key" json:"key"` Context string `yaml:"context" json:"context"` kmsContext kms.Context `msg:"-"` } // Validate validates input key rotation encryption options. func (e BatchJobKeyRotateEncryption) Validate() error { if e.Type != sses3 && e.Type != ssekms { return errInvalidArgument } spaces := strings.HasPrefix(e.Key, " ") || strings.HasSuffix(e.Key, " ") if e.Type == ssekms && spaces { return crypto.ErrInvalidEncryptionKeyID } if e.Type == ssekms && GlobalKMS != nil { ctx := kms.Context{} if e.Context != "" { b, err := base64.StdEncoding.DecodeString(e.Context) if err != nil { return err } json := jsoniter.ConfigCompatibleWithStandardLibrary if err := json.Unmarshal(b, &ctx); err != nil { return err } } e.kmsContext = kms.Context{} for k, v := range ctx { e.kmsContext[k] = v
} } return nil } // BatchKeyRotateFilter holds all the filters currently supported for batch replication type BatchKeyRotateFilter struct { NewerThan time.Duration `yaml:"newerThan,omitempty" json:"newerThan"` OlderThan time.Duration `yaml:"olderThan,omitempty" json:"olderThan"` CreatedAfter time.Time `yaml:"createdAfter,omitempty" json:"createdAfter"` CreatedBefore time.Time `yaml:"createdBefore,omitempty" json:"createdBefore"` Tags []BatchKeyRotateKV `yaml:"tags,omitempty" json:"tags"` Metadata []BatchKeyRotateKV `yaml:"metadata,omitempty" json:"metadata"` KMSKeyID string `yaml:"kmskeyid" json:"kmskey"` } // BatchKeyRotateNotification success or failure notification endpoint for each job attempts type BatchKeyRotateNotification struct { Endpoint string `yaml:"endpoint" json:"endpoint"` Token string `yaml:"token" json:"token"` } // BatchJobKeyRotateFlags various configurations for replication job definition currently includes // - filter // - notify // - retry type BatchJobKeyRotateFlags struct { Filter BatchKeyRotateFilter `yaml:"filter" json:"filter"` Notify BatchKeyRotateNotification `yaml:"notify" json:"notify"` Retry BatchKeyRotateRetry `yaml:"retry" json:"retry"` } // BatchJobKeyRotateV1 v1 of batch key rotation job type BatchJobKeyRotateV1 struct { APIVersion string `yaml:"apiVersion" json:"apiVersion"` Flags BatchJobKeyRotateFlags `yaml:"flags" json:"flags"` Bucket string `yaml:"bucket" json:"bucket"` Prefix string `yaml:"prefix" json:"prefix"` Endpoint string `yaml:"endpoint" json:"endpoint"` Encryption BatchJobKeyRotateEncryption `yaml:"encryption" json:"encryption"` } // Notify notifies notification endpoint if configured regarding job failure or success. func (r BatchJobKeyRotateV1) Notify(ctx context.Context, body io.Reader) error { if r.Flags.Notify.Endpoint == "" { return nil } ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.Flags.Notify.Endpoint, body) if err != nil { return err } if r.Flags.Notify.Token != "" { req.Header.Set("Authorization", r.Flags.Notify.Token) } clnt := http.Client{Transport: getRemoteInstanceTransport} resp, err := clnt.Do(req) if err != nil { return err } xhttp.DrainBody(resp.Body) if resp.StatusCode != http.StatusOK { return errors.New(resp.Status) } return nil } // KeyRotate rotates encryption key of an object func (r *BatchJobKeyRotateV1) KeyRotate(ctx context.Context, api ObjectLayer, objInfo ObjectInfo) error { srcBucket := r.Bucket srcObject := objInfo.Name if objInfo.DeleteMarker || !objInfo.VersionPurgeStatus.Empty() { return nil } sseKMS := crypto.S3KMS.IsEncrypted(objInfo.UserDefined) sseS3 := crypto.S3.IsEncrypted(objInfo.UserDefined) if !sseKMS && !sseS3 { // neither sse-s3 nor sse-kms disallowed return errInvalidEncryptionParameters } if sseKMS && r.Encryption.Type == sses3 { // previously encrypted with sse-kms, now sse-s3 disallowed return errInvalidEncryptionParameters } versioned := globalBucketVersioningSys.PrefixEnabled(srcBucket, srcObject) versionSuspended := globalBucketVersioningSys.PrefixSuspended(srcBucket, srcObject) lock := api.NewNSLock(r.Bucket, objInfo.Name) lkctx, err := lock.GetLock(ctx, globalOperationTimeout) if err != nil { return err } ctx = lkctx.Context() defer lock.Unlock(lkctx) opts := ObjectOptions{ VersionID: objInfo.VersionID, Versioned: versioned, VersionSuspended: versionSuspended, NoLock: true, } obj, err := api.GetObjectInfo(ctx, r.Bucket, objInfo.Name, opts) if err != nil { return err } oi := obj.Clone() var ( newKeyID string newKeyContext kms.Context ) encMetadata := make(map[string]string) for k, v := range oi.UserDefined { if strings.HasPrefix(strings.ToLower(k), ReservedMetadataPrefixLower) { encMetadata[k] = v } } if (sseKMS || sseS3) && r.Encryption.Type == ssekms { if err = r.Encryption.Validate(); err != nil { return err } newKeyID = strings.TrimPrefix(r.Encryption.Key, crypto.ARNPrefix) newKeyContext = r.Encryption.kmsContext } if err = rotateKey(ctx, []byte{}, newKeyID, []byte{}, r.Bucket, oi.Name, encMetadata, newKeyContext); err != nil { return err } // Since we are rotating the keys, make sure to update the metadata. oi.metadataOnly = true oi.keyRotation = true for k, v := range encMetadata { oi.UserDefined[k] = v } if _, err := api.CopyObject(ctx, r.Bucket, oi.Name, r.Bucket, oi.Name, oi, ObjectOptions{ VersionID: oi.VersionID, }, ObjectOptions{ VersionID: oi.VersionID, NoLock: true, }); err != nil { return err } return nil } const ( batchKeyRotationName = "batch-rotate.bin" batchKeyRotationFormat = 1 batchKeyRotateVersionV1 = 1 batchKeyRotateVersion = batchKeyRotateVersionV1 batchKeyRotateAPIVersion = "v1" batchKeyRotateJobDefaultRetries = 3 batchKeyRotateJobDefaultRetryDelay = 250 * time.Millisecond ) //
} ctx["MinIO batch API"] = "batchrotate" // Context for a test key operation if _, err := GlobalKMS.GenerateKey(GlobalContext, e.Key, ctx); err != nil { return err
random_line_split
batch-rotate.go
.WithTimeout(ctx, 10*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.Flags.Notify.Endpoint, body) if err != nil { return err } if r.Flags.Notify.Token != "" { req.Header.Set("Authorization", r.Flags.Notify.Token) } clnt := http.Client{Transport: getRemoteInstanceTransport} resp, err := clnt.Do(req) if err != nil { return err } xhttp.DrainBody(resp.Body) if resp.StatusCode != http.StatusOK { return errors.New(resp.Status) } return nil } // KeyRotate rotates encryption key of an object func (r *BatchJobKeyRotateV1) KeyRotate(ctx context.Context, api ObjectLayer, objInfo ObjectInfo) error { srcBucket := r.Bucket srcObject := objInfo.Name if objInfo.DeleteMarker || !objInfo.VersionPurgeStatus.Empty() { return nil } sseKMS := crypto.S3KMS.IsEncrypted(objInfo.UserDefined) sseS3 := crypto.S3.IsEncrypted(objInfo.UserDefined) if !sseKMS && !sseS3 { // neither sse-s3 nor sse-kms disallowed return errInvalidEncryptionParameters } if sseKMS && r.Encryption.Type == sses3 { // previously encrypted with sse-kms, now sse-s3 disallowed return errInvalidEncryptionParameters } versioned := globalBucketVersioningSys.PrefixEnabled(srcBucket, srcObject) versionSuspended := globalBucketVersioningSys.PrefixSuspended(srcBucket, srcObject) lock := api.NewNSLock(r.Bucket, objInfo.Name) lkctx, err := lock.GetLock(ctx, globalOperationTimeout) if err != nil { return err } ctx = lkctx.Context() defer lock.Unlock(lkctx) opts := ObjectOptions{ VersionID: objInfo.VersionID, Versioned: versioned, VersionSuspended: versionSuspended, NoLock: true, } obj, err := api.GetObjectInfo(ctx, r.Bucket, objInfo.Name, opts) if err != nil { return err } oi := obj.Clone() var ( newKeyID string newKeyContext kms.Context ) encMetadata := make(map[string]string) for k, v := range oi.UserDefined { if strings.HasPrefix(strings.ToLower(k), ReservedMetadataPrefixLower) { encMetadata[k] = v } } if (sseKMS || sseS3) && r.Encryption.Type == ssekms { if err = r.Encryption.Validate(); err != nil { return err } newKeyID = strings.TrimPrefix(r.Encryption.Key, crypto.ARNPrefix) newKeyContext = r.Encryption.kmsContext } if err = rotateKey(ctx, []byte{}, newKeyID, []byte{}, r.Bucket, oi.Name, encMetadata, newKeyContext); err != nil { return err } // Since we are rotating the keys, make sure to update the metadata. oi.metadataOnly = true oi.keyRotation = true for k, v := range encMetadata { oi.UserDefined[k] = v } if _, err := api.CopyObject(ctx, r.Bucket, oi.Name, r.Bucket, oi.Name, oi, ObjectOptions{ VersionID: oi.VersionID, }, ObjectOptions{ VersionID: oi.VersionID, NoLock: true, }); err != nil { return err } return nil } const ( batchKeyRotationName = "batch-rotate.bin" batchKeyRotationFormat = 1 batchKeyRotateVersionV1 = 1 batchKeyRotateVersion = batchKeyRotateVersionV1 batchKeyRotateAPIVersion = "v1" batchKeyRotateJobDefaultRetries = 3 batchKeyRotateJobDefaultRetryDelay = 250 * time.Millisecond ) // Start the batch key rottion job, resumes if there was a pending job via "job.ID" func (r *BatchJobKeyRotateV1) Start(ctx context.Context, api ObjectLayer, job BatchJobRequest) error { ri := &batchJobInfo{ JobID: job.ID, JobType: string(job.Type()), StartTime: job.Started, } if err := ri.load(ctx, api, job); err != nil { return err } globalBatchJobsMetrics.save(job.ID, ri) lastObject := ri.Object delay := job.KeyRotate.Flags.Retry.Delay if delay == 0 { delay = batchKeyRotateJobDefaultRetryDelay } rnd := rand.New(rand.NewSource(time.Now().UnixNano())) skip := func(info FileInfo) (ok bool) { if r.Flags.Filter.OlderThan > 0 && time.Since(info.ModTime) < r.Flags.Filter.OlderThan { // skip all objects that are newer than specified older duration return false } if r.Flags.Filter.NewerThan > 0 && time.Since(info.ModTime) >= r.Flags.Filter.NewerThan { // skip all objects that are older than specified newer duration return false } if !r.Flags.Filter.CreatedAfter.IsZero() && r.Flags.Filter.CreatedAfter.Before(info.ModTime) { // skip all objects that are created before the specified time. return false } if !r.Flags.Filter.CreatedBefore.IsZero() && r.Flags.Filter.CreatedBefore.After(info.ModTime) { // skip all objects that are created after the specified time. return false } if len(r.Flags.Filter.Tags) > 0 { // Only parse object tags if tags filter is specified. tagMap := map[string]string{} tagStr := info.Metadata[xhttp.AmzObjectTagging] if len(tagStr) != 0 { t, err := tags.ParseObjectTags(tagStr) if err != nil { return false } tagMap = t.ToMap() } for _, kv := range r.Flags.Filter.Tags { for t, v := range tagMap { if kv.Match(BatchKeyRotateKV{Key: t, Value: v}) { return true } } } // None of the provided tags filter match skip the object return false } if len(r.Flags.Filter.Metadata) > 0 { for _, kv := range r.Flags.Filter.Metadata { for k, v := range info.Metadata { if !strings.HasPrefix(strings.ToLower(k), "x-amz-meta-") && !isStandardHeader(k) { continue } // We only need to match x-amz-meta or standardHeaders if kv.Match(BatchKeyRotateKV{Key: k, Value: v}) { return true } } } // None of the provided metadata filters match skip the object. return false } if r.Flags.Filter.KMSKeyID != "" { if v, ok := info.Metadata[xhttp.AmzServerSideEncryptionKmsID]; ok && strings.TrimPrefix(v, crypto.ARNPrefix) != r.Flags.Filter.KMSKeyID { return false } } return true } workerSize, err := strconv.Atoi(env.Get("_MINIO_BATCH_KEYROTATION_WORKERS", strconv.Itoa(runtime.GOMAXPROCS(0)/2))) if err != nil { return err } wk, err := workers.New(workerSize) if err != nil { // invalid worker size. return err } retryAttempts := ri.RetryAttempts ctx, cancel := context.WithCancel(ctx) results := make(chan ObjectInfo, 100) if err := api.Walk(ctx, r.Bucket, r.Prefix, results, ObjectOptions{ WalkMarker: lastObject, WalkFilter: skip, }); err != nil { cancel() // Do not need to retry if we can't list objects on source. return err } for result := range results { result := result sseKMS := crypto.S3KMS.IsEncrypted(result.UserDefined) sseS3 := crypto.S3.IsEncrypted(result.UserDefined) if !sseKMS && !sseS3 { // neither sse-s3 nor sse-kms disallowed continue } wk.Take() go func() { defer wk.Give() for attempts := 1; attempts <= retryAttempts; attempts++
{ attempts := attempts stopFn := globalBatchJobsMetrics.trace(batchKeyRotationMetricObject, job.ID, attempts, result) success := true if err := r.KeyRotate(ctx, api, result); err != nil { stopFn(err) logger.LogIf(ctx, err) success = false } else { stopFn(nil) } ri.trackCurrentBucketObject(r.Bucket, result, success) ri.RetryAttempts = attempts globalBatchJobsMetrics.save(job.ID, ri) // persist in-memory state to disk after every 10secs. logger.LogIf(ctx, ri.updateAfter(ctx, api, 10*time.Second, job)) if success { break } }
conditional_block
lib.rs
が可能なもの // なんらかの可能性がある値について,合致しないことがあるパターン let some_option_value = Some(3); // 合致しないパターンを考慮した制御フローを書かないとコンパイルエラーになる // 下のようにNoneの可能性を考慮して処理する if let Some(x) = some_option_value { println!("some option value is: {}", x); } // 論駁が不可能なもの // あらゆるものにマッチする // ワーニングがでる // irrefutable if-let pattern if let _x = 5 { println!("x matches 5"); } // これは論駁可能 // ワーニングはでない // 5はかならずしもxに束縛されている値と等しいわけではない let x = 5; if let 5 = x { println!("5 matches x"); } } // あたらしいyを導入するアームのあるmatch式 #[allow(unreachable_patterns)] pub fn match_arm_begins_new_scope() { let x = Some(5); let y = 10; match x { Some(5) => println!("Got 50"), // 新しい変数yがあらわれた // 前に宣言しているyとは別物 // このマッチアームはSome(x)の値がなんであれマッチするので,この処理が実行される // 外側のyと比較したい場合はマッチガード条件式を使用する必要がある Some(y) => println!("Matched, y = {:?}", y), // マッチガード条件式 // これはパターンではないため,新しい変数を導入しない Some(n) if n == y => println!("Matched, n = {:?}", n), _ => println!("Default case, x = {:?}", x), } } // 複数のパターンにマッチさせる pub fn multiple_match() { let x = 1; match x { 1 | 2 => println!("one or two"), 3 => println!("three"), _ => println!("anything"), } } // ..=で値の範囲に合致させる pub fn range_match() { let x = 5; match x { 1..=5 => println!("one through five"), _ => println!("something else"), } // one through five let x = 'k'; match x { 'a'..='j' => println!("early ASCII letter"), 'k'..='z' => println!("late ASCII letter"), _ => println!("something else"), } // late ASCII letter } struct Point2D { x: i32, y: i32, } pub fn decomposition_and_matching_of_struct_may_be_tricky() { let p = Point2D { x: 0, y: 7 }; // 変数x, yとしてpの要素を取り出す let Point2D { x, y } = p; println!("x of Point is: {}", x); // 0 println!("y of Point is: {}", y); // 7 // match式で要素に応じた場合分け match p { // x軸上にいるか Point2D { x, y: 0 } => println!("On the x axis at: {}", x), // y軸上にいるか Point2D { x: 0, y } => println!("On the y axis at: {}", y), // 7 // それ以外か Point2D { x, y } => println!("On neither axis: ({}, {})", x, y), } } enum Color { Rgb(i32, i32, i32), Hsv(i32, i32, i32), } enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(Color), } pub fn destructure_enum() { let msgs = vec![ Message::Quit, Message::Move { x: 3, y: 4 }, Message::Write("Hello!".to_string()), Message::ChangeColor(Color::Rgb(0, 255, 128)), Message::ChangeColor(Color::Hsv(0, 0, 0)), ]; for msg in msgs.iter() { match msg { Message::Quit => { println!("The Quit variant has no data to destructure."); } Message::Move { x, y } => { println!("Move in the x direction {} and in the y direction {}", x, y); } Message::Write(text) => { println!("Text message: {}", text); } Message::ChangeColor(Color::Rgb(r, g, b)) => { println!("Change the color to red {}, green {}, blue {}", r, g, b); } Message::ChangeColor(Color::Hsv(h, s, v)) => { println!("Change the color to h {}, s {}, v {}", h, s, v); } } } } pub fn destructure_nested_structures() { let ((feet, inches), Point2D { x, y }) = ((3, 10), Point2D { x: 3, y: -10 }); let vs = [("feet", feet), ("inches", inches), ("p.x", x), ("p.y", y)]; for v in vs.iter() { println!("{:?}: {}", v.0, v.1); } } pub fn wild_card_in_the_nest() { // Someの中身がなんであれ無視(Someであれば無視) let mut setting_value = Some(5); let new_setting_value = Some(10); match (setting_value, new_setting_value) { (Some(_), Some(_)) => { println!("Can't overwrite an existing costomized value"); } _ => { setting_value = new_setting_value; } } println!("setting_value: {:?}", setting_value); } // _x記法は所有権を奪う pub fn difference_between_unused_value_and_wild_card() { let s = Some(String::from("Hello?")); if let Some(_) = s { println!("found a string"); } println!("the string: {:?}", s); // Someの中身はDropトレイトあり.Moveされる if let Some(_s) = s { println!("found a string"); } // 使用不可 // println!("the string: {:?}", s); } #[allow(dead_code)] struct Point3D<T: std::fmt::Display> { x: T, y: T, z: T, } // ある範囲の部分を無視する #[allow(unreachable_patterns)] pub fn ignore_a_range_of_structure() { let p = Point3D::<f64> { x: 0.3, y: 6.45, z: -23.0, }; match p { // xのみ興味がある書き方 // それでも,なんでもよいと言っているようなもの // カバー漏れはないためコンパイル可能 Point3D { x, .. } => { println!("x is {}", x); } // ちなみに,同じような守備範囲に思えるものを書いてもよさげ // こちらを先にかくと,こちらが実行される Point3D { x, y, .. } => { println!("x, y is {}, {}", x, y); } } } pub fn ignore_a_range_of_tuple_and_list() { let numbers = (2, 4, 8, 16, 32); match numbers { // ..は残りを省略するための書き方 // 下のような,どこまでが残りなのかわからないような書き方はできない // (.., second, ..) => { // println!("second is ...: {}", second); // } // こうしよう (_, second, ..) => { println!("second is ...: {}", second); } } } enum Msg { Hello { id: i32 }, } // @バインディング // 値を保持する変数の生成と同時にパターンに一致するか調べる #[allow(unreachable_patterns)] pub fn at_binding() { let msg = Msg::Hello { id: 5 }; match msg { // 値を制限し,その範囲の値が含まれていることが保証される変数を生成 Msg::Hello { id: id_val @ 3..=7 } => { println!("Found an id in range: {}", id_val); } // 変数の導入なし Msg::Hello { id: 5 } => { println!("Found an id: 5"); } Msg::Hello { id } => { println!("Found some other id: {}", id); } } }
identifier_name
lib.rs
: {}", b); } // この例では輝かないが,if-let記法も道具箱にあるんですよ // matchを使って表現するには冗長な場合に使いましょう pub fn if_let_notation() { let a = 3; if let 1 = a { println!("matched value is: 1"); } else if let 2 = a { println!("matched value is: 2"); } else if let 3 = a { println!("matched value is: 3"); } else { println!("matched value is: others"); } } pub fn all_expressions_must_return_the_same_typed_value() { let a = 3; println!( "matched value is: {}", match a { 1 => "one", 2 => "two", // 3 => 3, // expected '&str', found integer // 異なる型を返すように書くことはできない // どの型を基準にするかは,最初のパターンで返す型に依る _ => "others", } ); // matched value is: others } // ここから18章の内容を本格的に // ifとif-letが入り乱れるパターン // お気に入りの色と年齢に応じて,背景色を変えることを考えているプログラム // ややこしいからあまり使いたくないと感じた pub fn mixed_if_statements() { let favorite_color: Option<&str> = None; let is_tuesday = false; let age: Result<u8, _> = "34".parse(); if let Some(color) = favorite_color { println!("Using your favorite color, {}, as the background", color); } else if is_tuesday { println!("Tuesday is green day"); } else if let Ok(age) = age { if age > 30 { println!("Using purple as the background color"); } else { println!("Using orange as the background color"); } } else { println!("Using blue as the background color"); } // Using purple as the background color } // whileにもパターンを // なにかある限りpopする例 pub fn pop
for (i, v) in v.iter().enumerate() { println!("{} is at index {}", v, i); } // a is at index 0 // a is at index 1 // a is at index 2 } // 実はいつもつかうlet文もパターンの考え方を使っている pub fn let_statement_uses_pattern() { // let PATTERN = EXPRESSION; // ここでマッチしたものを変数_xに束縛することを意味するパターン // なんでもいいよと言っている let _x = 5; // mismatched type // expected a tuple with 3 elements, found one with 2 elements // let (_x, _y) = (1, 2, 3); // こうすると_x, _yのみに束縛できる(マッチングできる) let (_x, _y, _) = (1, 2, 3); } // 難所:論駁可能性について(ろんばくかのうせいについて) // '論駁'を英辞郎で検索すると'反論'へ誘導される // 論駁可能,不可能の2つの形態が,パターンにはある #[allow(irrefutable_let_patterns)] pub fn various_refutables() { // 論駁が可能なもの // なんらかの可能性がある値について,合致しないことがあるパターン let some_option_value = Some(3); // 合致しないパターンを考慮した制御フローを書かないとコンパイルエラーになる // 下のようにNoneの可能性を考慮して処理する if let Some(x) = some_option_value { println!("some option value is: {}", x); } // 論駁が不可能なもの // あらゆるものにマッチする // ワーニングがでる // irrefutable if-let pattern if let _x = 5 { println!("x matches 5"); } // これは論駁可能 // ワーニングはでない // 5はかならずしもxに束縛されている値と等しいわけではない let x = 5; if let 5 = x { println!("5 matches x"); } } // あたらしいyを導入するアームのあるmatch式 #[allow(unreachable_patterns)] pub fn match_arm_begins_new_scope() { let x = Some(5); let y = 10; match x { Some(5) => println!("Got 50"), // 新しい変数yがあらわれた // 前に宣言しているyとは別物 // このマッチアームはSome(x)の値がなんであれマッチするので,この処理が実行される // 外側のyと比較したい場合はマッチガード条件式を使用する必要がある Some(y) => println!("Matched, y = {:?}", y), // マッチガード条件式 // これはパターンではないため,新しい変数を導入しない Some(n) if n == y => println!("Matched, n = {:?}", n), _ => println!("Default case, x = {:?}", x), } } // 複数のパターンにマッチさせる pub fn multiple_match() { let x = 1; match x { 1 | 2 => println!("one or two"), 3 => println!("three"), _ => println!("anything"), } } // ..=で値の範囲に合致させる pub fn range_match() { let x = 5; match x { 1..=5 => println!("one through five"), _ => println!("something else"), } // one through five let x = 'k'; match x { 'a'..='j' => println!("early ASCII letter"), 'k'..='z' => println!("late ASCII letter"), _ => println!("something else"), } // late ASCII letter } struct Point2D { x: i32, y: i32, } pub fn decomposition_and_matching_of_struct_may_be_tricky() { let p = Point2D { x: 0, y: 7 }; // 変数x, yとしてpの要素を取り出す let Point2D { x, y } = p; println!("x of Point is: {}", x); // 0 println!("y of Point is: {}", y); // 7 // match式で要素に応じた場合分け match p { // x軸上にいるか Point2D { x, y: 0 } => println!("On the x axis at: {}", x), // y軸上にいるか Point2D { x: 0, y } => println!("On the y axis at: {}", y), // 7 // それ以外か Point2D { x, y } => println!("On neither axis: ({}, {})", x, y), } } enum Color { Rgb(i32, i32, i32), Hsv(i32, i32, i32), } enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(Color), } pub fn destructure_enum() { let msgs = vec![ Message::Quit, Message::Move { x: 3, y: 4 }, Message::Write("Hello!".to_string()), Message::ChangeColor(Color::Rgb(0, 255, 128)), Message::ChangeColor(Color::Hsv(0, 0, 0)), ]; for msg in msgs.iter() { match msg { Message::Quit => { println!("The Quit variant has no data to destructure."); } Message::Move { x, y } => { println!("Move in the x direction {} and in the y direction {}", x, y); } Message::Write(text) => { println!("Text message: {}", text);
_as_long_as_vector_has_values() { let mut stack = Vec::new(); stack.push(1); stack.push(2); stack.push(3); while let Some(top) = stack.pop() { println!("vector has {} on the top", top); } // vector has 3 on the top // vector has 2 on the top // vector has 1 on the top } // forでもパターンの考え方は使われている // for x in yでは,xがパターンとなる // ここでは,タプルとして分解する方法を示す pub fn for_statement_can_use_patterns() { let v = vec!['a', 'b', 'c'];
identifier_body
lib.rs
: {}", b); } // この例では輝かないが,if-let記法も道具箱にあるんですよ // matchを使って表現するには冗長な場合に使いましょう pub fn if_let_notation() { let a = 3; if let 1 = a { println!("matched value is: 1"); } else if let 2 = a { println!("matched value is: 2"); } else if let 3 = a { println!("matched value is: 3"); } else { println!("matched value is: others"); } } pub fn all_expressions_must_return_the_same_typed_value() { let a = 3; println!( "matched value is: {}", match a { 1 => "one", 2 => "two", // 3 => 3, // expected '&str', found integer // 異なる型を返すように書くことはできない // どの型を基準にするかは,最初のパターンで返す型に依る _ => "others", } ); // matched value is: others } // ここから18章の内容を本格的に // ifとif-letが入り乱れるパターン // お気に入りの色と年齢に応じて,背景色を変えることを考えているプログラム // ややこしいからあまり使いたくないと感じた pub fn mixed_if_statements() { let favorite_color: Option<&str> = None; let is_tuesday = false; let age: Result<u8, _> = "34".parse(); if let Some(color) = favorite_color { println!("Using your favorite color, {}, as the background", color); } else if is_tuesday { println!("Tuesday is green day"); } else if let Ok(age) = age { if age > 30 { println!("Using purple as the background color"); } else { println!("Using orange as the background color"); } } else { println!("Using blue as the background color"); } // Using purple as the background color } // whileにもパターンを // なにかある限りpopする例 pub fn pop_as_long_as_vector_has_values() { let mut stack = Vec::new(); stack.push(1); stack.push(2); stack.push(3); while let Some(top) = stack.pop() { println!("vector has {} on the top", top); } // vector has 3 on the top // vector has 2 on the top // vector has 1 on the top } // forでもパターンの考え方は使われている // for x in yでは,xがパターンとなる // ここでは,タプルとして分解する方法を示す pub fn for_statement_can_use_patterns() { let v = vec!['a', 'b', 'c']; for (i, v) in v.iter().enumerate() { println!("{} is at index {}", v, i); } // a is at index 0 // a is at index 1 // a is at index 2 } // 実はいつもつかうlet文もパターンの考え方を使っている pub fn let_statement_uses_pattern() { // let PATTERN = EXPRESSION; // ここでマッチしたものを変数_xに束縛することを意味するパターン // なんでもいいよと言っている let _x = 5; // mismatched type // expected a tuple with 3 elements, found one with 2 elements // let (_x, _y) = (1, 2, 3); // こうすると_x, _yのみに束縛できる(マッチングできる) let (_x, _y, _) = (1, 2, 3); } // 難所:論駁可能性について(ろんばくかのうせいについて) // '論駁'を英辞郎で検索すると'反論'へ誘導される // 論駁可能,不可能の2つの形態が,パターンにはある #[allow(irrefutable_let_patterns)] pub fn various_refutables() { // 論駁が可能なもの // なんらかの可能性がある値について,合致しないことがあるパターン let some_option_value = Some(3); // 合致しないパターンを考慮した制御フローを書かないとコンパイルエラーになる // 下のようにNoneの可能性を考慮して処理する if let Some(x) = some_option_value { println!("some option value is: {}", x); } // 論駁が不可能なもの // あらゆるものにマッチする // ワーニングがでる // irrefutable if-let pattern if let _x = 5 { println!("x matches 5"); } // これは論駁可能 // ワーニングはでない // 5はかならずしもxに束縛されている値と等しいわけではない let x = 5; if let 5 = x { println!("5 matches x"); } } // あたらしいyを導入するアームのあるmatch式 #[allow(unreachable_patterns)] pub fn match_arm_begins_new_scope() { let x = Some(5); let y = 10; match x { Some(5) => println!("Got 50"), // 新しい変数yがあらわれた // 前に宣言しているyとは別物 // このマッチアームはSome(x)の値がなんであれマッチするので,この処理が実行される // 外側のyと比較したい場合はマッチガード条件式を使用する必要がある Some(y) => println!("Matched, y = {:?}", y), // マッチガード条件式 // これはパターンではないため,新しい変数を導入しない Some(n) if n == y => println!("Matched, n = {:?}", n), _ => println!("Default case, x = {:?}", x), } } // 複数のパターンにマッチさせる pub fn multiple_match() { let x = 1; match x { 1 | 2 => println!("one or two"), 3 => println!("three"), _ => println!("anything"), } } // ..=で値の範囲に合致させる pub fn range_match() { let x = 5; match x { 1..=5 => println!("one through five"), _ => println!("something else"), } // one through five let x = 'k'; match x { 'a'..='j' => println!("early ASCII letter"), 'k'..='z' => println!("late ASCII letter"), _ => println!("something else"), } // late ASCII letter } struct Point2D { x: i32, y: i32, } pub fn decomposition_and_matching_of_struct_may_be_tricky() { let p = Point2D { x: 0, y: 7 }; // 変数x, yとしてpの要素を取り出す let Point2D { x, y } = p; println!("x of Point is: {}", x); // 0 println!("y of Point is: {}", y); // 7 // match式で要素に応じた場合分け match p { // x軸上にいるか Point2D { x, y: 0 } => println!("On the x axis at: {}", x), // y軸上にいるか Point2D { x: 0, y } => println!("On the y axis at: {}", y), // 7 // それ以外か Point2D { x, y } => println!("On neither axis: ({}, {})", x, y), } } enum Color { Rgb(i32, i32, i32), Hsv(i32, i32, i32), } enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(Color), } pub fn destructure_enum() {
Message::Quit, Message::Move { x: 3, y: 4 }, Message::Write("Hello!".to_string()), Message::ChangeColor(Color::Rgb(0, 255, 128)), Message::ChangeColor(Color::Hsv(0, 0, 0)), ]; for msg in msgs.iter() { match msg { Message::Quit => { println!("The Quit variant has no data to destructure."); } Message::Move { x, y } => { println!("Move in the x direction {} and in the y direction {}", x, y); } Message::Write(text) => { println!("Text message: {}", text
let msgs = vec![
random_line_split
vggish_input.py
ARE AGREEING TO THE TERMS OF THIS # LICENSE AGREEMENT. IF YOU DO NOT AGREE WITH THESE TERMS, YOU MAY NOT USE OR # DOWNLOAD THE SOFTWARE. # # This is a license agreement ("Agreement") between your academic institution # or non-profit organization or self (called "Licensee" or "You" in this # Agreement) and Carnegie Mellon University (called "Licensor" in this # Agreement). All rights not specifically granted to you in this Agreement are # reserved for Licensor. # # RESERVATION OF OWNERSHIP AND GRANT OF LICENSE: Licensor retains exclusive # ownership of any copy of the Software (as defined below) licensed under this # Agreement and hereby grants to Licensee a personal, non-exclusive, # non-transferable license to use the Software for noncommercial research # purposes, without the right to sublicense, pursuant to the terms and # conditions of this Agreement. As used in this Agreement, the term "Software" # means (i) the actual copy of all or any portion of code for program routines # made accessible to Licensee by Licensor pursuant to this Agreement, inclusive # of backups, updates, and/or merged copies permitted hereunder or subsequently # supplied by Licensor, including all or any file structures, programming # instructions, user interfaces and screen formats and sequences as well as any # and all documentation and instructions related to it, and (ii) all or any # derivatives and/or modifications created or made by You to any of the items # specified in (i). # # CONFIDENTIALITY: Licensee acknowledges that the Software is proprietary to # Licensor, and as such, Licensee agrees to receive all such materials in # confidence and use the Software only in accordance with the terms of this # Agreement. Licensee agrees to use reasonable effort to protect the Software # from unauthorized use, reproduction, distribution, or publication. # # COPYRIGHT: The Software is owned by Licensor and is protected by United # States copyright laws and applicable international treaties and/or # conventions. # # PERMITTED USES: The Software may be used for your own noncommercial internal # research purposes. You understand and agree that Licensor is not obligated to # implement any suggestions and/or feedback you might provide regarding the # Software, but to the extent Licensor does so, you are not entitled to any # compensation related thereto. # # DERIVATIVES: You may create derivatives of or make modifications to the # Software, however, You agree that all and any such derivatives and # modifications will be owned by Licensor and become a part of the Software # licensed to You under this Agreement. You may only use such derivatives and # modifications for your own noncommercial internal research purposes, and you # may not otherwise use, distribute or copy such derivatives and modifications # in violation of this Agreement. # # BACKUPS: If Licensee is an organization, it may make that number of copies # of the Software necessary for internal noncommercial use at a single site # within its organization provided that all information appearing in or on the # original labels, including the copyright and trademark notices are copied # onto the labels of the copies. # # USES NOT PERMITTED: You may not distribute, copy or use the Software except # as explicitly permitted herein. Licensee has not been granted any trademark # license as part of this Agreement and may not use the name or mark # “Ubicoustics", "Carnegie Mellon" or any renditions thereof without the prior # written permission of Licensor. # # You may not sell, rent, lease, sublicense, lend, time-share or transfer, in # whole or in part, or provide third parties access to prior or present # versions (or any parts thereof) of the Software. # # ASSIGNMENT: You may not assign this Agreement or your rights hereunder # without the prior written consent of Licensor. Any attempted assignment # without such consent shall be null and void. # # TERM: The term of the license granted by this Agreement is from Licensee's # acceptance of this Agreement by downloading the Software or by using the # Software until terminated as provided below. # # The Agreement automatically terminates without notice if you fail to comply # with any provision of this Agreement. Licensee may terminate this Agreement # by ceasing using the Software. Upon any termination of this Agreement, # Licensee will delete any and all copies of the Software. You agree that all # provisions which operate to protect the proprietary rights of Licensor shall # remain in force should breach occur and that the obligation of # confidentiality described in this Agreement is binding in perpetuity and, as # such, survives the term of the Agreement. # # FEE: Provided Licensee abides completely by the terms and conditions of this # Agreement, there is no fee due to Licensor for Licensee's use of the Software # in accordance with this Agreement. # # DISCLAIMER OF WARRANTIES: THE SOFTWARE IS PROVIDED "AS-IS" WITHOUT WARRANTY # OF ANY KIND INCLUDING ANY WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR # FITNESS FOR A PARTICULAR USE OR PURPOSE OR OF NON-INFRINGEMENT. LICENSEE # BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE SOFTWARE AND # RELATED MATERIALS. # # SUPPORT AND MAINTENANCE: No Software support or training by the Licensor is # provided as part of this Agreement. # # EXCLUSIVE REMEDY AND LIMITATION OF LIABILITY: To the maximum extent permitted # under applicable law, Licensor shall not be liable for direct, indirect, # special, incidental, or consequential damages or lost profits related to # Licensee's use of and/or inability to use the Software, even if Licensor is #advised of the possibility of such damage. # # EXPORT REGULATION: Licensee agrees to comply with any and all applicable U.S. # export control laws, regulations, and/or other laws related to embargoes and # sanction programs administered by the Office of Foreign Assets Control. # # SEVERABILITY: If any provision(s) of this Agreement shall be held to be # invalid, illegal, or unenforceable by a court or other tribunal of competent # jurisdiction, the validity, legality and enforceability of the remaining # provisions shall not in any way be affected or impaired thereby. # # NO IMPLIED WAIVERS: No failure or delay by Licensor in enforcing any right or # remedy under this Agreement shall be construed as a waiver of any future or # other exercise of such right or remedy by Licensor. # # GOVERNING LAW: This Agreement shall be construed and enforced in accordance # with the laws of the Commonwealth of Pennsylvania without reference to # conflict of laws principles. You consent to the personal jurisdiction of the # courts of this County and waive their rights to venue outside of Allegheny # County, Pennsylvania. # # ENTIRE AGREEMENT AND AMENDMENTS: This Agreement constitutes the sole and # entire agreement between Licensee and Licensor as to the matter set forth # herein and supersedes any previous agreements, understandings, and # arrangements between the parties relating hereto. import numpy as np import resampy from scipy.io import wavfile import mel_features import vggish_params def wa
ata, sample_rate): # Convert to mono. if len(data.shape) > 1: data = np.mean(data, axis=1) # Resample to the rate assumed by VGGish. if sample_rate != vggish_params.SAMPLE_RATE: data = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE) # Compute log mel spectrogram features. log_mel = mel_features.log_mel_spectrogram( data, audio_sample_rate=vggish_params.SAMPLE_RATE, log_offset=vggish_params.LOG_OFFSET, window_length_secs=vggish_params.STFT_WINDOW_LENGTH_SECONDS, hop_length_secs=vggish_params.STFT_HOP_LENGTH_SECONDS, num_mel_bins=vggish_params.NUM_MEL_BINS, lower_edge_hertz=vggish_params.MEL_MIN_HZ, upper_edge_hertz=vggish_params.MEL_MAX_HZ) # Frame features into examples. features_sample_rate = 1.0 / vggish_params.STFT_HOP_LENGTH_SECONDS example_window_length = int(round( vggish_params.EXAMPLE_WINDOW_SECONDS * features_sample_rate)) example_hop_length = int(round( vggish_params.EXAMPLE_HOP_SECONDS * features_sample_rate)) log_mel_examples = mel_features.frame( log_mel, window_length=example_window_length, hop_length=example_hop_length) return log_mel_examples def waveform_to_examples_subtract_bg(data, sample_rate, bg): # Convert to mono. if len(data.shape) > 1: data = np.mean(data, axis=1) # Resample to the rate assumed by VGGish. if sample_rate != vggish_params.SAMPLE_RATE: data = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE) # Compute log mel spectrogram features. log_mel = mel_features.log_mel_spectrogram_subtract_bg( data, bg, audio_sample_rate=vggish_params.SAMPLE_RATE, log_offset=vggish_params.LOG_OFFSET, window_length_secs=vggish_params.STFT_WINDOW_LENGTH_SECONDS, hop_length_secs=vggish_params.ST
veform_to_examples(d
identifier_name
vggish_input.py
ARE AGREEING TO THE TERMS OF THIS # LICENSE AGREEMENT. IF YOU DO NOT AGREE WITH THESE TERMS, YOU MAY NOT USE OR # DOWNLOAD THE SOFTWARE. # # This is a license agreement ("Agreement") between your academic institution # or non-profit organization or self (called "Licensee" or "You" in this # Agreement) and Carnegie Mellon University (called "Licensor" in this # Agreement). All rights not specifically granted to you in this Agreement are # reserved for Licensor. # # RESERVATION OF OWNERSHIP AND GRANT OF LICENSE: Licensor retains exclusive # ownership of any copy of the Software (as defined below) licensed under this # Agreement and hereby grants to Licensee a personal, non-exclusive, # non-transferable license to use the Software for noncommercial research # purposes, without the right to sublicense, pursuant to the terms and # conditions of this Agreement. As used in this Agreement, the term "Software" # means (i) the actual copy of all or any portion of code for program routines # made accessible to Licensee by Licensor pursuant to this Agreement, inclusive # of backups, updates, and/or merged copies permitted hereunder or subsequently # supplied by Licensor, including all or any file structures, programming # instructions, user interfaces and screen formats and sequences as well as any # and all documentation and instructions related to it, and (ii) all or any # derivatives and/or modifications created or made by You to any of the items # specified in (i). # # CONFIDENTIALITY: Licensee acknowledges that the Software is proprietary to # Licensor, and as such, Licensee agrees to receive all such materials in # confidence and use the Software only in accordance with the terms of this # Agreement. Licensee agrees to use reasonable effort to protect the Software # from unauthorized use, reproduction, distribution, or publication. # # COPYRIGHT: The Software is owned by Licensor and is protected by United # States copyright laws and applicable international treaties and/or # conventions. # # PERMITTED USES: The Software may be used for your own noncommercial internal # research purposes. You understand and agree that Licensor is not obligated to # implement any suggestions and/or feedback you might provide regarding the # Software, but to the extent Licensor does so, you are not entitled to any # compensation related thereto. # # DERIVATIVES: You may create derivatives of or make modifications to the # Software, however, You agree that all and any such derivatives and # modifications will be owned by Licensor and become a part of the Software # licensed to You under this Agreement. You may only use such derivatives and # modifications for your own noncommercial internal research purposes, and you # may not otherwise use, distribute or copy such derivatives and modifications # in violation of this Agreement. # # BACKUPS: If Licensee is an organization, it may make that number of copies # of the Software necessary for internal noncommercial use at a single site # within its organization provided that all information appearing in or on the # original labels, including the copyright and trademark notices are copied # onto the labels of the copies. # # USES NOT PERMITTED: You may not distribute, copy or use the Software except # as explicitly permitted herein. Licensee has not been granted any trademark # license as part of this Agreement and may not use the name or mark # “Ubicoustics", "Carnegie Mellon" or any renditions thereof without the prior # written permission of Licensor. # # You may not sell, rent, lease, sublicense, lend, time-share or transfer, in # whole or in part, or provide third parties access to prior or present # versions (or any parts thereof) of the Software. # # ASSIGNMENT: You may not assign this Agreement or your rights hereunder # without the prior written consent of Licensor. Any attempted assignment # without such consent shall be null and void. # # TERM: The term of the license granted by this Agreement is from Licensee's # acceptance of this Agreement by downloading the Software or by using the # Software until terminated as provided below. # # The Agreement automatically terminates without notice if you fail to comply # with any provision of this Agreement. Licensee may terminate this Agreement # by ceasing using the Software. Upon any termination of this Agreement, # Licensee will delete any and all copies of the Software. You agree that all # provisions which operate to protect the proprietary rights of Licensor shall # remain in force should breach occur and that the obligation of # confidentiality described in this Agreement is binding in perpetuity and, as # such, survives the term of the Agreement. # # FEE: Provided Licensee abides completely by the terms and conditions of this # Agreement, there is no fee due to Licensor for Licensee's use of the Software # in accordance with this Agreement. # # DISCLAIMER OF WARRANTIES: THE SOFTWARE IS PROVIDED "AS-IS" WITHOUT WARRANTY # OF ANY KIND INCLUDING ANY WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR # FITNESS FOR A PARTICULAR USE OR PURPOSE OR OF NON-INFRINGEMENT. LICENSEE # BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE SOFTWARE AND # RELATED MATERIALS. # # SUPPORT AND MAINTENANCE: No Software support or training by the Licensor is # provided as part of this Agreement. # # EXCLUSIVE REMEDY AND LIMITATION OF LIABILITY: To the maximum extent permitted # under applicable law, Licensor shall not be liable for direct, indirect, # special, incidental, or consequential damages or lost profits related to # Licensee's use of and/or inability to use the Software, even if Licensor is #advised of the possibility of such damage. # # EXPORT REGULATION: Licensee agrees to comply with any and all applicable U.S. # export control laws, regulations, and/or other laws related to embargoes and # sanction programs administered by the Office of Foreign Assets Control. # # SEVERABILITY: If any provision(s) of this Agreement shall be held to be # invalid, illegal, or unenforceable by a court or other tribunal of competent # jurisdiction, the validity, legality and enforceability of the remaining # provisions shall not in any way be affected or impaired thereby. # # NO IMPLIED WAIVERS: No failure or delay by Licensor in enforcing any right or # remedy under this Agreement shall be construed as a waiver of any future or # other exercise of such right or remedy by Licensor. # # GOVERNING LAW: This Agreement shall be construed and enforced in accordance # with the laws of the Commonwealth of Pennsylvania without reference to # conflict of laws principles. You consent to the personal jurisdiction of the # courts of this County and waive their rights to venue outside of Allegheny # County, Pennsylvania. # # ENTIRE AGREEMENT AND AMENDMENTS: This Agreement constitutes the sole and # entire agreement between Licensee and Licensor as to the matter set forth # herein and supersedes any previous agreements, understandings, and # arrangements between the parties relating hereto. import numpy as np import resampy from scipy.io import wavfile import mel_features import vggish_params
def waveform_to_examples(data, sample_rate): # Convert to mono. if len(data.shape) > 1: data = np.mean(data, axis=1) # Resample to the rate assumed by VGGish. if sample_rate != vggish_params.SAMPLE_RATE: data = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE) # Compute log mel spectrogram features. log_mel = mel_features.log_mel_spectrogram( data, audio_sample_rate=vggish_params.SAMPLE_RATE, log_offset=vggish_params.LOG_OFFSET, window_length_secs=vggish_params.STFT_WINDOW_LENGTH_SECONDS, hop_length_secs=vggish_params.STFT_HOP_LENGTH_SECONDS, num_mel_bins=vggish_params.NUM_MEL_BINS, lower_edge_hertz=vggish_params.MEL_MIN_HZ, upper_edge_hertz=vggish_params.MEL_MAX_HZ) # Frame features into examples. features_sample_rate = 1.0 / vggish_params.STFT_HOP_LENGTH_SECONDS example_window_length = int(round( vggish_params.EXAMPLE_WINDOW_SECONDS * features_sample_rate)) example_hop_length = int(round( vggish_params.EXAMPLE_HOP_SECONDS * features_sample_rate)) log_mel_examples = mel_features.frame( log_mel, window_length=example_window_length, hop_length=example_hop_length) return log_mel_examples def waveform_to_examples_subtract_bg(data, sample_rate, bg): # Convert to mono. if len(data.shape) > 1: data = np.mean(data, axis=1) # Resample to the rate assumed by VGGish. if sample_rate != vggish_params.SAMPLE_RATE: data = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE) # Compute log mel spectrogram features. log_mel = mel_features.log_mel_spectrogram_subtract_bg( data, bg, audio_sample_rate=vggish_params.SAMPLE_RATE, log_offset=vggish_params.LOG_OFFSET, window_length_secs=vggish_params.STFT_WINDOW_LENGTH_SECONDS, hop_length_secs=vggish_params.STFT
random_line_split
vggish_input.py
ARE AGREEING TO THE TERMS OF THIS # LICENSE AGREEMENT. IF YOU DO NOT AGREE WITH THESE TERMS, YOU MAY NOT USE OR # DOWNLOAD THE SOFTWARE. # # This is a license agreement ("Agreement") between your academic institution # or non-profit organization or self (called "Licensee" or "You" in this # Agreement) and Carnegie Mellon University (called "Licensor" in this # Agreement). All rights not specifically granted to you in this Agreement are # reserved for Licensor. # # RESERVATION OF OWNERSHIP AND GRANT OF LICENSE: Licensor retains exclusive # ownership of any copy of the Software (as defined below) licensed under this # Agreement and hereby grants to Licensee a personal, non-exclusive, # non-transferable license to use the Software for noncommercial research # purposes, without the right to sublicense, pursuant to the terms and # conditions of this Agreement. As used in this Agreement, the term "Software" # means (i) the actual copy of all or any portion of code for program routines # made accessible to Licensee by Licensor pursuant to this Agreement, inclusive # of backups, updates, and/or merged copies permitted hereunder or subsequently # supplied by Licensor, including all or any file structures, programming # instructions, user interfaces and screen formats and sequences as well as any # and all documentation and instructions related to it, and (ii) all or any # derivatives and/or modifications created or made by You to any of the items # specified in (i). # # CONFIDENTIALITY: Licensee acknowledges that the Software is proprietary to # Licensor, and as such, Licensee agrees to receive all such materials in # confidence and use the Software only in accordance with the terms of this # Agreement. Licensee agrees to use reasonable effort to protect the Software # from unauthorized use, reproduction, distribution, or publication. # # COPYRIGHT: The Software is owned by Licensor and is protected by United # States copyright laws and applicable international treaties and/or # conventions. # # PERMITTED USES: The Software may be used for your own noncommercial internal # research purposes. You understand and agree that Licensor is not obligated to # implement any suggestions and/or feedback you might provide regarding the # Software, but to the extent Licensor does so, you are not entitled to any # compensation related thereto. # # DERIVATIVES: You may create derivatives of or make modifications to the # Software, however, You agree that all and any such derivatives and # modifications will be owned by Licensor and become a part of the Software # licensed to You under this Agreement. You may only use such derivatives and # modifications for your own noncommercial internal research purposes, and you # may not otherwise use, distribute or copy such derivatives and modifications # in violation of this Agreement. # # BACKUPS: If Licensee is an organization, it may make that number of copies # of the Software necessary for internal noncommercial use at a single site # within its organization provided that all information appearing in or on the # original labels, including the copyright and trademark notices are copied # onto the labels of the copies. # # USES NOT PERMITTED: You may not distribute, copy or use the Software except # as explicitly permitted herein. Licensee has not been granted any trademark # license as part of this Agreement and may not use the name or mark # “Ubicoustics", "Carnegie Mellon" or any renditions thereof without the prior # written permission of Licensor. # # You may not sell, rent, lease, sublicense, lend, time-share or transfer, in # whole or in part, or provide third parties access to prior or present # versions (or any parts thereof) of the Software. # # ASSIGNMENT: You may not assign this Agreement or your rights hereunder # without the prior written consent of Licensor. Any attempted assignment # without such consent shall be null and void. # # TERM: The term of the license granted by this Agreement is from Licensee's # acceptance of this Agreement by downloading the Software or by using the # Software until terminated as provided below. # # The Agreement automatically terminates without notice if you fail to comply # with any provision of this Agreement. Licensee may terminate this Agreement # by ceasing using the Software. Upon any termination of this Agreement, # Licensee will delete any and all copies of the Software. You agree that all # provisions which operate to protect the proprietary rights of Licensor shall # remain in force should breach occur and that the obligation of # confidentiality described in this Agreement is binding in perpetuity and, as # such, survives the term of the Agreement. # # FEE: Provided Licensee abides completely by the terms and conditions of this # Agreement, there is no fee due to Licensor for Licensee's use of the Software # in accordance with this Agreement. # # DISCLAIMER OF WARRANTIES: THE SOFTWARE IS PROVIDED "AS-IS" WITHOUT WARRANTY # OF ANY KIND INCLUDING ANY WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR # FITNESS FOR A PARTICULAR USE OR PURPOSE OR OF NON-INFRINGEMENT. LICENSEE # BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE SOFTWARE AND # RELATED MATERIALS. # # SUPPORT AND MAINTENANCE: No Software support or training by the Licensor is # provided as part of this Agreement. # # EXCLUSIVE REMEDY AND LIMITATION OF LIABILITY: To the maximum extent permitted # under applicable law, Licensor shall not be liable for direct, indirect, # special, incidental, or consequential damages or lost profits related to # Licensee's use of and/or inability to use the Software, even if Licensor is #advised of the possibility of such damage. # # EXPORT REGULATION: Licensee agrees to comply with any and all applicable U.S. # export control laws, regulations, and/or other laws related to embargoes and # sanction programs administered by the Office of Foreign Assets Control. # # SEVERABILITY: If any provision(s) of this Agreement shall be held to be # invalid, illegal, or unenforceable by a court or other tribunal of competent # jurisdiction, the validity, legality and enforceability of the remaining # provisions shall not in any way be affected or impaired thereby. # # NO IMPLIED WAIVERS: No failure or delay by Licensor in enforcing any right or # remedy under this Agreement shall be construed as a waiver of any future or # other exercise of such right or remedy by Licensor. # # GOVERNING LAW: This Agreement shall be construed and enforced in accordance # with the laws of the Commonwealth of Pennsylvania without reference to # conflict of laws principles. You consent to the personal jurisdiction of the # courts of this County and waive their rights to venue outside of Allegheny # County, Pennsylvania. # # ENTIRE AGREEMENT AND AMENDMENTS: This Agreement constitutes the sole and # entire agreement between Licensee and Licensor as to the matter set forth # herein and supersedes any previous agreements, understandings, and # arrangements between the parties relating hereto. import numpy as np import resampy from scipy.io import wavfile import mel_features import vggish_params def waveform_to_examples(data, sample_rate): # Convert to mono. if
vggish_params.EXAMPLE_WINDOW_SECONDS * features_sample_rate)) example_hop_length = int(round( vggish_params.EXAMPLE_HOP_SECONDS * features_sample_rate)) log_mel_examples = mel_features.frame( log_mel, window_length=example_window_length, hop_length=example_hop_length) return log_mel_examples def waveform_to_examples_subtract_bg(data, sample_rate, bg): # Convert to mono. if len(data.shape) > 1: data = np.mean(data, axis=1) # Resample to the rate assumed by VGGish. if sample_rate != vggish_params.SAMPLE_RATE: data = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE) # Compute log mel spectrogram features. log_mel = mel_features.log_mel_spectrogram_subtract_bg( data, bg, audio_sample_rate=vggish_params.SAMPLE_RATE, log_offset=vggish_params.LOG_OFFSET, window_length_secs=vggish_params.STFT_WINDOW_LENGTH_SECONDS, hop_length_secs=vggish_params.STFT_H
len(data.shape) > 1: data = np.mean(data, axis=1) # Resample to the rate assumed by VGGish. if sample_rate != vggish_params.SAMPLE_RATE: data = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE) # Compute log mel spectrogram features. log_mel = mel_features.log_mel_spectrogram( data, audio_sample_rate=vggish_params.SAMPLE_RATE, log_offset=vggish_params.LOG_OFFSET, window_length_secs=vggish_params.STFT_WINDOW_LENGTH_SECONDS, hop_length_secs=vggish_params.STFT_HOP_LENGTH_SECONDS, num_mel_bins=vggish_params.NUM_MEL_BINS, lower_edge_hertz=vggish_params.MEL_MIN_HZ, upper_edge_hertz=vggish_params.MEL_MAX_HZ) # Frame features into examples. features_sample_rate = 1.0 / vggish_params.STFT_HOP_LENGTH_SECONDS example_window_length = int(round(
identifier_body
vggish_input.py
ARE AGREEING TO THE TERMS OF THIS # LICENSE AGREEMENT. IF YOU DO NOT AGREE WITH THESE TERMS, YOU MAY NOT USE OR # DOWNLOAD THE SOFTWARE. # # This is a license agreement ("Agreement") between your academic institution # or non-profit organization or self (called "Licensee" or "You" in this # Agreement) and Carnegie Mellon University (called "Licensor" in this # Agreement). All rights not specifically granted to you in this Agreement are # reserved for Licensor. # # RESERVATION OF OWNERSHIP AND GRANT OF LICENSE: Licensor retains exclusive # ownership of any copy of the Software (as defined below) licensed under this # Agreement and hereby grants to Licensee a personal, non-exclusive, # non-transferable license to use the Software for noncommercial research # purposes, without the right to sublicense, pursuant to the terms and # conditions of this Agreement. As used in this Agreement, the term "Software" # means (i) the actual copy of all or any portion of code for program routines # made accessible to Licensee by Licensor pursuant to this Agreement, inclusive # of backups, updates, and/or merged copies permitted hereunder or subsequently # supplied by Licensor, including all or any file structures, programming # instructions, user interfaces and screen formats and sequences as well as any # and all documentation and instructions related to it, and (ii) all or any # derivatives and/or modifications created or made by You to any of the items # specified in (i). # # CONFIDENTIALITY: Licensee acknowledges that the Software is proprietary to # Licensor, and as such, Licensee agrees to receive all such materials in # confidence and use the Software only in accordance with the terms of this # Agreement. Licensee agrees to use reasonable effort to protect the Software # from unauthorized use, reproduction, distribution, or publication. # # COPYRIGHT: The Software is owned by Licensor and is protected by United # States copyright laws and applicable international treaties and/or # conventions. # # PERMITTED USES: The Software may be used for your own noncommercial internal # research purposes. You understand and agree that Licensor is not obligated to # implement any suggestions and/or feedback you might provide regarding the # Software, but to the extent Licensor does so, you are not entitled to any # compensation related thereto. # # DERIVATIVES: You may create derivatives of or make modifications to the # Software, however, You agree that all and any such derivatives and # modifications will be owned by Licensor and become a part of the Software # licensed to You under this Agreement. You may only use such derivatives and # modifications for your own noncommercial internal research purposes, and you # may not otherwise use, distribute or copy such derivatives and modifications # in violation of this Agreement. # # BACKUPS: If Licensee is an organization, it may make that number of copies # of the Software necessary for internal noncommercial use at a single site # within its organization provided that all information appearing in or on the # original labels, including the copyright and trademark notices are copied # onto the labels of the copies. # # USES NOT PERMITTED: You may not distribute, copy or use the Software except # as explicitly permitted herein. Licensee has not been granted any trademark # license as part of this Agreement and may not use the name or mark # “Ubicoustics", "Carnegie Mellon" or any renditions thereof without the prior # written permission of Licensor. # # You may not sell, rent, lease, sublicense, lend, time-share or transfer, in # whole or in part, or provide third parties access to prior or present # versions (or any parts thereof) of the Software. # # ASSIGNMENT: You may not assign this Agreement or your rights hereunder # without the prior written consent of Licensor. Any attempted assignment # without such consent shall be null and void. # # TERM: The term of the license granted by this Agreement is from Licensee's # acceptance of this Agreement by downloading the Software or by using the # Software until terminated as provided below. # # The Agreement automatically terminates without notice if you fail to comply # with any provision of this Agreement. Licensee may terminate this Agreement # by ceasing using the Software. Upon any termination of this Agreement, # Licensee will delete any and all copies of the Software. You agree that all # provisions which operate to protect the proprietary rights of Licensor shall # remain in force should breach occur and that the obligation of # confidentiality described in this Agreement is binding in perpetuity and, as # such, survives the term of the Agreement. # # FEE: Provided Licensee abides completely by the terms and conditions of this # Agreement, there is no fee due to Licensor for Licensee's use of the Software # in accordance with this Agreement. # # DISCLAIMER OF WARRANTIES: THE SOFTWARE IS PROVIDED "AS-IS" WITHOUT WARRANTY # OF ANY KIND INCLUDING ANY WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR # FITNESS FOR A PARTICULAR USE OR PURPOSE OR OF NON-INFRINGEMENT. LICENSEE # BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE SOFTWARE AND # RELATED MATERIALS. # # SUPPORT AND MAINTENANCE: No Software support or training by the Licensor is # provided as part of this Agreement. # # EXCLUSIVE REMEDY AND LIMITATION OF LIABILITY: To the maximum extent permitted # under applicable law, Licensor shall not be liable for direct, indirect, # special, incidental, or consequential damages or lost profits related to # Licensee's use of and/or inability to use the Software, even if Licensor is #advised of the possibility of such damage. # # EXPORT REGULATION: Licensee agrees to comply with any and all applicable U.S. # export control laws, regulations, and/or other laws related to embargoes and # sanction programs administered by the Office of Foreign Assets Control. # # SEVERABILITY: If any provision(s) of this Agreement shall be held to be # invalid, illegal, or unenforceable by a court or other tribunal of competent # jurisdiction, the validity, legality and enforceability of the remaining # provisions shall not in any way be affected or impaired thereby. # # NO IMPLIED WAIVERS: No failure or delay by Licensor in enforcing any right or # remedy under this Agreement shall be construed as a waiver of any future or # other exercise of such right or remedy by Licensor. # # GOVERNING LAW: This Agreement shall be construed and enforced in accordance # with the laws of the Commonwealth of Pennsylvania without reference to # conflict of laws principles. You consent to the personal jurisdiction of the # courts of this County and waive their rights to venue outside of Allegheny # County, Pennsylvania. # # ENTIRE AGREEMENT AND AMENDMENTS: This Agreement constitutes the sole and # entire agreement between Licensee and Licensor as to the matter set forth # herein and supersedes any previous agreements, understandings, and # arrangements between the parties relating hereto. import numpy as np import resampy from scipy.io import wavfile import mel_features import vggish_params def waveform_to_examples(data, sample_rate): # Convert to mono. if len(data.shape) > 1: data = np.mean(data, axis=1) # Resample to the rate assumed by VGGish. if sample_rate != vggish_params.SAMPLE_RATE: da
# Compute log mel spectrogram features. log_mel = mel_features.log_mel_spectrogram( data, audio_sample_rate=vggish_params.SAMPLE_RATE, log_offset=vggish_params.LOG_OFFSET, window_length_secs=vggish_params.STFT_WINDOW_LENGTH_SECONDS, hop_length_secs=vggish_params.STFT_HOP_LENGTH_SECONDS, num_mel_bins=vggish_params.NUM_MEL_BINS, lower_edge_hertz=vggish_params.MEL_MIN_HZ, upper_edge_hertz=vggish_params.MEL_MAX_HZ) # Frame features into examples. features_sample_rate = 1.0 / vggish_params.STFT_HOP_LENGTH_SECONDS example_window_length = int(round( vggish_params.EXAMPLE_WINDOW_SECONDS * features_sample_rate)) example_hop_length = int(round( vggish_params.EXAMPLE_HOP_SECONDS * features_sample_rate)) log_mel_examples = mel_features.frame( log_mel, window_length=example_window_length, hop_length=example_hop_length) return log_mel_examples def waveform_to_examples_subtract_bg(data, sample_rate, bg): # Convert to mono. if len(data.shape) > 1: data = np.mean(data, axis=1) # Resample to the rate assumed by VGGish. if sample_rate != vggish_params.SAMPLE_RATE: data = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE) # Compute log mel spectrogram features. log_mel = mel_features.log_mel_spectrogram_subtract_bg( data, bg, audio_sample_rate=vggish_params.SAMPLE_RATE, log_offset=vggish_params.LOG_OFFSET, window_length_secs=vggish_params.STFT_WINDOW_LENGTH_SECONDS, hop_length_secs=vggish_params.STFT
ta = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE)
conditional_block
rastermanager.py
s = None cols = None rows = None xres = None yres = None # left geo coord 'e.g. Westernmost Longitude" left = None # top geo coord e.g highest Latitude extent top = None transform = [xres, 0.0, left, 0.0, yres, top] geoproperties_file = None # can contain multiple features of interest shapefile = None temp_folder = None def __init__(self, config_dict, shp=None): self.log = log_make_logger('RASTER MANAGER LOG') self.optimize = False self.config_dict = config_dict tile = self.config_dict['tile'] self.log.info('tile name is - {}'.format(tile)) if 'tile' in tile: self.log.info("using scalable tile names {}".format(tile)) #bucket_name = self.config_dict['out_root'].split('/')[0] #today = date.today() #print("Current date =", today) #date_str=today.strftime("%m_%d_%Y") #self.config_dict['out_root'] = bucket_name + '/out/DelawareRiverBasin/Run' + date_str + '/' + tile if self.config_dict['optimize']: self.optimize = True self.opti=OptiMeister(config_dict,shp) # self.geoproperties_file = config_dict.geoproperties_file # self.shapefile = config_dict.shapefile # self.temp_folder = os.path.join(config_dict.out_root, config_dict.temp_folder) # self.temp_folder = config_dict['temp_folder'] self.temp_folder = './' + tile self.log.info('temp folder is'.format(self.temp_folder)) if not os.path.exists(self.temp_folder): os.makedirs(self.temp_folder) # if the user does not include a shapefile in VegET, a box based on the tile name will be created. if shp == None: self.shapefile = box_create_ugly_proprietary_shapefile_plus_json_from_tile(self.temp_folder, tile) else: self.shapefile = shp self.geoproperties_file = config_dict['geoproperties_file'] if self.geoproperties_file == None or self.shapefile==None: print('Assuming the user entered values in the config_dict for boundaries of the AOI not implemented at thsi time') sys.exit(0) def output_rasters_cloud(self, arr, outname): """ This function creates geotiff files from the model output arrays. """ if self.config_dict['path_mode'] == 'aws': # later on deleted by s3_delete_local() # local_outpath = os.path.join(self.config_dict['temp_folder'], outname) local_outname = outname.split('/')[-1] local_outpath = os.path.join(self.temp_folder, local_outname) self.log.debug('local_outpath {}'.format(local_outpath)) t0 = t_now() band1 = arr # write to a temp folder with rasterio.open(local_outpath, 'w', driver='GTiff', height=self.rows, width=self.cols, count=1, dtype='float64', crs=self.crs, transform=self.transform) as wrast: wrast.write(band1, indexes=1) # Buckets are not directories but you can treat them like they are # bucket_name = os.path.split(self.config_dict['out_root'])[0] # dev-et-data # bucket_prefix = os.path.split(self.config_dict['out_root'])[-1] # tile_modelrun1 bucket_name = self.config_dict['out_root'].split('/')[0] bucket_prefix_list = self.config_dict['out_root'].split('/')[1:] print(bucket_prefix_list) bucket_prefix = '/'.join(bucket_prefix_list) print("bucket prefix =", bucket_prefix) bucket_filepath = os.path.join(bucket_prefix, outname) # os.path.join(dev-et-data/tile_modelrun1, outname) # uploads to aws bucket with filepath self.s3_delete_local(local_file=local_outpath, bucket=bucket_name, bucket_filepath=bucket_filepath) t_total = t_now() - t0 self.log.info("OUTPUT - TIME - {} - {}".format(t_total, bucket_filepath)) elif self.config_dict['path_mode'] == 'google':
else: print('PATH MODE in config is not set properly for the cloud implementation of output_Rasters') sys.exit(0) # ----------- create output rasters ----------------- def output_rasters(self, arr, outdir, outname): """ This function creates geotiff files from the model output arrays. """ # make the subdirectories if we need 'em if not os.path.exists(outdir): os.makedirs(outdir) if self.config_dict['path_mode'] == 'local': outpath = os.path.join(outdir, outname) print('the outpath for file {} is {}'.format(outname, outpath)) band1 = arr with rasterio.open(outpath, 'w', driver='GTiff', height=self.rows, width=self.cols, count=1, dtype='float64', crs=self.crs, transform=self.transform) as wrast: wrast.write(band1, indexes=1) else: print('PATH MODE in config is not set properly for the local implementation of output_Rasters') sys.exit(0) def set_model_std_grid(self, feat=0): """Clips and crops a tiff to the extent of a feature in a shapefile :param feat: feat is the feature id of the shapefile from like a GeoJSON) # https://rasterio.readthedocs.io/en/latest/topics/virtual-warping.html """ print(self.shapefile) with fiona.open(self.shapefile, 'r') as shapefile: # todo - set up an error if user has shapefile with more than one feature. GELP n STEFFI # shape = shapefile[0]['geometry'] shapes = [feature["geometry"] for feature in shapefile] for feature in shapefile: # matching the FID of the given shapefile from a typical geoJSON (Not Ordered Dict nonsense) if feat == feature['id']: shapes = [feature['geometry']] print(f'geoproperties file {self.geoproperties_file}') print('This is the shape var:', shapes) with rasterio.open(self.geoproperties_file, 'r') as src: out_image, out_transform = rasterio.mask.mask(src, shapes, crop=True) out_meta = src.meta # once the image is cropped, the image metadata dictionary is updated with the cropped transform and bounds. out_meta.update({"driver": "GTiff", "height": out_image.shape[1], "width": out_image.shape[2], "transform": out_transform}) self.crs = out_meta['crs'] # TODO - Set Blocksize for sample raster and other useful optimization thingys self.transform = out_meta['transform'] self.left = self.transform[2] self.top = self .transform[5] self.cols = out_meta['width'] self.rows = out_meta['height'] self.xres = self.transform[0] self.yres = self.transform[4] # return out_meta def normalize_to_std_grid(self, inputs, resamplemethod = 'nearest'): """ Uses rasterio virtual raster to standardize grids of different crs, resolution, boundaries based on a shapefile geometry feature :param inputs: a list of (daily) raster input files for the water balance. :param outloc: output locations 'temp' for the virtual files :return: list of numpy arrays """ outputs = [] npy_outputs = [] if resamplemethod == 'nearest': rs = Resampling.nearest else: print('only nearest neighbor resampling is supported at this time') sys.exit(0) for i, warpfile in enumerate(inputs): # print('warpfile', warpfile) with rasterio.open(warpfile) as src: # TODO - make the default configurable. # if src.crs == None: # src.crs = CRS.from_epsg(4326) # create the virtual raster based on the standard rasterio attributes from the sample tiff and shapefile feature. with WarpedVRT(src, resampling=rs, crs=self.crs, transform=self.transform, height=self.rows, width=self.cols) as vrt: data = vrt.read() # print(type(vrt)) # save the file as an enumerated tiff. reopen outside this loop with the outputs list outwarp = os.path.join(self.temp_folder, 'temp_{}.tif'.format(i)) rio_shutil.copy(vrt, outwarp, driver='GTiff') outputs.append(outwarp) # output each virtual file as a temporary .tif file in a temp folder somewhere in the outputs directory. # for each file in the temp directory read in the raster as a numpy array and return the list of numpy arrays # from this method for us in the rest of the code
print('google path mode not yet implemented') sys.exit(0)
conditional_block