branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>IsraelMeira/project_Ruby<file_sep>/README.md # project_Ruby sistema <file_sep>/conexao.php <?php session_start(); $conectar = mysql_connect("localhost","root","") or die ("Erro na conexão"); $mysql_select_db("tcc"); ?><file_sep>/index.php <?php session_start(); ?> <!DOCTYPE html> <html > <head> <meta charset="UTF-8"> <title>Ruby</title> <link rel="shortcut icon" type="image/x-icon" href="favicon.ico"> <link rel="stylesheet" href="css/reset.css"> <link rel='stylesheet prefetch' href='http://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900|RobotoDraft:400,100,300,500,700,900'> <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css'> <link rel="stylesheet" href="css/style.css"> </head> <body > <div class="pen-title"> <img src="css/1.png"/> <h1>Bem-Vindo ao Ruby</h1><span>Faça seu login ou cadastre-se</span> </div> <video autoplay loop poster="polina.jpg" class="bg_video"> <source src="3.webm" type="video/webm"> <source src="videos/bg.mp4" type="video/mp4"> </video> <div class="container"> <div class="card"></div> <div class="card"> <h1 class="title">Login</h1> <form method="POST" action="index.html" > <div class="input-container"> <input type="text" id="Username" required="required"/> <label for="Username">Username</label> <div class="bar"></div> </div> <div class="input-container"> <input type="password" id="Password" required="required"/> <label for="Password">Password</label> <div class="bar"></div> </div> <div class="button-container"> <button><span>Enter</span></button> </div> <div class="footer"><a href="#">Forgot your password?</a></div> </form> </div> <div class="card alt"> <div class="toggle"></div> <h1 class="title">Register <div class="close"></div> </h1> <form> <div class="input-container"> <input type="text" id="Username" required="required"/> <label for="Username">Username</label> <div class="bar"></div> </div> <div class="input-container"> <input type="password" id="Password" required="required"/> <label for="Password">Password</label> <div class="bar"></div> </div> <div class="input-container"> <input type="password" id="Repeat Password" required="required"/> <label for="Repeat Password">Repeat Password</label> <div class="bar"></div> </div> <div class="button-container"> <button><span>Next</span></button> </div> </form> </div> </div> <!-- CodePen--><a id="codepen" title="Follow me!"><i class="fa fa-codepen"></i></a> <script src="js/code.js"></script> <script src="js/index.js"></script> </body> </html> <file_sep>/valida_login.php <?php session_start(); $Usernamet = $_POST['Username']; $Passwordt = $_POST['<PASSWORD>']; echo $Usernamet.' - '.$Passwordt; include_once("conexao.php"); $result = mysql_query("SELECT * FROM username WHERE usuario='Usernamet' AND senha'<PASSWORD>' LIMIT 1"); $resultado = mysql_fetch_assoc($result); $resultado['nome']; if(empty($resultado)){ $_session['loginErro'] ="Ususario ou senha inválida"; } header("location: sistema.php"); ?>
a829805738261271d25d8b243ac87f0096e2dc6e
[ "Markdown", "PHP" ]
4
Markdown
IsraelMeira/project_Ruby
6338ca73f4f93665c0c6bd703259e937861aecb9
cf8836893bade165eaae84bcf9c4c2a448707b0c
refs/heads/master
<repo_name>Ornella-KK/Quotes<file_sep>/README.md ## Quotes ## Description This is a web-application that helps us write our quotes and deletes or vote them. ### Author <NAME> ## How It Works * INPUT: Author,Quote,Date. * OUTPUT: Quote added to other quotes ### Setup Installation * Fork the repository to your github account https://github.com/Ornella-KK/Quotes.git * Clone this repository to a location in your file system. eg.Desktop * Open terminal command line then navigate to the root folder of the application. cd Quotes * Type ng serve and see the live link(http://localhost:4200/) and the app is displayed ## Live Link https://Ornella-KK.github.io/Quotes/ ### License & Copyright MIT Copyright (C) 2020 <file_sep>/src/app/quotes.ts export class Quote { showQuot: boolean; constructor(public Author: string,public quot: string, public downvote:number,public upvote:number,public completeDate: Date){ this.showQuot=false; } }<file_sep>/src/app/quote/quote.component.ts import { Component, OnInit } from '@angular/core'; import { Quote } from '../quotes'; @Component({ selector: 'app-quote', templateUrl: './quote.component.html', styleUrls: ['./quote.component.css'] }) export class QuoteComponent implements OnInit { quotes: Quote[] = [ new Quote('<NAME>','I’m selfish, impatient and a little insecure. I make mistakes, I am out of control and at times hard to handle. But if you can’t handle me at my worst, then you sure as hell don’t deserve me at my best.',0,0, new Date(2020,6,13)), new Quote('<NAME>','When one door of happiness closes, another opens; but often we look so long at the closed door that we do not see the one which has been opened for us.',0,0, new Date(2019,4,5)), new Quote('<NAME>','Let us always meet each other with smile, for the smile is the beginning of love.', 0,0, new Date(2018,2,1)), new Quote('<NAME>','It had long since come to my attention that people of accomplishment rarely sat back and let things happen to them. They went out and happened to things.', 0,0, new Date(2020,9,28)), new Quote('<NAME>, Jr.','Remember that the happiest people are not those getting more, but those giving more.', 0,0, new Date(2005,5,20)), new Quote('<NAME>','If you want to live a happy life, tie it to a goal, not to people or things.', 0,0, new Date(2016,11,6)), ]; toggleDetails(index){ this.quotes[index].showQuot = !this.quotes[index].showQuot; } completeQuote(isComplete, index){ if (isComplete) { this.quotes.splice(index,1); } } deleteQuote(isComplete, index){ if (isComplete) { let toDelete = confirm(`Are you sure you want to delete ${this.quotes[index].Author}?`) if (toDelete){ this.quotes.splice(index,1) } } } addNewQuote(quote){ let quoteLength = this.quotes.length; quote.id = quoteLength+1; quote.completeDate = new Date(quote.completeDate) this.quotes.push(quote) } constructor() { } ngOnInit(): void { } }
1406fb8a965843e7521e020c8d3a2212692cbf91
[ "Markdown", "TypeScript" ]
3
Markdown
Ornella-KK/Quotes
d286c297b1ebfb29d5a4f7ccb1f68f1b1e9cacc1
c66c81272124354b2c915fc8fb03a0ecb8d94658
refs/heads/master
<repo_name>DonyJ97/DJ_CloudShopping_order<file_sep>/server/src/main/java/com/order/repository/OrderDetailRepository.java package com.order.repository; import com.order.dataobject.OrderDetail; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; /** * @ Author :djq. * @ Date :Created in 23:23 2020/1/2 * @ Description: * @ Modified By: * @Version: $ */ public interface OrderDetailRepository extends JpaRepository<OrderDetail,String> { List<OrderDetail> findByOrderId(String orderId); } <file_sep>/server/src/main/java/com/order/utils/KeyUtil.java package com.order.utils; import java.util.Random; /** * @ Author :djq. * @ Date :Created in 0:17 2020/1/3 * @ Description:生成唯一的主键,格式:时间+随机数 * @ Modified By: * @Version: $ */ public class KeyUtil { /*生成唯一的主键, **格式: **时间+随机数*/ public static synchronized String genUniqueKey(){//简单方法 Random random = new Random(); Integer number = random.nextInt(900000)+100000; return System.currentTimeMillis() + String.valueOf(number); } } <file_sep>/server/src/main/java/com/order/VO/ResultVO.java package com.order.VO; import lombok.Data; /** * @ Author :djq. * @ Date :Created in 12:01 2020/1/3 * @ Description: * @ Modified By: * @Version: $ */ @Data public class ResultVO<T> { private Integer code; private String message; private T data; } <file_sep>/server/src/main/java/com/order/dataobject/Product_info.java package com.order.dataobject; import lombok.Data; import javax.persistence.Entity; import javax.persistence.Id; import java.math.BigDecimal; import java.util.Date; /** * @ Author :djq. * @ Date :Created in 15:19 2020/1/2 * @ Description: * @ Modified By: * @Version: $ */ @Data @Entity public class Product_info { @Id private String productId; /** 名字 **/ private String productName; /** 单价 **/ private BigDecimal productPrice; /** 库存 **/ private Integer productStock; /** 描述 **/ private String productDescription; /** 小图 **/ private String productIcon; /** 状态 , 0正常1下架**/ private Integer productStatus; /** 类目编号 **/ private Integer categoryType; private Date createTime; private Date updateTime; } <file_sep>/server/src/main/java/com/order/service/OrderService.java package com.order.service; import com.order.dto.OrderDTO; /** * @ Author :djq. * @ Date :Created in 0:01 2020/1/3 * @ Description: * @ Modified By: * @Version: $ */ public interface OrderService {//建立dto包,为数据传输对象 /* * 创建订单 * OrderDTO * */ OrderDTO create(OrderDTO orderDTO); /* * 完结订单(只能卖家来操作) * OrderDTO * */ OrderDTO finish(String orderId); } <file_sep>/server/src/test/java/com/order/repository/OrderDetailRepositoryTest.java package com.order.repository; import com.order.dataobject.OrderDetail; import org.junit.Assert; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.math.BigDecimal; /** * @ Author :djq. * @ Date :Created in 23:50 2020/1/2 * @ Description: * @ Modified By: * @Version: $ */ @RunWith(SpringRunner.class) @SpringBootTest class OrderDetailRepositoryTest { @Autowired private OrderDetailRepository orderDetailRepository; @Test public void testsave(){ OrderDetail orderDetail = new OrderDetail(); orderDetail.setDetailId("1"); orderDetail.setOrderId("1"); orderDetail.setProductId("157811321161313248"); orderDetail.setProductName("蜜汁鸡翅"); orderDetail.setProductPrice(new BigDecimal(10.50)); orderDetail.setProductQuantity(5); orderDetail.setProductIcon("//fuss10.elemecdn.com/0/49/65d10ef215d3c770ebb2b5ea962a7jpeg.jpeg"); OrderDetail cur = orderDetailRepository.save(orderDetail); Assert.assertTrue(cur!=null); } } <file_sep>/server/src/main/java/com/order/client/ProductClient.java package com.order.client; import com.order.dataobject.Product_info; import com.order.dto.CartDTO; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import java.util.List; /** * @ Author :djq. * @ Date :Created in 10:27 2020/1/16 * @ Description: * @ Modified By: * @Version: $ */ @FeignClient(name = "product") public interface ProductClient { @GetMapping("/msg") String productMsg(); @PostMapping("/product/listForOrder") List<Product_info> listForOrder(@RequestBody List<String> productIdList); @PostMapping("/product/decreaseStock") void decreaseStock(@RequestBody List<CartDTO> cartDTOList); }
28a120c37d36b5cb3a112d49570730a42eaa7679
[ "Java" ]
7
Java
DonyJ97/DJ_CloudShopping_order
37a8e6b2b2dd464e9e26b91ec4a477eec85ce806
a06f84555d3212f5e791c03df6f1502cbf1774f2
refs/heads/master
<repo_name>laptewstein/utils<file_sep>/rtsp2file/lib/openRTSP/record_stream.sh #!/usr/bin/env bash # kill previous instances before pgrep openRTSP | xargs kill -9 > /dev/null 2>&1 URL=$1 DURATION=$2 VIDEO_LENGTH=$3 PREFIX=$(date +\%Y-\%M-\%d_\%H) cd ~/rtsp2file/history ../lib/openRTSP/openRTSP -B 10000000 -b 10000000 -q -t -V -w 1280 -h 720 -f 25 -F $PREFIX -d $DURATION -P $VIDEO_LENGTH -D 4 -Q $URL # self-check # ../lib/openRTSP/openRTSP -B 10000000 -b 10000000 -q -t -V -w 1280 -h 720 -f 25 -F $(date +\%Y-\%M-\%d_\%H) -d 30 -P 10 -D 4 -Q rtsp://127.0.0.1:554/stream<file_sep>/README.md ### Record RTSP streams with vlc or openRTSP. ###### By default, delete recordings older than 7 days. Current encoding with vlc stores 50Gb of video data weekly, 220Gb monthly, 2.6Tb yearly. **Scheduled by cron, it runs every _ minutes and records RTSP stream for _ minutes. File naming convention is record-YYYY-MM-DD-HH-MM-SS.ts** ```` USAGE: ./start_rtsp_recording -c rtsp://127.0.0.1:554/stream -s history -d 3600 -r 7 ./start_rtsp_recording -c rtsp://127.0.0.1:554/stream -s history Required arguments: -c camera xxx.xxx.xxx.xxx RTSP stream -s storage /../.. directory WITHOUT trailing '/' to record into OPTIONS: -d clip-duration 1800 clip duration in secs (default: 3600 which is 1 hour) -r retention 31 drop recordings after _ days (default: 7) -h Show this message and exit ```` ### IPcam: RTSP, DynamicDNS + miniwebserver [HTML: Welcome page](http://htmlpreview.github.io/?https://github.com/Kartoshka548/utils/blob/master/camera/home/web/index.html) *Xiaomi Yi IP Cam is a 'dropcam clone mini computer with wifi module, sold as an IP Camera.* It runs `Linux 3.0.8` with `ARM926EJ-S (ARMv5TEJ)` CPU, on `hi3518` machine. It exposes a mini web server which is updated to load simple html welcome page. This HTML page is periodically modified by cron job with sed -i to include information about CPU load. More importantly though, another cron job frequently makes a request with wget to update dynamicDNS server, kindly provided by [duckdns.org](www.duckdns.org) team - keeping DNS synchronized with dynamic IP of camera's router. <file_sep>/camera/crontab_enable.sh #! /usr/bin/env sh # change it also below (in ftpush.sh itself) CRONTAB=crontab # enable cron / stop and restart it with ps | grep cr[o]n #------------------------------------------------- mkdir -p /var/spool/cron/crontabs # install cronjob from local backup file crontab $CRONTAB # schedule it crond<file_sep>/camera/home/rtsp/update_public_dns.sh #!/usr/bin/env sh LOG=$1 PUBLIC_IP=$(wget http://ipinfo.io/ip -qO -) DUCK_DOMAIN=<UPDATE_YOURS> DUCK_TOKEN=<UPDATE_YOURS> echo '[' $(date +\%Y-\%m-\%d\ \%Hh\%Mm\%Ss)' EST ] ip:' $PUBLIC_IP 'duckdns.org update:' $(wget -q http://duckdns.org/update/$DUCK_DOMAIN/$DUCK_TOKEN -O -) >> $LOG <file_sep>/rtsp2file/lib/vlc/start_rtsp_recording #! /usr//bin/env bash usage(){ cat << EOF usage: $0 options Utility to record rtsp stream locally with vlc (tested with v2.2.1). It also deletes recordings older than 7 days USAGE: ./start_rtsp_recording -c 127.0.0.1 -s ~/history -d 3600 -r 7' Required arguments: -c camera - rtsp://127.0.0.1:0000/stream' RTSP_SOURCE -s storage /../.. directory WITHOUT TRAIING SLASH to record into -d clip-duration 3600 clip duration in secs -r retention 7 days to keep the records for, after which they are removed. OPTIONS: -h Show this message EOF } DATE_TAKEN=$(date +\%Y-\%m-\%d_\%Hh\%Mm\%Ss) FILE_PREFIX='record' RESOURCE= STORAGE=~/history DURATION=3600 RETENTION=7 # OSX. Feel free to modify. VLC_LOCATION=/Applications/VLC.app/Contents/MacOS/VLC while getopts “hc:s:d:r:” OPTION do case $OPTION in h) usage exit 1 ;; c) RESOURCE=$OPTARG ;; s) STORAGE=$OPTARG ;; d) DURATION=$OPTARG ;; r) RETENTION=$OPTARG ;; \?) usage exit ;; esac done # ---------------------------------------------------------------------- # delete files from the directory which are older than 7 days (local storage) # ---------------------------------------------------------------------- #echo "find $STORAGE/$file_prefix-* -mmin +$RETENTION -exec rm {} \;" # mtime +7 - for any files older than (days) # mmin +900 - for any files older than (minutes) find $STORAGE/$FILE_PREFIX-* -mtime +$RETENTION -exec rm {} \; # ---------------------------------------------------------------------- # start recording # ---------------------------------------------------------------------- $VLC_LOCATION -I dummy $RESOURCE --sout file/ts:$STORAGE/$FILE_PREFIX-$DATE_TAKEN.ts --run-time=$DURATION --stop-time=$DURATION vlc://quit
2f04621a8d436392de774bc5aaae3a92da7b41b0
[ "Markdown", "Shell" ]
5
Shell
laptewstein/utils
aec14122226f8bac263a9f2ada76efd9899358a9
59359f96f76ecf4140813958417d63240187c209
refs/heads/master
<repo_name>BurgerLUA/classmod3<file_sep>/lua/autorun/server/sv_cm_loadout.lua function CM_TakeMoney(ply,money) MONEYMOD_AddMoney(ply,-money) end function CM_Loadout( ply ) local WeightLimit = GetConVar("sv_class_weightlimit"):GetFloat() local TotalWeight = 0 local LoadoutTable = CM_GetPlayerWeapons(ply) if not ply:IsBot() then ply:StripAmmo() --ply:Give("weapon_physgun") --ply:Give("gmod_tool") local WeaponsToSpawnWith = {} local HighestSlot = 0 for k,v in pairs(LoadoutTable) do --print("BEFORE",v) local SWEP = CMWeapons[v] if SWEP then if CM_CanSpawnWith(ply,v,true,WeaponsToSpawnWith) then table.Add(WeaponsToSpawnWith,{v}) if SWEP.Cost then CM_TakeMoney(ply,SWEP.Cost) end local Slot = SWEP.Slot if HighestSlot < Slot and Slot ~= 5 and Slot ~= 1 then HighestSlot = Slot end end elseif v ~= "none" then ply:ChatPrint("ERROR: Unknown weapon " .. v ) end end for l,b in pairs(WeaponsToSpawnWith) do --print("AFTER",b) if CMWeapons[b].Equipment then else ply:Give(b) if CMWeapons[b].Slot == HighestSlot then ply:SelectWeapon(b) end end if CMWeapons[b].func then CMWeapons[b].func(ply) end end if #WeaponsToSpawnWith > 0 then if #WeaponsToSpawnWith > 1 then table.RemoveByValue(WeaponsToSpawnWith,"none") end ply:ConCommand("cm_editor_weapons " .. string.Implode(" ",WeaponsToSpawnWith)) else ply:ConCommand("cm_editor_weapons none") end return true end end hook.Add("PlayerLoadout","CM_Loadout",CM_Loadout) function CM_ShowSpare2(ply) ply:ConCommand("cm_menu") end hook.Add("ShowSpare2","CM: ShowSpare2 Override",CM_ShowSpare2) --[[ local ForbiddenWeapons = { "weapon_burger_cs_he", "weapon_burger_cs_flash", "weapon_burger_cs_smoke", "weapon_burger_cs_rpg", "weapon_smod_drank", "weapon_burger_cs_c4", "weapon_ex_gas", "weapon_smod_katana", "weapon_smod_tripmine", "weapon_smod_maggrenade" } --]] function CM_PreventWeaponExploits(ply,weapon,swep) --[[ if #player.GetHumans() > 1 then return false end --]] return true end hook.Add("PlayerGiveSWEP","CM_PreventWeaponExploits",CM_PreventWeaponExploits) util.AddNetworkString("CM_PlaceSpawn") net.Receive("CM_PlaceSpawn", function(len,ply) --[[ if ply:Alive() then local SpawnPoints = ents.FindByClass("ent_bur_spawnpoint") local ShouldSpawn = true local OldSpawnpoint = nil for k,v in pairs(SpawnPoints) do if v.Owner == ply then ShouldSpawn = false OldSpawnpoint = v end end if ShouldSpawn then local Ent = ents.Create("ent_bur_spawnpoint") Ent:SetPos(ply:GetPos()) Ent:SetAngles(ply:GetAngles()) Ent:Spawn() Ent:Activate() Ent:SetOwner(ply) else ply:ChatPrint("You already have a spawnpoint! Deleting old one in 3 seconds...") SafeRemoveEntityDelayed(OldSpawnpoint,3) end else ply:ChatPrint("But you're dead tho") end --]] end) <file_sep>/lua/autorun/client/cl_cm_menus.lua local DefaultWeapons = "weapon_burger_cs_m4 weapon_burger_cs_usp weapon_burger_cs_knife weapon_burger_cs_he" --local DefaultEquipment = "none" CreateClientConVar("cm_editor_weapons",DefaultWeapons,true,true) --CreateClientConVar("cm_editor_equipment",DefaultEquipment,true,true) local CurrentLoadout = CM_GetPlayerWeapons(LocalPlayer()) --local CurrentEquipment = CM_GetPlayerEquipment(LocalPlayer()) local TotalWeight = 0 local TextColorWhite = Color(255,255,255,255) local TextColorBlack = Color(0,0,0,255) -- Balance Info: -- Misc >Nade > Melee > Sniper > Rifle > Shotgun > Smg > Pistol -- 0, All T1 -- 1, T2 Pistols, T2 Melee -- 3, T2 SMGs, T2 Shotguns -- 5, T2 Rifles -- 8, T2 Snipers -- 11, T2 Nades, T2 Misc -- 14, T3 Pistols, T3 Melee -- 18, T3 SMGs, T3 Shotguns -- 22, T3 Rifles -- 26, T3 Snipers -- 30, T3 Nades, T3 Misc -- 35, T4 Pistols, T4 Melee -- 40, T4 SMGs, T4 Shotguns -- 45, T4 Rifles -- 50, T4 Snipers -- 55, T4 Nades, T4 Misc -- 60, T5 Pistols, T5 Melee -- 61, T5 SMGs, T5 Shotguns -- 62, T5 Rifles -- 63, T5 Snipers -- 64, T5 Nades, T5 Misc surface.CreateFont( "ClassmodTiny", { font = "Roboto-Medium", size = 12, weight = 500, blursize = 0, scanlines = 0, antialias = true, underline = false, italic = false, strikeout = false, symbol = false, rotary = false, shadow = false, additive = false, outline = false, } ) surface.CreateFont( "ClassmodSmall", { font = "Roboto-Medium", size = 18, weight = 500, blursize = 0, scanlines = 0, antialias = true, underline = false, italic = false, strikeout = false, symbol = false, rotary = false, shadow = false, additive = false, outline = false, } ) surface.CreateFont( "ClassmodTiny", { font = "Roboto-Medium", size = 14, weight = 500, blursize = 0, scanlines = 0, antialias = true, underline = false, italic = false, strikeout = false, symbol = false, rotary = false, shadow = false, additive = false, outline = false, } ) surface.CreateFont( "ClassmodLarge", { font = "Roboto-Medium", size = 36, weight = 500, blursize = 0, scanlines = 0, antialias = true, underline = false, italic = false, strikeout = false, symbol = false, rotary = false, shadow = false, additive = false, outline = false, } ) local SpaceOffset = 10 local TitleFontSize = 10 local LargeTitleFontSize = 40 local PanelHeight = 100 function CM_ShowClassMenu() local ply = LocalPlayer() local WeightLimit = GetConVar("sv_class_weightlimit"):GetFloat() CurrentLoadout = CM_GetPlayerWeapons(LocalPlayer()) --CurrentEquipment = CM_GetPlayerEquipment(LocalPlayer()) local x = ScrW() - 100 local y = ScrH() - 100 local BaseFrame = vgui.Create("DFrame") BaseFrame:SetSize(x,y) BaseFrame:Center() BaseFrame:SetVisible( true ) BaseFrame:SetDraggable( false ) BaseFrame:ShowCloseButton( true ) --BaseFrame:SetFont("ClassmodSmall") BaseFrame:SetTitle(" ") BaseFrame:MakePopup() BaseFrame.Paint = function(self,w,h) draw.RoundedBoxEx( 4, 0, 0, w, h, Color( 255, 255, 255, 150 ), true,true,true,true ) end BaseFrame:SetMouseInputEnabled( true ) local AllowedListItem = {} local ForbiddenListItem = {} local LW, LH = BaseFrame:GetSize() local AnotherFrame = vgui.Create("DPanel",BaseFrame) AnotherFrame:StretchToParent(SpaceOffset,SpaceOffset + 20,SpaceOffset,SpaceOffset) AnotherFrame.Paint = function(self,w,h) local FlashyColor = HSVToColor( (CurTime()*10)%360, 1, 1 ) FlashyColor.r = FlashyColor.r / 2 FlashyColor.g = FlashyColor.g / 2 FlashyColor.b = FlashyColor.b / 2 FlashyColor.a = 150 draw.RoundedBoxEx( 4, 0, 0, w, h, FlashyColor, true,true,true,true ) end local LW, LH = AnotherFrame:GetSize() local WeightFrame = vgui.Create("DPanel",BaseFrame) WeightFrame:SetPos(SpaceOffset*2,SpaceOffset*4) WeightFrame:SetSize(LW - SpaceOffset*2,LH*0.05 + SpaceOffset) WeightFrame.Paint = function(self,w,h) draw.RoundedBoxEx( 4, 0, 0, w, h, Color( 255, 255, 255, 150 ), true,true,true,true ) end local LW, LH = WeightFrame:GetSize() local WeightBar = vgui.Create("DPanel",WeightFrame) WeightBar:SetPos(SpaceOffset,SpaceOffset) WeightBar:SetSize(LW - SpaceOffset*2,LH - SpaceOffset*2) WeightBar.Paint = function(self,w,h) draw.RoundedBoxEx( 4, 0, 0, w, h, Color( 255, 255, 255, 150 ), true,true,true,true ) end local LW, LH = WeightBar:GetSize() local WeightFill = vgui.Create("DPanel",WeightBar) WeightFill:SetPos(SpaceOffset/2,SpaceOffset/2) WeightFill:SetSize(LW-SpaceOffset,LH-SpaceOffset) WeightFill.Paint = function(self,w,h) local WeightScale = TotalWeight / WeightLimit draw.RoundedBoxEx( 4, 0, 0, w * WeightScale, h, Color( 255 * WeightScale, 255 - (255*WeightScale), 0, 150 ), true,true,true,true ) end local WeightValue = vgui.Create("DLabel",WeightBar) WeightValue:SetText("FUCK YOU") WeightValue:SetFont("ClassmodSmall") WeightValue:SetTextColor(TextColorBlack) WeightValue:SetDark(true) WeightValue:SizeToContents() WeightValue:Center() local LW, LH = AnotherFrame:GetSize() local WeaponFrame = vgui.Create("DPanel",BaseFrame) WeaponFrame:SetSize(LW - SpaceOffset*2, LH * 0.90 - SpaceOffset*5 ) WeaponFrame:SetPos(SpaceOffset*2,SpaceOffset*6 + LH*0.05 ) WeaponFrame.Paint = function(self,w,h) draw.RoundedBoxEx( 4, 0, 0, w, h, Color( 255, 255, 255, 150 ), true,true,true,true ) end local WeaponScroll = vgui.Create("DScrollPanel",WeaponFrame) WeaponScroll:StretchToParent(SpaceOffset,SpaceOffset,SpaceOffset,SpaceOffset) WeaponScroll:Center() local LW, LH = WeaponScroll:GetSize() local List = vgui.Create("DIconLayout",WeaponScroll) List:SetSize(LW - SpaceOffset - 20,LH - SpaceOffset) -- 20 is for the scrollbars List:SetPos(0,0) List:SetSpaceX(SpaceOffset) List:SetSpaceY(SpaceOffset) local LW, LH = List:GetSize() local AllowedWeapons = table.Copy(CMWeapons) local ForbiddenWeapons = {} if CM_IsRankEnabled() then for k,v in pairs(AllowedWeapons) do if v.Rank and v.Rank > SimpleXPGetLevel(ply) then ForbiddenWeapons[k] = v AllowedWeapons[k] = nil end end end local AllowedKeys = table.GetKeys( AllowedWeapons ) local ForbiddenKeys = table.GetKeys( ForbiddenWeapons ) table.sort( ForbiddenKeys, function( a, b ) local WeaponA = ForbiddenWeapons[a] local WeaponB = ForbiddenWeapons[b] local ply = LocalPlayer() if WeaponA.Rank == WeaponB.Rank then if math.abs(WeaponA.Slot) == math.abs(WeaponB.Slot) then if WeaponA.Weight == WeaponB.Weight then return a < b else return WeaponA.Weight < WeaponB.Weight end else return WeaponA.Slot < WeaponB.Slot end else return WeaponA.Rank < WeaponB.Rank end end ) table.sort( AllowedKeys, function( a, b ) local WeaponA = AllowedWeapons[a] local WeaponB = AllowedWeapons[b] local ply = LocalPlayer() if math.abs(WeaponA.Slot) == math.abs(WeaponB.Slot) then if WeaponA.Weight == WeaponB.Weight then return a < b else return WeaponA.Weight < WeaponB.Weight end else return WeaponA.Slot < WeaponB.Slot end end ) --PrintTable(ForbiddenWeapons) local ply = LocalPlayer() for i=1, #AllowedKeys do CM_DrawThing(LW,LH,SpaceOffset,i,AllowedKeys,List,AllowedListItem,AllowedWeapons,WeightValue,false) end --[[ local Blocker = List:Add("DPanel") Blocker:SetSize(LW - SpaceOffset,PanelHeight) Blocker.Paint = function(self,w,h) draw.RoundedBoxEx( 4, 0, 0, w, h, Color( 255, 100, 100, 150 ), true,true,true,true ) end --]] for j=1, #ForbiddenKeys do CM_DrawThing(LW,LH,SpaceOffset,j,ForbiddenKeys,List,ForbiddenListItem,ForbiddenWeapons,WeightValue,true) end local LW, LH = AnotherFrame:GetSize() local ButtonFrame = vgui.Create("DButton",BaseFrame) ButtonFrame:SetPos(SpaceOffset*2,SpaceOffset*2 + LH * 0.95) ButtonFrame:SetText("RESET LOADOUT") ButtonFrame:SetSize(LW - SpaceOffset*2,LH*0.05) ButtonFrame.Paint = function(self,w,h) draw.RoundedBoxEx( 4, 0, 0, w, h, Color( 255, 255, 255, 150 ), true,true,true,true ) if self:IsHovered() then draw.RoundedBoxEx( 4, 0, 0, w, h, Color( 255, 255, 255, 150 ), true,true,true,true ) end end ButtonFrame.DoClick = function() CurrentLoadout = {"none"} --CurrentEquipment = {"none"} for k,v in pairs(AllowedListItem) do if v:IsValid() then v.IsCurrentlySelected = false end end for k,v in pairs(ForbiddenListItem) do if v:IsValid() then v.IsCurrentlySelected = false end end timer.Simple(0, function() CM_RedrawWeight(WeightValue) end) RunConsoleCommand("cm_editor_weapons", string.Trim(string.Implode(" ",CurrentLoadout))) --RunConsoleCommand("cm_editor_equipment", string.Trim(string.Implode(" ",CurrentEquipment))) end CM_RedrawWeight(WeightValue) end concommand.Add( "cm_menu", CM_ShowClassMenu) local LastRank = 0 local LastSlot = 0 function CM_DrawThing(LW,LH,SpaceOffset,i,Keys,List,ListItem,CMWeapons,WeightValue,IsForbidden) local k = Keys[i] local v = CMWeapons[k] if not v then --List:Remove() return end if IsForbidden then if CM_IsRankEnabled() then if LastRank ~= v.Rank then local Blocker = List:Add("DPanel") Blocker:SetSize(LW - SpaceOffset,LargeTitleFontSize + SpaceOffset) Blocker.Paint = function(self,w,h) draw.RoundedBoxEx( 4, 0, 0, w, h, Color( 255, 100, 100, 150 ), true,true,true,true ) end local BlockerText = vgui.Create("DLabel",Blocker) BlockerText:SetText("Requires " .. SimpleXPCheckRank(v.Rank)) BlockerText:SetFont("ClassmodSmall") BlockerText:SetTextColor(TextColorBlack) BlockerText:SizeToContents() BlockerText:Center() LastRank = v.Rank end end else if LastSlot ~= v.Slot then local Blocker = List:Add("DPanel") Blocker:SetSize(LW - SpaceOffset,LargeTitleFontSize + SpaceOffset) Blocker.Paint = function(self,w,h) draw.RoundedBoxEx( 4, 0, 0, w, h, Color( 255, 255, 255, 150 ), true,true,true,true ) end local TextTable = {} TextTable[1] = "Melee" TextTable[2] = "Sidearm" TextTable[3] = "Secondary" TextTable[4] = "Primary" TextTable[5] = "Equipment" TextTable[100] = "Special" if TextTable[v.Slot] then local BlockerText = vgui.Create("DLabel",Blocker) BlockerText:SetText(string.upper(TextTable[v.Slot])) BlockerText:SetFont("ClassmodLarge") BlockerText:SetTextColor(TextColorBlack) BlockerText:SizeToContents() BlockerText:Center() end LastSlot = v.Slot end end ListItem[i] = List:Add("DPanel") ListItem[i]:SetSize(LW/3 - SpaceOffset,PanelHeight) if table.HasValue(CurrentLoadout,k) then ListItem[i].IsCurrentlySelected = true else ListItem[i].IsCurrentlySelected = false end ListItem[i].Paint = function(self,w,h) local RedMod = 255 local GreenMod = 255 local BlueMod = 255 if self.IsCurrentlySelected then RedMod = 0 BlueMod = 0 elseif not CM_CanSpawnWith(LocalPlayer(),k,false) then GreenMod = 0 BlueMod = 0 end draw.RoundedBoxEx( 4, 0, 0, w, h, Color( RedMod, GreenMod, BlueMod, 150 ), true,true,true,true ) end local LW, LH = ListItem[i]:GetSize() local SWEP = weapons.GetStored(k) if SWEP or v.Equipment then local GetModel = "models/props_c17/lampShade001a.mdl" if v.IconModel then GetModel = v.IconModel elseif SWEP then GetModel = SWEP.WorldModel if SWEP.DisplayModel then GetModel = SWEP.DisplayModel end end if GetModel and GetModel ~= "" then local ModelPanel = vgui.Create( "DModelPanel",ListItem[i] ) ModelPanel:SetPos( SpaceOffset, SpaceOffset ) ModelPanel:SetSize( PanelHeight, PanelHeight ) ModelPanel:SetLookAt( Vector( 0,0,0 ) ) -- ModelPanel:SetLookAng( Angle(0,0,0) ) ModelPanel:SetFOV(10) ModelPanel:SetModel( GetModel ) end local WeaponNameFrame = vgui.Create("DPanel",ListItem[i]) WeaponNameFrame:SetPos(PanelHeight,SpaceOffset) WeaponNameFrame:SetSize(LW - PanelHeight - SpaceOffset*2,LargeTitleFontSize + SpaceOffset) WeaponNameFrame:SetText("") WeaponNameFrame.Paint = function(self,w,h) draw.RoundedBoxEx( 4, 0, 0, w, h, Color( 255, 255, 255, 150 ), true,true,true,true ) end --if CM_IsRankEnabled() then local DetailsFrame = vgui.Create("DPanel",ListItem[i]) DetailsFrame:SetPos(PanelHeight,SpaceOffset*3 + LargeTitleFontSize) DetailsFrame:SetSize(LW - PanelHeight - SpaceOffset*2,TitleFontSize + SpaceOffset) DetailsFrame:SetText("") DetailsFrame.Paint = function(self,w,h) draw.RoundedBoxEx( 4, 0, 0, w, h, Color( 255, 255, 255, 150 ), true,true,true,true ) end local DetailsText = vgui.Create("DLabel",DetailsFrame) local ActualText = "" if CM_IsRankEnabled() and CM_IsCostEnabled() and v.Cost then ActualText = SimpleXPCheckRank(v.Rank) .. ", $" .. v.Cost elseif CM_IsRankEnabled() then ActualText = SimpleXPCheckRank(v.Rank) elseif CM_IsCostEnabled() and v.Cost then ActualText = "$" .. v.Cost end DetailsText:SetText(ActualText) DetailsText:SetFont("ClassmodSmall") DetailsText:SetTextColor(TextColorBlack) DetailsText:SizeToContents() DetailsText:Center() --end local PrintName = "No Name" if v.Name then PrintName = v.Name elseif SWEP then PrintName = SWEP.PrintName end local WeaponNameText = vgui.Create("DLabel",WeaponNameFrame) WeaponNameText:SetText(PrintName .. " [" .. v.Weight .. "KG]") WeaponNameText:SetFont("ClassmodLarge") WeaponNameText:SetTextColor(TextColorBlack) WeaponNameText:SizeToContents() WeaponNameText:Center() local ButtonPanel = vgui.Create("DButton",ListItem[i]) ButtonPanel:SetPos(SpaceOffset,SpaceOffset) ButtonPanel:SetText("") ButtonPanel:SetSize(LW - SpaceOffset*2,LH - SpaceOffset*2) ButtonPanel.DoClick = function() if ListItem[i].IsCurrentlySelected then CurrentLoadout = CM_RemoveWeapon(k,CurrentLoadout) ListItem[i].IsCurrentlySelected = false else if not CM_CanSpawnWith(LocalPlayer(),k,true) then surface.PlaySound( "buttons/weapon_cant_buy.wav" ) else table.Add(CurrentLoadout,{k}) ListItem[i].IsCurrentlySelected = true end end RunConsoleCommand("cm_editor_weapons", string.Trim(string.Implode(" ",CurrentLoadout))) timer.Simple(0, function() CM_RedrawWeight(WeightValue) end) end if SWEP then ButtonPanel.WeaponStats = BURGERBASE_CalculateWeaponStats(LocalPlayer(),SWEP,true) end ButtonPanel.Paint = function(self,w,h) if self:IsHovered() then if self.WeaponStats then draw.RoundedBoxEx( 4, 0, 0, w, h, Color( 255, 255, 255, 255 ), true,true,true,true ) local Offset = 5 local MaxWidth = w - Offset*2 local TotalSpace = -5 local DamageMod = math.Clamp(self.WeaponStats.damage/100,0,1) draw.RoundedBoxEx( 2, Offset, Offset*2 + TotalSpace, MaxWidth, SpaceOffset, Color( 255, 0, 0, 150 ), true,true,true,true ) draw.RoundedBoxEx( 2, Offset, Offset*2 + TotalSpace, MaxWidth*DamageMod, SpaceOffset, Color( 255, 255, 0, 150 ), true,true,true,true ) draw.DrawText( "Damage","ClassmodTiny",Offset*2,Offset*1.5 + TotalSpace,Color( 0, 0, 0, 255 ), TEXT_ALIGN_LEFT ) TotalSpace = TotalSpace + Offset*3 local AccuracyMod = math.Clamp(self.WeaponStats.accuracy,0,1) draw.RoundedBoxEx( 2, Offset, Offset*2 + TotalSpace, MaxWidth, SpaceOffset, Color( 255, 0, 0, 150 ), true,true,true,true ) draw.RoundedBoxEx( 2, Offset, Offset*2 + TotalSpace, MaxWidth*AccuracyMod, SpaceOffset, Color( 255, 255, 0, 150 ), true,true,true,true ) draw.DrawText( "Accuracy","ClassmodTiny",Offset*2,Offset*1.5 + TotalSpace,Color( 0, 0, 0, 255 ), TEXT_ALIGN_LEFT ) TotalSpace = TotalSpace + Offset*3 local FireRateMod = math.Clamp(self.WeaponStats.rpm/800,0,1) draw.RoundedBoxEx( 2, Offset, Offset*2 + TotalSpace, MaxWidth, SpaceOffset, Color( 255, 0, 0, 150 ), true,true,true,true ) draw.RoundedBoxEx( 2, Offset, Offset*2 + TotalSpace, MaxWidth*FireRateMod, SpaceOffset, Color( 255, 255, 0, 150 ), true,true,true,true ) draw.DrawText( "Firerate","ClassmodTiny",Offset*2,Offset*1.5 + TotalSpace,Color( 0, 0, 0, 255 ), TEXT_ALIGN_LEFT ) TotalSpace = TotalSpace + Offset*3 local DPSMod = math.Clamp(self.WeaponStats.dps/600,0,1) draw.RoundedBoxEx( 2, Offset, Offset*2 + TotalSpace, MaxWidth, SpaceOffset, Color( 255, 0, 0, 150 ), true,true,true,true ) draw.RoundedBoxEx( 2, Offset, Offset*2 + TotalSpace, MaxWidth*DPSMod, SpaceOffset, Color( 255, 255, 0, 150 ), true,true,true,true ) draw.DrawText( "DPS","ClassmodTiny",Offset*2,Offset*1.5 + TotalSpace,Color( 0, 0, 0, 255 ), TEXT_ALIGN_LEFT ) TotalSpace = TotalSpace + Offset*3 local RangeMod = math.Clamp(self.WeaponStats.range/6000,0,1) draw.RoundedBoxEx( 2, Offset, Offset*2 + TotalSpace, MaxWidth, SpaceOffset, Color( 255, 0, 0, 150 ), true,true,true,true ) draw.RoundedBoxEx( 2, Offset, Offset*2 + TotalSpace, MaxWidth*RangeMod, SpaceOffset, Color( 255, 255, 0, 150 ), true,true,true,true ) draw.DrawText( "Range","ClassmodTiny",Offset*2,Offset*1.5 + TotalSpace,Color( 0, 0, 0, 255 ), TEXT_ALIGN_LEFT ) TotalSpace = TotalSpace + Offset*3 --[[ if SWEP.Description then draw.DrawText( SWEP.Description,"ClassmodTiny",Offset*2,Offset*1.5 + TotalSpace,Color( 0, 0, 0, 255 ), TEXT_ALIGN_LEFT ) end --]] else draw.RoundedBoxEx( 4, 0, 0, w, h, Color( 255, 255, 255, 100 ), true,true,true,true ) end end end local Description = "" if v.Description then Description = v.Description elseif SWEP and SWEP.Description then Description = v.Description end if Description ~= "" then ButtonPanel:SetTooltip(Description) end else ListItem[i]:Remove() end end function CM_RedrawWeight(WeightValue) local WeightLimit = GetConVar("sv_class_weightlimit"):GetFloat() local Weapons = string.Explode(" ",string.Trim(GetConVar("cm_editor_weapons"):GetString())) TotalWeight = 0 for k,v in pairs(Weapons) do if not CMWeapons[v] then else TotalWeight = TotalWeight + CMWeapons[v].Weight end end local MovePercent = CM_GetMoveMul(TotalWeight) * 100 WeightValue:SetText(TotalWeight .. "/" .. WeightLimit .. " (Mobility: " .. MovePercent .. "%)" ) WeightValue:SizeToContents() WeightValue:Center() end function CM_OnSpawnMenuOpen() --[[ if engine.ActiveGamemode() == "sandbox" then net.Start("CM_PlaceSpawn") net.WriteBool(true) net.SendToServer() end --]] end hook.Add("OnSpawnMenuOpen","CM_OnSpawnMenuOpen",CM_OnSpawnMenuOpen) <file_sep>/lua/autorun/sh_cm_weapons.lua CreateConVar( "sv_class_weightlimit", "100", FCVAR_ARCHIVE + FCVAR_NOTIFY + FCVAR_REPLICATED, "Maximum Weight Limit" ) CreateConVar( "sv_class_rankings", "0", FCVAR_ARCHIVE + FCVAR_NOTIFY + FCVAR_REPLICATED, "Enable Rankings" ) -- Class Mod Weapon Data function CM_GetPlayerWeapons(ply) local Weapons if CLIENT then Weapons = string.Explode(" ",string.Trim(GetConVar("cm_editor_weapons"):GetString())) else Weapons = string.Explode(" ",string.Trim(ply:GetInfo("cm_editor_weapons"))) end return Weapons end --[[ function CM_GetPlayerEquipment(ply) local Equipment if CLIENT then Equipment = string.Explode(" ",string.Trim(GetConVar("cm_editor_equipment"):GetString())) else Equipment = string.Explode(" ",string.Trim(ply:GetInfo("cm_editor_equipment"))) end return Weapons end --]] function CM_GetPlayerWeight(ply) local Weapons = CM_GetPlayerWeapons(ply) --+ CM_GetPlayerEquipment(ply) local WeightCount = 0 for k,v in pairs(Weapons) do local Weapon = CMWeapons[v] if Weapon then WeightCount = WeightCount + Weapon.Weight end end return WeightCount end function CM_GetPlayerWeightCurrent(ply) local Weapons = ply:GetWeapons() local WeightCount = (ply:Armor()/4) for k,v in pairs(Weapons) do local Weapon = CMWeapons[v:GetClass()] if Weapon then WeightCount = WeightCount + Weapon.Weight end end return WeightCount end function CM_UpdateWeight(ply) ply.CM_Weight = CM_GetPlayerWeightCurrent(ply) end local NextUpdate = 0 function CM_Think() if NextUpdate <= CurTime() then if SERVER then for k,v in pairs(player.GetHumans()) do CM_UpdateWeight(v) end end if CLIENT then CM_UpdateWeight(LocalPlayer()) end NextUpdate = NextUpdate + 0.25 end end hook.Add("Think","CM_Think",CM_Think) function CM_GetMoveMul(weight) if not weight then weight = 0 end return math.Round( math.Clamp(0.6 + (1 - (weight / 40))*0.5,0.25,1),2 ) end function CM_Move(ply,mv) if not ply:IsBot() then local SpeedMul = CM_GetMoveMul(ply.CM_Weight) mv:SetMaxClientSpeed(mv:GetMaxSpeed() * SpeedMul) mv:SetMaxSpeed(mv:GetMaxSpeed() * SpeedMul) end end hook.Add("Move","CM_Move",CM_Move) function CM_GetPlayerNadeCount(ply) local Weapons = CM_GetPlayerWeapons(ply) local NadeCount = 0 for k,v in pairs(Weapons) do local Weapon = CMWeapons[v] if Weapon then if WeaponSlot == 5 then NadeCount = NadeCount + 1 end end end return NadeCount end function CM_CanSpawnWith(ply,weapon,givereason,tableoverride) if not tableoverride then tableoverride = CM_GetPlayerWeapons(ply) end local Weapon01 = CMWeapons[weapon] if not Weapon01 then return false end if CM_IsRankEnabled() then if Weapon01.Rank then if Weapon01.Rank > SimpleXPGetLevel(ply) then if givereason then print("NOT UNLOCKED") end return false end else print(Weapon01.Name," has no rank!") end end if CM_IsCostEnabled() then if Weapon01.Cost > MONEYMOD_GetMoney(ply) then if givereason then print("NOT ENOUGH MONEY") end return false end end local Weapons = tableoverride if table.Count(Weapons) > 0 then local TotalWeight = Weapon01.Weight or 0 local TotalCost = Weapon01.Cost or 0 local GrenadeCount = 0 if Weapon01.Slot == 5 then GrenadeCount = 1 end for k,v in pairs(Weapons) do if CMWeapons[v] then local Weapon02 = CMWeapons[v] if Weapon01 ~= Weapon02 then if CM_SharesSameSlot(Weapon01,Weapon02) then if givereason then print("SHARES SAME SLOT") end return false end if Weapon02.Slot == 5 then GrenadeCount = GrenadeCount + 1 end if GrenadeCount > 3 then if givereason then print("YOU HAVE MORE THAN 3 GRENADES") end return false end if CM_IsCostEnabled() then TotalCost = TotalCost + (Weapon02.Cost or 0) if TotalCost > MONEYMOD_GetMoney(ply) then if givereason then print("NOT ENOUGH MONEY") end return false end end TotalWeight = TotalWeight + Weapon02.Weight if TotalWeight > CM_GetMaxWeight() then if givereason then print("TOTAL WEIGHT EXCEEDS MAXIMUM WEIGHT.") end return false end end end end end return true end function CM_SharesSameSlot(Weapon01,Weapon02) if Weapon01.Slot <= 1 or Weapon01.Slot == 5 then return false end return Weapon01.Slot == Weapon02.Slot end function CM_IsCostEnabled() return false end function CM_RemoveWeapon(weapon,CurrentLoadout) table.RemoveByValue(CurrentLoadout,weapon) if table.Count(CurrentLoadout) == 0 then CurrentLoadout = {"none"} elseif table.Count(CurrentLoadout) >= 2 and table.HasValue(CurrentLoadout,"none") then table.RemoveByValue(CurrentLoadout,"none") end return CurrentLoadout end function CM_IsRankEnabled() return ( GetConVar("sv_class_rankings"):GetFloat() == 1 ) end function CM_GetMaxWeight() return ( GetConVar("sv_class_weightlimit"):GetFloat() ) end<file_sep>/lua/autorun/sh_cm_data.lua local T00 = 0 local TMelee = 5 local T01Sidearm = 1 local T01Secondary = 3 local T01Primary = 5 local T01Special = 8 local T02Sidearm = 11 local T02Secondary = 14 local T02Primary = 18 local T02Special = 22 local T03Sidearm = 26 local T03Secondary = 30 local T03Primary = 35 local T03Special = 40 local T04Sidearm = 45 local T04Secondary = 50 local T04Primary = 55 local T04Special = 56 -- Special Equipment CMWeapons["armor20"] = { Name = "20 Armor", Equipment = true, Weight = 5, Slot = 100, Rank = T00, func = function(ply) ply:SetArmor(ply:Armor() + 20) end, } CMWeapons["armor50"] = { Name = "50 Armor", Equipment = true, Weight = 12.5, Slot = 100, Rank = T01Special, func = function(ply) ply:SetArmor(ply:Armor() + 50) end, } CMWeapons["armor100"] = { Name = "100 Armor", Equipment = true, Weight = 25, Slot = 100, Rank = T02Special, func = function(ply) ply:SetArmor(ply:Armor() + 100) end, } --[[ CMWeapons["weapon_smod_drank"] = { -- T1 Misc Weight = 2, Slot = 100, Rank = T00, } --]] -- Melee CMWeapons["weapon_hl2_fists"] = { -- T1 Melee Weight = 0, Slot = 1, Rank = 0, Cost = 0, } CMWeapons["weapon_burger_cs_knife"] = { -- T1 Melee Weight = 1, Slot = 1, Rank = TMelee, Cost = 0, } CMWeapons["weapon_hl2_crowbar"] = { -- T2 Melee Weight = 2, Slot = 1, Rank = TMelee, Cost = 50, } CMWeapons["weapon_hl2_stunstick"] = { -- T3 Melee Weight = 3, Slot = 1, Rank = TMelee, Cost = 500, } CMWeapons["weapon_smod_katana"] = { -- T3 Melee Weight = 25, Slot = 1, Rank = TMelee, } CMWeapons["weapon_halo_sword"] = { -- T2 Equipment Weight = 6, Slot = 1, Rank = TMelee, } CMWeapons["weapon_burfof_axe"] = { -- T2 Equipment Weight = 4, Slot = 1, Rank = TMelee, } CMWeapons["weapon_burfof_knife"] = { -- T2 Equipment Weight = 1.5, Slot = 1, Rank = TMelee, } CMWeapons["weapon_burfof_machete"] = { -- T2 Equipment Weight = 3, Slot = 1, Rank = TMelee, } -- T0 CMWeapons["weapon_smod_dbarrel"] = { -- T3 Shotgun Weight = 4, Slot = 3, Rank = T00, } CMWeapons["weapon_burger_cs_he"] = { -- T1 Nade Weight = 1, Slot = 5, Rank = T00, Cost = 200, } CMWeapons["weapon_burfof_deringer"] = { -- T2 Equipment Weight = 0, Slot = 2, Rank = T00, Cost = 0, } CMWeapons["weapon_hl2_pistol"] = { -- T0 Sidearm Weight = 2, Slot = 2, Rank = T00, Cost = 0, } CMWeapons["weapon_halo_plasmapistol"] = { -- T0 Sidearm Weight = 3, Slot = 2, Rank = T00, Cost = 0, } CMWeapons["weapon_hl2_smg"] = { -- T0 Secondary Weight = 4, Slot = 3, Rank = T00, Cost = 0, } CMWeapons["weapon_hl2_spas"] = { -- T0 Secondary Weight = 5, Slot = 3, Rank = T00, Cost = 0, } CMWeapons["weapon_burger_cs_m3"] = { -- T1 Shotgun Weight = 4, Slot = 3, Rank = T00, Cost = 1000, } CMWeapons["weapon_burger_cs_scout"] = { -- T0 Primary Weight = 6, Slot = 4, Rank = T00, Cost = 0, } CMWeapons["weapon_halo_sniper"] = { -- T0 Primary Weight = 8, Slot = 4, Rank = T00, Cost = 0, } CMWeapons["weapon_burger_cs_glock"] = { -- T1 Pistol Weight = 1, Slot = 2, Rank = T00, Cost = 0, } CMWeapons["weapon_burger_cs_usp"] = { -- T1 Pistol Weight = 1, Slot = 2, Rank = T00, Cost = 0, } CMWeapons["weapon_halo_magnum"] = { -- T2 Equipment Weight = 4, Slot = 2, Rank = T00, } CMWeapons["weapon_burger_cs_famas"] = { -- T2 Rifle Weight = 7, Slot = 4, Rank = T00, Cost = 0, } CMWeapons["weapon_burger_cs_galil"] = { -- T1 Rifle Weight = 6, Slot = 4, Rank = T00, Cost = 0, } CMWeapons["weapon_burger_cs_mac10"] = { -- T1 SMG Weight = 4, Slot = 3, Rank = T00, Cost = 1000, } CMWeapons["weapon_burger_cs_tmp"] = { -- T1 SMG Weight = 4, Slot = 3, Rank = T00, Cost = 1500, } -- T01 CMWeapons["weapon_burfof_bow"] = { -- T2 Equipment Weight = 2, Slot = 3, Rank = T01Special, } CMWeapons["weapon_smod_mp5k"] = { -- T3 SMG Weight = 5, Slot = 3, Rank = T01Special, } CMWeapons["weapon_burger_cs_xm1014"] = { -- T3 Shotgun Weight = 5, Slot = 3, Rank = T01Secondary, Cost = 2000, } CMWeapons["weapon_burger_cs_flash"] = { -- T2 Nade Weight = 2, Slot = 5, Rank = T01Special, Cost = 300, } CMWeapons["weapon_smod_cz52"] = { -- T2 Sidearm Weight = 3, Slot = 2, Rank = T01Sidearm, Cost = 300, } CMWeapons["weapon_burger_cs_m4"] = { -- T1 Rifle Weight = 6, Slot = 4, Rank = T01Primary, Cost = 2000, } CMWeapons["weapon_burger_cs_ak47"] = { -- T2 Rifle Weight = 7, Slot = 4, Rank = T01Primary, Cost = 3000, } CMWeapons["weapon_halo_smg"] = { -- T2 Equipment Weight = 5, Slot = 3, Rank = T01Secondary, } CMWeapons["weapon_burger_cs_fiveseven"] = { -- T2 Pistol Weight = 2, Slot = 2, Rank = T01Sidearm, Cost = 300, } CMWeapons["weapon_burger_cs_p228"] = { -- T2 Pistol Weight = 2, Slot = 2, Rank = T01Sidearm, Cost = 300, } CMWeapons["weapon_burfof_volcanic"] = { -- T2 Equipment Weight = 4.5, Slot = 2, Rank = T01Sidearm, } CMWeapons["weapon_halo_beamrifle"] = { -- T2 Equipment Weight = 7.5, Slot = 4, Rank = T01Primary, } CMWeapons["weapon_smod_anna"] = { -- T3 Primary Weight = 6, Slot = 4, Rank = T01Primary, Cost = 1000, } CMWeapons["weapon_burfof_sharps"] = { -- T2 Equipment Weight = 8, Slot = 4, Rank = T01Special, } CMWeapons["weapon_smod_kar98"] = { -- T2 Sniper Weight = 9, Slot = 4, Rank = T01Primary, } CMWeapons["weapon_smod_combinecannon"] = { -- T2 Special Weight = 12, Slot = 4, Rank = T01Special, } CMWeapons["weapon_halo_beamrifle"] = { -- T2 Equipment Weight = 7.5, Slot = 4, Rank = T01Primary, Cost = 1000, } CMWeapons["weapon_halo_plasmarifle"] = { -- T2 Equipment Weight = 5, Slot = 3, Rank = T01Primary, } CMWeapons["weapon_burger_cs_mp5"] = { -- T2 SMG Weight = 5, Slot = 3, Rank = T01Secondary, Cost = 1500, } CMWeapons["weapon_burger_cs_ump"] = { -- T3 SMG Weight = 5, Slot = 3, Rank = T01Secondary, Cost = 2000, } -- T02 CMWeapons["weapon_burfof_sawed_shotgun"] = { -- T2 Equipment Weight = 5, Slot = 2, Rank = T02Sidearm, } CMWeapons["weapon_smod_stg"] = { -- T3 SMG Weight = 6.5, Slot = 4, Rank = T02Secondary, } CMWeapons["weapon_smod_m4a1"] = { -- T3 Rifle Weight = 7, Slot = 4, Rank = T02Primary, } CMWeapons["weapon_smod_m1grande"] = { -- T3 Rifle Weight = 7, Slot = 4, Rank = T02Primary, } CMWeapons["weapon_burger_cs_smoke"] = { -- T3 Nade Weight = 3, Slot = 5, Rank = T02Primary, Cost = 400, } CMWeapons["weapon_halo_plasmarifle_red"] = { -- T2 Equipment Weight = 6, Slot = 3, Rank = T02Primary, } CMWeapons["weapon_halo_carbine"] = { -- T2 Equipment Weight = 7, Slot = 4, Rank = T02Primary, } CMWeapons["weapon_halo_shotgun"] = { -- T2 Equipment Weight = 5, Slot = 3, Rank = T02Secondary, } CMWeapons["weapon_burger_cs_awp"] = { -- T3 Sniper Weight = 9, Slot = 4, Rank = T02Primary, Cost = 4000, } CMWeapons["weapon_burger_cs_aug"] = { -- T3 Rifle Weight = 8, Slot = 4, Rank = T02Primary, Cost = 3000, } CMWeapons["weapon_smod_greasegun"] = { -- T3 SMG Weight = 5, Slot = 3, Rank = T02Secondary, } CMWeapons["weapon_burfof_maresleg"] = { -- T3 Secondary Weight = 4, Slot = 3, Rank = T02Secondary, } CMWeapons["weapon_burfof_peacemaker"] = { -- T2 Equipment Weight = 3.5, Slot = 2, Rank = T02Secondary, } CMWeapons["weapon_burfof_henry"] = { -- T2 Equipment Weight = 7.5, Slot = 4, Rank = T02Primary, } CMWeapons["weapon_burfof_coachgun"] = { -- T2 Equipment Weight = 6, Slot = 3, Rank = T02Secondary, } CMWeapons["weapon_smod_svd"] = { -- T3 Sniper Weight = 8, Slot = 4, Rank = T02Primary, } CMWeapons["weapon_burfof_carbine"] = { -- T2 Equipment Weight = 7, Slot = 4, Rank = T02Primary, } CMWeapons["weapon_halo_new"] = { -- T2 Equipment Weight = 9, Slot = 3, Rank = T02Secondary, } CMWeapons["weapon_burfof_carbine"] = { -- T2 Equipment Weight = 7, Slot = 4, Rank = T02Primary, } CMWeapons["weapon_burger_cs_para"] = { -- T3 Rifle Weight = 10, Slot = 4, Rank = T02Secondary, Cost = 4000, } CMWeapons["weapon_burger_cs_sig552"] = { -- T3 Rifle Weight = 8, Slot = 4, Rank = T02Secondary, Cost = 3000, } CMWeapons["weapon_burger_cs_deserteagle"] = { -- T3 Pistol Weight = 5, Slot = 2, Rank = T02Sidearm, Cost = 800, } CMWeapons["weapon_burger_cs_dualbertta"] = { -- T3 Pistol Weight = 4, Slot = 2, Rank = T02Sidearm, Cost = 900, } CMWeapons["weapon_burger_cs_p90"] = { -- T3 SMG Weight = 6, Slot = 3, Rank = T02Secondary, Cost = 2500, } CMWeapons["weapon_smod_oicw"] = { -- T3 Rifle Weight = 8, Slot = 4, Rank = T02Special, } CMWeapons["weapon_halo_battlerifle"] = { -- T2 Equipment Weight = 7, Slot = 4, Rank = T02Primary, } -- T03 CMWeapons["weapon_smod_alyxgun"] = { -- T3 Sidearm Weight = 6, Slot = 2, Rank = T03Sidearm, Cost = 500, } CMWeapons["weapon_smod_mp40"] = { -- T3 SMG Weight = 6, Slot = 3, Rank = T03Secondary, } CMWeapons["weapon_smod_tripmine"] = { -- T2 Equipment Weight = 5, Slot = 5, Rank = T03Special, } CMWeapons["weapon_smod_m4a1nade"] = { -- T3 Rifle Weight = 9, Slot = 4, Rank = T03Special, } CMWeapons["weapon_burfof_schofield"] = { -- T2 Equipment Weight = 5, Slot = 2, Rank = T03Sidearm, } CMWeapons["weapon_smod_m60"] = { -- T3 Rifle Weight = 11, Slot = 4, Rank = T03Special, } CMWeapons["weapon_smod_flamethrower"] = { -- T4 Special Weight = 10, Slot = 4, Rank = T03Special, } CMWeapons["weapon_smod_gl"] = { -- T4 Misc Weight = 12, Slot = 4, Rank = T03Special, } CMWeapons["weapon_burfof_walker"] = { -- T3 Sidearm Weight = 6, Slot = 2, Rank = T03Sidearm, } CMWeapons["weapon_burger_cs_g3"] = { -- T3 Sniper Weight = 10, Slot = 4, Rank = T03Primary, Cost = 5000, } CMWeapons["weapon_burger_cs_sig550"] = { -- T3 Sniper Weight = 10, Slot = 4, Rank = T03Primary, Cost = 5000, } CMWeapons["weapon_hl2_357"] = { -- T3 Pistol Weight = 5, Slot = 2, Rank = T03Sidearm, Cost = 800, } CMWeapons["weapon_hl2_ar2"] = { -- T3 Rifle Weight = 7, Slot = 4, Rank = T03Primary, Cost = 3000, } CMWeapons["weapon_hl2_crossbow"] = { -- T3 Misc Weight = 6, Slot = 4, Rank = T03Special, Cost = 1000, } -- T04 CMWeapons["weapon_smod_beangun"] = { -- T3 Misc Weight = 11, Slot = 4, Rank = T04Special, } CMWeapons["weapon_smod_dualcolts"] = { -- T4 Sidearm Weight = 6, Slot = 2, Rank = T04Sidearm, Cost = 1200, }
27a4c9f0719f7fbca215b68e0a053390f9fb6fbe
[ "Lua" ]
4
Lua
BurgerLUA/classmod3
801a76cac6e98040649626fb47ad3d1defb9120d
9ff3b91b40add297462601dfc3d2bf877055af6d
refs/heads/master
<repo_name>santosdiiih/Aulas-Php<file_sep>/aula12-1 MVC/Model/contatoClass.php <?php ########################## LEMBRETE ######################################### # Nome da classe :' Contato() # # Objetivo : Manipular dados com o BD MSQL referente a contatos # # Data da criaçao: 06/07/2020 # # Autor: <NAME> # # Data da modificação : # Autor da modificação : # Conteudos Modificados : # # ############################################################################# # atibutos da classe class Contato{ private $idContato; private $nome; private $endereco; private $bairro; private $cep; private $idEstado; private $telefone; private $celular; private $email; private $dataNascimento; private $obs; private $sexo; public function __construct() { } #get IdContato public function getIdContato(){ return $this->idContato; } #set Id Contatos public function setIdContato($idContato){ return $this->idContato = $idContato; } #get IdContato public function getNome(){ return $this->nome; } #set Id Contatos public function setNome($nome){ return $this->nome = $nome; } #get IdContato public function getEndereco(){ return $this->endereco; } #set Id Contatos public function setEndereco($endereco){ return $this->endereco = $endereco; } #get IdContato public function getBairro(){ return $this->bairro; } #set Id Contatos public function setBairro($bairro){ return $this->bairro = $bairro; } #get IdContato public function getCep(){ return $this->cep; } #set Id Contatos public function setCep($cep){ return $this->cep = $cep; } #get IdContato public function getIdEstado(){ return $this->idEstado; } #set idEstado public function setIdEstado($idEstado){ return $this->idEstado = $idEstado; } #get telefone public function getTelefone(){ return $this->telefone; } #set telefone public function setTelefone($telefone){ return $this->telefone = $telefone; } #get celular public function getCelular(){ return $this->celular; } #set celular public function setCelular($celular){ return $this->celular = $celular; } #get email public function getEmail(){ return $this->email; } #set email public function setEmail($email){ return $this->email = $email; } #get dataNascimento public function getDataNascimento(){ return $this->dataNascimento; } #set dataNascimento public function setDataNascimento($dataNascimento){ return $this->dataNascimento = $dataNascimento; } #get obs public function getObs(){ return $this->obs; } #set obs public function setObs($obs){ return $this->obs = $obs; } #get obs public function getSexo(){ return $this->obs; } #set obs public function setSexo($sexo){ return $this->sexo = $sexo; } } ?> <file_sep>/aula12-1upload-ajax/BD/visualizarContato.php <?php if(isset($_POST['modo'])){ if($_POST['modo'] == 'visualizar'){ if (isset($_POST['id'])){ # inserindo o arquivo de conexao que esta dentro da pasta BD (referente ao banco de dados); include_once('conexao.php'); # recebe a funcao de conexao do bd $conex = conexaoMysql(); $id = $_POST['id']; $sql = "select tblContatos.*, tblEstados.nome as nomeEstado, tblEstados.sigla from tblContatos, tblEstados where tblEstados.idEstado = tblContatos.idEstado and tblContatos.idContato = ".$id; $selectContato = mysqli_query($conex, $sql); // echo($sql); exit; if($rsContatos = mysqli_fetch_assoc($selectContato)){ $nome = $rsContatos['nome']; $endereco = $rsContatos['endereco']; $bairro = $rsContatos['bairro']; $cep = $rsContatos['cep']; $estado = $rsContatos['nomeEstado']. "-" . $rsContatos['sigla'] ; $telefone = $rsContatos['telefone']; $celular = $rsContatos['celular']; $email = $rsContatos['email']; $dtNascimento = explode("-", $rsContatos['dtNascimento']); $dataNascimento = $dtNascimento[2]."/".$dtNascimento[1]."/".$dtNascimento[0]; $sexo = $rsContatos['sexo']; $obs = $rsContatos['obs'] ; } } } } ?> <html> <head> <title> Visualizar Contatos</title> <link rel="stylesheet" type="text/css" href="../css/style.css"> <script src="scripts/jquery.js"></script> <script> $(document).ready(function(){ $('#fechar').click(function(){ $('#modal').fadeOut(1000); }); }); </script> </head> <body> <div id="visualizar"> <a href="#" id="fechar"> fechar </a> <table> <tr class="titulo"> <td colspan="2"> Contatos </td> </tr> <tr> <td> Nome: </td> <td><?=$nome?></td> </tr> <tr> <td> Endereço: </td> <td><?=$endereco?></td> </tr> <tr> <td> CEP: </td> <td><?=$cep?></td> </tr> <tr> <td> Bairro: </td> <td><?=$bairro?></td> </tr> <tr> <td> Estado: </td> <td><?=$estado?></td> </tr> <tr> <td> Telefone: </td> <td><?=$telefone?></td> </tr> <tr> <td> Celular: </td> <td><?=$celular?></td> </tr> <tr> <td> Email: </td> <td><?=$email?></td> </tr> <tr> <td> Data Nascimento: </td> <td><?=$dataNascimento?></td> </tr> <tr> <td> Sexo: </td> <td><?=$sexo?></td> </tr> <tr> <td> Obs: </td> <td><?=$obs?></td> </tr> </table> </div> </body> </html><file_sep>/aula12-1 MVC/View/home.php <!DOCTYPE> <html lang="pt-br"> <head> <meta charset="UTF-8"> <title> Cadastro </title> <link rel="stylesheet" type="text/css" href="View/style/style.css"> <script src="View/scripts/jquery.js"></script> </head> <body> <?php require_once('Contatos/contatosView.php'); ?> </body> </html> <file_sep>/aula12-1upload-ajax/BD/insertContato.php <?php # veridica se a variavel modo exite if (isset($_GET['modo'])) { # verifica que o conteudo do modo é inserir if ($_GET['modo'] == 'inserir') { # CONEXAO COM O BANCO DE DADOS require_once('conexao.php'); # recebe a funcao de conexao do bd $conex = conexaoMysql(); #VERIFICANDO SE O BOTAO FOI SUBMETIDO if (isset($_POST['btnEnviar'])) { # RECEBENDO OS DADOS FORNECIDOS PELO USUARIO $nome = $_POST['txtNome']; $endereco = $_POST['txtEndereco']; $cep = $_POST['txtCep']; $bairro = $_POST['txtBairro']; $telefone = $_POST['txtTelefone']; $celular = $_POST['txtCelular']; $email = $_POST['txtEmail']; #CONVERSAO DA DATA PARA O PADRAO AMERICANO PARA ENVIAR AO BANCO $dataNascimento = explode("/", $_POST['txtNascimento']); $dtNascimentoAmericano = $dataNascimento[2]."-".$dataNascimento[1]."-".$dataNascimento[0]; $observacao = $_POST['txtObs']; $sexo = $_POST['rdoSexo']; $idEstado = $_POST['sltEstados']; #ativa o uso da variavel de sessao e resgata o dado na variavel foto que vem do upload.php session_start(); $foto = $_SESSION['nomeFoto']; $sql = "insert into tblContatos (nome, endereco, cep, bairro, telefone, celular, email, dtNascimento, obs, sexo, idEstado, imagem) values ( '".$nome."', '".$endereco."', '".$cep."', '".$bairro."', '".$telefone."', '".$celular."', '".$email."', '".$dtNascimentoAmericano."', '".$observacao."', '".$sexo."', ".$idEstado.", '".$foto."' )"; # echo($sql); exit; # EXECUTANDO O INSERT NO BANCO DE DADOS if (mysqli_query($conex, $sql)) { echo(" <script> alert('registro inserido com sucesso'); location.href = '../index.php'; </script>"); } else { echo("<script> alert('erro ao salvar '); location.href = '../index.php'; window.history.back(); </script>"); } } } } # window.history.back() permite voltar a pagina anterior sem perder os dados do formulario ?><file_sep>/aula12-1upload-ajax/BD/deleteContato.php <?php # VERIFICA SE A VARIAVEL MODO EXISTE if(isset($_GET['modo'])){ # VERIFICA SE O CONTEUDO DA VARIAVEL É PARA EXCLUIR if($_GET['modo'] == 'excluir') { # inserindo o arquivo de conexao que esta dentro da pasta BD (referente ao banco de dados); include_once('conexao.php'); # recebe a funcao de conexao do bd $conex = conexaoMysql(); # VERIFICA SE O ID FOI ENVIADO PELO GET PARA CHAMAR O RESTANTE DO CODIGO if(isset($_GET['id'])){ # RECEBENDO O ID $id = $_GET['id']; # SCRIPT DELET A VARIAVEL ID RESGATA O ID DO CONTATO $sql = "delete from tblcontatos where idContato = " .$id; # MANDANDO AS INFORMAÇÕES PARA O BANCO if (mysqli_query($conex, $sql)){ # apaga um arquivo unlink('arquivos/'.$_GET['imagem']); # REDIRECIONA PARA A PAGINA INICIAL QUANDO UM DADO FOR DELETADO header('location:../index.php'); } } } } ?><file_sep>/aula12-1upload-ajax/BD/upload.php <?php #echo('teste'); exit; # valida se o campo da imagem é um arquivo valido e esta com as propriedades corretas if($_FILES['fleFoto'] > 0 && $_FILES['fleFoto']['type'] != "" ){ # nome da pasta para os arquivos upados $diretorioArquivo = "arquivos/"; # variavel que possui o tamanho da imagem convertendo o tamanho para KB $arquivoSize = round($_FILES['fleFoto']['size']/1024); #extensôes que serao permitidas no arquivo de imagem $arquivoPermitido = array("image/jpeg", "image/jpg", "image/png", "image/gif"); # guardando o tipo de arquivo $arquivoType = $_FILES['fleFoto']['type']; # variavel que possui a imagem $arquivo = $_FILES['fleFoto']; # valida se a extensao do arquivo é permitida no upload if(in_array($arquivoType, $arquivoPermitido)){ # valida o tamanho do arquivo if($arquivoSize <= 2000){ #resgata o nome do arquivo e separa ele da extensao $nomeArquivo = pathinfo($_FILES['fleFoto']['name'], PATHINFO_FILENAME); # resgatando a extensao do nome do arquivo $extensaoArquivo = pathinfo($_FILES['fleFoto']['name'], PATHINFO_EXTENSION); # gerando um nome de arquivo unico para que não ocorra substituicao de imagem sem intençao $nomeArquivocrypt = md5($nomeArquivo) . uniqid(time()); # concatenando o nome e a extensão da imagem $foto = $nomeArquivocrypt.".".$extensaoArquivo; # pasta temporario que o form disponibiliza para o servidor para que o arquivo seja upado para o servidor $arquivoTempo = $_FILES['fleFoto']['tmp_name']; # move a imagem de uma pasta e coloca em outra if(move_uploaded_file($arquivoTempo, $diretorioArquivo.$foto)){ # variavel de sessao é uma variavel que só finaliza quando o google for fechado # elimina a variavel de sessao # session_destroy(); # ativando uma variavel de sessao session_start(); # guarda o nome da foto que foi enviada para o servidor $_SESSION['nomeFoto'] = $foto; # exibe a imagem no campo indicado echo("<img src='BD/arquivos/".$foto."'>"); # SCRIPTS PARA ENVIAR OS DADOS AO BD } } else{ echo('funcionnnnaaa '); } } } ?><file_sep>/aula12-1 MVC/Controller/contatosController.php <?php ########################## LEMBRETE ######################################### # Nome da classe :' ContatoController() # Objetivo : Criar toda a regra de negiocio para o sistema( ela inermedia # entre a view e a model ) # Data da criaçao: 13/07/2020 # Autor: <NAME> # # Data da modificação : # Autor da modificação : # Conteudos Modificados : # # ############################################################################# class ContatoController{ # construtor da classe public function __construct() { } # inserir um novo contato public function inserirContato(){ # valida qual metodo de requisicao estara chegando no HTTP (POST, GET) if($_SERVER['REQUEST_METHOD'] == "POST"){ # resgatando os dados do formulario $nome = $_POST['txtNome']; $endereco = $_POST['txtEndereco']; $cep = $_POST['txtCep']; $bairro = $_POST['txtBairro']; $telefone = $_POST['txtTelefone']; $celular = $_POST['txtCelular']; $email = $_POST['txtEmail']; $dataNascimento = explode("/", $_POST['txtNascimento']); $dtNascimentoAmericano = $dataNascimento[2]."-".$dataNascimento[1]."-".$dataNascimento[0]; $observacao = $_POST['txtObs']; $sexo = $_POST['rdoSexo']; # $idEstado = $_POST['sltEstados']; require_once('model/contatoClass.php'); $contato = new Contato(); $contato->setNome($nome); $contato->setEndereco($endereco); $contato->setCep($cep); $contato->setBairro($bairro); $contato->setTelefone($telefone); $contato->setCelular($celular); $contato->setEmail($email); $contato->setDataNascimento($dtNascimentoAmericano); $contato->setObs($observacao); $contato->setSexo($sexo); $contato->setIdContato(1); require_once('model/DAO/contatoDAO.php'); $contatoDAO = new ContatoDAO; $contatoDAO->insertContato($contato); }; } # atualizar um novo contato public function atualizarContato(){} # deletar um novo contato public function deletarContato(){} # listar um novo contato public function listarContato(){} # buscar um novo contato public function buscarContato(){} # lisa contato em JSON public function listarContatoJson(){} } ?><file_sep>/aula12-1/BD/insertContato2.php <?php # veridica se a variavel modo exite use function PHPSTORM_META\type; if (isset($_GET['modo'])) { # verifica que o conteudo do modo é inserir if ($_GET['modo'] == 'inserir') { # CONEXAO COM O BANCO DE DADOS require_once('conexao.php'); # recebe a funcao de conexao do bd $conex = conexaoMysql(); #VERIFICANDO SE O BOTAO FOI SUBMETIDO if (isset($_POST['btnEnviar'])) { # RECEBENDO OS DADOS FORNECIDOS PELO USUARIO $nome = $_POST['txtNome']; $endereco = $_POST['txtEndereco']; $cep = $_POST['txtCep']; $bairro = $_POST['txtBairro']; $telefone = $_POST['txtTelefone']; $celular = $_POST['txtCelular']; $email = $_POST['txtEmail']; #CONVERSAO DA DATA PARA O PADRAO AMERICANO PARA ENVIAR AO BANCO $dataNascimento = explode("/", $_POST['txtNascimento']); $dtNascimentoAmericano = $dataNascimento[2]."-".$dataNascimento[1]."-".$dataNascimento[0]; $observacao = $_POST['txtObs']; $sexo = $_POST['rdoSexo']; $idEstado = $_POST['sltEstados']; # SCRIPT QUE RESGATA UMA IMAGEM ENVIADA PELO FORM # valida se o campo da imagem é um arquivo valido e esta com as propriedades corretas if($_FILES['fleFoto'] > 0 && $_FILES['fleFoto']['type'] != "" ){ # nome da pasta para os arquivos upados $diretorioArquivo = "arquivos/"; # variavel que possui o tamanho da imagem convertendo o tamanho para KB $arquivoSize = round($_FILES['fleFoto']['size']/1024); #extensôes que serao permitidas no arquivo de imagem $arquivoPermitido = array("image/jpeg", "image/jpg", "image/png", "image/gif"); # guardando o tipo de arquivo $arquivoType = $_FILES['fleFoto']['type']; # variavel que possui a imagem $arquivo = $_FILES['fleFoto']; # valida se a extensao do arquivo é permitida no upload if(in_array($arquivoType, $arquivoPermitido)){ # valida o tamanho do arquivo if($arquivoSize <= 2000){ #resgata o nome do arquivo e separa ele da extensao $nomeArquivo = pathinfo($_FILES['fleFoto']['name'], PATHINFO_FILENAME); # resgatando a extensao do nome do arquivo $extensaoArquivo = pathinfo($_FILES['fleFoto']['name'], PATHINFO_EXTENSION); # gerando um nome de arquivo unico para que não ocorra substituicao de imagem sem intençao $nomeArquivocrypt = md5($nomeArquivo) . uniqid(time()); # concatenando o nome e a extensão da imagem $foto = $nomeArquivocrypt.".".$extensaoArquivo; # pasta temporario que o form disponibiliza para o servidor para que o arquivo seja upado para o servidor $arquivoTempo = $_FILES['fleFoto']['tmp_name']; # move a imagem de uma pasta e coloca em outra if(move_uploaded_file($arquivoTempo, $diretorioArquivo.$foto)){ # SCRIPTS PARA ENVIAR OS DADOS AO BD $sql = "insert into tblContatos (nome, endereco, cep, bairro, telefone, celular, email, dtNascimento, obs, sexo, idEstado, imagem) values ( '".$nome."', '".$endereco."', '".$cep."', '".$bairro."', '".$telefone."', '".$celular."', '".$email."', '".$dtNascimentoAmericano."', '".$observacao."', '".$sexo."', ".$idEstado.", '".$foto."' )"; #echo($sql); exit; # EXECUTANDO O INSERT NO BANCO DE DADOS if (mysqli_query($conex, $sql)) { echo(" <script> alert('registro inserido com sucesso'); location.href = '../index.php'; </script>"); } else { echo("<script> alert('erro ao salvar '); location.href = '../index.php'; window.history.back(); </script>"); } } } } } else{ echo('erro ao mover o arquivo para o servidor'); } } else{ echo('tamanho maior que 2MB!'); } } else { echo('Extensao de arquivo não permitido pelo sistema'); } } else { echo('arquivo invalido na escolha da imagem'); } # window.history.back() permite voltar a pagina anterior sem perder os dados do formulario ?> <file_sep>/aula12-1 MVC/Model/DAO/conexaoPDO.php <?php ########################## LEMBRETE ######################################### # Nome da classe :' mysqlConection # # Objetivo : Criar conexao com banco de dados Mysql # # Data da criaçao: 06/07/2020 # # Autor: <NAME> # # Data da modificação : # Autor da modificação : # Conteudos Modificados : # # ############################################################################# # classe para conexao com banco mysql class mysqlConection { private $server; private $user; private $password; private $database; # metodo construtor php para instanciar os atributos da classe mae (acima) public function __construct(){ $this->server = "localhost"; $this->user = "root"; $this->password = "<PASSWORD>"; $this->database = "dbcontatos20201a"; } # metodo para abrir a conexao com banco de dados public function connectDatabase(){ try{ # estabelecendo a conexao com o banco $conexao = new PDO('mysql:host='.$this->server.';dbname='.$this->database, $this->user,$this->password); # retorna a conexao com banco return $conexao; } catch(PDOException $erro){ echo('Erro ao abrir a conexao com banco De Dados <br> linha '.$erro->getLine(). "<br> Mensagem de erro".$erro->getMessage()); } } # encerra a conexao para que ela não fique aberta de forma desnecessaria public function closeDatabase(){ $conexao = null; } } ?><file_sep>/aula12-1upload-ajax/BD/upDateContato.php <?php # veridica se a variavel modo exite if (isset($_GET['modo'])) { # verifica que o conteudo do modo é inserir if ($_GET['modo'] == 'atualizar') { # CONEXAO COM O BANCO DE DADOS require_once('conexao.php'); # recebe a funcao de conexao do bd $conex = conexaoMysql(); # essa variavel foi enviada pelo for da pagina index que é o a (PK) do registro a ser atualizado #VERIFICANDO SE O BOTAO FOI SUBMETIDO if (isset($_POST['btnEnviar'])) { $id = $_GET['id']; # RECEBENDO OS DADOS FORNECIDOS PELO USUARIO $nome = $_POST['txtNome']; $endereco = $_POST['txtEndereco']; $cep = $_POST['txtCep']; $bairro = $_POST['txtBairro']; $telefone = $_POST['txtTelefone']; $celular = $_POST['txtCelular']; $email = $_POST['txtEmail']; #CONVERSAO DA DATA PARA O PADRAO AMERICANO PARA ENVIAR AO BANCO $dataNascimento = explode("/", $_POST['txtNascimento']); $dtNascimentoAmericano = $dataNascimento[2]."-".$dataNascimento[1]."-".$dataNascimento[0]; $observacao = $_POST['txtObs']; $sexo = $_POST['rdoSexo']; $idEstado = $_POST['sltEstados']; # SCRIPTS PARA ENVIAR A ATUALIZACAO DOS DADOS AO BD $sql = "update tblContatos set nome = '".$nome."', endereco = '".$endereco."', cep = '".$cep."', bairro = '".$bairro."', telefone = '".$telefone."', celular = '".$celular."', email = '".$email."', dtNascimento = '".$dtNascimentoAmericano."', obs = '".$observacao."', sexo = '".$sexo."', idEstado = ".$idEstado." where idContato = " . $id; #echo($sql); exit; # EXECUTANDO O UPDATE NO BANCO DE DADOS if (mysqli_query($conex, $sql)) { echo(" <script> alert('registro inserido com sucesso'); location.href = '../index.php'; </script>"); } else { echo("<script> alert('erro ao salvar '); location.href = '../index.php'; window.history.back(); </script>"); } } } } # window.history.back() permite voltar a pagina anterior sem perder os dados do formulario ?> <file_sep>/aula12-1upload-ajax/BD/conexao.php <?php # funcao de cria a conexao com BD function conexaoMysql(){ $server = 'localhost'; $user = 'root'; $password = '<PASSWORD>'; $dataBase = 'dbContatos20201A'; # conexao com o banco de dados $conexao = mysqli_connect($server, $user, $password, $dataBase); # retorna todas as informações de conexao com o banco de dados # var_dump($conexao); return $conexao; } ?> <file_sep>/aula12-1 MVC/Model/DAO/contatoDAO.php <?php ########################## LEMBRETE ######################################### # Nome da classe :' ContatoDAO # # Objetivo : Manipular dados com o BD MSQL referente a contatos # # Data da criaçao: 06/07/2020 # # Autor: <NAME> # # Data da modificação : # Autor da modificação : # Conteudos Modificados : # # ############################################################################# class ContatoDAO{ # metodo construtor da classe public function __construct(){ } # metodo de insert na pagina de contato public function insertContato(Contato $contato){ $sql = "insert into tblContatos (nome, endereco, cep, bairro, telefone, celular, email, dtNascimento, obs, sexo, idEstado) values ( '".$contato->getNome()."', '".$contato->getEndereco()."', '".$contato->getCep()."', '".$contato->getBairro()."', '".$contato->getTelefone()."', '".$contato->getCelular()."', '".$contato->getEmail()."', '".$contato->getDataNascimento()."', '".$contato->getObs()."', '".$contato->getSexo()."', ".$contato->getIdEstado().")"; } # metodo update na pagina de contato public function updateContato(){ } # metodo para deletar um contato public function deletContato(){ } public function selectAllContato(){ } public function selectByIdContato(){ } } ?><file_sep>/aula12-1 MVC/router.php <?php # variveis que serao encaminhadas pela view # valiavel que identifica qual controller sera instanciada $controller = null; # identifica a acao do controller (inserir, excluir, atualizar) $model = null; # valida se a controller esta chegando pelo get if(isset($_GET['controller'])){ # recebe oque chegar na controller $controller = strtoupper($_GET['controller']); switch ($controller){ case 'CONTATOS' : # verifica se modo existe if(isset($_GET['modo'])){ # recebe o modo que foi enviado pela view $modo = strtoupper($_GET['modo']); # import do arquivo controler require_once('controller/contatosController.php'); $contatoController = new ContatoController(); switch($modo){ case 'INSERIR': echo('modo INSERIR'); # chama o metodo para inserir contato $contatoController->inserirContato(); break; case 'EDITAR': # chama o metodo para editar um contato $contatoController->atualizarContato(); break; case 'EXCLUIR': # chama o metodo para excluir o contato $contatoController->deletarContato(); break; } } break; } } ?><file_sep>/aula12-1upload-ajax/index.php <?php # inicializa a variavel para não possua erro $idEstado = 0; # inserindo o arquivo de conexao que esta dentro da pasta BD (referente ao banco de dados); include_once('BD/conexao.php'); # recebe a funcao de conexao do bd $conex = conexaoMysql(); #verificando se a conexao foi estabelecida (esse metodo retorna inroformacoes da conexao) # var_dump($conex); # inicializa as variaveis para não dar erro ao inicializar a tela com erro $nome = null; $endereco = null; $cep = null; $bairro = null; $telefone = null; $celular = null; $email = null; $dataNascimentoPadraoBR = null; $observacao = null; $sexo = null; # variavel para ser colocado no action do form $action = 'BD/insertContato.php?modo=inserir'; # verifica se a variavel (ela foi enviada no click do editar, na listagem dos dados) if(isset($_GET['modo'])){ # valida se a acao de modo é para buscar um registro no BD // $sql = "select * from tblContatos where idContato = ".$id if($_GET['modo'] == 'consultaEditar'){ # verifica se foi clicado no (botao) de editar if(isset($_GET['id'])){ # recebe o id enviado pela url $id = $_GET['id']; # lista as informacoes do banco $sql = "SELECT tblcontatos.*, tblcontatos.nome as nomeContato, tblcontatos.email, tblestados.sigla, tblestados.nome as nomeEstado FROM tblcontatos, tblestados where tblestados.idEstado = tblcontatos.idEstado and tblContatos.idContato = ".$id; $selectDados = mysqli_query($conex, $sql); if($rsListContatos = mysqli_fetch_assoc($selectDados)){ $id = $rsListContatos['idContato']; $nome = $rsListContatos['nome']; $endereco = $rsListContatos['endereco']; $cep = $rsListContatos['cep']; $bairro = $rsListContatos['bairro']; $telefone = $rsListContatos['telefone']; $celular = $rsListContatos['celular']; $email = $rsListContatos['email']; $dataNascimento = explode("-", $rsListContatos['dtNascimento']); $dataNascimentoPadraoBR = $dataNascimento[2]."/".$dataNascimento[1]."/".$dataNascimento[0]; $observacao = $rsListContatos['obs']; $sexo = strtoupper( $rsListContatos['sexo']); $idEstado = $rsListContatos['idEstado']; $nomeEstado = $rsListContatos['nomeEstado']; # acao que envia o form para a pagina update e enviamos o id para la tambem $action = "BD/upDateContato.php?modo=atualizar&id=".$rsListContatos['idContato']; } } } } ?> <!DOCTYPE> <html lang="pt-br"> <head> <meta charset="UTF-8"> <title> Cadastro </title> <link rel="stylesheet" type="text/css" href="style/style.css"> <script src="scripts/jquery.js"></script> <script src="scripts/jquery.form.js"></script> <script> // ativa as funcoes js após o carregamento do html $(document).ready(function(){ $('.pesquisar').click(function(){ $('#modal').fadeIn(1000); }); // fucao para upload de arquivo, visualizar antes que ela seja enviada ao banco $('#foto').live('change', function(){ // alert('heebhb'); $('#frmfoto').ajaxForm({ target: '#imagem' }).submit(); }); }); // funcao que abre um arquivo dentro da modal function visualizarContato(idContato){ // biblioteca que permite trabalhar com formulario $.ajax({ // chamada via post type: "POST", // chama a pagina que foi criada os elementos da modal url: "BD/visualizarContato.php", // variaveis que servirao enviadas a outra tela data: {modo: "visualizar", id: idContato}, // se o resultado for de sucesso cria uma funcao que serve para retorno success: function (dados){ // implementa a funcao no html $('#modalConteudo').html(dados); } }); } </script> </head> <body> <div id="modal" > <div id="modalConteudo"></div> </div> <div id="cadastro"> <div id="cadastroTitulo"> <h1> Cadastro de Contatos </h1> </div> <div id="cadastroInformacoes"> <form action="<?=$action?>" name="frmCadastro" method="post" enctype="multipart/form-data"> <div class="campos"> <div class="cadastroInformacoesPessoais"> <p> Nome: </p> </div> <div class="cadastroEntradaDeDados"> <input type="text" name="txtNome" value="<?=$nome?>"> </div> </div> <div class="campos"> <div class="cadastroInformacoesPessoais"> <p> Cep: </p> </div> <div class="cadastroEntradaDeDados"> <input type="text" name="txtCep" value="<?=$cep?>" id="cep" placeholder="Insira apenas numeros" required> </div> </div> <div class="campos"> <div class="cadastroInformacoesPessoais"> <p> Endereço: </p> </div> <div class="cadastroEntradaDeDados"> <input type="text" name="txtEndereco" value="<?=$endereco?>" id="endereco"> </div> </div> <div class="campos"> <div class="cadastroInformacoesPessoais"> <p> Bairro: </p> </div> <div class="cadastroEntradaDeDados"> <input type="text" name="txtBairro" value="<?=$bairro?>" id="bairro"> </div> </div> <div class="campos"> <div class="cadastroInformacoesPessoais"> <p> Estados: </p> </div> <div class="cadastroEntradaDeDados"> <select name="sltEstados"> <?php if(isset($_GET['modo'])){ if ($_GET['modo'] == 'consultaEditar'){ ?> <option value="<?=$idEstado?>" selected> <?=$nomeEstado?> </option> <?php } } else{ ?> <option value="Item"> Selecione um Item</option> <?php } #variavel que lista as informações do BD o where indica que não ha repeticao $sql = "select * from tblEstados where idEstado <> ".$idEstado." order by nome"; echo($sql); # Executa o script da variavel no BD $selectEstados = mysqli_query($conex, $sql); # Estrutura de repeticao para carregar os estados while ($rsEstados = mysqli_fetch_assoc($selectEstados)) { ?> <option value="<?php echo($rsEstados['idEstado'])?>"><?php echo($rsEstados['nome'])?></option> <!-- Também pode ser descrita dessa segunda forma --> <!-- <option value=" <?= ($rsEstados['idEstado'])?>"><?= ($rsEstados['nome'])?></option> --> <?php } ?> </select> </div> </div> <div class="campos"> <div class="cadastroInformacoesPessoais"> <p> Telefone: </p> </div> <div class="cadastroEntradaDeDados"> <input type="text" name="txtTelefone" value="<?=$telefone?>"> </div> </div> <div class="campos"> <div class="cadastroInformacoesPessoais"> <p> Celular: </p> </div> <div class="cadastroEntradaDeDados"> <input type="text" name="txtCelular" value="<?=$celular?>"> </div> </div> <div class="campos"> <div class="cadastroInformacoesPessoais"> <p> Email: </p> </div> <div class="cadastroEntradaDeDados"> <input type="email" name="txtEmail" value="<?=$email?>"> </div> </div> <div class="campos"> <div class="cadastroInformacoesPessoais"> <p> Data de Nascimento: </p> </div> <div class="cadastroEntradaDeDados"> <input type="text" name="txtNascimento" value="<?=$dataNascimentoPadraoBR?>"> </div> </div> <div class="campos"> <div class="cadastroInformacoesPessoais"> <p> Sexo: </p> </div> <div class="cadastroEntradaDeDados"> <input type="radio" name="rdoSexo" value="F" <?php if($sexo == 'F') echo('checked') ?>> Feminino. <input type="radio" name="rdoSexo" value="M" <?php echo $sexo == 'M' ? 'checked' : '' ?>> Masculino. <input type="radio" name="rdoSexo" value="O"> Outros. </div> </div> <div class="campos"> <div class="cadastroInformacoesPessoais"> <p> Observações: </p> </div> <div class="cadastroEntradaDeDados"> <textarea name="txtObs" cols="50" rows="7" ><?=$observacao?></textarea> </div> </div> <div class="campos"> <!-- formulario para upload da imagem com jquery --> </div> <div class="enviar"> <div class="enviar"> <input type="submit" name="btnEnviar" value="Salvar"> </div> </div> </form> <form name="frmfoto" id="frmfoto" method="post" action="BD/upload.php" enctype="multipart/form-data"> <div class="cadastroInformacoesPessoais"> <p> Imagem </p> </div> <div class="cadastroEntradaDeDados"> <input type="file" name="fleFoto" value="" accept="image/jpeg, image/png" id="foto"> </div> <div id="imagem"> </div> </form> </div> </div> <div id="consultaDeDados"> <table id="tblConsulta" > <tr> <td id="tblTitulo" colspan="6"> <h1> Consulta de Dados.</h1> </td> </tr> <tr id="tblLinhas"> <td class="tblColunas"> Nome </td> <td class="tblColunas"> Celular </td> <td class="tblColunas"> Estado </td> <td class="tblColunas"> Email </td> <td class="tblColunas"> foto </td> <td class="tblColunas"> Opções </td> </tr> <?php # SCRIPT QUE SELECIONA OS DADOS NO BANCO $sql = "SELECT tblcontatos.idContato, tblcontatos.nome as nomeContato, tblcontatos.celular, tblcontatos.email, tblestados.sigla, tblestados.nome as nomeEstado, tblcontatos.imagem FROM tblcontatos, tblestados where tblestados.idEstado = tblcontatos.idEstado order by tblcontatos.idContato desc"; # ENVIA O SCRIPT PARA O BANCO DE DADOS $selectContato = mysqli_query($conex, $sql); # ESTRUTURA DE REPETICAO QUE LISTA OS CONTATOS NA LISTA # MYSQLI_FETCH_ASSOC TRANSFORMA O RESULTADO EM UM ARRAY LIST while ($rsContatos = mysqli_fetch_assoc($selectContato)){ ?> <tr id="tblLinhas"> <td class="tblColunas"><?=$rsContatos['nomeContato']?></td> <td class="tblColunas"><?=$rsContatos['celular']?></td> <td class="tblColunas"><?=$rsContatos['sigla'] ." - ". $rsContatos['nomeEstado']?></td> <td class="tblColunas"><?=$rsContatos['email']?></td> <td class="tblColunas"> <img src="BD/arquivos/<?=$rsContatos['imagem']?>" class="imagembd"> </td> <td class="tblColunas"> <div class="tblImagens"> <a onclick="return confirm('Deseja realmente excluir o registro?')" href="BD/deleteContato.php?modo=excluir&id=<?=$rsContatos['idContato']?>&imagem=<?=$rsContatos['imagem']?>"> <div class="fechar"></div> </a> <div class="pesquisar" onclick="visualizarContato(<?=$rsContatos['idContato']?>);"></div> <a href="index.php?modo=consultaEditar&id=<?=$rsContatos['idContato']?>"> <div class="editar"></div> </a> </div> </td> </tr> <?php } ?> </table> </div> <script src="scripts/script.js" ></script> </body> </html><file_sep>/aula12-1upload-ajax/BD/SqlContatos.sql #Criacao do Database Contatos create database dbContatos20201A; #Ativa o Database a ser Utilizado use dbContatos20201A; #cria a tabela de estados create table tblEstados( idEstado int auto_increment not null primary key, sigla varchar(2) not null, nome varchar(100) not null ); #Cria a Tabela de Contatos create table tblContatos( idContato int auto_increment not null, nome varchar(100) not null, endereco varchar(150) not null, bairro varchar (50) not null, cep varchar (100) not null, idEstado int not null, telefone varchar (15) not null, celular varchar(16) not null, email varchar(50) not null, dtNascimento date not null , sexo varchar (1) not null, obs text not null, primary key(idContato), constraint FK_estados_contatos foreign key (idEstado) references tblEstados(idEstado) ); #Lista as tabelas show tables; # Permite visualizar a estrutura da tabela desc tblContatos; # Informações cadastradas pelo usuario select tblEstados.* from tblEstados; # Inserindo dados na tabela insert into tblEstados (sigla, nome) values ('SP', 'São Paulo'); select tblEstados.sigla, tblEstados.nome from tblEstados; insert into tblEstados (sigla, nome) values ('RJ', 'Rio de Janeiro'); select * from tblEstados; # Para deletar dados delete from tblEstados where idEstado = 2; # Para atualizar um registro na tabela update tblEstados set nome = 'SÃO PAULO', sigla = 'SP' where idEstado = 1; ALTER USER 'root'@'localhost'identified with mysql_native_password BY'<PASSWORD>';
2dba2b1f13b3013d7646f76cb3b8fda27b5da407
[ "SQL", "PHP" ]
15
PHP
santosdiiih/Aulas-Php
ba3b5c8133d6db3a90d10a82dfcaf9a2fe03bfee
7fa6b36b83e4c60947f3725e494738a962cee058
refs/heads/master
<file_sep>from django.conf.urls import url from . import views urlpatterns = [ url(r'^(?P<destinationID>\d+)', views.destination), ]<file_sep> # Travel A trip planning application with share feature among registered users. Implemented and deployed in under 4 hours for Coding Dojo Black Belt exam <file_sep>from django.shortcuts import render, redirect from models import Trip from django.contrib import messages from ..users_app.models import User # Create your views here. def travels(request): # not sure if request.session will work here user = User.objects.get(id = request.session['user_id']) trips = Trip.objects.filter(planned_by = user) | Trip.objects.filter(joined_by = user) other_trips = Trip.objects.exclude(planned_by = user).exclude(joined_by = user) context = { 'trips': trips, 'other_trips': other_trips } return render(request, 'trips_app/travels.html', context) def add(request): return render(request, 'trips_app/add.html') def process(request): add_result = Trip.objects.addTrip(request.POST) if add_result['valid']: return redirect('travels:travels') else: for error in add_result['errors']: messages.error(request, error) return redirect('travels:add') def join(request): result = Trip.objects.joinTrip(request.POST) if result: return redirect("travels:travels")<file_sep><!DOCTYPE html> <html lang="en"> <head> <title>{{trip.destination}}</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="header"> <a href="{% url 'travels:travels' %}">Home</a> <a href="{% url 'users:logout' %}" class='pull-right'>Logout</a> </div> <div class="container"> <h1>{{trip.destination}}</h1> <p>Planned by: {{trip.planned_by.name}}</p> <p>Description: {{trip.description}}</p> <p>Travel Date From: {{trip.from_date}}</p> <p>Travel Date To: {{trip.to_date}}</p> <h1>Other Users' joining this trip:</h1> {% for user in trip.joined_by.all %} <h3>{{ user.name }}</h3> {% endfor %} </div> </body> </html><file_sep>from django.shortcuts import render from ..trips_app.models import Trip # Create your views here. def destination(request, destinationID): # display destination data and users print int(destinationID) print "type of destination url param" trip = Trip.objects.get(id = destinationID) print trip.destination context = { 'trip': trip, } return render(request, 'destinations_app/destination.html', context)<file_sep>from __future__ import unicode_literals from ..users_app.models import User from django.db import models import datetime class TripManager(models.Manager): def addTrip(self, postData): data = { 'valid': False, 'errors': [], } if not postData: data['errors'].append('post data only!') return data # no empty entries print "*"*50 print "types..." print type(postData['to_date']) if len(postData['destination']) < 1: data['errors'].append('destination cannot be empty') if len(postData['description']) < 1: data['errors'].append('description cannot be empty') if postData['to_date'] == "": data['errors'].append('dates cannot be empty') return data if len(postData['from_date']) < 1: data['errors'].append('dates cannot be empty') return data start_date = datetime.datetime.strptime(postData['from_date'], '%Y-%m-%d') end_date = datetime.datetime.strptime(postData['to_date'], '%Y-%m-%d') if not isinstance(start_date, datetime.date): data['errors'].append('invalid start date') if not isinstance(end_date, datetime.date): data['errors'].append('invalid end') # future travel dates today = datetime.datetime.now() if start_date < today: data['errors'].append('start date must be in the future') if end_date < today: data['errors'].append('end date must be in the future') if end_date < start_date: data['errors'].append('end date must be after start date') # to must be after from if data['errors']: return data else: data['valid'] = True user = User.objects.get(id = postData['user_id']) newTrip = Trip.objects.create(destination = postData['destination'], description = postData['description'], from_date = postData['from_date'], to_date = postData['to_date'], planned_by = user) print newTrip.id, newTrip.destination, newTrip.planned_by.username return data def joinTrip(self, postData): if not postData: return False user = User.objects.get(id = postData['user_id']) trip = Trip.objects.get(id = postData['trip_id']) trip.joined_by.add(user) return True class Trip(models.Model): destination = models.CharField(max_length=100) description = models.TextField() from_date = models.DateField() to_date = models.DateField() planned_by = models.ForeignKey(User, related_name='trips_planned') joined_by = models.ManyToManyField(User, related_name='trips_joined') created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) objects = TripManager()<file_sep>from django.conf.urls import url from . import views urlpatterns = [ # displays users trips and other's trips url(r'^$', views.travels, name='travels'), # page with add trip form on it url(r'^add$', views.add, name='add'), url(r'^join$', views.join, name='join'), # route to handle form data from add page url(r'^process$', views.process, name='process'), ]
d1a8d250cf6e3e61f90b5d122e389d8488a9ff8c
[ "Markdown", "Python", "HTML" ]
7
Python
dusty-g/Travel
5ca6061884e7630a0b0365adfa640da3ce1a6c37
89501d156a3ea86f4478f7bb41e1f968c7087bd3
refs/heads/master
<file_sep>import "./App.css"; import BoxList from "./BoxList"; import React, { Component } from "react"; // this component should render the BoxList component class App extends Component { render() { return ( <div className="App"> <h1>Color Box Maker</h1> <BoxList /> </div> ); } } export default App;<file_sep>import React, { Component } from "react"; import { Cancel as X } from "@styled-icons/material-rounded/Cancel"; import "./Box.css"; class Box extends Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick() { this.props.deleteBox(this.props.id); } render() { return ( <div className="Box" style={{ width: `${this.props.width}px`, height: `${this.props.height}px`, backgroundColor: `${this.props.backgroundColor}`, }} > <button onClick={this.handleClick}>x</button> </div> ); } } export default Box;
d62cf29e8ca0f30e00220534171441b990fb28a6
[ "JavaScript" ]
2
JavaScript
scotlin1293/React-Color-Box
23395076c09da0a8148355a6f90af27e049376a7
8f1fe9bb493a490c611e0585589f58d8b5fb82a4
refs/heads/master
<file_sep>APG = 'legend'
40f99c76bbdeb7dc18d1ea62c04bd33d46f78449
[ "Python" ]
1
Python
DeviThangavelu/Python
1d726351a6801ff555ac5982db8746da66319351
a44786e6ddd072ece5f5a0d48967a4df24947124
refs/heads/master
<repo_name>dineshsrivasthav/Live-cricket-score<file_sep>/cric.py import time import requests from bs4 import BeautifulSoup import win10toast def LiveScore(showNotification): toast = win10toast.ToastNotifier() url = "http://mapps.cricbuzz.com/cbzios/match/livematches" response = requests.get(url) matchData = response.json() inprogress = [] completed = [] preview = [] inningsbreak = [] matches = matchData["matches"] msg = str(len(matches)) + " cricket matches are being played." if(showNotification): toast.show_toast("Live Score", msg) def categorizeMatches(): for match in matches: if(match["header"]["state"] == "inprogress"): inprogress.append(match) elif(match["header"]["state"] == "innings break" or match["header"]["state"] == "tea" or match["header"]["state"] == "stump" or match["header"]["state"] == "lunch"): inningsbreak.append(match) elif(match["header"]["state"] == "complete" or match["header"]["state"] == "mom"): completed.append(match) else: preview.append(match) def displayMatchData(matches): if(len(matches) != 0): for match in matches: match_status = match["header"]["status"] team1 = match["team1"] team2 = match["team2"] team1_name = team1["name"] team2_name = team2["name"] team1_id = team1["id"] # team2_id = team2["id"] series_name = match["series_name"] match_type = match["header"]["type"] msg = series_name+"\n"+team1_name+" VS " + \ team2_name+"\n"+match_type+"\n"+match_status print(msg) batting_team = match["bat_team"] bowling_team = match["bow_team"] if(batting_team["id"] == team1_id): batting_team_name = team1_name bowling_team_name = team2_name else: batting_team_name = team2_name bowling_team_name = team1_name print("Batting :"+str(batting_team_name) + str(batting_team)) print("Bowling :"+str(bowling_team_name)+str(bowling_team)) print("-------------------------------------") if(showNotification): toast.show_toast("Live Score", msg) categorizeMatches() print("++++++++++++++++++INPROGRESS++++++++++++++++++") displayMatchData(inprogress) print("++++++++++++++++++COMPLETED++++++++++++++++++") displayMatchData(completed) print("++++++++++++++++++INNINGS-BREAK++++++++++++++++++") displayMatchData(inningsbreak) #print("++++++++++++++++++PREVIEW++++++++++++++++++") #displayMatchData(preview) for match in matches: if(match["header"]["state"] != "preview"): team1 = match["team1"]["name"] team2 = match["team2"]["name"] series_name = match["series_name"] match_type = match["header"]["type"] msg = series_name+"\n"+team1+" VS "+team2+"\n"+match_type print(msg) batting_team = match["bat_team"] bowling_team = match["bow_team"] print(str(batting_team)) print(str(bowling_team)) print("-------------------------------------") if(showNotification): toast.show_toast("Live Score", msg) while True: LiveScore(showNotification=True) print("======================================\nNew Update\n======================================") LiveScore(showNotification=False)
e5ef62381519a5f5c432e1a28c88234b32a32f9c
[ "Python" ]
1
Python
dineshsrivasthav/Live-cricket-score
fa9cb20d28d4b0a888d1e1a740b6eba642b93013
0c97f2127a3a8d99a61a387e84615dd0fd3dbf26
refs/heads/master
<repo_name>dwilbank68/ReactReduxFrontendStarter<file_sep>/README.md ### Features jwt authentication built for backend at https://wilbanks-node-api.herokuapp.com/ npm run start state = { auth: { user: { email: STRING, id: STRING }, authenticated: BOOLEAN, error: STRING } } <file_sep>/src/components/header.jsx import React, {Component, PropTypes} from 'react'; import {connect} from 'react-redux'; import {Link} from 'react-router'; // import { bindActionCreators } from 'redux'; class Header extends Component { // constructor(props){ // super(props); // this.state = { // 'whatever':{} // } // this.handleClick = this.handleClick.bind(this) // } render() { return ( <nav className="navbar navbar-light"> <Link to="/" className="navbar-brand">Redux Auth</Link> <ul className="nav navbar-nav"> {this.renderLinks()} </ul> </nav> ); } renderLinks(){ if (this.props.authenticated) { return ( <li className="nav-item"> <Link to="/signout" className="nav-link">Sign Out</Link> </li> ) } else { return [ <li className="nav-item" key="signin"> <Link to="/signin" className="nav-link">Sign In</Link> </li>, <li className="nav-item" key="signup"> <Link to="/signup" className="nav-link">Sign Up</Link> </li> ] } } } Header.propTypes = {}; Header.defaultProps = {}; //function mapDispatchToProps(dispatch) { // return bindActionCreators( // { nameYouWantOnProps:nameOfImportedAction }, // dispatch // ); //} function mapStateToProps(state) { return {authenticated: state.auth.authenticated}; } export default connect(mapStateToProps)(Header); <file_sep>/src/components/feature.jsx import React, {Component, PropTypes} from 'react'; import {connect} from 'react-redux'; import * as actions from '../actions'; class Feature extends Component { componentWillMount() { this.props.fetchMessage(); } render() { return ( <div className="feature"> Here is your feature <p>{this.props.user.email}</p> <p>{this.props.user.id}</p> </div> ); } } Feature.propTypes = {}; Feature.defaultProps = {}; function mapStateToProps(state) { return { user: state.auth.user } } export default connect(mapStateToProps, actions)(Feature); <file_sep>/src/components/welcome.jsx import React, { PropTypes } from 'react'; const welcome = (props) => { return ( <div> Welcome View </div> ); }; welcome.propTypes = {}; welcome.defaultProps = {}; export default welcome; <file_sep>/src/components/auth/signout.jsx import React, { Component, PropTypes } from 'react'; import {connect} from 'react-redux'; import * as actions from '../../actions'; class Signout extends Component { // constructor(props){ // super(props); // this.handleFormSubmit = this.handleFormSubmit.bind(this) // } componentWillMount() { this.props.signoutUser(); // UNAUTH_USER } render() { return ( <div> Sorry to see you go </div> ); } } Signout.propTypes = {}; Signout.defaultProps = {}; export default connect( null, actions )(Signout); // remember to use 'this' binding now (choose one, #1 is best) // 1. In constructor (see constructor above) // 2. .bind(this) in your render ( onClick={this.onClick.bind(this)} ) // 3. Arrow functions in your render ( onClick={() => {}} ) // reducers/index.js // // import { reducer as formReducer} from 'redux-form'; // // const rootReducer = combineReducers({ // form: formReducer // });
f542c1f5d592a73b24972e7f8ffb4297e214ac98
[ "Markdown", "JavaScript" ]
5
Markdown
dwilbank68/ReactReduxFrontendStarter
4753413deedc3b423d9a9d50d17c6b4765f1bbfc
bb829a496d17fe9ce31693bcac2a95a55d644384
refs/heads/master
<repo_name>IT-CAMP3/2020.10.10-abstrakcja<file_sep>/src/Snake.java public class Snake extends Pet { @Override public void jedz() { System.out.println("Zaatakuj i zjedz i leż !!"); } } <file_sep>/src/Pet.java public abstract class Pet { int a = 5; public void go() { System.out.println("Idę !!"); } abstract public void jedz(); } <file_sep>/src/Fish.java public class Fish extends Pet { @Override public void jedz() { System.out.println("Zjedz glony i popływaj !!"); } }
b128efa7ddcd75bc4bf4204d2bca5d366432e06a
[ "Java" ]
3
Java
IT-CAMP3/2020.10.10-abstrakcja
377e85d3cb2454b436d8bbba126cdf505f0cd6f6
35e23d2fa907862b625014c4e5b139e153f3a335
refs/heads/master
<repo_name>bmokr/RPiDG<file_sep>/ServerScripts/setLeds.php <?php //if ($_SERVER["REQUEST_METHOD"] == "POST"){ $json = file_get_contents("php://input"); $data = json_decode($json); if(!empty($data)) { $arrSize = sizeof($data); for($i=0; $i < $arrSize; $i++) { $x = $data[$i]->x; $y = $data[$i]->y; $r = $data[$i]->r; $g = $data[$i]->g; $b = $data[$i]->b; $color = "-r$r -g$g -b$b"; exec("sudo ./zad3.py -x$y -y$x $color"); } } //} ?> <file_sep>/DesktopApp/rpiDataGrabber/rpiDataGrabber/rpiDataGrabber/dataTable.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using OxyPlot; using OxyPlot.Axes; using OxyPlot.WindowsForms; using OxyPlot.Series; using Newtonsoft.Json; using System.IO; using System.Timers; using Timer = System.Timers.Timer; namespace rpiDataGrabber { public partial class dataTable : UserControl { #region Fields private Timer RequestTimer; private IoTServer Server; const string filePath = @"C:\Users\Klient\Documents\GitHub\RPiDG\DesktopApp\rpiDataGrabber\rpiDataGrabber\config.json"; configData deserialized = JsonConvert.DeserializeObject<configData>(File.ReadAllText(filePath)); public string unitFlag = "basicUnits"; public double farenheit, mmhg, humi01; public double rRad, pRad, yRad; #endregion public dataTable() { InitializeComponent(); string ip = deserialized.ip.ToString(); string port = deserialized.port.ToString(); double maxSamples = deserialized.maxSamples; double sampleTime = deserialized.sampleTime; label10.Text = "[°C]"; label11.Text = "[hPa]"; label12.Text = "[%rH]"; label13.Text = "[DRG]"; label14.Text = "[DGR]"; label15.Text = "[DGR]"; Server = new IoTServer(ip, port); } #region Buttons //start private void button1_Click(object sender, EventArgs e) { if (RequestTimer == null) { double sampleTime = deserialized.sampleTime; RequestTimer = new Timer(sampleTime); RequestTimer.Elapsed += new ElapsedEventHandler(RequestTimerElapsed); RequestTimer.Enabled = true; } } //stop private void button2_Click(object sender, EventArgs e) { if (RequestTimer != null) { RequestTimer.Enabled = false; RequestTimer = null; } } //change unit to basic private void button3_Click(object sender, EventArgs e) { if (unitFlag == "otherUnits") { unitFlag = "basicUnits"; label10.Text = "[°C]"; label10.Refresh(); label11.Text = "[hPa]"; label11.Refresh(); label12.Text = "[%rH]"; label12.Refresh(); label13.Text = "[DRG]"; label13.Refresh(); label14.Text = "[DGR]"; label14.Refresh(); label15.Text = "[DGR]"; label15.Refresh(); } } //change unit to other private void button4_Click(object sender, EventArgs e) { if (unitFlag == "basicUnits") { unitFlag = "otherUnits"; label10.Text = "[°F]"; label10.Refresh(); label11.Text = "[mmHg]"; label11.Refresh(); label12.Text = "[0-1]"; label12.Refresh(); label13.Text = "[RAD]"; label13.Refresh(); label14.Text = "[RAD]"; label14.Refresh(); label15.Text = "[RAD]"; label15.Refresh(); } } #endregion #region Functions private void UpdateTable(string flag, ServerData resposneJson) { if (flag == "basicUnits") { label16.Text = resposneJson.temperature.ToString(); label16.Refresh(); label17.Text = resposneJson.pressure.ToString(); label17.Refresh(); label18.Text = resposneJson.humidity.ToString(); label18.Refresh(); label19.Text = resposneJson.roll.ToString(); label19.Refresh(); label20.Text = resposneJson.pitch.ToString(); label20.Refresh(); label21.Text = resposneJson.yaw.ToString(); label21.Refresh(); label22.Text = resposneJson.x.ToString(); label22.Refresh(); label23.Text = resposneJson.y.ToString(); label23.Refresh(); label24.Text = resposneJson.mid.ToString(); label24.Refresh(); } if (flag == "otherUnits") { farenheit = resposneJson.temperature * 1.8 + 32; label16.Text = farenheit.ToString(); label16.Refresh(); mmhg = resposneJson.pressure * 0.750062; label17.Text = mmhg.ToString(); label17.Refresh(); humi01 = resposneJson.humidity / 100; label18.Text = humi01.ToString(); label18.Refresh(); rRad = resposneJson.roll * Math.PI / 180; label19.Text = rRad.ToString(); label19.Refresh(); pRad = resposneJson.pitch * Math.PI / 180; label20.Text = pRad.ToString(); label20.Refresh(); yRad = resposneJson.yaw * Math.PI / 180; label21.Text = yRad.ToString(); label21.Refresh(); label22.Text = resposneJson.x.ToString(); label22.Refresh(); label23.Text = resposneJson.y.ToString(); label23.Refresh(); label24.Text = resposneJson.mid.ToString(); label24.Refresh(); } } private async void UpdateTableWithServerResponse() { string responseText = await Server.GETwithClient(); ServerData resposneJson = JsonConvert.DeserializeObject<ServerData>(responseText); UpdateTable(unitFlag, resposneJson); } private void RequestTimerElapsed(object sender, ElapsedEventArgs e) { UpdateTableWithServerResponse(); } #endregion #region PropertyChanged public event PropertyChangedEventHandler PropertyChanged; /** * @brief Simple function to trigger event handler * @params propertyName Name of ViewModel property as string */ protected void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } #endregion } } <file_sep>/AndroidApp/app/src/main/java/com/example/sensehat/COMMON.java package com.example.sensehat; public final class COMMON { // activities request codes public final static int REQUEST_CODE_CONFIG = 1; // configuration info: names and default values public final static String CONFIG_IP_ADDRESS = "ipAddress"; public static String DEFAULT_IP_ADDRESS = "192.168.0.17"; public final static String CONFIG_SAMPLE_TIME = "sampleTime"; public static int DEFAULT_SAMPLE_TIME = 500; public final static String CONFIG_MAX_SAMPLES = "maxSamples"; public static int DEFAULT_MAX_SAMPLES = 10; public final static String CONFIG_PORT_NUMBER = "portNumber"; static String DEFAULT_PORT_NUMBER = "80"; // error codes public final static int ERROR_TIME_STAMP = -1; public final static int ERROR_NAN_DATA = -2; public final static int ERROR_RESPONSE = -3; // IoT server data public final static String FILE_NAME = "chartdata.json"; public final static String FILE_MARIO= "mario.json"; public final static String FILE_LUIGI= "luigi.json"; public final static String SERWER_MARIO="mario.php"; public final static String SERWER_LUIGI="luigi.php"; public final static String SERWER_LED_DISPLAY="led_display.php"; }<file_sep>/WebApp/scripts/config.py #!/usr/bin/python3 import cgi, cgitb import json import sys import os content_len = int(os.environ["CONTENT_LENGTH"]) req_body = sys.stdin.read() myjson = json.loads(req_body) #data modification myjson["ip"] = "do sth" print('Content-Type: application/json\r\n\r\n') open with("config.json", "w") as file: file.write(json.dumps(myjson)) print(json.dumps(myjson)) <file_sep>/DesktopApp/rpiDataGrabber/rpiDataGrabber/rpiDataGrabber/configControl.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Newtonsoft.Json; using System.IO; namespace rpiDataGrabber { public partial class configControl : UserControl { //sciezka do pliku config const string filePath = @"C:\Users\Klient\Documents\GitHub\RPiDG\DesktopApp\rpiDataGrabber\rpiDataGrabber\config.json"; //funkcja do kodowania json public static void Serialize(object obj) { var serializer = new JsonSerializer(); using (var sw = new StreamWriter(filePath)) using (JsonWriter writer = new JsonTextWriter(sw)) { serializer.Serialize(writer, obj); } } public configControl() { InitializeComponent(); configData deserialized = JsonConvert.DeserializeObject<configData>(File.ReadAllText(filePath)); textBox1.Text = deserialized.ip; textBox2.Text = deserialized.port; textBox3.Text = deserialized.sampleTime.ToString(); textBox4.Text = deserialized.maxSamples.ToString(); textBox5.Text = deserialized.decimalPlaces.ToString(); } private void button1_Click(object sender, EventArgs e) { var conf = new configData { ip = textBox1.Text, port = textBox2.Text, sampleTime = Int16.Parse(textBox3.Text), maxSamples = Int16.Parse(textBox4.Text), decimalPlaces = Int16.Parse(textBox5.Text) }; Serialize(conf); // Inicjalizacja zmiennych do przekazania do metody MessageBox.Show. string message = "Your configuration have been successfully saved."; string caption = "Data Confirmation"; MessageBoxButtons buttons = MessageBoxButtons.OK; // Wyswietl MessageBox. MessageBox.Show(message, caption, buttons); } } } <file_sep>/DesktopApp/rpiDataGrabber/rpiDataGrabber/rpiDataGrabber/IoTServer.cs using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace rpiDataGrabber { public class IoTServer { private string ip, port; public IoTServer(string _ip, string _port) { ip = _ip; port = _port; } /** * @brief obtaining the address of the data file from IoT server IP. */ private string GetFileUrl() { return "http://" + ip + ":" + port + "/chartdata.json"; } /** * @brief obtaining the address of the PHP script from IoT server IP. */ private string GetScriptUrl() { return "http://" + ip + ":" + port + "server/serverscript.php"; } /** * @brief HTTP GET request using HttpClient */ public async Task<string> GETwithClient() { string responseText = null; try { using (HttpClient client = new HttpClient()) { responseText = await client.GetStringAsync(GetFileUrl()); } } catch (Exception e) { Debug.WriteLine("NETWORK ERROR"); Debug.WriteLine(e); } return responseText; } /** * @brief HTTP POST request using HttpClient */ public async Task<string> POSTwithClient() { string responseText = null; try { using (HttpClient client = new HttpClient()) { // POST request data var requestDataCollection = new List<KeyValuePair<string, string>>(); requestDataCollection.Add(new KeyValuePair<string, string>("filename", "chartdata")); var requestData = new FormUrlEncodedContent(requestDataCollection); // Sent POST request var result = await client.PostAsync(GetScriptUrl(), requestData); // Read response content responseText = await result.Content.ReadAsStringAsync(); } } catch (Exception e) { Debug.WriteLine("NETWORK ERROR"); Debug.WriteLine(e); } return responseText; } } } <file_sep>/DesktopApp/rpiDataGrabber/rpiDataGrabber/rpiDataGrabber/nullableServerData.cs namespace rpiDataGrabber { class nullableServerData { public double? temperature { get; set; } public double? pressure { get; set; } public double? humidity { get; set; } public double? roll { get; set; } public double? pitch { get; set; } public double? yaw { get; set; } public int? x { get; set; } public int? y { get; set; } public int? mid { get; set; } } } <file_sep>/ServerScripts/README.md Architektura: LED uruchamia skrypt php który uruchamia sudo exec skrypt py Reszta od razu wysyła zapytanie o dane z serwera z pliku .json Dane konfiguracyjne przechowywane w apce/kliencie/serwerze <file_sep>/WebApp/scripts/weather.js <!-- read configure data--> var sampleTimeSec = 0.1; ///< sample time in sec var sampleTimeMsec = 1000*sampleTimeSec; ///< sample time in msec var maxSamplesNumber = 100; ///< maximum number of samples ///< sample time in msec var lastTimeStamp; ///< most recent time stamp var xdata; ///< x-axis labels array: time stamps var ydata; ///< y-axis data array: random value var xdata2; ///< x-axis labels array: time stamps var ydata2; ///< y-axis data array: random value var xdata3; ///< x-axis labels array: time stamps var ydat3a; ///< y-axis data array: random value var chartContext; ///< chart context i.e. object that "owns" chart var chart; ///< Chart.js object var chartContext2; ///< chart context i.e. object that "owns" chart var chart2; ///< Chart.js object var chartContext3; ///< chart context i.e. object that "owns" chart var chart3; ///< Chart.js object var timer; var timer2; var timer3; const url ='http://192.168.1.15/ServerScripts/chartdata.json'; ///< server app with JSON API const curl ='scripts/config.json'; /** * @brief Add new value to next data point. * @param y New y-axis value */ function getConfig(){ /// Send request $.ajax( { url: curl, type: 'GET', dataType: 'json', /// success callback success: function(responseJSON, status, xhr) { console.log(JSON.stringify(responseJSON)); ip = responseJSON.ip; port = responseJSON.port; maxSamplesNumber = responseJSON.maxsamples; sampleTimeSec = responseJSON.stime; console.log(ip,port,maxSamplesNumber,sampleTimeSec); }, /// error callback error: function(response){ alert(response)} }); } function addData(y){ if(ydata.length > maxSamplesNumber) { removeOldData(); lastTimeStamp += sampleTimeSec; xdata.push(lastTimeStamp.toFixed(1)); } ydata.push(y); chart.update(); } function addData2(y){ if(ydata2.length > maxSamplesNumber) { removeOldData2(); lastTimeStamp += sampleTimeSec; xdata2.push(lastTimeStamp.toFixed(1)); } ydata2.push(y); chart2.update(); } function addData3(y){ if(ydata3.length > maxSamplesNumber) { removeOldData3(); lastTimeStamp += sampleTimeSec; xdata3.push(lastTimeStamp.toFixed(1)); } ydata3.push(y); chart3.update(); } /** * @brief Remove oldest data point. */ function removeOldData(){ xdata.splice(1,1); ydata.splice(1,1); } function removeOldData2(){ xdata2.splice(0,1); ydata2.splice(0,1); } function removeOldData3(){ xdata3.splice(0,1); ydata3.splice(0,1); } function startTimer(){ timer = setInterval(ajaxJSON, sampleTimeMsec); } function startTimer2(){ timer2 = setInterval(ajaxJSON2, sampleTimeMsec); } function startTimer3(){ timer3 = setInterval(ajaxJSON3, sampleTimeMsec); } function stopTimer(){ clearInterval(timer); } function stopTimer2(){ clearInterval(timer2); } function stopTimer3(){ clearInterval(timer3); } /** * @brief Send HTTP GET request to IoT server */ function ajaxJSON() { $.getJSON( url, function( data ) { $.each( data, function( key, val ) { if ( key == "temperature") { var temporary1 = val; addData(temporary1); } }); }); } function ajaxJSON2() { $.getJSON( url, function( data ) { $.each( data, function( key, val ) { if ( key == "pressure") { var temporary2 = val; addData2(temporary2); } }); }); } function ajaxJSON3() { $.getJSON( url, function( data ) { $.each( data, function( key, val ) { if ( key == "humidity") { var temporary3 = val; addData3(temporary3); } }); }); } /** * @brief Chart initialization */ function chartInit() { // array with consecutive integers: <0, maxSamplesNumber-1> xdata = [...Array(maxSamplesNumber).keys()]; // scaling all values ​​times the sample time xdata.forEach(function(p, i) {this[i] = (this[i]*sampleTimeSec).toFixed(1);}, xdata); // last value of 'xdata' lastTimeStamp = +xdata[xdata.length-1]; // empty array ydata = []; // get chart context from 'canvas' element chartContext = $("#chart")[0].getContext('2d'); chart = new Chart(chartContext, { // The type of chart: linear plot type: 'line', // Dataset: 'xdata' as labels, 'ydata' as dataset.data data: { labels: xdata, datasets: [{ fill: false, label: 'Temperature', backgroundColor: 'rgb(255, 0, 0)', borderColor: 'rgb(255, 0, 0)', data: ydata, lineTension: 0 }] }, // Configuration options options: { responsive: true, maintainAspectRatio: false, animation: false, scales: { yAxes: [{ scaleLabel: { display: true, labelString: 'Temperature [°C]' } }], xAxes: [{ scaleLabel: { display: true, labelString: 'Time [s]' } }] } } }); ydata = chart.data.datasets[0].data; xdata = chart.data.labels; } function chartInit2() { xdata2 = [...Array(maxSamplesNumber).keys()]; xdata2.forEach(function(p, i) {this[i] = (this[i]*sampleTimeSec).toFixed(1);}, xdata2); lastTimeStamp = +xdata2[xdata2.length-1]; ydata2 = []; chartContext2 = $("#chart2")[0].getContext('2d'); chart2 = new Chart(chartContext2, { type: 'line', data: { labels: xdata2, datasets: [{ fill: false, label: 'Pressure', backgroundColor: 'rgb(0, 255, 0)', borderColor: 'rgb(0, 255, 0)', data: ydata2, lineTension: 0 }] }, options: { responsive: true, maintainAspectRatio: false, animation: false, scales: { yAxes: [{ scaleLabel: { display: true, labelString: 'Pressure [hPa]' } }], xAxes: [{ scaleLabel: { display: true, labelString: 'Time [s]' } }] } } }); ydata2 = chart2.data.datasets[0].data; xdata2 = chart2.data.labels; } function chartInit3() { xdata3 = [...Array(maxSamplesNumber).keys()]; xdata3.forEach(function(p, i) {this[i] = (this[i]*sampleTimeSec).toFixed(1);}, xdata3); lastTimeStamp = +xdata3[xdata3.length-1]; ydata3 = []; chartContext3 = $("#chart3")[0].getContext('2d'); chart3 = new Chart(chartContext3, { type: 'line', data: { labels: xdata3, datasets: [{ fill: false, label: 'Humidity', backgroundColor: 'rgb(0, 0, 255)', borderColor: 'rgb(0, 0, 255)', data: ydata3, lineTension: 0 }] }, options: { responsive: true, maintainAspectRatio: false, animation: false, scales: { yAxes: [{ scaleLabel: { display: true, labelString: 'Humidity [%]' } }], xAxes: [{ scaleLabel: { display: true, labelString: 'Time [s]' } }] } } }); ydata3 = chart3.data.datasets[0].data; xdata3 = chart3.data.labels; } $(document).ready(() => { getConfig(); chartInit(); chartInit2(); chartInit3(); $("#start").click(startTimer); $("#stop").click(stopTimer); $("#start2").click(startTimer2); $("#stop2").click(stopTimer2); $("#start3").click(startTimer3); $("#stop3").click(stopTimer3); $("#sampletime").text(sampleTimeMsec.toString()); $("#samplenumber").text(maxSamplesNumber.toString()); $("#sampletime2").text(sampleTimeMsec.toString()); $("#samplenumber2").text(maxSamplesNumber.toString()); $("#sampletime3").text(sampleTimeMsec.toString()); $("#samplenumber3").text(maxSamplesNumber.toString()); }); <file_sep>/DesktopApp/rpiDataGrabber/rpiDataGrabber/rpiDataGrabber/rpyTimeline.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using OxyPlot; using OxyPlot.Axes; using OxyPlot.WindowsForms; using OxyPlot.Series; using Newtonsoft.Json; using System.IO; using System.Timers; using Timer = System.Timers.Timer; namespace rpiDataGrabber { public partial class rpyTimeline : UserControl { #region Fields public PlotModel DataPlotModel { get; set; } private int timeStamp = 0; private Timer RequestTimer; private IoTServer Server; const string filePath = @"C:\Users\Klient\Documents\GitHub\RPiDG\DesktopApp\rpiDataGrabber\rpiDataGrabber\config.json"; configData deserialized = JsonConvert.DeserializeObject<configData>(File.ReadAllText(filePath)); public string buttonFlag; #endregion public rpyTimeline() { InitializeComponent(); DataPlotModel = new PlotModel { Title = "RPY Timeline" }; string ip = deserialized.ip.ToString(); string port = deserialized.port.ToString(); double maxSamples = deserialized.maxSamples; double sampleTime = deserialized.sampleTime; double XAxisMax = maxSamples * sampleTime / 1000.0; DataPlotModel.Axes.Add(new LinearAxis() { Position = AxisPosition.Bottom, Minimum = 0, Maximum = XAxisMax, Key = "Horizontal", Unit = "sec", Title = "Time" }); DataPlotModel.Axes.Add(new LinearAxis() { Position = AxisPosition.Left, Key = "Vertical", Unit = "-", Title = "-" }); plotView1.Model = DataPlotModel; Server = new IoTServer(ip, port); } //roll private void button2_Click(object sender, EventArgs e) { if (RequestTimer != null) { RequestTimer.Enabled = false; RequestTimer = null; } if (RequestTimer == null) { double sampleTime = deserialized.sampleTime; buttonFlag = "Roll"; RequestTimer = new Timer(sampleTime); RequestTimer.Elapsed += new ElapsedEventHandler(RequestTimerElapsed); RequestTimer.Enabled = true; DataPlotModel.Series.Clear(); DataPlotModel.Series.Add(new LineSeries() { Title = "Roll", Color = OxyColor.Parse("#7386D5") }); DataPlotModel.ResetAllAxes(); } } //pitch private void button3_Click(object sender, EventArgs e) { if (RequestTimer != null) { RequestTimer.Enabled = false; RequestTimer = null; } if (RequestTimer == null) { double sampleTime = deserialized.sampleTime; buttonFlag = "Pitch"; RequestTimer = new Timer(sampleTime); RequestTimer.Elapsed += new ElapsedEventHandler(RequestTimerElapsed); RequestTimer.Enabled = true; DataPlotModel.Series.Clear(); DataPlotModel.Series.Add(new LineSeries() { Title = "Pitch", Color = OxyColor.Parse("#7386D5") }); DataPlotModel.ResetAllAxes(); } } //yaw private void button4_Click(object sender, EventArgs e) { if (RequestTimer != null) { RequestTimer.Enabled = false; RequestTimer = null; } if (RequestTimer == null) { double sampleTime = deserialized.sampleTime; buttonFlag = "Yaw"; RequestTimer = new Timer(sampleTime); RequestTimer.Elapsed += new ElapsedEventHandler(RequestTimerElapsed); RequestTimer.Enabled = true; DataPlotModel.Series.Clear(); DataPlotModel.Series.Add(new LineSeries() { Title = "Yaw", Color = OxyColor.Parse("#7386D5") }); DataPlotModel.ResetAllAxes(); } } private void UpdatePlot(double t, double d) { double maxSamples = deserialized.maxSamples; double sampleTime = deserialized.sampleTime; double XAxisMax = maxSamples * sampleTime / 1000.0; LineSeries lineSeries = DataPlotModel.Series[0] as LineSeries; lineSeries.Points.Add(new DataPoint(t, d)); if (lineSeries.Points.Count > maxSamples) lineSeries.Points.RemoveAt(0); if (t >= XAxisMax) { DataPlotModel.Axes[0].Minimum = (t - XAxisMax); DataPlotModel.Axes[0].Maximum = t + sampleTime / 1000.0; ; } if (buttonFlag == "Roll") { DataPlotModel.Axes[1].Unit = "DGR"; DataPlotModel.Axes[1].Title = "Roll"; } if (buttonFlag == "Pitch") { DataPlotModel.Axes[1].Unit = "DGR"; DataPlotModel.Axes[1].Title = "Pitch"; } if (buttonFlag == "Yaw") { DataPlotModel.Axes[1].Unit = "DGR"; DataPlotModel.Axes[1].Title = "Yaw"; } DataPlotModel.InvalidatePlot(true); } private async void UpdatePlotWithServerResponse() { string responseText = await Server.GETwithClient(); ServerData resposneJson = JsonConvert.DeserializeObject<ServerData>(responseText); if (buttonFlag == "Roll") { UpdatePlot(timeStamp / 1000.0, resposneJson.roll); } if (buttonFlag == "Pitch") { UpdatePlot(timeStamp / 1000.0, resposneJson.pitch); } if (buttonFlag == "Yaw") { UpdatePlot(timeStamp / 1000.0, resposneJson.yaw); } timeStamp += deserialized.sampleTime; } private void RequestTimerElapsed(object sender, ElapsedEventArgs e) { UpdatePlotWithServerResponse(); } #region PropertyChanged public event PropertyChangedEventHandler PropertyChanged; /** * @brief Simple function to trigger event handler * @params propertyName Name of ViewModel property as string */ protected void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } #endregion } } <file_sep>/README.md # RPiDG RaspberryPi Data Grabber project <file_sep>/AndroidApp/app/src/main/java/com/example/sensehat/joystickActivity.java package com.example.sensehat; import androidx.appcompat.app.AppCompatActivity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.util.Log; import android.view.View; import android.widget.TextView; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.jjoe64.graphview.GraphView; import com.jjoe64.graphview.series.DataPoint; import com.jjoe64.graphview.series.PointsGraphSeries; import org.json.JSONException; import org.json.JSONObject; import java.util.Timer; import java.util.TimerTask; public class joystickActivity extends AppCompatActivity { private final int dataGraphMaxDataPointsNumber = 1000; /* BEGIN config data */ private String ipAddress = COMMON.DEFAULT_IP_ADDRESS; private int sampleTime = COMMON.DEFAULT_SAMPLE_TIME; private int maxSamples = COMMON.DEFAULT_MAX_SAMPLES; private String portNumber = COMMON.DEFAULT_PORT_NUMBER; /* END config data */ /* BEGIN widgets */ private TextView textViewError; private GraphView joystickGraph; // private LineGraphSeries<DataPoint> joystickDataSeries; private PointsGraphSeries<DataPoint> joystickDataSeries; private final double joystickDataGraphMaxX = 4.0d; private final double joystickDataGraphMinX = -4.0d; private final double joystickDataGraphMaxY = 4.0d; private final double joystickDataGraphMinY = -4.0d; private AlertDialog.Builder configAlterDialog; /* END widgets */ /* BEGIN request timer */ private RequestQueue queue; private Timer requestTimer; private long requestTimerTimeStamp = 0; private long requestTimerPreviousTime = -1; private boolean requestTimerFirstRequest = true; private boolean requestTimerFirstRequestAfterStop; private TimerTask requestTimerTask; private final Handler handler = new Handler(); /* END request timer */ int previousBtnData=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_joystick); /* BEGIN initialize widgets */ /* BEGIN initialize TextViews */ textViewError = findViewById(R.id.textViewErrorMsg); textViewError.setText(""); /* END initialize TextViews */ /* BEGIN initialize GraphView */ // https://github.com/jjoe64/GraphView/wiki joystickGraph = (GraphView)findViewById(R.id.joystickGraph); // joystickDataSeries = new PointsGraphSeries<>(new DataPoint[]{}); // joystickGraph.addSeries(joystickDataSeries); joystickGraph.getViewport().setXAxisBoundsManual(true); joystickGraph.getViewport().setMinX(joystickDataGraphMinX); joystickGraph.getViewport().setMaxX(joystickDataGraphMaxX); joystickGraph.getViewport().setYAxisBoundsManual(true); joystickGraph.getViewport().setMinY(joystickDataGraphMinY); joystickGraph.getViewport().setMaxY(joystickDataGraphMaxY); joystickGraph.setTitle("Joystick"); /* END initialize GraphView */ /* BEGIN config alter dialog */ configAlterDialog = new AlertDialog.Builder(joystickActivity.this); configAlterDialog.setTitle("This will STOP data acquisition. Proceed?"); configAlterDialog.setIcon(android.R.drawable.ic_dialog_alert); configAlterDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { stopRequestTimerTask(); //next widget here } }); configAlterDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); /* END config alter dialog */ /* END initialize widgets */ // Initialize Volley request queue queue = Volley.newRequestQueue(joystickActivity.this); } /** * @brief Main activity button onClick procedure - common for all upper menu buttons * @param v the View (Button) that was clicked */ public void btns_onClick(View v) { switch (v.getId()) { case R.id.startBtn: { startRequestTimer(); break; } case R.id.stopBtn: { stopRequestTimerTask(); break; } default: { // do nothing } } } /** * @brief Create display text for IoT server IP address * @param ip IP address (string) * @retval Display text for textViewIP widget */ private String getIpAddressDisplayText(String ip) { return ("IP: " + ip); } /** * @brief Create JSON file URL from IoT server IP. * @param ip IP address (string) * @retval GET request URL */ private String getURL(String ip,String portNumber,String fileName) { return ("http://" + ip +":"+portNumber+ "/" + fileName); } /** * @brief Handles application errors. Logs an error and passes error code to GUI. * @param errorCode local error codes, see: COMMON */ private void errorHandling(int errorCode) { switch(errorCode) { case COMMON.ERROR_TIME_STAMP: textViewError.setText("ERR #1"); Log.d("errorHandling", "Request time stamp error."); break; case COMMON.ERROR_NAN_DATA: textViewError.setText("ERR #2"); Log.d("errorHandling", "Invalid JSON data."); break; case COMMON.ERROR_RESPONSE: textViewError.setText("ERR #3"); Log.d("errorHandling", "GET request VolleyError."); break; default: textViewError.setText("ERR ??"); Log.d("errorHandling", "Unknown error."); break; } } /** * @brief Reading x value of joystick from JSON response. * @param response IoT server JSON response as string * @retval new chart data */ private int getXDataFromResponse(String response) { JSONObject jObject; int x_pos = 0; // Create generic JSON object form string try { jObject = new JSONObject(response); } catch (JSONException e) { e.printStackTrace(); return x_pos; } // Read chart data form JSON object try { x_pos =(int) jObject.get("x"); } catch (JSONException e) { e.printStackTrace(); } return x_pos; } /** * @brief Reading y value of joystick from JSON response. * @param response IoT server JSON response as string * @retval new chart data */ private int getYDataFromResponse(String response) { JSONObject jObject; int y_pos = 0; // Create generic JSON object form string try { jObject = new JSONObject(response); } catch (JSONException e) { e.printStackTrace(); return y_pos; } // Read chart data form JSON object try { y_pos = (int)jObject.get("y"); } catch (JSONException e) { e.printStackTrace(); } return y_pos; } /** * @brief Reading button value of joystick from JSON response. * @param response IoT server JSON response as string * @retval new chart data */ private int getBtnDataFromResponse(String response) { JSONObject jObject; int mid =0; // Create generic JSON object form string try { jObject = new JSONObject(response); } catch (JSONException e) { e.printStackTrace(); return mid; } // Read chart data form JSON object try { mid = (int)jObject.get("mid"); } catch (JSONException e) { e.printStackTrace(); } return mid; } /** * @brief Starts new 'Timer' (if currently not exist) and schedules periodic task. */ private void startRequestTimer() { if(requestTimer == null) { // set a new Timer requestTimer = new Timer(); // initialize the TimerTask's job initializeRequestTimerTask(); requestTimer.schedule(requestTimerTask, 0, COMMON.DEFAULT_SAMPLE_TIME); // clear error message textViewError.setText(""); } } /** * @brief Stops request timer (if currently exist) * and sets 'requestTimerFirstRequestAfterStop' flag. */ private void stopRequestTimerTask() { // stop the timer, if it's not already null if (requestTimer != null) { requestTimer.cancel(); requestTimer = null; requestTimerFirstRequestAfterStop = true; } } /** * @brief Initialize request timer period task with 'Handler' post method as 'sendGetRequest'. */ private void initializeRequestTimerTask() { requestTimerTask = new TimerTask() { public void run() { handler.post(new Runnable() { public void run() { sendGetRequest(); } }); } }; } /** * @brief Sending GET request to IoT server using 'Volley'. */ private void sendGetRequest() { // Instantiate the RequestQueue with Volley // https://javadoc.io/doc/com.android.volley/volley/1.1.0-rc2/index.html String url = getURL(ipAddress,portNumber,COMMON.FILE_NAME); // Request a string response from the provided URL StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { responseHandling(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { errorHandling(COMMON.ERROR_RESPONSE); } }); // Add the request to the RequestQueue. queue.add(stringRequest); } /** * @brief Validation of client-side time stamp based on 'SystemClock'. */ private long getValidTimeStampIncrease(long currentTime) { // Right after start remember current time and return 0 if(requestTimerFirstRequest) { requestTimerPreviousTime = currentTime; requestTimerFirstRequest = false; return 0; } // After each stop return value not greater than sample time // to avoid "holes" in the plot if(requestTimerFirstRequestAfterStop) { if((currentTime - requestTimerPreviousTime) > COMMON.DEFAULT_SAMPLE_TIME) requestTimerPreviousTime = currentTime - COMMON.DEFAULT_SAMPLE_TIME; requestTimerFirstRequestAfterStop = false; } // If time difference is equal zero after start // return sample time if((currentTime - requestTimerPreviousTime) == 0) return COMMON.DEFAULT_SAMPLE_TIME; // Return time difference between current and previous request return (currentTime - requestTimerPreviousTime); } /** * @brief GET response handling - chart data series updated with IoT server data. */ private void responseHandling(String response) { if(requestTimer != null) { // get time stamp with SystemClock long requestTimerCurrentTime = SystemClock.uptimeMillis(); // current time requestTimerTimeStamp += getValidTimeStampIncrease(requestTimerCurrentTime); // get raw data from JSON response int XData_int = getXDataFromResponse(response); //double XData_double=(double)XData_int; int YData_int = getYDataFromResponse(response); //double YData_double=(double)YData_int; double YData = getYDataFromResponse(response); int btnData=getBtnDataFromResponse(response); boolean shape_flag=true; // update chart joystickDataSeries = new PointsGraphSeries<>(new DataPoint[]{new DataPoint(XData_int, YData_int)}); joystickGraph.addSeries(joystickDataSeries); //change point shape if(previousBtnData==btnData) { joystickDataSeries.setShape(PointsGraphSeries.Shape.POINT); } else { joystickDataSeries.setShape(PointsGraphSeries.Shape.RECTANGLE); previousBtnData=btnData; } // remember previous time stamp requestTimerPreviousTime = requestTimerCurrentTime; } } } <file_sep>/DesktopApp/rpiDataGrabber/rpiDataGrabber/rpiDataGrabber/configData.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace rpiDataGrabber { class configData { public string ip { get; set; } public string port { get; set; } public int sampleTime { get; set; } public int maxSamples { get; set; } public int decimalPlaces { get; set; } } } <file_sep>/AndroidApp/app/src/main/java/com/example/sensehat/chartsActivity.java package com.example.sensehat; import androidx.appcompat.app.AppCompatActivity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.util.Log; import android.view.View; import android.widget.TextView; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.jjoe64.graphview.GraphView; import com.jjoe64.graphview.series.DataPoint; import com.jjoe64.graphview.series.LineGraphSeries; import org.json.JSONException; import org.json.JSONObject; import java.util.Timer; import java.util.TimerTask; import static java.lang.Double.isNaN; public class chartsActivity extends AppCompatActivity { /* BEGIN config data */ private String ipAddress = COMMON.DEFAULT_IP_ADDRESS; private int sampleTime = COMMON.DEFAULT_SAMPLE_TIME; private int maxSamples = COMMON.DEFAULT_MAX_SAMPLES; private String portNumber = COMMON.DEFAULT_PORT_NUMBER; /* END config data */ /* BEGIN widgets */ private TextView textViewIP; private TextView textViewSampleTime; private TextView textViewError; private GraphView tempGraph; private GraphView pressGraph; private GraphView humGraph; private LineGraphSeries<DataPoint> dataSeries; private LineGraphSeries<DataPoint> pressDataSeries; private LineGraphSeries<DataPoint> humDataSeries; private final int dataGraphMaxDataPointsNumber = 1000; private final double dataGraphMaxX = 10.0d; private final double dataGraphMinX = 0.0d; private final double dataGraphMaxY = 105.0d; private final double dataGraphMinY = -30.0d; private final double pressGraphMaxX = 10.0d; private final double pressGraphMinX = 0.0d; private final double pressGraphMaxY = 1260.0d; private final double pressGraphMinY = 260.0d; private final double humGraphMaxX = 10.0d; private final double humGraphMinX = 0.0d; private final double humGraphMaxY = 100.0d; private final double humGraphMinY = 0.0d; private AlertDialog.Builder configAlterDialog; /* END widgets */ /* BEGIN request timer */ private RequestQueue queue; private Timer requestTimer; private long requestTimerTimeStamp = 0; private long requestTimerPreviousTime = -1; private boolean requestTimerFirstRequest = true; private boolean requestTimerFirstRequestAfterStop; private TimerTask requestTimerTask; private final Handler handler = new Handler(); /* END request timer */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_charts); /* BEGIN initialize widgets */ /* BEGIN initialize TextViews */ textViewIP = findViewById(R.id.textViewIP); textViewIP.setText(getIpAddressDisplayText(ipAddress)); textViewSampleTime = findViewById(R.id.textViewSampleTime); textViewSampleTime.setText(getSampleTimeDisplayText(Integer.toString(sampleTime))); textViewError = findViewById(R.id.textViewErrorMsg); textViewError.setText(""); /* END initialize TextViews */ /* BEGIN initialize GraphView */ // https://github.com/jjoe64/GraphView/wiki tempGraph = (GraphView)findViewById(R.id.temperatureGraph); dataSeries = new LineGraphSeries<>(new DataPoint[]{}); tempGraph.addSeries(dataSeries); tempGraph.getViewport().setXAxisBoundsManual(true); tempGraph.getViewport().setMinX(dataGraphMinX); tempGraph.getViewport().setMaxX(dataGraphMaxX); tempGraph.getViewport().setYAxisBoundsManual(true); tempGraph.getViewport().setMinY(dataGraphMinY); tempGraph.getViewport().setMaxY(dataGraphMaxY); tempGraph.setTitle("Temperature"); pressGraph =(GraphView)findViewById((R.id.pressureGraph)); pressDataSeries = new LineGraphSeries<>(new DataPoint[]{}); pressGraph.addSeries(pressDataSeries); pressGraph.getViewport().setXAxisBoundsManual(true); pressGraph.getViewport().setMinX(pressGraphMinX); pressGraph.getViewport().setMaxX(pressGraphMaxX); pressGraph.getViewport().setYAxisBoundsManual(true); pressGraph.getViewport().setMinY(pressGraphMinY); pressGraph.getViewport().setMaxY(pressGraphMaxY); pressGraph.setTitle("Pressure"); humGraph =(GraphView)findViewById((R.id.humidityGraph)); humDataSeries = new LineGraphSeries<>(new DataPoint[]{}); humGraph.addSeries(humDataSeries); humGraph.getViewport().setXAxisBoundsManual(true); humGraph.getViewport().setMinX(humGraphMinX); humGraph.getViewport().setMaxX(humGraphMaxX); humGraph.getViewport().setYAxisBoundsManual(true); humGraph.getViewport().setMinY(humGraphMinY); humGraph.getViewport().setMaxY(humGraphMaxY); humGraph.setTitle("Humidity"); /* END initialize GraphView */ /* BEGIN config alter dialog */ configAlterDialog = new AlertDialog.Builder(chartsActivity.this); configAlterDialog.setTitle("This will STOP data acquisition. Proceed?"); configAlterDialog.setIcon(android.R.drawable.ic_dialog_alert); configAlterDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { stopRequestTimerTask(); openConfig(); } }); configAlterDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); /* END config alter dialog */ /* END initialize widgets */ // Initialize Volley request queue queue = Volley.newRequestQueue(chartsActivity.this); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent dataIntent) { super.onActivityResult(requestCode, resultCode, dataIntent); if ((requestCode == COMMON.REQUEST_CODE_CONFIG) && (resultCode == RESULT_OK)) { // IoT server IP address ipAddress = dataIntent.getStringExtra(COMMON.CONFIG_IP_ADDRESS); textViewIP.setText(getIpAddressDisplayText(ipAddress)); // Sample time (ms) String sampleTimeText = dataIntent.getStringExtra(COMMON.CONFIG_SAMPLE_TIME); sampleTime = Integer.parseInt(sampleTimeText); textViewSampleTime.setText(getSampleTimeDisplayText(sampleTimeText)); // Max samples String maxSamplesText = dataIntent.getStringExtra(COMMON.CONFIG_MAX_SAMPLES); maxSamples = Integer.parseInt(maxSamplesText); } } /** * @brief Main activity button onClick procedure - common for all upper menu buttons * @param v the View (Button) that was clicked */ public void btns_onClick(View v) { switch (v.getId()) { case R.id.configBtn: { if(requestTimer != null) configAlterDialog.show(); else openConfig(); break; } case R.id.startBtn: { startRequestTimer(); break; } case R.id.stopBtn: { stopRequestTimerTask(); break; } default: { // do nothing } } } /** * @brief Create display text for IoT server IP address * @param ip IP address (string) * @retval Display text for textViewIP widget */ private String getIpAddressDisplayText(String ip) { return ("IP: " + ip); } /** * @brief Create display text for requests sample time * @param st Sample time in ms (string) * @retval Display text for textViewSampleTime widget */ private String getSampleTimeDisplayText(String st) { return ("Sample time: " + st + " ms"); } /** * @brief Create JSON file URL from IoT server IP. * @param ip IP address (string) * @retval GET request URL */ private String getURL(String ip,String portNumber,String fileName) { return ("http://" + ip +":"+portNumber+ "/" + fileName); } /** * @brief Handles application errors. Logs an error and passes error code to GUI. * @param errorCode local error codes, see: COMMON */ private void errorHandling(int errorCode) { switch(errorCode) { case COMMON.ERROR_TIME_STAMP: textViewError.setText("ERR #1"); Log.d("errorHandling", "Request time stamp error."); break; case COMMON.ERROR_NAN_DATA: textViewError.setText("ERR #2"); Log.d("errorHandling", "Invalid JSON data."); break; case COMMON.ERROR_RESPONSE: textViewError.setText("ERR #3"); Log.d("errorHandling", "GET request VolleyError."); break; default: textViewError.setText("ERR ??"); Log.d("errorHandling", "Unknown error."); break; } } /** * @brief Called when the user taps the 'Config' button. * */ private void openConfig() { Intent openConfigIntent = new Intent(this, configActivity.class); Bundle configBundle = new Bundle(); configBundle.putString(COMMON.CONFIG_IP_ADDRESS, ipAddress); configBundle.putInt(COMMON.CONFIG_SAMPLE_TIME, sampleTime); configBundle.putInt(COMMON.CONFIG_MAX_SAMPLES, maxSamples); openConfigIntent.putExtras(configBundle); startActivityForResult(openConfigIntent, COMMON.REQUEST_CODE_CONFIG); //startActivity(openConfigIntent); } /** * @brief Reading raw chart data from JSON response. * @param response IoT server JSON response as string * @retval new chart data */ private double getTempDataFromResponse(String response) { JSONObject jObject; double x = Double.NaN; // Create generic JSON object form string try { jObject = new JSONObject(response); } catch (JSONException e) { e.printStackTrace(); return x; } // Read chart data form JSON object try { x = (double)jObject.get("temperature"); } catch (JSONException e) { e.printStackTrace(); } return x; } /** * @brief Reading raw chart data from JSON response. * @param response IoT server JSON response as string * @retval new chart data */ private double getPressDataFromResponse(String response) { JSONObject jObject; double x = Double.NaN; // Create generic JSON object form string try { jObject = new JSONObject(response); } catch (JSONException e) { e.printStackTrace(); return x; } // Read chart data form JSON object try { x = (double)jObject.get("pressure"); } catch (JSONException e) { e.printStackTrace(); } return x; } /** * @brief Reading raw chart data from JSON response. * @param response IoT server JSON response as string * @retval new chart data */ private double getHumDataFromResponse(String response) { JSONObject jObject; double x = Double.NaN; // Create generic JSON object form string try { jObject = new JSONObject(response); } catch (JSONException e) { e.printStackTrace(); return x; } // Read chart data form JSON object try { x = (double)jObject.get("humidity"); } catch (JSONException e) { e.printStackTrace(); } return x; } /** * @brief Starts new 'Timer' (if currently not exist) and schedules periodic task. */ private void startRequestTimer() { if(requestTimer == null) { // set a new Timer requestTimer = new Timer(); // initialize the TimerTask's job initializeRequestTimerTask(); requestTimer.schedule(requestTimerTask, 0, sampleTime); // clear error message textViewError.setText(""); } } /** * @brief Stops request timer (if currently exist) * and sets 'requestTimerFirstRequestAfterStop' flag. */ private void stopRequestTimerTask() { // stop the timer, if it's not already null if (requestTimer != null) { requestTimer.cancel(); requestTimer = null; requestTimerFirstRequestAfterStop = true; } } /** * @brief Initialize request timer period task with 'Handler' post method as 'sendGetRequest'. */ private void initializeRequestTimerTask() { requestTimerTask = new TimerTask() { public void run() { handler.post(new Runnable() { public void run() { sendGetRequest(); } }); } }; } /** * @brief Sending GET request to IoT server using 'Volley'. */ private void sendGetRequest() { // Instantiate the RequestQueue with Volley // https://javadoc.io/doc/com.android.volley/volley/1.1.0-rc2/index.html String url = getURL(ipAddress,portNumber,COMMON.FILE_NAME); // Request a string response from the provided URL StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { responseHandling(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { errorHandling(COMMON.ERROR_RESPONSE); } }); // Add the request to the RequestQueue. queue.add(stringRequest); } /** * @brief Validation of client-side time stamp based on 'SystemClock'. */ private long getValidTimeStampIncrease(long currentTime) { // Right after start remember current time and return 0 if(requestTimerFirstRequest) { requestTimerPreviousTime = currentTime; requestTimerFirstRequest = false; return 0; } // After each stop return value not greater than sample time // to avoid "holes" in the plot if(requestTimerFirstRequestAfterStop) { if((currentTime - requestTimerPreviousTime) > sampleTime) requestTimerPreviousTime = currentTime - sampleTime; requestTimerFirstRequestAfterStop = false; } // If time difference is equal zero after start // return sample time if((currentTime - requestTimerPreviousTime) == 0) return sampleTime; // Return time difference between current and previous request return (currentTime - requestTimerPreviousTime); } /** * @brief GET response handling - chart data series updated with IoT server data. */ private void responseHandling(String response) { if(requestTimer != null) { // get time stamp with SystemClock long requestTimerCurrentTime = SystemClock.uptimeMillis(); // current time requestTimerTimeStamp += getValidTimeStampIncrease(requestTimerCurrentTime); // get raw data from JSON response double rawData = getTempDataFromResponse(response); double pressData =getPressDataFromResponse(response); double humData =getHumDataFromResponse(response); // update chart if (isNaN(rawData)||isNaN(pressData)||isNaN(humData)) { errorHandling(COMMON.ERROR_NAN_DATA); } else { // update plot series double timeStamp = requestTimerTimeStamp / 1000.0; // [sec] boolean scrollGraph = (timeStamp > dataGraphMaxX); boolean scrollPressGraph = (timeStamp > pressGraphMaxX); boolean scrollHumGraph = (timeStamp > humGraphMaxX); humDataSeries.appendData(new DataPoint(timeStamp,humData),scrollHumGraph,maxSamples); pressDataSeries.appendData(new DataPoint(timeStamp, pressData),scrollPressGraph, maxSamples); dataSeries.appendData(new DataPoint(timeStamp, rawData), scrollGraph, maxSamples); // refresh chart pressGraph.onDataChanged(true, true); tempGraph.onDataChanged(true, true); humGraph.onDataChanged(true,true); } // remember previous time stamp requestTimerPreviousTime = requestTimerCurrentTime; } } } <file_sep>/AndroidApp/app/src/main/java/com/example/sensehat/RgbButton.java package com.example.sensehat; import android.content.Context; import android.util.AttributeSet; import android.widget.Button; public class RgbButton extends androidx.appcompat.widget.AppCompatButton { public RgbButton(Context context, int x, int y) { super(context); this.x=x; this.y=y; } public int x; public int y; } <file_sep>/AndroidApp/app/src/main/java/com/example/sensehat/measurementsActivity.java package com.example.sensehat; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.app.ActionBar; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicInteger; //import android.support.v7.app.AppCompatActivity; public class measurementsActivity extends AppCompatActivity { /* BEGIN config data */ private String ipAddress = COMMON.DEFAULT_IP_ADDRESS; private int sampleTime = COMMON.DEFAULT_SAMPLE_TIME; private int maxSamples = COMMON.DEFAULT_MAX_SAMPLES; private String portNumber = COMMON.DEFAULT_PORT_NUMBER; /* END config data */ private TextView textViewError; int JSONSizeGloabal; int iGlobal; /* BEGIN request timer */ private RequestQueue queue; private Timer requestTimer; private long requestTimerTimeStamp = 0; private long requestTimerPreviousTime = -1; private boolean requestTimerFirstRequest = true; private boolean requestTimerFirstRequestAfterStop; private TimerTask requestTimerTask; private final Handler handler = new Handler(); /* END request timer */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_measurements); textViewError = findViewById(R.id.textViewErrorMsg); textViewError.setText(""); queue = Volley.newRequestQueue(measurementsActivity.this); } /** * @brief Main activity button onClick procedure - common for all upper menu buttons * @param v the View (Button) that was clicked */ public void btns_onClick(View v) { switch (v.getId()) { case R.id.startBtn: { startRequestTimer(); break; } case R.id.stopBtn: { stopRequestTimerTask(); break; } default: { // do nothing } } } private String getURL(String ip,String portNumber,String fileName) { return ("http://" + ip +":"+portNumber+ "/" + fileName); } /** * @brief Handles application errors. Logs an error and passes error code to GUI. * @param errorCode local error codes, see: COMMON */ private void errorHandling(int errorCode) { switch(errorCode) { case COMMON.ERROR_TIME_STAMP: textViewError.setText("ERR #1"); Log.d("errorHandling", "Request time stamp error."); break; case COMMON.ERROR_NAN_DATA: textViewError.setText("ERR #2"); Log.d("errorHandling", "Invalid JSON data."); break; case COMMON.ERROR_RESPONSE: textViewError.setText("ERR #3"); Log.d("errorHandling", "GET request VolleyError."); break; default: textViewError.setText("ERR ??"); Log.d("errorHandling", "Unknown error."); break; } } /** * @brief checking size of JSON response. * @param response IoT server JSON response as string * @retval size of JSON response */ private int getJSONSize(String response) { JSONObject jObject; int size = 0; // Create generic JSON object form string try { jObject = new JSONObject(response); } catch (JSONException e) { e.printStackTrace(); return size; } // Read chart data form JSON object size = jObject.length(); return size; } /** * @brief checking size of JSON response. * @param response IoT server JSON response as string * @retval size of JSON response */ private JSONArray getJSONnames(String response) { JSONObject jObject = null; int x = 0; // Create generic JSON object form string try { jObject = new JSONObject(response); } catch (JSONException e) { e.printStackTrace(); } JSONArray name=jObject.names(); return name; } /** * @brief checking size of JSON response. * @param response IoT server JSON response as string * @retval size of JSON response */ private List getListJSONnames(String response) { JSONObject jObject = null; List<String> namesList=new ArrayList<String>(); // Create generic JSON object form string try { jObject = new JSONObject(response); } catch (JSONException e) { e.printStackTrace(); } JSONArray names=jObject.names(); //converting JSONarray to normal list if(names!=null) { int len=names.length(); for(int i=0;i<len;i++){ try { namesList.add(names.get(i).toString()); } catch (JSONException e) { e.printStackTrace(); } } } return namesList; } /** * @brief checking size of JSON response. * @param response IoT server JSON response as string * @retval size of JSON response */ private double getJSONvalue(String response, JSONArray names,int it) { JSONObject jObject = null; double val = 0; // Create generic JSON object form string try { jObject = new JSONObject(response); } catch (JSONException e) { e.printStackTrace(); } //Read value from JSONobject try { val = (double) jObject.getDouble((String) names.get(it)); } catch (JSONException e) { e.printStackTrace(); } return val; } /** * @brief Starts new 'Timer' (if currently not exist) and schedules periodic task. */ private void startRequestTimer() { if(requestTimer == null) { // set a new Timer requestTimer = new Timer(); // initialize the TimerTask's job initializeRequestTimerTask(); requestTimer.schedule(requestTimerTask, 0, COMMON.DEFAULT_SAMPLE_TIME); // clear error message textViewError.setText(""); } } /** * @brief Stops request timer (if currently exist) * and sets 'requestTimerFirstRequestAfterStop' flag. */ private void stopRequestTimerTask() { // stop the timer, if it's not already null if (requestTimer != null) { requestTimer.cancel(); requestTimer = null; requestTimerFirstRequestAfterStop = true; } } /** * @brief Initialize request timer period task with 'Handler' post method as 'sendGetRequest'. */ private void initializeRequestTimerTask() { requestTimerTask = new TimerTask() { public void run() { handler.post(new Runnable() { public void run() { sendGetRequest(); } }); } }; } /** * @brief Sending GET request to IoT server using 'Volley'. */ private void sendGetRequest() { // Instantiate the RequestQueue with Volley // https://javadoc.io/doc/com.android.volley/volley/1.1.0-rc2/index.html String url = getURL(ipAddress,portNumber,COMMON.FILE_NAME); // Request a string response from the provided URL StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { responseHandling(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { errorHandling(COMMON.ERROR_RESPONSE); } }); // Add the request to the RequestQueue. queue.add(stringRequest); } /** * @brief Validation of client-side time stamp based on 'SystemClock'. */ private long getValidTimeStampIncrease(long currentTime) { // Right after start remember current time and return 0 if(requestTimerFirstRequest) { requestTimerPreviousTime = currentTime; requestTimerFirstRequest = false; return 0; } // After each stop return value not greater than sample time // to avoid "holes" in the plot if(requestTimerFirstRequestAfterStop) { if((currentTime - requestTimerPreviousTime) > COMMON.DEFAULT_SAMPLE_TIME) requestTimerPreviousTime = currentTime - COMMON.DEFAULT_SAMPLE_TIME; requestTimerFirstRequestAfterStop = false; } // If time difference is equal zero after start // return sample time if((currentTime - requestTimerPreviousTime) == 0) return COMMON.DEFAULT_SAMPLE_TIME; // Return time difference between current and previous request return (currentTime - requestTimerPreviousTime); } /** * @brief GET response handling - chart data series updated with IoT server data. */ @SuppressLint("SetTextI18n") private void responseHandling(String response) { if(requestTimer != null) { // get time stamp with SystemClock long requestTimerCurrentTime = SystemClock.uptimeMillis(); // current time requestTimerTimeStamp += getValidTimeStampIncrease(requestTimerCurrentTime); // get raw data from JSON response //int XData_int = getXDataFromResponse(response); JSONSizeGloabal=getJSONSize(response); int it = 0; String name; JSONArray names= getJSONnames(response); List namesString=getListJSONnames(response); List<Double> vals = new ArrayList<>(); //dynamic generate LinearLayout linearLayout = findViewById(R.id.rootLayout); List views=new ArrayList(); if (linearLayout != null) { linearLayout.removeAllViewsInLayout(); } for(int i=0;i<JSONSizeGloabal;i++) { vals.add(getJSONvalue(response,names,i)); } for(int i=0;i<JSONSizeGloabal;i++) { TextView textViewName = new TextView(this); TextView textViewValue = new TextView(this); textViewName.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); textViewValue.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT)); textViewName.setGravity(Gravity.LEFT); textViewValue.setGravity(Gravity.RIGHT); //textViewValue.setGravity(Gravity.CENTER); textViewValue.setText(vals.get(i).toString()); textViewName.setText(namesString.get(i).toString()); if (linearLayout != null) { linearLayout.addView(textViewName); linearLayout.addView(textViewValue); } } // remember previous time stamp requestTimerPreviousTime = requestTimerCurrentTime; } } } <file_sep>/WebApp/scripts/table.js const url = 'http://192.168.1.15/ServerScripts/chartdata.json'; const curl = 'scripts/config.json' var timer; function getConfig(){ $.ajax({ url : curl, type: 'GET', dataType: 'json', success: function(responseJSON, status, xhr) { console.log(responseJSON.dplaces); }, error: function(){ console.log('error') } }); } function getData(){ $.ajax({ url : url, type: 'GET', dataType: 'json', success: function(responseJSON, status, xhr) { console.log(responseJSON); var len = Object.keys(responseJSON).length; generateTable(responseJSON, len) }, error: function(){ console.log('error') } }); } function generateTable(responseJSON, len){ var tableH = document.getElementById('table-holder'); tableH.removeChild(tableH.childNodes[0]) tableC = document.createElement('div') tableC.setAttribute("id", 'table-content') tableH.appendChild(tableC) for(key in responseJSON){ if(responseJSON[key] != 0){ var tab = document.createElement("TR"); tab.innerHTML = "<h4>" + key + "</h>" + ": " + responseJSON[key].toFixed(2); document.getElementById('table-content').appendChild(tab); } } } function startTimer(){ timer = setInterval(getData, 100); } function stopTimer(){ clearInterval(timer); } $(document).ready(function (){ $("#start").click(startTimer); $("#stop").click(stopTimer); }); <file_sep>/ServerScripts/led_display.php <?php function ledIndexToTag($x, $y) { return "LED" .$x .$y; } $ledDisplay = array(); $ledDisplayTestFile = 'led_display.json'; $n = 0; for ($i =0; $i < 8; $i++) { for($j=0; $j < 8; $j++){ $ledTag = ledIndexToTag($i, $j); if(isset($_POST[$ledTag])){ $ledDisplay[$n] = json_decode($_POST[$ledTag]); $n=$n+1; } } } /*DEBUG print_r($ledDisplay);*/ $ledDisplayJson = json_encode($ledDisplay); file_put_contents($ledDisplayTestFile, $ledDisplayJson); echo"ACK1"; exec ("sudo ./led_display.py"); echo " ACK2"; ?><file_sep>/DesktopApp/rpiDataGrabber/rpiDataGrabber/rpiDataGrabber/ServerData.cs namespace rpiDataGrabber { internal class ServerData { public double temperature { get; set; } public double pressure { get; set; } public double humidity { get; set; } public double roll { get; set; } public double pitch { get; set; } public double yaw { get; set; } public int x { get; set; } public int y { get; set; } public int mid { get; set; } } }<file_sep>/DesktopApp/rpiDataGrabber/rpiDataGrabber/rpiDataGrabber/joystick.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using OxyPlot; using OxyPlot.Axes; using OxyPlot.WindowsForms; using OxyPlot.Series; using Newtonsoft.Json; using System.IO; using System.Timers; using Timer = System.Timers.Timer; namespace rpiDataGrabber { public partial class joystick : UserControl { #region Fields public PlotModel DataPlotModel { get; set; } private int timeStamp = 0; private Timer RequestTimer; private IoTServer Server; const string filePath = @"C:\Users\Klient\Documents\GitHub\RPiDG\DesktopApp\rpiDataGrabber\rpiDataGrabber\config.json"; configData deserialized = JsonConvert.DeserializeObject<configData>(File.ReadAllText(filePath)); int xMax = 10; #endregion public joystick() { InitializeComponent(); DataPlotModel = new PlotModel { Title = "Weather Timeline" }; string ip = deserialized.ip.ToString(); string port = deserialized.port.ToString(); double maxSamples = deserialized.maxSamples; double sampleTime = deserialized.sampleTime; double XAxisMax = maxSamples * sampleTime / 1000.0; DataPlotModel.Axes.Add(new LinearAxis() { Position = AxisPosition.Bottom, Minimum = -xMax, Maximum = xMax, Key = "Horizontal", Title = "X" }); DataPlotModel.Axes.Add(new LinearAxis() { Position = AxisPosition.Left, Key = "Vertical", Title = "Y" }); plotView1.Model = DataPlotModel; Server = new IoTServer(ip, port); RequestTimer = new Timer(sampleTime); RequestTimer.Elapsed += new ElapsedEventHandler(RequestTimerElapsed); RequestTimer.Enabled = true; DataPlotModel.Series.Clear(); DataPlotModel.Series.Add(new LineSeries() { Title = "Position", Color = OxyColor.Parse("#30323C"), MarkerFill = OxyColor.Parse("#7386D5"), MarkerType = OxyPlot.MarkerType.Circle }); DataPlotModel.ResetAllAxes(); } private void UpdatePlot(int x, int y) { LineSeries lineSeries = DataPlotModel.Series[0] as LineSeries; //punkt lineSeries.Points.Add(new DataPoint(x,y)); if(lineSeries.Points.Count()>1) lineSeries.Points.RemoveAt(0); //osie if (x >= xMax) { xMax = x; DataPlotModel.Axes[0].Minimum = xMax - 21; DataPlotModel.Axes[0].Maximum = xMax + 1 ; } if (x <= -xMax) { xMax = -x; DataPlotModel.Axes[0].Minimum = -xMax - 1; DataPlotModel.Axes[0].Maximum = -xMax + 21; } DataPlotModel.InvalidatePlot(true); } private async void UpdatePlotWithServerResponse() { string responseText = await Server.GETwithClient(); ServerData resposneJson = JsonConvert.DeserializeObject<ServerData>(responseText); UpdatePlot(resposneJson.x, resposneJson.y); } private void RequestTimerElapsed(object sender, ElapsedEventArgs e) { UpdatePlotWithServerResponse(); } #region PropertyChanged public event PropertyChangedEventHandler PropertyChanged; /** * @brief Simple function to trigger event handler * @params propertyName Name of ViewModel property as string */ protected void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } #endregion } } <file_sep>/DesktopApp/rpiDataGrabber/rpiDataGrabber/rpiDataGrabber/dynamicDataTable.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Newtonsoft.Json; using System.IO; using System.Timers; using Timer = System.Timers.Timer; namespace rpiDataGrabber { public partial class dynamicDataTable : UserControl { #region Fields private Timer RequestTimer; private IoTServer Server; const string filePath = @"C:\Users\Klient\Documents\GitHub\RPiDG\DesktopApp\rpiDataGrabber\rpiDataGrabber\config.json"; configData deserialized = JsonConvert.DeserializeObject<configData>(File.ReadAllText(filePath)); public string unitFlag = "basicUnits"; public double farenheit, mmhg, humi01; public double rRad, pRad, yRad; int dec; int labelFlag; string tempString; #endregion delegate void LabelDelegate(string message); public dynamicDataTable() { InitializeComponent(); string ip = deserialized.ip.ToString(); string port = deserialized.port.ToString(); dec = deserialized.decimalPlaces; Server = new IoTServer(ip, port); } #region Buttons //change unit to basic private void button1_Click(object sender, EventArgs e) { if (RequestTimer != null) { RequestTimer.Enabled = false; RequestTimer = null; label1.Text = ""; label2.Text = ""; label3.Text = ""; label4.Text = ""; label5.Text = ""; label6.Text = ""; label7.Text = ""; label8.Text = ""; label9.Text = ""; } if (RequestTimer == null) { double sampleTime = deserialized.sampleTime; RequestTimer = new Timer(sampleTime); RequestTimer.Elapsed += new ElapsedEventHandler(RequestTimerElapsed); RequestTimer.Enabled = true; } unitFlag = "basicUnits"; } //change unit to other private void button2_Click(object sender, EventArgs e) { if (RequestTimer != null) { RequestTimer.Enabled = false; RequestTimer = null; label1.Text = ""; label2.Text = ""; label3.Text = ""; label4.Text = ""; label5.Text = ""; label6.Text = ""; label7.Text = ""; label8.Text = ""; label9.Text = ""; } if (RequestTimer == null) { double sampleTime = deserialized.sampleTime; RequestTimer = new Timer(sampleTime); RequestTimer.Elapsed += new ElapsedEventHandler(RequestTimerElapsed); RequestTimer.Enabled = true; } unitFlag = "otherUnits"; } #endregion #region LabelUpdateSystem private void UpdateString(string msg) {//invoke zeby spoza UI thread updatowac labela if(labelFlag == 1) { if (this.label1.InvokeRequired) this.label1.Invoke(new LabelDelegate(UpdateString), new object[] { msg }); else this.label1.Text = msg; } if (labelFlag == 2) { if (this.label2.InvokeRequired) label2.Invoke(new LabelDelegate(UpdateString), new object[] { msg }); else this.label2.Text = msg; } if (labelFlag == 3) { if (this.label3.InvokeRequired) label3.Invoke(new LabelDelegate(UpdateString), new object[] { msg }); else this.label3.Text = msg; } if (labelFlag == 4) { if (this.label4.InvokeRequired) label4.Invoke(new LabelDelegate(UpdateString), new object[] { msg }); else this.label4.Text = msg; } if (labelFlag == 5) { if (this.label5.InvokeRequired) label5.Invoke(new LabelDelegate(UpdateString), new object[] { msg }); else this.label5.Text = msg; } if (labelFlag == 6) { if (this.label6.InvokeRequired) label6.Invoke(new LabelDelegate(UpdateString), new object[] { msg }); else this.label6.Text = msg; } if (labelFlag == 7) { if (this.label7.InvokeRequired) label7.Invoke(new LabelDelegate(UpdateString), new object[] { msg }); else this.label7.Text = msg; } if (labelFlag == 8) { if (this.label8.InvokeRequired) label8.Invoke(new LabelDelegate(UpdateString), new object[] { msg }); else this.label8.Text = msg; } if (labelFlag == 9) { if (this.label9.InvokeRequired) label9.Invoke(new LabelDelegate(UpdateString), new object[] { msg }); else this.label9.Text = msg; } } #endregion private async void UpdateLabelsWithServerResponse() { labelFlag = 1; string responseText = await Server.GETwithClient(); //przypisanie wartości null co by mozna było je porównać nullableServerData responseJson = new nullableServerData(); responseJson.temperature = null; responseJson.humidity = null; responseJson.pressure = null; responseJson.pitch = null; responseJson.roll = null; responseJson.yaw = null; responseJson.y = null; responseJson.x = null; responseJson.mid = null; responseJson = JsonConvert.DeserializeObject<nullableServerData>(responseText); #region calc&assignVals //temperature if (responseJson.temperature != null) { double normaDouble = responseJson.temperature ?? 0; double temporaryTemp = Math.Round(normaDouble, dec); if (unitFlag == "basicUnits") tempString = "Temperature: " + temporaryTemp.ToString() + " [°C]"; if (unitFlag == "otherUnits") { temporaryTemp = temporaryTemp * 1.8 + 32; temporaryTemp = Math.Round(temporaryTemp, dec); tempString = "Temperature: " + temporaryTemp.ToString() + " [°F]"; } UpdateString(tempString); labelFlag++; } if (responseJson.temperature == null) { //doNothing } //humidity if (responseJson.humidity != null) { double normaDouble = responseJson.humidity ?? 0; double temporary = Math.Round(normaDouble, dec); if (unitFlag == "basicUnits") tempString = "Humidity: " + temporary.ToString() + " [%rH]"; if (unitFlag == "otherUnits") { temporary = temporary / 100; temporary = Math.Round(temporary, dec); tempString = "Humidity: " + temporary.ToString() + " [0-1]"; } UpdateString(tempString); labelFlag++; } if (responseJson.humidity == null) { //doNothing } //pressure if (responseJson.pressure != null) { double normaDouble = responseJson.pressure ?? 0; double temporary = Math.Round(normaDouble, dec); if (unitFlag == "basicUnits") tempString = "Pressure: " + temporary.ToString() + " [hPa]"; if (unitFlag == "otherUnits") { temporary = temporary * 0.750062; temporary = Math.Round(temporary, dec); tempString = "Pressure: " + temporary.ToString() + " [mmHg]"; } UpdateString(tempString); labelFlag++; } if (responseJson.pressure == null) { //doNothing } //roll if (responseJson.roll != null) { double normaDouble = responseJson.roll ?? 0; double temporaryTemp = Math.Round(normaDouble, dec); if (unitFlag == "basicUnits") tempString = "Roll: " + temporaryTemp.ToString() + " [DRG]"; if (unitFlag == "otherUnits") { temporaryTemp = temporaryTemp * Math.PI / 180; temporaryTemp = Math.Round(temporaryTemp, dec); tempString = "Roll: " + temporaryTemp.ToString() + " [RAD]"; } UpdateString(tempString); labelFlag++; } if (responseJson.roll == null) { //doNothing } //pitch if (responseJson.pitch != null) { double normaDouble = responseJson.pitch ?? 0; double temporaryTemp = Math.Round(normaDouble, dec); if (unitFlag == "basicUnits") tempString = "Pitch: " + temporaryTemp.ToString() + " [DRG]"; if (unitFlag == "otherUnits") { temporaryTemp = temporaryTemp * Math.PI / 180; temporaryTemp = Math.Round(temporaryTemp, dec); tempString = "Pitch: " + temporaryTemp.ToString() + " [RAD]"; } UpdateString(tempString); labelFlag++; } if (responseJson.pitch == null) { //doNothing } //yaw if (responseJson.yaw != null) { double normaDouble = responseJson.yaw ?? 0; double temporaryTemp = Math.Round(normaDouble, dec); if (unitFlag == "basicUnits") tempString = "Yaw: " + temporaryTemp.ToString() + " [DRG]"; if (unitFlag == "otherUnits") { temporaryTemp = temporaryTemp * Math.PI / 180; temporaryTemp = Math.Round(temporaryTemp, dec); tempString = "Yaw: " + temporaryTemp.ToString() + " [RAD]"; } UpdateString(tempString); labelFlag++; } if (responseJson.yaw == null) { //doNothing } //x if (responseJson.x != null) { int normalInt = responseJson.x ?? 0; tempString = "X: " + normalInt.ToString(); UpdateString(tempString); labelFlag++; } if (responseJson.x == null) { //doNothing } //y if (responseJson.y != null) { int normalInt = responseJson.y ?? 0; tempString = "Y: " + normalInt.ToString(); UpdateString(tempString); labelFlag++; } if (responseJson.y == null) { //doNothing } //mid if (responseJson.mid != null) { int normalInt = responseJson.mid ?? 0; tempString = "MID: " + normalInt.ToString(); UpdateString(tempString); labelFlag++; } if (responseJson.mid == null) { //doNothing } #endregion } private void RequestTimerElapsed(object sender, ElapsedEventArgs e) { UpdateLabelsWithServerResponse(); } #region PropertyChanged public event PropertyChangedEventHandler PropertyChanged; /** * @brief Simple function to trigger event handler * @params propertyName Name of ViewModel property as string */ protected void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } #endregion } } <file_sep>/ToDo.txt Nazwa: RPI DATA GRABBER (RPi DG) Widoki: Menu Data Table Weather Timeline RPY Timeline LED Panel Joystick Position Configuration Nazwy danych: Temperature Pressure Humidity Roll Pitch Yaw X Y Middle Position Configuration: IP PORT SAMPLE TIME MAX SAMPLES DECIMAL PLACES Architektura: LED uruchamia skrypt php który uruchamia sudo exec skrypt py Reszta od razu wysyła zapytanie o dane z serwera z pliku .json Dane konfiguracyjne przechowywane w apce/kliencie/serwerze Trzy osobne skrypty(demony) pobierające dane do osobnych plików .json Kolory: Menu Background: #7386D5 Background: #30323C Text: #E3B2B2 Komentarze: * kom * <file_sep>/WebApp/scripts/config.js var ip; var port; var stime; var maxsamples; var dplaces; const url = 'http://1192.168.127.12/WebApp/scripts/config.php'; function subFunction(){ ip = document.getElementById("ip").value; port = document.getElementById("port").value; stime = document.getElementById("stime").value; maxsamples = document.getElementById("maxsamples").value; dplaces = document.getElementById("dplaces").value; sendToServer() }; function sendToServer(){ var jsonObj = {ip: ip, port: port, stime: stime, maxsamples: maxsamples, dplaces: dplaces}; var jsonStr = JSON.stringify(jsonObj); console.log(jsonStr); console.log(jsonObj); $.ajax({ url: url, data: {data: jsonStr}, type: 'POST', success: function(response) { alert(response); console.log('success'); }, error: function(response) { alert(response); console.log('fail'); } }); }; window.onload = function (){ $('#submitbtn').click(subFunction) } <file_sep>/WebApp/test/testsite.js const url = 'http://192.168.1.15/cgi-bin/hello.py'; function sendReq(){ $.get(url, function(data) { // Get JSON data from Python script if (data){ console.log("Data returned:", data) } jobDataJSON = JSON.parse(data) document.getElementById('return').innerHTML = data }) } window.onload = function (){ $('#submitbtn').click(sendReq) } <file_sep>/AndroidApp/settings.gradle rootProject.name='SenseHat' include ':app' <file_sep>/DesktopApp/rpiDataGrabber/rpiDataGrabber/rpiDataGrabber/UserControl2.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Newtonsoft.Json; using System.IO; using System.Net; using System.Net.Http; namespace rpiDataGrabber { public partial class UserControl2 : UserControl { public UserControl2() { InitializeComponent(); } //actual picked color Color actColor = Color.Transparent; //wybieranie koloru private void button66_Click(object sender, EventArgs e) { // buttTag = int(button1.Name); ColorDialog colDial = new ColorDialog(); // Keeps the user from selecting a custom color. colDial.AllowFullOpen = false; // Update the text box color if the user clicks OK if (colDial.ShowDialog() == DialogResult.OK) { shownColor.BackColor = colDial.Color; actColor = colDial.Color; } } //dummy way to use buttons private void button1_Click(object sender, EventArgs e) => button1.BackColor = actColor; private void button2_Click(object sender, EventArgs e) { button2.BackColor = actColor; } private void button3_Click(object sender, EventArgs e) { button3.BackColor = actColor; } private void button5_Click(object sender, EventArgs e) { button5.BackColor = actColor; } private void button6_Click(object sender, EventArgs e) { button6.BackColor = actColor; } private void button7_Click(object sender, EventArgs e) { button7.BackColor = actColor; } private void button8_Click(object sender, EventArgs e) { button8.BackColor = actColor; } private void button9_Click(object sender, EventArgs e) { button9.BackColor = actColor; } private void button10_Click(object sender, EventArgs e) { button10.BackColor = actColor; } private void button11_Click(object sender, EventArgs e) { button11.BackColor = actColor; } private void button12_Click(object sender, EventArgs e) { button12.BackColor = actColor; } private void button13_Click(object sender, EventArgs e) { button13.BackColor = actColor; } private void button14_Click(object sender, EventArgs e) { button14.BackColor = actColor; } private void button15_Click(object sender, EventArgs e) { button15.BackColor = actColor; } private void button16_Click(object sender, EventArgs e) { button16.BackColor = actColor; } private void button17_Click(object sender, EventArgs e) { button17.BackColor = actColor; } private void button18_Click(object sender, EventArgs e) { button18.BackColor = actColor; } private void button19_Click(object sender, EventArgs e) { button19.BackColor = actColor; } private void button20_Click(object sender, EventArgs e) { button20.BackColor = actColor; } private void button21_Click(object sender, EventArgs e) { button21.BackColor = actColor; } private void button22_Click(object sender, EventArgs e) { button22.BackColor = actColor; } private void button23_Click(object sender, EventArgs e) { button23.BackColor = actColor; } private void button24_Click(object sender, EventArgs e) { button24.BackColor = actColor; } private void button25_Click(object sender, EventArgs e) { button25.BackColor = actColor; } private void button26_Click(object sender, EventArgs e) { button26.BackColor = actColor; } private void button27_Click(object sender, EventArgs e) { button27.BackColor = actColor; } private void button28_Click(object sender, EventArgs e) { button28.BackColor = actColor; } private void button29_Click(object sender, EventArgs e) { button29.BackColor = actColor; } private void button30_Click(object sender, EventArgs e) { button30.BackColor = actColor; } private void button31_Click(object sender, EventArgs e) { button31.BackColor = actColor; } private void button32_Click(object sender, EventArgs e) { button32.BackColor = actColor; } private void button33_Click(object sender, EventArgs e) { button33.BackColor = actColor; } private void button34_Click(object sender, EventArgs e) { button34.BackColor = actColor; } private void button35_Click(object sender, EventArgs e) { button35.BackColor = actColor; } private void button36_Click(object sender, EventArgs e) { button36.BackColor = actColor; } private void button37_Click(object sender, EventArgs e) { button37.BackColor = actColor; } private void button38_Click(object sender, EventArgs e) { button38.BackColor = actColor; } private void button39_Click(object sender, EventArgs e) { button39.BackColor = actColor; } private void button40_Click(object sender, EventArgs e) { button40.BackColor = actColor; } private void button41_Click(object sender, EventArgs e) { button41.BackColor = actColor; } private void button42_Click(object sender, EventArgs e) { button42.BackColor = actColor; } private void button43_Click(object sender, EventArgs e) { button43.BackColor = actColor; } private void button44_Click(object sender, EventArgs e) { button44.BackColor = actColor; } private void button45_Click(object sender, EventArgs e) { button45.BackColor = actColor; } private void button46_Click(object sender, EventArgs e) { button46.BackColor = actColor; } private void button47_Click(object sender, EventArgs e) { button47.BackColor = actColor; } private void button48_Click(object sender, EventArgs e) { button48.BackColor = actColor; } private void button49_Click(object sender, EventArgs e) { button49.BackColor = actColor; } private void button50_Click(object sender, EventArgs e) { button50.BackColor = actColor; } private void button51_Click(object sender, EventArgs e) { button51.BackColor = actColor; } private void button52_Click(object sender, EventArgs e) { button52.BackColor = actColor; } private void button53_Click(object sender, EventArgs e) { button53.BackColor = actColor; } private void button54_Click(object sender, EventArgs e) { button54.BackColor = actColor; } private void button55_Click(object sender, EventArgs e) { button55.BackColor = actColor; } private void button56_Click(object sender, EventArgs e) { button56.BackColor = actColor; } private void button57_Click(object sender, EventArgs e) { button57.BackColor = actColor; } private void button58_Click(object sender, EventArgs e) { button58.BackColor = actColor; } private void button59_Click(object sender, EventArgs e) { button59.BackColor = actColor; } private void button60_Click(object sender, EventArgs e) { button60.BackColor = actColor; } private void button61_Click(object sender, EventArgs e) { button61.BackColor = actColor; } private void button62_Click(object sender, EventArgs e) { button62.BackColor = actColor; } private void button63_Click(object sender, EventArgs e) { button63.BackColor = actColor; } private void button64_Click(object sender, EventArgs e) { button64.BackColor = actColor; } private void button65_Click(object sender, EventArgs e) { button65.BackColor = actColor; } //color {"x": int, "y": int, "r" : int, ....} public class colorTag { public int x { get; set; } public int y { get; set; } public int r { get; set; } public int g { get; set; } public int b { get; set; } } //SEND private void button4_Click(object sender, EventArgs e) { //lista List<colorTag> listOfColors = new List<colorTag>(); //sprawdzanie koloru kazdego przycisku, jesli jest inny niz transparent to wpisz do listy foreach (Control c in tableLayoutPanel2.Controls) { /* if(c.Tag == i.ToString()+j.ToString())*/ if(c.BackColor != Color.Transparent) { char[] characters = c.Tag.ToString().ToCharArray(); //zmieniamy tag na string na char[] //zeby zmienic go na xy //zeby zrobic wydobywanie pojedynczych cyfr //z typ object var cT = new colorTag { x = Int16.Parse(characters[0].ToString()), y = Int16.Parse(characters[1].ToString()), r = c.BackColor.R, g = c.BackColor.G, b = c.BackColor.B }; listOfColors.Add(cT); } } //tworzenie wynikowego json'a string json = JsonConvert.SerializeObject(listOfColors, Formatting.Indented); //odczytanie ip i portu z pliku konfiguracyjnego //sciezka do pliku config const string filePath = @"C:\Users\Klient\Documents\GitHub\RPiDG\DesktopApp\rpiDataGrabber\rpiDataGrabber\config.json"; configData deserialized = JsonConvert.DeserializeObject<configData>(File.ReadAllText(filePath)); string ip = deserialized.ip; string port = deserialized.port.ToString(); HttpClient client = new HttpClient(); var content = new StringContent(json.ToString(), Encoding.UTF8, "application/json"); var result = client.PostAsync("http://" + ip +":"+port+"/setLeds.php", content).Result; //sciezka do pliku colors const string filePath1 = @"C:\Users\Klient\Desktop\colors.json"; System.IO.File.WriteAllText(filePath1, json); } } }
63a94adc8e2eb61702954ff6ae3083085da8b287
[ "Markdown", "JavaScript", "Gradle", "Java", "C#", "Python", "Text", "PHP" ]
26
PHP
bmokr/RPiDG
a07b018c36ae9d015519485cc3263393048480c4
694be82c5fb9b680e3c4e76ecb8647b48ee7208d
refs/heads/master
<repo_name>trivedigaurav/wordtree-electron<file_sep>/regex.py import re import os, getopt, sys import json import csv debug = False def doSplit(root, inFile="lorem.csv"): global debug if (not root): # print "Error: No root word provided!" return # print "Searching for", '"'+root+'"', "in" , total, "files." phrases = [] count = 0 docid = 0 sentenceid = 0 with open(inFile, 'r') as csvfile: csvreader = csv.reader(csvfile) next(csvreader) for row in csvreader: docid += 1 report = row[0].replace("\r\n", "\n") regex = r"([^.:]*?"+root+"[^.\n]*\.)" matches = re.findall(regex, report) numfound = len(matches) if(numfound): count += 1 # TODO: calculate TF-IDF for match in matches: sentenceid += 1 phrases.append({"doc": docid, "id": sentenceid, "sentence": match}) tree = [] for key in phrases: p = key['sentence'] p = p.replace("\' s", "'s") p = p.replace("\n", " ") p = p.strip(' \t\n') if (p[-1] == "."): p = p[:-1] left = re.findall(r"[\w']+|[.,!?;]", p[:p.rfind(root)].strip()) right = re.findall(r"[\w']+|[.,!?;]", p[p.rfind(root)+len(root):].strip()) tree.append({"left": left, "right": right, "doc": key["doc"], "id": key["id"]}) # # if(debug): # # for node in tree: # # print node['left'], "-", root, "-", node['right'] # # print "Documents included: ", count, "/", total, "(", round(100.0 * count / total, 2), "% )" return (tree,count,docid) def prepareData(tree, root, matches, total): global debug # if (tree == []): # print "Warning: Empty tree!" data = {} data['matches'] = matches data['total'] = total data['query'] = root data['lefts'] = [] for node in tree: printnode = node.copy() printnode.pop("right") printnode["sentence"] = printnode.pop("left") data['lefts'].append(printnode) data['rights'] = [] for node in tree: printnode = node.copy() printnode.pop("left") printnode["sentence"] = printnode.pop("right") data['rights'].append(printnode) return data def writeFile(data, prefix, outFile="sample"): global debug sys.stdout.write(json.dumps(data)) sys.stdout.flush() def main(argv): global debug usage = sys.argv[0] + ' -w <word-root> [-i <lorem.csv>] [-o <outfile>]\n' root = None outFile = None inFile = "lorem.csv" try: opts, args = getopt.getopt(argv, "hdi:w:o:", ["ifile"]) except getopt.GetoptError: sys.stdout.write(usage) sys.exit(2) for opt, arg in opts: if opt in ["-h", "--help"]: sys.stdout.write(usage) sys.exit(0) elif opt in ("-i", "--infile"): inFile = os.path.abspath(arg) elif opt in ("-w", "--word"): root = arg elif opt in ("-d", "--debug"): debug = True elif opt in ("-o", "--outfile"): outFile = arg if (not root or not inFile): sys.stdout.write(usage) sys.exit(2) if (not outFile): outFile = root (tree,matches,total) = doSplit(root=root, inFile=inFile) data = prepareData(tree=tree, root=root, matches=matches, total=total) writeFile(data=data, prefix="tree", outFile=outFile) #This is for standalone execution if __name__ == "__main__": main(sys.argv[1:])<file_sep>/lib/wordtree-javafx-interface.js function getSentenceStats() { updateSentenceStats(data.matches); } function updateSentenceStats(matches){ total = data.total; percentange = 100*matches/total; // JavaFXApp.setLabelText("Documents included: "+ // matches+"/"+total+ // " ( "+percentange.toFixed(2)+"% ) "); } function updateFeedback(selected, root){ // JavaFXApp.updateFeedback(selected, root); }<file_sep>/README.md # wordtree-electron Simple GUI to explore wordtrees. ## To Use To clone and run this repository you'll need [Git](https://git-scm.com) and [Node.js](https://nodejs.org/en/download/) (which comes with [npm](http://npmjs.com)) installed on your computer. Currently, the project calls the python script from [wordtree-python-cmd](https://github.com/trivedigaurav/wordtree-python-cmd) to generate the wordtree. You need to have python on your system. By default, the tool loads [lorem.csv](lorem.csv) to build trees on. You can drag and drop another similarly formatted CSV file to analyze your text with the tool. From your command line: ```bash # Clone this repository git clone https://github.com/trivedigaurav/wordtree-electron # Go into the repository cd wordtree-electron # Install dependencies npm install # Run the app npm start ``` Note: If you're using Linux Bash for Windows, [see this guide](https://www.howtogeek.com/261575/how-to-run-graphical-linux-desktop-applications-from-windows-10s-bash-shell/) or use `node` from the command prompt. ## Warning! This tool is for exploration only. Do not use in production. <file_sep>/wordtree-controller.js /** Computes the hierarchical word tree data structure from the given data then calls {@link #drawWordTree}. Uses the wordtree Javascript library in lib/wordtree.js @param {WordSeer.view.visualize.wordtree.WordTree} the WordTree view into which to render the tree. @param {String} query The root query, the root of the tree. @param {Object} concordance An object with 'left' and 'right' fields, which contain a list of sentence fragments that occurred to the left and right of the search query. */ function makeWordTree(){ var detail = 100; for(var i = 0; i < data.lefts.length; i++){ data.lefts[i].sentence = data.lefts[i].sentence.reverse(); } var rightTree = makeWordTreeDataStructure(data.rights, data.query, detail, "right"); var leftTree = makeWordTreeDataStructure(data.lefts, "", detail, "left"); var w = $('body').innerWidth(), canvasWidth = w*10, h = $(document).height(); var container = '#word-tree' var containerClass = 'word-tree-container'; $(container).addClass(containerClass); var m = [20, 120, 20, canvasWidth/2]; // Get ready to draw the word tree by emptying this container and adding // a new empty SVG container. $('.'+containerClass).html(""); var svg = d3.select("."+containerClass).append("svg:svg") .attr("width", canvasWidth) .attr("height", h) var vis = svg.append("svg:g") .style("fill", "white") .attr("transform", "translate(" + m[3] + "," + m[0] + ")"); panel = $(container); vis.panel = panel; // Calculate the dimensions of this Word Tree depending on the container // width and height, and the number of total branches. vis.m =m; vis.svg = svg; vis.w = w - vis.m[1] - vis.m[3]; vis.h = h - vis.m[0] - vis.m[2]; vis.maxVisibleBranches = Math.max(leftTree.children.length, rightTree.children.length); vis.leftData = leftTree; vis.rightData = rightTree; vis.maxWordTreeNodeID = 0; vis.container = $(container); vis.wordtreeID = (new Date()).getTime(); this.drawTree(leftTree, "left", vis, w, h, panel) this.drawTree(rightTree,"right", vis, w, h, panel) } /** Draws a WordTree. @param {Object} data The hierarchical data structure containing the word tree. Each node (including the root) has the following fields: - {Number} x0, y0, x, y Positions - {Number} count The number of sentences under this node. - {Number} id The identifier of this node. - {Boolean} isRoot Whether or not this node is the root. - {Number} depth The depth of this node. - {Array} ids The node ids of this node. - {Array} children The list of visible children of this node. - {Array} all_chilren The list of children of htis node - {Array} hidden_chilren a list of hidden children of this node. - {String} key The word or word sequence at this node. - {Boolean} expanded Whether or not this node is visible - {Boolean} selected Whether or not this node was selected for expansion by the user. @param {String} orientation "left" or "right", the side of the tree currently being drawn @param {WordSeer.view.visualize.wordtree.WordTree} the view in which the wordtree is currently being drawn. */ function drawTree(data, orientation, vis, width, height){ root = data; root.isRoot = true; if(orientation == "left"){ vis.leftData = root }else{ vis.rightData = root } vis.selectedIDs = []; vis.selectedNodeIDs = {left:[], right:[]}; vis.selectedNodes = {left: [], right: []}; // Initialize the display to show only one level of nodes. root.children.forEach(function(child){ toggleAll(child) // turn off all children of children }); // A function that calculates the total height of the tree, depending // on the number of visible branches. vis.treeHeight = function(){ var vis = this; var treeHeight = 20*vis.maxVisibleBranches; var svgHeight = Math.max(treeHeight+vis.m[0], 100); vis.svg.attr("height", svgHeight); vis.h = svgHeight; return treeHeight } // Initalize the tree layout algorithm from the D3 visualization library. vis.tree_layout = d3.layout.tree() .size([vis.treeHeight(), vis.w]) .sort(function(a, b){ return b.count - a.count;}) .separation(function(a, b){ return fontSize(a)+fontSize(b)/2}); vis.diagonal = d3.svg.diagonal() .projection(function(d) {return [d.y, d.x]; }); updateWordTreeNode(root, orientation, root, vis); } /** Calculates the font size of a node based on how many sentences are below it. @param {Object} d The node whose font size to calculate. */ function fontSize(d){ if(d.isRoot){ return 40 }else{ return Math.min(35, 2*Math.sqrt(d.count)+7) } } /** Calculates the width of a node. @param {Object} d The node whose width to calculate. */ function width(d){ return fontSize(d) * d.key.length * 0.7 } /** Called after any change to the word tree or when it's first rendered. Recursively moves nodes to their positions, and shows and hides them depending on whether they are expanded or not. @param {Object} source The parent node. @param {String} orientation Either 'left' or 'right' -- which tree we're drawing. @param {Object} root The root of this tree @param {SVGElement} vis The SVG element that is being drawn into. */ function updateWordTreeNode(source, orientation, root, vis) { var diagonal = vis.diagonal; var sign = (orientation == "left")?-1:1; var duration = d3.event && d3.event.altKey ? 5000 : 500; // Compute the new tree layout. Calculate the number of visible nodes // and place the root at the center. root.x0 = Math.min(vis.treeHeight()/2, 150); root.y0 = 0; // Hierarchially compute new x and y values for each node in the tree // using the D3 visualization library. vis.tree_layout.size([vis.treeHeight(), vis.w]); var nodes = vis.tree_layout.nodes(root); // Normalize for the length of the longest strings, and // move the root to the top of its child tree instead of // the center. calculateDepths(root, vis, sign); // Correct positions for left-right orientation if(orientation == "left"){ nodes.forEach(function(d){ d.y = -d.y; if(d.isRoot){ vis.leftData = d } }) }else{ nodes.forEach(function(d){ if(!d.isRoot){ d.y = d.y-50; }else{ vis.rightData = d; } }) } // Update the visualization to reflect the new node positions. var node = vis.selectAll("g.node"+"."+orientation) .data(nodes, function(d) { // If the nodes don't have ID's assign them id's. return d.id || (d.id = ++vis.maxWordTreeNodeID); }); // Start any newly-appearing nodes at the parent's previous position. var nodeEnter = node.enter().append("svg:g") .attr("class", "node "+orientation) .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; }) .on("click", function(d){ wordTreeNodeClick(node, d, orientation, root, vis, "click") }) // .on("contextmenu", function(d){ // d3.event.preventDefault(); // vis.panel.fireEvent('nodecontextmenu', // this, d,orientation, root, vis, "contextmenu"); // }) .on("mouseover", function(d){ wordTreeNodeMouseOver(node, d, orientation, root, vis, "mouseover") }) .on("mouseout", function(d){ wordTreeNodeMouseOut(node, d, orientation, root, vis, "mouseout") }); var padding = 5; var getNodeClasses = function(d) { var childrenState = d.all_children.length > 0? 'tree':'leaf' var filteredState = ""; if(vis.selectedNodeIDs[orientation].contains(d.id)){ filteredState = " selected"; } var sentenceIDs = ""; var docIDs = ""; if (d.ids) { for (var i = 0; i < d.ids.length; i++) { sentenceIDs += " wordtree-"+vis.wordtreeID+"-sentence-"+d.ids[i]; //TODO add wordtree id 2012-07-23 11:45 GMT-7 docIDs += " wordtree-doc-"+d.docs[i]; } } var classes = childrenState + filteredState + sentenceIDs + docIDs; return classes; } nodeEnter.append("svg:text") .attr("x", function(d) { if(d.isRoot){ return 0 }else{ return orientation == "left"? -padding/2:padding/2; } }) .attr("fill", "black") .attr("dy", ".35em") .attr("id", function(d){return "text-"+d.id+"-wordtree-"+vis.wordtreeID}) .attr("text-anchor",function(d){ return orientation=="left"?"end":"start" }) .attr("class", getNodeClasses) .text(function(d) { return d.key; }) .style("fill-opacity", 1e-6) .attr("font-size", fontSize); // Transition nodes to their new position. var nodeUpdate = node.transition() .duration(duration) .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; }); nodeUpdate.select("text") .attr("class", getNodeClasses) .style("fill-opacity", 1); // Transition exiting nodes to the parent's new position. var nodeExit = node.exit().transition() .duration(duration) .attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; }) .remove(); nodeExit.select("text") .style("fill-opacity", 1e-6); // Update the links between nodes. var link = vis.selectAll("path.link."+orientation) .data(vis.tree_layout.links(nodes), function(d) { return d.target.id; }); // Enter any new links at the parent's previous position. link.enter().insert("svg:path", "g") .attr("class", "link "+orientation) .attr("fill", "none") .attr("stroke", "orange") .attr("stroke-width", ".5px") .attr("d", function(d) { var bbox = d3.select("#text-"+source.id+"-wordtree-"+vis.wordtreeID)[0][0].getBBox(); var o = {x: source.x0, y: source.y0+((padding+bbox.width)*sign)}; return vis.diagonal({source: o, target: o}); }) .transition() .duration(duration) .attr("d", function(d){ var sourceBox = d3.select("#text-"+d.source.id+"-wordtree-"+vis.wordtreeID)[0][0].getBBox(); var s = {x: d.source.x, y: d.source.y+((padding+sourceBox.width)*sign)}; return vis.diagonal({source:s, target:d.target}) }); // Transition links to their new position. link.transition() .duration(duration) .attr("d", function(d){ var sourceBox = d3.select("#text-"+d.source.id+"-wordtree-"+vis.wordtreeID)[0][0].getBBox(); var s = {x: d.source.x, y:d.source.y+((padding+sourceBox.width)*sign)}; return vis.diagonal({source:s, target:d.target}) }); // Transition exiting links to the parent's new position. link.exit() .transition() .duration(duration) .attr("d", function(d) { var bbox = d3.select("#text-"+source.id+"-wordtree-"+vis.wordtreeID)[0][0].getBBox(); var o = {x: source.x0, y: source.y0-((padding+bbox.width)*sign)}; return vis.diagonal({source: o, target: o}); }) .remove(); // Stash the old positions for transition. nodes.forEach(function(d) { d.x0 = d.x; d.y0 = d.y; }); // Scroll the container of this word tree so that the root of the // tree is in view. // window.scrollTo('51%', {duration:1, axis:'x'}); window.scrollTo(($(document).width()-$(window).width())*.51,0); } /** Recursively repositions the x-value of tree nodes starting at the given node, to avoid overlapping text by moving them all to avoid the longest string at each level. Also calls {@link #adjustHeight} to move the node to the top of its child tree. @param {Object} d The node to reposition. @param {SVGElement} The main SVG canvas element. @param {Number} sign The sign of the adjustment to x, either -1 or +1. -1 if we're drawing the left tree, +1 if we're drawing the right tree. */ function calculateDepths(d, vis, sign){ if(d.isRoot){ d.y = d.y0; d.x = d.x0; d.depth = 0; }else{ if(d.parent.isRoot){ d.y = width(d.parent)+50; d.depth = 1; }else{ var maxWidth = -1; d.parent.parent.children.forEach(function(node){ var w = width(node); if(w > maxWidth && node.children.length > 0){ maxWidth = w } }) maxWidth = Math.max(maxWidth, 50); d.y = d.parent.y + maxWidth; d.depth = d.parent.depth + 1; } adjustHeight(d); } d.hidden_children = []; d.children.forEach(function(d){ calculateDepths(d, vis, sign) }); } /** To improve readability, recursively adjusts the y value (height) of parent nodes to the tops of their child trees (from the centers, where the D3 algorithm) positions them. @param {Object} d The node at which to start repositioning. */ function adjustHeight(d){ if(!d.isRoot){ var minX = d.x; d.children.forEach(function(node){ if(!minX){ minX = node.x } if(node.x < minX){ minX = node.x } }) var newX = Math.min(minX+20, d.x); if (newX != d.x){ d.x = newX; adjustHeight(d.parent); } } } /** Called when a word tree node is clicked or double clicked. For clicking, if the node was already selected, this deselcts it, and vice versa. Clicking a node filters the word tree to show only the sentences that 'pass through' that node. This list of sentences is stored in the 'ids' attribute of each node. Double clicking a node makes a difference (from just clicking a node) when there are already some filters active. Double clicking resets the filter to \ only filter take into account that node. @param {SVGElement} node The svg element representing the node that was hovered over. @param {Object} d The object containing the data for the node that was clicked. @param {String} orientation Either 'left' or 'right', which tree we're drawing. @param {Object} root The root of this tree. @param {SVGElement} vis The svg canvas we're drawing into. @param {String} clickType either "click" or "dbclick". */ function wordTreeNodeClick(node, d, orientation, root, vis, clickType){ // Calculate which nodes should be collapsed or expanded. // If it's the root node that was clicked, then reset the filters. if(d.isRoot){ vis.selectedIDs = []; vis.selectedNodeIDs = {left:[], right:[]}; vis.selectedNodes = {left: [], right: []}; vis.filterDepth = 0; vis.filterOrienation = null; } // If it was a double click, or there are no active filters, first // reset the filters and then add the ID's for that node as the // selected ID's. else if(vis.selectedIDs.length == 0 || clickType == "dblclick"){ vis.selectedIDs = d.ids; vis.selectedNodeIDs = {left:[], right:[]}; vis.selectedNodes = {left: [], right: []}; vis.selectedNodeIDs[orientation] = [d.id]; vis.selectedNodes[orientation] = [d]; vis.filterDepth = d.depth; vis.filterOrientation = orientation; toggle(d); } // If there are active filters, restrict the active filters to the // just the list of ID's passing through this node. else{ // toggle(d); if((d.depth > vis.filterDepth && orientation == vis.filterOrientation) || orientation != vis.filterOrientation){ // sub-filtering in progress vis.filterDepth = d.depth; vis.selectedNodeIDs[orientation].push(d.id) vis.selectedNodes[orientation].push(d); var intersection = [] d.ids.forEach(function(id){ if(vis.selectedIDs.contains(id)){ intersection.push(id) } }) vis.selectedIDs = intersection; vis.filterOrientation = orientation; }else if(d.depth < vis.filterDepth && orientation == vis.filterOrientation){ // backtracking up the tree vis.selectedIDs = d.ids; vis.selectedNodeIDs = {left:[], right:[]}; vis.selectedNodeIDs[orientation] = [d.id]; vis.selectedNodes[orientation] = [d.id]; vis.filterDepth = d.depth; vis.filterOrientation = orientation; } } // Apply the filter to the other tree, so nodes in the sentences that // should be hidden or shown because of new filters can be hidden // or shown as well. var otherRoot = (orientation == "right")? vis.leftData:vis.rightData; var otherOrientation = orientation == "right" ? "left" : "right"; vis.leftVisibleBranches = 0; vis.rightVisibleBranches = 0; showSentences(vis.selectedIDs, root, vis, orientation) showSentences(vis.selectedIDs, otherRoot, vis, otherOrientation); // Re-display the nodes. vis.maxVisibleBranches = Math.max(vis.leftVisibleBranches, vis.rightVisibleBranches); updateWordTreeNode(d, orientation, root, vis); updateWordTreeNode(otherRoot, otherOrientation, otherRoot, vis); // Compute the selected phrase. var selected_phrase = ""; var root_phrase = ""; for (var i = vis.selectedNodes.left.length-1; i >= 0; i--) { selected_phrase += vis.selectedNodes.left[i].key +" "; } if (vis.leftData.key.length > 0) { selected_phrase += vis.leftData.key +" "; root_phrase += vis.leftData.key +" "; } if (vis.rightData.key.length > 0) { selected_phrase += vis.rightData.key + " "; root_phrase += vis.rightData.key + " "; } for (var i = 0; i < vis.selectedNodes.right.length; i++) { selected_phrase += vis.selectedNodes.right[i].key +" "; } // Update stats if(d.isRoot){ getSentenceStats(); } else{ updateSentenceStats(d.ids.length); } // Update feedback updateFeedback(selected_phrase.trim(), root_phrase.trim()); // $(vis.container).trigger('filter', [selected_phrase.trim(), // main_phrase.trim()]); } /** Show or hide the immediate children of the given node. If they are visible, hide them. If they are not visible, show them. @param {Object} d The node whose children should be hidden. */ function toggle(d) { if (d.children.length > 0) { hideChildren(d); } else { showChildren(d); } } /** Recursively show or hide all the descendants of the given node. If they are visible, hide them. If they are not visible, show them. @param {Object} d The node whose children should be hidden. */ function toggleAll(d) { if (d.children) { d.children.forEach(function(child){ toggleAll(child) }); toggle(d); } } /** Hide the children of the given node. @param {Object} d The node whose children should be hidden. */ function hideChildren(d) { d.hidden_children = d.all_children; d.children = [] } /** Show the children of the given node. @param {Object} d The node whose children should be hidden. */ function showChildren(d){ d.children = d.all_children; d.hidden_children = []; } /** Recursively hide or show a nodes upto a certain depth depending on how many sentences there are in this tree @param {Array[Number]} The list of visible sentence IDs. */ function showSentences(ids, tree, vis, thisOrientation){ // fanOut is the depth to which to show nodes. var fanOut = (ids.length < 50)? 10 : (ids.length < 100)? 3: (ids.length < 200)? 3 : 1; // If there are sentences in this filter, recursively travel the // tree and mark nodes visible if they span one of these sentences. if(ids.length > 0){ tree.children = []; tree.all_children.forEach(function(t){ t.selected = false; ids.forEach(function(id){ if(t.ids.contains(id)){ t.selected = true; } }) if(t.selected){ // Show the nodes of this tree upto a certain depth var show = false; if(thisOrientation == vis.filterOrientation){ if(t.depth <= vis.filterDepth + fanOut ){ show = true } }else{ if(t.depth <= fanOut){ show = true } } if(show){ if(thisOrientation == "left"){ vis.leftVisibleBranches += 1; }else{ vis.rightVisibleBranches += 1; } showSentences(ids, t, vis, thisOrientation); tree.children.push(t); } } }) } // If there are no selected sentences (i.e. there is no active filter) // reset the tree nodes' visibility to their original state. else{ // Show the children of the root if(tree.isRoot){ showChildren(tree); tree.children.forEach(function(child){ hideChildren(child); }) if(thisOrientation == "left"){ vis.leftVisibleBranches = tree.children.length; }else{ vis.rightVisibleBranches = tree.children.length; } } } } /** When the user hovers over a node, shows contextual information. If the node is not a leaf, it shows a popup with the number of sentences under the node. If the node is a leaf, it highlights all the nodes corresponding to the sentence, and shows a sentence popup. @param {SVGElement} node The svg element representing the node that was hovered over. @param {Object} d The object containing the data for the node that was clicked. @param {String} orientation Either 'left' or 'right', which tree we're drawing. @param {Object} root The root of this tree. @param {SVGElement} vis The svg canvas we're drawing into. @param {String} clickType either "click" or "dbclick". */ function wordTreeNodeMouseOver(node, d, orientation, root, vis, eventName){ // Do nothing if the root is hovered over. if(!d.isRoot){ ids = d.ids // console.log(ids); for (var i = 0; i < ids.length; i++) { // var nodes = $( ('*[class~="wordtree-' + // vis.wordtreeID +'-sentence-'+ids[i]+'"]')); d3.selectAll('*[class~="wordtree-' + vis.wordtreeID +'-sentence-'+ids[i]+'"]').classed("wordtree-highlight-sentence", true) // for (var j = 0; j < nodes.length; j++) { // // console.log('#'+nodes[j].id) // var element = document.getElementById(nodes[j].id); // var old_class = element.getAttribute("class"); // console.log(old_class); // element.setAttribute("old-classes", old_class); // element.setAttribute("class", old_class + " wordtree-highlight-sentence"); // } } } // if(!d.isRoot){ // // If the hovered node is not a leaf, show a popup with the number. // if(d.all_children.length > 1){ // // Remove the previous popups. // removePopup(vis.popup); // if (vis.number_popup) { // vis.number_popup.remove(); // } // vis.number_popup = d3.select(node).append("svg:text") // .attr("x", -15*(orientation=="left"?-1:1)) // .attr("y", -10) // .attr("id", "number-popup") // .text("("+d.ids.length+")") // .attr("font-size", 10) // .attr("class", "number-popup"); // } // // If the hovered node is a leaf, ask the server for details // // about the sentence, and highlight the nodes corresponding to // // this sentence. // else { // // Get the sentence ID of the leaf -- since it's a leaf, there's // // only one ID. // var id = d.ids[0]; // // Highlight the nodes corresponding to this sentence by adding // // a CSS class to those SVG elements. // var nodes = $( ('*[class~="wordtree-' + // vis.wordtreeID +'-sentence-'+id+'"]')); // for (var i = 0; i < nodes.length; i++) { // var old_class = $('#'+nodes[i].id).attr("class"); // $('#'+nodes[i].id).attr("old-classes", old_class); // $('#'+nodes[i].id).attr("class", // old_class+" wordtree-highlight-sentence"); // } // // // Only ask for a popup after 0.5 seconds, so that passing // // // mouseovers don't cause popups to appear. // // vis.event = d3.event; // // vis.mouseoverTimeout = setTimeout(function(){ // // getMetadataForSentenceNode(node, id, orientation, vis) // // }, 100); // } // } } /** Requests details about the hovered-over sentence from the server. The server responds with a JSON object containing the following fields: - {String} sentence: The full sentence. - {String} title: The title of the document to which the sentence belongs. - {Object} metadata: Objects with name: and value: fields for metadata belonging to this sentence. @param {SVGElement} node: The svg element displaying the node that was hovered over. @param {Number} sentenceID The ID of the sentence about which to request information. @param {String} orientation 'left' or 'right' -- the side of the tree that we're drawing. #@param {SVGElement} vis The SVGElement in which the word tree is being drawn. */ // function getMetadataForSentenceNode(node, sentenceID, orientation, vis){ // Ext.Ajax.request({ // url:'../../src/php/strip-vis/getsentence.php', // method:'GET', // disableCaching: false, // params:{ // id:sentenceID, // wordtree:'true', // instance:getInstance(), // user:getUsername(), // }, // scope:this, // success:function(response){ // var data = Ext.decode(response.responseText); // var sentence = {}; // sentence.words = data.words; // sentence.sentenceID = data.sentence_id; // sentence.documentID = data.document_id; // sentence.metadata = data.metadata; // if (vis.number_popup) { // vis.number_popup.remove(); // } // this.getController('SentencePopupController') // .removePopup(vis.popup); // vis.popup = Ext.create( // 'WordSeer.view.visualize.wordtree.SentencePopup', // { // sentences: [sentence], // }); // vis.popup.show(); // vis.popup.setPosition(vis.event.pageX+20, // vis.event.pageY+20); // } // }) // } /** Called when the user mouses away from a node. @param {SVGElement} node The svg element representing the node that was hovered over. @param {Object} d The object containing the data for the node that was clicked. @param {String} orientation Either 'left' or 'right', which tree we're drawing. @param {Object} root The root of this tree. @param {SVGElement} vis The svg canvas we're drawing into. @param {String} clickType either "click" or "dbclick". */ function wordTreeNodeMouseOut(node, d, orientation, root, vis, eventName){ // // clearTimeout(vis.mouseoverTimeout); //cancel queued popup // if (vis.popup) { // var popup = vis.popup; // var number_popup = vis.number_popup; // destroySentencePopupTimeOut = setTimeout(function(){ // removePopup(popup); // if (number_popup){ // number_popup.remove(); // } // }, 1000); // } // Remove the highlight that was applied to the nodes when the user // hovered over them, by restoring the old CSS class which we stored in // the 'old-classes' attribute. d3.selectAll('*[class~="wordtree-highlight-sentence"]').classed("wordtree-highlight-sentence", false) // var nodes = $('*[class~="wordtree-highlight-sentence"]'); // for (var i = 0; i < nodes.length; i++) { // $('#'+nodes[i].id).attr("class", $('#'+nodes[i].id).attr("old-classes")); // $('#'+nodes[i].id).attr("old-classes", ""); // } } function addDocClass(ids, classname){ d3.selectAll('*[class~="wordtree-doc-' + ids+'"]').classed(classname, true); } function removeDocClass(ids, classname){ d3.selectAll('*[class~="wordtree-doc-' + ids+'"]').classed(classname, false); } /** Utils **/ /** checks if an array <a> contains an object <obj>**/ Array.prototype.contains = function(obj) { var i = this.length; while (i--) { if (this[i] === obj) { return true; } } return false; } /** Sentence Popup Controller **/ /** Destroys the sentence popup that appeared when a user last hovered a node. @param {WordSeer.view.visualize.wordtree.SentencePopup} popup The sentence popup. */ // function removePopup(popup) { // if (popup) { // if (!popup.isHovered) { // if (popup.destroy) { // popup.destroy(); // } // else { // popup.destroy(); // } // } // } // } /** Prevents the sentence popup from fading away. @param {WordSeer.view.visualize.wordtree.SentencePopup} popup The sentence popup. */ // function sentencePopupMouseEnter(popup) { // popup.isHovered = true; // } // * Sets a timeout for the the sentence popup to fade away 0.5s after the // user's mouse leaves it. // @param {WordSeer.view.visualize.wordtree.SentencePopup} popup The sentence // popup. // function sentencePopupMouseOut(popup) { // popup.isHovered = false; // destroySentencePopupTimeOut = setTimeout(function(){ // removePopup(popup); // }, 500); // } /** Called when the 'go to text' button in the {@link WordSeer.view.visualize.wordtree.SentencePopup} is clicked. Calls the DocumentsController's {@link WordSeer.controller.DocumentsController#openDocument} method with the {@link WordSeer.view.visualize.wordtree.SentencePopup#documentId} and {@link WordSeer.view.visualize.wordtree.SentencePopup#sentenceId} of the sentence in the popup. */ // function sentencePopupGoToText(button) { // var index = button.index; // var popup = button.up('sentence-popup'); // var sentence = popup.getSentences()[index]; // this.getController('DocumentsController').openDocument( // sentence.documentID, sentence.sentenceID); // }
0ed28165e9e54eb6cd96a9207099657a4db31232
[ "JavaScript", "Python", "Markdown" ]
4
Python
trivedigaurav/wordtree-electron
72725fbaed3beefe37e0dda264395c17d343fb61
2805be86d7633b5ecae80dbfa46552e4fa0e6f24
refs/heads/master
<repo_name>allison-johnson/scraping-reading-online-web-ft-120919<file_sep>/lib/scraper.rb require 'nokogiri' require 'open-uri' html = open("https://flatironschool.com/") doc = Nokogiri::HTML(html) #puts doc.css(".headline-26OIBN").text p doc.css(".title-oE5vT4")[0].attributes # courses.each do |course| # puts course.text # end
66170b8b720097b56faa4f662744dc406c4b1694
[ "Ruby" ]
1
Ruby
allison-johnson/scraping-reading-online-web-ft-120919
adb9ebc71e36b20601032253a417950fbeafc321
f3a1576bbd844d6821e29f185d74f6b92e730ea2
refs/heads/master
<file_sep>// // ISSAPI.swift // ISS Pager // // Created by <NAME> on 12/21/16. // Copyright © 2016 Dedual Enterprises Inc. All rights reserved. // import Foundation import Moya private func JSONResponseDataFormatter(data: Data) -> Data { do { let dataAsJSON = try JSONSerialization.jsonObject(with: data, options: []) let prettyData = try JSONSerialization.data(withJSONObject: dataAsJSON, options: .prettyPrinted) return prettyData } catch { return data //fallback to original data if it cant be serialized } } let endpointClosure = {(target:ISSAPI) -> Endpoint<ISSAPI> in let url = target.baseURL.appendingPathComponent(target.path).absoluteString let endpoint:Endpoint<ISSAPI> = Endpoint<ISSAPI>(url: url, sampleResponseClosure: {.networkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters) return endpoint } struct ISSNetwork { static let provider = MoyaProvider<ISSAPI>(endpointClosure:endpointClosure, plugins: [NetworkLoggerPlugin(verbose: false, responseDataFormatter: JSONResponseDataFormatter)]) static func request( target: ISSAPI, success successCallback: @escaping (Any) -> Void, error errorCallback: @escaping (_ statusCode: Response) -> Void, failure failureCallback: @escaping (Moya.Error) -> Void ) { provider.request(target, completion: { result in switch result { case let .success(response): do { _ = try response.filterSuccessfulStatusCodes() let json = try response.mapJSON() successCallback(json) } catch { errorCallback(response) } case let .failure(error): failureCallback(error) } }) } } enum ISSAPI { case CurrentLocation() case PassTimes(lat:Double, lng:Double) } extension ISSAPI:TargetType { var baseURL:URL {return URL(string:"http://api.open-notify.org")!} var path:String { switch self { case.CurrentLocation(): return "/iss-now.json" case .PassTimes(_,_): return "/iss-pass.json" } } var method:Moya.Method { switch self { case .CurrentLocation, .PassTimes: return .get } } var parameters:[String:Any]? { switch self { case.CurrentLocation(): return nil case .PassTimes(let lat, let lng): return ["lat":lat, "lon":lng] } } public var task: Task { switch self { case .CurrentLocation, .PassTimes: return .request } } var sampleData:Data { switch self { case.CurrentLocation(): let returnString = "{\"timestamp\": 1482380125, \"message\": \"success\", \"iss_position\": {\"longitude\": \"-112.7691\", \"latitude\": \"-24.8663\"}}" return returnString.UTF8EncodedData case .PassTimes(_, _): let returnString = "{\"message\": \"success\",\"request\": {\"altitude\": 100,\"datetime\": 1482373586,\"latitude\":40.825133,\"longitude\": -73.9540127,\"passes\": 5},\"response\": [{\"duration\": 310,\"risetime\": 1482410637},{\"duration\": 626,\"risetime\": 1482416221},{\"duration\": 615,\"risetime\": 1482422021},{\"duration\": 552,\"risetime\": 1482427892},{\"duration\": 581,\"risetime\": 1482433727}]}" return returnString.UTF8EncodedData } } } <file_sep>// // ISSViewAReminderViewController.swift // ISS Pager // // Created by <NAME> on 12/22/16. // Copyright © 2016 Dedual Enterprises Inc. All rights reserved. // import UIKit import MapKit import CoreLocation // note: we need to confirm that whenever we update a reminder we're updating, not instantiating a new one. -<NAME>. class ISSViewAReminderViewController: UITableViewController { // MARK: - Variables // shortcuts to text fields var nameTextField:UITextField! var addressTextField:UITextField! @IBOutlet var mapCell:MapTableViewCell! var tempPlacemark:CLPlacemark? { didSet { // create a suitable ISSReminder and update the tableview if newReminder != nil, self.tempPlacemark != nil { if let nameText = nameTextField.text { newReminder!.name = nameText } let streetComponent = (tempPlacemark?.subThoroughfare ?? "") + " " + (tempPlacemark?.thoroughfare ?? "") let cityComponent = tempPlacemark?.locality ?? "" let stateComponent = tempPlacemark?.administrativeArea ?? "" let postalCodeComponent = tempPlacemark?.postalCode ?? "" let countryCode = tempPlacemark?.country ?? "" newReminder!.address = streetComponent + " " + cityComponent + ", " + stateComponent + ", " + countryCode + ", " + postalCodeComponent // do we want to change the user-entered address? To be decided later, Nick. } } } var newReminder:ISSReminder? //MARK: - Initializers class func detailViewControllerForReminder(_ reminder: ISSReminder) -> ISSViewAReminderViewController { let viewController = ISSViewAReminderViewController(reminder: reminder) return viewController } init(placemark:CLPlacemark? = nil, reminder:ISSReminder? = nil) { super.init(style: .grouped) self.newReminder = reminder ?? ISSReminder() self.tempPlacemark = placemark } required convenience init?(coder aDecoder: NSCoder) { self.init(placemark: nil) } convenience override init(style:UITableViewStyle) { self.init(placemark: nil) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. Bundle.main.loadNibNamed("RemindersDetailMainCell", owner: self, options: nil) Bundle.main.loadNibNamed("MapCell", owner: self, options: nil) self.title = "Reminder" // Determine if view is added modally. If so, add close button let dismissButton:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(ISSViewAReminderViewController.close(_:))) if(self.isModal()) { self.navigationItem.leftBarButtonItem = dismissButton } //Looks for single or multiple taps. let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ISSViewAReminderViewController.dismissKeyboard)) //Uncomment the line below if you want the tap not not interfere and cancel other interactions. //tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func dismissKeyboard() { //Causes the view (or one of its embedded text fields) to resign the first responder status. view.endEditing(true) } @IBAction func close(_ sender:UIButton?) { self.dismiss(animated: true) { } } @IBAction func saveChanges(sender:UIButton?) { // save changes made to form // load all saved reminders var allReminders:[ISSReminder] = [] if let savedItems = UserDefaults.standard.array(forKey: kSavedItemsKey) { for savedItem in savedItems { if let regionToMonitor = NSKeyedUnarchiver.unarchiveObject(with: savedItem as! Data) as? ISSReminder { allReminders.append(regionToMonitor) } } } // save the new one if let reminder = self.newReminder { allReminders.append(reminder) let items = NSMutableArray() for aReminder in allReminders { let item = NSKeyedArchiver.archivedData(withRootObject: aReminder) items.add(item) } UserDefaults.standard.set(items, forKey: kSavedItemsKey) UserDefaults.standard.synchronize() } else { // throw alert here. Something's wrong } } func isModal() -> Bool { if self.presentingViewController != nil { return true } else if self.navigationController?.presentingViewController?.presentedViewController == self.navigationController { return true } else if self.tabBarController?.presentingViewController is UITabBarController { return true } return false } //MARK: - Forward Geocoding methods func forwardGeocode(inputAddress:String, completed: @escaping (_ finished:Bool, _ error:Error?, _ placemark:CLPlacemark?) -> ()) { let geocoder = CLGeocoder() geocoder.geocodeAddressString(inputAddress) { (placemarks, error) in if error != nil { // handle error here completed(false, error, nil) } else { completed(true, nil, placemarks?.last) } } } //MARK: - Reverse Geocoding methods // we might need to move this one away from here, it's not being used right now and proably will be later on. func reverseGeocode(inputCoordinate:CLLocation, completed: @escaping (_ finished:Bool, _ error:Error?, _ placemark:CLPlacemark?) -> ()) { let geocoder = CLGeocoder() geocoder.reverseGeocodeLocation(inputCoordinate) { (placemarks, error) in if error != nil { // handle error here completed(false, error, nil) } else { completed(true, nil, placemarks?.last) } } } // MARK: - TableView Delegates and Data Sources override func numberOfSections(in tableView: UITableView) -> Int { if self.tempPlacemark != nil || self.newReminder?.arrivalTimes != nil { return (self.newReminder?.arrivalTimes!.count)! > 0 ? 5 : 3 } else { return 3 } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 3: return (self.newReminder?.arrivalTimes!.count)! default: return 1 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch(indexPath.section) { case 0: // Name var cell = tableView.dequeueReusableCell(withIdentifier: "RemindersDetailMainCell") as? RemindersDetailMainCell if cell == nil { tableView.register(UINib(nibName: "RemindersDetailMainCell", bundle: nil), forCellReuseIdentifier: "RemindersDetailMainCell") cell = tableView.dequeueReusableCell(withIdentifier: "RemindersDetailMainCell") as? RemindersDetailMainCell } cell!.label.text = "Name" if let name = self.newReminder?.name { cell!.textfield.text = name } else { cell!.textfield.placeholder = "Enter a name here" } self.nameTextField = cell!.textfield // for quick reference self.nameTextField.delegate = self return cell! case 1: // Address var cell = tableView.dequeueReusableCell(withIdentifier: "RemindersDetailMainCell") as? RemindersDetailMainCell if cell == nil { tableView.register(UINib(nibName: "RemindersDetailMainCell", bundle: nil), forCellReuseIdentifier: "RemindersDetailMainCell") cell = tableView.dequeueReusableCell(withIdentifier: "RemindersDetailMainCell") as? RemindersDetailMainCell } cell!.label.text = "Address" if let address = self.newReminder?.address { cell!.textfield.text = address } else { cell!.textfield.placeholder = "Enter an address here" } self.addressTextField = cell!.textfield // for quick reference self.addressTextField.delegate = self return cell! case 2: // Map if tempPlacemark != nil { // point the map to our placemark let region = MKCoordinateRegionMakeWithDistance(self.tempPlacemark!.location!.coordinate, 200, 200); // not entirely safe, I know self.mapCell.mapview.region = region; // add a pin using self as the object implementing the MKAnnotation protocol self.mapCell.mapview.addAnnotation(self) return self.mapCell; } else if let count = self.newReminder?.arrivalTimes?.count, count > 0 { let region = MKCoordinateRegionMakeWithDistance(self.newReminder!.location.coordinate, 200, 200); // not entirely safe, I know self.mapCell.mapview.region = region; // add a pin using self as the object implementing the MKAnnotation protocol self.mapCell.mapview.addAnnotation(self) return self.mapCell; } else { //save button goes here var cell = tableView.dequeueReusableCell(withIdentifier: "basicCellButton") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "basicCellButton") cell?.selectionStyle = .none } if let subviews = cell?.contentView.subviews // make sure that nothing funky's going on with how Apple preserves views { for aSubview in subviews { aSubview.removeFromSuperview() } } let button = UIButton(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height:44)) button.backgroundColor = UIColor.green button.setBackgroundImage(UIImage.fromColor(.green),for: .normal) button.setBackgroundImage(UIImage.fromColor(UIColor.init(red: 0.0, green: 0.6, blue: 0.0, alpha: 1.0)), for: UIControlState.highlighted) button.setTitleColor(UIColor.white, for: .normal) button.setTitle("SAVE CHANGES", for: .normal) button.titleLabel?.textAlignment = .center button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17.0) button.addTarget(self, action: #selector(ISSViewAReminderViewController.saveChanges(sender:)), for: .touchUpInside) cell?.contentView.addSubview(button) return cell! } case 3: // Next ISS Viewing OR save button (if there's no placemark var cell = tableView.dequeueReusableCell(withIdentifier: "basicCell") if cell == nil { cell = UITableViewCell(style: .subtitle, reuseIdentifier: "basicCell") cell?.selectionStyle = .none } let arrivalTimeObject = (self.newReminder?.arrivalTimes?[indexPath.item])! cell?.textLabel?.text = arrivalTimeObject.riseTime.humanReadableDate cell?.detailTextLabel?.text = "Duration: \(arrivalTimeObject.duration!) seconds" return cell! case 4: // Save changes var cell = tableView.dequeueReusableCell(withIdentifier: "basicCellButton") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "basicCellButton") cell?.selectionStyle = .none } if let subviews = cell?.contentView.subviews // make sure that nothing funky's going on with how Apple preserves views { for aSubview in subviews { aSubview.removeFromSuperview() } } let button = UIButton(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height:44)) button.backgroundColor = UIColor.green button.setTitleColor(UIColor.white, for: .normal) button.setTitle("SAVE CHANGES", for: .normal) button.titleLabel?.textAlignment = .center button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17.0) button.addTarget(self, action: #selector(ISSViewAReminderViewController.saveChanges(sender:)), for: .touchUpInside) cell?.contentView.addSubview(button) return cell! default: let cell = tableView.dequeueReusableCell(withIdentifier: "basicCell") return cell! } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let titles = ["Name", "Address", "Map", "Next ISS viewing", ""] if(section == 2 && self.tempPlacemark == nil) { return "" } return titles[section] } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == 2 && (self.tempPlacemark != nil || self.newReminder?.arrivalTimes != nil) { return 240.0 } return self.tableView.rowHeight } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension ISSViewAReminderViewController:UITextFieldDelegate { // remember, we want to update the map and entry every time there's a change func textFieldDidEndEditing(_ textField: UITextField) { if textField == nameTextField { self.newReminder?.name = textField.text } if textField == addressTextField, textField.text!.characters.count > 0 { // query for a location here let address = textField.text! self.forwardGeocode(inputAddress: address, completed: { (success, error, aPlacemark) in if(success) { DispatchQueue.main.async { self.tempPlacemark = aPlacemark } // Is our data fresh? self.newReminder?.latitude = aPlacemark?.location?.coordinate.latitude self.newReminder?.longitude = aPlacemark?.location?.coordinate.longitude if let arrivalTimes = self.newReminder?.arrivalTimes { if(Date().minutes(from: arrivalTimes[0].riseTime) > 1)// if our data's older than a minute, it most likely won't be accurate { self.newReminder?.refreshArrivalTimes(completed: { (success, error) in if(success) { DispatchQueue.main.async { self.tableView.reloadData() } } }) } } else { self.newReminder?.refreshArrivalTimes(completed: { (success, error) in if(success) { DispatchQueue.main.async { self.tableView.reloadData() } } }) } } else { // handle error here } }) } } } extension ISSViewAReminderViewController:MKAnnotation { var coordinate: CLLocationCoordinate2D { if(self.tempPlacemark != nil) { return (self.tempPlacemark?.location?.coordinate)! } else{ return (self.newReminder?.location.coordinate)! } } } <file_sep>// // BaseTableViewController.swift // ISS Pager // // Created by <NAME> on 12/22/16. // Copyright © 2016 Dedual Enterprises Inc. All rights reserved. // import UIKit class BaseTableViewController: UITableViewController { // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() } // MARK: - Configuration func configureCell(_ cell: UITableViewCell, forReminder reminder: ISSReminder) { // configure cell here, Nick cell.textLabel?.text = reminder.name cell.detailTextLabel?.text = "Earliest arrival: \(reminder.arrivalTimes![0].riseTime.humanReadableDate)" } } <file_sep>// // ViewController.swift // ISS Pager // // Created by <NAME> on 12/21/16. // Copyright © 2016 Dedual Enterprises Inc. All rights reserved. // import UIKit class MainContainerViewController: UIViewController { @IBOutlet var segmentedControl: UISegmentedControl! private lazy var mapViewController: ISSMapViewController = { // Load Storyboard let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main) // Instantiate View Controller var viewController = storyboard.instantiateViewController(withIdentifier: "ISSMapViewController") as! ISSMapViewController viewController.referenceContainerViewController = self // Add View Controller as Child View Controller self.add(asChildViewController: viewController) return viewController }() private lazy var remindersViewController: ISSRemindersViewController = { // Load Storyboard let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main) // Instantiate View Controller var viewController = storyboard.instantiateViewController(withIdentifier: "ISSRemindersViewController") as! ISSRemindersViewController viewController.referenceContainerViewController = self // Add View Controller as Child View Controller self.add(asChildViewController: viewController) return viewController }() lazy var reminders:[ISSReminder] = { var allReminders:[ISSReminder] = [] if let savedItems = UserDefaults.standard.array(forKey: kSavedItemsKey) { for savedItem in savedItems { if let reminder = NSKeyedUnarchiver.unarchiveObject(with: savedItem as! Data) as? ISSReminder { allReminders.append(reminder) reminder.refreshArrivalTimes(completed: { (success, error) in }) } } } return allReminders }() // MARK: - View Methods override func viewDidLoad() { super.viewDidLoad() setupView() let addRemindersButton:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(MainContainerViewController.addReminder(_:))) self.navigationItem.rightBarButtonItem = addRemindersButton // update reminders here } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) refreshAllReminders() } func refreshAllReminders() { var allReminders:[ISSReminder] = [] if let savedItems = UserDefaults.standard.array(forKey: kSavedItemsKey) { for savedItem in savedItems { if let reminder = NSKeyedUnarchiver.unarchiveObject(with: savedItem as! Data) as? ISSReminder { allReminders.append(reminder) reminder.refreshArrivalTimes(completed: { (success, error) in }) } } } self.reminders = allReminders } private func setupView() { setupSegmentedControl() updateView() } private func updateView() { if segmentedControl.selectedSegmentIndex == 0 { remove(asChildViewController: remindersViewController) add(asChildViewController: mapViewController) } else { remove(asChildViewController: mapViewController) add(asChildViewController: remindersViewController) } } private func setupSegmentedControl() { // Configure Segmented Control segmentedControl.removeAllSegments() segmentedControl.insertSegment(withTitle: "Map", at: 0, animated: false) segmentedControl.insertSegment(withTitle: "Saved", at: 1, animated: false) segmentedControl.addTarget(self, action: #selector(selectionDidChange(_:)), for: .valueChanged) // Select First Segment segmentedControl.selectedSegmentIndex = 0 } // MARK: - Actions func selectionDidChange(_ sender: UISegmentedControl) { updateView() } // MARK: - Helper Methods private func add(asChildViewController viewController: UIViewController) { // Add Child View Controller // addChildViewController(viewController) // Add Child View as Subview view.addSubview(viewController.view) // Configure Child View viewController.view.frame = view.bounds viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] // Notify Child View Controller // viewController.didMove(toParentViewController: self) } private func remove(asChildViewController viewController: UIViewController) { // Notify Child View Controller viewController.willMove(toParentViewController: nil) // Remove Child View From Superview viewController.view.removeFromSuperview() // Notify Child View Controller viewController.removeFromParentViewController() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func addReminder(_ sender:UIButton) { // save current reminders state let items = NSMutableArray() for aReminder in reminders { let item = NSKeyedArchiver.archivedData(withRootObject: aReminder) items.add(item) } UserDefaults.standard.set(items, forKey: kSavedItemsKey) UserDefaults.standard.synchronize() let popViewController = ISSViewAReminderViewController() let navigationController = UINavigationController(rootViewController: popViewController) self.present(navigationController, animated: true) { } } } <file_sep>// // ISSExtensions.swift // ISS Pager // // Created by <NAME> on 12/21/16. // Copyright © 2016 Dedual Enterprises Inc. All rights reserved. // import Foundation import UIKit let kSavedItemsKey = "ISSPagerSavedReminders" extension String { var URLEscapedString: String { return self.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlHostAllowed)! } var UTF8EncodedData: Data { return self.data(using: String.Encoding.utf8)! } } extension UIImage { static func fromColor(_ color: UIColor) -> UIImage { let rect = CGRect(x: 0, y: 0, width: 1, height: 1) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context!.setFillColor(color.cgColor) context!.fill(rect) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img! } } extension Notification.Name // the different notifications we'll want to listen to { static let onISSWithinUserRange = Notification.Name("onISSWithinUserRange") static let onISSWithinReminderRange = Notification.Name("onISSWithinReminderRange") } extension Date { var humanReadableDate:String { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium dateFormatter.timeStyle = .medium dateFormatter.locale = Locale(identifier: "en_US") // for now. Useful for localization later return dateFormatter.string(from: self) } /// Returns the amount of years from another date func years(from date: Date) -> Int { return Calendar.current.dateComponents([.year], from: date, to: self).year ?? 0 } /// Returns the amount of months from another date func months(from date: Date) -> Int { return Calendar.current.dateComponents([.month], from: date, to: self).month ?? 0 } /// Returns the amount of weeks from another date func weeks(from date: Date) -> Int { return Calendar.current.dateComponents([.weekOfYear], from: date, to: self).weekOfYear ?? 0 } /// Returns the amount of days from another date func days(from date: Date) -> Int { return Calendar.current.dateComponents([.day], from: date, to: self).day ?? 0 } /// Returns the amount of hours from another date func hours(from date: Date) -> Int { return Calendar.current.dateComponents([.hour], from: date, to: self).hour ?? 0 } /// Returns the amount of minutes from another date func minutes(from date: Date) -> Int { return Calendar.current.dateComponents([.minute], from: date, to: self).minute ?? 0 } /// Returns the amount of seconds from another date func seconds(from date: Date) -> Int { return Calendar.current.dateComponents([.second], from: date, to: self).second ?? 0 } } <file_sep>// // ISSLocationAnnotation.swift // ISS Pager // // Created by <NAME> on 12/22/16. // Copyright © 2016 Dedual Enterprises Inc. All rights reserved. // import UIKit import MapKit import CoreLocation class ISSLocationAnnotation: NSObject, MKAnnotation { var identifier: String! var issLocation:ISSLocation! var coordinate:CLLocationCoordinate2D var title:String? { return "Last updated: \(issLocation.lastUpdated.humanReadableDate)" } init(coordinate:CLLocationCoordinate2D, identifier:String, location:ISSLocation) { self.coordinate = coordinate self.identifier = identifier self.issLocation = location } } <file_sep>// // ISSReminderAnnotation.swift // ISS Pager // // Created by <NAME> on 12/22/16. // Copyright © 2016 Dedual Enterprises Inc. All rights reserved. // import Foundation import UIKit import MapKit import CoreLocation class ISSReminderAnnotation: NSObject, MKAnnotation { var identifier: String! var reminder:ISSReminder! var coordinate:CLLocationCoordinate2D var title:String? { if let name = reminder.name { return name } else { return nil } } var subtitle: String? { return "Earliest arrival: \(reminder.arrivalTimes![0].riseTime.humanReadableDate)" } init(coordinate:CLLocationCoordinate2D, identifier:String, reminder:ISSReminder) { self.coordinate = coordinate self.identifier = identifier self.reminder = reminder } } <file_sep># ISS-Pager A demo application that reminds the user to call their friends whenever the International Space Station is visible to the user or near an area of interest. To run, please remember to run Cocoapods before testing the application <file_sep>// // ISSRemindersViewController.swift // ISS Pager // // Created by <NAME> on 12/22/16. // Copyright © 2016 Dedual Enterprises Inc. All rights reserved. // import UIKit class ISSRemindersViewController: BaseTableViewController, UISearchBarDelegate, UISearchControllerDelegate, UISearchResultsUpdating { /// State restoration values. enum RestorationKeys : String { case viewControllerTitle case searchControllerIsActive case searchBarText case searchBarIsFirstResponder } struct SearchControllerRestorableState { var wasActive = false var wasFirstResponder = false } var referenceContainerViewController:MainContainerViewController! var reminders:[ISSReminder] { return referenceContainerViewController.reminders } /// Search controller to help us with filtering. var searchController: UISearchController! /// Secondary search results table view. var resultsTableController: ResultsTableViewController! /// Restoration state for UISearchController var restoredState = SearchControllerRestorableState() //MARK: - View Management override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. resultsTableController = ResultsTableViewController() // We want to be the delegate for our filtered table so didSelectRowAtIndexPath(_:) is called for both tables. resultsTableController.tableView.delegate = self searchController = UISearchController(searchResultsController: resultsTableController) searchController.searchResultsUpdater = self searchController.searchBar.sizeToFit() tableView.tableHeaderView = searchController.searchBar searchController.delegate = self searchController.dimsBackgroundDuringPresentation = false // default is YES searchController.searchBar.delegate = self // so we can monitor text changes + others /* Search is now just presenting a view controller. As such, normal view controller presentation semantics apply. Namely that presentation will walk up the view controller hierarchy until it finds the root view controller or one that defines a presentation context. */ definesPresentationContext = true } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Restore the searchController's active state. if restoredState.wasActive { searchController.isActive = restoredState.wasActive restoredState.wasActive = false if restoredState.wasFirstResponder { searchController.searchBar.becomeFirstResponder() restoredState.wasFirstResponder = false } } self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - UISearchBarDelegate func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() } // MARK: - UISearchControllerDelegate func presentSearchController(_ searchController: UISearchController) { //debugPrint("UISearchControllerDelegate invoked method: \(__FUNCTION__).") } func willPresentSearchController(_ searchController: UISearchController) { //debugPrint("UISearchControllerDelegate invoked method: \(__FUNCTION__).") } func didPresentSearchController(_ searchController: UISearchController) { //debugPrint("UISearchControllerDelegate invoked method: \(__FUNCTION__).") } func willDismissSearchController(_ searchController: UISearchController) { //debugPrint("UISearchControllerDelegate invoked method: \(__FUNCTION__).") } func didDismissSearchController(_ searchController: UISearchController) { //debugPrint("UISearchControllerDelegate invoked method: \(__FUNCTION__).") } func updateSearchResults(for searchController: UISearchController) { // Update the filtered array based on the search text. let searchResults = reminders // Strip out all the leading and trailing spaces. let whitespaceCharacterSet = CharacterSet.whitespaces let strippedString = searchController.searchBar.text!.trimmingCharacters(in: whitespaceCharacterSet) let searchItems = strippedString.components(separatedBy: " ") as [String] // Build all the "AND" expressions for each value in the searchString. let andMatchPredicates: [NSPredicate] = searchItems.map { searchString in var searchItemsPredicate = [NSPredicate]() // Below we use NSExpression represent expressions in our predicates. // NSPredicate is made up of smaller, atomic parts: two NSExpressions (a left-hand value and a right-hand value). // Name field matching. let titleExpression = NSExpression(forKeyPath: "name") let searchStringExpression = NSExpression(forConstantValue: searchString) let titleSearchComparisonPredicate = NSComparisonPredicate(leftExpression: titleExpression, rightExpression: searchStringExpression, modifier: .direct, type: .contains, options: .caseInsensitive) searchItemsPredicate.append(titleSearchComparisonPredicate) // Address field matching. let addressExpression = NSExpression(forKeyPath: "address") let addressSearchStringExpression = NSExpression(forConstantValue: searchString) let addressSearchComparisonPredicate = NSComparisonPredicate(leftExpression: addressExpression, rightExpression: addressSearchStringExpression, modifier: .direct, type: .contains, options: .caseInsensitive) searchItemsPredicate.append(addressSearchComparisonPredicate) // Add this OR predicate to our master AND predicate. let orMatchPredicate = NSCompoundPredicate(orPredicateWithSubpredicates:searchItemsPredicate) return orMatchPredicate } // Match up the fields of the Product object. let finalCompoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: andMatchPredicates) let filteredResults = searchResults.filter { finalCompoundPredicate.evaluate(with: $0) } // Hand over the filtered results to our search results table. let resultsController = searchController.searchResultsController as! ResultsTableViewController resultsController.filteredReminders = filteredResults resultsController.tableView.reloadData() } // MARK: - UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return reminders.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "basicCellReminder") if cell == nil { cell = UITableViewCell(style: .subtitle, reuseIdentifier: "basicCellReminder") cell?.selectionStyle = .none } let reminder = reminders[indexPath.row] configureCell(cell!, forReminder: reminder) return cell! } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let items = NSMutableArray() for aReminder in reminders { let item = NSKeyedArchiver.archivedData(withRootObject: aReminder) items.add(item) } UserDefaults.standard.set(items, forKey: kSavedItemsKey) UserDefaults.standard.synchronize() let selectedReminder: ISSReminder // Check to see which table view cell was selected. if tableView === self.tableView { selectedReminder = reminders[indexPath.row] } else { selectedReminder = resultsTableController.filteredReminders[indexPath.row] } // Set up the detail view controller to show. let detailViewController = ISSViewAReminderViewController.detailViewControllerForReminder(selectedReminder) referenceContainerViewController.navigationController?.pushViewController(detailViewController, animated: true) } // MARK: - UIStateRestoration override func encodeRestorableState(with coder: NSCoder) { super.encodeRestorableState(with: coder) // Encode the view state so it can be restored later. // Encode the title. coder.encode(navigationItem.title!, forKey:RestorationKeys.viewControllerTitle.rawValue) // Encode the search controller's active state. coder.encode(searchController.isActive, forKey:RestorationKeys.searchControllerIsActive.rawValue) // Encode the first responser status. coder.encode(searchController.searchBar.isFirstResponder, forKey:RestorationKeys.searchBarIsFirstResponder.rawValue) // Encode the search bar text. coder.encode(searchController.searchBar.text, forKey:RestorationKeys.searchBarText.rawValue) } override func decodeRestorableState(with coder: NSCoder) { super.decodeRestorableState(with: coder) // Restore the title. guard let decodedTitle = coder.decodeObject(forKey: RestorationKeys.viewControllerTitle.rawValue) as? String else { fatalError("A title did not exist. In your app, handle this gracefully.") } title = decodedTitle // Restore the active state: // We can't make the searchController active here since it's not part of the view // hierarchy yet, instead we do it in viewWillAppear. // restoredState.wasActive = coder.decodeBool(forKey: RestorationKeys.searchControllerIsActive.rawValue) // Restore the first responder status: // Like above, we can't make the searchController first responder here since it's not part of the view // hierarchy yet, instead we do it in viewWillAppear. // restoredState.wasFirstResponder = coder.decodeBool(forKey: RestorationKeys.searchBarIsFirstResponder.rawValue) // Restore the text in the search field. searchController.searchBar.text = coder.decodeObject(forKey: RestorationKeys.searchBarText.rawValue) as? String } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>// // ISSReminder.swift // ISS Pager // // Created by <NAME> on 12/22/16. // Copyright © 2016 Dedual Enterprises Inc. All rights reserved. // import UIKit import CoreLocation class ISSReminderRiseAndDuration:NSObject, NSCoding { let kISSReminderRiseTimeKey = "riseTime" let kISSRemindeDurationKey = "duration" var riseTime:Date! var duration:Double! // in seconds init(rise:NSNumber, duration:NSNumber) { super.init() self.riseTime = Date(timeIntervalSince1970: rise.doubleValue) self.duration = duration.doubleValue } init(json:[String:AnyObject]) { super.init() self.prepareWithJSON(json: json) } required init?(coder decoder:NSCoder) { self.duration = decoder.decodeDouble(forKey: kISSRemindeDurationKey) self.riseTime = decoder.decodeObject(forKey: kISSReminderRiseTimeKey) as! Date } func encode(with coder:NSCoder) { coder.encode((self.duration as Double), forKey: kISSRemindeDurationKey) // Oh, the joys of typecasting in Swift coder.encode(self.riseTime, forKey: kISSReminderRiseTimeKey) } func prepareWithJSON(json:[String:AnyObject]) { let riseTimeValue = json["risetime"] as! NSNumber let durationValue = json["duration"] as! NSNumber self.riseTime = Date(timeIntervalSince1970: riseTimeValue.doubleValue) self.duration = durationValue.doubleValue } } class ISSReminder: NSObject, NSCoding { let kISSRemindersNameKey:String = "name" let kISSRemindersAddressKey:String = "address" let kISSReminderLatitudeKey:String = "latitude" let kISSReminderLongitudeKey:String = "longitude" let kISSReminderRiseTimeArrayKey:String = "riseTimeArray" let kISSReminderLastUpdatedKey:String = "lastUpdated" var name:String! var address:String! var latitude:Double! var longitude:Double! var location:CLLocation { return CLLocation(latitude: latitude, longitude: longitude) } var lastUpdated:Date! var arrivalTimes:[ISSReminderRiseAndDuration]? override init() { super.init() } init(json:[String:AnyObject]) { super.init() self.prepareWithJSON(json: json) } required init?(coder decoder:NSCoder) { self.latitude = decoder.decodeDouble(forKey: kISSReminderLatitudeKey) self.longitude = decoder.decodeDouble(forKey: kISSReminderLongitudeKey) self.name = decoder.decodeObject(forKey: kISSRemindersNameKey) as! String self.lastUpdated = decoder.decodeObject(forKey: kISSReminderLastUpdatedKey) as! Date self.address = decoder.decodeObject(forKey: kISSRemindersAddressKey) as! String self.arrivalTimes = decoder.decodeObject(forKey: kISSReminderRiseTimeArrayKey) as! [ISSReminderRiseAndDuration] } func encode(with coder:NSCoder) { coder.encode((self.latitude as Double), forKey:kISSReminderLatitudeKey) coder.encode((self.longitude as Double), forKey: kISSReminderLongitudeKey) // swift being ridiculous coder.encode(self.name, forKey: kISSRemindersNameKey) coder.encode(self.address, forKey: kISSRemindersAddressKey) coder.encode(self.lastUpdated, forKey: kISSReminderLastUpdatedKey) coder.encode(self.arrivalTimes, forKey: kISSReminderRiseTimeArrayKey) } func clearArrivalTimes() { if self.arrivalTimes != nil { self.arrivalTimes!.removeAll() self.arrivalTimes = nil } } func prepareWithJSON(json:[String:AnyObject]) { let requestObject = json["request"] as! [String:AnyObject] self.lastUpdated = Date.init(timeIntervalSince1970: (requestObject["datetime"] as! NSNumber).doubleValue) if let lat = requestObject["latitude"]?.doubleValue { self.latitude = lat } if let lng = requestObject["longitude"]?.doubleValue { self.longitude = lng } // address should be entered after forward geocoding. Let's not do that here // same with name arrivalTimes = Array<ISSReminderRiseAndDuration>() if let responseObject = json["response"] as? [[String:AnyObject]] { for riseTimeObject in responseObject { let riseTime = riseTimeObject["risetime"] as! NSNumber let duration = riseTimeObject["duration"] as! NSNumber let arrivalTime = ISSReminderRiseAndDuration(rise: riseTime, duration: duration) arrivalTimes!.append(arrivalTime) } } } func refreshArrivalTimes(completed: @escaping (_ finished:Bool, _ error:Error?) -> ()) { ISSNetwork.request(target: .PassTimes(lat: self.location.coordinate.latitude, lng: self.location.coordinate.longitude), success: { json in if let jsonObject = json as? [String:AnyObject] { self.clearArrivalTimes() self.prepareWithJSON(json: jsonObject) } completed(true, nil) }, error: { response in do{ var errorMessage = "Network error in how we recover a pass time" if let json = try response.mapJSON() as? [String:AnyObject] { errorMessage = json["errors"] as! String } // handle it further here completed(false, nil) } catch { // failed to even parse the response. Handle appropriately } }, failure: { error in // handle error here completed(false, error) }) } } <file_sep>// // AnnotationView.swift // ISS Pager // // Created by <NAME> on 12/22/16. // Copyright © 2016 Dedual Enterprises Inc. All rights reserved. // import MapKit class AnnotationView: MKAnnotationView { } <file_sep>// // Cells.swift // ISS Pager // // Created by <NAME> on 12/22/16. // Copyright © 2016 Dedual Enterprises Inc. All rights reserved. // import Foundation import MapKit class MapTableViewCell:UITableViewCell { @IBOutlet var mapview:MKMapView! } class RemindersDetailMainCell:UITableViewCell { @IBOutlet var label:UILabel! @IBOutlet var textfield:UITextField! } <file_sep>// // ISSLocation.swift // ISS Pager // // Created by <NAME> on 12/22/16. // Copyright © 2016 Dedual Enterprises Inc. All rights reserved. // import UIKit import CoreLocation class ISSLocation: NSObject { var currLocation:CLLocation! var lastUpdated:Date! var arrivalTimes:[ISSReminderRiseAndDuration]? override init() { super.init() } init(json:[String:AnyObject]) { super.init() self.prepareWithJSON(json: json) } func prepareWithJSON(json:[String:AnyObject]) { self.lastUpdated = Date.init(timeIntervalSince1970: (json["timestamp"] as! NSNumber).doubleValue) let coordinatesData = json["iss_position"] as! [String:AnyObject] if let lat = coordinatesData["latitude"]?.doubleValue, let lng = coordinatesData["longitude"]?.doubleValue { self.currLocation = CLLocation(latitude: lat, longitude: lng) } } func arrivalTimesFor(location:CLLocation, completed: @escaping (_ finished:Bool, _ error:Error?) -> ()) { ISSNetwork.request(target: .PassTimes(lat: location.coordinate.latitude, lng: location.coordinate.longitude), success: { json in if let jsonObject = json as? [String:AnyObject] { self.arrivalTimes = Array<ISSReminderRiseAndDuration>() if let responseObject = jsonObject["response"] as? [[String:AnyObject]] { for riseTimeObject in responseObject { let riseTime = riseTimeObject["risetime"] as! NSNumber let duration = riseTimeObject["duration"] as! NSNumber let arrivalTime = ISSReminderRiseAndDuration(rise: riseTime, duration: duration) self.arrivalTimes!.append(arrivalTime) } } } completed(true, nil) }, error: { response in do{ var errorMessage = "Network error in how we recover a pass time" if let json = try response.mapJSON() as? [String:AnyObject] { errorMessage = json["errors"] as! String } // handle it further here completed(false, nil) } catch { // failed to even parse the response. Handle appropriately } }, failure: { error in // handle error here completed(false, error) }) } // add pass by's based on user's location here } <file_sep> source 'https://github.com/CocoaPods/Specs.git' platform :ios, '9.3' use_frameworks! target 'ISS Pager' do pod 'Alamofire', '~> 4.0' pod 'Moya', '8.0.0-beta.6' end post_install do |installer| installer.pods_project.targets.each do |target| target.build_configurations.each do |configuration| configuration.build_settings['SWIFT_VERSION'] = "3.0" end end end <file_sep>// // ResultsTableViewController.swift // ISS Pager // // Created by <NAME> on 12/22/16. // Copyright © 2016 Dedual Enterprises Inc. All rights reserved. // import UIKit class ResultsTableViewController: BaseTableViewController { var filteredReminders:[ISSReminder] = [ISSReminder]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filteredReminders.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "basicCellReminder") if cell == nil { cell = UITableViewCell(style: .subtitle, reuseIdentifier: "basicCellReminder") cell?.selectionStyle = .none } let reminder = filteredReminders[indexPath.row] configureCell(cell!, forReminder: reminder) return cell! } } <file_sep>// // ISSMapViewController.swift // ISS Pager // // Created by <NAME> on 12/22/16. // Copyright © 2016 Dedual Enterprises Inc. All rights reserved. // import UIKit import MapKit import CoreLocation class ISSMapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { let locationManager = CLLocationManager() @IBOutlet var mapView:MKMapView! var currISSLocation:ISSLocation? var myLocation:CLLocation? var referenceContainerViewController:MainContainerViewController! var reminders:[ISSReminder] { return referenceContainerViewController.reminders } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.mapView.showsUserLocation = true if CLLocationManager.authorizationStatus() == .notDetermined { locationManager.requestWhenInUseAuthorization() } else if CLLocationManager.locationServicesEnabled() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.startUpdatingLocation() } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func refreshISSLocation() { ISSNetwork.request(target: .CurrentLocation(), success: { json in if let jsonObject = json as? [String:AnyObject] { self.currISSLocation = ISSLocation(json: jsonObject) if let currUserLocation = self.myLocation { self.currISSLocation?.arrivalTimesFor(location: currUserLocation, completed: { (success, error) in if(success) { for anAnnotation in self.mapView.annotations { if anAnnotation is ISSLocationAnnotation { self.mapView.removeAnnotation(anAnnotation) } } self.mapView.removeOverlays(self.mapView.overlays) let identifier = "ISSLocation" let annotation = ISSLocationAnnotation(coordinate: self.currISSLocation!.currLocation.coordinate, identifier: identifier, location: self.currISSLocation!) self.mapView.addAnnotation(annotation) let circle = MKCircle(center: annotation.coordinate, radius: 80000.0) self.mapView.add(circle) let dateText:String? = (self.currISSLocation?.arrivalTimes?[0].riseTime.humanReadableDate) if let date = dateText { let text = "Earliest ISS arrival: \(date)" self.mapView.userLocation.subtitle = text } } }) } } }, error: { response in }) { error in } } func refreshMapAnnotations() // we always worry about our local data { for anAnnotation in self.mapView.annotations { self.mapView.removeAnnotation(anAnnotation) } // add placepoints here for aReminder in reminders { let identifier = "reminder_\(aReminder.location.coordinate.latitude)\(aReminder.location.coordinate.longitude)\(aReminder.lastUpdated.humanReadableDate)" let annotation = ISSReminderAnnotation(coordinate: aReminder.location.coordinate, identifier: identifier, reminder: aReminder) self.mapView.addAnnotation(annotation) } } //MARK: - MKMapViewDelegate function func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) { } func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) { for view in views { if view.annotation is MKUserLocation { view.canShowCallout = true } } } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if annotation is MKUserLocation { mapView.userLocation.title = "My location!" if let issLocation = currISSLocation, let arrivalTimes = issLocation.arrivalTimes { mapView.userLocation.subtitle = "Earliest arrival: \(arrivalTimes[0].riseTime.humanReadableDate)" } return nil } if annotation is ISSReminderAnnotation { var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "Pin") if annotationView == nil { annotationView = AnnotationView(annotation: annotation, reuseIdentifier: "Pin") annotationView?.canShowCallout = true annotationView?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) }else { annotationView?.annotation = annotation } annotationView?.image = UIImage(named: "RemindersIcon") return annotationView } else if annotation is ISSLocationAnnotation { var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "ISS") if annotationView == nil { annotationView = AnnotationView(annotation: annotation, reuseIdentifier: "ISS") annotationView?.canShowCallout = true }else { annotationView?.annotation = annotation } annotationView?.image = UIImage(named: "ISSIcon") return annotationView } else { return nil } } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { let items = NSMutableArray() for aReminder in reminders { let item = NSKeyedArchiver.archivedData(withRootObject: aReminder) items.add(item) } UserDefaults.standard.set(items, forKey: kSavedItemsKey) UserDefaults.standard.synchronize() let selectedReminder = (view.annotation as! ISSReminderAnnotation).reminder! // Set up the detail view controller to show. let detailViewController = ISSViewAReminderViewController.detailViewControllerForReminder(selectedReminder) referenceContainerViewController.navigationController?.pushViewController(detailViewController, animated: true) } func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { } func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) { if view.isKind(of: AnnotationView.self) { for subview in view.subviews { subview.removeFromSuperview() } } } func mapViewDidFinishRenderingMap(_ mapView: MKMapView, fullyRendered: Bool) { self.refreshMapAnnotations() self.refreshISSLocation() } func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { let circleRenderer = MKCircleRenderer(overlay: overlay) circleRenderer.fillColor = UIColor.blue.withAlphaComponent(0.1) circleRenderer.strokeColor = UIColor.blue circleRenderer.lineWidth = 1 return circleRenderer } //MARK: - Location Manager Delegates func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { self.myLocation = locations.last } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if(status == .authorizedWhenInUse || status == .authorizedAlways) { self.refreshMapAnnotations() self.refreshISSLocation() } else { let alertController = UIAlertController( title: "Background Location Access Disabled", message: "In order to be notified of when the ISS is near you, please open this app's settings and set location access to 'When in Use'.", preferredStyle: .alert) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alertController.addAction(cancelAction) let openAction = UIAlertAction(title: "Open Settings", style: .default) { (action) in if let url = URL(string:UIApplicationOpenSettingsURLString) { UIApplication.shared.openURL(url) } } alertController.addAction(openAction) self.present(alertController, animated: true, completion: nil) } } }
df3daccac433c6fc869e83035938fb0f53dce5bf
[ "Swift", "Ruby", "Markdown" ]
16
Swift
dedual/ISS-Pager
301989ae5833d17c2b42abf5cda1e6d5cf51ea83
d5785a3133608a9d43b76533061ec3cd152b45ac
refs/heads/master
<file_sep>data class DatosBasicosDTO ( val fechaEmisionTransf : String, val impTransferencia : Double, val impComision : Int, val impGastos : Int, val impLiquido : Double, val nombreOrdenante : String, val descCuentaAbono : String, val descCuentaCargo : String, val impTotalDivBase : String? ) <file_sep> data class Currency ( val type : String, val error : Int, val descError : String?, val datosBasicos : DatosBasicos, val listaComisiones : String? )<file_sep> data class CurrencyDTO ( val error : Int, val descError : String?, val datosBasicos : DatosBasicosDTO, val listaComisiones : String? )
79fda8be9ebe5ffb23a6f32e5b3db7218f797d60
[ "Kotlin" ]
3
Kotlin
linchis/ParserGsonKotlin
4d3ae261fb5133c0658c2c04ac26f518f07514b2
1b1e2a6f850612a29fbff0e660088dd693341ec1
refs/heads/master
<repo_name>philion/chiron<file_sep>/src/main/java/com/acmerocket/chiron/spi/Credentials.java package com.acmerocket.chiron.spi; import java.io.Serializable; public interface Credentials extends Serializable { } <file_sep>/src/main/java/com/acmerocket/chiron/provider/withings/model/MeasureType.java package com.acmerocket.chiron.provider.withings.model; import java.util.HashMap; import java.util.Map; /** * From http://www.withings.com/fr/api/balance#getmeas * * @author philion */ public enum MeasureType { // FIXME: Need a custom mapper, but I can't figure out how they work. Can't even find example code. unknown(0, "?"), weight(1, "Weight (kg)"), unknown2(2, "?"), unknown3(3, "?"), height(4, "Height (meter)"), mass(5, "Fat Free Mass (kg)"), fatRatio(6, "Fat Ratio (%)"), unknown7(7, "?"), fatMass(8, "Fat Mass Weight"), bpDiastolic(9, "Diastolic Blood Pressure (mmHg)"), bpSystolic(10, "Systolic Blood Pressure (mmHg)"), pulse(11, "Heart Pulse (bpm)"); private int ordinal; private String description; private MeasureType(int type, String description) { this.ordinal = type; this.description = description; } public int getOrdinal() { return this.ordinal; } public String getDescription() { return this.description; } private static final Map<Integer, MeasureType> typeMap = new HashMap<Integer, MeasureType>(); static { for (MeasureType type : MeasureType.values()) { typeMap.put(type.getOrdinal(), type); } } public static MeasureType valueOf(int type) { return typeMap.get(type); } } <file_sep>/src/main/java/com/acmerocket/chiron/provider/withings/model/User.java package com.acmerocket.chiron.provider.withings.model; import java.io.Serializable; import java.util.Date; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties("fatmethod") public class User implements Serializable { private static final long serialVersionUID = 1L; private long id; private String firstName; private String lastName; private String shortName; private String publicKey; private Gender gender; private Date birthDate; private boolean isPublic; public User() {}; public User(long id, String firstname, String lastname, String shortname, String publicKey, boolean isFemale, Date birthDate) { this(id, firstname, lastname, shortname, publicKey, isFemale, false, birthDate); } public User(long id, String firstname, String lastname, String shortname, String publicKey, boolean isFemale, boolean isPublic, Date birthDate) { this.id = id; this.firstName = firstname; this.lastName = lastname; this.shortName = shortname; this.publicKey = publicKey; this.gender = isFemale == true ? Gender.female : Gender.male; this.isPublic = isPublic; this.birthDate = birthDate; } public String getFirstname() { return this.firstName; } public void setFirstname(String firstname) { this.firstName = firstname; } /** */ public String getLastname() { return this.lastName; } /** */ public void setLastname(String lastname) { this.lastName = lastname; } /** */ public String getShortname() { return this.shortName; } /** */ public void setShortname(String shortname) { this.shortName = shortname; } public Gender getGender() { return this.gender; } /** */ public Date getBirthDate() { return this.birthDate; } @JsonProperty("birthdate") public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } @JsonProperty("ispublic") public void setIsPublic(boolean isPublic) { this.isPublic = isPublic; } /** */ public boolean isPublic() { return this.isPublic; } @JsonProperty("publickey") public void setPublicKey(String publicKey) { this.publicKey = publicKey; } public String getPublicKey() { return this.publicKey; } public void setId(long id) { this.id = id; } public long getId() { return this.id; } @Override public String toString() { return "User [id=" + this.id + ", firstname=" + this.firstName + ", lastname=" + this.lastName + ", shortname=" + this.shortName + ", publicKey=" + this.publicKey + ", birthDate=" + this.birthDate + ", gender=" + this.gender + ", isPublic=" + this.isPublic + "]"; } } <file_sep>/src/main/java/com/acmerocket/chiron/provider/withings/model/Measurement.java package com.acmerocket.chiron.provider.withings.model; import java.io.Serializable; /** * A measure is an actual measurement of something. It has three parameters: A * type which can be one of the ones specified in the Measure types table. A * value which is the actual value of the measure (integer). A unit which * represents the power of 10 that has to be multipled by value to find the * actual data (integer). * * @author jon */ public class Measurement implements Serializable { private static final long serialVersionUID = 1L; private static final float POUND = 0.453592f; private static final float FOOT = 0.0254f * 12; private MeasureType type; private float value; private int transportValue; private int unit; public Measurement() {}; public Measurement(MeasureType type, int value, int unit) { this.transportValue = value; this.type = type; this.unit = unit; } public Measurement(int typeOrd, int value, int unit) { this.transportValue = value; this.type = MeasureType.valueOf(typeOrd); this.unit = unit; } public void setValue(int transportValue) { this.transportValue = transportValue; this.value = actualValue(transportValue, unit); } public float getValue() { return this.value; } public float getValue(MeasureSystem system) { switch (this.type) { case weight: case mass: case fatMass: if (MeasureSystem.IMPERIAL == system) { return roundToHundred(this.value / POUND); } else { return roundToHundred(this.value); } case height: if (MeasureSystem.IMPERIAL == system) { double feet = Math.round(this.value / FOOT); return roundToHundred((float)feet); } else { return roundToHundred(this.value); } default: return roundToHundred(this.value); } } public MeasureType getType() { return this.type; } public void setType(MeasureType type) { this.type = type; } public void setUnit(int unit) { this.unit = unit; this.value = actualValue(this.transportValue, unit); } private static float actualValue(int transportValue, int unit) { return (float)(transportValue * Math.pow(10, unit)); } /** * Returns a nicely formatted string. */ public String getMeasurement() { return this.getMeasurement(MeasureSystem.IMPERIAL); } private void appendMeasure(StringBuilder result, MeasureType type, MeasureSystem ms) { switch (ms) { case IMPERIAL: result.append(roundToHundred(this.getValue() / POUND)).append(" lb"); break; case SI: result.append(roundToHundred(this.getValue())).append(" Kg"); break; } } /** * Returns a nicely formatted string based on the requested System. */ public String getMeasurement(MeasureSystem system) { if (this.type == null) { return "?type?"; } StringBuilder result = new StringBuilder(); result.append(this.type.getDescription()).append(' '); switch (this.type) { case weight: case mass: case fatMass: this.appendMeasure(result, getType(), system); break; case height: if (system == MeasureSystem.IMPERIAL) { double inches = Math.round(this.getValue() / FOOT / 12); int foot = Double.valueOf(Math.floor(inches / FOOT)).intValue(); int inch = Double.valueOf(inches - (FOOT * foot)).intValue(); result.append(foot); result.append(" ft "); result.append(inch); result.append(" in"); } else { result.append(roundToHundred(this.getValue())); result.append(" m"); } break; case fatRatio: result.append(this.getValue()); break; default: result.append("?"); } return result.toString(); } public enum MeasureSystem { IMPERIAL, SI; } /** */ @Override public String toString() { //return "Measure [actualValue=" + this.getValue() + ", type=" + this.type + ", unit=" + this.unit // + ", value=" + this.transportValue + ", imperial: " + this.getMeasure(MeasureSystem.IMPERIAL) + ", si: " // + this.getMeasure(MeasureSystem.SI) + "]"; return this.type + ": " + this.getValue(MeasureSystem.IMPERIAL); } public static float roundToHundred(float value) { return Math.round(value * 100) / 100f; } } <file_sep>/src/main/java/com/acmerocket/chiron/provider/withings/response/MeasurementGroupResponseBody.java package com.acmerocket.chiron.provider.withings.response; import java.util.Date; import java.util.List; import com.acmerocket.chiron.provider.withings.model.MeasurementGroup; import com.fasterxml.jackson.annotation.JsonProperty; public class MeasurementGroupResponseBody { private List<MeasurementGroup> groups; private Date updateTime; public List<MeasurementGroup> getGroups() { return groups; } @JsonProperty("measuregrps") public void setGroups(List<MeasurementGroup> groups) { this.groups = groups; } public Date getUpdateTime() { return updateTime; } @JsonProperty("updatetime") public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }<file_sep>/src/main/java/com/acmerocket/chiron/provider/withings/response/JsonResponse.java package com.acmerocket.chiron.provider.withings.response; import com.fasterxml.jackson.databind.JsonNode; public class JsonResponse extends AbstractResponseObject<JsonNode> {} <file_sep>/src/main/java/com/acmerocket/chiron/provider/withings/response/GetUserResponse.java package com.acmerocket.chiron.provider.withings.response; public class GetUserResponse extends AbstractResponseObject<GetUserBody> {} <file_sep>/src/main/java/com/acmerocket/chiron/provider/withings/WithingsImpl.java package com.acmerocket.chiron.provider.withings; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.Date; import java.util.List; import org.apache.commons.codec.digest.DigestUtils; import com.acmerocket.chiron.provider.withings.model.MeasureType; import com.acmerocket.chiron.provider.withings.model.MeasurementGroup; import com.acmerocket.chiron.provider.withings.model.StatusCode; import com.acmerocket.chiron.provider.withings.model.User; import com.acmerocket.chiron.provider.withings.response.GetUserBody; import com.acmerocket.chiron.provider.withings.response.GetUserResponse; import com.acmerocket.chiron.provider.withings.response.GetUsersBody; import com.acmerocket.chiron.provider.withings.response.GetUsersResponse; import com.acmerocket.chiron.provider.withings.response.JsonResponse; import com.acmerocket.chiron.provider.withings.response.MeasurementGroupResponse; import com.acmerocket.chiron.provider.withings.response.MeasurementGroupResponseBody; import com.acmerocket.chiron.provider.withings.response.ResponseObject; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; /* * MAJOR INTERFACES * - credentials * - provider * -- pulse * -- blood pressure * -- user * -- height, weight, etc... "body" * -- activity... ? * - getdata * - putdata * - notification */ public class WithingsImpl implements WithingsAPI { private static final String URL_BASE = "http://wbsapi.withings.net/"; private static final String URL_USER_UPDATE = URL_BASE + "user?action=update&userid=%s&publickey=%s&ispublic=%s"; private static final String URL_NOTIFY_REVOKE = URL_BASE + "notify?action=revoke&userid=%s&publickey=%s&callbackurl=%s"; private static final String URL_NOTIFY_GET = URL_BASE + "notify?action=get&userid=%s&publickey=%s&callbackurl=%s"; private static final String URL_SUBSCRIBE = URL_BASE + "notify?action=subscribe&userid=%s&publickey=%s&callbackurl=%s"; private static final String URL_GETUSERSLIST = URL_BASE + "account?action=getuserslist&email=%s&hash=%s"; private static final String URL_GETBYUSERID = URL_BASE + "user?action=getbyuserid&userid=%s&publickey=%s"; private static final String URL_GET_MEASURE_BASE = URL_BASE + "measure?action=getmeas&userid=%s&publickey=%s"; private static final String URL_GET_ONCE = URL_BASE + "once?action=get"; private final ObjectMapper mapper = new ObjectMapper(); // TODO: Custom config? private String getOneTimeKey() throws WithingsException { JsonNode rootNode = this.requestResource(URL_GET_ONCE, JsonResponse.class); return rootNode.path("once").textValue(); } private String getHash(String email, String password) throws WithingsException { String passwordMd5 = DigestUtils.md5Hex(password); return DigestUtils.md5Hex(email + ":" + passwordMd5 + ":" + this.getOneTimeKey()); } public List<MeasurementGroup> getMeasureGroups(WithingsCredentials creds) throws WithingsException { return this.internalGetMeasureGroups(creds, null, null, null, null, -1, -1); } public List<MeasurementGroup> getMeasureGroups(WithingsCredentials creds, Date startDate, Date endDate, MeasureType type) throws WithingsException { return this.internalGetMeasureGroups(creds, startDate, endDate, null, type, -1, -1); } public List<MeasurementGroup> getMeasureGroups(WithingsCredentials creds, Date startDate, Date endDate, MeasureType type, int limit, int offset) throws WithingsException { return this.internalGetMeasureGroups(creds, startDate, endDate, null, type, limit, offset); } public List<MeasurementGroup> getMeasureGroups(WithingsCredentials creds, Date lastUpdateDate, MeasureType type) throws WithingsException { return this.internalGetMeasureGroups(creds, null, null, lastUpdateDate, type, -1, -1); } public List<MeasurementGroup> getMeasureGroups(WithingsCredentials creds, Date lastUpdateDate, MeasureType type, int limit, int offset) throws WithingsException { return this.internalGetMeasureGroups(creds, null, null, lastUpdateDate, type, limit, offset); } private <B, R extends ResponseObject<B>> B requestResource(String urlStr, Class<R> resourceType) throws WithingsException { try { URL url = new URL(urlStr); return requestResource(url, resourceType); } catch (MalformedURLException e) { throw new WithingsException(e); } } private <B, R extends ResponseObject<B>> B requestResource(URL url, Class<R> resourceType) throws WithingsException { URLConnection conn = null; try { conn = url.openConnection(); conn.connect(); R response = this.mapper.readValue(conn.getInputStream(), resourceType); StatusCode status = response.getStatus(); if (StatusCode.success != status) { throw new WithingsException(status); } return response.getBody(); } catch (Exception e) { throw new WithingsException(e); } finally { if ((conn != null) && (conn instanceof HttpURLConnection)) ((HttpURLConnection) conn).disconnect(); } } private List<MeasurementGroup> internalGetMeasureGroups(WithingsCredentials creds, Date startDate, Date endDate, Date lastUpdateDate, MeasureType type, int limit, int offset) throws WithingsException { StringBuilder urlStr = new StringBuilder(String.format(URL_GET_MEASURE_BASE, creds.getId(), creds.getKey())); //StringBuilder urlStr = new StringBuilder(String.format(URL_GET_MEASURE_BASE, userId, publicKey)); if (startDate != null) { urlStr.append("&startdate=" + startDate.getTime() / 1000); } if (endDate != null) { urlStr.append("&enddate=" + endDate.getTime() / 1000); } if (lastUpdateDate != null) { urlStr.append("&lastupdate=" + lastUpdateDate.getTime() / 1000); } if (type != null) { urlStr.append("&meastype=" + type); } if (limit >= 0) { urlStr.append("&limit=" + limit); } if (offset >= 0) { urlStr.append("&offsetby=" + offset); } MeasurementGroupResponseBody body = this.requestResource(urlStr.toString(), MeasurementGroupResponse.class); return body.getGroups(); } public User getUser(WithingsCredentials creds) throws WithingsException { String urlStr = String.format(URL_GETBYUSERID, creds.getId(), creds.getKey()); GetUserBody body = this.requestResource(urlStr.toString(), GetUserResponse.class); return body.getUser(); } public List<User> getUsers(String email, String hash) throws WithingsException { String urlStr = String.format(URL_GETUSERSLIST, email, hash); GetUsersBody body = this.requestResource(urlStr, GetUsersResponse.class); return body.getUsers(); } public void addSubscription(WithingsCredentials creds, String callbackUrl) throws WithingsException { String urlStr = String.format(URL_SUBSCRIBE, creds.getId(), creds.getKey(), encode(callbackUrl)); this.requestResource(urlStr, JsonResponse.class); } private static String encode(String urlStr) { try { return URLEncoder.encode(urlStr, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } public Date getSubscription(WithingsCredentials creds, String callbackUrl) throws WithingsException { String urlStr = String.format(URL_NOTIFY_GET, creds.getId(), creds.getKey(), encode(callbackUrl)); JsonNode rootNode = this.requestResource(urlStr, JsonResponse.class); // FIXME return new Date(rootNode.path("body").path("expires").longValue() * 1000); } public void removeSubscription(WithingsCredentials creds, String callbackUrl) throws WithingsException { String urlStr = String.format(URL_NOTIFY_REVOKE, creds.getId(), creds.getKey(), encode(callbackUrl)); this.requestResource(urlStr, JsonResponse.class); } public void setPublic(WithingsCredentials creds, boolean isPublic) throws WithingsException { // FIXME String publicFlag = isPublic ? "1" : "0"; String urlStr = String.format(URL_USER_UPDATE, creds.getId(), creds.getKey(), publicFlag); this.requestResource(urlStr, JsonResponse.class); } public static void main(String[] args) throws WithingsException { WithingsImpl withings = new WithingsImpl(); String hash = withings.getHash("<EMAIL>", "d1sn3y"); List<User> users = withings.getUsers("<EMAIL>", hash); for (User user : users) { System.out.println("User: " + user); WithingsCredentials creds = new WithingsCredentials(user); List<MeasurementGroup> measures = withings.getMeasureGroups(creds); System.out.println("Measure: " + measures); } } } <file_sep>/src/main/java/com/acmerocket/chiron/provider/withings/response/ResponseObject.java package com.acmerocket.chiron.provider.withings.response; import com.acmerocket.chiron.provider.withings.model.StatusCode; public interface ResponseObject<T> { public StatusCode getStatus(); public T getBody(); }
dd3c846d78803aa88b657ef9f6bdb85319fa66b1
[ "Java" ]
9
Java
philion/chiron
4114c4b3db3ead62a65dd3307bfa2c74e54101d2
6843d6227e2bea2ef70a92e99194cfabc058b4e2
refs/heads/master
<file_sep><?php require 'vendor/autoload.php'; require 'config/config.php'; if (isset($_GET['img'])) { imgurl_kuri($_GET['img']); } else _kuri();
db162d6b9de82a604a5ba2b66608993ea1c49e4f
[ "PHP" ]
1
PHP
masterforweb/imgurl
d61551aa0877ded0a8141d2a0eed5488e4d82e56
fa9bf28b04b92db953eaa4f7b793f8fc7b2a87dd
refs/heads/master
<file_sep>package cn.com.interfaces; import java.util.List; import cn.com.beans.AnswerBean; /** * @author Xianxiaofei * @date:2014-5-10 上午10:15:09 */ public interface AnswerDaoInf { //根据id得到问题信息 AnswerBean getAnswerByAnswerId(int answer_id); //根据标回答描述得到回答信息 List<AnswerBean> getAnswerByAnswerDescription(String answer_description); //新增回答信息 boolean addAnswer(AnswerBean answerBean); //删除回答信息 boolean deleteAnswer(int answer_id); //查找回答信息 List<AnswerBean> findAnswerByAnswerName(String answer_name); //修改回答信息 boolean updateAnswer(AnswerBean answerBean); //统计某个问题回答总数 int getContOfAnswer(int questionId); //获得热门问题 List<AnswerBean> getHotAnswersByAnswerId(int answerId); } <file_sep>$(document).ready(function() { question_id = $("#questionid").attr('value'); var answerlist = new Array(); var praise = $('#praise'); var tread = $('#tread'); var praises = $('#praises'); // answerlist $('.list-1').each(function() { answerlist.push($(this).children('div.col-lg-1').children('button').first().children('span').attr('id')) }); // question praises $.post('praises', {'question_id': question_id}, function(data) { praises.html(data) }); // answer praisesas and pre answerlist.forEach(function(answerid) { $.post('praisesas', {'answerid' : answerid}, function(data) { var select_id = "#" + answerid; console.log(answerid); $(select_id).html(data); if(data == 1){ $(select_id).parent().attr("value", 1); $(select_id).parent().next().html("<span class=' glyphicon glyphicon-thumbs-up'></span>已赞"); } else if(data == -1){ $(select_id).parent().attr("value", -1); $(select_id).parent().next().next().html("<span class=' glyphicon glyphicon-thumbs-down'></span>已踩"); } else{ $(select_id).parent().attr("value", 0); } }); }); //prepraise $.post('prepraise',{'question_id': question_id}, function(data) { if(data == 1) { praise.attr('value', 1); praise.html("<span class=' glyphicon glyphicon-thumbs-up'></span>已赞"); } if(data == -1){ praise.attr('value', -1); tread.html("<span class=' glyphicon glyphicon-thumbs-down'></span>已踩"); } else{ praise.attr('value', 0); } }); //praise question praise.click(function() { console.log('praise'); $.post('praise', {'question_id': question_id}, function(data) { console.log(data) if (data == "False") { console.log("praised"); } else if (data == "True"){ console.log("success"); $.post('praises', {'question_id': question_id}, function(data) { $('#praises').html(data) }); if(praise.attr('value') == 0){ praise.attr('value', 1) praise.html("<span class=' glyphicon glyphicon-thumbs-up'></span>已赞"); } else if(praise.attr('value') == -1){ praise.attr('value', 1) praise.html("<span class=' glyphicon glyphicon-thumbs-up'></span>已赞"); tread.html("<span class=' glyphicon glyphicon-thumbs-down'></span>踩"); } else { praise.attr('value', 0) praise.html("<span class=' glyphicon glyphicon-thumbs-up'></span>赞"); } } else { console.log(data); console.log("require login"); } }); }); //tread question tread.click(function() { $.post('tread', {'question_id': question_id}, function(data) { if (data == "False") { console.log("treaded"); } else if (data == "True"){ console.log("success"); $.post('praises', {'question_id': question_id}, function(data) { $('#praises').html(data); }); if(praise.attr('value') == 0){ praise.attr('value', -1) tread.html("<span class=' glyphicon glyphicon-thumbs-down'></span>已踩"); } else if(praise.attr('value') == 1){ praise.attr('value', -1); praise.html("<span class=' glyphicon glyphicon-thumbs-up'></span>赞"); tread.html("<span class=' glyphicon glyphicon-thumbs-down'></span>已踩"); } else { praise.attr('value', 0); tread.html("<span class=' glyphicon glyphicon-thumbs-down'></span>踩"); } } else { console.log(data); console.log("require login"); } }); }); }); function praiseas(value){ $.post('praiseas', {'answerid': value}, function(data) { if (data == "False") { console.log("praised"); } else if (data == "True"){ $.post('praisesas', {'answerid' : value}, function(data) { var select_id = "#" + value; console.log(value); $(select_id).html(data); if($(select_id).parent().attr("value") == 1){ $(select_id).parent().attr("value", 0); $(select_id).parent().next().html("<span class=' glyphicon glyphicon-thumbs-up'></span>赞"); } else if($(select_id).parent().attr("value") == -1){ $(select_id).parent().attr("value", 1); $(select_id).parent().next().html("<span class=' glyphicon glyphicon-thumbs-up'></span>已赞"); $(select_id).parent().next().next().html("<span class=' glyphicon glyphicon-thumbs-down'></span>踩"); } else { $(select_id).parent().attr("value", 1); $(select_id).parent().next().html("<span class=' glyphicon glyphicon-thumbs-up'></span>已赞"); } }); } else { console.log(data); console.log("require login"); } }); }; function treadas(value){ $.post('treadas', {'answerid': value}, function(data) { if (data == "False") { console.log("treaded"); } else if (data == "True"){ console.log("success"); $.post('praisesas', {'answerid' : value}, function(data) { var select_id = "#" + value; console.log(value); $(select_id).html(data); if($(select_id).parent().attr("value") == 1){ $(select_id).parent().attr("value", -1); $(select_id).parent().next().html("<span class=' glyphicon glyphicon-thumbs-up'></span>赞"); $(select_id).parent().next().next().html("<span class=' glyphicon glyphicon-thumbs-down'></span>已踩"); } else if($(select_id).parent().attr("value") == -1){ $(select_id).parent().attr("value", 0); $(select_id).parent().next().next().html("<span class=' glyphicon glyphicon-thumbs-down'></span>踩"); } else { $(select_id).parent().attr("value", -1); $(select_id).parent().next().next().html("<span class=' glyphicon glyphicon-thumbs-down'></span>已踩"); } }); } else { console.log(data); console.log("require login"); } }); };<file_sep>package cn.com.mq; import cn.com.daos.UserInfoDaoImp; import cn.com.beans.UserInfoBean; public class FollowSubject extends Subject{ UserInfoDaoImp userdao = new UserInfoDaoImp(); UserInfoBean userbean = new UserInfoBean(); public void bong(int userid, int followingid){ userbean = userdao.getUserInfoByUserId(userid); String str = "2:Äã±»:" + userbean.getUser_name() + ":¹Ø×¢ÁË:" + userid; this.info(followingid, str); } }<file_sep>package cn.com.beans; /** * @author Xianxiaofei * @date:2014-5-21 下午8:35:19 */ /** * * @author Xianxiaofei * QuestionOthesBean用于主页信息显示 */ public class QuestionAllInfoBean { //问题回答数量 private int countOfAnswers; //提问者名称 private String QuestionUserName; //最佳答案 private String bestAnswer; //问题访问量 private int vpOfQuestion; //问题基本信息 private QuestionBean questionBean; public QuestionBean getQuestionBean() { return questionBean; } public void setQuestionBean(QuestionBean questionBean) { this.questionBean = questionBean; } public int getCountOfAnswers() { return countOfAnswers; } public void setCountOfAnswers(int countOfAnswers) { this.countOfAnswers = countOfAnswers; } public String getQuestionUserName() { return QuestionUserName; } public void setQuestionUserName(String questionUserName) { QuestionUserName = questionUserName; } public String getBestAnswer() { return bestAnswer; } public void setBestAnswer(String bestAnswer) { this.bestAnswer = bestAnswer; } public int getVpOfQuestion() { return vpOfQuestion; } public void setVpOfQuestion(int vpOfQuestion) { this.vpOfQuestion = vpOfQuestion; } } <file_sep>package cn.com.beans; public class UserAllInfoBean { private UserInfoBean userInfo; private int askTotal; private int ansTotal; public int getAskTotal() { return askTotal; } public void setAskTotal(int askTotal) { this.askTotal = askTotal; } public int getAnsTotal() { return ansTotal; } public void setAnsTotal(int ansTotal) { this.ansTotal = ansTotal; } public UserInfoBean getUserInfo() { return userInfo; } public void setUserInfo(UserInfoBean userInfo) { this.userInfo = userInfo; } } <file_sep>/** * */ package cn.com.servlets.answer; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import cn.com.beans.AnswerBean; import cn.com.beans.AnswersKeywordsBean; import cn.com.beans.QuestionBean; import cn.com.beans.QuestionsKeywordsBean; import cn.com.beans.UserInfoBean; import cn.com.daos.AnswerDaoImp; import cn.com.daos.AnswersKeywordsDaoImp; import cn.com.daos.QuestionsKeywordsDaoImp; import cn.com.util.ChineseAnalyzerUtil; /*********************** * @author butterfly * @version:1.0 * @created:2014-5-17 *********************** */ /** * @author butterfly * */ public class AddAnswerInfoServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); HttpSession session = request.getSession(); UserInfoBean userInfoBean = (UserInfoBean) session.getAttribute("userBean"); if(userInfoBean == null){ request.getRequestDispatcher("userLogin.jsp").forward(request, response); return; } String answerDescription; int question_id = Integer.parseInt(request.getParameter("question_id")); try{ answerDescription = request.getParameter("answer_description"); System.out.println(answerDescription); }catch(Exception e){ request.setAttribute("question_id", question_id); request.getRequestDispatcher("getDetilQuestion").forward(request, response); return; } System.out.println(question_id); Date date = new Date(); AnswerDaoImp answerDaoImp = new AnswerDaoImp(); AnswerBean answerBean = new AnswerBean(); String dateTimeString = (date.getYear()+1900)+"-"+(date.getMonth()+1)+"-"+date.getDate()+"-"+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds(); answerBean.setAnswer_description(answerDescription); answerBean.setAnswer_time(dateTimeString); answerBean.setAnswer_user_id(userInfoBean.getUser_id()); answerBean.setQuestion_id(question_id); if(answerDaoImp.addAnswer(answerBean)){ //对当前问题分词处理 ChineseAnalyzerUtil chineseAnalyzerUtil = new ChineseAnalyzerUtil(); AnswerBean answerBean1 = new AnswerBean(); answerBean1 = answerDaoImp.getAnswerByAnswerKeywords(answerDescription); int answers_id = answerBean1.getAnswer_id(); StringBuffer answerContext = new StringBuffer(answerBean1.getAnswer_description()); StringBuffer answerContext2 = new StringBuffer(); StringBuffer countTopN = new StringBuffer(); List<Map.Entry<String, Integer>> map = chineseAnalyzerUtil.getAnalyzerKeywordsString(chineseAnalyzerUtil.getTextDef(answerContext.toString())); AnswersKeywordsBean answersKeywordsBean = new AnswersKeywordsBean(); answersKeywordsBean.setAnswers_id(answers_id); //取分词频率最高的前20 for (int i1 = 0; i1 < 20 && i1 < map.size(); i1++) { Map.Entry<String, Integer> wordFrenEntry = map.get(i1); answerContext2.append(wordFrenEntry.getKey()+","); countTopN.append(wordFrenEntry.getValue()+","); } answersKeywordsBean.setAnswers_keywords_topN(answerContext2.toString()); answersKeywordsBean.setAnswers_keywords_counts(countTopN.toString()); ////存入数据库中 AnswersKeywordsDaoImp answersKeywordsDaoImp = new AnswersKeywordsDaoImp(); if(answersKeywordsDaoImp.addAnswersKeywordsBean(answersKeywordsBean)){ System.out.println("新增回答分词处理success!"); } request.setAttribute("question_id", question_id); request.getRequestDispatcher("getDetilQuestion").forward(request, response); return ; }else{ request.setAttribute("Msg", "新增失败"); request.getRequestDispatcher("index.jsp").forward(request, response); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } <file_sep>package cn.com.mservlets.user; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.json.JSONException; import redis.clients.jedis.Jedis; import net.sf.json.JSONObject; import cn.com.beans.AnswerBean; import cn.com.beans.QuestionBean; import cn.com.beans.UserInfoBean; import cn.com.daos.AnswerDaoImp; import cn.com.daos.QuestionDaoImp; import cn.com.daos.UserInfoDaoImp; import cn.com.util.RUtil; public class GetPersionInfoServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RUtil redis = new RUtil(); Jedis rdb = redis.con(); if (request.getParameter("user_id") == null){ HttpSession session = request.getSession(); UserInfoBean uib = (UserInfoBean) session.getAttribute("userBean"); if(uib == null){ request.getRequestDispatcher("userLogin.jsp").forward(request, response); return; } int userID = uib.getUser_id(); QuestionDaoImp questionDao = new QuestionDaoImp(); AnswerDaoImp answerDao = new AnswerDaoImp(); List<QuestionBean> listQuestion = new ArrayList<QuestionBean>(); List<AnswerBean> listAnswer = new ArrayList<AnswerBean>(); listQuestion = questionDao.getQuestionByUserId(userID,0,10); listAnswer = answerDao.getAnswerByUserId(userID); if(listAnswer.size()>10){ listAnswer = listAnswer.subList(0, 10); } QuestionDaoImp questionDaoImp = new QuestionDaoImp(); int len = questionDaoImp.getContOfQuestionByUserId(uib.getUser_id())/10; int countOfQuestion = questionDaoImp.getContOfQuestionByUserId(uib.getUser_id()); // System.out.println("×ÜÒ³Êý£º"+len); request.setAttribute("currentPage", 0); request.setAttribute("len", len); request.setAttribute("listQuestion", listQuestion); request.setAttribute("listAnswer", listAnswer); request.setAttribute("countOfQuestion",countOfQuestion); request.setAttribute("countOfAuswer", listAnswer.size()); request.getRequestDispatcher("person.jsp").forward(request, response); } else{ int userID = Integer.parseInt(request.getParameter("user_id")); UserInfoDaoImp userdao = new UserInfoDaoImp(); UserInfoBean userbean = userdao.getUserInfoByUserId(userID); QuestionDaoImp questionDao = new QuestionDaoImp(); AnswerDaoImp answerDao = new AnswerDaoImp(); List<QuestionBean> listQuestion = new ArrayList<QuestionBean>(); List<AnswerBean> listAnswer = new ArrayList<AnswerBean>(); listQuestion = questionDao.getQuestionByUserId(userID,0,10); listAnswer = answerDao.getAnswerByUserId(userID); if(listAnswer.size()>10){ listAnswer = listAnswer.subList(0, 10); } QuestionDaoImp questionDaoImp = new QuestionDaoImp(); int len = questionDaoImp.getContOfQuestionByUserId(userID)/10; int countOfQuestion = questionDaoImp.getContOfQuestionByUserId(userID); String rank = request.getParameter("rank"); String uid = userID +""; String select_star = "user:" + uid + ":star"; System.out.println(select_star); int begin = 10 * Integer.parseInt(rank); int end = 10 * (Integer.parseInt(rank) + 1) + 1; ArrayList stars = new ArrayList(rdb.zrange(select_star, begin, end)); ArrayList lists = new ArrayList(); for(int i=0; i < stars.size(); i++){ int questionid = Integer.parseInt((String) stars.get(i)); QuestionBean questionBean = questionDaoImp.getQuestionByQuestionId(questionid); JSONObject qs = new JSONObject(); qs.put("questionid", questionid); qs.put("question", questionBean.getQuestion_title()); qs.put("questionTime", questionBean.getQuestion_time()); lists.add(qs); } Map<String,Object> map = new HashMap<String,Object>(); map.put("currentPage", 0); map.put("len", len); map.put("listQuestion", listQuestion); map.put("listAnswer", listAnswer); map.put("countOfQuestion",countOfQuestion); map.put("countOfQuestion",countOfQuestion); map.put("listCollection",lists); JSONObject json = JSONObject.fromObject(map); System.out.println(json); response.getWriter().println(json); } } } <file_sep>package cn.com.util; import redis.clients.jedis.Jedis; public class RUtil{ public Jedis con(){ /*****填写redis数据库相关信息(请查找数据库详情页)*****/ // String databaseName = "DIArawKPnaXwjXHCHVAl"; // String host = "redis.duapp.com"; //127.0.0.1 // String portStr = "80"; //6379 // int port = Integer.parseInt(portStr); // String username = "3dN4oydNzXvFL9NfDmdZ0KhP";//用户名(api key); // String password = "<PASSWORD>";//密码(secret key) // // /******2. 接着连接并选择数据库名为databaseName的服务器******/ // Jedis jedis = new Jedis(host,port); // jedis.connect(); // //auth:简单密码认证 // jedis.auth(username + "-" + password + "-" + databaseName); /*至此连接已完全建立,就可对当前数据库进行相应的操作了*/ Jedis jedis = new Jedis("127.0.0.1",6379); return jedis; } }<file_sep>$(document).ready(function(){ /*$.post('stared', {'question_id':32}, function(data){ //console.log("this question stared"); //console.log(data); });*/ var person_id = $('#person').attr('value'); //console.log(person_id); $.post('stars', {'rank': 0, 'user_id': person_id}, function(data){ var datas = $.parseJSON(data); var html = $('#collectqs').html(); for(i in datas["list"]){ html = html + "<tr><td><a href='getDetilQuestion?question_id=" + datas["list"][i]["questionid"] + "'>" + datas["list"][i]["question"] + "</a></td><td>" + datas["list"][i]["time"] + "</td></tr>"; /*html = html + "<li class='row'>" + "<div class='col-md-2'>" + "<div class='btn btn-primary btn-lg active'>" + "<span class='glyphicon glyphicon-comment'></span> 0<br></div></div>" + "<div class='col-md-8 qa-margin-left'>" + "<p><a href='getDetilQuestion?question_id=" + datas["list"][i]["questionid"] + "'>" + datas["list"][i]["question"] +"</a></p>" + "<div class='qa-tags'>" + "<span class='glyphicon glyphicon-tags'> </span> " + "<a href=''><span class='badge'>linux</span></a>" + "<a href=''><span class='badge'>python</span></a>&nbsp;&nbsp;" + "<span class='glyphicon glyphicon-eye-open'> </span> " + "<span class='badge'>1.2 K</span>&nbsp;&nbsp;" + "<span class='glyphicon glyphicon-time'> </span> " + "<span class='badge'>1 days ago</span></div></div> " + "<div class='col-md-2'>" + "<img src='./static/image/git.png' alt='...' class='qa-img img-circle'></div>"*/ } $('#collectqs').html(html); }) $.post('havestar', {'user_id': person_id}, function(data){ var havastar = "<span class='glyphicon glyphicon-bookmark'></span> 收藏" + data; $('#havastar').html(havastar); }) $.post('follows', {'user_id': person_id}, function(data) { var datas = $.parseJSON(data); //console.log(datas['following']); var following = "<span class='glyphicon glyphicon-user'></span> 关注 " + datas['following'] $('#following').html(following); }); $.post('prefollow', {'user_id': person_id}, function(data) { var pre = $("#prefollow"); if (data == 1) { console.log(1); pre.attr("value", "1") pre.html("已关注") } else { pre.attr("value", "0") pre.html("关注") } }); }); function next_follow(){ var pre = $("#prefollow"); var person_id = $('#person').attr('value'); if (pre.attr("value") == "0"){ $.post('follow', {'following': person_id}, function(data) { if (data == 1) { pre.attr("value", "1") pre.html("已关注") } }); } else{ $.post('unfollow', {'following': person_id}, function(data) { if (data == 1) { pre.attr("value", "0") pre.html("关注") } }); } }<file_sep>package cn.com.daos; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import cn.com.beans.AnswersKeywordsBean; import cn.com.beans.QuestionBean; import cn.com.beans.QuestionsKeywordsBean; import cn.com.interfaces.QuesionsKeywordsInf; import cn.com.util.DBUtil; /** * @author Xianxiaofei * @date:2014年7月30日 下午5:57:41 */ public class QuestionsKeywordsDaoImp implements QuesionsKeywordsInf { private DBUtil db; public QuestionsKeywordsDaoImp() { db = new DBUtil(); } public QuestionsKeywordsBean getQuestionKeyByQuestionId(int questions_id) { // 根据标问题题目得到问题信息 Connection conn = db.getConn(); PreparedStatement pst = null; ResultSet rs = null; QuestionsKeywordsBean qb = new QuestionsKeywordsBean(); String sql = "select * from questions_keywords where questions_id = ?"; try { pst = conn.prepareStatement(sql); pst.setInt(1, questions_id); rs = pst.executeQuery(); if (rs != null) { while (rs.next()) { qb.setQuestions_keywords_id(rs.getInt("questions_keywords_id")); qb.setQuestion_id(rs.getInt("questions_id")); qb.setQuesitons_keywords_topN(rs.getString("quesitons_keywords_topN")); qb.setQuestions_keywords_counts(rs.getString("questions_keywords_counts")); } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { db.free(rs, pst, conn); } return qb; } public List<QuestionsKeywordsBean> getQuestionsKeywordsByKeyWords( String keywords) { // 根据标问题题目得到问题信息 Connection conn = db.getConn(); PreparedStatement pst = null; ResultSet rs = null; List<QuestionsKeywordsBean> list = null; QuestionsKeywordsBean qb = null; String sql = "select * from questions_keywords where quesitons_keywords_topN like ?"; try { pst = conn.prepareStatement(sql); pst.setString(1, "%" + keywords + "%"); rs = pst.executeQuery(); if (rs != null) { list = new ArrayList<QuestionsKeywordsBean>(); while (rs.next()) { qb = new QuestionsKeywordsBean(); qb.setQuestions_keywords_id(rs.getInt("questions_keywords_id")); qb.setQuestion_id(rs.getInt("questions_id")); qb.setQuesitons_keywords_topN(rs.getString("quesitons_keywords_topN")); qb.setQuestions_keywords_counts(rs.getString("questions_keywords_counts")); list.add(qb); } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { db.free(rs, pst, conn); } return list; } public boolean addQuestionsKeywordsBean( QuestionsKeywordsBean questionsKeywordsBean) { // TODO Auto-generated method stub boolean bool = false; Connection connection = db.getConn(); PreparedStatement pstm = null; try { String sql = "Insert into questions_keywords (questions_id,quesitons_keywords_topN,questions_keywords_counts) values(?,?,?)"; pstm = connection.prepareStatement(sql); pstm.setInt(1, questionsKeywordsBean.getQuestion_id()); pstm.setString(2, questionsKeywordsBean.getQuesitons_keywords_topN()); pstm.setString(3, questionsKeywordsBean.getQuestions_keywords_counts()); int len = pstm.executeUpdate(); if (len > 0) { bool = true; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { db.free(pstm, connection); } return bool; } public boolean deleteQuestionsKeywordsBean(int questions_keywords_id){ return false; } } <file_sep>package cn.com.interfaces; import java.util.List; import cn.com.beans.DiscussBean; public interface DiscussDaoInf { //根据id得到评论 DiscussBean getDiscussByDiscussId(int discuss_id); //根评论内容得到评论 List<DiscussBean> getDiscussByDiscussContent(String discuss_content); //根评论问题id得到评论 List<DiscussBean> getDiscussByAnswerId(int answer_id); //新增评论信息 boolean addDiscuss(DiscussBean discussBean); //删除评论信息 boolean deleteDiscussr(int answer_id); //修改评论信息 boolean updateDiscuss(DiscussBean discussBean); //统计某个问题评论总数 int getContOfAnswerDiscuss(int disscussId); //获得热门评论 List<DiscussBean> getHotDiscussByAnswerDiscussId(int discussId); } <file_sep>package com.example.app.hnust_qa.Tools; import android.content.Context; import android.net.wifi.WifiManager; /** * Created by Administrator on 2014/7/31 0031. */ public class NetTool { public static String web = "http://hnustqa.duapp.com/"; public static String sessionId = null; public static String username = null; public static String userId = null; //检查网络 public static boolean isWifiConnected(Context context) { WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); return manager.isWifiEnabled(); } } <file_sep>package cn.com.servlets.category; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.com.beans.QuestionAllInfoBean; import cn.com.beans.QuestionBean; import cn.com.beans.TagsCategoriesBean; import cn.com.beans.TagsInfoBean; import cn.com.beans.UserAllInfoBean; import cn.com.daos.AnswerDaoImp; import cn.com.daos.QuestionDaoImp; import cn.com.daos.TagsCategoriesDao; import cn.com.daos.TagsInfoDaoImp; import cn.com.daos.UserInfoDaoImp; import cn.com.util.GetHotUserInfoUtil; /** * Servlet implementation class GetDetailTagsServlet */ public class GetDetailTagsServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); int tags_categories_id = Integer.parseInt(request .getParameter("tags_categories_id")); //编码转换 String tags_name = request.getParameter("tags_name"); String result = new String(tags_name.getBytes("ISO-8859-1"),"UTF-8"); String tags_id = request.getParameter("tags_id"); System.out.println(result+":"+tags_id); System.out.println(tags_categories_id); QuestionAllInfoBean questionAllInfoBean = null; TagsInfoDaoImp tagsInfoDaoImp = new TagsInfoDaoImp(); TagsCategoriesDao tagsCaregory = new TagsCategoriesDao(); TagsCategoriesBean tagsCB = new TagsCategoriesBean(); QuestionBean questionBean = new QuestionBean(); tagsCB = tagsCaregory.getTagsCategoriesrById(tags_categories_id); UserInfoDaoImp userInfoDaoImp = new UserInfoDaoImp(); QuestionDaoImp questionDao = new QuestionDaoImp(); AnswerDaoImp answerDaoImp = new AnswerDaoImp(); List<QuestionAllInfoBean> listAllQuestions = new ArrayList<QuestionAllInfoBean>(); //正则表达式匹配 Pattern pattern = Pattern.compile("[0-9]*"); List<QuestionBean> listTime = new ArrayList<QuestionBean>(); listTime = questionDao.getQuestionByQuestionByTags(tags_id); // 处理得到的所有问题信息 for (int i = 0; i < listTime.size(); i++) { questionAllInfoBean = new QuestionAllInfoBean(); questionBean = listTime.get(i); if (questionBean.getQuestion_description().length() > 100) { questionBean.setQuestion_description(questionBean .getQuestion_description().substring(0, 100) + "..."); } //得到该问题的标签 String tagsId [] = null; // System.out.println(questionBean.getQuestion_tags()); if(questionBean.getQuestion_tags() == null||questionBean.getQuestion_tags().equals("")){ //这里默认为无,数据库应该插入0为无标签描述,下面的11应该可以改为0 questionBean.setQuestion_tags("暂无"); }else{ if(questionBean.getQuestion_tags() != null&&questionBean.getQuestion_tags().indexOf(",")==-1&&pattern.matcher(questionBean.getQuestion_tags()).matches()){ String tagsStr = tagsInfoDaoImp.getTagsInfoByTagsId(Integer.parseInt(questionBean.getQuestion_tags())).getTags_name(); questionBean.setQuestion_tags(tagsStr); } else{ if(questionBean.getQuestion_tags().indexOf(",")!=-1){ tagsId = questionBean.getQuestion_tags().split(","); StringBuffer tagStrBuffer = new StringBuffer(); for(int i1=0; i1< tagsId.length;i1++){ int tagsIdInt = Integer.parseInt(tagsId[i1]); String tagsStr = tagsInfoDaoImp.getTagsInfoByTagsId(tagsIdInt).getTags_name()+" "; tagStrBuffer.append(tagsStr); } //设置标签为文字显示 questionBean.setQuestion_tags(tagStrBuffer.toString()); } } } String userName = userInfoDaoImp.getUserInfoByUserId( questionBean.getQuestion_user_id()).getUser_name(); int countOfAnswer = answerDaoImp.getContOfAnswer(questionBean .getQuestion_id()); questionAllInfoBean.setQuestionUserName(userName); questionAllInfoBean.setCountOfAnswers(countOfAnswer); questionAllInfoBean.setVpOfQuestion(50); questionAllInfoBean.setBestAnswer("暂无"); questionAllInfoBean.setQuestionBean(questionBean); listAllQuestions.add(questionAllInfoBean); } List<QuestionBean> listHot = new ArrayList<QuestionBean>(); List<QuestionAllInfoBean> listHotQuestions = new ArrayList<QuestionAllInfoBean>(); listHot = questionDao.getHotQuestionByQuestionByTags(tags_id); // 处理得到的所有热门问题信息 for (int i = 0; i < listHot.size(); i++) { questionAllInfoBean = new QuestionAllInfoBean(); questionBean = listHot.get(i); if (questionBean.getQuestion_description().length() > 100) { questionBean.setQuestion_description(questionBean .getQuestion_description().substring(0, 100) + "..."); } //得到该问题的标签 String tagsId [] = null; // System.out.println(questionBean.getQuestion_tags()); if(questionBean.getQuestion_tags() == null||questionBean.getQuestion_tags().equals("")){ //这里默认为无,数据库应该插入0为无标签描述,下面的11应该可以改为0 questionBean.setQuestion_tags("暂无"); }else{ if(questionBean.getQuestion_tags() != null&&questionBean.getQuestion_tags().indexOf(",")==-1&&pattern.matcher(questionBean.getQuestion_tags()).matches()){ String tagsStr = tagsInfoDaoImp.getTagsInfoByTagsId(Integer.parseInt(questionBean.getQuestion_tags())).getTags_name(); questionBean.setQuestion_tags(tagsStr); } else{ if(questionBean.getQuestion_tags().indexOf(",")!=-1){ tagsId = questionBean.getQuestion_tags().split(","); StringBuffer tagStrBuffer = new StringBuffer(); for(int i1=0; i1< tagsId.length;i1++){ int tagsIdInt = Integer.parseInt(tagsId[i1]); String tagsStr = tagsInfoDaoImp.getTagsInfoByTagsId(tagsIdInt).getTags_name()+" "; tagStrBuffer.append(tagsStr); } //设置标签为文字显示 questionBean.setQuestion_tags(tagStrBuffer.toString()); } } } String userName = userInfoDaoImp.getUserInfoByUserId( questionBean.getQuestion_user_id()).getUser_name(); int countOfAnswer = answerDaoImp.getContOfAnswer(questionBean .getQuestion_id()); questionAllInfoBean.setQuestionUserName(userName); questionAllInfoBean.setCountOfAnswers(countOfAnswer); questionAllInfoBean.setVpOfQuestion(50); questionAllInfoBean.setBestAnswer("暂无"); questionAllInfoBean.setQuestionBean(questionBean); listHotQuestions.add(questionAllInfoBean); } System.out.println(tagsCB.getTags_categories_description()); request.setAttribute("tagsDec", tagsCB.getTags_categories_description()); request.setAttribute("listQuestionTime", listAllQuestions); request.setAttribute("listQuestionHot", listHotQuestions); request.setAttribute("tags_name", result); request.getRequestDispatcher("tag_category_detail.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } } <file_sep>package cn.com.mq; import cn.com.daos.QuestionDaoImp; import cn.com.beans.QuestionBean; import cn.com.daos.UserInfoDaoImp; import cn.com.beans.UserInfoBean; public class PraiseSubject extends Subject{ QuestionDaoImp qsdao = new QuestionDaoImp(); QuestionBean qsbean = new QuestionBean(); UserInfoDaoImp userdao = new UserInfoDaoImp(); UserInfoBean userbean = new UserInfoBean(); public void bong(int userid, int questionid){ qsbean = qsdao.getQuestionByQuestionId(questionid); userbean = userdao.getUserInfoByUserId(userid); String str = "3:你的问题:" + qsbean.getQuestion_title() + ":被:" + userbean.getUser_name() + ":赞了:" + questionid + ":" + userid; this.info(qsbean.getQuestion_user_id(), str); } } <file_sep>package com.example.app.hnust_qa; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.app.hnust_qa.Tools.NetTool; import com.example.hnust.R; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Created by Devilsen on 2014/7/30 0030. */ public class LoginActivity extends Activity { private EditText et_username; private EditText et_password; private Button bu_login; private Button bu_register; private String username; private String password; private String userId; private SharedPreferences sp; private String reurl = NetTool.web + "loginMobileServlet"; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.login_layout); sp = this.getSharedPreferences("userInfo", Context.MODE_PRIVATE); et_username = (EditText) findViewById(R.id.et_username); et_password = (EditText) findViewById(R.id.et_password); bu_login = (Button) findViewById(R.id.bu_login); bu_register = (Button) findViewById(R.id.bu_register); autoLoging(); bu_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { username = et_username.getText().toString().trim(); NetTool.username = username; password = et_password.getText().toString().trim(); new URLConnect(LoginActivity.this).execute(); } }); } private boolean autoLoging(){ boolean flag = false; String spUsername = sp.getString("username", ""); String spPassword = sp.getString("password", ""); NetTool.userId = sp.getString("userId", ""); if( !spUsername.isEmpty() || !spPassword.isEmpty() ){ Intent intent = new Intent(LoginActivity.this,MainActivity.class); intent.putExtra("username",spUsername); startActivity(intent); finish(); flag = true; } return flag; } class URLConnect extends AsyncTask<String, Integer, String> { String message; String sessionid; String status = "null"; private Context mContext; private ProgressDialog dialog; public URLConnect(Context mContext) { this.mContext = mContext; initDialog(); } //初始化进度条框 private void initDialog() { dialog = new ProgressDialog(mContext); dialog.setMax(100); // dialog.setCancelable(false);//返回键不可取消 // dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); dialog.setMessage("正在登陆"); } @Override protected void onPreExecute() { super.onPreExecute(); dialog.show(); } @Override protected String doInBackground(String... strings) { try { HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,8000);//核心连接名称。。。 httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,5000); HttpPost httpPost = new HttpPost(reurl); List<NameValuePair> valuePairs = new ArrayList<NameValuePair>(); valuePairs.add(new BasicNameValuePair("user_name", username)); valuePairs.add(new BasicNameValuePair("user_password", <PASSWORD>)); httpPost.setEntity(new UrlEncodedFormEntity(valuePairs)); HttpResponse httpResponse = httpClient.execute(httpPost); if( httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK ){ //获取sessionid String session = httpResponse.getFirstHeader("Set-Cookie").toString(); NetTool.sessionId = session.substring(13,session.indexOf(";")); Log.e("session",session); // Log.e("sessionid",sessionid); HttpEntity httpEntity = httpResponse.getEntity(); String json = EntityUtils.toString(httpEntity, "utf-8"); Log.e("json",json); JSONObject object = new JSONObject(json); message = object.getString("message"); userId = object.getString("userId"); NetTool.userId = userId; status = "true"; }else{ status = "连接错误"; } } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return null; } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); dialog.setProgress(values[0]);//如果是进度条的话,这里来改变进度条的进度。需要在doInBackground方法里添加 publishProgress((int) ((count / (float) length) * 100)); 方法,就是按比例来加进度。同时设置progress的style为dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); if(status.equals("true")){ if(message.equals("true")){ Intent intent = new Intent(LoginActivity.this,MainActivity.class); intent.putExtra("sessionid",sessionid); intent.putExtra("username",username); startActivity(intent); dialog.dismiss(); //保存用户名、密码 Editor editor = sp.edit(); editor.putString("username", username); editor.putString("password", <PASSWORD>); editor.putString("userId", userId); editor.commit(); finish(); }else{ AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this); builder.setTitle("提示"); builder.setMessage("用户名或密码出错了哦(⊙o⊙)"); builder.setPositiveButton("确定",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }).create().show(); } }else if(status.equals("null")){ dialog.dismiss(); Toast.makeText(LoginActivity.this,"服务器无响应",Toast.LENGTH_SHORT).show(); }else{ dialog.dismiss(); Toast.makeText(LoginActivity.this,status,Toast.LENGTH_SHORT).show(); } } } } <file_sep>package cn.com.servlets.question; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import redis.clients.jedis.Jedis; import cn.com.beans.AnswerAllInfoBean; import cn.com.beans.AnswerBean; import cn.com.beans.DiscussAllInfoBean; import cn.com.beans.DiscussBean; import cn.com.beans.QuestionAllInfoBean; import cn.com.beans.QuestionBean; import cn.com.beans.QuestionsKeywordsBean; import cn.com.beans.UserInfoBean; import cn.com.daos.AnswerDaoImp; import cn.com.daos.DiscussDaoImp; import cn.com.daos.QuestionDaoImp; import cn.com.daos.QuestionsKeywordsDaoImp; import cn.com.daos.TagsInfoDaoImp; import cn.com.daos.UserInfoDaoImp; import cn.com.util.RUtil; public class GetDetilQuestion extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 得到传入问题ID HttpSession session = request.getSession(); UserInfoBean uib = (UserInfoBean) session.getAttribute("userBean"); QuestionDaoImp questionDaoImp = new QuestionDaoImp(); // System.out.println(request.getParameter("question_id")); // 正则表达式匹配 Pattern pattern = Pattern.compile("[0-9]*"); TagsInfoDaoImp tagsInfoDaoImp = new TagsInfoDaoImp(); int question_id; try { question_id = Integer.parseInt(request.getParameter("question_id")); } catch (NumberFormatException e) { // 如果传入非数值,跳到首页 response.sendRedirect("index"); return; } // 如果页数小于0 if (question_id < 0) { response.sendRedirect("index"); return; } QuestionBean questionBean = questionDaoImp .getQuestionByQuestionId(question_id); // 得到提问者的名字 UserInfoDaoImp userInfoDaoImp = new UserInfoDaoImp(); String userName = userInfoDaoImp.getUserInfoByUserId( questionBean.getQuestion_user_id()).getUser_name(); // 得到该问题的标签 String tagsId[] = null; // System.out.println(questionBean.getQuestion_tags()); if (questionBean.getQuestion_tags() == null || questionBean.getQuestion_tags().equals("")) { // 这里默认为无,数据库应该插入0为无标签描述,下面的11应该可以改为0 questionBean.setQuestion_tags("暂无"); } else { if (questionBean.getQuestion_tags() != null && questionBean.getQuestion_tags().indexOf(",") == -1 && pattern.matcher(questionBean.getQuestion_tags()) .matches()) { String tagsStr = tagsInfoDaoImp.getTagsInfoByTagsId( Integer.parseInt(questionBean.getQuestion_tags())) .getTags_name(); questionBean.setQuestion_tags(tagsStr); } else { if (questionBean.getQuestion_tags().indexOf(",") != -1) { tagsId = questionBean.getQuestion_tags().split(","); StringBuffer tagStrBuffer = new StringBuffer(); for (int i1 = 0; i1 < tagsId.length; i1++) { int tagsIdInt = Integer.parseInt(tagsId[i1]); String tagsStr = tagsInfoDaoImp.getTagsInfoByTagsId( tagsIdInt).getTags_name() + " "; tagStrBuffer.append(tagsStr); } // 设置标签为文字显示 questionBean.setQuestion_tags(tagStrBuffer.toString()); } } } // 放入完整的问题描述中 QuestionAllInfoBean questionAllInfoBean = new QuestionAllInfoBean(); questionAllInfoBean.setQuestionUserName(userName); questionAllInfoBean.setBestAnswer("无"); questionAllInfoBean.setCountOfAnswers(23); questionAllInfoBean.setVpOfQuestion(50); questionAllInfoBean.setQuestionBean(questionBean); // 得到该问题的所有答案 AnswerDaoImp answerDaoImp = new AnswerDaoImp(); List<AnswerBean> listAnswer = answerDaoImp .findAnswerByQuestionId(question_id); List<AnswerAllInfoBean> listAllAnswer = new ArrayList<AnswerAllInfoBean>(); // 评论获取 List<DiscussAllInfoBean> listAllDiscuss = new ArrayList<DiscussAllInfoBean>(); List<DiscussBean> listdiscussBean = new ArrayList<DiscussBean>(); DiscussDaoImp discussDao = new DiscussDaoImp(); DiscussAllInfoBean discussBean = null; // 用户Dao UserInfoDaoImp userDao = new UserInfoDaoImp(); AnswerAllInfoBean answerAllBean = null; for (int i = 0; i < listAnswer.size(); i++) { answerAllBean = new AnswerAllInfoBean(); String answerUserName = userInfoDaoImp.getUserInfoByUserId( listAnswer.get(i).getAnswer_user_id()).getUser_name(); answerAllBean.setAnswerBean(listAnswer.get(i)); answerAllBean.setUserName(answerUserName); listAllAnswer.add(answerAllBean); // 得到当前循环问题的评论 listdiscussBean = discussDao.getDiscussByAnswerId(listAnswer.get(i) .getAnswer_id()); for (int j = 0; j < listdiscussBean.size(); j++) { // 评论进行封装 discussBean = new DiscussAllInfoBean(); String userDiscussName = userDao.getUserInfoByUserId( listdiscussBean.get(j).getUser_id()).getUser_name(); discussBean.setUserName(userDiscussName); discussBean.setDiscussBean(listdiscussBean.get(j)); listAllDiscuss.add(discussBean); } } // 按热门问题得到信息 List<AnswerBean> listHotAnswer = answerDaoImp .findHotAnswerByQuestionId(question_id); List<AnswerAllInfoBean> listHotAllAnswer = new ArrayList<AnswerAllInfoBean>(); // 评论获取 List<DiscussAllInfoBean> listHotAllDiscuss = new ArrayList<DiscussAllInfoBean>(); List<DiscussBean> listHotdiscussBean = new ArrayList<DiscussBean>(); DiscussAllInfoBean discussHotBean = null; AnswerAllInfoBean answerHotAllBean = null; for (int i = 0; i < listHotAnswer.size(); i++) { answerHotAllBean = new AnswerAllInfoBean(); String answerUserName = userInfoDaoImp.getUserInfoByUserId( listHotAnswer.get(i).getAnswer_user_id()).getUser_name(); answerHotAllBean.setAnswerBean(listHotAnswer.get(i)); answerHotAllBean.setUserName(answerUserName); listHotAllAnswer.add(answerHotAllBean); // 得到当前循环问题的评论 listHotdiscussBean = discussDao.getDiscussByAnswerId(listAnswer .get(i).getAnswer_id()); for (int j = 0; j < listHotdiscussBean.size(); j++) { // 评论进行封装 discussHotBean = new DiscussAllInfoBean(); String userDiscussName = userDao.getUserInfoByUserId( listHotdiscussBean.get(j).getUser_id()).getUser_name(); discussHotBean.setUserName(userDiscussName); discussHotBean.setDiscussBean(listHotdiscussBean.get(j)); listHotAllDiscuss.add(discussHotBean); } } int coutAnswer = listAnswer.size(); // 通过request把所需信息发送给详细问题页面 // 得到问题推荐************************ QuestionsKeywordsDaoImp questionKeyDao = new QuestionsKeywordsDaoImp(); QuestionsKeywordsBean questionsKeywordsBean = new QuestionsKeywordsBean(); // 得到当前问题的分词处理结果 questionsKeywordsBean = questionKeyDao .getQuestionKeyByQuestionId(question_id); String[] tmp = questionsKeywordsBean.getQuesitons_keywords_topN() .split(","); // 根据当前问题结果去匹配所有问题分词 List<QuestionsKeywordsBean> listTemp = new ArrayList<QuestionsKeywordsBean>(); // 封装所有匹配得到的问题ID List<Integer> listQuestionId = new ArrayList<Integer>(); for (int j = 0; j < tmp.length; j++) { listTemp = questionKeyDao.getQuestionsKeywordsByKeyWords(tmp[j]); for (int i = 0; i < listTemp.size(); i++) { int empId = listTemp.get(i).getQuestion_id(); // 如果取得问题ID不等于当前问题ID,则存入 if (empId != question_id) { listQuestionId.add(listTemp.get(i).getQuestion_id()); } } } // 根据得到的问题ID集合得到所有问题后去查找问题信息 List<QuestionBean> questionKeyList = new ArrayList<QuestionBean>(); // 去除重复的ID listQuestionId = this.removeDuplicateWithOrder(listQuestionId); for (int i = 0; i < listQuestionId.size(); i++) { questionKeyList.add(questionDaoImp .getQuestionByQuestionId(listQuestionId.get(i))); } // ******************************** // ***************whether the question belongs to the logined // people***************** if (uib != null) { if (uib.getUser_id() == questionAllInfoBean.getQuestionBean() .getQuestion_user_id()) { request.setAttribute("belong", "1"); } else { request.setAttribute("belong", "0"); } } else { request.setAttribute("belong", "0"); } RUtil redis = new RUtil(); Jedis rdb = redis.con(); String best = "questionid:" + questionAllInfoBean.getQuestionBean().getQuestion_id(); String bestcode = rdb.hget("accept", best); if (bestcode == null) { request.setAttribute("best", "-1"); } else { request.setAttribute("best", bestcode); } request.setAttribute("questionKeyList", questionKeyList); request.setAttribute("listAllDiscuss", listAllDiscuss); request.setAttribute("coutAnswer", coutAnswer); request.setAttribute("question", questionAllInfoBean); request.setAttribute("listAnswer", listAllAnswer); request.setAttribute("listHotAllDiscuss", listHotAllDiscuss); request.setAttribute("listHotAllAnswer", listHotAllAnswer); request.getRequestDispatcher("question_contents.jsp").forward(request, response); } // 去除重复的问题ID public static List removeDuplicateWithOrder(List list) { Set set = new HashSet(); List newList = new ArrayList(); for (Iterator iter = list.iterator(); iter.hasNext();) { Object element = iter.next(); if (set.add(element)) newList.add(element); } return newList; } } <file_sep>package cn.com.beans; /** * @author Xianxiaofei * @date:2014-5-10 上午10:00:48 */ public class AnswerBean { //答案编号 private int answer_id; //答案描述 private String answer_description; //回答时间 private String answer_time; //答案评分(赞、踩) private int answer_mark; //提问用户编号 private int answer_user_id; //所属问题编号 private int question_id; //是否为最佳答案 private int answer_best; //对应的Get、Set方法 public int getAnswer_id() { return answer_id; } public void setAnswer_id(int answer_id) { this.answer_id = answer_id; } public String getAnswer_description() { return answer_description; } public void setAnswer_description(String answer_description) { this.answer_description = answer_description; } public String getAnswer_time() { return answer_time; } public void setAnswer_time(String answer_time) { this.answer_time = answer_time; } public int getAnswer_mark() { return answer_mark; } public void setAnswer_mark(int answer_mark) { this.answer_mark = answer_mark; } public int getAnswer_user_id() { return answer_user_id; } public void setAnswer_user_id(int answer_user_id) { this.answer_user_id = answer_user_id; } public int getQuestion_id() { return question_id; } public void setQuestion_id(int question_id) { this.question_id = question_id; } public int getAnswer_best() { return answer_best; } public void setAnswer_best(int answer_best) { this.answer_best = answer_best; } } <file_sep>package com.example.app.hnust_qa.Tools; import android.app.ActionBar; import android.app.Activity; /** * Created by Administrator on 2014/8/11 0011. */ public class LayoutTool { public static void setCustomTitle(Activity activity,int layout){ activity.getActionBar().setDisplayHomeAsUpEnabled(true); activity.getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); activity.getActionBar().setCustomView(layout); } } <file_sep>/* Navicat MySQL Data Transfer Source Host : localhost:3306 Source Database : hnust_qa Target Host : localhost:3306 Target Database : hnust_qa Date: 2014-10-06 12:51:05 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for answer -- ---------------------------- DROP TABLE IF EXISTS `answer`; CREATE TABLE `answer` ( `answer_id` int(11) NOT NULL AUTO_INCREMENT, `answer_description` varchar(2000) NOT NULL, `answer_time` varchar(50) NOT NULL, `answer_mark` int(11) NOT NULL, `answer_user_id` int(11) NOT NULL, `question_id` int(11) NOT NULL, `answer_best` int(11) NOT NULL, PRIMARY KEY (`answer_id`) ) ENGINE=InnoDB AUTO_INCREMENT=45 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of answer -- ---------------------------- INSERT INTO `answer` VALUES ('1', '据我所知没有.\r\n只有一个参数-Xss可以用来设置每个栈的大小', '2014-05-13', '0', '1', '1', '0'); INSERT INTO `answer` VALUES ('2', '进程是可以控制的,线程的是没法控制的。只能增大Xmx Xms这些参数,或者优化程序。\r\n\r\n避免因为用户查询大量数据占用内存 这个可以通过程序优化的方式来解决,比如:用分页、动态分页、流的方式向前台输出数据(估计jvm没问题浏览器都改卡死了)', '2014-05-13', '0', '2', '1', '0'); INSERT INTO `answer` VALUES ('3', '监视文件变动,可以使用跨平台的 watchdog 模块,不过可能不支持 Python 3。\r\n\r\n在 Linux 平台可以使用 pyinotify 模块。\r\n\r\n一个简单的办法是每隔几秒检查一下文件的 mtime(最后修改时间)(Tornado 使用此法),不过比较耗资源。\r\n\r\nPS: 这些都和 git 不一样。git 有自己的数据库,里边存储了文件的上一个版本。你 git status 时它会把当前工作区的文件和它已经储存的版本进行比对。\r\n\r\nPPS: 所以你的需求还没说清楚。', '2014-05-13', '0', '1', '2', '1'); INSERT INTO `answer` VALUES ('4', '可以参考 django 或 flask 的 debug 模式,这些都会自动检测文件变动,然后重启开发服务器。不过具体我也没研究过它们的实现方式,你可以看看它们的源码', '2014-05-13', '0', '2', '2', '0'); INSERT INTO `answer` VALUES ('5', '这个问题问的好\\(^o^)/~', '2014-5-20- 12:54:31', '0', '1', '0', '0'); INSERT INTO `answer` VALUES ('6', '我不知道这个问题,表问我!!!\r\n', '2014-5-20- 13:13:56', '0', '1', '0', '1'); INSERT INTO `answer` VALUES ('7', '智商捉鸡啊吖,这么弱智的问题也问', '2014-5-20- 13:15:9', '0', '1', '0', '0'); INSERT INTO `answer` VALUES ('8', '今天不下雨,逗比!\r\n', '2014-5-20- 13:18:27', '0', '1', '0', '0'); INSERT INTO `answer` VALUES ('9', '这个........', '2014-5-20- 13:20:4', '0', '1', '0', '1'); INSERT INTO `answer` VALUES ('10', '这个........', '2014-5-20- 13:20:38', '0', '1', '0', '0'); INSERT INTO `answer` VALUES ('11', '两个的值都会提交到服务器端,就看服务器端用的是什么语言了。\r\nasp中根据name取值的话,会是以逗号加空格连接取来的字符串\r\nasp.net中则是以逗号连接起来的字符串\r\n其他语言的就不太清楚了 \r\n\r\nform里面input大概如下3个么?\r\n<input type=\"text\" name=\"test\" value=\"\" style=\"display:\'\';\" ></input>\r\n<input type=\"text\" name=\"test\" value=\"test\" style=\"display:none;\" ></input>\r\n<input type=\"hidden\" name=\"test\" value=\"h\" />\r\n我用Firefox的firebug监控了post的参数,都会提交的,参数名称都是test,只是post的值不一样,这说明浏览器都不把input提交到服务器端的,只是服务器端根据所用的平台及语言接收时候,写法不一样罢了。你在java里面遍历看看 \r\n\r\n查到了,java中如果用request.getParameter(String name)是获得相应名的数据,如果有重复的名,则返回第一个的值 .如果用request.getParameterValues(String name)是获得名字相同,但值有多个的数据, 接收数组变量 。你可以用的是第一个,改用request.getParameterValues就会得到数组,如上面输入abc的话,得到的就是[abc, test, h],至于数组java该怎么用就怎么用了', '2014-6-28- 15:14:10', '0', '1', '0', '0'); INSERT INTO `answer` VALUES ('12', '计算机科学 C语言 等等', '2014-6-28- 15:22:17', '0', '1', '0', '0'); INSERT INTO `answer` VALUES ('13', '我是计算机科学与技术专业的,我们的课程偏软件和网络方向,C语言,数据结构,数电与模电,汇编语言,C++,VC++,数据库,操作系统,计算机网络,计算机组成原理,软件工程,asp,ps,flash,perimer,计算机图形学,Linux(红旗,红帽子,Ubuntu)下的编程与组网服务器的应用,网络工程,计算机前沿技术 一下子就只能想出这么多专业课\r\n各个大学各个专业侧重点会不一样,不过给你说下考研的课程吧。全国都一样 数据结构,操作系统,计算机网络,计算机组成原理 应该是本科阶段的核心课程。\r\n至于编译原理 看自己的兴趣,反正我本科没学,翻过几页', '2014-6-28- 15:29:6', '0', '1', '10', '0'); INSERT INTO `answer` VALUES ('14', '这个不就是科大食府吗?味道一般。。。。。。有时候有石头小青虫会跑出来~~~啦啦啦啦~~', '2014-6-28- 15:33:26', '0', '1', '9', '0'); INSERT INTO `answer` VALUES ('15', '没吃过,不谢\r\n', '2014-6-28- 15:33:50', '0', '1', '9', '0'); INSERT INTO `answer` VALUES ('16', 'MongoDB数据不存在时插入,已存在时更新', '2014-6-28- 15:35:12', '0', '1', '9', '0'); INSERT INTO `answer` VALUES ('17', 'MongoDB数据不存在时插入,已存在时更新', '2014-6-28- 15:39:0', '0', '1', '9', '0'); INSERT INTO `answer` VALUES ('18', '不可以,逗比。大三可以', '2014-6-28- 15:43:33', '0', '1', '8', '0'); INSERT INTO `answer` VALUES ('19', '半个月左右,不放假', '2014-6-28- 15:47:59', '0', '1', '7', '0'); INSERT INTO `answer` VALUES ('20', '周五', '2014-6-28- 20:21:24', '0', '1', '22', '0'); INSERT INTO `answer` VALUES ('21', '你是 范德萨 地方', '2014-6-28- 20:21:38', '0', '1', '22', '0'); INSERT INTO `answer` VALUES ('22', '不认识,呵呵', '2014-7-7- 9:45:31', '0', '1', '23', '0'); INSERT INTO `answer` VALUES ('24', '那就不说啊', '2014-7-13- 22:47:54', '0', '1', '24', '0'); INSERT INTO `answer` VALUES ('25', '问题是个好问题,就是回答不出来 啊', '2014-7-13- 22:48:17', '0', '1', '24', '0'); INSERT INTO `answer` VALUES ('26', '在二本上还可以,湖南比较好的二本院校是:湖南农大,中南林科大,湖南科大,南华大,湖南商学院。\r\n湖南科大主要是在与“采矿”有关的专业比较好,其他就非常一般,假如不想报考与采矿有关的专业建议最好别去,在加上,湖南科大在湘潭这地方不怎么样……除了了毛泽东什么也没有了,长株潭是长沙最好,株洲也不错,湘潭最垃圾,大学地点也比较重要,最好去长沙,湖南农大实力强在长沙,中南林科大也不错,也在长沙,校园风景很好……在市中心!\r\n去湖南科大建议报 采矿 因为湖南科大是前几年合并的大学,以前就没有湖南科大,它是有湘潭工学院与湘潭师专……合并的!\r\n不过现在已经升一本了,貌似出北京广州外均是一本招生。', '2014-7-13- 22:50:52', '0', '1', '26', '0'); INSERT INTO `answer` VALUES ('27', '湖南科技大学地处湘潭,在湖南省排名在第5或第6左右,属於省重点建设大学,第一批本科招生。其中地质勘探专业比较牛。湖南科技大学的综合实力绝对高於湖南农业大学,总所周知,湖南农业大学除了农林方面比较厉害,其他就属於鸡肋专业。湖南科技大学坐落在湘潭,没有省会那麼浮躁,和湘潭大学彼肩而立。绝对是读书的好地方。学生的素质相对还是比较高的。你可以去官网具体瞭解。', '2014-7-13- 22:52:7', '1', '1', '27', '0'); INSERT INTO `answer` VALUES ('28', '我这边也经常进不去,还校园网呢,不过一般早上好进去,试试。。。 不过、、、现在15:49,咦?可以进。。。 这学期的校园网 就是这样让人琢磨不透。', '2014-7-13- 22:55:2', '0', '1', '28', '0'); INSERT INTO `answer` VALUES ('29', '这个系统是湖南科技大学的问答平台,为hnuster提供一个自己学校的百科全书,大家可以提出自己的问题,也可以帮助别人,建立一个互帮互助的网络平台,在开发后期,可以根据相关的信息,构建一个问答网络和好友网络,实现答案推荐和好友推荐。请大家一起维护我们自己的平台,不要灌水,追求绿色和谐!我们一起努力,加油!\r\n 王大锤', '2014-7-14- 15:9:8', '0', '1', '1', '0'); INSERT INTO `answer` VALUES ('30', '就我们四个人玩,太没意思了。都想@许永利了。', '2014-7-14- 20:39:22', '0', '1', '29', '0'); INSERT INTO `answer` VALUES ('31', '比好', '2014-7-19- 16:17:37', '0', '1', '16', '0'); INSERT INTO `answer` VALUES ('32', '我次啊,不用登陆啊', '2014-7-19- 16:18:12', '0', '1', '16', '0'); INSERT INTO `answer` VALUES ('33', '天知道', '2014-7-19- 16:18:53', '0', '1', '26', '0'); INSERT INTO `answer` VALUES ('34', '邮箱验证功能可能无法重复验证多次,这是用于smtp邮箱协议和一些邮箱服务提供商所决定的,他们会把短时间重复发送多次的邮箱比较为垃圾邮箱,所以可能无法验证。如遇到哪这种情况,亲们可以发送邮件给:<EMAIL>,管理员收到邮件后会第一时间处理。', '2014-7-24- 10:47:19', '1', '4', '30', '0'); INSERT INTO `answer` VALUES ('35', '对面相关问题是假的,链接功能根本用不了。还有标签添加了为什么没有反应啊,添加后还是没有显示。求解释?????', '2014-7-24- 10:48:58', '0', '9', '30', '0'); INSERT INTO `answer` VALUES ('36', '有', '2014-7-30- 9:23:6', '0', '17', '31', '0'); INSERT INTO `answer` VALUES ('37', '竟敢如此地侮辱我,你这是作死滴节奏么???', '2014-7-30- 10:31:28', '0', '1', '31', '0'); INSERT INTO `answer` VALUES ('38', '我能经得起多少诋毁,就能经得起多少赞美。Lumia ——不跟随!', '2014-7-30- 10:33:18', '0', '4', '31', '0'); INSERT INTO `answer` VALUES ('39', '测试', '2014-7-30- 15:17:59', '0', '17', '31', '0'); INSERT INTO `answer` VALUES ('40', 'CSS网页中的相对定位与绝对定位在CSS中有这样的一个指令:(position),在DreamWeaver中文版中翻译为“定位”,常用的属性有两个:relative(相对)与 absolute(绝对)。有很多朋友对这条指令的用法还是不清楚,这里做一些细致的讲解。position:relative; 表示相对定位,被定位了这个属性的标签在所属的范围内可以进行上下左右的移,这里的移动与padding或是margin所产生的位置变化是不一样的。padding与margin是元素本身的一种边距与填充距离并不是真正的移动,而被定义为relative的元素是真正的移动,这所产生的移动距离是从margin的外围到父级标签内侧之间这一段。position:absolute; 表示绝对定位,如果定义了这个属性的元素,其位置将依据浏览器左上角的0点开始计算,并且是浮动正常元素之上的。那么当你需要某个元素定位在浏览器内容区的某个地方就可以用到这个属性。于是产生了一个问题:现在大家做的网页大部分是居中的,如果我需要这个元素跟着网页中的某个元素位置,不论屏幕的分辨率是多少它的位置始终是针对页内的某个元素的,靠单纯的absolute是不行的。正确的解决方法是:在元素的父级元素定义为position:relative;(这里可以是祖父级,也可以是position:absolute;,多谢谢old9的提出)需要绝对定位的元素设为position:absolute;这样再设定top,right,bottom,left的值就可以了,这样其定位的参照标准就是父级的左上角padding的左上侧。', '2014-7-31- 12:12:7', '3', '4', '32', '0'); INSERT INTO `answer` VALUES ('41', 'SD ', '2014-8-13- 21:29:20', '1', '1', '32', '0'); INSERT INTO `answer` VALUES ('42', '如果是本地没问题,到BAE上就404,基本上就是因为在BAE上部署的时候报错了。你可以看看部署的时候是不是提示:异常,然后再看看userlog,是不是有对应的错误日志。', '2014-8-26- 18:29:14', '-1', '1', '33', '0'); INSERT INTO `answer` VALUES ('43', '直接将从Myeclips中导出的.war文件上传就行。', '2014-8-26- 18:32:51', '1', '1', '33', '0'); INSERT INTO `answer` VALUES ('44', '', '2014-8-31- 11:44:10', '0', '4', '33', '0'); -- ---------------------------- -- Table structure for answers_keywords -- ---------------------------- DROP TABLE IF EXISTS `answers_keywords`; CREATE TABLE `answers_keywords` ( `answers_keywords_id` int(11) NOT NULL AUTO_INCREMENT, `answers_id` int(11) NOT NULL, `answers_keywords_topN` varchar(2000) DEFAULT NULL, `answers_keywords_counts` varchar(2000) DEFAULT NULL, PRIMARY KEY (`answers_keywords_id`), KEY `answer_id_keywords` (`answers_id`), CONSTRAINT `answer_id_keywords` FOREIGN KEY (`answers_id`) REFERENCES `answer` (`answer_id`) ) ENGINE=InnoDB AUTO_INCREMENT=44 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of answers_keywords -- ---------------------------- INSERT INTO `answers_keywords` VALUES ('1', '1', '参数,大小,设置,xss,', '1,1,1,1,'); INSERT INTO `answers_keywords` VALUES ('2', '2', '优化,程序,数据,控制,方式,分页,参数,只能,内存,jvm,线程,查询,进程,前台,动态,浏览器,xmx,增大,xms,输出,', '2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,'); INSERT INTO `answers_keywords` VALUES ('3', '3', '文件,git,平台,版本,模块,比对,不支持,需求,里边,资源,时间,pyinotify,python,变动,不一样,还没,上一个,检查一下,简单,储存,', '4,3,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,'); INSERT INTO `answers_keywords` VALUES ('4', '4', '自动检测,源码,参考,flask,开发,服务器,django,debug,都会,变动,模式,方式,重启,研究,文件,', '1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,'); INSERT INTO `answers_keywords` VALUES ('5', '5', '', ''); INSERT INTO `answers_keywords` VALUES ('6', '6', '不知道,问我,', '1,1,'); INSERT INTO `answers_keywords` VALUES ('7', '7', '弱智,智商,', '1,1,'); INSERT INTO `answers_keywords` VALUES ('8', '8', '不下雨,', '1,'); INSERT INTO `answers_keywords` VALUES ('9', '9', '', ''); INSERT INTO `answers_keywords` VALUES ('10', '10', '', ''); INSERT INTO `answers_keywords` VALUES ('11', '11', 'input,test,服务器端,type,数组,语言,java,abc,request.getparametervalues,text,交到,display,逗号,参数,数据,都会,不一样,style,post,第一个,', '7,6,4,3,3,3,3,2,2,2,2,2,2,2,2,2,2,2,2,2,'); INSERT INTO `answers_keywords` VALUES ('12', '12', '计算机,科学,语言,', '1,1,1,'); INSERT INTO `answers_keywords` VALUES ('13', '13', '计算机,原理,课程,本科,数据结构,操作系统,专业,计算机网络,flash,只能,技术,红帽子,网络,大学,说下,几页,没学,图形学,前沿技术,编译,', '5,3,3,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,'); INSERT INTO `answers_keywords` VALUES ('14', '14', '大食,不就是,有时候,石头,味道,跑出来,', '1,1,1,1,1,1,'); INSERT INTO `answers_keywords` VALUES ('15', '15', '没吃过,', '1,'); INSERT INTO `answers_keywords` VALUES ('16', '16', '数据,更新,mongodb,插入,不存在,', '1,1,1,1,1,'); INSERT INTO `answers_keywords` VALUES ('17', '17', '数据,更新,mongodb,插入,不存在,', '1,1,1,1,1,'); INSERT INTO `answers_keywords` VALUES ('18', '18', '大三,不可以,', '1,1,'); INSERT INTO `answers_keywords` VALUES ('19', '19', '放假,半个月,', '1,1,'); INSERT INTO `answers_keywords` VALUES ('20', '20', '周五,', '1,'); INSERT INTO `answers_keywords` VALUES ('21', '21', '地方,', '1,'); INSERT INTO `answers_keywords` VALUES ('22', '22', '不认识,', '1,'); INSERT INTO `answers_keywords` VALUES ('23', '24', '那就,不说,', '1,1,'); INSERT INTO `answers_keywords` VALUES ('24', '25', '问题是,不出来,回答,', '1,1,1,'); INSERT INTO `answers_keywords` VALUES ('25', '26', '湖南,科大,湘潭,长沙,采矿,二本,专业,建议,大学,一本,不错,比较好,农大,中南林,合并,北京,南华,师专,报考,地方,', '10,8,4,4,3,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,'); INSERT INTO `answers_keywords` VALUES ('26', '27', '湖南,科技大学,湘潭,专业,大学,农业大学,厉害,落在,地处,鸡肋,农林,读书,素质,地质勘探,本科,综合,去官,排名,学生,好地方,', '5,3,3,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,'); INSERT INTO `answers_keywords` VALUES ('27', '28', '校园网,49,学期,早上好,琢磨不透,15,试试,进不去,', '2,1,1,1,1,1,1,1,'); INSERT INTO `answers_keywords` VALUES ('28', '29', '平台,网络,推荐,和好友,问答,开发,构建,加油,绿色,科技大学,信息,答案,提供,后期,百科全书,灌水,互帮互助,和谐,建立,学校,', '3,3,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,'); INSERT INTO `answers_keywords` VALUES ('29', '30', '太没,四个人,都想,', '1,1,1,'); INSERT INTO `answers_keywords` VALUES ('30', '31', '', ''); INSERT INTO `answers_keywords` VALUES ('31', '32', '登陆,不用,', '1,1,'); INSERT INTO `answers_keywords` VALUES ('32', '33', '天知道,', '1,'); INSERT INTO `answers_keywords` VALUES ('33', '34', '邮箱,验证,邮件,发送,重复,smtp,会把,收到,提供商,第一时间,议和,这是,<EMAIL>,用于,后会,情况,短时间,管理员,功能,服务,', '5,3,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,'); INSERT INTO `answers_keywords` VALUES ('34', '35', '没有反应,显示,用不了,问题是,对面,标签,加了,功能,链接,相关,添加,解释,', '1,1,1,1,1,1,1,1,1,1,1,1,'); INSERT INTO `answers_keywords` VALUES ('35', '36', '', ''); INSERT INTO `answers_keywords` VALUES ('36', '37', '节奏,作死,竟敢,这是,侮辱,', '1,1,1,1,1,'); INSERT INTO `answers_keywords` VALUES ('37', '38', '经得起,诋毁,就能,lumia,跟随,赞美,', '2,1,1,1,1,1,'); INSERT INTO `answers_keywords` VALUES ('38', '39', '测试,', '1,'); INSERT INTO `answers_keywords` VALUES ('39', '40', '元素,定位,position,absolute,relative,位置,属性,padding,margin,定义,网页,就可以,位在,浏览器,以是,指令,css,距离,标签,左上角,', '11,7,6,5,4,4,4,3,3,3,3,2,2,2,2,2,2,2,2,2,'); INSERT INTO `answers_keywords` VALUES ('40', '41', 'sd,', '1,'); INSERT INTO `answers_keywords` VALUES ('41', '42', '是不是,bae,部署,看看,时候,错误,可以,然后再,提示,基本上,userlog,异常,错了,就是,如果是,因为,日志,对应,404,本地,', '2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,'); INSERT INTO `answers_keywords` VALUES ('42', '43', '上传,直接,将从,文件,就行,war,导出,myeclips,', '1,1,1,1,1,1,1,1,'); INSERT INTO `answers_keywords` VALUES ('43', '44', '', ''); -- ---------------------------- -- Table structure for crawl -- ---------------------------- DROP TABLE IF EXISTS `crawl`; CREATE TABLE `crawl` ( `id` int(11) NOT NULL AUTO_INCREMENT, `question_id` int(11) NOT NULL, `title` varchar(500) COLLATE utf8_bin NOT NULL, `url` varchar(500) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=371 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- ---------------------------- -- Records of crawl -- ---------------------------- INSERT INTO `crawl` VALUES ('1', '31', '请问乡情爱情还有没有第6部_360问答', 'http://wenda.so.com/q/1404453086726473'); INSERT INTO `crawl` VALUES ('2', '31', 'QQ飞车里的剧情(暴风第6人)怎么没有了!还有请问怎样可以刷级...', 'http://wenda.so.com/q/1371017337066865'); INSERT INTO `crawl` VALUES ('3', '31', '新银~请问~还有第六季吗_虚幻勇士吧_百度贴吧', 'http://tieba.baidu.com/p/2819270102'); INSERT INTO `crawl` VALUES ('4', '31', '药物流产第一天流出胎儿之后就没再流血第六天B超显示宫内有...', 'http://wenda.so.com/q/1366221882069364'); INSERT INTO `crawl` VALUES ('5', '31', '生化危机5还没有结束生化。请问还有第6部? - 已回答 - 搜搜问...', 'http://wenwen.sogou.com/z/q406484337.htm'); INSERT INTO `crawl` VALUES ('6', '31', '请问月经第六天了怎么还有血_好大夫在线', 'http://www.haodf.com/wenda/licunli_g_755197744.htm'); INSERT INTO `crawl` VALUES ('7', '31', '请问我人流第6天,可是还有血流出,量不是很大,一直在吃新生化...', 'http://club.xywy.com/static/2454/1226875.htm'); INSERT INTO `crawl` VALUES ('8', '31', '你好:请问第六城摩卡商业街小平米商铺还有吗?是多在平米的?...', 'http://www.jiwu.com/wenda/3920403.html'); INSERT INTO `crawl` VALUES ('9', '31', '我的月经推迟了7天了,昨天第六天晚上的时候我测试了一下,没...', 'http://wenda.so.com/q/1367946721067379'); INSERT INTO `crawl` VALUES ('10', '31', '《嘻哈四重奏-第五季》结束,请问何时出第六季?_卢正雨吧_百...', 'http://tieba.baidu.com/p/2749074239'); INSERT INTO `crawl` VALUES ('11', '33', '关于java程序在BAE3.0上部署关于java程序在BAE3.0上部署80...', 'http://www.uukkuu.com/v617092905534185612/'); INSERT INTO `crawl` VALUES ('12', '33', '【BAE3.0使用系列】Java Runtime简介_bae吧_百度贴吧', 'http://tieba.baidu.com/p/2574882923'); INSERT INTO `crawl` VALUES ('13', '33', '如何在BAE3.0中部署wordpress_互联网_百度经验', 'http://jingyan.baidu.com/album/fb48e8be5bac1d6e622e14c1.html'); INSERT INTO `crawl` VALUES ('14', '33', '百度BAE2.0 JAVA环境项目部署和调试- using - 开源中国社区', 'http://my.oschina.net/using/blog/167038'); INSERT INTO `crawl` VALUES ('15', '33', '【每日一博】百度BAE JAVA环境项目部署和调试- 看引擎KEN...', 'http://www.kankanews.com/ICkengine/archives/56648.shtml'); INSERT INTO `crawl` VALUES ('16', '33', 'servlet相关jar包位置BAE上部署web应用- Yogurshine - 博客园', 'http://www.cnblogs.com/Yogurshine/p/3171142.html'); INSERT INTO `crawl` VALUES ('17', '33', '【BAE3.0使用系列】Java博客--Dlog4j的移植| BAE技术博客', 'http://godbae.duapp.com/?p=249'); INSERT INTO `crawl` VALUES ('18', '33', '(转)微信公众平台开发之基于百度BAE3.0 的开发环境搭建(采用...', 'http://www.cnblogs.com/ixxonline/p/3659434.html'); INSERT INTO `crawl` VALUES ('19', '33', '百度BAE JAVA环境项目部署和调试-Java-第七城市', 'http://www.th7.cn/Program/java/201310/153446.shtml'); INSERT INTO `crawl` VALUES ('20', '33', '百度开放云平台', 'http://developer.baidu.com/events/bae3'); INSERT INTO `crawl` VALUES ('21', '33', '关于java程序在BAE3.0上部署关于java程序在BAE3.0上部署80...', 'http://www.uukkuu.com/v617092905534185612/'); INSERT INTO `crawl` VALUES ('22', '33', '【BAE3.0使用系列】Java Runtime简介_bae吧_百度贴吧', 'http://tieba.baidu.com/p/2574882923'); INSERT INTO `crawl` VALUES ('23', '33', '如何在BAE3.0中部署wordpress_互联网_百度经验', 'http://jingyan.baidu.com/album/fb48e8be5bac1d6e622e14c1.html'); INSERT INTO `crawl` VALUES ('24', '33', '百度BAE2.0 JAVA环境项目部署和调试- using - 开源中国社区', 'http://my.oschina.net/using/blog/167038'); INSERT INTO `crawl` VALUES ('25', '33', '【每日一博】百度BAE JAVA环境项目部署和调试- 看引擎KEN...', 'http://www.kankanews.com/ICkengine/archives/56648.shtml'); INSERT INTO `crawl` VALUES ('26', '33', 'servlet相关jar包位置BAE上部署web应用- Yogurshine - 博客园', 'http://www.cnblogs.com/Yogurshine/p/3171142.html'); INSERT INTO `crawl` VALUES ('27', '33', '【BAE3.0使用系列】Java博客--Dlog4j的移植| BAE技术博客', 'http://godbae.duapp.com/?p=249'); INSERT INTO `crawl` VALUES ('28', '33', '(转)微信公众平台开发之基于百度BAE3.0 的开发环境搭建(采用...', 'http://www.cnblogs.com/ixxonline/p/3659434.html'); INSERT INTO `crawl` VALUES ('29', '33', '百度BAE JAVA环境项目部署和调试-Java-第七城市', 'http://www.th7.cn/Program/java/201310/153446.shtml'); INSERT INTO `crawl` VALUES ('30', '33', 'Bae3.0计费说明| 岭南六少- 一朵在LAMP架构下挣扎的云', 'http://blog.chedushi.com/archives/7297'); INSERT INTO `crawl` VALUES ('31', '27', '湖南科技大学什么专业最好?_360问答', 'http://wenda.so.com/q/1365838327064957'); INSERT INTO `crawl` VALUES ('32', '27', '湖南科技大学优势专业排名及最好的专业有哪些_大学专业', 'http://www.ccutu.com/gaokao/17290.shtml'); INSERT INTO `crawl` VALUES ('33', '27', '湖南科技大学最好的专业 - 特色专业 - 萝卜侠网 - 高考,志愿,填...', 'http://www.luoboxia.com/best-majors/10534.html'); INSERT INTO `crawl` VALUES ('34', '27', '我的大学-湖南科技大学最好的本科专业是哪个啊', 'http://bbs.rednet.cn/thread-25074484-1-1.html'); INSERT INTO `crawl` VALUES ('35', '27', '湖南科技大学,的重点专业是哪些?', 'http://wenwen.sogou.com/z/q210664149.htm'); INSERT INTO `crawl` VALUES ('36', '27', '湖南科技大学什么专业好?_湖南科技大学吧_百度贴吧', 'http://tieba.baidu.com/p/125493668'); INSERT INTO `crawl` VALUES ('37', '27', '湖南科技大学什么专业最好_2014湖南科技大学的专业怎么样_...', 'http://gaokao.0s.net.cn/tesezhuanye/hnkjdx/'); INSERT INTO `crawl` VALUES ('38', '27', '湖南科技大学里面什么专业比较好_百度知道', 'http://zhidao.baidu.com/question/103809922.html'); INSERT INTO `crawl` VALUES ('39', '27', '湖南科技大学哪个专业好?_百度知道', 'http://zhidao.baidu.com/question/97252518.html'); INSERT INTO `crawl` VALUES ('40', '27', '湖南科技大学有什么专业比较好~~_天涯问答', 'http://wenda.tianya.cn/question/6b05425863e2a44c'); INSERT INTO `crawl` VALUES ('41', '24', '一句话说不清楚,形容事情很复杂 是什么成语', 'http://iask.sina.com.cn/b/f1rGsxouR.html'); INSERT INTO `crawl` VALUES ('42', '24', '求求大家帮帮忙谢谢了:事情是我与邻居之间的矛盾,听起来感觉...', 'http://wenda.so.com/q/1377339787064329'); INSERT INTO `crawl` VALUES ('43', '24', '怎么在中国知网下东西?_firefox吧_百度贴吧', 'http://tieba.baidu.com/p/2083814776'); INSERT INTO `crawl` VALUES ('44', '24', 'V 357 缘嫁首长老公- 请看小说网', 'http://www.qingkan.net/book/yuanjiashouchanglaogong/4694837.html'); INSERT INTO `crawl` VALUES ('45', '24', '如何看待中国学术造假? - 步行街- 虎扑篮球论坛', 'http://bbs.hupu.com/8073776.html'); INSERT INTO `crawl` VALUES ('46', '24', '艺术,一句话说不清楚(《国家美术》杂志,王天德创作访谈) - 《国...', 'http://blog.artintern.net/article/58072'); INSERT INTO `crawl` VALUES ('47', '24', '《网游之我是NPC》第十三章豆豆删号了- 原创首发- 《小说阅...', 'http://www.readnovel.com/novel/12230/13.html'); INSERT INTO `crawl` VALUES ('48', '24', '好想给前男友打电话,可是我不知道第一句话说什么', 'http://wenwen.sogou.com/z/q421755508.htm'); INSERT INTO `crawl` VALUES ('49', '24', '有没有萍乡的朋友?急事相求_李宇春吧_百度贴吧', 'http://tieba.baidu.com/p/488896278'); INSERT INTO `crawl` VALUES ('50', '24', '一句话两句话说不清楚的问题看看吧100分! - 已解决- 搜狗问问', 'http://wenwen.sogou.com/z/q209292169.htm'); INSERT INTO `crawl` VALUES ('51', '36', 'TAG: 检测- 分析测试百科网', 'http://www.antpedia.com/?action-tag-tagname-%E6%A3%80%E6%B5%8B'); INSERT INTO `crawl` VALUES ('52', '36', 'Vlan 测试实战(tag untag pvid vid )_百度文库', 'http://wenku.baidu.com/view/da3be3c608a1284ac85043e8.html'); INSERT INTO `crawl` VALUES ('53', '36', '【安卓龙珠TAG VS游戏测试】完美能玩了我是有好激动!BGM...', 'http://tieba.baidu.com/p/2368565279'); INSERT INTO `crawl` VALUES ('54', '36', 'VLAN 测试实战(TAG UNTAG PVID VID ) - 豆丁网', 'http://www.docin.com/p-392969719.html'); INSERT INTO `crawl` VALUES ('55', '36', '趣味测试TAG标签_Txt电子书下载_一博书库', 'http://www.ebookcn.com/tag/%E8%B6%A3%E5%91%B3%E6%B5%8B%E8%AF%95'); INSERT INTO `crawl` VALUES ('56', '36', '[个人测试] 龙珠TAG VS。_ppsspp吧_百度贴吧', 'http://tieba.baidu.com/p/2374227481'); INSERT INTO `crawl` VALUES ('57', '36', '《剑网三》团队事件监控官方测试TAG--可随意修改资料库', 'http://tag.j3ui.com/10/Buff'); INSERT INTO `crawl` VALUES ('58', '36', 'VLAN 测试实战(TAG UNTAG PVID VID ) - 技术总结- 道客巴巴', 'http://www.doc88.com/p-436727263401.html'); INSERT INTO `crawl` VALUES ('59', '36', '测试tag 临时用- 都市小说- 红袖添香', 'http://novel.hongxiu.com/a/69760/'); INSERT INTO `crawl` VALUES ('60', '36', 'Vlan 测试实战(tag untag pvid vid ) - 豆丁网', 'http://www.docin.com/p-537535966.html'); INSERT INTO `crawl` VALUES ('61', '10', '专业课程_360百科', 'http://baike.so.com/doc/6743502.html'); INSERT INTO `crawl` VALUES ('62', '10', '大学有哪些专业 专业课程是什么 - 学校大全', 'http://xuexiao.chazidian.com/news60267/'); INSERT INTO `crawl` VALUES ('63', '10', '市场营销专业课程', 'http://www.oh100.com/a/201106/1087.html'); INSERT INTO `crawl` VALUES ('64', '10', '大学英语专业课程有哪些_360问答', 'http://wenda.so.com/q/1361983100061558'); INSERT INTO `crawl` VALUES ('65', '10', '旅游管理的专业课程有哪些?_360问答', 'http://wenda.so.com/q/1361504792067323'); INSERT INTO `crawl` VALUES ('66', '10', '会计专业有哪些课程?_360问答', 'http://wenda.so.com/q/1378240055060890'); INSERT INTO `crawl` VALUES ('67', '10', '土木工程专业课程_百度百科', 'http://baike.baidu.com/view/3950723.htm'); INSERT INTO `crawl` VALUES ('68', '10', '汉语言文学专业课程简介', 'http://www.douban.com/group/topic/16320721/'); INSERT INTO `crawl` VALUES ('69', '10', '护理专业课程介绍', 'http://www.houxue.com/kecheng/334223/'); INSERT INTO `crawl` VALUES ('70', '10', '法学专业课程', 'http://www.oh100.com/a/201106/1463.html'); INSERT INTO `crawl` VALUES ('71', '37', '实名举报晋城市文化局刘小飞这个SB! 删帖的请自重!(转载)_哈...', 'http://blog.sina.com.cn/s/blog_67af5eca0101d27x.html'); INSERT INTO `crawl` VALUES ('72', '37', '张小飞_360百科', 'http://baike.so.com/doc/6123674-6336829.html'); INSERT INTO `crawl` VALUES ('73', '37', 'LOL体验服的SB。叫Angle丶小飞。看到了喷死他- 已回答- 搜狗...', 'http://wenwen.sogou.com/z/q402282179.htm'); INSERT INTO `crawl` VALUES ('74', '37', '小飞160E1SB93,近期RP大爆发,完美屏!_穗城春秋_新浪博客', 'http://blog.sina.com.cn/s/blog_643fcfcc0100iaw4.html'); INSERT INTO `crawl` VALUES ('75', '37', '不要啃旧帖屁股了,小飞的sb庄,炒股炒成股东了_飞乐音响(600...', 'http://guba.eastmoney.com/news,600651,52336352.html'); INSERT INTO `crawl` VALUES ('76', '37', 'Sb//白小飞_土豆_高清视频在线观看', 'http://www.tudou.com/programs/view/DiCdqGjlvXY/'); INSERT INTO `crawl` VALUES ('77', '37', '000900的sb小飞_现代投资(000900)股吧_东方财富网股吧', 'http://guba.eastmoney.com/news,000900,4866711.html'); INSERT INTO `crawl` VALUES ('78', '37', '看看这SB,小飞大神好心给他带玩,结果吧别人装备宝石全部分解...', 'http://tieba.baidu.com/p/3086107543'); INSERT INTO `crawl` VALUES ('79', '37', 'SB小飞的视频空间_SB小飞的视频专辑、相册_56.com', 'http://i.56.com/u/r791997769'); INSERT INTO `crawl` VALUES ('80', '37', '水沟们,谁听过龙翔小飞这个SB名字进来下! - 真三国无双- 游久...', 'http://bbs.uuu9.com/thread-7071038-1-1.html'); INSERT INTO `crawl` VALUES ('81', '38', '消费日报网-消费日报社官方网站', 'http://www.xfrb.com.cn/'); INSERT INTO `crawl` VALUES ('82', '38', '消费_360百科', 'http://baike.so.com/doc/5414637-5652779.html'); INSERT INTO `crawl` VALUES ('83', '38', '中国汽车消费网_中国汽车消费门户', 'http://www.315che.com/'); INSERT INTO `crawl` VALUES ('84', '38', 'xiaofei的微博_腾讯微博', 'http://t.qq.com/xiaofei_xfcat'); INSERT INTO `crawl` VALUES ('85', '38', 'Xiaofei Lu', 'http://www.personal.psu.edu/xxl13/'); INSERT INTO `crawl` VALUES ('86', '38', 'xiaofei5184的BLOG xiaofei5184_新浪博客', 'http://blog.sina.com.cn/xiaofei5184'); INSERT INTO `crawl` VALUES ('87', '38', 'xiaofei123xiaofei123的视频空间_xiaofei123xiaofei123的视频专...', 'http://xiaofei123xiaofei123.56.com/'); INSERT INTO `crawl` VALUES ('88', '38', '落叶知秋的博客xiaofei_新浪博客', 'http://blog.sina.com.cn/guaguagrandma'); INSERT INTO `crawl` VALUES ('89', '38', 'xiaofei 有多少xiaofei,xiaofei同名同姓-人人网校内', 'http://name.renren.com/TongMing1018794'); INSERT INTO `crawl` VALUES ('90', '38', 'xiaofei217 视频_播客_个人多媒体土豆网', 'http://www.tudou.com/home/xiaofei217/'); INSERT INTO `crawl` VALUES ('91', '1', '三姑六婆这是干什么的_360问答', 'http://wenda.so.com/q/1391469760061820'); INSERT INTO `crawl` VALUES ('92', '1', 'MDAC_TYP.EXE 这是干什么用的啊?_360问答', 'http://wenda.so.com/q/1362089122067071'); INSERT INTO `crawl` VALUES ('93', '1', '这是干什么用的? | 问答| 果壳网科技有意思', 'http://www.guokr.com/question/222628/'); INSERT INTO `crawl` VALUES ('94', '1', '02195512这是干啥的电话啊?_360问答', 'http://wenda.so.com/q/1375306847062017'); INSERT INTO `crawl` VALUES ('95', '1', '东京知名红灯区猜出这是干啥的都是流氓- 图说海外- 铁血社区', 'http://bbs.tiexue.net/post_4799186_1.html'); INSERT INTO `crawl` VALUES ('96', '1', '这个是用来干什么的? 用英文怎么说[1]', 'http://bbs.globalimporter.net/bbsdetail-N11101102-45036-1.htm'); INSERT INTO `crawl` VALUES ('97', '1', '武警这是干啥用的? - 警察之家- 铁血社区', 'http://bbs.tiexue.net/post_4156800_1.html'); INSERT INTO `crawl` VALUES ('98', '1', '这是干什么的? - 竞技家越野e族论坛越野/SUV/旅行/赛事/改装/...', 'http://bbs.fblife.com/thread_3469541_3.html'); INSERT INTO `crawl` VALUES ('99', '1', 'tts service 这是干什么的程序啊,这个进程可以关闭吗,HTC Des...', 'http://bbs.gfan.com/android-613548-1-1.html'); INSERT INTO `crawl` VALUES ('100', '1', '楼主,给你经验拿好!哎…你这是干什么!不用!真不用!你快起来!_...', 'http://tieba.baidu.com/p/2060522937'); INSERT INTO `crawl` VALUES ('101', '1', '三姑六婆这是干什么的_360问答', 'http://wenda.so.com/q/1391469760061820'); INSERT INTO `crawl` VALUES ('102', '1', 'MDAC_TYP.EXE 这是干什么用的啊?_360问答', 'http://wenda.so.com/q/1362089122067071'); INSERT INTO `crawl` VALUES ('103', '1', '这是干什么用的? | 问答| 果壳网科技有意思', 'http://www.guokr.com/question/222628/'); INSERT INTO `crawl` VALUES ('104', '1', '02195512这是干啥的电话啊?_360问答', 'http://wenda.so.com/q/1375306847062017'); INSERT INTO `crawl` VALUES ('105', '1', '东京知名红灯区猜出这是干啥的都是流氓- 图说海外- 铁血社区', 'http://bbs.tiexue.net/post_4799186_1.html'); INSERT INTO `crawl` VALUES ('106', '1', '这个是用来干什么的? 用英文怎么说[1]', 'http://bbs.globalimporter.net/bbsdetail-N11101102-45036-1.htm'); INSERT INTO `crawl` VALUES ('107', '1', '武警这是干啥用的? - 警察之家- 铁血社区', 'http://bbs.tiexue.net/post_4156800_1.html'); INSERT INTO `crawl` VALUES ('108', '1', '这是干什么的? - 竞技家越野e族论坛越野/SUV/旅行/赛事/改装/...', 'http://bbs.fblife.com/thread_3469541_3.html'); INSERT INTO `crawl` VALUES ('109', '1', 'tts service 这是干什么的程序啊,这个进程可以关闭吗,HTC Des...', 'http://bbs.gfan.com/android-613548-1-1.html'); INSERT INTO `crawl` VALUES ('110', '1', '楼主,给你经验拿好!哎…你这是干什么!不用!真不用!你快起来!_...', 'http://tieba.baidu.com/p/2060522937'); INSERT INTO `crawl` VALUES ('111', '29', '我是大三计算机专业,下个学期要找工作,想在暑假的时候做点项...', 'http://wenda.so.com/q/1394125949065582'); INSERT INTO `crawl` VALUES ('112', '29', '大学里电脑艺术设计专业学什么课程_360问答', 'http://wenda.so.com/q/1364884751063451'); INSERT INTO `crawl` VALUES ('113', '29', '动漫设计专业都是教什么的、一般出来是做什么工作呢?_360问...', 'http://wenda.so.com/q/1361553581069612'); INSERT INTO `crawl` VALUES ('114', '29', '技校都有什么专业|不上学可以去干吗|计算机专业都有什么课程...', 'http://www.studyems.com/bmcenter/em779e5c6c12f7764cs.php'); INSERT INTO `crawl` VALUES ('115', '29', '中专学计算机平面设计专业有什么课程_360问答', 'http://wenda.so.com/q/1359572472069815'); INSERT INTO `crawl` VALUES ('116', '29', '制作动画用什么工具我要课程设计是做液压的因为是要它运动所...', 'http://iask.sina.com.cn/b/8102174.html'); INSERT INTO `crawl` VALUES ('117', '29', '计算机科学与技术(图形图像)专业出来是做什么的?主要的课程...', 'http://wenwen.sogou.com/z/q212473392.htm'); INSERT INTO `crawl` VALUES ('118', '29', 'UI设计具体是做什么的哟?大学有这个课程吗?好像我都没有听说...', 'http://tieba.baidu.com/p/1739139840'); INSERT INTO `crawl` VALUES ('119', '29', '电脑设计_360百科', 'http://baike.so.com/doc/6069276.html'); INSERT INTO `crawl` VALUES ('120', '29', '作为计算机专业学生,最应该学习的课程前五位是什么? - 知乎', 'http://www.zhihu.com/question/19628851'); INSERT INTO `crawl` VALUES ('121', '10', '专业课程_360百科', 'http://baike.so.com/doc/6743502.html'); INSERT INTO `crawl` VALUES ('122', '10', '大学有哪些专业 专业课程是什么 - 学校大全', 'http://xuexiao.chazidian.com/news60267/'); INSERT INTO `crawl` VALUES ('123', '10', '市场营销专业课程', 'http://www.oh100.com/a/201106/1087.html'); INSERT INTO `crawl` VALUES ('124', '10', '大学英语专业课程有哪些_360问答', 'http://wenda.so.com/q/1361983100061558'); INSERT INTO `crawl` VALUES ('125', '10', '旅游管理的专业课程有哪些?_360问答', 'http://wenda.so.com/q/1361504792067323'); INSERT INTO `crawl` VALUES ('126', '10', '会计专业有哪些课程?_360问答', 'http://wenda.so.com/q/1378240055060890'); INSERT INTO `crawl` VALUES ('127', '10', '土木工程专业课程_百度百科', 'http://baike.baidu.com/view/3950723.htm'); INSERT INTO `crawl` VALUES ('128', '10', '汉语言文学专业课程简介', 'http://www.douban.com/group/topic/16320721/'); INSERT INTO `crawl` VALUES ('129', '10', '护理专业课程介绍', 'http://www.houxue.com/kecheng/334223/'); INSERT INTO `crawl` VALUES ('130', '10', '法学专业课程', 'http://www.oh100.com/a/201106/1463.html'); INSERT INTO `crawl` VALUES ('131', '7', '大一新生一般要军训多久?_360问答', 'http://wenda.so.com/q/1373933368064266'); INSERT INTO `crawl` VALUES ('132', '7', '大学军训多长时间?累不累?_360问答', 'http://wenda.so.com/q/1365902871067428'); INSERT INTO `crawl` VALUES ('133', '7', '大一军训经验_百度文库', 'http://wenku.baidu.com/view/0a2cd94d852458fb770b56fe.html'); INSERT INTO `crawl` VALUES ('134', '7', '大一军训多长时间_360问答', 'http://wenda.so.com/q/1404798520725234?src=110'); INSERT INTO `crawl` VALUES ('135', '7', '大一新生军训注意事项?2012下半年大学新生军训多少时间?什...', 'http://www.tesoon.com/ask/htm/21/103899.htm'); INSERT INTO `crawl` VALUES ('136', '7', '郑州大学大一新生军训一般多久时间地点在哪?_360问答', 'http://wenda.so.com/q/1372167963068495'); INSERT INTO `crawl` VALUES ('137', '7', '大一新生军训感言- 文化教育- 道客巴巴', 'http://www.doc88.com/p-096200763649.html'); INSERT INTO `crawl` VALUES ('138', '7', '大一新生军训必看~ - 人在师大- 蛋蛋网- 师大人的精神家园', 'http://www.oiegg.com/viewthread.php?tid=115190'); INSERT INTO `crawl` VALUES ('139', '7', '南师大中北学院大一新生军训多长时间?军训过后有放假吗?放...', 'http://wenda.so.com/q/1404906735721785'); INSERT INTO `crawl` VALUES ('140', '7', '厦门大学每年的大一入学军训时间是多久啊_百度知道', 'http://zhidao.baidu.com/question/59367819.html'); INSERT INTO `crawl` VALUES ('141', '22', '今天是农历几月几日星期几,今天农历几月几号,今天是什么日子...', 'http://nongli.85384.com/'); INSERT INTO `crawl` VALUES ('142', '22', '今天是农历几月几日星期几_今天几号', 'http://www.jintianjihao.com/'); INSERT INTO `crawl` VALUES ('143', '22', '今天星期几?', 'http://www.douban.com/group/topic/7438493/'); INSERT INTO `crawl` VALUES ('144', '22', '怎么设置电脑时间显示星期几_百度经验', 'http://jingyan.baidu.com/article/546ae1854146ef1149f28cb6.html'); INSERT INTO `crawl` VALUES ('145', '22', '怎么样让电脑时间显示星期几._360问答', 'http://wenda.so.com/q/1367106301065344'); INSERT INTO `crawl` VALUES ('146', '22', '今天是农历几月几日星期几_每日农历和阳历查询_在线电子万...', 'http://www.qqjia.com/mu/wannianli.htm'); INSERT INTO `crawl` VALUES ('147', '22', '今天是几月几日星期几-我爱万年历', 'http://www.qtoday.net/'); INSERT INTO `crawl` VALUES ('148', '22', '淘宝宝贝什么时间星期几上架最佳?_360问答', 'http://wenda.so.com/q/1378232158066648'); INSERT INTO `crawl` VALUES ('149', '22', '今天星期几_360百科', 'http://baike.so.com/doc/6623986.html'); INSERT INTO `crawl` VALUES ('150', '22', '2014愚人节是几月几日星期几_万年历', 'http://wannianli.tianqi.com/news/22334.html'); INSERT INTO `crawl` VALUES ('151', '2', 'Python_360百科', 'http://baike.so.com/doc/1790119.html'); INSERT INTO `crawl` VALUES ('152', '2', 'Welcome to Python.org', 'https://www.python.org/'); INSERT INTO `crawl` VALUES ('153', '2', '简明 Python 教程', 'http://sebug.net/paper/python/'); INSERT INTO `crawl` VALUES ('154', '2', 'Python入门教程 超详细1小时学会Python_python_脚本之家', 'http://www.jb51.net/article/926.htm'); INSERT INTO `crawl` VALUES ('155', '2', 'Python教程 - 廖雪峰的官方网站', 'http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000'); INSERT INTO `crawl` VALUES ('156', '2', 'PythonTab:Python中文开发者社区门户', 'http://www.pythontab.com/'); INSERT INTO `crawl` VALUES ('157', '2', 'Python 中文社区', 'http://python.cn/'); INSERT INTO `crawl` VALUES ('158', '2', 'Python编程小组', 'http://www.douban.com/group/python/'); INSERT INTO `crawl` VALUES ('159', '2', 'Python基础教程 (豆瓣)', 'http://book.douban.com/subject/4866934/'); INSERT INTO `crawl` VALUES ('160', '2', 'python吧_百度贴吧', 'http://tieba.baidu.com/f?kw=python'); INSERT INTO `crawl` VALUES ('161', '28', '湖南科技大学图书馆_360百科', 'http://baike.so.com/doc/2322023.html'); INSERT INTO `crawl` VALUES ('162', '28', '湖南科技大学图书馆', 'http://lib.hnust.cn/'); INSERT INTO `crawl` VALUES ('163', '28', '湖南科技大学', 'http://www.hnust.edu.cn/'); INSERT INTO `crawl` VALUES ('164', '28', '湖南科技大学南校区图书馆_360问答', 'http://wenda.so.com/q/1367085821066931'); INSERT INTO `crawl` VALUES ('165', '28', '湖南科技大学图书馆广场景观施工方案- 豆丁网', 'http://www.docin.com/p-412600015.html'); INSERT INTO `crawl` VALUES ('166', '28', '国防科技大学图书馆_百度百科', 'http://baike.baidu.com/view/1290316.htm'); INSERT INTO `crawl` VALUES ('167', '28', '湖南科技大学南校区图书馆卫星地图', 'http://www.52maps.com/ditu/90aeeffe4261c837.html'); INSERT INTO `crawl` VALUES ('168', '28', '永州湖南科技大学图书馆_电话_公交_地址_地图_点评-爱帮网', 'http://www.aibang.com/detail/443219115-444035558'); INSERT INTO `crawl` VALUES ('169', '28', '湖南科技大学图书馆书籍网上续借最近怎么老是打不开网址啊_...', 'http://zhidao.baidu.com/question/274106486.html'); INSERT INTO `crawl` VALUES ('170', '28', '湖南湘潭科技大学图书馆与市政府调研报告_百度文库', 'http://wenku.baidu.com/view/ee019b76f46527d3240ce0f4.html'); INSERT INTO `crawl` VALUES ('171', '15', 'jquery ajax例子返回值详解_jquery_脚本之家', 'http://www.jb51.net/article/31237.htm'); INSERT INTO `crawl` VALUES ('172', '15', 'jquery ajax return没有返回值的解决方法_jquery_脚本之家', 'http://www.jb51.net/article/28597.htm'); INSERT INTO `crawl` VALUES ('173', '15', 'jquery 返回值问题_360问答', 'http://wenda.so.com/q/1370782982066576'); INSERT INTO `crawl` VALUES ('174', '15', 'jquery ajax例子返回值详解', 'http://www.poluoluo.com/jzxy/201209/178484.html'); INSERT INTO `crawl` VALUES ('175', '15', 'jquery怎么调用返回值?_360问答', 'http://wenda.so.com/q/1378702013062756'); INSERT INTO `crawl` VALUES ('176', '15', 'jquery ajax 返回值_360问答', 'http://wenda.so.com/q/1376957772069700'); INSERT INTO `crawl` VALUES ('177', '15', 'jquery返回值_360问答', 'http://wenda.so.com/q/1375078655067510'); INSERT INTO `crawl` VALUES ('178', '15', '使用jquery form 返回值的问题-CSDN论坛-CSDN.NET-中国最大...', 'http://bbs.csdn.net/topics/360192769'); INSERT INTO `crawl` VALUES ('179', '15', 'jquery 的返回值问题- coolpig86的专栏- 博客频道- CSDN.NET', 'http://blog.csdn.net/coolpig86/article/details/5397876'); INSERT INTO `crawl` VALUES ('180', '15', 'jquery的Ajax返回值怎么取?-CSDN论坛-CSDN.NET-中国最大的...', 'http://bbs.csdn.net/topics/390379472?page=1'); INSERT INTO `crawl` VALUES ('181', '9', '美食天下|美食|菜谱大全|家常菜谱|美食社区-最大的中文美食网...', 'http://www.meishichina.com/'); INSERT INTO `crawl` VALUES ('182', '9', '美食_360百科', 'http://baike.so.com/doc/5373894-5609902.html'); INSERT INTO `crawl` VALUES ('183', '9', '美食杰 - 美食|菜谱大全|食谱|美食网 - 做你最喜爱的美食,食谱...', 'http://www.meishij.net/'); INSERT INTO `crawl` VALUES ('184', '9', '美食吧_百度贴吧', 'http://tieba.baidu.com/f?kw=%C3%C0%CA%B3'); INSERT INTO `crawl` VALUES ('185', '9', '天天美食网(www.TTMeiShi.com)-为您提供菜谱大全、美食制作...', 'http://www.ttmeishi.com/'); INSERT INTO `crawl` VALUES ('186', '9', '家常菜谱大全 > 美食厨房 > 美食天下 - 最大最全的家常美食菜...', 'http://www.meishichina.com/Eat/Menu/'); INSERT INTO `crawl` VALUES ('187', '9', '中华美食网__中国美食、餐饮行业第一品牌', 'http://www.zhms.cn/'); INSERT INTO `crawl` VALUES ('188', '9', '美食厨房_学做各地大众家常美食_精品营养美食推荐_简单传统...', 'http://www.meishichina.com/Eat/'); INSERT INTO `crawl` VALUES ('189', '9', '美食博客_新浪美食_新浪网', 'http://eat.sina.com.cn/'); INSERT INTO `crawl` VALUES ('190', '9', '中华美食 - 中华美食网', 'http://www.meishij.net/china-food/'); INSERT INTO `crawl` VALUES ('191', '24', '一句话说不清楚,形容事情很复杂 是什么成语- 新浪旗下中文互...', 'http://iask.sina.com.cn/b/f1rGsxouR.html'); INSERT INTO `crawl` VALUES ('192', '24', '求求大家帮帮忙谢谢了:事情是我与邻居之间的矛盾,听起来感觉...', 'http://wenda.so.com/q/1377339787064329'); INSERT INTO `crawl` VALUES ('193', '24', '怎么在中国知网下东西?_firefox吧_百度贴吧', 'http://tieba.baidu.com/p/2083814776'); INSERT INTO `crawl` VALUES ('194', '24', 'V 357 缘嫁首长老公- 请看小说网', 'http://www.qingkan.net/book/yuanjiashouchanglaogong/4694837.html'); INSERT INTO `crawl` VALUES ('195', '24', '如何看待中国学术造假? - 步行街- 虎扑篮球论坛', 'http://bbs.hupu.com/8073776.html'); INSERT INTO `crawl` VALUES ('196', '24', '艺术,一句话说不清楚(《国家美术》杂志,王天德创作访谈) - 《国...', 'http://blog.artintern.net/article/58072'); INSERT INTO `crawl` VALUES ('197', '24', '《网游之我是NPC》第十三章豆豆删号了- 原创首发- 《小说阅...', 'http://www.readnovel.com/novel/12230/13.html'); INSERT INTO `crawl` VALUES ('198', '24', '好想给前男友打电话,可是我不知道第一句话说什么', 'http://wenwen.sogou.com/z/q421755508.htm'); INSERT INTO `crawl` VALUES ('199', '24', '有没有萍乡的朋友?急事相求_李宇春吧_百度贴吧', 'http://tieba.baidu.com/p/488896278'); INSERT INTO `crawl` VALUES ('200', '24', '一句话两句话说不清楚的问题看看吧100分! - 已解决- 搜狗问问', 'http://wenwen.sogou.com/z/q209292169.htm'); INSERT INTO `crawl` VALUES ('201', '8', '大一该谈恋爱吗_360问答', 'http://wenda.so.com/q/1383002420062802'); INSERT INTO `crawl` VALUES ('202', '8', '大一新生应该谈恋爱吗_360问答', 'http://wenda.so.com/q/1375822646061626'); INSERT INTO `crawl` VALUES ('203', '8', '大一女生可以谈恋爱吗? - 已回答- 搜狗问问', 'http://wenwen.sogou.com/z/q230292800.htm'); INSERT INTO `crawl` VALUES ('204', '8', '大一学生可以谈恋爱吗- 已回答- 搜狗问问', 'http://wenwen.sogou.com/z/q114041489.htm'); INSERT INTO `crawl` VALUES ('205', '8', '刚上大一,可以谈恋爱吗?_百度知道', 'http://zhidao.baidu.com/question/65588047.html'); INSERT INTO `crawl` VALUES ('206', '8', '大一谈恋爱合适吗_360问答', 'http://wenda.so.com/q/1372542106068112'); INSERT INTO `crawl` VALUES ('207', '8', '大一女生谈恋爱的几率有多大?_360问答', 'http://wenda.so.com/q/1375433273063464'); INSERT INTO `crawl` VALUES ('208', '8', '大一女生谈恋爱,痴心老妈苦开导_hwzhao_新浪博客', 'http://blog.sina.com.cn/s/blog_5061d22a0100afr5.html'); INSERT INTO `crawl` VALUES ('209', '8', '大一大二适合谈恋爱吗? - 职业规划董老师的日志 - 网易博客', 'http://blog.163.com/dlcyhr/blog/static/2038360912010102211307812/'); INSERT INTO `crawl` VALUES ('210', '8', '大一 的女生该谈恋爱吗_囡囡心语_新浪博客', 'http://blog.sina.com.cn/s/blog_49ed52a5010006en.html'); INSERT INTO `crawl` VALUES ('211', '21', 'input元素hidden属性和text属性的取值问题,_360问答', 'http://wenda.so.com/q/1378785347064494'); INSERT INTO `crawl` VALUES ('212', '21', 'input元素hidden属性和text属性的取值问题,_已解决- 阿里巴巴生...', 'http://baike.1688.com/doc/view-d25583156.html'); INSERT INTO `crawl` VALUES ('213', '21', 'hidden 取值的问题_百度知道', 'http://zhidao.baidu.com/question/75174196.html'); INSERT INTO `crawl` VALUES ('214', '21', 'HTML input 标签', 'http://www.w3school.com.cn/tags/tag_input.asp'); INSERT INTO `crawl` VALUES ('215', '21', '关于input type=hidden后台取值的问题', 'http://www.phpfans.net/ask/MTc1NTEwMQ.html'); INSERT INTO `crawl` VALUES ('216', '21', 'HTML input 标签的disabled 属性', 'http://www.w3school.com.cn/tags/att_input_disabled.asp'); INSERT INTO `crawl` VALUES ('217', '21', '后台怎么对html控件赋值和取值-CSDN论坛-CSDN.NET-中国最...', 'http://bbs.csdn.net/topics/360233363'); INSERT INTO `crawl` VALUES ('218', '21', '为什么input 元素能用width 属性? - 知乎', 'http://www.zhihu.com/question/20495297'); INSERT INTO `crawl` VALUES ('219', '21', 'Jquery 表单取值赋值的一些基本操作_jquery_脚本之家', 'http://www.jb51.net/article/20336.htm'); INSERT INTO `crawl` VALUES ('220', '21', '关于input type=hidden后台取值的问题-CSDN论坛-CSDN.NET...', 'http://bbs.csdn.net/topics/370140397'); INSERT INTO `crawl` VALUES ('221', '11', 'Windows系统故障专区_天极软件_操作系统', 'http://os.yesky.com/conkout/'); INSERT INTO `crawl` VALUES ('222', '11', 'windows系统错误问题_360问答', 'http://wenda.so.com/q/1378220482068839'); INSERT INTO `crawl` VALUES ('223', '11', '系统问题_网易科技论坛', 'http://bbs.tech.163.com/list/tech_btwp.html'); INSERT INTO `crawl` VALUES ('224', '11', '电脑常见问题与故障1000例_360百科', 'http://baike.so.com/doc/2030829.html'); INSERT INTO `crawl` VALUES ('225', '11', '系统故障_百度百科', 'http://baike.baidu.com/view/9929426.htm'); INSERT INTO `crawl` VALUES ('226', '11', 'Tipask问答系统- 最强大的问答系统!', 'http://www.tipask.com/'); INSERT INTO `crawl` VALUES ('227', '11', '上交所确认暴涨是光大证券系统问题光大停牌_网易财经', 'http://money.163.com/13/0816/13/96DD0ONT00251LIE.html'); INSERT INTO `crawl` VALUES ('228', '11', '上交所确认股市暴涨是光大证券系统问题,光大午后停牌-外汇频...', 'http://forex.hexun.com/2013-08-16/157161796.html'); INSERT INTO `crawl` VALUES ('229', '11', '国务院关于全国中小企业股份转让系统有关问题的决定', 'http://www.gov.cn/zwgk/2013-12/14/content_2547699.htm'); INSERT INTO `crawl` VALUES ('230', '11', '上交所确认暴涨是光大证券系统问题光大午后停牌_ 财经频道_...', 'http://finance.eastmoney.com/news/1345,20130816315704451.html'); INSERT INTO `crawl` VALUES ('231', '30', '如何实现微信公众平台智能问答_百度经验', 'http://jingyan.baidu.com/article/358570f6033b84ce4624fc48.html'); INSERT INTO `crawl` VALUES ('232', '30', '创维电视酷开智能平台在网页浏览,点电影观看,提示未安装FLA...', 'http://wenda.so.com/q/1378762745064586'); INSERT INTO `crawl` VALUES ('233', '30', '智能手机的功能_360问答', 'http://wenda.so.com/q/1349999261063988'); INSERT INTO `crawl` VALUES ('234', '30', '如何创建微信公众平台并实现智能化问答_百度经验', 'http://jingyan.baidu.com/article/e75aca85bacf23142fdac675.html'); INSERT INTO `crawl` VALUES ('235', '30', '搜狗问答全新上线智能秒答功能开创业界先河_互联网_比特网', 'http://net.chinabyte.com/257/12684257.shtml'); INSERT INTO `crawl` VALUES ('236', '30', '图吧智能导航软件v3更新能自己升级吗_天涯问答', 'http://wenda.tianya.cn/question/2d9352f1a646a845'); INSERT INTO `crawl` VALUES ('237', '30', '9.3.5、V5KF智能平台问答培训直接调用【系统功能】作为回复...', 'http://www.56.com/u91/v_MTE1NjQwNTI4.html'); INSERT INTO `crawl` VALUES ('238', '30', '三星智能手机怎样更新升级_天涯问答', 'http://wenda.tianya.cn/question/3397c78804502018'); INSERT INTO `crawl` VALUES ('239', '30', '从价格和功能分析,买智能手机划算还是买可以打电话的平板电...', 'http://iask.sina.com.cn/b/19671019.html'); INSERT INTO `crawl` VALUES ('240', '30', '如何关闭V5KF微信机器人自动回复功能_V5KF微信智能平台-常...', 'http://www.56.com/w36/play_album-aid-12797958_vid-MTE1ODI2NzU4.html'); INSERT INTO `crawl` VALUES ('241', '33', '关于java程序在BAE3.0上部署关于java程序在BAE3.0上部署80...', 'http://www.uukkuu.com/v617092905534185612/'); INSERT INTO `crawl` VALUES ('242', '33', '如何在BAE3.0中部署wordpress_百度经验', 'http://jingyan.baidu.com/article/fb48e8be5bac1d6e622e14c1.html'); INSERT INTO `crawl` VALUES ('243', '33', '【BAE3.0使用系列】Java Runtime简介_bae吧_百度贴吧', 'http://tieba.baidu.com/p/2574882923'); INSERT INTO `crawl` VALUES ('244', '33', '如何在BAE3.0中部署wordpress_互联网_百度经验', 'http://jingyan.baidu.com/album/fb48e8be5bac1d6e622e14c1.html'); INSERT INTO `crawl` VALUES ('245', '33', '百度BAE2.0 JAVA环境项目部署和调试- using - 开源中国社区', 'http://my.oschina.net/using/blog/167038'); INSERT INTO `crawl` VALUES ('246', '33', 'servlet相关jar包位置BAE上部署web应用- Yogurshine - 博客园', 'http://www.cnblogs.com/Yogurshine/p/3171142.html'); INSERT INTO `crawl` VALUES ('247', '33', '【每日一博】百度BAE JAVA环境项目部署和调试- 看引擎KEN...', 'http://www.kankanews.com/ICkengine/archives/56648.shtml'); INSERT INTO `crawl` VALUES ('248', '33', '【BAE3.0使用系列】Java博客--Dlog4j的移植| BAE技术博客', 'http://godbae.duapp.com/?p=249'); INSERT INTO `crawl` VALUES ('249', '33', '(转)微信公众平台开发之基于百度BAE3.0 的开发环境搭建(采用...', 'http://www.cnblogs.com/ixxonline/p/3659434.html'); INSERT INTO `crawl` VALUES ('250', '33', '百度BAE JAVA环境项目部署和调试-Java-第七城市', 'http://www.th7.cn/Program/java/201310/153446.shtml'); INSERT INTO `crawl` VALUES ('251', '16', '体育彩票_体彩排列5 13124期开奖结果_中奖号码查询 - 爱波网', 'http://www.aibo123.com/kaijiang/tc_pl5/13124/'); INSERT INTO `crawl` VALUES ('252', '16', '胜负彩13124期初盘:维拉主场分胜负 枪手客场翻船_14场胜负彩...', 'http://www.310win.com/zucai/info_t2i105087.html'); INSERT INTO `crawl` VALUES ('253', '16', '中国足球彩票13124期胜负游戏14场交战记录_彩票_新浪竞技风...', 'http://sports.sina.com.cn/l/2013-08-28/17366746109.shtml'); INSERT INTO `crawl` VALUES ('254', '16', '佬牛足彩:13124期胜负彩分析(英德意)_佬牛_新浪博客', 'http://blog.sina.com.cn/s/blog_50896bbe0102e60n.html'); INSERT INTO `crawl` VALUES ('255', '16', '乐透13124期开奖:头奖1注1000万 奖池2.07亿_体育_腾讯网', 'http://sports.qq.com/a/20131023/017312.htm'); INSERT INTO `crawl` VALUES ('256', '16', '田伟胜负彩13124期:纽卡难胜 拜仁仍稳胆_体育_腾讯网', 'http://sports.qq.com/a/20130914/004714_all.htm'); INSERT INTO `crawl` VALUES ('257', '16', '李小五胜负彩13124期:西布朗凶多吉少 国米分胜负-东方体育-东...', 'http://sports.eastday.com/gd/2013/0914/1261133920.html'); INSERT INTO `crawl` VALUES ('258', '16', '[足球魔方]足彩13124期裁判:韦伯执法切尔西不败_彩票_新浪竞...', 'http://sports.sina.com.cn/l/2013-09-13/12116781214.shtml'); INSERT INTO `crawl` VALUES ('259', '16', '中国足球彩票胜负彩13124期澳盘最新赔率(17:00)_彩票_新浪竞...', 'http://sports.sina.com.cn/l/2013-09-09/16396773436.shtml'); INSERT INTO `crawl` VALUES ('260', '16', '足球胜负游戏第13124期14场推荐_网易新闻中心', 'http://news.163.com/13/0913/04/98KHQUIR00014AED.html'); INSERT INTO `crawl` VALUES ('261', '33', '关于java程序在BAE3.0上部署关于java程序在BAE3.0上部署80...', 'http://www.uukkuu.com/v617092905534185612/'); INSERT INTO `crawl` VALUES ('262', '33', '百度BAE2.0 JAVA环境项目部署和调试- using - 开源中国社区', 'http://my.oschina.net/using/blog/167038'); INSERT INTO `crawl` VALUES ('263', '33', '如何在BAE3.0中部署wordpress_百度经验', 'http://jingyan.baidu.com/article/fb48e8be5bac1d6e622e14c1.html'); INSERT INTO `crawl` VALUES ('264', '33', '【BAE3.0使用系列】Java Runtime简介_bae吧_百度贴吧', 'http://tieba.baidu.com/p/2574882923'); INSERT INTO `crawl` VALUES ('265', '33', '如何在BAE3.0中部署wordpress_互联网_百度经验', 'http://jingyan.baidu.com/album/fb48e8be5bac1d6e622e14c1.html'); INSERT INTO `crawl` VALUES ('266', '33', 'servlet相关jar包位置BAE上部署web应用- Yogurshine - 博客园', 'http://www.cnblogs.com/Yogurshine/p/3171142.html'); INSERT INTO `crawl` VALUES ('267', '33', '【每日一博】百度BAE JAVA环境项目部署和调试- 看引擎KEN...', 'http://www.kankanews.com/ICkengine/archives/56648.shtml'); INSERT INTO `crawl` VALUES ('268', '33', '(转)微信公众平台开发之基于百度BAE3.0 的开发环境搭建(采用...', 'http://www.cnblogs.com/ixxonline/p/3659434.html'); INSERT INTO `crawl` VALUES ('269', '33', '【BAE3.0使用系列】Java博客--Dlog4j的移植| BAE技术博客', 'http://godbae.duapp.com/?p=249'); INSERT INTO `crawl` VALUES ('270', '33', '百度BAE JAVA环境项目部署和调试-Java-第七城市', 'http://www.th7.cn/Program/java/201310/153446.shtml'); INSERT INTO `crawl` VALUES ('271', '27', '湖南科技大学什么专业最好?_360问答', 'http://wenda.so.com/q/1365838327064957'); INSERT INTO `crawl` VALUES ('272', '27', '湖南科技大学优势专业排名及最好的专业有哪些_大学专业', 'http://www.ccutu.com/gaokao/17290.shtml'); INSERT INTO `crawl` VALUES ('273', '27', '湖南科技大学最好的专业 - 特色专业 - 萝卜侠网 - 高考,志愿,填...', 'http://www.luoboxia.com/best-majors/10534.html'); INSERT INTO `crawl` VALUES ('274', '27', '我的大学-湖南科技大学最好的本科专业是哪个啊', 'http://bbs.rednet.cn/thread-25074484-1-1.html'); INSERT INTO `crawl` VALUES ('275', '27', '湖南科技大学,的重点专业是哪些?', 'http://wenwen.sogou.com/z/q210664149.htm'); INSERT INTO `crawl` VALUES ('276', '27', '湖南科技大学什么专业好?_湖南科技大学吧_百度贴吧', 'http://tieba.baidu.com/p/125493668'); INSERT INTO `crawl` VALUES ('277', '27', '湖南科技大学什么专业最好_2014湖南科技大学的专业怎么样_...', 'http://gaokao.0s.net.cn/tesezhuanye/hnkjdx/'); INSERT INTO `crawl` VALUES ('278', '27', '湖南科技大学里面什么专业比较好_百度知道', 'http://zhidao.baidu.com/question/103809922.html'); INSERT INTO `crawl` VALUES ('279', '27', '湖南科技大学怎样?二本哪个专业好?_360问答', 'http://wenda.so.com/q/1364774238060705'); INSERT INTO `crawl` VALUES ('280', '27', '湖南科技大学哪个专业好?_百度知道', 'http://zhidao.baidu.com/question/97252518.html'); INSERT INTO `crawl` VALUES ('281', '33', '关于java程序在BAE3.0上部署关于java程序在BAE3.0上部署80...', 'http://www.uukkuu.com/v617092905534185612/'); INSERT INTO `crawl` VALUES ('282', '33', '百度BAE2.0 JAVA环境项目部署和调试- using - 开源中国社区', 'http://my.oschina.net/using/blog/167038'); INSERT INTO `crawl` VALUES ('283', '33', '如何在BAE3.0中部署wordpress_百度经验', 'http://jingyan.baidu.com/article/fb48e8be5bac1d6e622e14c1.html'); INSERT INTO `crawl` VALUES ('284', '33', '【BAE3.0使用系列】Java Runtime简介_bae吧_百度贴吧', 'http://tieba.baidu.com/p/2574882923'); INSERT INTO `crawl` VALUES ('285', '33', '如何在BAE3.0中部署wordpress_互联网_百度经验', 'http://jingyan.baidu.com/album/fb48e8be5bac1d6e622e14c1.html'); INSERT INTO `crawl` VALUES ('286', '33', 'servlet相关jar包位置BAE上部署web应用- Yogurshine - 博客园', 'http://www.cnblogs.com/Yogurshine/p/3171142.html'); INSERT INTO `crawl` VALUES ('287', '33', '【每日一博】百度BAE JAVA环境项目部署和调试- 看引擎KEN...', 'http://www.kankanews.com/ICkengine/archives/56648.shtml'); INSERT INTO `crawl` VALUES ('288', '33', '(转)微信公众平台开发之基于百度BAE3.0 的开发环境搭建(采用...', 'http://www.cnblogs.com/ixxonline/p/3659434.html'); INSERT INTO `crawl` VALUES ('289', '33', '【BAE3.0使用系列】Java博客--Dlog4j的移植| BAE技术博客', 'http://godbae.duapp.com/?p=249'); INSERT INTO `crawl` VALUES ('290', '33', '百度BAE JAVA环境项目部署和调试-Java-第七城市', 'http://www.th7.cn/Program/java/201310/153446.shtml'); INSERT INTO `crawl` VALUES ('291', '21', 'input元素hidden属性和text属性的取值问题,_360问答', 'http://wenda.so.com/q/1369285075062156'); INSERT INTO `crawl` VALUES ('292', '21', 'input元素hidden属性和text属性的取值问题,_已解决- 阿里巴巴生...', 'http://baike.1688.com/doc/view-d25583156.html'); INSERT INTO `crawl` VALUES ('293', '21', 'hidden 取值的问题_百度知道', 'http://zhidao.baidu.com/question/75174196.html'); INSERT INTO `crawl` VALUES ('294', '21', 'HTML input 标签', 'http://www.w3school.com.cn/tags/tag_input.asp'); INSERT INTO `crawl` VALUES ('295', '21', '关于input type=hidden后台取值的问题', 'http://www.phpfans.net/ask/MTc1NTEwMQ.html'); INSERT INTO `crawl` VALUES ('296', '21', 'HTML input 标签的disabled 属性', 'http://www.w3school.com.cn/tags/att_input_disabled.asp'); INSERT INTO `crawl` VALUES ('297', '21', '为什么input 元素能用width 属性? - 知乎', 'http://www.zhihu.com/question/20495297'); INSERT INTO `crawl` VALUES ('298', '21', '后台怎么对html控件赋值和取值-CSDN论坛-CSDN.NET-中国最...', 'http://bbs.csdn.net/topics/360233363'); INSERT INTO `crawl` VALUES ('299', '21', '关于input type=hidden后台取值的问题-CSDN论坛-CSDN.NET...', 'http://bbs.csdn.net/topics/370140397'); INSERT INTO `crawl` VALUES ('300', '21', 'Jquery 表单取值赋值的一些基本操作_jquery_脚本之家', 'http://www.jb51.net/article/20336.htm'); INSERT INTO `crawl` VALUES ('301', '20', 'input元素hidden属性和text属性的取值问题,_360问答', 'http://wenda.so.com/q/1369285075062156'); INSERT INTO `crawl` VALUES ('302', '20', 'input元素hidden属性和text属性的取值问题,_已解决- 阿里巴巴生...', 'http://baike.1688.com/doc/view-d25583156.html'); INSERT INTO `crawl` VALUES ('303', '20', 'hidden 取值的问题_百度知道', 'http://zhidao.baidu.com/question/75174196.html'); INSERT INTO `crawl` VALUES ('304', '20', 'HTML input 标签', 'http://www.w3school.com.cn/tags/tag_input.asp'); INSERT INTO `crawl` VALUES ('305', '20', '关于input type=hidden后台取值的问题', 'http://www.phpfans.net/ask/MTc1NTEwMQ.html'); INSERT INTO `crawl` VALUES ('306', '20', 'HTML input 标签的disabled 属性', 'http://www.w3school.com.cn/tags/att_input_disabled.asp'); INSERT INTO `crawl` VALUES ('307', '20', '为什么input 元素能用width 属性? - 知乎', 'http://www.zhihu.com/question/20495297'); INSERT INTO `crawl` VALUES ('308', '20', '后台怎么对html控件赋值和取值-CSDN论坛-CSDN.NET-中国最...', 'http://bbs.csdn.net/topics/360233363'); INSERT INTO `crawl` VALUES ('309', '20', '关于input type=hidden后台取值的问题-CSDN论坛-CSDN.NET...', 'http://bbs.csdn.net/topics/370140397'); INSERT INTO `crawl` VALUES ('310', '20', 'Jquery 表单取值赋值的一些基本操作_jquery_脚本之家', 'http://www.jb51.net/article/20336.htm'); INSERT INTO `crawl` VALUES ('311', '26', '我的大学-湖南科技大学怎么样?', 'http://bbs.rednet.cn/thread-10640698-1-1.html'); INSERT INTO `crawl` VALUES ('312', '26', '湖南科技大学怎么样?_360问答', 'http://wenda.so.com/q/1404410841726029'); INSERT INTO `crawl` VALUES ('313', '26', '湖南科技大学怎么样?_湖南科技大学吧_百度贴吧', 'http://tieba.baidu.com/p/1509445236'); INSERT INTO `crawl` VALUES ('314', '26', '湖南科技大学好吗?_360问答', 'http://wenda.so.com/q/1372632307062416'); INSERT INTO `crawl` VALUES ('315', '26', '湖南科技大学怎么样|湖南科技大学的评价–爱帮网', 'http://www.aibang.com/detail/559434692-432643795/reviews/'); INSERT INTO `crawl` VALUES ('316', '26', '湖南科技大学_360百科', 'http://baike.so.com/doc/3043743-3208850.html'); INSERT INTO `crawl` VALUES ('317', '26', '湖南科技大学怎么样,就业前景如何-湖南科技大学大学简介-人...', 'http://bbs.pinggu.org/z_zixun_gaoxiao_view.php?gid=536'); INSERT INTO `crawl` VALUES ('318', '26', '湖南科技大学是几本 湖南科技大学怎么样', 'http://www.027art.com/gaokao/HTML/550943.html'); INSERT INTO `crawl` VALUES ('319', '26', '2014年报考湖南科技大学热门专业有哪些?湖南科技大学最受欢...', 'http://www.tesoon.com/ask/htm/36/178982.htm'); INSERT INTO `crawl` VALUES ('320', '26', '湖南科技大学怎么样', 'http://www.yjbys.com/bbs/630715.html'); INSERT INTO `crawl` VALUES ('321', '7', '大一新生一般要军训多久?_360问答', 'http://wenda.so.com/q/1373933368064266'); INSERT INTO `crawl` VALUES ('322', '7', '大一军训军训感言!_360问答', 'http://wenda.so.com/q/1369260823062563'); INSERT INTO `crawl` VALUES ('323', '7', '大一新生军训一般是什么?(详细点)_360问答', 'http://wenda.so.com/q/1372338586067525'); INSERT INTO `crawl` VALUES ('324', '7', '大一军训小结', 'http://www.lz13.cn/daxueshenglizhi/17378.html'); INSERT INTO `crawl` VALUES ('325', '7', '大一新生军训什么时候开始呀?_360问答', 'http://wenda.so.com/q/1370267818069264'); INSERT INTO `crawl` VALUES ('326', '7', '大一军训一般要多久啊?军训时有学习任务吗_百度知道', 'http://zhidao.baidu.com/question/449708941.html'); INSERT INTO `crawl` VALUES ('327', '7', '大一军训多长时间_360问答', 'http://wenda.so.com/q/1404798520725234?src=110'); INSERT INTO `crawl` VALUES ('328', '7', '大一新生军训必看~ - 人在师大- 蛋蛋网- 师大人的精神家园', 'http://www.oiegg.com/viewthread.php?tid=115190'); INSERT INTO `crawl` VALUES ('329', '7', '大一军训多久阿', 'http://www.douban.com/group/topic/21389014/'); INSERT INTO `crawl` VALUES ('330', '7', '大一军训一般多长时间?_百度知道', 'http://zhidao.baidu.com/question/67006702.html'); INSERT INTO `crawl` VALUES ('331', '2', 'Python_360百科', 'http://baike.so.com/doc/1790119.html'); INSERT INTO `crawl` VALUES ('332', '2', 'Welcome to Python.org', 'https://www.python.org/'); INSERT INTO `crawl` VALUES ('333', '2', '简明 Python 教程', 'http://sebug.net/paper/python/'); INSERT INTO `crawl` VALUES ('334', '2', 'Python教程 - 廖雪峰的官方网站', 'http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000'); INSERT INTO `crawl` VALUES ('335', '2', 'Python入门教程 超详细1小时学会Python_python_脚本之家', 'http://www.jb51.net/article/926.htm'); INSERT INTO `crawl` VALUES ('336', '2', 'PythonTab:Python中文开发者社区门户', 'http://www.pythontab.com/'); INSERT INTO `crawl` VALUES ('337', '2', 'Python 中文社区', 'http://python.cn/'); INSERT INTO `crawl` VALUES ('338', '2', 'python吧_百度贴吧', 'http://tieba.baidu.com/f?kw=python'); INSERT INTO `crawl` VALUES ('339', '2', 'Python编程小组', 'http://www.douban.com/group/python/'); INSERT INTO `crawl` VALUES ('340', '2', 'Python基础教程 (豆瓣)', 'http://book.douban.com/subject/4866934/'); INSERT INTO `crawl` VALUES ('341', '27', '湖南科技大学什么专业最好?_360问答', 'http://wenda.so.com/q/1365838327064957'); INSERT INTO `crawl` VALUES ('342', '27', '湖南科技大学优势专业排名及最好的专业有哪些_大学专业', 'http://www.ccutu.com/gaokao/17290.shtml'); INSERT INTO `crawl` VALUES ('343', '27', '湖南科技大学最好的专业 - 特色专业 - 萝卜侠网 - 高考,志愿,填...', 'http://www.luoboxia.com/best-majors/10534.html'); INSERT INTO `crawl` VALUES ('344', '27', '我的大学-湖南科技大学最好的本科专业是哪个啊', 'http://bbs.rednet.cn/thread-25074484-1-1.html'); INSERT INTO `crawl` VALUES ('345', '27', '湖南科技大学,的重点专业是哪些?', 'http://wenwen.sogou.com/z/q210664149.htm'); INSERT INTO `crawl` VALUES ('346', '27', '湖南科技大学有哪些比较好专业?_360问答', 'http://wenda.so.com/q/1367358865069119'); INSERT INTO `crawl` VALUES ('347', '27', '湖南科技大学什么专业比较好?_360问答', 'http://wenda.so.com/q/1372153031061812'); INSERT INTO `crawl` VALUES ('348', '27', '湖南科技大学里面什么专业比较好_360问答', 'http://wenda.so.com/q/1378382719078986'); INSERT INTO `crawl` VALUES ('349', '27', '湖南科技大学哪个专业好?_360问答', 'http://wenda.so.com/q/1382826062062436'); INSERT INTO `crawl` VALUES ('350', '27', '湖南科技大学最好的6个专业_360问答', 'http://wenda.so.com/q/1372518190060566'); INSERT INTO `crawl` VALUES ('351', '28', '湖南科技大学图书馆_360百科', 'http://baike.so.com/doc/2322023.html'); INSERT INTO `crawl` VALUES ('352', '28', '湖南科技大学图书馆', 'http://lib.hnust.cn/'); INSERT INTO `crawl` VALUES ('353', '28', '湖南科技大学', 'http://www.hnust.edu.cn/'); INSERT INTO `crawl` VALUES ('354', '28', '湖南科技大学南校区图书馆_360问答', 'http://wenda.so.com/q/1367085821066931'); INSERT INTO `crawl` VALUES ('355', '28', '湖南科技大学图书馆广场景观施工方案- 豆丁网', 'http://www.docin.com/p-412600015.html'); INSERT INTO `crawl` VALUES ('356', '28', '国防科技大学图书馆_百度百科', 'http://baike.baidu.com/view/1290316.htm'); INSERT INTO `crawl` VALUES ('357', '28', '湖南科技大学吧_百度贴吧', 'http://tieba.baidu.com/f?kw=%BA%FE%C4%CF%BF%C6%BC%BC%B4%F3%D1%A7'); INSERT INTO `crawl` VALUES ('358', '28', '湖南科技大学南校区图书馆卫星地图', 'http://www.52maps.com/ditu/90aeeffe4261c837.html'); INSERT INTO `crawl` VALUES ('359', '28', '永州湖南科技大学图书馆_电话_公交_地址_地图_点评-爱帮网', 'http://www.aibang.com/detail/443219115-444035558'); INSERT INTO `crawl` VALUES ('360', '28', '湖南科技大学图书馆书籍网上续借最近怎么老是打不开网址啊_...', 'http://zhidao.baidu.com/question/274106486.html'); INSERT INTO `crawl` VALUES ('361', '29', '我是大三计算机专业,下个学期要找工作,想在暑假的时候做点项...', 'http://wenda.so.com/q/1394125949065582'); INSERT INTO `crawl` VALUES ('362', '29', '网络工程师是做什么的_360问答', 'http://wenda.so.com/q/1366692337066788'); INSERT INTO `crawl` VALUES ('363', '29', '中专学计算机平面设计专业有什么课程_360问答', 'http://wenda.so.com/q/1359572472069815'); INSERT INTO `crawl` VALUES ('364', '29', '中专学计算机平面设计专业有什么课程', 'http://wenwen.sogou.com/z/q389166556.htm'); INSERT INTO `crawl` VALUES ('365', '29', '电脑设计_360百科', 'http://baike.so.com/doc/6069276.html'); INSERT INTO `crawl` VALUES ('366', '29', '计算机专业吧_百度贴吧', 'http://tieba.baidu.com/f?kw=%BC%C6%CB%E3%BB%FA%D7%A8%D2%B5'); INSERT INTO `crawl` VALUES ('367', '29', '技校都有什么专业|不上学可以去干吗|计算机专业都有什么课程...', 'http://www.studyems.com/bmcenter/em779e5c6c12f7764cs.php'); INSERT INTO `crawl` VALUES ('368', '29', '平面设计具体是做什么?发展哪方面发展的? _电脑_天涯问答', 'http://wenda.tianya.cn/question/16u9mkb3gvo8bbed74fnp58q4vjis13k2mg0s'); INSERT INTO `crawl` VALUES ('369', '29', '计算机软件专业_百度百科', 'http://baike.baidu.com/view/1018110.htm'); INSERT INTO `crawl` VALUES ('370', '29', '现在计算机科学与技术专业出来主要是做什么工作?这些工作主...', 'http://wenda.so.com/q/1369778007062617'); -- ---------------------------- -- Table structure for discuss -- ---------------------------- DROP TABLE IF EXISTS `discuss`; CREATE TABLE `discuss` ( `discuss_id` int(11) NOT NULL AUTO_INCREMENT, `discuss_content` varchar(500) NOT NULL, `discuss_time` varchar(50) NOT NULL, `discuss_user_id` int(11) NOT NULL, `discuss_answer_id` int(11) NOT NULL, PRIMARY KEY (`discuss_id`), KEY `answer_discuss` (`discuss_answer_id`), KEY `user_discuss` (`discuss_user_id`) ) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of discuss -- ---------------------------- INSERT INTO `discuss` VALUES ('1', '为什么mongodb插入数据经常出现时间相同的情况', '2014-07-21 02:24:53', '4', '23'); INSERT INTO `discuss` VALUES ('6', '梵蒂冈梵蒂冈', '2014-07-21 05:28:53', '1', '24'); INSERT INTO `discuss` VALUES ('7', 'sdfds dsf ', '2014-07-21 05:40:55', '1', '2'); INSERT INTO `discuss` VALUES ('9', 'sdfds dsf ', '2014-07-21 05:41:17', '1', '5'); INSERT INTO `discuss` VALUES ('12', '这问的有水平啊', '2014-07-21 09:23:20', '5', '22'); INSERT INTO `discuss` VALUES ('13', '为什么又可以了?', '2014-07-21 09:23:39', '5', '23'); INSERT INTO `discuss` VALUES ('14', '小飞机到此一游,不谢', '2014-07-21 09:49:04', '4', '30'); INSERT INTO `discuss` VALUES ('15', '傻,你看你都回答了什么,灌水么?', '2014-07-22 12:41:26', '4', '25'); INSERT INTO `discuss` VALUES ('16', '我是冒充哦', '2014-07-22 03:57:40', '9', '30'); INSERT INTO `discuss` VALUES ('17', '测试你妹啊,不许灌水。', '2014-07-30 07:00:20', '4', '39'); INSERT INTO `discuss` VALUES ('18', '我就是用的这个。', '2014-08-26 06:35:21', '4', '43'); INSERT INTO `discuss` VALUES ('19', '查看日志就行。', '2014-08-31 10:38:26', '4', '42'); INSERT INTO `discuss` VALUES ('20', '这个问题是你自己写的么?', '2014-09-06 11:04:16', '1', '40'); INSERT INTO `discuss` VALUES ('21', '做个消息试试', '2014-09-11 09:45:05', '1', '43'); -- ---------------------------- -- Table structure for message -- ---------------------------- DROP TABLE IF EXISTS `message`; CREATE TABLE `message` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `message` varchar(500) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- ---------------------------- -- Records of message -- ---------------------------- INSERT INTO `message` VALUES ('1', '1', '你被<a href=\'GetPersionInfoServlet?user_id=1\'>admin</a>关注了'); INSERT INTO `message` VALUES ('2', '1', '你的问题<a href=\'getDetilQuestion?question_id=33\'>关于java程序在BAE3.0上部署</a>被<a href=\'GetPersionInfoServlet?user_id=1\'>admin</a>赞了'); INSERT INTO `message` VALUES ('3', '1', '你的问题<a href=\'getDetilQuestion?question_id=33\'>关于java程序在BAE3.0上部署</a>被<a href=\'GetPersionInfoServlet?user_id=1\'>admin</a>赞了'); INSERT INTO `message` VALUES ('4', '1', '你的问题<a href=\'getDetilQuestion?question_id=33\'>关于java程序在BAE3.0上部署</a>被踩了'); INSERT INTO `message` VALUES ('5', '1', '你的问题<a href=\'getDetilQuestion?question_id=33\'>关于java程序在BAE3.0上部署</a>被<a href=\'GetPersionInfoServlet?user_id=1\'>admin</a>收藏了'); INSERT INTO `message` VALUES ('6', '1', '<a href=\'getDetilQuestion?question_id=33\'>你的回答被采纳了</a>'); INSERT INTO `message` VALUES ('7', '1', '你的问题<a href=\'getDetilQuestion?question_id=33\'>关于java程序在BAE3.0上部署</a>被<a href=\'GetPersionInfoServlet?user_id=1\'>admin</a>赞了'); -- ---------------------------- -- Table structure for question -- ---------------------------- DROP TABLE IF EXISTS `question`; CREATE TABLE `question` ( `question_id` int(11) NOT NULL AUTO_INCREMENT, `question_title` varchar(100) NOT NULL, `question_description` varchar(500) DEFAULT NULL, `question_time` varchar(50) NOT NULL, `question_mark` int(11) NOT NULL, `question_user_id` int(11) NOT NULL, `question_tags` varchar(255) DEFAULT NULL, `question_categories_id` int(11) DEFAULT '0', PRIMARY KEY (`question_id`), KEY `question` (`question_categories_id`) ) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of question -- ---------------------------- INSERT INTO `question` VALUES ('1', '这是做什么的?', '这个系统是做什么的?', '2014-05-13', '-1', '2', '2', '0'); INSERT INTO `question` VALUES ('2', 'python', '是中编程语言么?', '2014-05-13', '0', '3', '2,5,8,46', '0'); INSERT INTO `question` VALUES ('3', '今天星期几?', '时间', '2014-05-21 08:03:12', '1', '0', '生活', '0'); INSERT INTO `question` VALUES ('4', '你是不是二货?', '迷惑', '2014-05-21 08:05:19', '-1', '0', '娱乐', '0'); INSERT INTO `question` VALUES ('5', 'SQL语句区分大小写么?', '数据库查询语句区分大小写么?', '2014-05-21 08:06:33', '0', '0', '55', '0'); INSERT INTO `question` VALUES ('7', '大一军训多久?', '湖南科技大学大一新生军训多长时间,严不严?可以不军训么....', '2014-05-21 10:21:43', '0', '0', '6', '0'); INSERT INTO `question` VALUES ('8', '大一可以谈恋爱么?', '大一新生谈恋爱的多不多?科大美女多不多,是南校女生多,还是北校多呀,那个校区女生整体质量比较好?', '2014-05-21 10:28:12', '0', '0', '其它', '0'); INSERT INTO `question` VALUES ('9', '美食', '湖南科技大学那个食堂的饭比较好吃,那个食堂的最不好吃?', '2014-05-21 11:59:08', '0', '0', '66', '0'); INSERT INTO `question` VALUES ('10', '专业课程', '有谁知道大一计算机系有哪些课程?跪求解答!!!', '2014-05-22 12:00:48', '0', '0', '22', '0'); INSERT INTO `question` VALUES ('11', '系统问题', '为什么我发的答案显示不了?求许永利解释@许永利', '2014-05-22 12:12:17', '0', '0', '许永利', '0'); INSERT INTO `question` VALUES ('12', '熬夜', '现在都00点13分了,有木有还没有睡的?', '2014-05-22 12:14:16', '0', '0', '困', '0'); INSERT INTO `question` VALUES ('13', '问答有问题', '为什么每次发表问题后返回的页面中都没有我刚刚题的问题,求王大神解释!!!', '2014-05-22 12:15:44', '0', '0', '问答系统', '0'); INSERT INTO `question` VALUES ('14', 'html按钮button怎么加超链接', '<input name=\"注册\" type=\"button\" id=\"btn1\" title=\"登注册\" value=\"注册\" />怎么让这个点下,转向一个链接? 晕。。 我不是要提交数据,只是想用按钮当个超链接啊! ', '2014-05-25 11:07:49', '0', '0', '56', '0'); INSERT INTO `question` VALUES ('15', '返回值:jQueryjQuery', 'jQuery 的核心功能都是通过这个函数实现的。 jQuery中的一切都基于这个函数,或者说都是在以某种方式使用这个函数。这个函数最基本的用法就是向它传递一个表达式(通常由 CSS 选择器组成),然后根据这个表达式来查找所有匹配的元素。\r\n\r\n默认情况下, 如果没有指定context参数,$()将在当前的 HTML document中查找 DOM 元素;如果指定了 context 参数,如一个 DOM 元素集或 jQuery 对象,那就会在这个 context 中查找。在jQuery 1.3.2以后,其返回的元素顺序等同于在context中出现的先后顺序。\r\n', '2014-05-25 11:30:04', '0', '0', '56', '0'); INSERT INTO `question` VALUES ('16', '13124', '32423', '2014-06-15 01:37:41', '0', '0', '1', '0'); INSERT INTO `question` VALUES ('19', '求GTASA里面的DATA文件 不要装MOD的', '还有我添加了个双枪WEAPON.DOT文件 开枪为什么会弹出', '2014-06-28 02:47:59', '0', '0', '', '0'); INSERT INTO `question` VALUES ('20', 'input元素hidden属性和text属性的取值问题', '两个input元素,一个hidden属性,一个text属性,名字都叫name的话,提交到表单的值是hidden的还是text的\r\n是jsp的,两个同名input,属性均为text,但是设置一个display:“”\r\n一个display:none;显示出来的input值是有的,不显示的input的值是空,交到后台,得不到值,加上一个同名hidden就能取到了,就想知道同名元素怎么取值的', '2014-06-28 03:12:11', '1', '0', '', '0'); INSERT INTO `question` VALUES ('21', 'input元素hidden属性和text属性的取值问题', '两个input元素,一个hidden属性,一个text属性,名字都叫name的话,提交到表单的值是hidden的还是text的\r\n是jsp的,两个同名input,属性均为text,但是设置一个display:“”\r\n一个display:none;显示出来的input值是有的,不显示的input的值是空,交到后台,得不到值,加上一个同名hidden就能取到了,就想知道同名元素怎么取值的', '2014-06-28 03:14:35', '0', '0', '', '0'); INSERT INTO `question` VALUES ('22', '\'几天周几?', '今天时间...', '2014-06-28 08:21:02', '0', '0', '', '0'); INSERT INTO `question` VALUES ('23', '我们认识么?', '我想知道我们究竟认识么、?', '2014-04-13', '0', '1', '情感', '0'); INSERT INTO `question` VALUES ('24', '这事儿一句话说不清楚', '这事儿一句话说不清楚这事儿一句话说不清楚这事儿一句话说不清楚这事儿一句话说不清楚这事儿一句话说不清楚这事儿一句话说不清楚这事儿一句话说不清楚这事儿一句话说不清楚这事儿一句话说不清楚这事儿一句话说不清楚这事儿一句话说不清楚这事儿一句话说不清楚这事儿一句话说不清楚这事儿一句话说不清楚这事儿一句话说不清楚', '2014-07-13 03:07:04', '0', '5', '', '0'); INSERT INTO `question` VALUES ('26', '湖南科技大学怎么样', '湖南科技大学怎么样', '2014-07-13 10:49:58', '2', '1', '', '0'); INSERT INTO `question` VALUES ('27', '湖南科技大学什么专业最好?', '想报考那个学校。', '2014-07-13 10:51:55', '3', '1', '', '0'); INSERT INTO `question` VALUES ('28', '湖南科技大学图书馆在哪?', '位置在哪儿', '2014-07-13 10:54:46', '2', '1', '', '0'); INSERT INTO `question` VALUES ('29', '计算机专业下个学期的课程设计是做什么,做多久啊?', '如题,请大声告诉我一下,感激不尽!!!', '2014-07-14 02:58:28', '-1', '7', '课程设计', '0'); INSERT INTO `question` VALUES ('30', '智能问答平台功能更新', '湖南科技大学智能问答平台功能更新说明:\r\n1、系统安全方面注册和登录增加验证码功能;\r\n2、用户的注册成功邮箱提醒和密码邮箱验证密码找回。', '2014-07-24 10:43:52', '2', '1', '', '0'); INSERT INTO `question` VALUES ('31', '请问还有没有第六个人在!!', '哈哈哈哈哈哈哈哈哈哈,我是来打酱油的!!!', '2014-07-28 08:51:48', '1', '18', '酱油', '0'); INSERT INTO `question` VALUES ('32', 'CSS绝对定位与相对定位的区别?', 'CSS绝对定位与相对定位的区别?', '2014-07-31 12:11:34', '1', '4', '网页设计', '0'); INSERT INTO `question` VALUES ('33', '关于java程序在BAE3.0上部署', '是这样,原来用BAE2.0的时候,创建完程序,直接将从Myeclips中导出的.war文件上传就行,但是现在改成BAE3.0之后,就放在SVN里面发布。我将一个能够正常运行的java程序的.war文件发布之后,点击查看页面,出来404错误。。这是为什么。', '2014-08-26 06:20:00', '1', '1', '39', '0'); -- ---------------------------- -- Table structure for question_categories -- ---------------------------- DROP TABLE IF EXISTS `question_categories`; CREATE TABLE `question_categories` ( `question_categories_id` int(11) NOT NULL AUTO_INCREMENT, `question_categories_name` varchar(20) DEFAULT NULL, `question_categories_description` varchar(200) NOT NULL, `last_categories_id` int(11) NOT NULL, PRIMARY KEY (`question_categories_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of question_categories -- ---------------------------- -- ---------------------------- -- Table structure for questions_keywords -- ---------------------------- DROP TABLE IF EXISTS `questions_keywords`; CREATE TABLE `questions_keywords` ( `questions_keywords_id` int(11) NOT NULL AUTO_INCREMENT, `questions_id` int(11) NOT NULL, `quesitons_keywords_topN` varchar(2000) DEFAULT NULL, `questions_keywords_counts` varchar(2000) DEFAULT NULL, PRIMARY KEY (`questions_keywords_id`), KEY `questions_keywords` (`questions_id`), CONSTRAINT `questions_keywords` FOREIGN KEY (`questions_id`) REFERENCES `question` (`question_id`) ) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of questions_keywords -- ---------------------------- INSERT INTO `questions_keywords` VALUES ('1', '31', '哈哈哈,请问,第六个,酱油,哈哈哈哈,人在,', '2,1,1,1,1,1,'); INSERT INTO `questions_keywords` VALUES ('2', '30', '功能,问答,注册,智能,平台,更新,邮箱,验证码,成功,用户,登录,密码,科技大学,系统安全,湖南,提醒,密码找回,验证,增加,', '3,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,'); INSERT INTO `questions_keywords` VALUES ('3', '29', '如题,专业,大声,做什么,计算机,学期,感激不尽,多久,告诉我,课程设计,下个,', '1,1,1,1,1,1,1,1,1,1,1,'); INSERT INTO `questions_keywords` VALUES ('4', '28', '科技大学,图书馆,位置,湖南,在哪儿,在哪,', '1,1,1,1,1,1,'); INSERT INTO `questions_keywords` VALUES ('5', '27', '科技大学,专业,学校,湖南,报考,', '1,1,1,1,1,'); INSERT INTO `questions_keywords` VALUES ('6', '26', '科技大学,湖南,', '2,2,'); INSERT INTO `questions_keywords` VALUES ('7', '24', '说不清楚,一句话,这事儿,', '16,16,16,'); INSERT INTO `questions_keywords` VALUES ('8', '23', '想知道,', '1,'); INSERT INTO `questions_keywords` VALUES ('9', '22', '天周,时间,', '1,1,'); INSERT INTO `questions_keywords` VALUES ('10', '21', 'input,属性,text,hidden,元素,同名,交到,display,两个,取值,显示,表单,jsp,显示出来,就能,就想,得不到,设置,名字,均为,', '5,5,4,4,3,3,2,2,2,2,1,1,1,1,1,1,1,1,1,1,'); INSERT INTO `questions_keywords` VALUES ('11', '20', 'input,属性,text,hidden,元素,同名,交到,display,两个,取值,显示,表单,jsp,显示出来,就能,就想,得不到,设置,名字,均为,', '5,5,4,4,3,3,2,2,2,2,1,1,1,1,1,1,1,1,1,1,'); INSERT INTO `questions_keywords` VALUES ('12', '19', '文件,weapon.dot,开枪,mod,加了,data,弹出,gtasa,', '2,1,1,1,1,1,1,1,'); INSERT INTO `questions_keywords` VALUES ('15', '16', '1312432423,', '1,'); INSERT INTO `questions_keywords` VALUES ('16', '15', '函数,元素,context,jquery,查找,参数,dom,指定,表达式,都是,1.3.2,如一,某种,匹配,document,默认,jqueryjqueryjquery,顺序,将在,选择器,', '4,4,4,3,3,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,'); INSERT INTO `questions_keywords` VALUES ('17', '14', '注册,超链接,按钮,button,当个,转向,链接,type,数据,input,title,想用,btn1,html,提交,', '3,2,2,2,1,1,1,1,1,1,1,1,1,1,1,'); INSERT INTO `questions_keywords` VALUES ('18', '13', '发表,大神,每次,问答,中都,解释,刚刚,页面,返回,', '1,1,1,1,1,1,1,1,1,'); INSERT INTO `questions_keywords` VALUES ('19', '12', '还没有,00点,分了,熬夜,13,', '1,1,1,1,1,'); INSERT INTO `questions_keywords` VALUES ('20', '11', '显示,答案,系统,解释,', '1,1,1,1,'); INSERT INTO `questions_keywords` VALUES ('21', '10', '计算机系,解答,有谁,大一,跪求,专业课程,课程,', '1,1,1,1,1,1,1,'); INSERT INTO `questions_keywords` VALUES ('22', '9', '好吃,食堂,科技大学,最不,湖南,美食,', '2,2,1,1,1,1,'); INSERT INTO `questions_keywords` VALUES ('23', '8', '谈恋爱,女生,大一,多不多,新生,质量,校区,美女,科大,整体,比较好,', '2,2,2,2,1,1,1,1,1,1,1,'); INSERT INTO `questions_keywords` VALUES ('24', '7', '军训,大一,科技大学,多长时间,新生,不严,湖南,多久,', '3,2,1,1,1,1,1,1,'); INSERT INTO `questions_keywords` VALUES ('25', '5', '语句,区分,大小写,sql,数据库,查询,', '2,2,2,1,1,1,'); INSERT INTO `questions_keywords` VALUES ('26', '4', '迷惑,', '1,'); INSERT INTO `questions_keywords` VALUES ('27', '3', '星期,时间,', '1,1,'); INSERT INTO `questions_keywords` VALUES ('28', '2', 'python,编程,语言,', '1,1,1,'); INSERT INTO `questions_keywords` VALUES ('29', '1', '做什么,系统,这是,', '2,1,1,'); INSERT INTO `questions_keywords` VALUES ('30', '32', '定位,区别,css,', '4,2,2,'); INSERT INTO `questions_keywords` VALUES ('31', '33', '程序,war,文件,之后,java,bae3.0,发布,bae2.0,点击,放在,改成,这是,就行,部署,能够,这样,正常,错误,上传,为什么,', '3,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,'); -- ---------------------------- -- Table structure for tags_categories -- ---------------------------- DROP TABLE IF EXISTS `tags_categories`; CREATE TABLE `tags_categories` ( `tags_categories_id` int(11) NOT NULL, `tags_categories_name` varchar(20) NOT NULL, `tags_categories_description` varchar(200) NOT NULL, `last_categories_id` int(11) DEFAULT NULL, PRIMARY KEY (`tags_categories_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of tags_categories -- ---------------------------- INSERT INTO `tags_categories` VALUES ('1', '我是新生', '作为一名新生对于校园的种种疑惑,在这里为你解答。', '0'); INSERT INTO `tags_categories` VALUES ('2', '考证专区', '大学考证五花八门,你有不懂我来回答。', '0'); INSERT INTO `tags_categories` VALUES ('3', '专业知识', '专业方面的疑惑或许这里有你需要的答案哦!', '0'); INSERT INTO `tags_categories` VALUES ('4', '工作离校', '大四离校、三方协议、工作实习、这里有你想要。', '0'); INSERT INTO `tags_categories` VALUES ('5', 'IT领域', '为计算机专业特色定制的编程语言版块。', '0'); INSERT INTO `tags_categories` VALUES ('6', '科大周边', '科大周边,吃喝玩乐统统搞定。', '0'); INSERT INTO `tags_categories` VALUES ('7', '学校后勤', ' 学校后勤方面的疑问,也可以在这里得到解决哦。', '0'); INSERT INTO `tags_categories` VALUES ('8', '学长学姐', '学霸经验,学渣奋斗史,看屌丝如何逆袭高富帅。', '0'); INSERT INTO `tags_categories` VALUES ('9', '校园活动', '社团竞选,学生会,晚会,比赛应有尽有。', '0'); INSERT INTO `tags_categories` VALUES ('10', '考研攻略', '选你所爱,爱你所选。考研辅导,给你想要的。', '0'); -- ---------------------------- -- Table structure for tags_info -- ---------------------------- DROP TABLE IF EXISTS `tags_info`; CREATE TABLE `tags_info` ( `tag_id` int(11) NOT NULL AUTO_INCREMENT, `tag_name` varchar(20) NOT NULL, `tags_categories_id` varchar(11) DEFAULT '0', `tags_description` varchar(500) DEFAULT NULL, PRIMARY KEY (`tag_id`), KEY `tags_info` (`tags_categories_id`) ) ENGINE=InnoDB AUTO_INCREMENT=96 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of tags_info -- ---------------------------- INSERT INTO `tags_info` VALUES ('0', '录取信息', '1', null); INSERT INTO `tags_info` VALUES ('1', '迎新', '1', null); INSERT INTO `tags_info` VALUES ('2', '报到', '1', null); INSERT INTO `tags_info` VALUES ('3', '住宿', '1', null); INSERT INTO `tags_info` VALUES ('4', '入学教育', '1', null); INSERT INTO `tags_info` VALUES ('5', '社团竞选', '1', null); INSERT INTO `tags_info` VALUES ('6', '军训', '1', null); INSERT INTO `tags_info` VALUES ('7', '学生会', '1', null); INSERT INTO `tags_info` VALUES ('8', '校历', '1', null); INSERT INTO `tags_info` VALUES ('9', '新生规划', '1', null); INSERT INTO `tags_info` VALUES ('10', '英语考证', '2', null); INSERT INTO `tags_info` VALUES ('11', '会计资格证', '2', null); INSERT INTO `tags_info` VALUES ('12', '计算机证书', '2', null); INSERT INTO `tags_info` VALUES ('13', '教师资格证', '2', null); INSERT INTO `tags_info` VALUES ('14', '导游资格证', '2', null); INSERT INTO `tags_info` VALUES ('15', '普通话考试', '2', null); INSERT INTO `tags_info` VALUES ('16', '经济学类', '3', null); INSERT INTO `tags_info` VALUES ('17', '管理学类', '3', null); INSERT INTO `tags_info` VALUES ('18', '土建类', '3', null); INSERT INTO `tags_info` VALUES ('19', '文学类', '3', null); INSERT INTO `tags_info` VALUES ('20', '农学类', '3', null); INSERT INTO `tags_info` VALUES ('21', '教育学类', '3', null); INSERT INTO `tags_info` VALUES ('22', '计算机类', '3', null); INSERT INTO `tags_info` VALUES ('23', '能源与材料类', '3', null); INSERT INTO `tags_info` VALUES ('24', '历史学类', '3', null); INSERT INTO `tags_info` VALUES ('25', '法学类', '3', null); INSERT INTO `tags_info` VALUES ('26', '电气电子类', '3', null); INSERT INTO `tags_info` VALUES ('27', '生化与药品类', '3', null); INSERT INTO `tags_info` VALUES ('28', '传媒与艺术类', '3', null); INSERT INTO `tags_info` VALUES ('29', '实习', '4', null); INSERT INTO `tags_info` VALUES ('30', '工作', '4', null); INSERT INTO `tags_info` VALUES ('31', '就业信息', '4', null); INSERT INTO `tags_info` VALUES ('32', '三方协议', '4', null); INSERT INTO `tags_info` VALUES ('33', '数字离校', '4', null); INSERT INTO `tags_info` VALUES ('34', '劳动合同', '4', null); INSERT INTO `tags_info` VALUES ('35', '薪资待遇', '4', null); INSERT INTO `tags_info` VALUES ('36', '毕业相关', '4', null); INSERT INTO `tags_info` VALUES ('37', '校友', '4', null); INSERT INTO `tags_info` VALUES ('38', '培训', '4', null); INSERT INTO `tags_info` VALUES ('39', 'java', '5', null); INSERT INTO `tags_info` VALUES ('40', 'php', '5', null); INSERT INTO `tags_info` VALUES ('41', 'c', '5', null); INSERT INTO `tags_info` VALUES ('42', 'c++', '5', null); INSERT INTO `tags_info` VALUES ('43', 'c#', '5', null); INSERT INTO `tags_info` VALUES ('44', '.net', '5', null); INSERT INTO `tags_info` VALUES ('45', 'asp', '5', null); INSERT INTO `tags_info` VALUES ('46', 'python', '5', null); INSERT INTO `tags_info` VALUES ('47', 'javascript', '5', null); INSERT INTO `tags_info` VALUES ('48', 'objective-c', '5', null); INSERT INTO `tags_info` VALUES ('49', 'node.js', '5', null); INSERT INTO `tags_info` VALUES ('50', '软件破解', '5', null); INSERT INTO `tags_info` VALUES ('51', 'mobil OS', '5', null); INSERT INTO `tags_info` VALUES ('52', 'PC OS', '5', null); INSERT INTO `tags_info` VALUES ('53', '手机APP', '5', null); INSERT INTO `tags_info` VALUES ('55', 'DataBase', '5', null); INSERT INTO `tags_info` VALUES ('56', '其它语言', '5', null); INSERT INTO `tags_info` VALUES ('57', 'IDE', '5', null); INSERT INTO `tags_info` VALUES ('58', 'PS', '5', null); INSERT INTO `tags_info` VALUES ('59', '游戏影音', '5', null); INSERT INTO `tags_info` VALUES ('60', '游戏办公', '5', null); INSERT INTO `tags_info` VALUES ('64', '其它', '5', null); INSERT INTO `tags_info` VALUES ('65', '网页前端', '5', null); INSERT INTO `tags_info` VALUES ('66', '美食', '6', null); INSERT INTO `tags_info` VALUES ('67', '娱乐', '6', null); INSERT INTO `tags_info` VALUES ('68', '景点', '6', null); INSERT INTO `tags_info` VALUES ('69', '活动', '6', null); INSERT INTO `tags_info` VALUES ('70', '打折优惠', '6', null); INSERT INTO `tags_info` VALUES ('71', '爱心公益', '6', null); INSERT INTO `tags_info` VALUES ('72', '公交路线', '6', null); INSERT INTO `tags_info` VALUES ('73', '基础设施', '7', null); INSERT INTO `tags_info` VALUES ('74', '保修', '7', null); INSERT INTO `tags_info` VALUES ('75', '建议', '7', null); INSERT INTO `tags_info` VALUES ('76', '咨询', '7', null); INSERT INTO `tags_info` VALUES ('77', '基础设施', '7', null); INSERT INTO `tags_info` VALUES ('78', '保修', '7', null); INSERT INTO `tags_info` VALUES ('79', '建议', '7', null); INSERT INTO `tags_info` VALUES ('80', '咨询', '7', null); INSERT INTO `tags_info` VALUES ('81', '其它', '7', null); INSERT INTO `tags_info` VALUES ('82', '二手市场', '8', null); INSERT INTO `tags_info` VALUES ('83', '考试攻略', '8', null); INSERT INTO `tags_info` VALUES ('84', '选修推荐', '8', null); INSERT INTO `tags_info` VALUES ('85', '经验分享', '8', null); INSERT INTO `tags_info` VALUES ('86', '其它相关', '8', null); INSERT INTO `tags_info` VALUES ('87', '社团活动', '9', null); INSERT INTO `tags_info` VALUES ('88', '素质拓展', '9', null); INSERT INTO `tags_info` VALUES ('89', '俱乐部', '9', null); INSERT INTO `tags_info` VALUES ('90', '文艺晚会', '9', null); INSERT INTO `tags_info` VALUES ('91', '热门推荐', '9', null); INSERT INTO `tags_info` VALUES ('92', '前期准备', '10', null); INSERT INTO `tags_info` VALUES ('93', '考研必备', '10', null); INSERT INTO `tags_info` VALUES ('94', '培训推荐', '10', null); INSERT INTO `tags_info` VALUES ('95', '相关资料', '10', null); -- ---------------------------- -- Table structure for user_info -- ---------------------------- DROP TABLE IF EXISTS `user_info`; CREATE TABLE `user_info` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `user_name` varchar(20) NOT NULL, `user_password` varchar(20) NOT NULL, `user_email` varchar(40) NOT NULL, `user_mark` int(11) DEFAULT NULL, `user_tags` varchar(100) DEFAULT NULL, `user_logo` varchar(150) DEFAULT NULL, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of user_info -- ---------------------------- INSERT INTO `user_info` VALUES ('1', 'admin', 'admin', '<EMAIL>', '0', '1,2', null); INSERT INTO `user_info` VALUES ('2', 'xuyongli', 'xuyongli', '<EMAIL>', '1', '1,2,3', null); INSERT INTO `user_info` VALUES ('3', 'niu', 'niu', '<EMAIL>', '0', '2.5.8', null); INSERT INTO `user_info` VALUES ('4', 'xiaofei', 'xiaofei', '<EMAIL>', '0', '1,2,3', null); INSERT INTO `user_info` VALUES ('5', 'bubu', 'bubu', '<EMAIL>', '0', null, null); INSERT INTO `user_info` VALUES ('6', 'niuyichao', 'nyc', '<EMAIL>', '0', null, null); INSERT INTO `user_info` VALUES ('7', '王大锤', 'wangdachui', '<EMAIL>', '0', null, null); INSERT INTO `user_info` VALUES ('8', 'xutao', 'xutao', '<EMAIL>', '0', null, null); INSERT INTO `user_info` VALUES ('9', 'gmf', 'gmf', '<EMAIL>', '0', null, null); INSERT INTO `user_info` VALUES ('10', 'daxia', 'daxia', '987<EMAIL>', '0', null, null); INSERT INTO `user_info` VALUES ('13', 'zxc', 'zxczxc', '<EMAIL>', '0', null, null); INSERT INTO `user_info` VALUES ('15', '小飞', 'xiaofei', '<EMAIL>', '0', null, null); INSERT INTO `user_info` VALUES ('16', '24', '24', '<EMAIL>', '0', null, null); INSERT INTO `user_info` VALUES ('17', 'Devilsen', 'dmc375913436', '<EMAIL>', '0', null, null); INSERT INTO `user_info` VALUES ('18', '许涛', '24', '<EMAIL>', '0', null, null); <file_sep>demos ===== It's my codes. <file_sep>package com.example.app.hnust_qa; import android.app.Activity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.example.app.hnust_qa.Tools.NetTool; import com.example.hnust.R; import me.imid.swipebacklayout.lib.SwipeBackLayout; import me.imid.swipebacklayout.lib.app.SwipeBackActivity; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import java.io.IOException; import static com.example.app.hnust_qa.Tools.LayoutTool.setCustomTitle; /** * Created by Administrator on 2014/8/11 0011. */ public class AddAnwserActivity extends SwipeBackActivity { private TextView title_name; private TextView title_center; private TextView title_right; private EditText et_add_anwser; private String addAnswerUrl; private String comment; private String questionId; //SwipeBackActivity相关组件 private SwipeBackLayout mSwipeBackLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.add_anwser_layout); //设置swipeBackLayout mSwipeBackLayout = getSwipeBackLayout(); mSwipeBackLayout.setEdgeTrackingEnabled(SwipeBackLayout.EDGE_LEFT); Intent intent = getIntent(); questionId = intent.getStringExtra("questionId"); //设置标题栏 setCustomTitle(AddAnwserActivity.this,R.layout.title_layout); title_name = (TextView) findViewById(R.id.title_name); title_center = (TextView) findViewById(R.id.title_middle); title_right = (TextView) findViewById(R.id.title_right); title_name.setText("添加答案"); title_center.setText(""); title_right.setText("发布"); et_add_anwser = (EditText) findViewById(R.id.et_add_anwser); //设置进入画效果(退出效果在onpause里面) overridePendingTransition(R.anim.enter_animation,R.anim.back_animation ); title_right.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { comment = et_add_anwser.getText().toString().trim(); new AddAnswerTask().execute(); finish(); } }); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); //设置退出动画效果 overridePendingTransition(R.anim.enter_animation,R.anim.back_animation ); } //评论 class AddAnswerTask extends AsyncTask { private int statuCode = 0; @Override protected Object doInBackground(Object[] objects) { addAnswerUrl = NetTool.web + "addAnswerInfoMobile?answer_description="; addAnswerUrl = addAnswerUrl + comment + "&question_id=" + questionId + "&userId=" + NetTool.userId; try { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(addAnswerUrl); httpGet.setHeader("Cookie", NetTool.sessionId); HttpResponse httpResponse = httpClient.execute(httpGet); statuCode = httpResponse.getStatusLine().getStatusCode(); Log.e("url", addAnswerUrl); Log.e("comment",comment); Log.e("questionId",questionId); HttpEntity httpEntity = httpResponse.getEntity(); String string = EntityUtils.toString(httpEntity, "utf-8"); Log.e("string",string); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Object o) { super.onPostExecute(o); if(statuCode == 200){ Toast.makeText(AddAnwserActivity.this, "评论成功", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(AddAnwserActivity.this,"评论有点小问题,再试一次吧",Toast.LENGTH_SHORT).show(); } } } } <file_sep>package cn.com.servlets.question; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.com.beans.QuestionAllInfoBean; import cn.com.beans.QuestionBean; import cn.com.beans.QuestionsKeywordsBean; import cn.com.daos.AnswerDaoImp; import cn.com.daos.QuestionDaoImp; import cn.com.daos.QuestionsKeywordsDaoImp; import cn.com.daos.TagsInfoDaoImp; import cn.com.daos.UserInfoDaoImp; import cn.com.util.ChineseAnalyzerUtil; public class SearchQuestionServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String context = request.getParameter("context"); if(context == null||context.equals("")){ request.getRequestDispatcher("index").forward(request, response); return; } System.out.println("You input words is "+context); QuestionDaoImp questionDaoImp = new QuestionDaoImp(); AnswerDaoImp answerDaoImp = new AnswerDaoImp(); UserInfoDaoImp userInfoDaoImp = new UserInfoDaoImp(); List<QuestionAllInfoBean> listAllQuestions = new ArrayList<QuestionAllInfoBean>(); Pattern pattern = Pattern.compile("[0-9]*"); TagsInfoDaoImp tagsInfoDaoImp = new TagsInfoDaoImp(); QuestionAllInfoBean questionAllInfoBean = null; QuestionBean questionBean = new QuestionBean(); ChineseAnalyzerUtil chineseAnalyzerUtil = new ChineseAnalyzerUtil(); List<String> listKeyWords = chineseAnalyzerUtil .getSearchKeyWords(context); StringBuffer tempKeywords = new StringBuffer(); for (int i = 0; i < listKeyWords.size(); i++) { tempKeywords.append(listKeyWords.get(i) + "%"); } System.out.println(tempKeywords); List<QuestionBean> questionKeyList = new ArrayList<QuestionBean>(); questionKeyList = questionDaoImp.getQuestionByQuestionName(tempKeywords .toString()); System.out.println("Search keywords:" + tempKeywords); System.out.println("Result total:" + questionKeyList.size()); //问题描述信息截取 for (int i = 0; i < questionKeyList.size(); i++) { questionAllInfoBean = new QuestionAllInfoBean(); questionBean = questionKeyList.get(i); if (questionBean.getQuestion_description().length() > 100) { questionBean.setQuestion_description(questionBean .getQuestion_description().substring(0, 100) + "..."); } String tagsId[] = null; //问题标签处理 if (questionBean.getQuestion_tags() == null || questionBean.getQuestion_tags().equals("")) { questionBean.setQuestion_tags("暂无"); } else { if (questionBean.getQuestion_tags() != null && questionBean.getQuestion_tags().indexOf(",") == -1 && pattern.matcher(questionBean.getQuestion_tags()) .matches()) { String tagsStr = tagsInfoDaoImp.getTagsInfoByTagsId( Integer.parseInt(questionBean.getQuestion_tags())) .getTags_name(); questionBean.setQuestion_tags(tagsStr); } else { if (questionBean.getQuestion_tags().indexOf(",") != -1) { tagsId = questionBean.getQuestion_tags().split(","); StringBuffer tagStrBuffer = new StringBuffer(); for (int i1 = 0; i1 < tagsId.length; i1++) { int tagsIdInt = Integer.parseInt(tagsId[i1]); String tagsStr = tagsInfoDaoImp .getTagsInfoByTagsId(tagsIdInt) .getTags_name() + " "; tagStrBuffer.append(tagsStr); } questionBean.setQuestion_tags(tagStrBuffer.toString()); } } } String userName = userInfoDaoImp.getUserInfoByUserId( questionBean.getQuestion_user_id()).getUser_name(); int countOfAnswer = answerDaoImp.getContOfAnswer(questionBean .getQuestion_id()); //封装完整的问题信息 questionAllInfoBean.setQuestionUserName(userName); questionAllInfoBean.setCountOfAnswers(countOfAnswer); questionAllInfoBean.setVpOfQuestion(50); questionAllInfoBean.setBestAnswer("暂无"); questionAllInfoBean.setQuestionBean(questionBean); listAllQuestions.add(questionAllInfoBean); } //搜索的热门问题信息处理 List<QuestionAllInfoBean> listHotQuestions = new ArrayList<QuestionAllInfoBean>(); List<QuestionBean> listHotQuestion = questionDaoImp .getHotQuestionsBySearch(tempKeywords.toString()); // UserInfoDaoImp userInfoDaoImp = new UserInfoDaoImp(); int len = 0; if (listHotQuestion.size() < 10) { len = listHotQuestion.size(); } else { len = 10; } for (int i = 0; i < len; i++) { questionAllInfoBean = new QuestionAllInfoBean(); questionBean = listHotQuestion.get(i); if (questionBean.getQuestion_description().length() > 100) { questionBean.setQuestion_description(questionBean .getQuestion_description().substring(0, 100) + "..."); } String tagsId[] = null; // System.out.println(questionBean.getQuestion_tags()); if (questionBean.getQuestion_tags() == null || questionBean.getQuestion_tags().equals("")) { questionBean.setQuestion_tags("暂无"); } else { if (questionBean.getQuestion_tags() != null && questionBean.getQuestion_tags().indexOf(",") == -1 && pattern.matcher(questionBean.getQuestion_tags()) .matches()) { String tagsStr = tagsInfoDaoImp.getTagsInfoByTagsId( Integer.parseInt(questionBean.getQuestion_tags())) .getTags_name(); questionBean.setQuestion_tags(tagsStr); } else { if (questionBean.getQuestion_tags().indexOf(",") != -1) { tagsId = questionBean.getQuestion_tags().split(","); StringBuffer tagStrBuffer = new StringBuffer(); for (int i1 = 0; i1 < tagsId.length; i1++) { int tagsIdInt = Integer.parseInt(tagsId[i1]); String tagsStr = tagsInfoDaoImp .getTagsInfoByTagsId(tagsIdInt) .getTags_name() + " "; tagStrBuffer.append(tagsStr); } questionBean.setQuestion_tags(tagStrBuffer.toString()); } } } String userName = userInfoDaoImp.getUserInfoByUserId( questionBean.getQuestion_user_id()).getUser_name(); int countOfAnswer = answerDaoImp.getContOfAnswer(questionBean .getQuestion_id()); questionAllInfoBean.setQuestionUserName(userName); questionAllInfoBean.setCountOfAnswers(countOfAnswer); questionAllInfoBean.setVpOfQuestion(50); questionAllInfoBean.setBestAnswer("暂无"); questionAllInfoBean.setQuestionBean(questionBean); listHotQuestions.add(questionAllInfoBean); } request.setAttribute("searchKeyWords", context); request.setAttribute("listHotQuestions", listHotQuestions); // ************************************************ request.setAttribute("listQuestions", listAllQuestions); request.getRequestDispatcher("index.jsp").forward(request, response); } } <file_sep>package cn.com.interfaces; import java.util.List; import cn.com.beans.TagsInfoBean; /** * @author Xianxiaofei * @date:2014-5-10 上午10:15:27 */ public interface TagsInfoDaoInf { //根据id得到标签信息 TagsInfoBean getTagsInfoByTagsId(int tags_id); //根据标签名得到标签信息 List<TagsInfoBean> getTagsInfoByTagsName(String tags_name); //新增标签信息 boolean addTagsInfo(TagsInfoBean tagsInfoBean); //删除标签信息 boolean deleteTagsInfo(int tags_id); //获得所有标签信息 List<TagsInfoBean> getAllTagsInfo(); //修改标签信息 boolean updateTagsInfo(TagsInfoBean tagsInfoBean); //统计标签总数 int getContOfTags(); //获得热门标签 List<TagsInfoBean> getHotTags(); } <file_sep> // 按需加载 // Step:3 conifg ECharts's path, link to echarts.js from current page. // Step:3 为模块加载器配置echarts的路径,从当前页面链接到echarts.js,定义所需图表路径 require.config({ paths: { echarts: './js/echarts' //echarts.js的路径 } }); // Step:4 require echarts and use it in the callback. // Step:4 动态加载echarts然后在回调函数中开始使用,注意保持按需加载结构定义图表路径 require( [ 'echarts', 'echarts/chart/line' ], //回调函数 DrawEChart ); Array.prototype.in_array = Array.prototype.in_array || function(e) { for(i=0;i<this.length && this[i]!=e;i++); return !(i==this.length); } var nodes3 = new Array() //渲染ECharts图表 function DrawEChart(ec) { //图表渲染的容器对象 var chartContainer = document.getElementById("echart_person"); //加载图表 var myChart = ec.init(chartContainer); var nodes = new Array(); var links = new Array(); nodes.push({ category: 0, name: "Me", value: 10 }) var person_id = $('#person').attr('value'); $.post('/userRelation', {'userid':person_id}, function(data){ var datas = $.parseJSON(data); console.log(datas) for(var i=0; i < datas['following'].length; i++){ nodes.push({ category : 1, name : datas['following'][i], value : 10 }); links.push({ source : 'Me', target : datas['following'][i], weight : 5 }) } for(var i=0; i < datas['follower'].length; i++){ if(!datas['following'].in_array(datas['follower'][i])){ console.log(datas['follower'][i],datas['following'] ) nodes.push({ category : 2, name : datas['follower'][i], value : 10 }); } links.push({ source :datas['follower'][i], target :'Me', weight : 5 }) } for (i in datas['link']){ for(var j=0; j<datas['link'][i].length; j++){ links.push({ source : i, target : datas['link'][i][j], weight : 5 }) } } myChart.setOption({ title : { x:'right', y:'bottom' }, tooltip : { trigger: 'item', formatter: '{a} : {b}' }, toolbox: { show : true, feature : { restore : {show: true}, saveAsImage : {show: true} } }, legend: { x: 'left', data:['被关注','关注'] }, series : [ { type:'force', name : "人物关系", categories : [ { name: '自己' }, { name: '关注' }, { name:'被关注' } ], itemStyle: { normal: { label: { show: true, textStyle: { color: '#333' } }, nodeStyle : { brushType : 'both', strokeColor : 'rgba(255,215,0,0.4)', lineWidth : 1 } }, emphasis: { label: { show: false // textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE }, nodeStyle : { //r: 30 }, linkStyle : {} } }, useWorker: false, minRadius : 6, maxRadius : 10, gravity: 1.1, scaling: 1.1, linkSymbol: 'arrow', nodes:nodes, links : links } ] }); }); }<file_sep>package cn.com.interfaces; import java.util.List; import cn.com.beans.BasicUserInfoBean; import cn.com.beans.UserInfoBean; /** * @author Xianxiaofei * @date:2014-5-10 ����10:14:24 */ public interface UserInfoDaoInf { // ͨ���û�����֤�û��Ƿ���� boolean validataByUserName(String user_name); // ��¼��֤ boolean validateByUserNameAndUserPassword(String user_name, String user_password); // ����û���õ��û���Ϣ UserInfoBean getUserInfoByUserName(String user_name); // ���id�õ��û���Ϣ UserInfoBean getUserInfoByUserId(int user_id); // �õ�������Ϣ List<UserInfoBean> getAllUserInfo(); // ɾ���û���Ϣ boolean deleteUserInfoByUserId(int user_id); // ������ģ���ѯ List<UserInfoBean> getUserInfoAllInfoByUserName(String user_name); // �����û���Ϣ(ע����) boolean addUserInfo(UserInfoBean uib); // �޸��û���Ϣ boolean updateUserInfoByUserId(UserInfoBean uib); // ����û����� int getCountOfUser(); // ������ŵ��û� List<UserInfoBean> getHotUserInfos(); BasicUserInfoBean getBasicUserInfoByUserId(int user_id); } <file_sep>package cn.com.daos; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import cn.com.beans.AnswerBean; import cn.com.beans.QuestionCategoriesBean; import cn.com.util.DBUtil; public class QuestionCategoriesDaoImp { private DBUtil db; public QuestionCategoriesDaoImp(){ db = new DBUtil(); } //根据id得到问题分类 public QuestionCategoriesBean getQuestionCategoriesrById(int quesion_categories_id) { QuestionCategoriesBean questionCategoriesBean = null; Connection con = db.getConn(); PreparedStatement pst = null; ResultSet rs = null; String sql= "select * from question_categories where quesion_categories_id = ?"; try { pst = con.prepareStatement(sql); pst.setInt(1, quesion_categories_id); rs = pst.executeQuery(); while (rs.next()) { questionCategoriesBean = new QuestionCategoriesBean(); questionCategoriesBean.setQuestion_categories_id(rs.getInt("question_categories_id")); questionCategoriesBean.setQuestion_categories_name(rs.getString("question_categories_name")); questionCategoriesBean.setQuestion_categories_description(rs.getString("question_categories_description")); questionCategoriesBean.setLast_categories_id(rs.getInt("last_categories_id")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ db.free(rs, pst, con); } return questionCategoriesBean; } //根据上一级id得到问题分类 public List<QuestionCategoriesBean> getQuestionCategoriesrByLastId(int last_categories_id) { List<QuestionCategoriesBean> list = new ArrayList<QuestionCategoriesBean>(); QuestionCategoriesBean questionCategoriesBean = null; Connection con = db.getConn();; PreparedStatement pst = null; ResultSet rs = null; String sql= "select * from question_categories where answer_id = ?"; try { pst = con.prepareStatement(sql); pst.setInt(1, last_categories_id); rs = pst.executeQuery(); while (rs.next()) { questionCategoriesBean = new QuestionCategoriesBean(); questionCategoriesBean.setQuestion_categories_id(rs.getInt("question_categories_id")); questionCategoriesBean.setQuestion_categories_name(rs.getString("question_categories_name")); questionCategoriesBean.setQuestion_categories_description(rs.getString("question_categories_description")); questionCategoriesBean.setLast_categories_id(rs.getInt("last_categories_id")); list.add(questionCategoriesBean); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ db.free(rs, pst, con); } return list; } } <file_sep>package cn.com.servlets.rest; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import redis.clients.jedis.Jedis; import cn.com.beans.QuestionBean; import cn.com.beans.QuestionsKeywordsBean; import cn.com.beans.UserInfoBean; import cn.com.daos.QuestionDaoImp; import cn.com.daos.QuestionsKeywordsDaoImp; import cn.com.daos.UserInfoDaoImp; import cn.com.util.ChineseAnalyzerUtil; import redis.clients.jedis.Jedis; import cn.com.util.RUtil; import cn.com.mq.Notify; /** * @author Banama * * praise( zan ) a question * POST /praise question_id * if the event success return "True", or return something other. */ public class Praise extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RUtil redis = new RUtil(); Jedis rdb = redis.con(); response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(); UserInfoBean uib = (UserInfoBean) session.getAttribute("userBean"); if (uib == null) { out.write("require login"); } else { String question_id = request.getParameter("question_id"); String select_praise = "userid:" + uib.getUser_id() + ":questionid:" + question_id; String select_praises = "questionid:" + question_id; QuestionDaoImp qsDao = new QuestionDaoImp(); QuestionBean qs = qsDao.getQuestionByQuestionId(Integer.parseInt(question_id)); int qs_mark = qs.getQuestion_mark(); String mark = (String) rdb.hget("praise", select_praise); if (mark == null || mark.equals("0")) { // praise notify Notify notifys = new Notify(); notifys.set_questionid(Integer.parseInt(question_id)); notifys.set_userid(uib.getUser_id()); notifys.praise(); rdb.hset("praise", select_praise, "1"); rdb.hincrBy("praises", select_praises, 1); String marks = (String) rdb.hget("praises", select_praises); qsDao.updateQS_remark(Integer.parseInt(marks), Integer.parseInt(question_id)); out.write("True"); } else if (mark.equals("-1")) { // praise notify Notify notifys = new Notify(); notifys.set_questionid(Integer.parseInt(question_id)); notifys.set_userid(uib.getUser_id()); notifys.praise(); rdb.hset("praise", select_praise, "1"); rdb.hincrBy("praises", select_praises, 2); String marks = (String) rdb.hget("praises", select_praises); qsDao.updateQS_remark(Integer.parseInt(marks), Integer.parseInt(question_id)); out.write("True"); } else { rdb.hset("praise", select_praise, "0"); rdb.hincrBy("praises", select_praises, -1); String marks = (String) rdb.hget("praises", select_praises); qsDao.updateQS_remark(Integer.parseInt(marks), Integer.parseInt(question_id)); out.write("True"); } } out.flush(); out.close(); } }<file_sep>/** * */ package cn.com.mservlets.question; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import net.sf.json.JSONObject; import cn.com.beans.QuestionBean; import cn.com.beans.QuestionsKeywordsBean; import cn.com.beans.UserInfoBean; import cn.com.daos.QuestionDaoImp; import cn.com.daos.QuestionsKeywordsDaoImp; import cn.com.util.ChineseAnalyzerUtil; /** * @author Xianxiaofei * @date 2014-5-13 下午5:06:38 */ @SuppressWarnings("serial") public class AskQuestionServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // HttpSession session = request.getSession(); // UserInfoBean uib = (UserInfoBean)session.getAttribute("userBean"); // if(uib == null){ // request.getRequestDispatcher("userLogin.jsp").forward(request, response); // return; // } String question_title = request.getParameter("question_title"); String question_description = request .getParameter("question_description"); String question_tags = request.getParameter("question_tags"); //登录后使用注释的语句 int question_user_id = Integer.parseInt(request.getParameter("userId")); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//设置日期格式 String question_time = sdf.format(new Date()); int question_mark = 0; QuestionBean questionBean = new QuestionBean(); questionBean.setQuestion_title(question_title); questionBean.setQuestion_description(question_description); questionBean.setQuestion_tags(question_tags); questionBean.setQuestion_user_id(question_user_id); questionBean.setQuestion_time(question_time); questionBean.setQuestion_mark(question_mark); //问题分类默认为0 questionBean.setQuestion_categories_id(0); QuestionDaoImp questionDao = new QuestionDaoImp(); // boolean status = questionDao.addQuestion(questionBean); // request.getRequestDispatcher("index").forward(request, response); boolean status; if( status = questionDao.addQuestion(questionBean)){ QuestionBean questionBean1 = new QuestionBean(); questionBean1 = questionDao.getQuestionByQuestionByDescription(question_description); //对当前问题分词处理 ChineseAnalyzerUtil chineseAnalyzerUtil = new ChineseAnalyzerUtil(); StringBuffer questionContext = new StringBuffer(questionBean1.getQuestion_description()+questionBean1.getQuestion_title()); StringBuffer questionContext2 = new StringBuffer(); StringBuffer countTopN = new StringBuffer(); int questionId = questionBean1.getQuestion_id(); List<Map.Entry<String, Integer>> map = chineseAnalyzerUtil.getAnalyzerKeywordsString(chineseAnalyzerUtil.getTextDef(questionContext.toString())); QuestionsKeywordsBean questionKeywords = new QuestionsKeywordsBean(); questionKeywords.setQuestion_id(questionId); //取分词频率最高的前20 for (int i1 = 0; i1 < 20 && i1 < map.size(); i1++) { Map.Entry<String, Integer> wordFrenEntry = map.get(i1); questionContext2.append(wordFrenEntry.getKey()+","); countTopN.append(wordFrenEntry.getValue()+","); } questionKeywords.setQuesitons_keywords_topN(questionContext2.toString()); questionKeywords.setQuestions_keywords_counts(countTopN.toString()); //存入数据库中 QuestionsKeywordsDaoImp questionsKeywordsDaoImp = new QuestionsKeywordsDaoImp(); if(questionsKeywordsDaoImp.addQuestionsKeywordsBean(questionKeywords)){ System.out.println("新增问题分词处理成功!"); } Map<String,Boolean> map1 = new HashMap<String,Boolean>(); map1.put("message", status); JSONObject json = JSONObject.fromObject(map1); response.getWriter().println(json); }else { } } } <file_sep>package cn.com.servlets.user; /** * @author Xianxiaofei * @date:2014年8月5日 下午5:28:37 */ import java.util.HashMap; import java.util.Map; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.omg.PortableInterceptor.USER_EXCEPTION; import cn.com.beans.UserInfoBean; import cn.com.daos.UserInfoDaoImp; import cn.com.renrenConfig.AppConfig; import com.renren.api.AuthorizationException; import com.renren.api.RennClient; import com.renren.api.RennException; /** * 用于处理用人人网帐号登录的Servlet, * 当从人人网的OAuth 2.0服务器跳转回来时,会到达这个Servlet,参数中会有code */ @SuppressWarnings("serial") public class RenrenLoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { String code = request.getParameter("code"); if (code == null || code.length() == 0) { //缺乏有效参数,跳转到登录页去 response.sendRedirect("userLogin.jsp"); return; } //到人人网的OAuth 2.0的token endpoint用code换取access token RennClient client = new RennClient(AppConfig.API_KEY, AppConfig.APP_SECRET); try { client.authorizeWithAuthorizationCode(code, "http://hnustqa.duapp.com/rr_login"); com.renren.api.service.User user = client.getUserService().getUserLogin (); String userName = user.getName(); String userPassword = Long.toString(user.getId()); System.out.println("用户姓名:"+userName); System.out.println("用户密码:"+<PASSWORD>Password); request.setAttribute("userName", userName); request.setAttribute("userPassword", <PASSWORD>Password); //判断该账号是否已绑定 UserInfoDaoImp userDaoImp = new UserInfoDaoImp(); UserInfoBean userInfoBean = new UserInfoBean(); //如果已经绑定 if(userDaoImp.validateByUserNameAndUserPassword(userName, userPassword)){ userInfoBean = userDaoImp.getUserInfoByUserName(userName); HttpSession session = request.getSession(); session.setAttribute("userBean", userInfoBean); request.getRequestDispatcher("index").forward(request, response); } else{ request.getRequestDispatcher("UserBind.jsp").forward(request, response); } } catch (AuthorizationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RennException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>package cn.com.mservlets.question; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import redis.clients.jedis.Jedis; import net.sf.json.JSONObject; import cn.com.beans.AnswerAllInfoBean; import cn.com.beans.AnswerBean; import cn.com.beans.DiscussAllInfoBean; import cn.com.beans.DiscussBean; import cn.com.beans.QuestionAllInfoBean; import cn.com.beans.QuestionBean; import cn.com.daos.AnswerDaoImp; import cn.com.daos.DiscussDaoImp; import cn.com.daos.QuestionDaoImp; import cn.com.daos.TagsInfoDaoImp; import cn.com.daos.UserInfoDaoImp; import cn.com.util.RUtil; public class GetDetilQuestion extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //得到传入问题ID QuestionDaoImp questionDaoImp = new QuestionDaoImp(); // System.out.println(request.getParameter("question_id")); int question_id = Integer.parseInt(request.getParameter("question_id")); String userid = request.getParameter("userid"); QuestionBean questionBean = questionDaoImp.getQuestionByQuestionId(question_id); //得到提问者的名字 UserInfoDaoImp userInfoDaoImp = new UserInfoDaoImp(); String userName = userInfoDaoImp.getUserInfoByUserId(questionBean.getQuestion_user_id()).getUser_name(); //得到该问题的标签 String tagsId [] = null; TagsInfoDaoImp tagsInfoDaoImp = new TagsInfoDaoImp(); //System.out.println(questionBean.getQuestion_tags()); if(questionBean.getQuestion_tags()== null || questionBean.getQuestion_tags().indexOf(",")==-1){ //这里默认为无,数据库应该插入0为无标签描述,下面的11应该可以改为0 tagsId = new String[1]; tagsId[0]= "11"; }else{ tagsId = questionBean.getQuestion_tags().split(","); } StringBuffer tagStrBuffer = new StringBuffer(); for(int i=0; i< tagsId.length;i++){ int tagsIdInt = Integer.parseInt(tagsId[i]); String tagsStr = tagsInfoDaoImp.getTagsInfoByTagsId(tagsIdInt).getTags_name()+" "; tagStrBuffer.append(tagsStr); } //设置标签为文字显示 questionBean.setQuestion_tags(tagStrBuffer.toString()); //放入完整的问题描述中 QuestionAllInfoBean questionAllInfoBean = new QuestionAllInfoBean(); questionAllInfoBean.setQuestionUserName(userName); questionAllInfoBean.setBestAnswer("无"); questionAllInfoBean.setCountOfAnswers(23); questionAllInfoBean.setVpOfQuestion(50); questionAllInfoBean.setQuestionBean(questionBean); //得到该问题的所有答案 AnswerDaoImp answerDaoImp = new AnswerDaoImp(); List<AnswerBean> listAnswer = answerDaoImp.findAnswerByQuestionId(question_id); List<AnswerAllInfoBean> listAllAnswer = new ArrayList<AnswerAllInfoBean>(); //评论获取 List<DiscussAllInfoBean> listAllDiscuss = new ArrayList<DiscussAllInfoBean>(); List<DiscussBean> listdiscussBean = new ArrayList<DiscussBean>(); DiscussDaoImp discussDao = new DiscussDaoImp(); DiscussAllInfoBean discussBean = null; //用户Dao UserInfoDaoImp userDao = new UserInfoDaoImp(); AnswerAllInfoBean answerAllBean = null; for(int i=0; i < listAnswer.size();i++){ answerAllBean = new AnswerAllInfoBean(); String answerUserName = userInfoDaoImp.getUserInfoByUserId(listAnswer.get(i).getAnswer_user_id()).getUser_name(); answerAllBean.setAnswerBean(listAnswer.get(i)); answerAllBean.setUserName(answerUserName); listAllAnswer.add(answerAllBean); //得到当前循环问题的评论 listdiscussBean = discussDao.getDiscussByAnswerId(listAnswer.get(i).getAnswer_id()); for(int j = 0 ; j < listdiscussBean.size(); j++){ //评论进行封装 discussBean = new DiscussAllInfoBean(); String userDiscussName = userDao.getUserInfoByUserId(listdiscussBean.get(j).getUser_id()).getUser_name(); discussBean.setUserName(userDiscussName); discussBean.setDiscussBean(listdiscussBean.get(j)); listAllDiscuss.add(discussBean); } } int coutAnswer = listAnswer.size(); //通过request把所需信息发送给详细问题页面 // ***************whether the question belongs to the logined people***************** String belongFlag = "0"; String bestFlag = "0"; if (userid != null) { if (Integer.parseInt(userid) == questionAllInfoBean.getQuestionBean().getQuestion_user_id()){ belongFlag = "1"; } else { belongFlag = "0"; } } else { belongFlag = "0"; } System.out.println("userid:" + userid); System.out.println(questionAllInfoBean.getQuestionBean().getQuestion_user_id()); RUtil redis = new RUtil(); Jedis rdb = redis.con(); String best = "questionid:" + questionAllInfoBean.getQuestionBean().getQuestion_id(); String bestcode = rdb.hget("accept", best); if ( bestcode == null){ bestFlag = "-1"; } else { bestFlag = bestcode; System.out.println("bestcode" + bestcode); } System.out.println("bestcode" + bestFlag); /*封装并发送*/ Map<String,Object> map = new HashMap<String,Object>(); map.put("listAllDiscuss", listAllDiscuss); map.put("coutAnswer", coutAnswer); map.put("question", questionAllInfoBean); map.put("listAnswer", listAllAnswer); map.put("belongFlag",belongFlag); map.put("bestFlag", bestFlag); JSONObject json = JSONObject.fromObject(map); response.getWriter().println(json); System.out.println(json); //request.getRequestDispatcher("question_contents.jsp").forward(request, response); } } <file_sep>package com.example.app.hnust_qa.Bean; /** * @author Xianxiaofei * @date:2014-5-10 ����10:00:48 */ public class AnswerBean { //�𰸱�� private int answer_id; //������ private String answer_description; //�ش�ʱ�� private String answer_time; //�����֣��ޡ��ȣ� private int answer_mark; //�����û���� private int answer_user_id; //���������� private int question_id; //�Ƿ�Ϊ��Ѵ� private int answer_best; private String userName; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } //��Ӧ��Get��Set���� public int getAnswer_id() { return answer_id; } public void setAnswer_id(int answer_id) { this.answer_id = answer_id; } public String getAnswer_description() { return answer_description; } public void setAnswer_description(String answer_description) { this.answer_description = answer_description; } public String getAnswer_time() { return answer_time; } public void setAnswer_time(String answer_time) { this.answer_time = answer_time; } public int getAnswer_mark() { return answer_mark; } public void setAnswer_mark(int answer_mark) { this.answer_mark = answer_mark; } public int getAnswer_user_id() { return answer_user_id; } public void setAnswer_user_id(int answer_user_id) { this.answer_user_id = answer_user_id; } public int getQuestion_id() { return question_id; } public void setQuestion_id(int question_id) { this.question_id = question_id; } public int getAnswer_best() { return answer_best; } public void setAnswer_best(int answer_best) { this.answer_best = answer_best; } } <file_sep>package cn.com.daos; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import cn.com.beans.AnswersKeywordsBean; import cn.com.beans.QuestionsKeywordsBean; import cn.com.interfaces.AnswersKeywordsInf; import cn.com.util.DBUtil; /** * @author Xianxiaofei * @date:2014年7月30日 下午5:58:09 */ public class AnswersKeywordsDaoImp implements AnswersKeywordsInf { private DBUtil db; public AnswersKeywordsDaoImp() { db = new DBUtil(); } public AnswersKeywordsBean getDiscussByAnswersKeywordsId( int answers_keywords_id) { return null; } public List<AnswersKeywordsBean> AnswersKeywords(String keywords) { // 根据标问题题目得到问题信息 Connection conn = db.getConn(); PreparedStatement pst = null; ResultSet rs = null; List<AnswersKeywordsBean> list = null; AnswersKeywordsBean qb = null; String sql = "select * from questions_keywords where quesitons_keywords_topN like ?"; try { pst = conn.prepareStatement(sql); pst.setString(1, "%" + keywords + "%"); rs = pst.executeQuery(); if (rs != null) { list = new ArrayList<AnswersKeywordsBean>(); while (rs.next()) { qb = new AnswersKeywordsBean(); qb.setAnswers_keywords_id(rs.getInt("questions_keywords_id")); qb.setAnswers_id(rs.getInt("questions_id")); qb.setAnswers_keywords_topN(rs.getString("quesitons_keywords_topN")); qb.setAnswers_keywords_counts(rs.getString("questions_keywords_counts")); list.add(qb); } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { db.free(rs, pst, conn); } return list; } public boolean addAnswersKeywordsBean( AnswersKeywordsBean answersKeywordsBean) { // TODO Auto-generated method stub boolean bool = false; Connection connection = db.getConn(); PreparedStatement pstm = null; try { String sql = "Insert into answers_keywords (answers_id,answers_keywords_topN,answers_keywords_counts) values(?,?,?)"; pstm = connection.prepareStatement(sql); pstm.setInt(1, answersKeywordsBean.getAnswers_id()); pstm.setString(2, answersKeywordsBean.getAnswers_keywords_topN()); pstm.setString(3, answersKeywordsBean.getAnswers_keywords_counts()); int len = pstm.executeUpdate(); if (len > 0) { bool = true; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { db.free(pstm, connection); } return bool; } public boolean deleteAnswersKeywordsBean(int answers_keywords_id) { return false; } } <file_sep>package cn.com.daos; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import cn.com.beans.BasicUserInfoBean; import cn.com.beans.QuestionAllInfoBean; import cn.com.beans.QuestionBean; import cn.com.beans.UserInfoBean; import cn.com.interfaces.UserInfoDaoInf; import cn.com.util.DBUtil; /** * @author Xianxiaofei * @date:2014-5-10 锟斤拷锟斤拷10:16:17 */ /** * @author Friday * @date 2014-5-18 锟斤拷锟斤拷4:12:33 */ public class UserInfoDaoImp implements UserInfoDaoInf { private DBUtil db; public UserInfoDaoImp() { db = new DBUtil(); } // 通锟斤拷锟矫伙拷锟斤拷锟斤拷证锟矫伙拷锟角凤拷锟斤拷锟� public boolean validataByUserName(String user_name) { Boolean bool = false; Connection conn = db.getConn(); PreparedStatement pst = null; ResultSet rs = null; String sql = "select *from user_info where user_name=?"; try { pst = conn.prepareStatement(sql); pst.setString(1, user_name); rs = pst.executeQuery(); bool = rs.next(); } catch (SQLException e) { e.printStackTrace(); } finally { db.free(rs, pst, conn); } return bool; } // 锟斤拷录锟斤拷证 public boolean validateByUserNameAndUserPassword(String user_name, String user_password) { Boolean bool = false; Connection conn = db.getConn(); PreparedStatement pst = null; ResultSet rs = null; String sql = "select *from user_info where user_name=? and user_password=?"; try { pst = conn.prepareStatement(sql); pst.setString(1, user_name); pst.setString(2, user_password); rs = pst.executeQuery(); bool = rs.next(); } catch (SQLException e) { e.printStackTrace(); } finally { db.free(rs, pst, conn); } return bool; } // 锟斤拷锟斤拷锟揭伙拷 public boolean validateByUserNameAndUserEmail(String user_name, String user_email) { Boolean bool = false; Connection conn = db.getConn(); PreparedStatement pst = null; ResultSet rs = null; String sql = "select *from user_info where user_name=? and user_email=?"; try { pst = conn.prepareStatement(sql); pst.setString(1, user_name); pst.setString(2, user_email); rs = pst.executeQuery(); bool = rs.next(); } catch (SQLException e) { e.printStackTrace(); } finally { db.free(rs, pst, conn); } return bool; } // 锟斤拷锟斤拷没锟斤拷锟矫碉拷锟矫伙拷锟斤拷息 public UserInfoBean getUserInfoByUserName(String user_name) { Connection conn = db.getConn(); PreparedStatement pst = null; ResultSet rs = null; UserInfoBean userBean = new UserInfoBean(); String sql = "select *from user_info where user_name=?"; try { pst = conn.prepareStatement(sql); pst.setString(1, user_name); rs = pst.executeQuery(); while (rs.next()) { userBean.setUser_id(rs.getInt("user_id")); userBean.setUser_name(rs.getString("user_name")); userBean.setUser_password(rs.getString("user_password")); userBean.setUser_email(rs.getString("user_email")); userBean.setUser_mark(rs.getInt("user_mark")); userBean.setUser_tags(rs.getString("user_tags")); userBean.setUser_logo(rs.getString("user_logo")); } } catch (SQLException e) { e.printStackTrace(); } finally { db.free(rs, pst, conn); } return userBean; } // 锟斤拷锟絠d锟矫碉拷锟矫伙拷锟斤拷息 public UserInfoBean getUserInfoByUserId(int user_id) { Connection conn = db.getConn(); PreparedStatement pst = null; ResultSet rs = null; UserInfoBean userBean = new UserInfoBean(); String sql = "select *from user_info where user_id=?"; try { pst = conn.prepareStatement(sql); pst.setInt(1, user_id); rs = pst.executeQuery(); while (rs.next()) { userBean.setUser_id(rs.getInt("user_id")); userBean.setUser_name(rs.getString("user_name")); userBean.setUser_password(<PASSWORD>("<PASSWORD>")); userBean.setUser_email(rs.getString("user_email")); userBean.setUser_mark(rs.getInt("user_mark")); userBean.setUser_tags(rs.getString("user_tags")); userBean.setUser_logo(rs.getString("user_logo")); } } catch (SQLException e) { e.printStackTrace(); } finally { db.free(rs, pst, conn); } return userBean; } // 删锟斤拷锟矫伙拷锟斤拷息 public boolean deleteUserInfoByUserId(int user_id) { boolean bool = false; Connection conn = db.getConn(); PreparedStatement pst = null; try { String sql = "delete from user_info where user_id = ?"; pst = conn.prepareStatement(sql); pst.setInt(1, user_id); int len = pst.executeUpdate(); if (len > 0) { bool = true; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { db.free(pst, conn); } return bool; } // 锟斤拷锟斤拷锟斤拷锟侥o拷锟斤拷询锟矫碉拷锟矫伙拷锟斤拷息锟叫憋拷 public List<UserInfoBean> getUserInfoAllInfoByUserName(String user_name) { Connection conn = db.getConn(); PreparedStatement pst = null; ResultSet rs = null; List<UserInfoBean> list = null; UserInfoBean userBean = null; String sql = "select * from user_info where user_name like ?"; try { pst = conn.prepareStatement(sql); pst.setString(1, "%" + user_name + "%"); rs = pst.executeQuery(); if (rs != null) { list = new ArrayList<UserInfoBean>(); while (rs.next()) { userBean = new UserInfoBean(); userBean.setUser_id(rs.getInt("user_id")); userBean.setUser_name(rs.getString("user_name")); userBean.setUser_password(rs.getString("<PASSWORD>")); userBean.setUser_email(rs.getString("user_email")); userBean.setUser_mark(rs.getInt("user_mark")); userBean.setUser_tags(rs.getString("user_tags")); userBean.setUser_logo(rs.getString("user_logo")); list.add(userBean); } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { db.free(rs, pst, conn); } return list; } // 锟睫革拷锟矫伙拷锟斤拷息 public boolean updateUserInfoByUserId(UserInfoBean uib) { boolean bool = false; Connection conn = db.getConn(); PreparedStatement pst = null; try { String sql = "update user_info set user_name=?,user_password=?,user_email=?,user_mark=?,user_tags=?,user_logo=? where user_id=?"; pst = conn.prepareStatement(sql); pst.setString(1, uib.getUser_name()); pst.setString(2, uib.getUser_password()); pst.setString(3, uib.getUser_email()); pst.setInt(4, uib.getUser_mark()); pst.setString(5, uib.getUser_tags()); pst.setString(6, uib.getUser_logo()); pst.setInt(7, uib.getUser_id()); int len = pst.executeUpdate(); if (len > 0) { bool = true; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { db.free(pst, conn); } return bool; } // 锟矫碉拷锟斤拷锟斤拷锟矫伙拷锟斤拷息 public List<UserInfoBean> getAllUserInfo() { List<UserInfoBean> list = null; UserInfoBean userBean = null; Connection conn = db.getConn(); Statement st = null; ResultSet rs = null; String sql = "select * from user_info"; try { st = conn.createStatement(); rs = st.executeQuery(sql); if (rs != null) { list = new ArrayList<UserInfoBean>(); while (rs.next()) { userBean = new UserInfoBean(); userBean.setUser_id(rs.getInt("user_id")); userBean.setUser_name(rs.getString("user_name")); userBean.setUser_password(rs.getString("<PASSWORD>_password")); userBean.setUser_email(rs.getString("user_email")); userBean.setUser_mark(rs.getInt("user_mark")); userBean.setUser_tags(rs.getString("user_tags")); userBean.setUser_logo(rs.getString("user_logo")); list.add(userBean); } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { db.free(rs, st, conn); } return list; } // 锟斤拷锟斤拷锟矫戯拷锟斤拷息,注锟结功锟斤拷 public boolean addUserInfo(UserInfoBean uib) { boolean bool = false; Connection conn = db.getConn(); PreparedStatement pst = null; try { String sql = "Insert into user_info (user_name,user_password,user_email,user_mark,user_tags,user_logo) values(?,?,?,?,?,?)"; pst = conn.prepareStatement(sql); pst.setString(1, uib.getUser_name()); pst.setString(2, uib.getUser_password()); pst.setString(3, uib.getUser_email()); pst.setInt(4, uib.getUser_mark()); pst.setString(5, uib.getUser_tags()); pst.setString(6, uib.getUser_logo()); int len = pst.executeUpdate(); if (len > 0) { bool = true; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { db.free(pst, conn); } return bool; } // 统锟斤拷锟矫伙拷锟斤拷锟斤拷 public int getCountOfUser() { int count = 0; Connection conn = db.getConn(); Statement st = null; ResultSet rs = null; String sql = "select * from user_info"; try { st = conn.createStatement(); rs = st.executeQuery(sql); if (rs != null) { while (rs.next()) { count = count + 1; } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { db.free(rs, st, conn); } return count; } // 锟斤拷锟斤拷锟斤拷诺锟斤拷没锟� public List<UserInfoBean> getHotUserInfos() { List<UserInfoBean> list = null; UserInfoBean userBean = null; Connection conn = db.getConn(); Statement st = null; ResultSet rs = null; String sql = "select * from user_info order by user_mark desc"; try { st = conn.createStatement(); rs = st.executeQuery(sql); if (rs != null) { list = new ArrayList<UserInfoBean>(); while (rs.next()) { userBean = new UserInfoBean(); userBean.setUser_id(rs.getInt("user_id")); userBean.setUser_name(rs.getString("user_name")); userBean.setUser_password(rs.getString("user_password")); userBean.setUser_email(rs.getString("user_email")); userBean.setUser_mark(rs.getInt("user_mark")); userBean.setUser_tags(rs.getString("user_tags")); userBean.setUser_logo(rs.getString("user_logo")); list.add(userBean); } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { db.free(rs, st, conn); } return list; } // 锟叫讹拷锟街凤拷锟角凤拷锟斤拷锟斤拷母锟斤拷锟斤拷锟街癸拷锟斤拷 public boolean isIleagle(String str) { boolean bool = false; bool = str.matches("^[\\da-zA-Z]*$"); // 没锟斤拷锟斤拷锟街凤拷锟津返伙拷true return bool; } // get basic infomation of user public BasicUserInfoBean getBasicUserInfoByUserId(int user_id) { int count = 0; BasicUserInfoBean basicInfo = new BasicUserInfoBean(); Connection conn = db.getConn(); PreparedStatement pst = null; ResultSet rs = null; String sql = "select *from question where question_user_id=?"; try { pst = conn.prepareStatement(sql); pst.setInt(1, user_id); rs = pst.executeQuery(); if (rs != null) { while (rs.next()) { count = count + 1; } } basicInfo.set_questions(count); } catch (SQLException e) { e.printStackTrace(); } finally { db.free(rs, pst, conn); } return basicInfo; } // get UserTags By UserID public List<String> getUserTagsByUserId(int userId) { List<String> listTags = new ArrayList<String>(); // 正则表达式匹配 Pattern pattern = Pattern.compile("[0-9]*"); QuestionDaoImp questionDao = new QuestionDaoImp(); TagsInfoDaoImp tagsInfoDaoImp = new TagsInfoDaoImp(); List<QuestionBean> list = questionDao .getQuestionByUserId(userId, 0, 20); // 处理得到的所有问题信息 for (int i = 0; i < list.size(); i++) { QuestionBean questionBean = new QuestionBean(); questionBean = list.get(i); // 得到该问题的标签 String tagsId[] = null; // System.out.println(questionBean.getQuestion_tags()); if (questionBean.getQuestion_tags() == null || questionBean.getQuestion_tags().equals("")) { // 这里默认为无,数据库应该插入0为无标签描述,下面的11应该可以改为0 questionBean.setQuestion_tags("暂无"); } else { if (questionBean.getQuestion_tags() != null && questionBean.getQuestion_tags().indexOf(",") == -1 && pattern.matcher(questionBean.getQuestion_tags()) .matches()) { String tagsStr = tagsInfoDaoImp.getTagsInfoByTagsId( Integer.parseInt(questionBean.getQuestion_tags())) .getTags_name(); listTags.add(tagsStr); } else { if (questionBean.getQuestion_tags().indexOf(",") != -1) { tagsId = questionBean.getQuestion_tags().split(","); StringBuffer tagStrBuffer = new StringBuffer(); for (int i1 = 0; i1 < tagsId.length; i1++) { int tagsIdInt = Integer.parseInt(tagsId[i1]); String tagsStr = tagsInfoDaoImp .getTagsInfoByTagsId(tagsIdInt) .getTags_name() + " "; listTags.add(tagsStr); } } } } } return listTags; } } <file_sep>package cn.com.util; /** * @author Xianxiaofei * @date:2014年7月30日 下午3:28:03 */ import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import org.wltea.analyzer.core.IKSegmenter; import org.wltea.analyzer.core.Lexeme; import cn.com.beans.AnswerBean; import cn.com.beans.AnswersKeywordsBean; import cn.com.beans.QuestionBean; import cn.com.beans.QuestionsKeywordsBean; import cn.com.daos.AnswerDaoImp; import cn.com.daos.AnswersKeywordsDaoImp; import cn.com.daos.QuestionDaoImp; import cn.com.daos.QuestionsKeywordsDaoImp; public class ChineseAnalyzerUtil { /** * getTextDef对传入的参数进行分词,并统计好每个次的频率 * 代码很简单,主要介绍下IK中的类,IKSegmenter是分词的主要类,其参数分别是分词的句子或者文章,后面的参数是是否开启智能模式, * 不开启就按最小词义分。 分词的结果是Lexeme这个类,用其中的getLexemeText()方法就能取出相关的分词结果。 * */ public Map<String, Integer> getTextDef(String text) throws IOException { Map<String, Integer> wordsFren = new HashMap<String, Integer>(); //true使用智能分词策略 IKSegmenter ikSegmenter = new IKSegmenter(new StringReader(text), true); //词元对象 Lexeme lexeme; //next分词,获取下一个词元 while ((lexeme = ikSegmenter.next()) != null) { if (lexeme.getLexemeText().length() > 1) { //Map containsKey(String Key)判断key有没有对应的value值;有,则返回true if (wordsFren.containsKey(lexeme.getLexemeText())) { wordsFren.put(lexeme.getLexemeText(), //存在把当前分词的次数加1 wordsFren.get(lexeme.getLexemeText()) + 1); } else { //不存在就添加 wordsFren.put(lexeme.getLexemeText(), 1); } } } return wordsFren; } /** * 接下来是计算词频,将分词结果和出现次数放到一个map结构中,map的value对应了词的出现次数。这里注意一下, * 我只记录两个字及两个字以上的分词结果。 * * @param wordsFrenMaps * @param topWordsCount */ public List<Map.Entry<String, Integer>> getAnalyzerKeywordsString(Map<String, Integer> wordsFrenMaps) { List<Map.Entry<String, Integer>> oldWordFrenList = new ArrayList<Map.Entry<String, Integer>>( wordsFrenMaps.entrySet()); //这个方法主要对分词结果及词频按照出现次数排序,没有自己去写实现,主要借用了collections的sort方法。 Collections.sort(oldWordFrenList, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> obj1, Map.Entry<String, Integer> obj2) { return obj2.getValue() - obj1.getValue(); } }); return oldWordFrenList; } //对已有问题进行分词处理 public static void main(String args[]) throws IOException { ChineseAnalyzerUtil chineseAnalyzerUtil = new ChineseAnalyzerUtil(); List<QuestionBean> listQuestionBeans = new ArrayList<QuestionBean>(); List<AnswerBean> listAnswerBeans = new ArrayList<AnswerBean>(); QuestionDaoImp questionDaoImp = new QuestionDaoImp(); AnswerDaoImp answerDaoImp = new AnswerDaoImp(); //这里所传参数只在Dao方法中的无参数的语句使用 listQuestionBeans = questionDaoImp.getAllQuestions(0, 0); listAnswerBeans = answerDaoImp.getAnswerByUserId(0); QuestionsKeywordsDaoImp questionsKeywordsDaoImp = new QuestionsKeywordsDaoImp(); AnswersKeywordsDaoImp answersKeywordsDaoImp = new AnswersKeywordsDaoImp(); for(int i=0; i<listQuestionBeans.size();i++){ int questionId = listQuestionBeans.get(i).getQuestion_id(); StringBuffer questionContext = new StringBuffer(listQuestionBeans.get(i).getQuestion_title()+listQuestionBeans.get(i).getQuestion_description()); StringBuffer questionContext2 = new StringBuffer(); StringBuffer countTopN = new StringBuffer(); List<Map.Entry<String, Integer>> map = chineseAnalyzerUtil.getAnalyzerKeywordsString(chineseAnalyzerUtil.getTextDef(questionContext.toString())); QuestionsKeywordsBean questionKeywords = new QuestionsKeywordsBean(); questionKeywords.setQuestion_id(questionId); //取分词频率最高的前20 for (int i1 = 0; i1 < 20 && i1 < map.size(); i1++) { Map.Entry<String, Integer> wordFrenEntry = map.get(i1); questionContext2.append(wordFrenEntry.getKey()+","); countTopN.append(wordFrenEntry.getValue()+","); } questionKeywords.setQuesitons_keywords_topN(questionContext2.toString()); questionKeywords.setQuestions_keywords_counts(countTopN.toString()); if(questionsKeywordsDaoImp.addQuestionsKeywordsBean(questionKeywords)){ System.out.println("第"+(i+1)+"个问题"+"success!"); } } for(int j=0; j<listAnswerBeans.size();j++){ int answers_id = listAnswerBeans.get(j).getAnswer_id(); StringBuffer answerContext = new StringBuffer(listAnswerBeans.get(j).getAnswer_description()); StringBuffer answerContext2 = new StringBuffer(); StringBuffer countTopN = new StringBuffer(); List<Map.Entry<String, Integer>> map = chineseAnalyzerUtil.getAnalyzerKeywordsString(chineseAnalyzerUtil.getTextDef(answerContext.toString())); AnswersKeywordsBean answersKeywordsBean = new AnswersKeywordsBean(); answersKeywordsBean.setAnswers_id(answers_id); //取分词频率最高的前20 for (int i1 = 0; i1 < 20 && i1 < map.size(); i1++) { Map.Entry<String, Integer> wordFrenEntry = map.get(i1); answerContext2.append(wordFrenEntry.getKey()+","); countTopN.append(wordFrenEntry.getValue()+","); } answersKeywordsBean.setAnswers_keywords_topN(answerContext2.toString()); answersKeywordsBean.setAnswers_keywords_counts(countTopN.toString()); if(answersKeywordsDaoImp.addAnswersKeywordsBean(answersKeywordsBean)){ System.out.println("第"+(j+1)+"个回答"+"success!"); } } } public List<String> getSearchKeyWords(String text) throws IOException { List<String> listKeyWords = new ArrayList<String>(); //true使用智能分词策略 IKSegmenter ikSegmenter = new IKSegmenter(new StringReader(text), true); //词元对象 Lexeme lexeme; //next分词,获取下一个词元 while ((lexeme = ikSegmenter.next()) != null) { if (lexeme.getLexemeText().length() > 1) { //查找是否已经存在该分词 boolean bool = false; for(int i=0; i<listKeyWords.size();i++){ if(listKeyWords.get(i).equals(lexeme.getLexemeText())){ bool = true; break; } } if (!bool) { listKeyWords.add(lexeme.getLexemeText()); } } } return listKeyWords; } } <file_sep>package cn.com.beans; public class QuestionCategoriesBean { private int question_categories_id; private String question_categories_name; private String question_categories_description; private int last_categories_id; public int getQuestion_categories_id() { return question_categories_id; } public void setQuestion_categories_id(int question_categories_id) { this.question_categories_id = question_categories_id; } public String getQuestion_categories_name() { return question_categories_name; } public void setQuestion_categories_name(String question_categories_name) { this.question_categories_name = question_categories_name; } public String getQuestion_categories_description() { return question_categories_description; } public void setQuestion_categories_description( String question_categories_description) { this.question_categories_description = question_categories_description; } public int getLast_categories_id() { return last_categories_id; } public void setLast_categories_id(int last_categories_id) { this.last_categories_id = last_categories_id; } }
e557e70ae73aa8ce3cda90c982e6936e75498eff
[ "JavaScript", "Java", "Markdown", "SQL" ]
35
Java
xianxiaofei007/demos
4d9c1f49f2db229d58b170dd3c3476be9213444d
19edb0ba00a60136454b7f3771f50e69bba9b20a
refs/heads/master
<file_sep># A Simple Dynamic Site with Node. Project code to support the Treehouse course ```Build a Simple Dynamic Site with Node``` This app searches and retrieves Treehouse members' profiles. ## Setup - clone the repo and cd to the project folder. - Ensure you have node installed. - Start the app: ```$ node app.js``` - Access the app at: ```localhost:3000```<file_sep>//problem: We need a simple way to look at a user's badge count and JS points from a web browser. //Solution: Use Node.js to perfowm the profile search and serve our templates via HTTP. // create a web server. const router = require('./router.js'); const http = require('http'); //define the port const port = 3000; const server = http.createServer((request, response) => { //Register the routes router.home(request, response); router.user(request, response); }); server.listen(port); console.log('Server listening at http://workspace url/');
6dc40e8f40fb4983745b5b3e39c5476faa459a4f
[ "Markdown", "JavaScript" ]
2
Markdown
victoriaaoka/treehouse-profile-finder
9b457ac53c75a4115cec4fc02f2dd5c1dccd2191
799db11175a4bef7871d2cbea0f694aadd22fa7f
refs/heads/master
<file_sep>import React from 'react'; import { Flex,Toast } from 'antd-mobile'; import styles from './AwardHead.css'; import userImg from '../../assets/img/timg.jpg' class AwardHead extends React.Component { constructor() { super() } render(){ let balance = this.props.balance; let balanceShow; if(balance){ Toast.hide(); balanceShow = <div> <Flex> <img src = {userImg} className = {styles['user-img']}/> <span className = {styles['user-name-span']}>这是名字</span> </Flex> <br/> <Flex justify = "center" className = {styles['reward-decribe']}>"已在万人车汇APP累计获得佣金"</Flex><br/> <Flex justify = "center" className = {styles['reward-money']}>¥{balance.amount}</Flex> <Flex justify = "center" className = {styles['reward-ratio']}>厉害了,你已超过100%的客户</Flex> </div> }else{ balanceShow = Toast.loading('加载中',0) } return( <div className = {styles['Head-frame']}> {balanceShow} </div> ) } } export default AwardHead; <file_sep>import history from '../history'; import { MClient } from '../config/asteroid.config.js'; import { product } from '../reducers/product.redux'; export const EXCEPT_RECOMMAND_PRODUCTS = 'EXCEPT_RECOMMAND_PRODUCTS'; export const RECEIVE_RECOMMAND_PRODUCTS = 'RECEIVE_RECOMMAND_PRODUCTS'; export const RECEIVE_PRODUCT_BYID = 'RECEIVE_PRODUCT_BYID'; export const ADD_COUNT = "ADD_COUNT"; export const RECEIVE_SHOP_PRODUCTS_BYSHOPID = "RECEIVE_SHOP_PRODUCTS_BYSHOPID"; export const GET_RECOMMAND_PRODUCTS= "GET_RECOMMAND_PRODUCTS" // export const RECOMMAND_PRODUCTS_LIST = "RECOMMAND_PRODUCTS_LIST" function exceptRecommandProduct(){ return { type: EXCEPT_RECOMMAND_PRODUCTS, text: '加载中', } } function receiveRecommandProduct(products){ return { type: RECEIVE_RECOMMAND_PRODUCTS, products, } } export function loadRecommandProducts(page, pagesize){ return dispatch => { dispatch(exceptRecommandProduct()); const subId = MClient.sub("home.top.products", [page, pagesize]); let products = []; MClient.on("ready", message => { if (message.subs.includes(subId)) { console.log("mySubscription ready"); } }); MClient.on("added", message => { console.log(message.collection); }); MClient.on("added", message => { if (message.collection === 'products') { console.log('首页加载的东西',message); if (products.length < pagesize) { products.push({fields: message.fields, id: message.id}); console.log(message); console.log(products) dispatch(receiveRecommandProduct(products)); } } }); } } function exceptProductById(id){ } function getRecommandProducts(products){ return { type: GET_RECOMMAND_PRODUCTS, products } } function receiveProductById(product){ return { type: RECEIVE_PRODUCT_BYID, product, } } function receiveProductByIdError(error){ } function receiveShopProductsByShopId(products) { return { type: RECEIVE_SHOP_PRODUCTS_BYSHOPID, products } } export function addCount(count) { return { type: ADD_COUNT, count: count } } export function loadProductById(id){ return dispatch => { // dispatch(exceptProductById(id)); MClient.sub("get.product.id", [id]); let product = []; MClient.connect(); let methodId = MClient.method("get.oneproduct.id", [id]); MClient.on("result", message => { if(message.id === methodId && !message.error){ console.log(`gogogo`) console.log(message.result) dispatch(receiveProductById(message.result)); }else{ // dispatch(receiveProductByIdError(message.error)); } }) } } export function loadProductList(){ } export function createOrder(product) { return dispatch => { let methodId = MClient.method('app.orders.insert',[product]); MClient.on('result', message => { if(message.id === methodId && !message.error){ console.log(`订单提交成功`) if(message.result){ history.push(`/firmorder/${message.result}`) }else{ console.log(message.error); } } }) } } export function loadShopProductsByShopId(shopId,page,pagesize) { return dispatch => { console.log(`加载店铺商品`) console.log(shopId) MClient.sub('app.get.shop.products',[shopId,page,pagesize]); MClient.connect(); let products = []; MClient.on("added", ({collection, id, fields}) => { if(collection==='products'){ if(products.length< pagesize){ products.push({fields,id}) } console.log(`~~~~`) console.log(products) dispatch(receiveShopProductsByShopId(products)); } }); } } export function gainRecommandProducts(page,pagesize,data=[]) { return dispatch => { console.log(`获取推荐商品`) MClient.sub('app.get.recommend.products', [page,pagesize]); MClient.connect(); let products = []; // data = data.slice(); console.log(data); console.log(page); MClient.on("added", message => { console.log(message.fields) if(message.collection==='products'){ if(products.length< pagesize){ message.fields.id = message.id products.push(message.fields) } console.log(data.concat(products)) dispatch(getRecommandProducts(data.concat(products))) } }) } } <file_sep>import React from 'react'; import { Flex } from 'antd-mobile'; import shopImg from '../../assets/img/timg.jpg'; import goodImg from '../../assets/img/reward/good.jpg'; import OrderBtn from './OrderBtn'; class OrderList extends React.Component { constructor(props) { super(props) } // let {name, price, spec,num} = this.props render(){ // let {name, price, spec,num} = this.props let { dataSource } = this.props; // console.log(this.props); console.log(dataSource) // console.log(shop) return ( <div style = {{backgroundColor:'#fff',marginTop:'50px',padding:'10px 10px'}}> {dataSource.map((v,index)=>{ return( <div key={index}> <Flex justify = "start"> <img src = {shopImg} style = {{width:'38px',height:'38px',borderRadius:'19px',marginRight:'10px'}}/> <span style = {{color:'#333',fontSize:'16px',fontWeight:'600'}}>店铺名字</span> </Flex> <Flex justify = "start" style = {{backgroundColor:'#eee',padding:'10px',marginTop:'10px'}}> <Flex style = {{width:'70px'}}> <img src = {goodImg} style = {{width:'60px',height:'60px'}}/> </Flex> <Flex direction = "column" justify = "start" align = "start" style = {{width:'100%'}}> <span style = {{color:'#333',fontSize:'16px',fontWeight:'600',width:'100%',paddingLeft:'10px'}}>{v.name}</span><br/> <div style = {{display:'flex',justifyContent:'space-around',paddingLeft:'10px',color:'#666'}}> <div>类型:{v.spec}</div> <div style = {{paddingLeft:'3rem',paddingRight:'15px'}}>¥{v.price}元</div> <div>×{ v.count }</div> </div> </Flex> </Flex> <OrderBtn status={2} history={this.props.history} orderId={v._id}/> </div> ) })} </div> ) } } export default OrderList; <file_sep>import React from 'react'; import { Flex, Button, Checkbox } from 'antd-mobile'; import goodsImg from '../../assets/img/reward/good.jpg'; import ShopCartList from './ShopCartList'; import style from './common.css'; // import ShopCartList from './test'; import { getCart } from '../../reducers/cart.redux'; import { connect } from 'react-redux'; import { cartInfo } from '../../map_props'; import DeleteBtn from './DeleteBtn'; import BalanceBtn from './BalanceBtn'; const CheckboxItem = Checkbox.CheckboxItem; class ShopCart extends React.Component{ constructor() { super() this.state = { edit: false, } } componentDidMount() { // this.props.getCart(2); } render(){ var text = this.state.edit ? '完成' : '编辑' var btn = this.state.edit ? <DeleteBtn history={this.props.history}/>:<BalanceBtn history={this.props.history}/> return( <div className = {style['bg-color']} > <Flex justify = "end" style = {{backgroundColor:"#333",color:'#fff',lineHeight:'3em',padding:'5px 10px'}}> <span style = {{textAlign:'right'}}> <span onClick={(e) => { e.preventDefault(); this.setState({ edit:!this.state.edit, }); }}>{text}</span></span> </Flex> <div className = {style['item-frame']}> <ShopCartList/> </div> <div> {btn} </div> </div> ) } } export default connect(cartInfo,{getCart})(ShopCart); <file_sep>import React from 'react'; import { Flex } from 'antd-mobile'; import picture from '../../assets/img/orders/qrcode.jpg'; class QrCode extends React.Component { constructor() { super(); } render(){ return ( <Flex justify = "center" style = {{marginTop:'180px'}}><img src = {picture} style = {{width:'260px',height:'200px'}}/></Flex> ) } } export default QrCode; <file_sep>import { EXPECT_LOGOUT, LOGOUT_SUCCESS, EXPECT_LOGIN_SMS_CODE, GET_LOGIN_SMS_CODE_SUCCESS, GET_LOGIN_SMS_CODE_FAIL } from "../actions/users"; export default function AppUser(state={ id: '', username: "", status: 'offline', loginSMSCode: '', validSMSCode: "", roleName: 'nobody', orders: [], balance: { incomes: [], charges: [], }, products: [], }, action){ switch (action.type) { case EXPECT_LOGOUT: return Object.assign({}, state, { status: 'logouting' }); case LOGOUT_SUCCESS: return Object.assign({}, state, { status: 'offline' }); case EXPECT_LOGIN_SMS_CODE: return Object.assign({}, state, { loginSMSCode: "loading", }); case GET_LOGIN_SMS_CODE_SUCCESS: return Object.assign({}, state, { loginSMSCode: action.code, }) case GET_LOGIN_SMS_CODE_FAIL: return Object.assign({}, state, { loginSMSCode: "error", }) default: return state; } }<file_sep>import React from 'react'; import { Tabs } from 'antd-mobile'; import style from './ProductTabs.css'; class ProductTabs extends React.Component { constructor() { super() } render(){ const tabs = [ {title:'详情'}, {title:'参数'}, ]; return( <div className = {style['tab-height']}> <Tabs tabs = {tabs} initialPage = {2} animated = {false} useOnPan = {false}> <div className = {style['tab-first']}> Content of first tab<br/> 这是详情页面<br/> 这是随便填充的内容 </div> <div className = {style['tab-second']}> <span>品牌:Shell/壳牌</span><br/> <span>型号:喜力HX7</span><br/> <span>型号:喜力HX7</span><br/> <span>适合发动机种类:柴油发动机、汽油发动机</span><br/> <span>净含量:4L</span><br/> <span>机油分类:半合成机油</span><br/> <span>粘度级别:5W-40</span><br/> <span>机油级别:SN/CF</span> </div> </Tabs> </div> ) } } export default ProductTabs; <file_sep>import { List, InputItem,Picker, Button, DatePicker } from 'antd-mobile'; import { createForm } from 'rc-form'; import React from 'react'; // import { district, provinceLite } from 'antd-mobile-demo-data'; const gender = [ { label:'未知', value:'未知', },{ label:'保密', value:'保密', },{ label:'男', value:'男', },{ label:'女', value:'女', }, ] class Personal extends React.Component { constructor() { super(); this.state = { date: '', } } render() { const { getFieldProps } = this.props.form; return( <List renderHeader={() => '个人信息'}> <InputItem clear >姓名</InputItem> <InputItem clear >签名</InputItem> <InputItem {...getFieldProps('phone')} type="phone" placeholder="186 1234 1234" >手机号码</InputItem> <Picker data={gender} cols={1} {...getFieldProps('gender')} className="forss"> <List.Item arrow="horizontal">性别</List.Item> </Picker> <Picker extra="请选择" data='' title="地区" {...getFieldProps('district', { })} onOk={e => console.log('ok', e)} onDismiss={e => console.log('dismiss', e)} > <List.Item arrow="horizontal">地区</List.Item> </Picker> <DatePicker style = {{width:'100%'}} mode="date" title="请选择你的出生日期" value={this.state.date} onChange={date => this.setState({ date })} > <List.Item arrow="horizontal">生日</List.Item> </DatePicker> <List.Item align="bottom" className="my-btn"> <Button type="primary" size="small" inline onClick={this.onSubmit} >保存</Button> </List.Item> </List> ) } } const PersonalWrapper = createForm()(Personal) export default PersonalWrapper;<file_sep>import React from 'react'; import { connect } from 'react-redux'; import { Flex, Accordion, InputItem, Button, TextareaItem, ImagePicker, WingBlank, SegmentedControl,DatePicker, List, PickerView, Picker } from 'antd-mobile'; import { createForm } from 'rc-form'; import arrayTreeFilter from 'array-tree-filter'; import { MClient } from '../../config/asteroid.config.js' // import { getCurrentUser,handleNickname } from '../../actions/users.js' const nowTimeStamp = Date.now(); const now = new Date(nowTimeStamp); const gender = [ { label:'未知', value:'未知', },{ label:'保密', value:'保密', },{ label:'男', value:'男', },{ label:'女', value:'女', }, ] class UserData extends React.Component { constructor() { super(); this.state = { // files: data, date:now, value: null, sValue: ['未知'], nickName:'' } } hanldNicknameValue(value){ console.log(value) this.setState({ nickName:value }) } changeNickname(){ const { dispatch } = this.props; let user = this.props.current_user let nickName = this.state.nickName console.log(this.state.nickName) console.log(this.props.current_user) // dispatch(handleNickname(user,nickName)) } componentDidMount(){ const { dispatch } = this.props; console.log('组件渲染完成'); console.log(MClient) console.log(MClient.userId) // dispatch(getCurrentUser("rcZ5wnrzYvgDmaYgm")); this.setState({ nickName:this.props.current_user.nickname }) } render(){ const { dispatch } = this.props; const {getFieldProps} = this.props.form; return( <div> <Accordion> <Accordion.Panel header = "花名" > <Flex justify = "center"> <InputItem defaultValue={this.props.current_user.nickname} onChange={(v)=>(this.hanldNicknameValue(v))}placeholder = "设置花名" style = {{borderBottom:'1px solid #aaa'}}/> <Button size = "small" onClick={this.changeNickname.bind(this)}style = {{backgroundColor:'#2bbbba',color:'#fff'}}>提交</Button> </Flex> </Accordion.Panel> </Accordion> <Picker data={gender} cols={1} > <List.Item arrow="horizontal" value={this.state.sValue} onChange={v => this.setState({ sValue: v })} onOk={v => this.setState({ sValue: v })} >性别</List.Item> </Picker> <Accordion> <Accordion.Panel header = "签名" > <TextareaItem placeholder = "开始发布您的签名吧(30个字符限制)" rows={2} count={30} style = {{width:'95%',marginBottom:'8px',marginRight:'16px', border:'1px solid #aaa',borderRadius:'5px',fontSize:'12px'}} > </TextareaItem> <Flex justify = "center" style = {{}}> <Button size = "small" style = {{backgroundColor:'#2bbbba',color:'#fff',width:'30%',marginBottom:'15px'}}>提交</Button> </Flex> </Accordion.Panel> </Accordion> <Picker extra="地区" data={{}} title="地区" {...getFieldProps('district', { initialValue: ['340000', '341500', '341502'], })} onOk={e => console.log('ok', e)} onDismiss={e => console.log('dismiss', e)} > <List.Item arrow="horizontal">地区</List.Item> </Picker> <List> <DatePicker style = {{width:'100%'}} mode="date" title="请选择你的出生日期" // extra="Optional" value={this.state.date} onChange={date => this.setState({ date })} > <List.Item arrow="horizontal">生日</List.Item> </DatePicker> </List> <Accordion> <Accordion.Panel header = "修改密码" > <InputItem placeholder = "设置你的新密码" /> <InputItem placeholder = "确认你的新密码"/><br/> <Flex justify = "center" style = {{}}> <Button size = "small" style = {{backgroundColor:'#2bbbba',color:'#fff',width:'30%',marginBottom:'15px'}}>提交</Button> </Flex> </Accordion.Panel> <Accordion.Panel header = "手机" > <Flex justify ="center" style = {{fontSize:'18px',padding:'15px'}}>暂不支持修改此项</Flex> </Accordion.Panel> <Accordion.Panel header = "车牌号" > <Flex justify = "center"> <InputItem placeholder = "设置车牌号" style = {{borderBottom:'1px solid #aaa'}}/> <Button size = "small" style = {{backgroundColor:'#2bbbba',color:'#fff'}}>提交</Button> </Flex> </Accordion.Panel> </Accordion> </div> ) } } const UserDataWrapper = createForm()(UserData) function mapStateToProps(state) { return { current_user: state.currentUser.current_user, user: state.user } } export default connect(mapStateToProps)(UserDataWrapper); <file_sep>import React from 'react'; import { Flex, Button, Tabs } from 'antd-mobile'; import MyWallet from './MyWallet'; import Withdraw from './Withdraw'; import WithdrawSuccess from './WithdrawSuccess'; import WithdrawWait from './WithdrawWait'; class Wallet extends React.Component { constructor() { super(); } render(){ return( <div> <MyWallet history = {this.props.history}/> </div> ) } } export default Wallet; <file_sep>/* Author @Simon <EMAIL> 这个文件处理消息盒子 */ import React from 'react' import { connect } from 'react-redux'; import axios from 'axios'; import { appInfo } from '../../map_props.js'; import {setAppTitle} from '../../actions/app.js'; import MyList from './MyList'; import { Flex } from 'antd-mobile'; import { List, Badge, Button, WhiteSpace, WingBlank,Card, Checkbox,Modal, Toast} from 'antd-mobile'; import { Link } from 'react-router-dom'; import MyItem from './MyItem'; import style from './common.css'; import userImg from '../../assets/img/timg.jpg'; import{ logout } from '../../actions/users'; import { MClient } from '../../config/asteroid.config.js' const alert = Modal.alert; class AppMy extends React.Component{ constructor(props) { super(props); this.confirmWindow = this.confirmWindow.bind(this); } confirmWindow() { let self = this const { dispatch } = this.props; alert('退出当前账号','您是否确认推出当前帐号?',[ { text: '确定', onPress: () => { dispatch(logout()); }}, { text: '取消', onPress: () => console.log('取消了') }, ]) } componentDidMount(){ const { dispatch } = this.props; console.log('组件渲染完成'); console.log(MClient) console.log(MClient.userId) console.log('userId local', window.localStorage["Meteor.userId"]); } render(){ const { dispatch, current_user, appUser } = this.props; console.log("当前用户", current_user) if(appUser.status === 'logouting' ){ Toast.loading("正在登出", 3, ()=>{ console.log('登出中') }); } if(appUser.status === 'offline' ){ Toast.info("请先登陆", 2, ()=>{ this.props.history.push('/tablogin'); }); } return ( <div > <div className = {style['back-color']}> <Flex justify = 'center' align = "center"> <img src = {userImg} className = {style['user-img']}/> </Flex> <Flex justify = "end" className = {style['pencil-position']} > <Link to = "/personal"> <img src = {require('../svg/pencil.svg')} className = {style['pencil-svg']} /> </Link> </Flex> <Flex justify = "center" className = {style['nick-name-pos']}> <span>{this.props.current_user.nickname}</span> </Flex> <Flex justify = "center"> <span className = {style['user-name-span']}>{this.props.current_user.username}</span> </Flex> <Flex justify = "center"> <span className = {style['slogan-span']}>{this.props.current_user.dataAutograph}</span> </Flex> </div> <div className = {style['item-position']} > <MyItem/> <WingBlank> <Button className = {style['sign-out-btn']} onClick={this.confirmWindow}>退出当前帐号</Button> </WingBlank> </div> </div> ) } } function mapStateToProps(state) { return { current_user: state.currentUser.current_user, user: state.user, appUser: state.AppUser, } } export default connect(mapStateToProps)(AppMy); // export default connect(appInfo)(AppMy); <file_sep>import React from 'react' import { List, InputItem, Toast ,WingBlank, Button, WhiteSpace} from 'antd-mobile'; import { register,getLocation } from '../../reducers/user.redux.js' import { connect } from 'react-redux' import { getAddress } from '../../service/amap/api/getCurrentLocationByIP' import { testPhone, testPassword, testUser} from '../../config/reg' import Count from '../login/Count' import { setStore } from '../../config/mUtils' import { MClient } from '../../config/asteroid.config.js' class Register extends React.Component { constructor(props) { super(props) this.state = { user: '', pwd: '', mobile: '', verify: '', count: 60, countingDone:false, status: 'disable' } this.register = this.register.bind(this); this.handleChange = this.handleChange.bind(this); this.goBack = this.goBack.bind(this); this.onChildChange = this.onChildChange.bind(this) this.sendCode = this.sendCode.bind(this) } sendCode() { MClient.call('get.phonesms', this.state.user) .then(result => { Toast.info('验证码已发送请查看手机'); setStore('verify', result) }) .catch(error => { }) } onChildChange(tips,status){ if(status) this.setState({ status:status }) } componentWillReceiveProps(nextProps){ if(nextProps.user.authenticated){ nextProps.history.push('/'); } } goBack() { this.props.history.goBack() } register(){ let self = this; let {user, pwd, mobile,verify} = this.state console.log(`mobile`) console.log(mobile) if(!testUser(user)){ Toast.info('账户格式错误') return } if(!testPhone(mobile)){ Toast.info('手机格式错误') return } if(!testPassword(pwd)){ Toast.info('密码格式错误') return } getAddress() this.props.register(user,pwd,mobile,verify) } handlePhone=(event)=>{ // 倒计时按钮处于倒计时未结束状态时手机号不能修改 var phone = event; if(this.state.status==='sending') return false; // 同步input值 this.setState({ mobile: phone }); // 验证手机号 if(testPhone(phone)){ console.log(`手机验证成功`) this.setState({ status:'able' }); } else{ this.setState({ status:'disable' }); } } handleChange(key,value){ this.setState({ [key]:value }) } render() { return ( <div> <WingBlank> <List renderHeader={() => '进入万车汇'}> <InputItem type="text" placeholder="输入您的账户" onChange={v=>this.handleChange('user',v)} error={this.state.hasError} >账户</InputItem> <InputItem type="number" placeholder="输入您的手机" onChange={this.handlePhone} >手机</InputItem> <InputItem type="number" placeholder="验证码" onChange={v=>this.handleChange('verify',v)} >验证码 <Count status={this.state.status} nums={this.state.count} callback={this.onChildChange} sendCode={this.sendCode}/> </InputItem> <InputItem type="password" placeholder="输入您的密码" onChange={v=>this.handleChange('pwd',v)} >密码</InputItem> </List> <WhiteSpace /> <Button onClick={this.register} type='primary' >登录</Button> <WhiteSpace /> <Button onClick={this.goBack} type='primary' >返回</Button> </WingBlank> </div> ); } } function mapStateToProps(state) { return { user: state.user } } export default connect(mapStateToProps,{register})(Register);<file_sep>import React from 'react'; import { Flex, Carousel } from 'antd-mobile'; import ProductTabs from './ProductTabs'; import ProductShare from './ProductShare'; import ProductBottom from './ProductBottom'; import ProductModal from './ProductModal'; import style from './common.css' import goodImg from '../../assets/img/reward/good.jpg'; import '../../service/data/datasource'; import axios from 'axios'; import {getProduct} from '../../reducers/product.redux'; import { getCart } from '../../reducers/cart.redux'; import { loadProductById } from '../../actions/products'; import { connect } from 'react-redux'; class Goods extends React.Component { constructor(props) { super(props); this.state = { modal2: false, val: 1, product: [], data: ['1', '2', '3'], imgHeight: 176, slideIndex: 0, tagMenuClick: [true] } } componentDidMount() { let id = this.props.match.params.id; this.props.loadProductById(id) // this.props.getProduct(id) } componentWillReceiveProps(nextProps) { console.log(nextProps) console.log(123456); if(nextProps.reviceProduce) { // let tagMenuArr = []; // let spec = nextProps.productShow.specifications // for(var i=0;i<spec.length;i++){ // tagMenuArr.push(false) // } // tagMenuArr[0] = true // console.log(tagMenuArr) // this.setState({ // tagMenuClick: tagMenuArr // }) } // if(nextProps.product.good){ // let spec = nextProps.product.good.spec // let tagMenuArr = []; // for(var i=0;i<spec.length;i++){ // if(spec[i].isThis == true){ // tagMenuArr.push(true) // }else{ // tagMenuArr.push(false) // } // } // this.setState({ // // product: nextProps.product.good, // tagMenuClick: tagMenuArr // }) // }else{ // console.log('no') // } } render(){ let product = this.props.productShow.product let productDefault = this.props.productShow let pic = product.images.map((img,index)=>{ return( <div key={index} style={{ display: 'inline-block', width: '100%', height: this.state.imgHeight }} > <img src={`${img}`} style={{ width: '100%', verticalAlign: 'top' }} onLoad={() => { window.dispatchEvent(new Event('resize')); this.setState({ imgHeight: 'auto' }); }} /> </div> ) }) return ( <div className = {style['product-frame']}> <div > <Carousel dots = {true} autoplay={false} infinite selectedIndex={0} beforeChange={(from, to) => console.log(`slide from ${from} to ${to}`)} afterChange={index => console.log('slide to', index)} > {pic} </Carousel> </div> <div className = {style['describe']}> <Flex className = {style['describe-font']}> {product.description} </Flex> <Flex style = {{marginBottom:'-10px'}}> <Flex.Item justify = "center" > <span className = {style['price-font']}>¥{product.endPrice/100}</span> <span className = {style['black-card']}>{product.name_zh}</span> </Flex.Item> <span align = "right" style = {{color:'#7b7b7b'}}>{productDefault.address}</span> </Flex> <span style = {{ textDecoration:'line-through',color:'#aaa',paddingTop:'3px',lineHeight:'1.8em'}}>¥{product.price}</span> </div> <Flex justify = "between" className = {style['item']}> <Flex > <ProductShare/></Flex> <Flex>一级奖励:<span style= {{color:'#ffcf2d'}}>¥20</span></Flex> <Flex>二级奖励:<span style= {{color:'#ffcf2 d'}}>¥10</span><img src={require('../svg/no.svg')} style = {{paddingLeft:'10px',width:'14px',width:'14px'}}/></Flex> </Flex> <Flex justify = "between" className = {style['item-des']}> <Flex>配送方式:{productDefault.deliver}</Flex> <Flex>库存:{productDefault.inventory}</Flex> <Flex>销量: {productDefault.sales} </Flex> </Flex> <Flex className = {style['item-type']}> <ProductModal spec={product.specifications} tagMenuClick={this.state.tagMenuClick} history={this.props.history}/> </Flex> <ProductTabs/> <ProductBottom history={this.props.history} shopId={product.shopId} /> </div> ) } } function mapStateToProps(state) { return { product: state.product, productShow: state.productShow, reviceProduce: state.productShow.product } } export default connect(mapStateToProps,{getProduct,loadProductById})(Goods); <file_sep>// import {SET_CURRENT_USER, SET_CURRENT_USER_ERROR } from '../actions/users.js' const initialState = { current_user: { "username" : "", "profile" : { "mobile" : "", "isNewFromMobile" : false }, "score" : '', "headurl" : "", "createdAt" : '', "logintimes" : '', "lastLoginTime" : '', "sex" : "保密", "nickname" : "未设置花名", "dataAutograph" : "我的梦想是让世界和平", }, } export function currentUser(state = initialState,action){ switch (action.type){ case 'SET_CURRENT_USER': console.log(action.user); return Object.assign({}, state, { current_user: action.user, }) default: return state } } <file_sep>import React from 'react' import { HashRouter as Router, Route, Switch, Link, BrowserRouter } from 'react-router-dom'; import MainLayout from '../layouts/MainLayout.js' import MessageBox from './messages' import AppHome from './home'; import My from './my'; import Register from './register/Register'; import { connect } from 'react-redux'; import PrivateRoute from './container/PrivateRoute'; import TabLogin from './login/TabLogin'; import { getStore } from '../config/mUtils'; import Test from './checkbox'; // import Orders from './orders/index'; import Goods from './product/index'; import ShopCart from './shop_cart/index'; import WaitDetails from './orders/WaitDetails'; import Paid from './orders/Paid'; import Refund from './orders/Refund'; import UntreatedDetail from './orders/UntreatedDetail'; import QrCode from './orders/QrCode'; import CartNull from './shop_cart/CartNull'; import CartTest from './checkbox/cart' import UserData from './my/UserData'; import ProductModal from './product/ProductModal'; import Facilitator from './product/Facilitator'; import FirmOrder from './product/FirmOrder'; import PaySuccess from './product/PaySuccess'; import Address from './product/Address'; import SearchBox from './search/ProductSearch'; import SearchResult from './search/SearchResult'; import Cart from './checkbox/cart'; import Wallet from './wallet/index'; import Withdraw from './wallet/Withdraw'; import WithdrawSuccess from './wallet/WithdrawSuccess'; import WithdrawWait from './wallet/WithdrawWait'; import VipCard from './vipcard/index'; import Coupon from './coupon/index'; import MyBankCard from './wallet/MyBankCard'; import EditBankCard from './wallet/EditBankCard'; // import OrderList from './orders/OrderList'; import ForgotPassword from './password/' import ResetPassword from './password/ResetPassword' import NoMatchPage from './no_match/' import Shops from './shops/' import Personal from './my/Personal'; // import Orders from './Orders/index'; // import OrderList from './Orders/OrderList'; import Orders from './orders/index'; import OrderList from './orders/OrderList'; import createHistory from 'history/createHashHistory'; const history = createHistory(); const Home = ({ match }) => ( <AppHome path={match.path} /> ) const ShopsPage = ({ match }) => ( <Shops path={match.path} params={match.params} /> ) const Messages = ({match}) => ( <MessageBox path={match.path} /> ) const Topic = ({ match }) => ( <div> <h3>{match.params.topicId}</h3> </div> ) const Topics = ({ match }) => ( <div> <h2>Topics</h2> <ul> <li> <Link to={`${match.url}/rendering`}> Rendering with React </Link> </li> <li> <Link to={`${match.url}/components`}> Components </Link> </li> <li> <Link to={`${match.url}/props-v-state`}> Props v. State </Link> </li> </ul> <Route path={`${match.url}/:topicId`} component={Topic}/> <Route exact path={match.url} render={() => ( <h3>Please select a topic.</h3> )}/> </div> ) class App extends React.Component { componentDidMount(){ console.log('开始进入App'); console.log('检查用户状态'); console.log('检查当前路由状态'); console.log(history); } routeControl(CurrentUser){ } render() { console.log('每次渲染都要检测'); const authenticated = getStore('authenticated'); // console.log(MClient) // console.log(MClient.userId) // MClient.ddp.on('result',({id,message,result}) =>{ // console.log(result.id) // }) // MClient.connected() return ( <Router > <MainLayout history={history}> <Switch> <Route exact path="/" component={Home} authenticated={authenticated}/> <Route exact path="/money" component={Home} authenticated={authenticated}/> <Route path="/messages" component={Messages} authenticated={authenticated}/> <Route path = "/shop_cart" component={ShopCart} /> <Route path="/my" component={My} authenticated={authenticated}/> <Route path="/register" component={Register}/> <Route path="/tablogin" component={TabLogin} /> <Route path="/test" component={Test} /> {/* <Route path = "/orders" component={Orders}/> */} <Route path = "/product/:id" component={Goods}/> <Route path = "/order_details/:orderId" component={WaitDetails}/> <Route path = "/paid/:orderId" component={Paid}/> <Route path = "/refund" component={Refund}/> <Route path = "/untreated" component={UntreatedDetail}/> <Route path = "/qrcode" component={QrCode}/> <Route path = "/nullcart" component={ CartNull }/> <Route path = "/userdata" component={ UserData }/> <Route path = "/facilitator/:shopId" component = { Facilitator }/> <Route path = "/productmodal" component={ ProductModal }/> <Route path = "/firmorder/:orderId" component = {FirmOrder}/> {/* <Route path = "/firmorder" component = {FirmOrder}/> */} <Route path = "/paysuccess" component = {PaySuccess}/> <Route path="/forgotpassword" component={ForgotPassword} /> <Route path="/resetpassword" component={ResetPassword} /> <Route path="/carttest" component={CartTest} /> <Route path="/address" component={Address} /> <Route path="/searchbar" component={SearchBox} /> <Route path="/searchresult" component={SearchResult}/> <Route path="/shops/:tagId" component={ShopsPage}/> <Route path="/pull" component={Cart}/> <Route path="/wallet" component={Wallet}/> <Route path="/withdraw" component={Withdraw}/> <Route path="/withdrawsuccess" component={WithdrawSuccess}/> <Route path="/withdrawwait" component={WithdrawWait}/> <Route path="/vipcard" component={VipCard}/> <Route path="/coupon" component={Coupon}/> <Route path="/bankcard" component={MyBankCard}/> <Route path="/editbankcard" component={EditBankCard}/> <Route path="/orderlist" component={OrderList}/> <Route path = "/orders" component={Orders}/> <Route path = "/personal" component={Personal}/> <Route component={NoMatchPage}/> </Switch> </MainLayout> </Router> ) } } function mapStateToProps(state) { return { user: state.user } } export default connect(mapStateToProps)(App); <file_sep>import { RECEIVEORDERBYID } from '../actions/orders.js' const initState = { "_id" : "", "type" : null, "userId" : "", "status" : "", "shopId" : "", "products" : [ ], "username" : "", "address" : null } export function order(state=initState, action){ switch (action.type) { case RECEIVEORDERBYID: console.log(`orderid`) return Object.assign({},state,{ ...action.order }) break; default: return state } } <file_sep>/* Author @Simon <EMAIL> 这个文件处理消息盒子 */ import React from 'react' import { connect } from 'react-redux'; import { appInfo } from '../../map_props.js'; import { Flex, WhiteSpace, WingBlank,Tabs } from 'antd-mobile'; //redux actions import {setAppTitle} from '../../actions/app.js'; import AwardDetail from './AwardDetail.js'; import AwardIncome from './AwardIncome.js'; import AwardHead from './AwardHead.js'; import { MClient } from '../../config/asteroid.config.js'; import { gainBlance,gainGetBalanceIncomesTotal } from '../../actions/balance'; class MessageBox extends React.Component{ constructor(props) { super(props); this.state = { username: [ {name: 'Hiark'}, ], balance: { }, } } componentDidMount() { let { dispatch } = this.props; let userId = "ZCFqbZeRpKZge3uGf" dispatch(gainBlance(userId)) dispatch(gainGetBalanceIncomesTotal(userId)) } render(){ let {total,balance} = this.props.balance console.log(this.props.balance) return ( <div> <AwardHead balance={balance}/> <AwardIncome total={total}/> <AwardDetail/> </div> ) } } function mapBalanceState(state) { return { balance: state.balance } } export default connect(mapBalanceState)(MessageBox); <file_sep>import { MClient } from '../config/asteroid.config.js' export const EXPECT_LOGOUT = "EXPECT_LOGOUT"; export const LOGOUT_SUCCESS = "LOGOUT_SUCCESS"; export const EXPECT_LOGIN_SMS_CODE = "EXPECT_LOGIN_SMS_CODE"; export const GET_LOGIN_SMS_CODE_SUCCESS = "GET_LOGIN_SMS_CODE_SUCCESS"; export const GET_LOGIN_SMS_CODE_FAIL="GET_LOGIN_SMS_CODE_FAIL"; const crypto = require('crypto'); //============== 用户的注册登录 ====================== export function login(loginType, loginParams){ } export function expectLoginSMSCode(){ return { type: EXPECT_LOGIN_SMS_CODE, } } export function getLoginSMSCodeSuccess(code){ return { type: GET_LOGIN_SMS_CODE_SUCCESS, code } } export function getLoginSMSCodeFail(){ return { type: GET_LOGIN_SMS_CODE_FAIL, } } export function getLoginSMSCode(mobile){ return dispatch => { dispatch(expectLoginSMSCode()); let methodId = MClient.method('get.phonesms', [mobile]); MClient.on("result", message => { if (message.id === methodId && !message.error) { //加密验证码 let hash = crypto.createHash('sha256'); let cryptoCode = hash.update(message.result).digest('hex'); dispatch(getLoginSMSCodeSuccess(cryptoCode)); }else{ dispatch(getLoginSMSCodeFail()); } }); } } export function mobileLogin(loginParams){ } export function passwordLogin(loingParams){ } export function registerLogin(regParams){ } export function expectLogout(){ return { type: EXPECT_LOGOUT, } } export function logout(){ return dispatch => { dispatch(expectLogout()); let methodId = MClient.method('logout'); MClient.on('result', message=>{ if(message.id === methodId && !message.error){ dispatch(logoutSuccess()); }else{ console.error(message.error); } }) } } export function logoutSuccess(){ return { type: LOGOUT_SUCCESS, } } //================================================= //============ 用户权限管理 ========================== export function checkUserAccess(userId){ } export function checkUserLogined(userId){ } export function refuseUserAccess(userId){ } export function acceptUserAccess(userId){ } //=================================================== //===============获取登录用户的信息========================== export function expectUserInfo(){ } export function loadUserInfo(){ } export function loadUserInfoError(){ } //========================================================= //===============载入用户信息========================================== export function expectUserById(id){ } export function loadUserById(id){ } export function expectUsersAsFollows(){ } //======================================= <file_sep>import React from 'react'; import { Flex } from 'antd-mobile'; import cardImg from '../../assets/img/blackcard.png' class VipCard extends React.Component { constructor() { super(); } render(){ return ( <Flex direction = "column" justify = "start" align = "start" style = {{padding:'0 15px',backgroundColor:'#fff'}}> <div style = {{margin:'15px 0',borderLeft:'3px solid #aaa',paddingLeft:'10px'}}>我的会员卡</div> <img src = {cardImg} style = {{width:'100%',height:'100%',marginBottom:'15px'}}/> <Flex justify = "center" align = "center">对应的车牌号</Flex> </Flex> ) } } export default VipCard; <file_sep>import React from 'react'; import { Flex } from 'antd-mobile'; // import s from './BtnStyle.css'; import styles from './Common.css'; class OrderBtn extends React.Component { constructor(props) { super(props) this.paid = this.paid.bind(this) this.details = this.details.bind(this) } paid(){ this.props.history.push('/paid') } details(){ this.props.history.push(`/order_details/${this.props.orderId}`) } render() { return ( <div> {(()=>{ switch(this.props.status) { case 1: return ( <Flex justify = "end" > <button >详情</button> <button >删除订单</button> </Flex> ); case 2: return( <Flex justify = "end" style = {{margin:'10px',paddingBottom:'10px'}}> <button className = {styles['detail-btn']} onClick = {this.details}>详情</button> <button className = {styles['cancel-btn']}>取消订单</button> <button className = {styles['pay-btn']} style = {{marginLeft:'15px'}} >支付</button> </Flex> ); case 3: return( <Flex justify = "end" className = {styles['btn-frame']}> <button className = {styles['detail-btn']} >详情</button> <button className = {styles['delete-btn']}>删除订单</button> </Flex> ) case 4: return( <Flex justify = "end" style = {{margin:'10px'}}> <button className = {styles['detail-btn']}>详情</button> <button className = {styles['revoke-btn']}>撤销退款</button> </Flex> ) } })()} </div> ) } } export default OrderBtn;<file_sep>import React from 'react' import { List, InputItem, Button, WhiteSpace, WingBlank, Toast } from 'antd-mobile'; import { MClient } from '../../config/asteroid.config.js' import { connect } from 'react-redux' import { mobileRegister } from '../../reducers/user.redux' import Count from './Count' import { setStore } from '../../config/mUtils' import { testPhone } from '../../config/reg' import { getLoginSMSCode } from '../../actions/users.js' class MobileLogin extends React.Component { constructor(props) { super(props) this.state = { user:'', pwd:'', count: 60, countingDone:false, status: 'disable' } this.register = this.register.bind(this) this.handleLogin = this.handleLogin.bind(this) this.handleLogout = this.handleLogout.bind(this) this.onChildChange = this.onChildChange.bind(this) this.sendCode = this.sendCode.bind(this) } componentDidMount(){ document.title="登陆万人车汇"; } sendCode() { const {dispatch, appUser} = this.props; dispatch(getLoginSMSCode(this.state.user)); if(appUser.loginSMSCode !=="" && appUser.loginSMSCode !=="loading" && appUser.loginSMSCode !== "error"){ Toast.success("验证码发送成功!"); } if(appUser.loginSMSCode ==="error"){ Toast.offline("验证码发送失败,请检查您的网络链接,或者是您请求过于频繁,过一个小时再试试吧", 3); } if (appUser.loginSMSCode==="loading") { Toast.loading("正在发送验证码"); } } onChildChange(tips,status){ if(status) this.setState({ status:status }) } register() { this.props.history.push('/register') } handleLogin() { let phone = this.state.user; let pwd = this.state.pwd if(!testPhone(phone)){ Toast.info("手机格式不正确") }else{ this.props.mobileRegister(phone,pwd) } } handleLogout() { MClient.logout() } handlePhone=(event)=>{ // 倒计时按钮处于倒计时未结束状态时手机号不能修改 console.log(event); var phone = event; if(this.state.status==='sending') return false; // 同步input值 this.setState({ user: phone }); // 验证手机号 if(testPhone(phone)){ this.setState({ status:'able' }); } else{ this.setState({ status:'disable' }); } } handleChange(key,value){ this.setState({ [key]:value }) } render() { const { appUser } = this.props; return ( <div> <WingBlank> <List renderHeader={() => '进入万车汇'}> <InputItem type="text" placeholder="输入您的手机号" onChange={this.handlePhone} onErrorClick={this.onErrorClick} error={this.state.hasError} >手机号码</InputItem> <InputItem type="password" placeholder="输入您的验证码" onChange={v=>this.handleChange('pwd',v)} >验证码 <Count status={this.state.status} nums={this.state.count} callback={this.onChildChange} sendCode={this.sendCode}/> </InputItem> </List> <WhiteSpace /> <Button onClick={this.handleLogin} type='primary' >登录</Button> <WhiteSpace /> <Button onClick={this.register} type='primary' >注册</Button> </WingBlank> </div> ); } } function mapStateToProps(state) { return { appUser: state.AppUser, } } export default connect(mapStateToProps)(MobileLogin); <file_sep>import React from 'react'; import { Flex, Button, Modal, WhiteSpace, List, Stepper, Carousel} from 'antd-mobile'; import goodImg from '../../assets/img/reward/good.jpg'; import style from './ProductBottom.css'; import s from './ProductModal.css'; import { connect } from 'react-redux'; import { openSpecModel, closeSpecModel } from '../../reducers/model.redux'; import { changeProduct } from '../../reducers/product.redux'; import { addCount,createOrder } from '../../actions/products'; import { addCart, getCart, insertCart } from '../../reducers/cart.redux'; import { modelInfo } from '../../map_props'; const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent); let wrapProps; if (isIPhone) { wrapProps = { onTouchStart: e => e.preventDefault(), }; } class ProductModal extends React.Component { constructor(props) { super(props); this.state = { // modal2: false, val: 1, data: ['1', '2', '3'], imgHeight: 176, slideIndex: 0, tagMenuClick: [false,false], } } componentDidMount() { console.log(this.props) this.props.getCart(2) } componentWillReceiveProps(nextProps) { this.setState({ tagMenuClick: nextProps.tagMenuClick }); } showModal = key => (e) => { e.preventDefault(); // 修复 Android 上点击穿透 this.props.openSpecModel() } loopSpecOrderItem(spec) { } //加入购物车 onClose = key => (e) => { e.preventDefault(); console.log(123) let {cart} = this.props; let product = this.props.productShow.product; let count = this.props.productShow.count // console.log(product) // console.log(cart) let spec = this.props.spec.length == 0 ? '默认规格': product.specifications; if(this.props.model.way=="orders"){ let params = { userId: 2, status: 'unpay', shopId: product.shopId, address: "user.address.id", username: "李逍遥", mobile: "13751124249", products: [ { price: product.endPrice, count, cover: product.cover, id: product._id, name: product.name_zh, specifications: { name: spec } }, ] }; console.log(`提交订单`) this.props.createOrder(params); this.props.closeSpecModel() } // let selected =product.selected !== undefined ?product.selected :product.good.spec[0] // let count =product.count !== undefined ?product.count : 1 // let productId =product.good.id // let shopId =product.good.shop_id // let shopIds = []; // let goodIds = []; // var ShopReplaceData; // var ProductReplaceData; // if(this.props.model.way=="orders"){ // let params = { // shop_id: product.good.shop_id, // prodductSpec: selected, // product_id: product.good.id, // count: count, // } // console.log(params) // }else{ // if(cart.goods.user_id == ''){ // console.log(`购物车不存在`) // let params = { // user_id: 2, // shopsData: [ // { // shop_name: product.good.shop_name, // checked: false, // shop_id: product.good.shop_id, // productsData: [ // { // shop_id: product.good.shop_id, // checked: false, // name: product.good.name, // status: 1, // count: count, // prodductSpec: selected, // product_id: product.good.id // } // ] // } // ] // } // console.log(params) // this.props.insertCart(params) // this.props.closeSpecModel() // return // } // for(var i = 0;i < cart.goods.shopsData.length;i++){ // shopIds.push(cart.goods.shopsData[i].shop_id); // for(var j=0;j<cart.goods.shopsData[i].productsData.length;j++){ // goodIds.push(cart.goods.shopsData[i].productsData[j].product_id) // } // } // if(goodIds.includes(product.good.id) && shopIds.includes(product.good.shop_id)){ // for(var i = 0;i < cart.goods.shopsData.length;i++){ // for(var j=0;j<cart.goods.shopsData[i].productsData.length;j++){ // if(cart.goods.shopsData[i].productsData[j].product_id==productId){ // if(cart.goods.shopsData[i].productsData[j].prodductSpec.name==selected.name){ // cart.goods.shopsData[i].productsData[j].count = cart.goods.shopsData[i].productsData[j].count*1+count // }else{ // console.log(`生成新的规格商品`) // cart.goods.shopsData[i].productsData.push({ // shop_id: product.good.shop_id, // checked: false, // name: product.good.name, // status: 1, // count: count, // prodductSpec: selected, // product_id: product.good.id // }) // } // } // } // } // }else if(shopIds.includes(product.good.shop_id)){ // for(var i = 0;i < cart.goods.shopsData.length;i++){ // if(cart.goods.shopsData[i].shop_id == product.good.shop_id){ // cart.goods.shopsData[i].productsData.push({ // shop_id: product.good.shop_id, // checked: false, // name: product.good.name, // status: 1, // count: count, // prodductSpec: selected, // product_id: product.good.id // }) // } // } // }else{ // cart.goods.shopsData.push({ // shop_name: product.good.shop_name, // checked: false, // shop_id: product.good.shop_id, // productsData: [ // { // shop_id: product.good.shop_id, // checked: false, // name: product.good.name, // status: 1, // count: count, // prodductSpec: selected, // product_id: product.good.id // } // ] // }) // } // this.props.addCart(cart.goods.shopsData); // this.props.closeSpecModel() // } } Close = key => (e) => { e.preventDefault(); this.props.closeSpecModel() } onChange = (val) => { this.setState({ val },()=>{ this.props.addCount(this.state.val) }); } handleSelectedSpec(i){ let tagMenuClick = this.state.tagMenuClick; this.clearClickedStyle(); tagMenuClick[i] = !tagMenuClick[i]; this.setState({ tagMenuClick, }) // this.props.changeProduct(i) } handleTagMenuClick(num){ let tagMenuClick = this.state.tagMenuClick; this.clearClickedStyle(); tagMenuClick[num] = !tagMenuClick[num]; this.setState({ tagMenuClick, }) } clearClickedStyle(){ let tagMenuClick = this.state.tagMenuClick; for (var i = 0; i < tagMenuClick.length; i++) { tagMenuClick[i] = false; } } renderSpec() { } render(){ let modelStatus = this.props.model.spec_model; let product = this.props.productShow.product; console.log(this.props.spec.length) let spec = this.props.spec.length == 0 ? [{name: '默认规格',price: product.endPrice,isThis: true}] : product.specifications; console.log(spec) console.log(spec.length) let specArr = [] let price = []; for(var i=0; i<spec.length;i++){ console.log(123); specArr.push( <div className = {style['color-div']} style={{background: this.state.tagMenuClick[i] ? "#e85839" : "#e5e5e5"}} key={i} onClick={this.handleSelectedSpec.bind(this,i)}> {spec[i].name} </div> ) {spec[i].isThis===true ? price.push(`${spec[i].price}`) : null } } return( <div> <Flex.Item onClick={this.showModal('modal2')} style = {{color:'black',justify:'center'}}><span style = {{color:'#888'}}>选择类型</span></Flex.Item> <WhiteSpace /> <Modal popup visible={modelStatus} maskClosable={false} animationType="slide-up" > <div style = {{margin:'10px'}}> <Flex> <img src = {goodImg} style = {{width:'60px',height:'60px',border:'6px solid #680000'}}/> <div style = {{paddingLeft:'10px'}}> <span style = {{color:'red',fontSize:'22px',paddingRight:'10px'}}>¥{price/100}</span><br/> <span style = {{color:'#666',fontSize:'14px'}}>请选择类型</span> </div> <img src = {require('../svg/close_black.svg')} style = {{position:'absolute',right:'15px',top:'10px',width:'25px',height:'25px',paddingBottom:'44px'}} onClick = {this.Close('modal2')}/><br/> </Flex> <Flex style = {{display:'flex',alignSelf:'flex-end'}}> </Flex> <WhiteSpace/> <Flex wrap = "wrap" justify = "start"> {specArr} </Flex> <Flex className = {style['num-padding']}> 购买数量: <Stepper style={{ width: '50%', minWidth: '80px'}} showNumber max={99} min={1} value={this.state.val} onChange={this.onChange} /> </Flex> <List> <List.Item> <Button type = "warning" onClick = {this.onClose('modal2')}>确定</Button> </List.Item> </List> </div> </Modal> </div> ) } } export default connect(modelInfo,{changeProduct,addCart,addCount,openSpecModel,closeSpecModel,getCart,insertCart,createOrder })(ProductModal);
3befb9d90191d1785b59768a46fd0206e35cc36f
[ "JavaScript" ]
22
JavaScript
youngiyang1990/fancyshop
cb7e111d210c414fafbf258002b827bd0991cc4c
0ccaabff17738b687352c3ee3956537a1209c190
refs/heads/master
<repo_name>izayah/PTSD_APP<file_sep>/settings.gradle include ':ptsd', ':ptsd_mobile', ':mobile' <file_sep>/ptsd/src/main/java/com/example/ptsd/StressToolsActivity.java package com.example.ptsd; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class StressToolsActivity extends Activity { Button breathing, muscle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_stress_tools); /*breathing = (Button) findViewById(R.id.breathing_tool_button); breathing.setOnClickListener(new View.OnClickListener*/ } public void startBreathingTool(View view) { Intent startBreathing = new Intent(StressToolsActivity.this, BreathingActivity.class); startActivity(startBreathing); } public void startMuscleTool(View view) { Intent startMuscle = new Intent(StressToolsActivity.this, MuscleRelaxationActivity.class); startActivity(startMuscle); } } /*------------------------------------------------------------------------------------------------*/ /*play=(Button) findViewById(R.id.play); pause=(Button) findViewById(R.id.pause); final MediaPlayer sound=MediaPlayer.create(this, R.raw.rain); play.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ sound.start(); } }); pause.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ sound.pause(); } }); */ <file_sep>/README.md # PTSD_APP REU Summer TAMU/PSU 2016 bf g g bg bg bg bgbg<file_sep>/ptsd/src/main/java/com/example/ptsd/AmbientMonitor.java package com.example.ptsd; import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import java.text.SimpleDateFormat; import java.util.Locale; public class AmbientMonitor extends IntentService implements SensorEventListener{ private Sensor senHeartRate,senHeartBeat,senAccelerometer; private SensorManager senSensorManager; String status; String testString = "Now returning from AmbientMonitor service."; IntentFilter mStatusIntentFilter = new IntentFilter("AmbientMonitor"); private float last_x, last_y, last_z; long lastUpdate = 0; int heartRateThreshold = 80; public AmbientMonitor(String name) { super(name); } public AmbientMonitor(){ super("AmbientMonitor"); } @Override protected void onHandleIntent(Intent intent) { //Get information from the incoming intent String dataString = intent.getDataString(); monitorHeart(); //send broadcast back to main Intent tempIntent = new Intent(status); LocalBroadcastManager.getInstance(this).sendBroadcast(tempIntent); } private static final SimpleDateFormat AMBIENT_DATE_FORMAT = new SimpleDateFormat("HH:mm", Locale.US); protected void onCreate(Bundle savedInstanceState) { //super.onCreate(savedInstanceState); } public void monitorHeart(){ senSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); senAccelerometer = senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); senHeartRate = senSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE); senSensorManager.registerListener(this, senAccelerometer , SensorManager.SENSOR_DELAY_NORMAL); senSensorManager.registerListener(this, senHeartRate , SensorManager.SENSOR_DELAY_NORMAL); //Sends broadcast signalling end of operation Intent tempIntent = new Intent(status); LocalBroadcastManager.getInstance(this).sendBroadcast(tempIntent); } public void onAccuracyChanged(Sensor sensor, int accuracy) { //Log.d(TAG, "onAccuracyChanged - accuracy: " + accuracy); } public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_HEART_RATE) { //Log.i("Ambient Heart Rate", ""+event.values[0] + " bpm"); //checks if heart beat is over threshold as well as the accuracy //low accuracy measures aren't counted //if(event.values[0] >= heartRateThreshold /*&& event.accuracy != 0*/){ status = "Intervene"; //Log.i("Ambient Heart Rate", "Reached heart rate threshold! Critical Limits"); //broadcast to the main activity to start intervention and end this service this.stopSelf(); Intent tempIntent = new Intent(status); LocalBroadcastManager.getInstance(this).sendBroadcast(tempIntent); //} } if (event.sensor.getType() == Sensor.TYPE_HEART_BEAT) { Log.d("Ambient Heart Beat", ""+event.values[0]); } if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){ float x = event.values[0]; float y = event.values[1]; float z = event.values[2]; long curTime = System.currentTimeMillis(); /*increase interval to reduce amount of data*/ if ((curTime - lastUpdate) > 100) { long diffTime = (curTime - lastUpdate); lastUpdate = curTime; float speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 1000; last_x = x; last_y = y; last_z = z; Log.i("Velocity",speed + " m/s" ); //int speedThreshold = 150; } } } } <file_sep>/ptsd/src/main/java/com/example/ptsd/InterventionActivity.java package com.example.ptsd; import android.os.Bundle; import android.os.Vibrator; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; public class InterventionActivity extends AppCompatActivity { private TextView mTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_intervention); Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); //vibrator.vibrate(5000); } }
bb831f6aa1e782385cb30244860541ccd7c3cb29
[ "Markdown", "Java", "Gradle" ]
5
Gradle
izayah/PTSD_APP
84f75ffd55008921eab7c3bdf435395cd231d5b6
d265d44072fe622af8dccf1c9636ce33755a05dd
refs/heads/main
<file_sep> $(document).ready(function(){ $("#loguinAluno").submit(function(event){ var usuario = $("#inputUsuario").val() var senha = $("#inputSenha").val() //*Testar se usuario e senha estão corretos*// if(usuario == "nome" && senha == "<PASSWORD>"){ $("#mensagem").addClass("alert alert-sucess alert-dismissible fade show") $("mensagem").removeClass("alert-warning") $("#mensagem").text("Usuário logado!").show().fadeOut(3000) }else{ $("#mensagem").addClass("alert alert-warning alert-dismissible fade show") $("mensagem").removeClass("alert-sucess") $("#mensagem").text("Usuário ou senha inválida!").show().fadeOut(3000) event.preventDefault() } }) })
c4b4860963a10437c2f0f835d2669e908d855334
[ "JavaScript" ]
1
JavaScript
jhucyy/frontend_projetoteste
4e45fb5f3f7cc538c5432d899c5c65dcb820dfcf
327af48b9e8bb9f682968394ffc9c37e133a6c10
refs/heads/master
<repo_name>anushac5318/DataWranglingProject<file_sep>/Parsing.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ After auditing is complete the next step is to prepare the data to be inserted into a SQL database. To do so you will parse the elements in the OSM XML file, transforming them from document format to tabular format, thus making it possible to write to .csv files. These csv files can then easily be imported to a SQL database as tables. The process for this transformation is as follows: - Use iterparse to iteratively step through each top level element in the XML - Shape each element into several data structures using a custom function - Utilize a schema and validation library to ensure the transformed data is in the correct format - Write each data structure to the appropriate .csv files We've already provided the code needed to load the data, perform iterative parsing and write the output to csv files. Your task is to complete the shape_element function that will transform each element into the correct format. To make this process easier we've already defined a schema (see the schema.py file in the last code tab) for the .csv files and the eventual tables. Using the cerberus library we can validate the output against this schema to ensure it is correct. ## Shape Element Function The function should take as input an iterparse Element object and return a dictionary. ### If the element top level tag is "node": The dictionary returned should have the format {"node": .., "node_tags": ...} The "node" field should hold a dictionary of the following top level node attributes: - id - user - uid - version - lat - lon - timestamp - changeset All other attributes can be ignored The "node_tags" field should hold a list of dictionaries, one per secondary tag. Secondary tags are child tags of node which have the tag name/type: "tag". Each dictionary should have the following fields from the secondary tag attributes: - id: the top level node id attribute value - key: the full tag "k" attribute value if no colon is present or the characters after the colon if one is. - value: the tag "v" attribute value - type: either the characters before the colon in the tag "k" value or "regular" if a colon is not present. Additionally, - if the tag "k" value contains problematic characters, the tag should be ignored - if the tag "k" value contains a ":" the characters before the ":" should be set as the tag type and characters after the ":" should be set as the tag key - if there are additional ":" in the "k" value they and they should be ignored and kept as part of the tag key. For example: <tag k="addr:street:name" v="Lincoln"/> should be turned into {'id': 12345, 'key': 'street:name', 'value': 'Lincoln', 'type': 'addr'} - If a node has no secondary tags then the "node_tags" field should just contain an empty list. The final return value for a "node" element should look something like: {'node': {'id': 757860928, 'user': 'uboot', 'uid': 26299, 'version': '2', 'lat': 41.9747374, 'lon': -87.6920102, 'timestamp': '2010-07-22T16:16:51Z', 'changeset': 5288876}, 'node_tags': [{'id': 757860928, 'key': 'amenity', 'value': 'fast_food', 'type': 'regular'}, {'id': 757860928, 'key': 'cuisine', 'value': 'sausage', 'type': 'regular'}, {'id': 757860928, 'key': 'name', 'value': "Shelly's Tasty Freeze", 'type': 'regular'}]} ### If the element top level tag is "way": The dictionary should have the format {"way": ..., "way_tags": ..., "way_nodes": ...} The "way" field should hold a dictionary of the following top level way attributes: - id - user - uid - version - timestamp - changeset All other attributes can be ignored The "way_tags" field should again hold a list of dictionaries, following the exact same rules as for "node_tags". Additionally, the dictionary should have a field "way_nodes". "way_nodes" should hold a list of dictionaries, one for each nd child tag. Each dictionary should have the fields: - id: the top level element (way) id - node_id: the ref attribute value of the nd tag - position: the index starting at 0 of the nd tag i.e. what order the nd tag appears within the way element The final return value for a "way" element should look something like: {'way': {'id': 209809850, 'user': 'chicago-buildings', 'uid': 674454, 'version': '1', 'timestamp': '2013-03-13T15:58:04Z', 'changeset': 15353317}, 'way_nodes': [{'id': 209809850, 'node_id': 2199822281, 'position': 0}, {'id': 209809850, 'node_id': 2199822390, 'position': 1}, {'id': 209809850, 'node_id': 2199822392, 'position': 2}, {'id': 209809850, 'node_id': 2199822369, 'position': 3}, {'id': 209809850, 'node_id': 2199822370, 'position': 4}, {'id': 209809850, 'node_id': 2199822284, 'position': 5}, {'id': 209809850, 'node_id': 2199822281, 'position': 6}], 'way_tags': [{'id': 209809850, 'key': 'housenumber', 'type': 'addr', 'value': '1412'}, {'id': 209809850, 'key': 'street', 'type': 'addr', 'value': 'West Lexington St.'}, {'id': 209809850, 'key': 'street:name', 'type': 'addr', 'value': 'Lexington'}, {'id': '209809850', 'key': 'street:prefix', 'type': 'addr', 'value': 'West'}, {'id': 209809850, 'key': 'street:type', 'type': 'addr', 'value': 'Street'}, {'id': 209809850, 'key': 'building', 'type': 'regular', 'value': 'yes'}, {'id': 209809850, 'key': 'levels', 'type': 'building', 'value': '1'}, {'id': 209809850, 'key': 'building_id', 'type': 'chicago', 'value': '366409'}]} """ import csv import codecs import pprint import re import xml.etree.cElementTree as ET import cerberus import schema OSM_PATH = "atlanta_georgia.osm" NODES_PATH = "nodes.csv" NODE_TAGS_PATH = "nodes_tags.csv" WAYS_PATH = "ways.csv" WAY_NODES_PATH = "ways_nodes.csv" WAY_TAGS_PATH = "ways_tags.csv" LOWER_COLON = re.compile(r'^([a-z]|_)+:([a-z]|_)+') PROBLEMCHARS = re.compile(r'[=\+/&<>;\'"\?%#$@\,\. \t\r\n]') street_type_re = re.compile(r'\S+\.?$', re.IGNORECASE) SCHEMA = schema.schema # Make sure the fields order in the csvs matches the column order in the sql table schema NODE_FIELDS = ['id', 'lat', 'lon', 'user', 'uid', 'version', 'changeset', 'timestamp'] NODE_TAGS_FIELDS = ['id', 'key', 'value', 'type'] WAY_FIELDS = ['id', 'user', 'uid', 'version', 'changeset', 'timestamp'] WAY_TAGS_FIELDS = ['id', 'key', 'value', 'type'] WAY_NODES_FIELDS = ['id', 'node_id', 'position'] # To fix the street names STREET_NAMES_FIX = {"Aly": "Alley", "Av": "Avenue", "Ave": "Avenue", "Ave.": "Avenue", "AVENUE": "Avenue", "BLF": "Bluff", "Bldv": "Boulevard", "blvd": "Boulevard", "Blvd": "Boulevard", "Blvd.": "Boulevard", "Cir": "Circle", "circle": "Circle", "Clse": "Close", "Cmns": "Commons", "court": "Court", "COurt": "Court", "Ct": "Court", "Ct.": "Court", "creek": "Creek", "Crest": "Crst", "Dr": "Drive", "dr": "Drive", "Dr.": "Drive", "drive": "Drive", "East": "E", "EAST": "E", "Glenn": "Glen", "GLN": "Glen", "Grn": "Green", "GRV": "Grove", "Hallow": "Hollow", "Hts": "Heights", "highway": "Hwy", "Highway": "Hwy", "Hill": "Hills", "Lake": "Lakes", "Lndg": "Landing", "Ln": "Lane", "LN": "Lane", "Ln.": "Lane", "lane": "Lane", "Meadows": "Meadow", "N": "North", "NORTH": "North", "N.W.": "Northwest", "NorthWest": "Northwest", "NW": "Northwest", "NE": "Northwest", "NorthEast": "Northwest", "parkway": "Parkway", "Parkway,": "Parkway", "Pkwy": "Parkway", "Pl": "Place", "place": "Place", "Pointe": "Point", "Pt": "Point", "RD": "Rd", "Rd.": "Rd", "ROAD": "Rd", "Road": "Rd", "RUN": "Run", "S": "South", "S.E.": "Southeast", "SE": "Southeast", "Shores": "SHR", "SW": "Southwest", "Spr": "Springs", "Spring": "Springs", "Sq": "Square", "St": "Street", "St.": "Street", "Ter": "Terrace", "Trce": "Trace", "Trl": "Trail", "Vw": "View", "way": "Way", "West": "W", "Wood": "Woods" } def is_street_name(elem): return (elem.tag == "tag") and (elem.attrib['k'] == "addr:street") def fix_street_name(value): m = street_type_re.search(value) if m: street_type = m.group() if (STREET_NAMES_FIX.has_key(street_type)): return value.replace(street_type, STREET_NAMES_FIX.get(street_type)) # return street_type_re.sub(STREET_NAMES_FIX.get(street_type),value) else: return value else: return value def shape_element(element, node_attr_fields=NODE_FIELDS, way_attr_fields=WAY_FIELDS, problem_chars=PROBLEMCHARS, default_tag_type='regular'): """Clean and shape node or way XML element to Python dict""" node_attribs = {} way_attribs = {} way_nodes = [] tags = [] # Handle secondary tags the same way for both node and way elements # Node tag if element.tag == 'node': dict = {} for key in node_attr_fields: # node_attribs[key] = element.attrib[key] if problem_chars.search(element.attrib[key]): node_attribs[key] = element.attrib[key] else: node_attribs[key] = element.attrib[key] for child in element.findall('tag'): tag = {} tag["id"] = element.attrib["id"] split_key = child.attrib["k"].split(":", 1) if len(split_key) == 2: tag["type"] = split_key[0] tag["key"] = split_key[1] else: tag["type"] = default_tag_type tag["key"] = split_key[0] if (is_street_name(child)): tag["value"] = fix_street_name(child.attrib["v"]) else: tag["value"] = child.attrib["v"] tags.append(tag) # Way tag if element.tag == 'way': for key in way_attr_fields: # way_attribs[key]= element.attrib[key] if problem_chars.search(element.attrib[key]): way_attribs[key] = element.attrib[key] else: way_attribs[key] = element.attrib[key] for child in element.findall('tag'): tag = {} tag["id"] = element.attrib["id"] split_key = child.attrib["k"].split(":", 1) if len(split_key) == 2: tag["type"] = split_key[0] tag["key"] = split_key[1] else: tag["type"] = default_tag_type tag["key"] = split_key[0] if (is_street_name(child)): tag["value"] = fix_street_name(child.attrib["v"]) else: tag["value"] = child.attrib["v"] tags.append(tag) position = 0 for ndref in element.findall('nd'): way_node = {} way_node['id'] = element.attrib['id'] way_node['node_id'] = ndref.attrib['ref'] way_node['position'] = len(way_nodes) way_nodes.append(way_node) # position += 1 if element.tag == 'node': return {'node': node_attribs, 'node_tags': tags} elif element.tag == 'way': return {'way': way_attribs, 'way_nodes': way_nodes, 'way_tags': tags} # ================================================== # # Helper Functions # # ================================================== # def get_element(osm_file, tags=('node', 'way', 'relation')): """Yield element if it is the right type of tag""" context = ET.iterparse(osm_file, events=('start', 'end')) _, root = next(context) for event, elem in context: if event == 'end' and elem.tag in tags: yield elem root.clear() def validate_element(element, validator, schema=SCHEMA): """Raise ValidationError if element does not match schema""" if validator.validate(element, schema) is not True: field, errors = next(validator.errors.iteritems()) message_string = "\nElement of type '{0}' has the following errors:\n{1}" error_string = pprint.pformat(errors) raise Exception(message_string.format(field, error_string)) class UnicodeDictWriter(csv.DictWriter, object): """Extend csv.DictWriter to handle Unicode input""" def writerow(self, row): super(UnicodeDictWriter, self).writerow({ k: (v.encode('utf-8') if isinstance(v, unicode) else v) for k, v in row.iteritems() }) def writerows(self, rows): for row in rows: self.writerow(row) # ================================================== # # Main Function # # ================================================== # def process_map(file_in, validate): """Iteratively process each XML element and write to csv(s)""" with codecs.open(NODES_PATH, 'w') as nodes_file, \ codecs.open(NODE_TAGS_PATH, 'w') as nodes_tags_file, \ codecs.open(WAYS_PATH, 'w') as ways_file, \ codecs.open(WAY_NODES_PATH, 'w') as way_nodes_file, \ codecs.open(WAY_TAGS_PATH, 'w') as way_tags_file: nodes_writer = UnicodeDictWriter(nodes_file, NODE_FIELDS) node_tags_writer = UnicodeDictWriter(nodes_tags_file, NODE_TAGS_FIELDS) ways_writer = UnicodeDictWriter(ways_file, WAY_FIELDS) way_nodes_writer = UnicodeDictWriter(way_nodes_file, WAY_NODES_FIELDS) way_tags_writer = UnicodeDictWriter(way_tags_file, WAY_TAGS_FIELDS) nodes_writer.writeheader() node_tags_writer.writeheader() ways_writer.writeheader() way_nodes_writer.writeheader() way_tags_writer.writeheader() validator = cerberus.Validator() count = 0 for element in get_element(file_in, tags=('node', 'way')): count += 1 print element.tag + str(count) el = shape_element(element) if el: if validate is True: validate_element(el, validator) if element.tag == 'node': nodes_writer.writerow(el['node']) node_tags_writer.writerows(el['node_tags']) elif element.tag == 'way': ways_writer.writerow(el['way']) way_nodes_writer.writerows(el['way_nodes']) way_tags_writer.writerows(el['way_tags']) if __name__ == '__main__': # Note: Validation is ~ 10X slower. For the project consider using a small # sample of the map when validating. process_map(OSM_PATH, validate=False) <file_sep>/AuditPostalCode.py #!/usr/bin/env python # -*- coding: utf-8 -*- import xml.etree.cElementTree as ET from collections import defaultdict import re osm_file = open("sample.osm", "r") postalcode_type_re = re.compile(r'\S+\.?$', re.IGNORECASE) postalcode_types = defaultdict(int) # Adds the postalcodes to dictionary def audit_postalcode_type(postalcode_types, postal_code): postalcode_types[postal_code] += 1 # sorting keys in dictionary def print_sorted_dict(d): keys = d.keys() keys = sorted(keys, key=lambda s: s.lower()) for k in keys: v = d[k] print "%s: %d" % (k, v) # function returns if it's a tag and key is addr:postcode def is_postcode(elem): return (elem.tag == "tag") and (elem.attrib['k'] == "addr:postcode") # Auditing on osm file def audit(): for event, elem in ET.iterparse(osm_file): if is_postcode(elem): audit_postalcode_type(postalcode_types, elem.attrib['v']) print_sorted_dict(postalcode_types) if __name__ == '__main__': audit()
316ee4df27b9ee2446353b0f3093aa8dc210827c
[ "Python" ]
2
Python
anushac5318/DataWranglingProject
5f6529681dbb2a6a33f2ba519a8d09bbdaafeadf
ce68a1fd081eafe3837f0e6a560877aba29b7bb3
refs/heads/master
<repo_name>brancz/vulnweb<file_sep>/Vagrantfile # -*- mode: ruby -*- # vi: set ft=ruby : coreos_linux_update_channel = "alpha" # All Vagrant configuration is done below. The "2" in Vagrant.configure # configures the configuration version (we support older styles for # backwards compatibility). Please don't change it unless you know what # you're doing. Vagrant.configure("2") do |config| # always use Vagrant's insecure key config.ssh.insert_key = false config.vm.box = "coreos-%s" % coreos_linux_update_channel config.vm.box_version = ">= 766.0.0" config.vm.box_url = "http://%s.release.core-os.net/amd64-usr/current/coreos_production_vagrant.json" % coreos_linux_update_channel # plugin conflict if Vagrant.has_plugin?("vagrant-vbguest") then config.vbguest.auto_update = false end config.vm.define vm_name = "rkt-machine" do |machine| machine.vm.hostname = vm_name machine.vm.provider :virtualbox do |vb| vb.cpus = 1 vb.gui = false vb.memory = 2048 end machine.vm.network :private_network, ip: "172.17.5.100" machine.vm.synced_folder "_output/", "/vagrant" end end <file_sep>/README.md # Vulnweb > Note these steps are written as an example using the `Vagrantfile` within > this repository. So to use these exact commands using vagrant is > recommended. Compile (outside of vagrant, this requires a Go compiler) make build From now on everything is inside of vagrant. We start the vulnerable web application. sudo rkt run quay.io/brancz/vulnweb-amd64 --net=host Normal behaviour/traffic our application would receive: curl -XPOST --data '{"hello":"world","from":"rkt"}' 172.17.5.100:5001 Oh but we have this remote execution vulnerability which let's us execute arbitrary commands: curl -XPOST --data '{"hello":"world","from":"rkt"}' 172.17.5.100:5001?exec=/bin/true Oh noes! rkt to the rescue: When starting normally we can exploit the "remote execution" vulnerability, but using `seccomp` support in rkt we can explicitly whitelist or blacklist system calls. First the non recommended way (in terms of security) of blacklisting syscalls: sudo rkt run quay.io/brancz/vulnweb-amd64 --net=host --seccomp mode=remove,getpid,pipe2 And then the better way of only allowing the syscalls that we know we need. For that we use: ``` strace -c /vagrant/bin/linux/amd64/vulnweb ``` Then perform our expected/normal behavior on the application: curl -XPOST --data '{"hello":"world","from":"rkt"}' 172.17.5.100:5001 And we get a statistic of which syscalls were used how often. ``` % time seconds usecs/call calls errors syscall ------ ----------- ----------- --------- --------- ---------------- 0.00 0.000000 0 6 1 read 0.00 0.000000 0 2 write 0.00 0.000000 0 5 close 0.00 0.000000 0 8 mmap 0.00 0.000000 0 1 munmap 0.00 0.000000 0 114 rt_sigaction 0.00 0.000000 0 6 rt_sigprocmask 0.00 0.000000 0 4 socket 0.00 0.000000 0 3 bind 0.00 0.000000 0 1 listen 0.00 0.000000 0 2 getsockname 0.00 0.000000 0 9 setsockopt 0.00 0.000000 0 2 clone 0.00 0.000000 0 1 execve 0.00 0.000000 0 2 sigaltstack 0.00 0.000000 0 1 arch_prctl 0.00 0.000000 0 1 gettid 0.00 0.000000 0 3 futex 0.00 0.000000 0 1 sched_getaffinity 0.00 0.000000 0 5 epoll_wait 0.00 0.000000 0 3 epoll_ctl 0.00 0.000000 0 1 openat 0.00 0.000000 0 3 2 accept4 0.00 0.000000 0 1 epoll_create1 ------ ----------- ----------- --------- --------- ---------------- 100.00 0.000000 185 3 total ``` > Note: the `execve` entry above is due to `strace` itself and can be omitted from the whitelist. Now that we know that list of syscalls we can use it to start our applicaton with: sudo rkt run quay.io/brancz/vulnweb-amd64 --net=host --seccomp mode=retain,errno=EPERM,read,write,close,mmap,munmap,rt_sigaction,rt_sigprocmask,socket,bind,listen,getsockname,setsockopt,clone,sigaltstack,arch_prctl,gettid,futex,sched_getaffinity,epoll_wait,epoll_ctl,openat,accept4,epoll_create1 <file_sep>/Makefile all: build OS=linux ARCH=amd64 BIN=vulnweb REPO=quay.io/brancz/vulnweb TAG=latest build: mkdir -p _output/bin/$(OS)/$(ARCH) GOOS=$(OS) GOARCH=$(ARCH) CGO_ENABLED=0 go build --installsuffix cgo --ldflags="-s" -o _output/bin/$(OS)/$(ARCH)/$(BIN) container: build @sed \ -e 's|ARG_OS|$(OS)|g' \ -e 's|ARG_ARCH|$(ARCH)|g' \ -e 's|ARG_BIN|$(BIN)|g' \ Dockerfile.in > .dockerfile-$(ARCH) docker build -f .dockerfile-$(ARCH) -t $(REPO)-$(ARCH):$(TAG) . .PHONY: all build
d5527e9e7bb9299fb2cbb63ff3feaae50b9631dc
[ "Markdown", "Ruby", "Makefile" ]
3
Ruby
brancz/vulnweb
da9c5dec92a4c3cf4b3776b2c82dd63d19006a8d
1e7d27b68765d795749e022a4eef31d1c23e4f9f
refs/heads/master
<file_sep>package runescape; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.DisplayMode; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.GridLayout; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.UIManager; /* Currently testing to see if screen DPI is going to cause an issue with the program... How could I fix it? * Personal notes: * Laptop - 144DPI, 1920x1080 * Desktop - 96DPI, 1920x1080 * 8 pixel difference on the Y axis will set it properly... * * */ public class RunescapeUI extends JFrame { /** Don't ask why serialVersionUID exists... Eclipse told me I should include it. * */ private static final long serialVersionUID = -9153255398948721284L; ClassLoader cl = this.getClass().getClassLoader(); public ImageIcon runescapeLoginIntro = new ImageIcon(cl.getResource("runescape/images/rsLogin.jpg")); // Get the resource of the rsLogin public ImageIcon rsLgn = new ImageIcon(cl.getResource("runescape/images/rsLogin2.png")); JLabel bg = new JLabel(runescapeLoginIntro); JButton loginButton, newAccountButton, searchButton, creditsButton; JTextField lookUp; final int offset = getScreenResolution(); final int frameWidth = 765; final int frameHeight = 540 - offset; final Dimension dm = new Dimension(135, 35); public RunescapeUI() { Container content = this; //debugScreenResolution(); debugMousePosition(this); setDefaultLookAndFeelDecorated(true); lookUp = new JTextField(); loginButton = new JButton(); searchButton = new JButton(); newAccountButton = new JButton(); creditsButton = new JButton(); // creditsButton always shown creditsButton.setOpaque(true); creditsButton.setBorderPainted(false); creditsButton.setContentAreaFilled(false); creditsButton.setFocusable(false); creditsButton.setLocation(frameWidth - 756, frameHeight - (38 + offset)); creditsButton.setSize(91, 30); // First original display loginButton.setLocation(frameWidth - 370, frameHeight - (231 + offset)); loginButton.setSize(dm); newAccountButton.setLocation(frameWidth - 529, frameHeight - (230 + offset)); newAccountButton.setSize(dm); // Buttons that show up after you click loginButton searchButton.setLocation(frameWidth - 442, frameHeight - (204 + offset)); searchButton.setSize(dm); lookUp.setLocation(frameWidth - 425, frameHeight - (285 + offset)); lookUp.setSize(125, 20); searchButton.setOpaque(false); searchButton.setBackground(Color.black); searchButton.setBorderPainted(false); searchButton.setContentAreaFilled(false); searchButton.setVisible(false); searchButton.setFocusable(false); lookUp.setOpaque(true); lookUp.setBackground(new Color(72, 75, 84)); lookUp.setForeground(Color.white); lookUp.setBorder(BorderFactory.createEmptyBorder()); lookUp.setVisible(false); lookUp.setFocusable(true); newAccountButton.setOpaque(false); newAccountButton.setBorderPainted(false); newAccountButton.setContentAreaFilled(false); newAccountButton.setBackground(Color.black); newAccountButton.setFocusable(false); loginButton.setOpaque(false); loginButton.setBackground(Color.BLACK); loginButton.setBorderPainted(false); loginButton.setContentAreaFilled(false); loginButton.setFocusable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setResizable(false); // Don't allow the frame to be resized, we don't want it to distort the login picture getContentPane().add(loginButton); getContentPane().add(newAccountButton); getContentPane().add(lookUp); getContentPane().add(bg); // Add the runescape login picture to the frame getContentPane().add(searchButton); getContentPane().add(creditsButton); bg.setSize(this.getSize().width, this.getSize().height); setComponentZOrder(searchButton, 0); setComponentZOrder(loginButton, 0); setComponentZOrder(lookUp, 0); setComponentZOrder(newAccountButton, 0); setComponentZOrder(creditsButton, 0); setComponentZOrder(bg, 1); setSize(frameWidth, frameHeight); // Don't change this! This is the perfect size for the rsLogin picture! creditsButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(content, "Credits: " + "\n" + "<NAME> - Lead Developer, only developer."); } }); loginButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //Execute when button is pressed System.out.println("Registered existing character click..."); newAccountButton.setEnabled(false); newAccountButton.setVisible(false); loginButton.setEnabled(false); loginButton.setVisible(false); bg.setIcon(rsLgn); lookUp.setIgnoreRepaint(true); lookUp.setVisible(true); lookUp.requestFocusInWindow(); searchButton.setVisible(true); } }); lookUp.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if(key == KeyEvent.VK_ENTER && !lookUp.getText().isEmpty()) { try { RunescapeCharacter.readStats(lookUp.getText().toLowerCase().toString()); } catch (Throwable e1) { // TODO Auto-generated catch block e1.printStackTrace(); } lookUp.setText(""); lookUp.requestFocusInWindow(); } } }); searchButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("Ayy!"); if(lookUp.getText().isEmpty()) { System.out.println("There should be text here!"); } if(lookUp.getText() == null) { System.out.println("They need to enter text here!"); } else { if(lookUp.getText().contains(" ")) { System.out.println("No spaces are allowed!"); } else if(lookUp.getText().isEmpty()) { System.out.println("You need text here!"); } else { System.out.println("Text in box: " + lookUp.getText().toString()); try { RunescapeCharacter.readStats(lookUp.getText().toLowerCase().toString()); lookUp.setText(""); } catch (Throwable e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } } }); newAccountButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("Character import..."); newAccountButton.setEnabled(false); newAccountButton.setVisible(false); loginButton.setEnabled(false); loginButton.setVisible(false); } }); } private int getScreenResolution() { int screenResolution = Toolkit.getDefaultToolkit().getScreenResolution(); int offset; if(screenResolution == 144) { offset = 0; } else { offset = (144 - screenResolution) / 6; } return offset; } private static void debugScreenResolution() { final JFrame box = new JFrame("Screen Res."); box.setAlwaysOnTop(true); box.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); box.setSize(600, 100); box.setLayout(new GridLayout(1,3)); box.setVisible(true); int screenRes = Toolkit.getDefaultToolkit().getScreenResolution(); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); JLabel wid = new JLabel("Width: " + String.valueOf(screenSize.getWidth())); JLabel hei = new JLabel("Height: " + String.valueOf(screenSize.getHeight())); JLabel res = new JLabel("Resolution: " + String.valueOf(screenRes)); box.add(wid); box.add(hei); box.add(res); } /** Debug frame for getting the mouse information. Not intended to have in final project. * @param frame */ private static void debugMousePosition(JFrame frame) { final JFrame box = new JFrame("Mouse Position"); box.setAlwaysOnTop(true); box.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); box.setLocation(frame.getX() + 800,frame.getY()); box.setSize(300, 100); box.setLayout(new GridLayout(1,2)); box.setVisible(true); final JLabel X = new JLabel(); final JLabel Y = new JLabel(); frame.addMouseMotionListener(new MouseAdapter() { public void mouseMoved(MouseEvent me) { X.setText(String.valueOf("X Position: " + me.getX())); Y.setText(String.valueOf("Y Position: " + me.getY())); box.repaint(); } }); box.add(X); box.add(Y); } public static void main(String[] args) { // TODO Auto-generated method stub try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Throwable e) { e.printStackTrace(); } SwingUtilities.invokeLater(new Runnable() { public void run() { new RunescapeUI().setVisible(true); } }); } } <file_sep>package vending_machine; import java.util.Arrays; public class VendingMachine { public int i=0; public int k=0; String[][] items; double[][] price; double moneyEntered = 0.00; VendingMachine() { items = new String[2][2]; //Set up each column in the 0th (technically 1st in real life) row items[0][0] = "Cool Ranch Doritos"; items[0][1] = "Sour Cream & Onion Lays"; //Set up each column in the 1st (technically 2nd in real life) row items[1][0] = "Extremely Unhealthy Food"; items[1][1] = "Totally Radical Healthy Food"; //End of items price = new double[2][2]; //Set up price for items in the 1st row price[0][0] = 2.00; price[0][1] = 2.00; //Set up price for items in the 2nd row price[1][0] = 4.00; price[1][1] = 4.00; //End of price moneyEntered = 0.00; } VendingMachine(int NUM_OF_ROWS, int NUM_OF_COLUMNS) { items = new String[NUM_OF_ROWS][NUM_OF_COLUMNS]; //Item defining done here //End of items price = new double[NUM_OF_ROWS][NUM_OF_COLUMNS]; //Pricing for each item done here //End of price moneyEntered = 0.00; } //Setters void addOrChangeItem(int row, int column, String itemName, double itemPrice) { if(items[row][column] == null) { System.out.println("This element appears to be empty... Continuing"); items[row][column] = itemName; price[row][column] = itemPrice; System.out.println("New item added at "+row+","+column+" with the price of: $"+itemPrice); } else { System.out.println("Replacing " + items[row][column] + " (cost: $" + price[row][column] + ")" + " with " + itemName + " (cost: $" + itemPrice + ")"); items[row][column] = itemName; price[row][column] = itemPrice; } } void changePrice(int row, int column, double itemPrice) { if(items[row][column] != null) { System.out.println("Changing the price of " + items[row][column] + " to $" + itemPrice); price[row][column] = itemPrice; } } void enterMoney(double m) { moneyEntered = m; } void chooseFood(int row, int column) { if(moneyEntered >= price[row][column]) { System.out.println("You chose " + items[row][column] + " which has a price of $" + price[row][column]); moneyEntered-= price[row][column]; System.out.println("Enjoy!"); } else if (moneyEntered < price[row][column]) { System.out.println("You don't have enough money for this! The price of this item is " + price[row][column] + " Current money in the machine: $" + moneyEntered); } } //Getters void getFoodsAndPrices() { for(i = 0; i < 2; i++) { for(k = 0; k < 2; k++) { System.out.println("Price of " + items[i][k] + " is: " + "$" +price[i][k]); } } } void getMoneyEntered() { System.out.println("There is currently $" + moneyEntered + " in this machine."); } } <file_sep>package guitar_class; import javax.swing.JOptionPane; public class Guitar_tester { public static void main(String[] args) { // TODO Auto-generated method stub Guitar poptun = new Guitar(); Guitar bubby = new Guitar("Fender","Stratocaster","Cherry Red",'f'); System.out.println(poptun); System.out.println(bubby); JOptionPane.showMessageDialog(null,bubby); } } <file_sep>package guitar_class; /*Program: Guitar.java *Purpose: Class to create Guitar objects *Programmers: <NAME>, <NAME>, <NAME> * */ public class Guitar { String brand, make, color; static int num_strings = 6; char tuning; public Guitar() { brand = " "; make = " "; color = " "; num_strings = 6; tuning = 'E'; } public Guitar(String b, String m, String c, char t) { brand = b; make = m; color = c; num_strings = 6; tuning = t; } public Guitar(String b, String m, String c) { brand = b; make = m; color = c; num_strings = 6; tuning = 'E'; } public Guitar(String b, String m) { brand = b; make = m; color = "Black"; num_strings = 6; tuning = 'E'; } @Override public String toString() { return "Guitar [brand=" + brand + ", make=" + make + ", color=" + color + ", tuning=" + tuning + "]"; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getMake() { return make; } public void setMake(String make) { this.make = make; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public static int getNum_strings() { return num_strings; } public static void setNum_strings(int num_strings) { Guitar.num_strings = num_strings; } public char getTuning() { return tuning; } public void setTuning(char tuning) { this.tuning = tuning; } } <file_sep>/* keyin Programmer: <NAME> Program: BasicArray Purpose: This program illustrates how basic 1-D arrays work and some of the manipulations you can do with them. One thing to note is the use of the word 'static' in front of those methods... */ import javax.swing.*; public class BasicArray { // Notice I am not calling this method toString, but // instead I am calling it aString and sending it an array // as a parameter. I can't override the toString method if // I write methods this way. public static String aString(int[] a) { String result = ""; for(int i = 0; i<a.length; i++) { result += a[i] + " "; } System.out.println(result); return result; } // This method sorts an array (a) and returns it all // sorted in order (see questions below...) // See the document for other sorting techniques public static int[] sort(int[] a) { int i,j; int temp; // crucial! for(i = 0; i<a.length-1; i++) { for(j = i+1; j<a.length; j++) { if(a[j] < a[i]) { temp = a[j]; a[j] = a[i]; a[i] = temp; } } } return a; }//end sort method public void greaterThan(Object j) { if((j.getClass().getName()).equals("String")); } public static void main(String[] args) { String[] Name = { "Seymore Code", "Ima Coder", "<NAME>" , "<NAME>", "Doyour Best"}; int[] grades = {98, 88, 87, 90, 92}; String searchName = " ";//initializing int correspondingGrade = -1; //initializeing int total=0, ave=0; int[] sorted = new int[grades.length]; searchName = JOptionPane.showInputDialog(null, "Name: "); while(!searchName.equals("q")) { // reinitializing everything total = 0; ave = 0; // To search a parallel array: for(int i = 0; i < Name.length; i++) { if(searchName.equals(Name[i])) { correspondingGrade = grades[i]; break; } } if(correspondingGrade == -1) { JOptionPane.showMessageDialog(null,"Sorry I didn't find that one! Check spelling."); }else { JOptionPane.showMessageDialog(null,searchName + "'s grade is " + correspondingGrade); // If you want to sum up all of the integers in an array: for(int j = 0; j<grades.length;j++) { total += grades[j]; } ave = total/grades.length; JOptionPane.showMessageDialog(null, "The average is: " + ave); sorted = sort(grades); JOptionPane.showMessageDialog(null, "Sorted grades: " + aString(sorted)); }// end else searchName = JOptionPane.showInputDialog(null, "Name (q to quit): "); }// end while } } /* 1. Take this program and write the following 4 methods: a. copy(int[] original) This method will accept as a parameter an integer array and return a copy of that array. b. sum(int[] a) This method will sum up the elements of the array sent to it and return the value of the sum. c. search(int[] a, int value) This method will search the array a for the integer value given and return the index location of the given value. d. getLarge(int[] a) This method will return the larges value found in the(unsorted) array given. 2. Change this program so that you can fill in the names by asking the user to enter the names. Create an array that can hold up to 5 names. have the user enter the names to fill in the array. What is a potential problem with setting up an array this way? 3. Does the sort method sort in ascending or descending order? 4. What is the meaning of the key word static? why am I using it here? What would happen if I didn't use it? ** Make sure to look at the Searching and Sorting document in this module */<file_sep>package rational; public class Rational_tester { public static void main(String[] args) { // TODO Auto-generated method stub Rational r = new Rational(1, 3); Rational x = new Rational(10, 2); System.out.println(r); //r.setNumerator(872); //r.setDenominator(8); System.out.println(r.add(x)); System.out.println(r.subtract(x)); System.out.println(r.multiply(x)); System.out.println("Rational: (" + r + ") / (" + x + ") = " + r.divide(x)); System.out.println("Rational: (" + r + ") as double: " + r.toDouble()); } } <file_sep>import javax.swing.JOptionPane; public class bankTeller { // Scrum idea: /* Bank Teller program --------- * Pre-Planning: make a list of pins, and give a balance to them to use * 1. ask the user for their pin * 2. check to see if the pin exists, if it does, find the variable associated with it * 3. allow them to deposit, withdraw from their account * */ private static double account_balance; private static int pin; public static int[] getUsersList() { int[] user = {1234, 2019, 2100, 1900, 1111, 0000}; return user; } public static double[] getBalanceList() { double[] balance = {200, 5, 100, 10000, 1241.21, 5000}; return balance; } public static void getPin() { boolean invalid_format = true; while(invalid_format) { String input = JOptionPane.showInputDialog("Please enter your Personal Identification Number","Enter your PIN"); if(input==null) { System.exit(0); } try { pin = Integer.parseInt(input); invalid_format = false; } catch(NumberFormatException e) { JOptionPane.showMessageDialog(null,"I'm sorry, but it appears you did not enter a pin in the form of an integer.","Error",JOptionPane.ERROR_MESSAGE); } } setPin(pin); } public static void setPin(int p) { pin = p; } public static void welcome() { JOptionPane.showMessageDialog(null,"Good day! Welcome to the Bank of Middleton","Welcome!",JOptionPane.PLAIN_MESSAGE); } public static void preCheck() { getPin(); boolean noPin = false; int i = 0; int[] users = getUsersList(); double account_balance = 0.0; double[] balance = getBalanceList(); JOptionPane.showMessageDialog(null,"Thank you for entering your pin, please hold while we check to see if your pin is correct...","Please Wait...",JOptionPane.PLAIN_MESSAGE); for(i=0;i<users.length;i++) { if(users[i] == pin) { account_balance=balance[i]; noPin = false; break; } else { noPin = true; } } if(noPin == true) { JOptionPane.showMessageDialog(null,"It apppears that you have entered a pin that does not exist in our database. Try again.","Error",JOptionPane.ERROR_MESSAGE); preCheck(); } setBalance(account_balance); createGUI(); } public static void setBalance(double a) { account_balance = a; } public static void createGUI() { Object[] choices = {"Deposit","Withdraw","Go Back"}; int choice = JOptionPane.showOptionDialog(null,"Hello! What would you like to do with your account?"+"\nYour current balance is: $"+account_balance,"Account",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE,null,choices,choices[0]); if(choice==0) // User has chosen deposit { deposit(account_balance); JOptionPane.showMessageDialog(null,"Your new balance: $"+account_balance,"Balance",JOptionPane.PLAIN_MESSAGE); } else if(choice==1) { withdraw(account_balance); JOptionPane.showMessageDialog(null,"Your new balance is: $"+account_balance,"Balance",JOptionPane.PLAIN_MESSAGE); } else if(choice==2) { account_balance = 0; pin = 0; preCheck(); } else { System.exit(0); } } public static void deposit(double user_input) { double addMoney=checkNumber(user_input,"add"); account_balance+=addMoney; createGUI(); } public static void withdraw(double user_input) { double removeMoney=checkNumber(user_input,"remove"); if(removeMoney > account_balance) { JOptionPane.showMessageDialog(null,"I'm sorry, but you cannot withdraw more than you have in your account","Error",JOptionPane.ERROR_MESSAGE); withdraw(account_balance); } else { account_balance-=removeMoney; createGUI(); } } public static double checkNumber(double user_input,String addOrRemove) { boolean invalid = true; double changeMoney = 0; while(invalid) { String input = JOptionPane.showInputDialog(null, "How much money would you like to "+ addOrRemove +" to your account?",addOrRemove+" Money",JOptionPane.PLAIN_MESSAGE); try { changeMoney = Double.parseDouble(input); invalid = false; } catch(NumberFormatException e) { JOptionPane.showMessageDialog(null,"Sorry, you did not enter a proper number.","Error",JOptionPane.ERROR_MESSAGE); } } changeMoney = Math.abs(changeMoney); return changeMoney; } public static void main(String[] args) { // TODO Auto-generated method stub welcome(); preCheck(); } } <file_sep>package runescape; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; import javax.swing.JOptionPane; /* Purpose: This class is meant to allow the creation of a RunescapeCharacter and to store it in a text file with BufferedStreams * */ public class RunescapeCharacter extends RunescapeConstants { /** * @param n - Username * @param statLevels - An ArrayList that accepts only integers, one for every skill * @throws Throwable - Throws exception if you use too many integers for the stats */ RunescapeCharacter(String n, ArrayList<Integer> statLevels) throws Throwable { super(); name = n; int j = stats.size(); for(int i = 0; i < j; i++) { //System.out.println("Array is passed the same amount of arguments as the allowed combat skills! (This is good)"); if(stats.containsKey(combatNames[i].toLowerCase())) { stats.put(combatNames[i].toLowerCase(), statLevels.get(i)); //System.out.println(stats.get(combatNames[i].toLowerCase())); } } this.checkLevel(); } public String getCombatLevel() { String output = ""; double temp = calculateFinalLevel(); output = "Your total combined stats will give you: " + temp + " combat."; return output; } public RunescapeCharacter getCharacter() { RunescapeCharacter a = this; return a; } /** Similar to String.toString() but using our own set of information * @return output - String that comprises of the username + stats for that object */ public String dataToString() { String username = this.getUser(); String stats = this.getStats(); String output = username + stats.toString(); return output; } /** Method to create a file in the location of the class, usually found in ..\bin\stats.txt * * */ public static void createFile() { // TODO Auto-generated method stub try { //Get information from here and store it statFile = new File(getPath() + "stats.txt"); if(statFile.isFile() && !statFile.isDirectory()) { System.out.println("This already exists.."); } else if(!statFile.exists()) { System.out.println("Ayy this doesn't exist"); statFile.createNewFile(); } } catch(IOException e) { e.printStackTrace(); } //End of File Creation Segment } /** Writes to the stats.txt file, with the given information of the object. * @throws Throwable * */ public void writeStats() throws Throwable { /* Attempt to gather information about statistics and apply them here... */ try { String info = this.dataToString(); System.out.println("Information attempting to place: " + info); Scanner s = new Scanner(statFile); FileWriter fw = new FileWriter(statFile.getAbsolutePath(), true); FileReader fr = new FileReader(statFile.getAbsolutePath()); BufferedWriter bw = new BufferedWriter(fw); BufferedReader br = new BufferedReader(fr); String line = null; if(statFile.length() == 0) { bw.write(info); } while(s.hasNextLine() && (line = s.nextLine()) != null) { if(line.equalsIgnoreCase(info) && s.hasNextLine()) { break; } else if(!line.equalsIgnoreCase(info) && !s.hasNextLine()) { bw.newLine(); bw.write(info); } else if(line.equalsIgnoreCase(info) && s.hasNextLine()) { break; } } s.close(); br.close(); fr.close(); bw.close(); fw.close(); } catch(IOException e) { e.printStackTrace(); } readStats(); } /** Reads in from the stats.txt file, creates a new list that includes every line, which contains our character information * @throws Throwable */ public static void readStats() throws Throwable { try { Scanner s = new Scanner(statFile); String line = null; list = new ArrayList<String>(); BufferedReader br = new BufferedReader(new FileReader(statFile)); while(s.hasNextLine() && (line = s.nextLine()) != null) { if(list.contains(line)) { System.out.println("This entry is already in list!"); } else { list.add(line); } } br.close(); System.out.println("List size: " + list.size()); s.close(); } catch(IOException e) { e.printStackTrace(); } } public static void readStats(String text) throws Throwable { try { Scanner s = new Scanner(new File(getPath() + "stats.txt")); String data = null; String line = null; while(s.hasNextLine() && (line = s.nextLine()) != null) { if(line.toLowerCase().contains(text)) { data = line; break; } else { data = null; } } if(data == null) { JOptionPane.showMessageDialog(null, "No user was found!"); } else { System.out.println(data); parseStats(data); s.close(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static void parseStats(String data) throws Throwable { // TODO Auto-generated method stub String name = "Test"; int atk = 1; int str = 1; int def = 1; int range = 1; int pray = 1; int mage = 1; int hp = 10; name = data.substring(0, data.indexOf("{")); /* Start of long try-catch for each stat, no point in reading this, as this was the only way I could find to properly parse the information that I had * Starting with Attack */ try { atk = Integer.parseInt(data.substring(data.indexOf("attack=") + "attack=".length(), data.indexOf("attack=") + "attack=".length() + 2)); } catch(NumberFormatException e) { atk = Integer.parseInt(data.substring(data.indexOf("attack=") + "attack=".length(), data.indexOf("attack=") + "attack=".length() + 1)); } try { str = Integer.parseInt(data.substring(data.indexOf("strength=") + "strength=".length(), data.indexOf("strength=") + "strength=".length() + 2)); } catch(NumberFormatException e) { str = Integer.parseInt(data.substring(data.indexOf("strength=") + "strength=".length(), data.indexOf("strength=") + "strength=".length() + 1)); } try { def = Integer.parseInt(data.substring(data.indexOf("defense=") + "defense=".length(), data.indexOf("defense=") + "defense=".length() + 2)); } catch(NumberFormatException e) { def = Integer.parseInt(data.substring(data.indexOf("defense=") + "defense=".length(), data.indexOf("defense=") + "defense=".length() + 1)); } try { range = Integer.parseInt(data.substring(data.indexOf("range=") + "range=".length(), data.indexOf("range=") + "range=".length() + 2)); } catch(NumberFormatException e) { range = Integer.parseInt(data.substring(data.indexOf("range=") + "range=".length(), data.indexOf("range=") + "range=".length() + 1)); } try { pray = Integer.parseInt(data.substring(data.indexOf("prayer=") + "prayer=".length(), data.indexOf("prayer=") + "prayer=".length() + 2)); } catch(NumberFormatException e) { pray = Integer.parseInt(data.substring(data.indexOf("prayer=") + "prayer=".length(), data.indexOf("prayer=") + "prayer=".length() + 1)); } try { mage = Integer.parseInt(data.substring(data.indexOf("magic=") + "magic=".length(), data.indexOf("magic=") + "magic=".length() + 2)); } catch(NumberFormatException e) { mage = Integer.parseInt(data.substring(data.indexOf("magic=") + "magic=".length(), data.indexOf("magic=") + "magic=".length() + 1)); } try { hp = Integer.parseInt(data.substring(data.indexOf("hitpoints=") + "hitpoints=".length(), data.indexOf("hitpoints=") + "hitpoints=".length() + 2)); } catch(NumberFormatException e) { hp = Integer.parseInt(data.substring(data.indexOf("hitpoints=") + "hitpoints=".length(), data.indexOf("hitpoints=") + "hitpoints=".length() + 1)); } RunescapeCharacter temp = new RunescapeCharacter(name, new ArrayList<Integer>(Arrays.asList(atk,str,def,range,pray,mage,hp))); String combatLevel = temp.getCombatLevel(); JOptionPane.showMessageDialog(null,"Character Name: " + name + "\n" + "Stats" + "\n" + "-----------------------" + "\n" + "| Attack: " + atk + "\n" + "| Strength: " + str + "\n" + "| Defense: " + def + "\n" + "| Range: " + range + "\n" + "| Prayer: " + pray + "\n" + "| Magic: " + mage + "\n" + "| Hitpoints: " + hp + "\n" + "| " + combatLevel.trim() + "\n" + "-----------------------" + "\n"); } /** Parse the information that we found in the file, and makes a new RunescapeCharacter from the information found on each line. * @throws Throwable - NumberFormatException: if the input that is passed is unable to be parsed to an integer, it'll go ahead and search 1 space less than the previous search */ public static void parseStats() throws Throwable { String name = "Test"; int atk = 1; int str = 1; int def = 1; int range = 1; int pray = 1; int mage = 1; int hp = 10; for(int i = 0; i < list.size(); i++) { name = list.get(i).substring(0, list.get(i).indexOf("{")); /* Start of long try-catch for each stat, no point in reading this, as this was the only way I could find to properly parse the information that I had * Starting with Attack */ try { atk = Integer.parseInt(list.get(i).substring(list.get(i).indexOf("attack=") + "attack=".length(), list.get(i).indexOf("attack=") + "attack=".length() + 2)); } catch(NumberFormatException e) { atk = Integer.parseInt(list.get(i).substring(list.get(i).indexOf("attack=") + "attack=".length(), list.get(i).indexOf("attack=") + "attack=".length() + 1)); } try { str = Integer.parseInt(list.get(i).substring(list.get(i).indexOf("strength=") + "strength=".length(), list.get(i).indexOf("strength=") + "strength=".length() + 2)); } catch(NumberFormatException e) { str = Integer.parseInt(list.get(i).substring(list.get(i).indexOf("strength=") + "strength=".length(), list.get(i).indexOf("strength=") + "strength=".length() + 1)); } try { def = Integer.parseInt(list.get(i).substring(list.get(i).indexOf("defense=") + "defense=".length(), list.get(i).indexOf("defense=") + "defense=".length() + 2)); } catch(NumberFormatException e) { def = Integer.parseInt(list.get(i).substring(list.get(i).indexOf("defense=") + "defense=".length(), list.get(i).indexOf("defense=") + "defense=".length() + 1)); } try { range = Integer.parseInt(list.get(i).substring(list.get(i).indexOf("range=") + "range=".length(), list.get(i).indexOf("range=") + "range=".length() + 2)); } catch(NumberFormatException e) { range = Integer.parseInt(list.get(i).substring(list.get(i).indexOf("range=") + "range=".length(), list.get(i).indexOf("range=") + "range=".length() + 1)); } try { pray = Integer.parseInt(list.get(i).substring(list.get(i).indexOf("prayer=") + "prayer=".length(), list.get(i).indexOf("prayer=") + "prayer=".length() + 2)); } catch(NumberFormatException e) { pray = Integer.parseInt(list.get(i).substring(list.get(i).indexOf("prayer=") + "prayer=".length(), list.get(i).indexOf("prayer=") + "prayer=".length() + 1)); } try { mage = Integer.parseInt(list.get(i).substring(list.get(i).indexOf("magic=") + "magic=".length(), list.get(i).indexOf("magic=") + "magic=".length() + 2)); } catch(NumberFormatException e) { mage = Integer.parseInt(list.get(i).substring(list.get(i).indexOf("magic=") + "magic=".length(), list.get(i).indexOf("magic=") + "magic=".length() + 1)); } try { hp = Integer.parseInt(list.get(i).substring(list.get(i).indexOf("hitpoints=") + "hitpoints=".length(), list.get(i).indexOf("hitpoints=") + "hitpoints=".length() + 2)); } catch(NumberFormatException e) { hp = Integer.parseInt(list.get(i).substring(list.get(i).indexOf("hitpoints=") + "hitpoints=".length(), list.get(i).indexOf("hitpoints=") + "hitpoints=".length() + 1)); } JOptionPane.showMessageDialog(null,"Character Name: " + name + "\n" + "Stats" + "\n" + "-----------------------" + "\n" + "| Attack: " + atk + "\n" + "| Strength: " + str + "\n" + "| Defense: " + def + "\n" + "| Range: " + range + "\n" + "| Prayer: " + pray + "\n" + "| Magic: " + mage + "\n" + "| Hitpoints: " + hp + "\n" + "-----------------------" + "\n"); } } }<file_sep>package rational; public class UML_tester { public static void main(String[] args) { // TODO Auto-generated method stub } } <file_sep>package rational; /** * @author <NAME> * */ public class Rational { public int numerator; public int denominator; public int wholeNumber; /** Creates a rational object with a pre-specified numerator/denominator from the user * @param n - Integer to be assigned as the numerator * @param d - Integer to be assigned as the denominator */ Rational(int n, int d) { int g = gcd(n, d); numerator = n/g; denominator = d/g; if(denominator < 0) { denominator = -denominator; numerator = -numerator; } } //Methods /** Adds rational 'a' to rational 'b' * @param b - A rational that will be added to rational 'a' * @return Returns new object of rational a+b */ Rational add(Rational b) { Rational a = this; int n = (a.numerator * b.denominator) + (a.denominator * b.numerator); int d = (a.denominator * b.denominator); return new Rational(n, d); } /** Subtracts rational 'a' to rational 'b' * @param b - A rational that will be subtracted to rational 'a' * @return Returns new object of rational a-b */ Rational subtract(Rational b) { Rational a = this; int n = (a.numerator * b.denominator) - (a.denominator * b.numerator); int d = (a.denominator * b.denominator); return new Rational(n, d); } /** Multiply rational 'a' to rational 'b' * @param b - A rational that will multiply with rational 'a' * @return Returns new object of rational a*b */ Rational multiply(Rational b) { Rational a = this; Rational c = new Rational(a.numerator, b.denominator); Rational d = new Rational(b.numerator, a.denominator); return new Rational(c.numerator*d.numerator, c.denominator*d.denominator); } Rational reciprocal() { return new Rational(denominator, numerator); } /** Divide rational 'a' by rational 'b' * @param b - A rational that will divide rational 'a' * @return Returns new object of rational a/b */ Rational divide(Rational b) { Rational a = this; return a.multiply(b.reciprocal()); } /** * @param a * @param b * @return */ private static int gcd(int a, int b) { if(a<0) { a = -a; } if(b<0) { b = -b; } if(0 == b) { return a; } else return gcd(b, a%b); } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { if(denominator == 1) { return numerator + ""; } else { return numerator + "/" + denominator; } } /** * @return Returns rational as a double */ public double toDouble() { return (double) numerator/denominator; } /** * @return Returns the numerator as an integer */ public int getNumerator() { return this.numerator; } /** * @param numerator */ public void setNumerator(int n) { numerator = n; } /** * @return Returns the denominator as an integer */ public int getDenominator() { return this.denominator; } /** * @param denominator */ public void setDenominator(int d) { denominator = d; } /** * @return */ } <file_sep>package runescape; import java.util.ArrayList; import java.util.Arrays; public class RunescapeTester { /* Information to use this class: * This class is the tester for the RunescapeCharacter & RunescapeConstants classes */ // TODO Add proper interface to make adding characters easy... public static void main(String[] args) throws Throwable { // TODO Auto-generated method stub RunescapeCharacter.createFile(); RunescapeCharacter test2 = new RunescapeCharacter("Endlyng", new ArrayList<Integer>(Arrays.asList(20,13,11,2,8,17,18))); RunescapeCharacter test1 = new RunescapeCharacter("CammyJammy", new ArrayList<Integer>(Arrays.asList(4,46,45,54,43,52,48))); RunescapeCharacter test3 = new RunescapeCharacter("Urkchar", new ArrayList<Integer>(Arrays.asList(32,30,29,34,30,23,34))); RunescapeCharacter test4 = new RunescapeCharacter("IcyDice", new ArrayList<Integer>(Arrays.asList(20,20,19,1,8,2,21))); RunescapeCharacter.readStats(); RunescapeCharacter.parseStats(); } }
6cd1be278f655ac9258ea66c0ff6310808158563
[ "Java" ]
11
Java
liquidsystem/AP-Advanced-Programming
341d61505ad5d69d55f11cf8e11c7e88deb1ed7d
c5e180c401ababea4aaf83650bf09614e3f937db
refs/heads/master
<file_sep>import pandas as pd import matplotlib.pyplot as plt import re import math # # Data (csv file) downloaded from # # http://www.nasdaq.com/screening/company-list.aspx if __name__ == "__main__": # # read csv file df = pd.read_csv('companylist_nyse.csv') # df = pd.read_csv('companylist_nasdaq.csv') # # choose the field to analyze field = 'LastSale' # price # field = 'MarketCap' # market size # # the digit to look at (1st digit => 0) digit = 0 # # find the first (or second ...) non-zero digit pattern = r'[^1-9]' df['digit'] = map( lambda x: re.sub(pattern,'',str(x))[digit] if len(re.sub(pattern,'',str(x))) > digit else None, df[field]) ptable = df.pivot_table(field,rows='digit',aggfunc=len) # # normalize count prop_table = pd.DataFrame(ptable / ptable.sum()) # # probability according to Benford's Law prop_table['Benford Law'] = [math.log10(1+1.0/i) for i in range(1,10)] title_text = '{}{} Digit of {}'.format( digit+1, 'st' if digit==0 else 'nd' if digit==1 else 'rd' if digit==2 else 'th', field) prop_table.plot(kind='bar',title=title_text) plt.show() """Findings For NYSE and NASDAQ stocks: - The first digit of LastSale (price) and MarketCap (total market value) closely follow Benford's Law. - The only exception is the first digit of LastSale for NYSE stocks. Digit 2 seems to have much higher proportion (about double) than predicted by Benford's Law. - The second and third digits of LastSale and MarketCap roughly follow a uniform distribution, very different from Benford's Law. """ <file_sep># Python-practice Practice with Python This repo is my sandbox for Python programming. Code is organized by folder, which is listed here. ## Benford's Law I was introduced to this concept during the "Introduction to Data Science" class on Coursera. It is a very interesting proposition, so I decide to test it out using real world data. Data on stock price and market value (in csv format) come from [here](http://www.nasdaq.com/screening/company-list.aspx). Analyzing the data, it seems for NYSE and NASDAQ stocks: - The first digit of LastSale (price) and MarketCap (total market value) closely follow Benford's Law. - The only exception is the first digit of LastSale for NYSE stocks. Digit 2 seems to have much higher proportion (about double) than predicted by Benford's Law. - The second and third digits of LastSale and MarketCap roughly follow a uniform distribution, very different from Benford's Law.
7243605e434890bc7e79627cf62effa47aa91f0d
[ "Markdown", "Python" ]
2
Python
xuanyiguang/Python-practice
cfb8f70304f6c783b937fefc42ee484d67ce0cf5
a8f7288f595a9789bd6f74be992a5853696abf06
refs/heads/master
<file_sep>### @qietuzi/validate A js library for common regs,一个常用的正则库 ### Install && Use(安装&&使用) ``` npm i@qietuzi/validate --save ``` ```js import validate from '@qietuzi/validate' validate.isCellPhone(cellphone) // or import { isCellPhone } from '@qietuzi/validate' isCellPhone(cellphone) // or const validate = require('@qietuzi/validate') validate.isCellPhone(cellphone) ``` ### Main method(主要方法) **All methord return a boolean** **isQQ(input: string): boolean** Tencent qq number **isEmpty(input: string): boolean** **isIdNum(input: string): boolean** China id number **isZipCode(input: string): boolean** China zip code **isTelPhone(input: string): boolean** China telphone **isCellPhone(input: string): boolean** China cellphone <file_sep>import verify from '../src/index' describe('This is isEmpty', () => { let empty = '' let notEmpty = 'i am not empty' it('This is empty', () => { expect(verify.isEmpty(empty)).toBe(true) }) it('This is not empty', () => { expect(verify.isEmpty(notEmpty)).toBe(false) }) }) describe('This is phone', () => { let rightPhone = '18108127001' let errorPhone = 'not a phone' it('This is right phone', () => { expect(verify.isCellPhone(rightPhone)).toBe(true) }) it('This is error phone', () => { expect(verify.isCellPhone(errorPhone)).toBe(false) }) }) <file_sep>// isQQ const isQQ = function (input: string): boolean { return /\d{5,11}/.test(input) } // isEmpty const isEmpty = function (input: string): boolean { return !!!input } // isIdNum const isIdNum = function (input: string): boolean { return /^\d{15}|\d{18}$/.test(input) } // isEmail const isEmail = function (input: string): boolean { return /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/.test(input) } // isZipCode const isZipCode = function (input: string): boolean { return /^[1-9][0-9]{5}$/.test(input) } // isTelPhone const isTelPhone = function (input: string): boolean { return /([0-9]{3,4}-)?[0-9]{7,8}/.test(input) } // isCellPhone const isCellPhone = function (input: string): boolean { return /^1[3456789]\d{9}$/.test(input) } export { isQQ, isEmpty, isEmail, isIdNum, isZipCode, isTelPhone, isCellPhone, } export default { isQQ, isEmpty, isEmail, isIdNum, isZipCode, isTelPhone, isCellPhone, }<file_sep>declare const isQQ: (input: string) => boolean; declare const isEmpty: (input: string) => boolean; declare const isIdNum: (input: string) => boolean; declare const isEmail: (input: string) => boolean; declare const isZipCode: (input: string) => boolean; declare const isTelPhone: (input: string) => boolean; declare const isCellPhone: (input: string) => boolean; export { isQQ, isEmpty, isEmail, isIdNum, isZipCode, isTelPhone, isCellPhone, }; declare const _default: { isQQ: (input: string) => boolean; isEmpty: (input: string) => boolean; isEmail: (input: string) => boolean; isIdNum: (input: string) => boolean; isZipCode: (input: string) => boolean; isTelPhone: (input: string) => boolean; isCellPhone: (input: string) => boolean; }; export default _default;
3e20525b2ff920467eb04594465eb17386aab93a
[ "Markdown", "TypeScript" ]
4
Markdown
qiangqiang93/easy-verify
d0f341a5f8cdf07b3ce0f402ffe4655418533192
9318f0424c53f8f61e2e43f74c8ab936afbf13f8
refs/heads/master
<repo_name>divya-github18/PythonSelinumTesting<file_sep>/Tests1/conftest.py import pytest from selenium import webdriver from Config.config import TestData from Pages.LoginPage import LoginPage web_driver = None @pytest.fixture(params=["chrome"], scope='class') def init_driver(request): global web_driver if request.param == "chrome": web_driver = webdriver.Chrome(executable_path=TestData.CHROME_EXECUTABLE_PATH) web_driver.set_window_size(1552, 840) web_driver.delete_all_cookies() request.cls.driver = web_driver request.cls.loginPage = LoginPage(web_driver) yield web_driver.close() <file_sep>/utilities/BaseClass.py import inspect import logging import pytest from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.select import Select @pytest.mark.usefixtures("setup") class BaseClass: def verifyLinkPresence(self, text): element = WebDriverWait(self.driver, 10).until( EC.presence_of_element_located((By.LINK_TEXT, text))) def selectOptionByText(self,locator,text): sel = Select(locator) sel.select_by_visible_text(text) <file_sep>/PracticeExamples/pytestsDemo/test_demo1.py # Any pytest file should start with test_ or end with _test #pytest method names should start with test #Any code should be wrapped in method only import pytest @pytest.mark.smoke def test_firstProgram(setup): print("Hello") @pytest.mark.xfail def test_SecondGreetCreditCard(): print("Good Morning") def test_crossBrowser(crossBrowser): print(crossBrowser[1]) <file_sep>/venv/Lib/site-packages/python_basics/exceptions.py def exception(): print('It is used for not to crash your computer when an error is occur') <file_sep>/PyTestDemo/test_fixtures.py import pytest @pytest.fixture def input_value(): input1 = 39 return input1 def test_divisible_by_3(input_value): assert input_value % 3 == 0 @pytest.mark.skip def test_divisible_by_6(input_value): assert input_value % 6 == 0 @pytest.mark.login def test_login_fb_insta(): assert "admin" == "admin123"<file_sep>/PyTestDemo/test_webpage_fun.py import pytest from selenium import webdriver import time print("test case started") driver = None @pytest.fixture(scope="module") def fun(): global driver print("---driver set up method---") driver = webdriver.Chrome(r"C:\Users\dboyapalli\PycharmProjects\pythonProject\Browsers\chromedriver.exe") yield print("---driver tear down method---") driver.quit() @pytest.mark.usefixtures("fun") def test_open_google(): driver.get("https://www.google.com/") assert driver.title == "Google" time.sleep(2) @pytest.mark.usefixtures("fun") def test_open_fb(): driver.get("https://www.facebook.com/") assert driver.title == "Facebook – log in or sign up" time.sleep(2) <file_sep>/Example/conftest.py from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager import pytest from webdriver_manager.firefox import GeckoDriverManager web_driver = None @pytest.fixture(params=["chrome"], scope='class') def init_driver(request): global web_driver if request.param == 'chrome': web_driver = webdriver.Chrome(ChromeDriverManager().install()) #if request.param == 'firefox': # web_driver = webdriver.Firefox(r"C:\Users\dboyapalli\PycharmProjects\pythonProject\Browsers\geckodriver.exe") request.cls.driver = web_driver yield web_driver.close() <file_sep>/Tests1/test_LoginPage.py from Config.config import TestData from Pages.LoginPage import LoginPage from Tests1.test_login_base import BaseLoginTest from Pages.BasePage import BasePage class TestLogin(BaseLoginTest): def test_login(self): self.loginPage = LoginPage(self.driver) self.basePage = BasePage(self.driver) self.loginPage.do_login(TestData.STANDARD_USER_NAME, TestData.PASSWORD) welcome_log=self.basePage.get_element_text(LoginPage.welcome_log) assert welcome_log == "Welcome Divya" def test_login_failure(self): self.loginPage = LoginPage(self.driver) self.basePage = BasePage(self.driver) self.loginPage.do_login("sak", "fgh") error = self.basePage.get_invalid_message(LoginPage.error_message) assert error == "Invalid credentials" def test_login_password_empty(self): self.loginPage = LoginPage(self.driver) self.basePage = BasePage(self.driver) self.loginPage.do_login(TestData.STANDARD_USER_NAME, "") error = self.basePage.get_invalid_message(LoginPage.error_message) assert error == "Password cannot be empty" def test_login_username_empty(self): self.loginPage = LoginPage(self.driver) self.basePage = BasePage(self.driver) self.loginPage.do_login("", "H752") error = self.basePage.get_invalid_message(LoginPage.error_message) assert error == "Username cannot be empty"<file_sep>/Pages/LoginPage.py import selenium from Config.config import TestData from Pages.BasePage import BasePage from selenium.webdriver.common.by import By class LoginPage(BasePage): # By Locators # user_name = (By.ID, "txtUsername") password = (By.ID, "<PASSWORD>") login_button = (By.ID, "btnLogin") error_message = (By.XPATH, "//span[@id='spanMessage']") welcome_log = (By.XPATH, "//li[contains(text(),'Welcome Divya')]") # Page Actions # def __init__(self, driver): super().__init__(driver) self.driver.get(TestData.BASE_URL) def do_login(self, username, password): self.send_keys(self.user_name, username) self.send_keys(self.password, <PASSWORD>) self.press_button(self.login_button) <file_sep>/PracticeExamples/FileHandling/Append.py f = open('demoFile.txt', 'a') f.write(" python ") f = open('demoFile.txt', 'r') print(f.read())<file_sep>/PracticeExamples/FileHandling/Read.py f = open('demoFile.txt', 'r') print(f.read()) print('------------------------------------') f1 = open('demoFile.txt') line = f1.readline() while line != "": print(line) line = f1.readline() print('------------------------------------') f2 = open('demoFile.txt') for element in f2.readlines(): print(element) <file_sep>/PracticeExamples/FileHandling/Delete.py import os #os.remove("demoFile2.txt") print("------------------------------") if os.path.exists("demoFile2.txt"): os.remove("demoFile2.txt") else: print("The file does not exist") print("------------------------------")<file_sep>/PracticeExamples/FileHandling/Write.py f = open("demoFile2.txt", "w") f.write("Welcome") f.close() f = open("demoFile2.txt", "r") print(f.read()) print("---------------------------------------------") with open("demoFile.txt", "r") as file: content = file.read() print(content) reversed_text = reversed(content) print("---------------------------------------------") with open("demoFile.txt", "w") as file1: for line in reversed_text: file1.write(line) with open("demoFile.txt", "r") as file1: print(file1.read())<file_sep>/PyTestDemo/test_parameterized.py import pytest # A simple addition function that adds/concatenates two input values def add_operation(input_1, input_2): return input_1 + input_2 # We make use of the parametrize decorator to supply input arguments # to the test function @pytest.mark.parametrize('inp_1, inp_2,result', [ (9, 6, 15), ('Cross browser testing on ', 'LambdaTest', 'Cross browser testing on LambdaTest'), ('pytest', 'framework', 'pytest framework1') ] ) def test_add_integers_strings(inp_1, inp_2, result): result_1 = add_operation(inp_1, inp_2) assert result_1 == result # Enable the stack trace for debugging the issue @pytest.mark.parametrize('inp_1, inp_2,result', [ (9, 6, 15), ('Cross browser testing on ', 'LambdaTest', 'Cross browser testing on LambdaTest1') ] ) def test_add_integers_strings_fail_case(inp_1, inp_2, result): result_1 = add_operation(inp_1, inp_2) if result_1 != result: pytest.fail("Test failed", True)<file_sep>/PracticeExamples/pythonBasics/loops.py greeting = "<NAME>" a = 4 if a > 2: print(" Condition matches") print("second line") else: print("condition do not match") print("if else condition code is completed") #for loop obj= [2, 3, 5, 7, 9] for i in obj: print(i*2) # sum of First Natural numbers 1+2+3+4+5 = 15 #range(i,j) -> i to j-1 summation = 0 for j in range(1, 6): summation = summation + j print(summation) print("*******************************") for k in range(1, 10, 5): print(k) print("**************SKIPPING FIRST INDEX*****************") for m in range(10): print(m) <file_sep>/PracticeExamples/Selinium/actionsDemo.py import time from selenium import webdriver from selenium.webdriver import ActionChains driver = webdriver.Chrome(r"C:\Users\dboyapalli\PycharmProjects\pythonProject\Browsers\chromedriver.exe") #ActionChains driver.get("https://chercher.tech/practice/practice-pop-ups-selenium-webdriver") action = ActionChains(driver) action.context_click(driver.find_element_by_id("double-click")).perform() print("-------------------------------------") time.sleep(5) action.double_click(driver.find_element_by_id("double-click")).perform() time.sleep(5) print("-------------------------------------") alert = driver.switch_to.alert assert "You double clicked me!!!, You got to be kidding me" == alert.text alert.accept() driver.close() <file_sep>/PyTestDemo/test_google_class_scope.py import pytest from selenium import webdriver import time print("test case started") @pytest.fixture(scope="class") def fun_setup_chrome(request): print("---chrome driver set up method---") ch_driver = webdriver.Chrome(r"C:\Users\dboyapalli\PycharmProjects\pythonProject\Browsers\chromedriver.exe") request.cls.driver = ch_driver yield print("---chrome driver tear down method---") ch_driver.quit() @pytest.mark.usefixtures("fun_setup_chrome") class BaseChromeTest: pass class TestGoogleChrome(BaseChromeTest): @pytest.mark.skip def test_open_google(self): self.driver.get("https://www.google.com/") assert self.driver.title == "Google" time.sleep(2) <file_sep>/PracticeExamples/pythonBasics/Demo2.py values = [1, 2, "rahul", 4, 5] # List is data type that allows multiple values and can be different data types print(values[0]) # 1 print(values[3]) # 4 print(values[-1]) #5 print(values[1:3]) # 2 rahul values.insert(3, "shetty") #[1, 2, 'rahul', 'shetty', 4, 5] print(values) values.append("End") #[1, 2, 'rahul', 'shetty', 4, 5, 'End'] print(values) values[2] = "RAHUL" #Updating del values[0] print(values) # Tuple - Same as LIST Data type but immutable val = (1, 2, "rahul", 4.5) print(val[1]) #val[2] = "RAHUL" print(val) # Dictionary dic = {"a": 2, 4:"bcd", "c": "Hello world"} print(dic[4]) print(dic["c"]) # dict = {} dict["firstname"] = "Rahul" dict["lastname"] = "shetty" dict["gender"] = "Male" print(dict) print(dict["lastname"]) <file_sep>/PracticeExamples/FileHandling/TryExcept.py # The try block will raise an error when trying to write to a read-only file: try: f = open("demoFile.txt") f.write("Welcome") except Exception as e: print(e) print("Something went wrong when writing to the file") finally: f.close() # The program can continue, without leaving the file object open print('------------------------------------') x = -1 if x < 0: raise Exception("Sorry, no numbers below zero")<file_sep>/PracticeExamples/pythonBasics/StringsDemo.py str = "RahulShettyAcademy.com" str1 = "Consulting firm" str3 = "RahulShetty" print(str[1]) #a print(str[0:5]) # if you want substring in python print(str+str1) # concatenation print(str3 in str) # substring check var = str.split(".") print(var) print(var[0]) str4 = " great " print(str4.strip()) print(str4.lstrip()) print(str4.rstrip()) <file_sep>/PracticeExamples/pythonBasics/FirstDemo.py print("hello") # here are the comments i have defined a = 3 print(a) Str = "Hello World" print(Str) b, c, d = 5, 6.4, "Great" #print("Value is"+b+"fdfd") print("{} {}".format("Value is", b)) print(type(b)) print(type(c)) print(type(d)) <file_sep>/Example/test_params.py import time from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.by import By import pytest from selenium.webdriver.support import expected_conditions as ec @pytest.mark.usefixtures("init_driver") class BaseTest: pass class Test_HubSpot(BaseTest): @pytest.mark.parametrize( "username,password", [ ("<EMAIL>", "admin123"), ("<EMAIL>", "<PASSWORD>") ] ) def send_keys(self, by_locator, text): WebDriverWait(self.driver, 10).until(ec.visibility_of_element_located(by_locator)).send_keys(text) def test_login(self, username, password): """ this method is used to login to hub spot application :param username: :param password: :return: """ self.driver.get("https://app.hubspot.com/login") self.driver.find_element(By.ID, 'username'.send_keys(username)) time.sleep(3) self.driver.find_element(By.ID, 'password'.send_keys(<PASSWORD>)) time.sleep(3) <file_sep>/TestData/HomePageData.py import openpyxl class HomePageData: test_HomePage_data = [{"firstname":"Rahul","lastname":"shetty","gender":"Male"}, {"firstname":"Anshika", "lastname":"shetty", "gender":"Female"}] <file_sep>/venv/Lib/site-packages/python_basics/control_flows.py def control_flows(): print('It contains all the information about if-else, while-looop, for-loop etc') <file_sep>/PyTestDemo/test_demo.py import pytest def fun(x): return 3+x @pytest.mark.xfail def test_fun(): assert fun(3) == 7 def f(): raise SystemExit(1) def test_my_test(): with pytest.raises(SystemExit): f() def f1(): print(1/0) def test_my_test1(): with pytest.raises(ZeroDivisionError): f1() def test_recursion_depth(): with pytest.raises(RuntimeError) as exc_info: def f(): f() f() assert "maximum recursion" in str(exc_info.value) @pytest.mark.login def test_login_gmail(): assert "admin" == "admin" @pytest.mark.login def test_divisible_by_6(): assert 3 % 6 == 0<file_sep>/PyTestDemo/test_fixture_params.py from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager import pytest from webdriver_manager.firefox import GeckoDriverManager web_driver = None @pytest.fixture(params=["chrome", "firefox"],scope='class') def init__driver(request): global web_driver if request.param == "chrome": web_driver = webdriver.Chrome(ChromeDriverManager().install()) if request.param == "firefox": web_driver = webdriver.Firefox(executable_path=r"C:\Users\dboyapalli\PycharmProjects\pythonProject\Browsers\geckodriver.exe") request.cls.driver = web_driver yield web_driver.close() @pytest.mark.usefixtures("init__driver") class BaseTest: pass class TestGoogle(BaseTest): def test_google_title(self): self.driver.get("http://www.google.com") assert self.driver.title == "Google" <file_sep>/PracticeExamples/Selinium/explicitwaitDemo.py import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait list1 = [] list2 = [] driver = webdriver.Chrome(r"C:\Users\dboyapalli\PycharmProjects\pythonProject\Browsers\chromedriver.exe") driver.get("https://rahulshettyacademy.com/seleniumPractise/") driver.find_element_by_css_selector("input.search-keyword").send_keys("ber") time.sleep(4) count =len(driver.find_elements_by_xpath("//div[@class='products']/div")) assert count == 3 buttons = driver.find_elements_by_xpath("//div[@class='product-action']/button") for button in buttons: list1.append(button.find_element_by_xpath("parent::div/parent::div/h4").text) button.click() print(list1) driver.find_element_by_css_selector("img[alt='Cart']").click() driver.find_element_by_xpath("//button[text()='PROCEED TO CHECKOUT']").click() wait = WebDriverWait(driver, 8) wait.until(expected_conditions.presence_of_element_located((By.CLASS_NAME, "promoCode"))) veggies =driver.find_elements_by_css_selector("p.product-name") for veg in veggies: list2.append(veg.text) print(list2) assert list1 == list2 originalAmount = driver.find_element_by_css_selector(".discountAmt").text driver.find_element_by_class_name("promoCode").send_keys("rahulshettyacademy") driver.find_element_by_css_selector(".promoBtn").click() wait.until(expected_conditions.presence_of_element_located((By.CSS_SELECTOR,"span.promoInfo"))) discountAmount = driver.find_element_by_css_selector(".discountAmt").text assert float(discountAmount) < int(originalAmount) print(driver.find_element_by_css_selector("span.promoInfo").text) amounts = driver.find_elements_by_xpath("//tr/td[5]/p") sum = 0 for amount in amounts: sum = sum + int(amount.text) #32+48+60 print(sum) totalAmount = int(driver.find_element_by_class_name("totAmt").text) assert sum == totalAmount <file_sep>/PracticeExamples/Selinium/demoBrowser.py from selenium import webdriver driver = webdriver.Chrome(r"C:\Users\dboyapalli\PycharmProjects\pythonProject\Browsers\chromedriver.exe") driver.maximize_window() driver.get("https://rahulshettyacademy.com/") #get method to hit url on browser print(driver.title) print(driver.current_url) driver.get("https://rahulshettyacademy.com/AutomationPractice/") driver.minimize_window() driver.back() driver.refresh() driver.close() <file_sep>/Config/config.py class TestData: CHROME_EXECUTABLE_PATH = r"C:\Users\dboyapalli\PycharmProjects\pythonProject\Browsers\chromedriver.exe" BASE_URL = r"https://intranet.primesoft.net/symfony/web/index.php/auth/login" STANDARD_USER_NAME = "H752" PASSWORD = "<PASSWORD>" <file_sep>/PracticeExamples/Selinium/Demo.py #Implicit wait - #Explicit Wait import time from selenium import webdriver #pause the test for few seconds using Time class from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait #driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") driver = webdriver.Chrome(r"C:\Users\dboyapalli\PycharmProjects\pythonProject\Browsers\chromedriver.exe") driver.implicitly_wait(5) list1 = [] list2 = [] driver.get("https://rahulshettyacademy.com/seleniumPractise/") driver.find_element_by_css_selector("input.search-keyword").send_keys("ber") time.sleep(4) count = len(driver.find_elements_by_xpath("//div[@class='products']/div")) assert count == 3 buttons = driver.find_elements_by_xpath("//div[@class='product-action']/button") for button in buttons: list1.append(button.find_element_by_xpath("parent::div / parent::div / h4").text) button.click() print(list1) driver.find_element_by_css_selector("img[alt='Cart']").click() driver.find_element_by_xpath("//button[text()='PROCEED TO CHECKOUT']").click() wait = WebDriverWait(driver, 5) wait.until(expected_conditions.presence_of_element_located((By.CLASS_NAME, "promoCode"))) veggies = driver.find_elements_by_css_selector("p.product-name") for l in veggies: list2.append(l.text) print(list2) assert list1 == list2 amount1= driver.find_element_by_css_selector(".discountAmt").text driver.find_element_by_class_name("promoCode").send_keys("ra<PASSWORD>academy") driver.find_element_by_css_selector(".promoBtn").click() print(driver.find_element_by_css_selector("span.promoInfo").text) amount2 = driver.find_element_by_css_selector(".discountAmt").text assert int(amount1) > float(amount2) veggiesAmount = driver.find_elements_by_xpath("//tr/td[5]/p") sum = 0 for v in veggiesAmount: sum = sum + int(v.text) print(sum) assert sum == int(amount1) <file_sep>/PracticeExamples/Selinium/locators.py import time from selenium import webdriver from selenium.webdriver.support.select import Select driver = webdriver.Chrome(r"C:\Users\dboyapalli\PycharmProjects\pythonProject\Browsers\chromedriver.exe") driver.get("https://rahulshettyacademy.com/angularpractice/") driver.implicitly_wait(5) driver.find_element_by_css_selector("input[name='name']").send_keys("Rahul") driver.find_element_by_name("email").send_keys("Shetty") driver.find_element_by_id("exampleCheck1").click() dropdown = Select(driver.find_element_by_id("exampleFormControlSelect1")) dropdown.select_by_visible_text("Female") time.sleep(4) dropdown.select_by_index(0) time.sleep(4) driver.find_element_by_xpath("//input[@type='submit']").click() time.sleep(4) message = driver.find_element_by_class_name("alert-success").text time.sleep(4) assert "success" in message driver.close()
c0742bd4f5ef3fd0dac5f51a6d2c0abfcc91bab3
[ "Python" ]
31
Python
divya-github18/PythonSelinumTesting
bf69918badd7351fc909fb8372ec1b677bd65e6b
5568914efcea0afc89c79869408cd2a4737f4ba2
refs/heads/master
<repo_name>Fabionunez/lab-javascript-clue<file_sep>/src/clue.js // Characters Collection var mrGreen = { first_name: "Jacob", last_name: "Green", color: "green", description: "He has a lot of connections", age: 45, image: "https://pbs.twimg.com/profile_images/506787499331428352/65jTv2uC.jpeg", occupation: "Entrepreneur" }; var drOrchid = { first_name: "Doctor", last_name: "Orchid", color: "white", description: "PhD in plant toxicology. Adopted daughter of Mr. Boddy", age: 26, image: "http://www.radiotimes.com/uploads/images/Original/111967.jpg", occupation: "Scientist" }; var profPlum = { first_name: "Victor", last_name: "Plum", color: "purple", description: "Billionare video game designer", age: 22, image: "https://metrouk2.files.wordpress.com/2016/07/professor-plum.jpg", occupation: "Designer" }; var missScarlet = { first_name: "Kasandra", last_name: "Scarlet", color: "red", description: "She is an A-list movie star with a dark past", age: 31, image: "https://metrouk2.files.wordpress.com/2016/07/miss-scarlett.jpg", occupation: "Actor" }; var mrsPeacock = { first_name: "Eleanor", last_name: "Peacock", color: "blue", description: "She is from a wealthy family and uses her status and money to earn popularity", age: 36, image: "https://metrouk2.files.wordpress.com/2016/07/mrs-peacock.jpg", occupation: "Socialité" }; var mrMustard = { first_name: "Jack", last_name: "Mustard", color: "yellow", description: "He is a former football player who tries to get by on his former glory", age: 62, image: "https://metrouk2.files.wordpress.com/2016/07/colonel-mustard.jpg", occupation: "Retired Football player" }; // Weapons Collection var rope = { name: "rope", weight: 10 }; var knife = { name: "knife", weight: 8 }; var candlestick = { name: "candlestick", weight: 2 }; var dumbbell = { name: "dumbbell", weight: 30 }; var poison = { name: "poison", weight: 2 }; var axe = { name: "axe", weight: 15 }; var bat = { name: "bat", weight: 13 }; var trophy = { name: "trophy", weight: 25 }; var pistol = { name: "pistol", weight: 20 }; var weaponsArray = [ rope, knife, candlestick, dumbbell, poison, axe, bat, trophy ]; var charactersArray = [ mrGreen, drOrchid, profPlum, missScarlet, mrsPeacock, mrMustard ]; var roomsArray = [ "Dinning Room", "Conservatory", "Kitchen", "Study", "Library", "Billiard Room", "Lounge", "Ballroom", "Hall", "Spa", "Living Room", "Observatory", "Theater", "Guest House", "Patio" ]; // Find a random element of the array - randomSelector //Defines randomSelector function randomSelector() { var randomRoom = roomsArray[Math.floor(Math.random() * roomsArray.length)]; var randomCharacters = charactersArray[Math.floor(Math.random() * charactersArray.length)]; var randomWeapons = weaponsArray[Math.floor(Math.random() * weaponsArray.length)]; var pickMistery = [randomRoom, randomCharacters, randomWeapons]; if (pickMistery !== 0) { return pickMistery; } else { return undefined; } } var misteryEnvelope = randomSelector(); console.log(misteryEnvelope); console.log( `${misteryEnvelope[1].first_name} ${ misteryEnvelope[1].last_name } killed Mr.Boddy using the ${misteryEnvelope[2].name} in the ${ misteryEnvelope[0] }!!!!` );
21212f278184db341a853708b48f18023f4fd241
[ "JavaScript" ]
1
JavaScript
Fabionunez/lab-javascript-clue
a4c0394f15e8938d3bf3ea640f765aceeecc0f50
8a56e97e303c915fe1b166f9fe59d7132b9fa9d2
refs/heads/master
<file_sep>const cacheName = 'philman-+VI6LInC96cEeQ=='; self.addEventListener('install', event => { event.waitUntil( caches.open(cacheName).then(cache => { return cache.addAll([ '/', 'index.html', '/dist/fonts/big-john.ttf', '/dist/fonts/big-john.woff', '/dist/fonts/big-john.woff2', '/dist/fonts/Champagne-&-Limousines.ttf', '/dist/fonts/Champagne-&-Limousines.woff', '/dist/fonts/Champagne-&-Limousines.woff2', '/dist/main.css' ]); }).then(() => self.skipWaiting()) ); }); self.addEventListener('activate', event => { event.waitUntil( caches.keys().then(keyList => { return Promise.all(keyList.map(key => { if (key !== cacheName) { console.log('[ServiceWorker] Removing old cache', key); return caches.delete(key); } })).then(() => console.log('New cache now ready')); }) ); return self.clients.claim(); }); self.addEventListener('fetch', event => { if (event.request.url.startsWith(self.location.origin) && event.request.method === 'GET') { event.respondWith( caches.match(event.request).then(cachedResponse => { return cachedResponse || fetch(event.request); }) ); } else { return; } }); <file_sep>const rsvpOptions = document.querySelector('[data-component="rsvp"]'); const dietarySection = document.querySelector('[data-component="dietary"]'); dietarySection.classList.add('hide'); rsvpOptions.addEventListener('change', function(event) { if (event.srcElement.id === 'yes') { dietarySection.classList.remove('hide'); } else { dietarySection.classList.add('hide'); } }); <file_sep>import { tresillianLocation, townLocations, accommodationLocations, pointsOfInterest } from './locations'; let mapIsLoaded; const viewportHeight = document.documentElement.clientHeight; const options = { token: '<KEY>', element: document.getElementById('map'), triggerPosition: viewportHeight + (viewportHeight / 2), defaultPosition: { minZoom: 9, zoom: 11, center: [50.378687,-5.001103] }, style: 'mapbox://styles/glynnphillips/cjlccjlsa695m2so58osa1c53' } const throttle = (func, wait) => { let time = Date.now(); return function() { if ((time + wait - Date.now()) < 0) { func(); time = Date.now(); } } } const loadMap = () => { if (!mapIsLoaded && options.element.getBoundingClientRect().top <= options.triggerPosition) { mapIsLoaded = true; const mapbox = L.mapbox; mapbox.accessToken = options.token; const map = mapbox.map('map', 'mapbox.streets', options.defaultPosition) mapbox.styleLayer('mapbox://styles/glynnphillips/cjlccjlsa695m2so58osa1c53') .addTo(map); mapbox.featureLayer() .addTo(map) .on('layeradd', (event) => { const marker = event.layer; const feature = marker.feature; if (feature.properties.icon) { marker.setIcon(L.divIcon(feature.properties.icon)); } }) .setGeoJSON(townLocations .concat(tresillianLocation, pointsOfInterest)); map.dragging.disable() map.scrollWheelZoom.disable() } } window.addEventListener('scroll', throttle(loadMap, 500)); loadMap(); <file_sep>#!/usr/bin/env bash echo "Running pre commit" randomString=`head -c 10 /dev/random | base64` sed -i "" "s/^const cacheName = 'philman-.*';/const cacheName = 'philman-${randomString}';/g" src/service-worker.js git add src/service-worker.js <file_sep>import "./css/main.scss"; import "./map.js"; import "./rsvp-options.js"; if ('serviceWorker' in navigator) { window.addEventListener('load', function() { navigator.serviceWorker.register('/sw.js'); }); } <file_sep>module.exports = { tresillianLocation: [ { type: 'Feature', geometry: { type: 'Point', coordinates: [-5.018260, 50.380117] }, properties: { icon: { className: 'map__tresillian', html: 'Tresillian House', iconSize: [110, 20] } } } ], townLocations: [ { type: 'Feature', geometry: { type: 'Point', coordinates: [-5.076292, 50.412975] }, properties: { icon: { className: 'map__marker', html: 'Newquay', iconSize: [100, 20] } } }, { type: 'Feature', geometry: { type: 'Point', coordinates: [-5.040000, 50.256576] }, properties: { icon: { className: 'map__marker', html: 'Truro', iconSize: [120, 20] } } }, { type: 'Feature', geometry: { type: 'Point', coordinates: [-5.480473, 50.213783] }, properties: { icon: { className: 'map__marker', html: 'St. Ives', iconSize: [100, 20] } } }, { type: 'Feature', geometry: { type: 'Point', coordinates: [-4.465020, 50.454405] }, properties: { icon: { className: 'map__marker', html: 'Liskeard', iconSize: [100, 20] } } }, { type: 'Feature', geometry: { type: 'Point', coordinates: [-4.759151, 50.333999] }, properties: { icon: { className: 'map__marker', html: '<NAME>', iconSize: [150, 20] } } } ], accommodationLocations: [ { type: 'Feature', geometry: { type: 'Point', coordinates: [-5.007850, 50.352774] }, properties: { title: 'The Plume of Feathers', 'marker-color': '#004c53', 'marker-size': 'medium', 'marker-symbol': 'village' } }, { type: 'Feature', geometry: { type: 'Point', coordinates: [-4.944162,50.377834] }, properties: { title: 'Premier Inn - Fraddon', 'marker-color': '#004c53', 'marker-size': 'medium', 'marker-symbol': 'village' } }, { type: 'Feature', geometry: { type: 'Point', coordinates: [-5.029169, 50.401417] }, properties: { title: 'Premier Inn - Quintrell Downs', 'marker-color': '#004c53', 'marker-size': 'medium', 'marker-symbol': 'village' } }, { type: 'Feature', geometry: { type: 'Point', coordinates: [-5.042802, 50.419914] }, properties: { title: 'The Crantock Suite', 'marker-color': '#004c53', 'marker-size': 'medium', 'marker-symbol': 'village' } }, { type: 'Feature', geometry: { type: 'Point', coordinates: [-5.053714,50.424506] }, properties: { title: 'The Beach Apartment', 'marker-color': '#004c53', 'marker-size': 'medium', 'marker-symbol': 'village' } }, { type: 'Feature', geometry: { type: 'Point', coordinates: [-5.069751, 50.379469] }, properties: { title: 'The Stable Conversion', 'marker-color': '#004c53', 'marker-size': 'medium', 'marker-symbol': 'village' } }, { type: 'Feature', geometry: { type: 'Point', coordinates: [-4.983328, 50.368739] }, properties: { title: 'Carvynick Holiday Park', 'marker-color': '#004c53', 'marker-size': 'medium', 'marker-symbol': 'campsite' } } ], pointsOfInterest: [ { type: 'Feature', geometry: { type: 'Point', coordinates: [-4.997862, 50.437957] }, properties: { title: 'Newquay Airport', 'marker-color': '#004c53', 'marker-size': 'medium', 'marker-symbol': 'airport' } }, { type: 'Feature', geometry: { type: 'Point', coordinates: [-5.064639, 50.263957] }, properties: { title: 'Truro Train Station', 'marker-color': '#004c53', 'marker-size': 'medium', 'marker-symbol': 'rail' } }, { type: 'Feature', geometry: { type: 'Point', coordinates: [-5.028229, 50.404256] }, properties: { title: 'Quintrell Downs Train Station', 'marker-color': '#004c53', 'marker-size': 'medium', 'marker-symbol': 'rail' } }, { type: 'Feature', geometry: { type: 'Point', coordinates: [-4.789259,50.339591] }, properties: { title: 'St. Austell Train Station', 'marker-color': '#004c53', 'marker-size': 'medium', 'marker-symbol': 'rail' } }, { type: 'Feature', geometry: { type: 'Point', coordinates: [-5.110372, 50.436277] }, properties: { 'marker-color': '#004c53', 'marker-size': 'medium', 'marker-symbol': 'swimming' } } ] }
93acc81bc8b29c318eb28af2fb650e3e51faa880
[ "JavaScript", "Shell" ]
6
JavaScript
GlynnPhillips/philman
fee1c3a9d134f9ae06241a82cced3f9a739d3bae
470897c7797a099bc27bb2c5eab8239ab5dbbac3
refs/heads/main
<repo_name>levopeti/crypto_trading<file_sep>/binance_test/binance_api_test.py import json from binance.client import Client from binance.websockets import BinanceSocketManager from twisted.internet import reactor from jarvix import jprint with open('secret.json') as f: secret = json.load(f) api_key = secret['api_key'] api_secret = secret['secret_key'] client = Client(api_key, api_secret) btc_price = {'error': False} # # client.API_URL = 'https://testnet.binance.vision/api' # # # get balances for all assets & some account information # jprint(client.get_account()) # # # get balance for a specific asset only (BTC) # print(client.get_asset_balance(asset='BTC')) # # # get balances for futures account # # print(client.futures_account_balance()) # # # get balances for margin account # jprint(client.get_margin_account()) # jprint(client.get_symbol_ticker(symbol="DOGEUSDT")) #################################### # def btc_trade_history(msg): # """define how to process incoming WebSocket messages""" # if msg['e'] != 'error': # print(msg['c']) # btc_price['last'] = msg['c'] # btc_price['bid'] = msg['b'] # btc_price['last'] = msg['a'] # else: # btc_price['error'] = True # # # # init and start the WebSocket # bsm = BinanceSocketManager(client) # conn_key = bsm.start_symbol_ticker_socket('DOGEUSDT', btc_trade_history) # bsm.start() # from time import sleep # sleep(10) # # # stop websocket # bsm.stop_socket(conn_key) # # # properly terminate WebSocket # reactor.stop() #####################################x # valid intervals - 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M # get timestamp of earliest date data is available timestamp = client._get_earliest_valid_timestamp('BTCUSDT', '1d') print(timestamp) # request historical candle (or klines) data bars = client.get_historical_klines('BTCUSDT', '1d', timestamp, limit=1000) print(bars)
6687e2baff0de64aa7e168c379dbe9cb1ab9ea41
[ "Python" ]
1
Python
levopeti/crypto_trading
1d130866a55b306af708810b7242cc2ea7d490ba
4083d19bcad277b27c1c91045e0ecd41e8b7a5fb
refs/heads/master
<repo_name>mottus-app/mottus-server<file_sep>/src/utils/testDecorator.spec.ts import { UserResponse } from 'src/users/entity/user.entity'; import { returnBoolean, returnString, returnUserResponse, } from './utilDecorators'; describe('returnsString', () => { it('works', () => { expect(true).toBeTruthy(); }); it('returns String', () => { expect(returnString()).toBe(String); }); }); describe('returnsUserResponse', () => { it('returns UserRreposne', () => { expect(returnUserResponse()).toBe(UserResponse); }); }); describe('returnBoolean', () => { it('just works', () => { expect(returnBoolean()).toBe(Boolean); }); }); <file_sep>/src/utils/utilDecorators.ts import { UserResponse } from 'src/users/entity/user.entity'; export const returnString = () => String; export const returnUserResponse = () => UserResponse; export const returnBoolean = () => Boolean; <file_sep>/merge.ts import * as fs from 'fs'; import * as libCoverage from 'istanbul-lib-coverage'; import * as libReport from 'istanbul-lib-report'; import * as reports from 'istanbul-reports'; import * as path from 'path'; import { checkFinalCoverage, defaultWaterMarks, readDirectoryRecursive, } from './scripts'; async function main() { const reportFiles = readDirectoryRecursive( 'coverage', 'coverage-final.json', '', ); const map = libCoverage.createCoverageMap(); reportFiles.forEach((file) => { const finalReport: Record< string, libCoverage.FileCoverageData > = JSON.parse( fs.readFileSync(path.join(__dirname, file), { encoding: 'utf8' }), ); Object.values(finalReport).forEach((fileReport) => { map.addFileCoverage(fileReport); }); }); const context = libReport.createContext({ dir: './coverage', coverageMap: map, watermarks: defaultWaterMarks, }); const jsonSummary: libReport.ReportBase = (reports.create( 'json-summary', ) as unknown) as libReport.ReportBase; const lcov: libReport.ReportBase = (reports.create( 'lcov', {}, ) as unknown) as libReport.ReportBase; jsonSummary.execute(context); lcov.execute(context); const { length } = await checkFinalCoverage(defaultWaterMarks); return length ? process.exit(1) : false; } main().catch((err) => { console.error(err); process.exit(1); }); <file_sep>/src/utils/base.response.ts import { ObjectType, Field } from '@nestjs/graphql'; import { returnString } from './utilDecorators'; @ObjectType() export class FieldError { @Field( /* istanbul ignore next */ () => String, ) field: string; @Field( /* istanbul ignore next */ () => String, ) message: string; } @ObjectType() export class BaseResponse { @Field( /* istanbul ignore next */ () => [FieldError], { nullable: true }, ) errors?: FieldError[]; } <file_sep>/src/users/users.service.ts import { Injectable } from '@nestjs/common'; import { GqlContext } from 'src/utils/gqlContext'; import { SignupDto } from './dto/signup.dto'; import { LogInDto } from './dto/login.dto'; import * as bcrypt from 'bcryptjs'; import { UserResponse } from './entity/user.entity'; import { COOKIE_NAME } from 'src/utils/cookieName'; import validator from 'validator'; import { FieldError } from 'src/utils/base.response'; @Injectable() export class UsersService { async getMe({ req, prisma, res }: GqlContext): Promise<UserResponse> { if (!req.session?.userId) { return { user: null, }; } try { const user = await prisma.user.findUnique({ where: { id: req.session.userId, }, }); if (!user) { res.clearCookie(COOKIE_NAME); return { user: null, }; } return { user, }; } catch (error) { console.log('ERROR: ', error.code, error.message); return { errors: [ { field: 'internal server error', message: 'please try again later' }, ], }; } } async signup( signupDto: SignupDto, context: GqlContext, ): Promise<UserResponse> { const errors = this.signupValidation(signupDto); if (errors) { return { errors }; } // you get the password value and call it toHash const { password: toHash } = signupDto; try { const password = await bcrypt.hash(toHash, await bcrypt.genSalt()); const user = await context.prisma.user.create({ data: { ...signupDto, password, role: 'USER', }, }); // NOW THE USER IS LOGGED IN context.req.session.userId = user.id; return { user }; } catch (error) { // if (error.code === 'P2002' || error.message.includes('constraint')) { if (error.message.match(/constraint|email/gi)) { return { errors: [{ field: 'email', message: 'this email is already taken' }], }; } console.log('ERROR', error.message, error.code); return { errors: [ { field: 'internal server error', message: `please check your console`, }, ], }; } } async login(loginDto: LogInDto, context: GqlContext): Promise<UserResponse> { const errors = this.loginValidation(loginDto); if (errors) { return { errors }; } const { password: toBeDecrypted, email } = loginDto; try { const user = await context.prisma.user.findUnique({ where: { email: email }, }); if (!user) { return { errors: [ { field: 'email', message: `email does not exist`, }, ], }; } const isValid = await bcrypt.compare(toBeDecrypted, user.password); if (!isValid) { return { errors: [ { field: 'credentials', message: `Invalid credentials`, }, ], }; } context.req.session.userId = user.id; return { user }; } catch (error) { console.log('ERROR', error.message, error.code); return { errors: [ { field: 'internal server error', message: 'please check your console', }, ], }; } } async logout({ req, res }: GqlContext) { if (!req.headers?.cookie?.includes(COOKIE_NAME)) { return false; } res.clearCookie(COOKIE_NAME); if (!req.session.userId) { return false; } return new Promise((resolve) => { req.session.destroy((err) => { if (err) { console.log('ERRORRRR', err.message, err.code); return resolve(false); } resolve(true); }); }); } private signupValidation(signupDto: SignupDto): FieldError[] | false { const errors: FieldError[] = []; if ( typeof signupDto.name !== 'string' || !validator.isLength(signupDto.name, { min: 5 }) ) { errors.push({ field: `name`, message: `Your name is too short. Please have, at least, 5 chars`, }); } if ( typeof signupDto.email !== 'string' || !validator.isEmail(signupDto.email) ) { errors.push({ field: 'email', message: 'Invalid email', }); } if ( typeof signupDto.password !== 'string' || !validator.matches( signupDto.password, /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/, ) ) { errors.push({ field: `password`, message: `your password is shit. please have minimum of 8 chars, 1 number, one small letter, and one big letter`, }); } return errors.length ? errors : false; } private loginValidation(loginDto: LogInDto): FieldError[] | false { const errors: FieldError[] = []; if (typeof loginDto.password !== 'string' || !loginDto.password) { errors.push({ field: 'password', message: 'Please write a password', }); } if ( typeof loginDto.email !== 'string' || !validator.isEmail(loginDto.email) ) { errors.push({ field: 'email', message: 'Please write a valid email', }); } return errors.length ? errors : false; } } <file_sep>/src/utils/createUserDataLoader.ts import * as DataLoader from 'dataloader'; import { PrismaClient } from '@prisma/client'; import { User } from 'src/users/entity/user.entity'; export const createUserDataLoader = (prisma: PrismaClient) => new DataLoader<string, User>(async (userIds) => { console.log('userIds:', userIds); const users = await prisma.user.findMany({ where: { id: { in: userIds as string[] }, }, }); const userIdsToUser: Record<string, User> = {}; users.forEach((e) => (userIdsToUser[e.id] = e)); const sortedUsers = userIds.map((id) => userIdsToUser[id]); return sortedUsers; }); <file_sep>/src/organization/organization.service.ts import { Injectable, UnauthorizedException } from '@nestjs/common'; import { GqlContext } from 'src/utils/gqlContext'; import { AddToOrgDto } from './dto/add-to-org.dto'; import { CreateOrganizationDto } from './dto/create-organization.dto'; import { AddToOrgResponse, OrganizationResponse, OrganizationsResponse, } from './entity/organization.entity'; @Injectable() export class OrganizationService { async create( createOrganizationDto: CreateOrganizationDto, context: GqlContext, ): Promise<OrganizationResponse> { if (!context.req.session.userId) { return { errors: [{ field: 'unauthorized', message: 'You not logged in' }], }; } // !TODO DO VALIDATION OF INPUT try { const organization = await context.prisma.organization.create({ data: { ...createOrganizationDto, workers: { connect: { id: context.req.session.userId, }, }, owner: { connect: { id: context.req.session.userId, }, }, }, }); return { organization }; } catch (error) { if (error.message.match(/constraint|name/gi)) { return { errors: [ { field: 'company name', message: 'this company name is already taken', }, ], }; } return { errors: [ { field: 'internal server error', message: 'please check your console', }, ], }; } } async getAllOrgs({ prisma }: GqlContext) { // throw new UnauthorizedException('DUMB FUCK'); const organizations = await prisma.organization.findMany({ // include: { workers: true }, }); return { organizations }; } async addToOrg( addToOrgDto: AddToOrgDto, context: GqlContext, ): Promise<AddToOrgResponse> { if (!context.req.session.userId) { return { errors: [ { field: 'not authenticated', message: 'you are not logged in' }, ], }; } const organization = await context.prisma.organization.findUnique({ where: { id: addToOrgDto.orgId, }, }); if (!organization) { return { errors: [{ field: 'organizationId', message: 'no such organization' }], }; } if (organization.ownerId !== context.req.session.userId) { return { errors: [ { field: 'not authenticated', message: 'you are not logged in' }, ], }; } await context.prisma.organization.update({ where: { id: organization.id, }, data: { workers: { connect: { id: addToOrgDto.userIdToAdd, }, }, }, }); return { worked: true, }; } } <file_sep>/scripts/utils/consts.ts import { WATERMARKS } from './types'; export const defaultWaterMarks: WATERMARKS = { statements: [50, 100], branches: [50, 100], functions: [50, 100], lines: [50, 100], }; <file_sep>/src/utils/gqlContext.ts import { Request, Response } from 'express'; import { PrismaClient } from '@prisma/client'; import { Session, SessionData } from 'express-session'; // export type MySession = Session & Partial<SessionData> & { userId: string }; // import { Request, Response } from "express"; // import { Session, SessionData } from "express-session"; // import { Redis } from "ioredis"; // export type MyContext = { // req: Request & { // session: Session & Partial<SessionData> & { UserID: number }; // }; // redis: Redis; // res: Response; // }; // here we have a request with the session overrriden by our own session interface type CustomRequest = Request & { session: Session & Partial<SessionData> & { userId: string }; }; export interface GqlContext { prisma: PrismaClient; req: CustomRequest; res: Response; } <file_sep>/src/organization/dto/add-to-org.dto.ts import { InputType, Field } from '@nestjs/graphql'; @InputType() export class AddToOrgDto { @Field(() => String) userIdToAdd: string; @Field(() => String) orgId: string; } <file_sep>/src/organization/organization.resolver.ts import { Args, Context, Mutation, Query, ResolveField, Resolver, Root, } from '@nestjs/graphql'; import { User } from 'src/users/entity/user.entity'; import { GqlContext } from 'src/utils/gqlContext'; import { returnString } from 'src/utils/utilDecorators'; import { CreateOrganizationDto } from './dto/create-organization.dto'; import { AddToOrgDto } from './dto/add-to-org.dto'; import { AddToOrgResponse, Organization, OrganizationResponse, OrganizationsResponse, } from './entity/organization.entity'; import { OrganizationService } from './organization.service'; import { BadRequestException, UnauthorizedException } from '@nestjs/common'; import { IsLogged } from 'src/shared/is-logged.guard'; @Resolver(() => Organization) export class OrganizationResolver { constructor(private readonly orgService: OrganizationService) {} @ResolveField(() => User) async owner(@Root() org: Organization, @Context() context: GqlContext) { throw new UnauthorizedException('Bad in owner'); const owner = await context.prisma.organization .findUnique({ where: { id: org.id } }) .owner(); return owner; } @ResolveField(() => [User]) async workers(@Root() org: Organization, @Context() context: GqlContext) { // console.log( // await context.prisma.organization // .findUnique({ where: { id: org.id } }) // .workers(), // ); throw new UnauthorizedException('Bad in workers'); return context.prisma.organization .findUnique({ where: { id: org.id } }) .workers({ take: 5 }); } @Mutation(() => OrganizationResponse) createOrganization( @Args('createOrganizationInput') createOrganizationDto: CreateOrganizationDto, @Context() context: GqlContext, ) { return this.orgService.create(createOrganizationDto, context); } @Query(() => OrganizationsResponse) // @IsLogged() getAllOrgs(@Context() context: GqlContext) { return this.orgService.getAllOrgs(context); } @Mutation(() => AddToOrgResponse) addToOrg( @Args('addToOrgOptions') addToOrgDto: AddToOrgDto, @Context() context: GqlContext, ) { return this.orgService.addToOrg(addToOrgDto, context); } } <file_sep>/test/utils/index.ts export * from './authQueries'; <file_sep>/scripts/funcs/index.ts export * from './readDirRecursive'; <file_sep>/prisma/test-environment.js require('dotenv/config'); const util = require('util'); const NodeEnvironment = require('jest-environment-node'); const { nanoid } = require('nanoid'); const { PrismaClient } = require('@prisma/client'); const exec = util.promisify(require('child_process').exec); const { DB_USERNAME, DB_PASSWORD } = process.env; class PrismaTestEnvironment extends NodeEnvironment { constructor(config) { super(config); // Generate a unique sqlite identifier for this test context this.schema = nanoid(); this.url = `postgresql://${DB_USERNAME}:${DB_PASSWORD}@localhost:5432/prisma?connection_limit=1&schema=${this.schema}`; process.env.DB_URL = this.url; this.global.process.env.DB_URL = this.url; this.client = new PrismaClient(); } async setup() { // Run the migrations to ensure our schema has the required structure await exec(`yarn migrate:prod`); return super.setup(); } async teardown() { await this.client.$executeRaw( `drop schema if exists "${this.schema}" cascade`, ); await this.client.$disconnect(); } } module.exports = PrismaTestEnvironment; <file_sep>/src/utils/setPrisma.ts /* istanbul ignore file */ import { PrismaClient } from '@prisma/client'; import { __isProd__ } from './isProd'; // export const prisma = new PrismaClient({ // // to log only the queries when in development // log: __isProd__ ? [] : ['query'], // }); export const prisma = new PrismaClient(); <file_sep>/src/utils/cookieName.ts export const COOKIE_NAME = 'mid'; // another config name for future use <file_sep>/src/users/dto/signup.dto.ts import { InputType, Field } from '@nestjs/graphql'; @InputType() export class SignupDto { @Field(() => String) name: string; @Field(() => String) password: string; @Field(() => String) email: string; @Field(() => String, { nullable: true }) profilePic?: string; } <file_sep>/scripts/utils/funcs.ts import * as chalk from 'chalk'; import { join } from 'path'; import * as fs from 'fs'; export const smallerMsg = (msg: string, color: keyof chalk.Chalk = 'white') => chalk.bgBlack[color as string](` ${msg} `); export const keyPassingOrPassing = ( key: string, color: keyof chalk.Chalk = 'black', ) => chalk.bgBlack.bold[color as string](` ${key.toUpperCase()} `); export function includesFromPath(path: string, lookAhead: string) { return fs.readdirSync(path).includes(lookAhead); } let counter = 0; export function getCoverageDir(dir = '') { const currentDir = dir ? join(dir, '..') : join(__dirname); const [file] = process.argv[1].split('/').reverse(); const isRootWithGit = includesFromPath(currentDir, '.git') || includesFromPath(currentDir, 'package.json') || includesFromPath(currentDir, file); counter++; if (counter >= 7) { throw new Error( "Didn't find the root of your folder. Do you have a gir repository initialized?", ); } return isRootWithGit ? currentDir : getCoverageDir(currentDir); } <file_sep>/src/organization/entity/organization.entity.ts import { Organization as PrismaOrganization } from '@prisma/client'; import { ObjectType, Field } from '@nestjs/graphql'; import { BaseResponse } from 'src/utils/base.response'; import { User } from 'src/users/entity/user.entity'; @ObjectType() export class Organization implements PrismaOrganization { @Field(() => String) id: string; @Field(() => String) createdAt: Date; @Field(() => String) updatedAt: Date; @Field(() => String) name: string; @Field(() => String, { nullable: true }) companyPic: string | null; @Field(() => [User]) workers?: User[]; @Field(() => User) owner?: User; ownerId: string; } @ObjectType() export class OrganizationResponse extends BaseResponse { @Field(() => Organization, { nullable: true }) organization?: Organization; } @ObjectType() export class OrganizationsResponse extends BaseResponse { @Field(() => [Organization], { nullable: true }) organizations?: Organization[]; } @ObjectType() export class AddToOrgResponse extends BaseResponse { @Field(() => Boolean, { nullable: true }) worked?: boolean; } <file_sep>/scripts/utils/index.ts export * from './consts'; export * from './funcs'; export * from './types'; <file_sep>/scripts/index.ts import * as fsExtra from 'fs-extra'; import { join } from 'path'; import { defaultWaterMarks, getCoverageDir, keyPassingOrPassing, smallerMsg, TotalSection, WATERMARKS, } from './utils'; export * from './utils'; export * from './funcs'; export async function checkFinalCoverage( watermarks: WATERMARKS = defaultWaterMarks, ) { const coverageDir = getCoverageDir(); const { total: finalCoverage } = await fsExtra.readJSON( join(coverageDir, 'coverage', 'coverage-summary.json'), ); const entriesOfStatus = Object.entries(finalCoverage); return entriesOfStatus.filter((el: [keyof WATERMARKS, TotalSection]) => { const [minThresh, maxThresh] = watermarks[el[0]]; const [name, { pct: currentPerc }] = el; if (currentPerc < minThresh) { console.log( `${keyPassingOrPassing(name, 'red')}${smallerMsg( `is failing with ${currentPerc}`, 'red', )}`, ); return true; } if (currentPerc < maxThresh) { return console.log( `${keyPassingOrPassing(name, 'yellow')}${smallerMsg( `is okay. Could be better. ${currentPerc}`, 'yellow', )}`, ); } return console.log( `${keyPassingOrPassing(name, 'green')}${smallerMsg( 'is perfect', 'green', )}`, ); }); } <file_sep>/src/shared/is-logged.guard.ts import { CanActivate, ExecutionContext, Injectable, UseGuards, } from '@nestjs/common'; import { GqlExecutionContext } from '@nestjs/graphql'; import { Observable } from 'rxjs'; import { GqlContext } from 'src/utils/gqlContext'; @Injectable() export class IsLoggedGuard implements CanActivate { canActivate( context: ExecutionContext, ): boolean | Promise<boolean> | Observable<boolean> { return false; const ctx = GqlExecutionContext.create(context); const myContext: GqlContext = ctx.getContext(); console.log('req:', Object.keys(myContext)); if (!myContext?.req?.session?.userId) { return false; } return true; } } export const IsLogged = () => UseGuards(IsLoggedGuard); <file_sep>/src/users/entity/user.entity.ts import { User as PrismaUser } from '@prisma/client'; import { ObjectType, Field, registerEnumType } from '@nestjs/graphql'; import { BaseResponse } from 'src/utils/base.response'; enum Role { ADVERTISER = 'ADVERTISER', USER = 'USER', } registerEnumType(Role, { name: 'Role', description: 'The possible roles of a user', }); @ObjectType() export class User implements PrismaUser { @Field(() => String) id: string; @Field(() => String) createdAt: Date; @Field(() => String) updatedAt: Date; @Field(() => String) name: string; @Field(() => String) profilePic: string; @Field(() => String) email: string; password: string; @Field(() => Role) role: 'ADVERTISER' | 'USER'; } @ObjectType() export class UserResponse extends BaseResponse { @Field(() => User, { nullable: true }) user?: User; } <file_sep>/scripts/funcs/readDirRecursive.ts import * as fs from 'fs'; import * as path from 'path'; export function readDirectoryRecursive( dir: string, fileExtension: string, relativeDir: string, ) { const files = []; const entries: string[] = fs.readdirSync(dir, { encoding: 'utf-8' }); for (const entry of entries) { const filePath = `${dir}/${entry}`; const stats = fs.lstatSync(filePath); if (stats.isDirectory()) { files.push( ...readDirectoryRecursive(filePath, fileExtension, relativeDir), ); } else if (stats.isFile() && entry.endsWith(fileExtension)) { const entityPath = path .relative(relativeDir, filePath) .replace(/\.ts$/, ''); files.push(path.normalize(entityPath)); } } return files; } <file_sep>/src/users/users.resolver.ts import { Args, Context, Mutation, Query, Resolver } from '@nestjs/graphql'; import { IsLogged } from 'src/shared/is-logged.guard'; import { GqlContext } from 'src/utils/gqlContext'; import { returnString, returnUserResponse } from 'src/utils/utilDecorators'; import { LogInDto } from './dto/login.dto'; import { SignupDto } from './dto/signup.dto'; import { User, UserResponse } from './entity/user.entity'; import { UsersService } from './users.service'; @Resolver(() => User) export class UsersResolver { constructor(private readonly usersService: UsersService) {} @Query(returnString) hello() { return `hello`; } @Query(returnUserResponse) @IsLogged() me(@Context() context: GqlContext) { return this.usersService.getMe(context); } @Mutation(returnUserResponse) signup( @Args('signupOptions') signupDto: SignupDto, @Context() context: GqlContext, ) { return this.usersService.signup(signupDto, context); } @Mutation(returnUserResponse) login( @Args('loginOptions') loginDto: LogInDto, @Context() context: GqlContext, ) { return this.usersService.login(loginDto, context); } @Mutation(() => Boolean) logout(@Context() context: GqlContext) { return this.usersService.logout(context); } } <file_sep>/scripts/utils/types.ts import * as libReport from 'istanbul-lib-report'; export type WATERMARKS = libReport.Watermarks; export interface TotalSection { total: number; covered: number; skipped: number; pct: number; } export enum CoverageStatus { ERROR = 'ERROR', GOOD = 'GOOD', PERFECT = 'PERFECT', } interface EachStatus { status: CoverageStatus; value: number; } export type StatusReport = { [K in keyof libReport.Watermarks]: EachStatus; }; <file_sep>/src/users/users.resolver.spec.ts import { Test, TestingModule } from '@nestjs/testing'; import { UsersResolver } from './users.resolver'; import { createMock } from '@golevelup/ts-jest'; import { UsersService } from './users.service'; import { GqlContext } from 'src/utils/gqlContext'; import { COOKIE_NAME } from 'src/utils/cookieName'; import { User } from 'src/users/entity/user.entity'; import { SignupDto } from './dto/signup.dto'; import { genSalt, hash } from 'bcryptjs'; import { LogInDto } from './dto/login.dto'; // we pass the User resolver for testing let resolver: UsersResolver; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [UsersResolver, UsersService], }).compile(); resolver = module.get<UsersResolver>(UsersResolver); }); describe('UsersResolver', () => { it('should be defined', () => { expect(resolver).toBeDefined(); }); describe('Get User', () => { describe('null states', () => { it('sends null with no userId', async () => { const context = createMock<GqlContext>({ req: { session: { userId: null, }, }, }); const callResolver = await resolver.me(context); expect(callResolver.user).toBeNull(); }); it('sends null if no user found', async () => { const ctx = createMock<GqlContext>({ res: { clearCookie: jest.fn(), }, req: { session: { userId: '123' as any, }, }, prisma: { user: { findUnique: jest.fn().mockResolvedValue(null), }, }, }); const callResolver = await resolver.me(ctx as any); expect(ctx.prisma.user.findUnique).toHaveBeenCalled(); expect(ctx.res.clearCookie).toHaveBeenCalled(); expect(ctx.res.clearCookie).toHaveBeenCalledWith(COOKIE_NAME); expect(callResolver.user).toBeNull(); }); it('when error', async () => { const ctx = createMock<GqlContext>({ req: { session: { userId: '123' as any, }, }, prisma: { user: { findUnique: jest.fn().mockRejectedValue(new Error('Error')), }, }, }); const callResolver = await resolver.me(ctx); expect(callResolver.user).not.toBeDefined(); expect(callResolver).toStrictEqual({ errors: [ { field: 'internal server error', message: 'please try again later', }, ], }); expect(callResolver.errors).toStrictEqual([ { field: 'internal server error', message: 'please try again later', }, ]); }); }); describe('works', () => { it('sends back a user', async () => { const mockedUser: User = { createdAt: new Date(), email: '<EMAIL>', id: '123', name: 'andre', password: '<PASSWORD>', profilePic: '', role: 'USER', updatedAt: new Date(), }; const ctx = createMock<GqlContext>({ req: { session: { userId: '123' as any, }, }, prisma: { user: { findUnique: jest.fn().mockResolvedValue(mockedUser), }, }, }); const calledResolver = await resolver.me(ctx); expect(calledResolver.user).toBeDefined(); expect(calledResolver.user.email).toBe(mockedUser.email); }); }); }); describe('Signup', () => { describe('error states', () => { describe('input validation', () => { // we use this so we can do proper unit testing for each resolver const mockContext = createMock<GqlContext>(); const obj = { email: '123', name: '123', password: '123', }; it('name fails', async () => { //here we call the resolver it self const callResolver = await resolver.signup(obj, mockContext); expect(callResolver.user).toBeUndefined(); expect(callResolver.errors).toBeDefined(); expect(callResolver.errors.length).toBeGreaterThan(1); const isUsernameError = callResolver.errors.find( (el) => el.field === 'name', ); expect(isUsernameError).toBeDefined(); const callResolverWithArr = await resolver.signup( { // @ts-expect-error name: [], }, mockContext, ); const stillUsername = callResolverWithArr.errors.find( (el) => el.field === 'name', ); expect(stillUsername).toBeDefined(); }); it('username works', async () => { const callResolver = await resolver.signup( { ...obj, name: '<NAME>arez de la conna madre que te pario', }, mockContext, ); const notUsername = callResolver.errors.find( (e) => e.field === 'name', ); expect(notUsername).not.toBeDefined(); }); it('email fails', async () => { const callResolver = await resolver.signup(obj, mockContext); expect(callResolver.user).toBeUndefined(); expect(callResolver.errors).toBeDefined(); expect(callResolver.errors.length).toBeGreaterThan(1); const isEmailError = callResolver.errors.find( (el) => el.field === 'email', ); expect(isEmailError).toBeDefined(); const callResolverWithArr = await resolver.signup( { // @ts-expect-error email: [], }, mockContext, ); const stillEmail = callResolverWithArr.errors.find( (el) => el.field === 'email', ); expect(stillEmail).toBeDefined(); const anotherResolver = await resolver.signup( // @ts-expect-error { email: '<EMAIL>', }, mockContext, ); expect( anotherResolver.errors.find((e) => e.field === 'email'), ).toBeDefined(); }); it('email works', async () => { const callResolver = await resolver.signup( { ...obj, email: '<EMAIL>', }, mockContext, ); const isEmail = callResolver.errors.find( (el) => el.field === 'email', ); expect(isEmail).not.toBeDefined(); }); it('password fails', async () => { const callResolver = await resolver.signup(obj, mockContext); expect( callResolver.errors.find((el) => el.field === 'password'), ).toBeDefined(); }); it('password works', async () => { const callResolver = await resolver.signup( { ...obj, password: '<PASSWORD>' }, mockContext, ); expect( callResolver.errors.find((e) => e.field === 'password'), ).not.toBeDefined(); }); }); describe('creatingUserFail', () => { const validSignup: SignupDto = { email: '<EMAIL>', name: 'Andre', password: '<PASSWORD>.', }; it('non unique email', async () => { const mockContext = createMock<GqlContext>({ prisma: { user: { // creating a fake context so when prisma.user.create is called in the resolver it throws and error create: jest .fn() .mockRejectedValue(new Error('constraint email')), }, }, }); const callResolver = await resolver.signup(validSignup, mockContext); expect(callResolver.errors).toStrictEqual([ { field: 'email', message: 'this email is already taken' }, ]); expect(callResolver.user).not.toBeDefined(); }); it('internal server error', async () => { const mockContext = createMock<GqlContext>({ prisma: { user: { // creating a fake context so when prisma.user.create is called in the resolver it throws and error create: jest .fn() .mockRejectedValue(new Error('oops i did it again')), }, }, }); const callResolver = await resolver.signup(validSignup, mockContext); expect(callResolver.errors).toStrictEqual([ { field: 'internal server error', message: 'please check your console', }, ]); expect(callResolver.user).not.toBeDefined(); }); }); }); describe('works', () => { const validSignup: SignupDto = { email: '<EMAIL>', password: '<PASSWORD>', name: '<NAME> chars', }; const mockContext = createMock<GqlContext>({ req: { session: {}, }, prisma: { user: { //fake context with an expected value returned create: jest.fn().mockResolvedValue({ ...validSignup, role: 'USER', id: '123456789', }), }, }, }); it('works', async () => { const callResolver = await resolver.signup(validSignup, mockContext); expect(callResolver.errors).not.toBeDefined(); expect(callResolver.user).toStrictEqual({ ...validSignup, role: 'USER', id: '123456789', }); expect(mockContext.req.session.userId).toBe('123456789'); }); }); }); describe('Logout', () => { describe('errors', () => { describe('no cookie', () => { it('returns false with no cookie', async () => { const mockCtxNoReq = createMock<GqlContext>(); const callResolver = await resolver.logout(mockCtxNoReq); expect(callResolver).toBe(false); const mockCtxNoHeaders = createMock<GqlContext>({ req: {}, }); const callResolverNoH = await resolver.logout(mockCtxNoHeaders); expect(callResolverNoH).toBe(false); const mockCtxNoCookies = createMock<GqlContext>({ req: { headers: {}, }, }); const callResolverNoC = await resolver.logout(mockCtxNoCookies); expect(callResolverNoC).toBe(false); const mockCtxNotCookieName = createMock<GqlContext>({ req: { headers: { cookie: '1234', }, }, }); const callResolverNoCookieName = await resolver.logout( mockCtxNotCookieName, ); expect(callResolverNoCookieName).toBe(false); }); }); describe('no user', () => { it('no user and no cookie', async () => { const mockCtx = createMock<GqlContext>({ req: { session: { userId: null, }, headers: { cookie: 'bla bla bla bla', }, }, res: { clearCookie: jest.fn(), }, }); const calledResolver = await resolver.logout(mockCtx); expect(calledResolver).toBe(false); expect(mockCtx.res.clearCookie).not.toHaveBeenCalled(); }); it('no user but cookie', async () => { const mockCtx = createMock<GqlContext>({ req: { session: { userId: null, }, headers: { cookie: COOKIE_NAME, }, }, res: { clearCookie: jest.fn(), }, }); const calledResolver = await resolver.logout(mockCtx); expect(mockCtx.res.clearCookie).toHaveBeenCalled(); expect(mockCtx.res.clearCookie).toHaveBeenCalledWith(COOKIE_NAME); expect(calledResolver).toBe(false); }); }); it('destroy error', async () => { const mockCtx = createMock<GqlContext>({ req: { session: { userId: '123' as any, destroy: jest .fn() .mockImplementation((fn) => fn(new Error('PROBLEMS'))) as any, }, headers: { cookie: COOKIE_NAME, }, }, res: { clearCookie: jest.fn(), }, }); const calledResolver = await resolver.logout(mockCtx); expect(calledResolver).toBe(false); }); }); describe('logs out', () => { const mockCtx = createMock<GqlContext>({ req: { headers: { cookie: COOKIE_NAME, }, session: { userId: '123' as any, destroy: jest.fn().mockImplementation((fn) => fn()) as any, }, }, res: { clearCookie: jest.fn(), }, }); it('works', async () => { const callResolver = await resolver.logout(mockCtx); expect(callResolver).toBe(true); expect(mockCtx.res.clearCookie).toHaveBeenCalled(); expect(mockCtx.res.clearCookie).toHaveBeenCalledWith(COOKIE_NAME); }); }); }); describe('Login', () => { const input: LogInDto = { email: '<EMAIL>', password: '<PASSWORD>', }; describe('error states', () => { describe('input validation', () => { const mockCtx = createMock<GqlContext>(); describe('bad email', () => { const input: LogInDto = { email: 'asd', password: '123', }; it('fails with not a good email', async () => { const callResolver = await resolver.login(input, mockCtx); expect(callResolver.user).not.toBeDefined(); expect( callResolver.errors.find((e) => e.field === 'email'), ).toBeDefined(); }); }); describe('general bad inputs', () => { it('with array inputs', async () => { const callResolver = await resolver.login( { // @ts-expect-error email: [], // @ts-expect-error password: [], }, mockCtx, ); expect(callResolver.errors.length).toBeGreaterThan(1); }); }); }); it('no user with email', async () => { const mockCtx = createMock<GqlContext>({ prisma: { user: { findUnique: jest.fn().mockResolvedValue(null), }, }, }); const callResolver = await resolver.login(input, mockCtx); expect(callResolver.user).not.toBeDefined(); expect(callResolver.errors[0].field).toBe('email'); }); it('wrong password', async () => { const mockCtx = createMock<GqlContext>({ prisma: { user: { findUnique: jest.fn().mockResolvedValue({ ...input, id: '123' }), }, }, }); const callResolver = await resolver.login(input, mockCtx); expect(callResolver.user).not.toBeDefined(); expect(callResolver.errors[0].field).toBe('credentials'); }); it('internal errors', async () => { const mockCtx = createMock<GqlContext>({ prisma: { user: { findUnique: jest.fn().mockRejectedValue(new Error('Oppsie')), }, }, }); const callResolver = await resolver.login(input, mockCtx); expect(callResolver.user).not.toBeDefined(); expect(callResolver.errors[0].field).toMatch(/internal server error/gi); }); }); describe('Success', () => { it('works', async () => { const hashPass = await hash(input.password, await genSalt()); const mockCtx = createMock<GqlContext>({ req: { session: {}, }, prisma: { user: { findUnique: jest .fn() .mockResolvedValue({ ...input, password: <PASSWORD>, id: '123' }), }, }, }); const callResolver = await resolver.login({ ...input }, mockCtx); expect(callResolver.errors).not.toBeDefined(); expect(callResolver.user).toStrictEqual({ ...input, password: <PASSWORD>, id: '123', }); expect(mockCtx.req.session.userId).toBe('123'); }); }); }); }); <file_sep>/test/utils/authQueries.ts export const getMeQuery = `query {me {errors {field message} user {id}}}`; export const signupMutation = `mutation { signup( signupOptions: { name: "andre" password: "<PASSWORD>" email: "<EMAIL>" } ) { errors { field message } user { id } } } `; export const logoutMutation = `mutation {logout}`; <file_sep>/src/utils/isProd.ts /* istanbul ignore file */ export const __isProd__ = process.env.NODE_ENV === 'production'; <file_sep>/test/users.e2e-spec.ts import { Test, TestingModule } from '@nestjs/testing'; import { INestApplication } from '@nestjs/common'; import * as request from 'supertest'; import { AppModule } from '../src/app.module'; import { COOKIE_NAME } from 'src/utils/cookieName'; import { getMeQuery, logoutMutation, signupMutation } from './utils'; const GRAPHQL_ENDPOINT = '/graphql'; describe('User Module (e2e)', () => { let app: INestApplication; const base = () => request(app.getHttpServer()).post(GRAPHQL_ENDPOINT); /** * * @param cookie the cookie that was received upon login * @param query the query that we will send for the test */ const privateTest = (cookie: string, query: string) => base().set('Cookie', cookie).send({ query }); const publicT = (query: string) => base().send({ query }); beforeAll(async () => { const module: TestingModule = await Test.createTestingModule({ imports: [AppModule], }).compile(); app = module.createNestApplication(); await app.init(); }); afterAll(async () => { await app.close(); }); describe('test', () => { it.only('works to get user, when no session', async () => { const { body } = await publicT(getMeQuery); console.log('body:', body); expect(body.data).toBeNull(); expect(body.errors).toBeDefined(); // expect(body.data?.me.errors).toBeNull(); // expect(body.data?.me.user).toBeNull(); // expect(body.errors).toBeDefined(); }); }); it('auth flow', async () => { const { body, header } = await publicT(signupMutation); const cookie = (header['set-cookie'] as string[]).find((c) => c.includes(COOKIE_NAME), ); const data = await privateTest(cookie, getMeQuery) .expect('Content-Type', /json/) .expect(200); expect(data.body.data.me.user.id).toBeDefined(); expect(data.body.data.me.user.id).toBe(body.data.signup.user.id); const { body: logoutB, headers: logoutHs } = await privateTest( cookie, logoutMutation, ); const theCookieString = (logoutHs['set-cookie'] as string[]).find((el) => el.includes(COOKIE_NAME), ); const theCookie = theCookieString ?.replace(`${COOKIE_NAME}=`, '') ?.split(';')[0]; expect(theCookie).toBeFalsy(); expect(logoutB.data.logout).toBe(true); const { body: logoutAtt2 } = await publicT(logoutMutation); expect(logoutAtt2.data.logout).toBe(false); }); }); <file_sep>/src/app.module.ts import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'; import { GraphQLModule } from '@nestjs/graphql'; import { PrismaSessionStore } from '@quixo3/prisma-session-store'; import * as session from 'express-session'; import { join } from 'path'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { OrganizationModule } from './organization/organization.module'; import { UsersModule } from './users/users.module'; import { COOKIE_NAME } from './utils/cookieName'; import { createUserDataLoader } from './utils/createUserDataLoader'; import { __isProd__ } from './utils/isProd'; import { prisma } from './utils/setPrisma'; @Module({ imports: [ GraphQLModule.forRoot({ autoSchemaFile: join(process.cwd(), 'src', 'schema.graphql'), // so we can use our own cors cors: false, context: ({ req, res }) => ({ req, res, prisma, userLoader: createUserDataLoader(prisma), }), formatError: (err) => { // console.log('err:', err); // return // const res = err.extensions?.exception?.response; // const isAuthError = res?.statusCode === 401 || res?.statusCode === 403; // // console.log('isAuthError:', isAuthError); // if (isAuthError) { // return { // field: 'auth', // message: 'you are not authorized', // }; // } // const field: // console.log('err:', err); // return err.extensions?.exception?.response; return err; }, }), UsersModule, OrganizationModule, ], controllers: [AppController], providers: [AppService], }) export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer .apply( session({ name: COOKIE_NAME, cookie: { //is the time the cookie will expire maxAge: 7 * 24 * 60 * 60 * 1000, secure: __isProd__, httpOnly: true, sameSite: 'lax', }, secret: process.env.SESSION_SECRET || 'session-secret', resave: false, saveUninitialized: false, //make sure to have a session model in the prisma schema store: new PrismaSessionStore(prisma, { // checkPeriod: 2 * 1000 * 60, dbRecordIdIsSessionId: true, // checkPeriod: 2 * 1000 * 60 * 60, //ms // dbRecordIdIsSessionId: true, // dbRecordIdFunction: undefined, }), }), ) .forRoutes('*'); } }
697dd5bdad3cc7b222665371d82fcd93f46ad8cc
[ "JavaScript", "TypeScript" ]
31
TypeScript
mottus-app/mottus-server
30f01189f43d57657a6c86d6d04c30fb3b1d605c
f28308052a89018c7868afa1c8e6305c3a1b0d48
refs/heads/master
<repo_name>mulyo88/Form-Button-Report-<file_sep>/laporan2.java package airwaybill; import java.io.File; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.HashMap; import java.util.Map; import javax.swing.JOptionPane; import koneksi.db_form; import net.sf.jasperreports.engine.JasperCompileManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.engine.design.JasperDesign; import net.sf.jasperreports.engine.xml.JRXmlLoader; import net.sf.jasperreports.view.JasperViewer; import java.awt.Dimension; import java.awt.Toolkit; import java.sql.DriverManager; import java.sql.SQLException; public class laporan2 extends javax.swing.JFrame { db_form con; Connection conn = new db_form().getConnection(); ResultSet rs = null; PreparedStatement pst = null; JasperReport jasperReport; JasperDesign jasperDesign; JasperPrint jasperPrint; Map par=new HashMap(); //Map <String,Object> par = new HashMap<String,Object>(); //Connection conn = new koneksidb.koneksi().getConnection(); //private String JasperPrint; //private String JasperDesign; //private JasperReport JasperReport; //private Map param; String nama = UserSession.get_username(); public laporan2() { initComponents(); this.setLocationRelativeTo(null); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); this.setSize(dim.width, dim.height); con = new db_form(); con.Class(); ComboGroup(); this.setExtendedState(laporan2.MAXIMIZED_BOTH); lblUserLogin.setText(nama); //ReportController = new ReportController(); } private void ComboGroup(){ try { String sql = "select * from user"; pst = con.cc.prepareStatement(sql); rs=pst.executeQuery(); while(rs.next()){ String shift = rs.getString("shift"); FComboGroup.addItem(shift); } } catch (SQLException e) { JOptionPane.showMessageDialog(null, e); } } private void laporan_shift() { Connection conn = new db_form().getConnection(); try { String path = "src/airwaybill/report1.jasper"; // File file=new File("src/nyobarepotlagi/report1.jrxml"); // JasperDesign jasperdesign=JRXmlLoader.load(file); // Map parameter = new HashMap(); par.clear(); //par.put("USER", lblUserLogin.getText()); // JasperReport jasperreport=JasperCompileManager.compileReport(jasperdesign); JasperPrint print = JasperFillManager.fillReport(path,par, conn); JasperViewer jv = new JasperViewer(print, false); jv.setVisible(true); //JasperViewer.viewReport(print, false); } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Dokumen Tidak Ada" + "\n" + ex.getMessage()); } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jLabel3 = new javax.swing.JLabel(); FComboGroup = new javax.swing.JComboBox(); jLabel5 = new javax.swing.JLabel(); Button_shift = new javax.swing.JButton(); jPanel3 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jDate1 = new com.toedter.calendar.JDateChooser(); jLabel7 = new javax.swing.JLabel(); jDate2 = new com.toedter.calendar.JDateChooser(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jLabel8 = new javax.swing.JLabel(); lblUserLogin = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(102, 204, 255)); jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/pesawat1.png"))); // NOI18N jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel1.setText("LAPORAN - LAPORAN"); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel3.setText("LAPORAN BERDASARKAN SHIFT / GROUP "); jLabel5.setText("PILIH GROUP"); Button_shift.setText("PRINT"); Button_shift.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { Button_shiftMouseClicked(evt); } }); Button_shift.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Button_shiftActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel3) .addGap(0, 14, Short.MAX_VALUE)) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5) .addComponent(FComboGroup, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Button_shift))) .addContainerGap(25, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(19, 19, 19) .addComponent(jLabel3) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel5) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Button_shift, javax.swing.GroupLayout.DEFAULT_SIZE, 89, Short.MAX_VALUE) .addComponent(FComboGroup, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel2.setText("LAPORAN BERDASARKAN TANGGAL / PERIODE"); jLabel6.setText("MASUKAN TANGGAL "); jLabel7.setText("SAMPAI"); jButton2.setText("PRINT"); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel6)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jDate2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 161, Short.MAX_VALUE) .addComponent(jDate1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jLabel7)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton2) .addGap(29, 29, 29)))) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel2) .addGap(18, 18, 18) .addComponent(jLabel6) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jDate1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel7) .addGap(18, 18, 18) .addComponent(jDate2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(20, Short.MAX_VALUE)) ); jButton3.setText("EXIT"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/logo-GapuraAngkasa_k.png"))); // NOI18N lblUserLogin.setEditable(false); jLabel9.setText("Welcome"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(82, 82, 82) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(61, 61, 61) .addComponent(jLabel8)) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane1) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(0, 67, Short.MAX_VALUE) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1) .addGap(314, 314, 314)))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel9) .addGap(18, 18, 18) .addComponent(lblUserLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(24, 24, 24) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblUserLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel9)))) .addGap(9, 9, 9) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(72, 72, 72) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 75, Short.MAX_VALUE) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane1)) .addGap(30, 30, 30)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed this.dispose(); }//GEN-LAST:event_jButton3ActionPerformed private void Button_shiftActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button_shiftActionPerformed laporan_shift(); }//GEN-LAST:event_Button_shiftActionPerformed private void Button_shiftMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Button_shiftMouseClicked // laporan_shift(); }//GEN-LAST:event_Button_shiftMouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception ex) { java.util.logging.Logger.getLogger(laporan2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new laporan2().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton Button_shift; private javax.swing.JComboBox FComboGroup; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private com.toedter.calendar.JDateChooser jDate1; private com.toedter.calendar.JDateChooser jDate2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField lblUserLogin; // End of variables declaration//GEN-END:variables } <file_sep>/db_form.java package koneksi; import java.sql.*; public class db_form { public Connection cc; public Statement ss; public ResultSet rs; public void Class () { try { Class.forName("com.mysql.jdbc.Driver"); cc=DriverManager.getConnection("jdbc:mysql://localhost/awb","root","root"); System.out.println("Koneksi OK!!"); } catch (Exception e) { System.out.println(e); } } public Connection getConnection() { return cc; } }
840a4f21ea8ebb9a37a785674aadebc15138a95a
[ "Java" ]
2
Java
mulyo88/Form-Button-Report-
7157b3998a0ceb653b42c1b217b3060426aaff2e
7433241a0ca10a5e05631252ffb611aeee0e1807
refs/heads/master
<repo_name>elcct/amazingwebsite<file_sep>/system/middleware.go package system import ( "net/http" "github.com/golang/glog" "github.com/zenazn/goji/web" "github.com/elcct/amazingwebsite/models" "github.com/gorilla/context" "github.com/gorilla/sessions" "labix.org/v2/mgo" "labix.org/v2/mgo/bson" ) // Makes sure templates are stored in the context func (application *Application) ApplyTemplates(c *web.C, h http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { c.Env["Template"] = application.Template h.ServeHTTP(w, r) } return http.HandlerFunc(fn) } // Makes sure controllers can have access to session func (application *Application) ApplySessions(c *web.C, h http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { session, _ := application.Store.Get(r, "session") c.Env["Session"] = session h.ServeHTTP(w, r) context.Clear(r) } return http.HandlerFunc(fn) } // Makes sure controllers can have access to the database func (application *Application) ApplyDatabase(c *web.C, h http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { session := application.DBSession.Clone() defer session.Close() c.Env["DBSession"] = session c.Env["DBName"] = application.Configuration.Database.Database h.ServeHTTP(w, r) } return http.HandlerFunc(fn) } func (application *Application) ApplyAuth(c *web.C, h http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { session := c.Env["Session"].(*sessions.Session) if userId, ok := session.Values["User"].(bson.ObjectId); ok { dbSession := c.Env["DBSession"].(*mgo.Session) database := dbSession.DB(c.Env["DBName"].(string)) user := new(models.User) err := database.C("users").Find(bson.M{"_id": userId}).One(&user) if err != nil { glog.Warningf("Auth error: %v", err) c.Env["User"] = nil } else { c.Env["User"] = user } } h.ServeHTTP(w, r) } return http.HandlerFunc(fn) } <file_sep>/helpers/auth.go package helpers import ( "labix.org/v2/mgo" "labix.org/v2/mgo/bson" "code.google.com/p/go.crypto/bcrypt" "github.com/elcct/amazingwebsite/models" ) func Login(c *mgo.Database, email string, password string) (user *models.User, err error) { err = c.C("users").Find(bson.M{"e": email}).One(&user) if err != nil { return } err = bcrypt.CompareHashAndPassword(user.Password, []byte(password)) if err != nil { user = nil } return } <file_sep>/system/controller.go package system import ( "bytes" "html/template" "labix.org/v2/mgo" "github.com/zenazn/goji/web" "github.com/gorilla/sessions" ) type Controller struct { } func (controller *Controller) GetSession(c web.C) *sessions.Session { return c.Env["Session"].(*sessions.Session) } func (controller *Controller) GetTemplate(c web.C) *template.Template { return c.Env["Template"].(*template.Template) } func (controller *Controller) GetDatabase(c web.C) *mgo.Database { dbSession := c.Env["DBSession"].(*mgo.Session) return dbSession.DB(c.Env["DBName"].(string)) } func (controller *Controller) Parse(t *template.Template, name string, data interface{}) string { var doc bytes.Buffer t.ExecuteTemplate(&doc, name, data) return doc.String() }<file_sep>/README.md Default Project [![Build Status](https://drone.io/github.com/elcct/amazingwebsite/status.png)](https://drone.io/github.com/elcct/amazingwebsite/latest) =============== Provides essentials that most web applications need - MVC pattern and user authorisation that can be easily extended. It consists of 3 core components: - Goji - A web microframework for Golang - http://goji.io/ - Gorilla web toolkit sessions - cookie (and filesystem) sessions - http://www.gorillatoolkit.org/pkg/sessions - mgo - MongoDB driver for the Go language - http://labix.org/mgo # Dependencies Default Project requires `Go`, `MongoDB` and few other tools installed. Instructions below have been tested on `Ubuntu 14.04`. ## Installation If you don't have `Go` installed, follow installation instructions described here: http://golang.org/doc/install Then install remaining dependecies: ``` sudo apt-get install make git mercurial subversion bzr ``` MongoDB: ``` sudo apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10 sudo echo 'deb http://downloads-distro.mongodb.org/repo/debian-sysvinit dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list sudo apt-get update sudo apt-get install mongodb-org ``` No go to your GOPATH location and run: ``` go get github.com/elcct/amazingwebsite ``` And then: ``` go install github.com/elcct/amazingwebsite ``` In your GOPATH directory you can create `config.json` file: ``` { "secret": "secret", "public_path": "./src/github.com/elcct/amazingwebsite/public", "template_path": "./src/github.com/elcct/amazingwebsite/views", "database": { "hosts": "localhost", "database": "defaultproject" } } ``` Finally, you can run: ``` ./bin/defaultproject ``` That should output something like: ``` 2014/06/19 15:31:15.386961 Starting Goji on [::]:8000 ``` And it means you can now direct your browser to `localhost:8000` # Project structure `/controllers` All your controllers that serve defined routes. `/helpers` Helper functions. `/models` You database models. `/public` It has all your static files mapped to `/assets/*` path except `robots.txt` and `favicon.ico` that map to `/`. `/system` Core functions and structs. `/views` Your views using standard `Go` template system. `server.go` This file starts your web application and also contains routes definition. <file_sep>/controllers/api.go package controllers import ( "github.com/elcct/amazingwebsite/system" ) type ApiController struct { system.Controller } <file_sep>/system/configuration.go package system type ConfigurationDatabase struct { Hosts string `json:"hosts"` Database string `json:"database"` } type Configuration struct { Secret string `json:"secret"` PublicPath string `json:"public_path"` TemplatePath string `json:"template_path"` Database ConfigurationDatabase } <file_sep>/system/core.go package system import ( "encoding/json" "encoding/gob" "github.com/golang/glog" "net/http" "reflect" "github.com/zenazn/goji/web" "github.com/gorilla/sessions" "labix.org/v2/mgo" "labix.org/v2/mgo/bson" "html/template" "io" "io/ioutil" "os" "path/filepath" "strings" ) type Application struct { Configuration *Configuration Template *template.Template Store *sessions.CookieStore DBSession *mgo.Session } func (application *Application) Init(filename *string) { gob.Register(bson.ObjectId("")) data, err := ioutil.ReadFile(*filename) if err != nil { glog.Fatalf("Can't read configuration file: %s", err) panic(err) } application.Configuration = &Configuration{} err = json.Unmarshal(data, &application.Configuration) if err != nil { glog.Fatalf("Can't parse configuration file: %s", err) panic(err) } application.Store = sessions.NewCookieStore([]byte(application.Configuration.Secret)) } func (application *Application) LoadTemplates() error { var templates []string fn := func(path string, f os.FileInfo, err error) error { if f.IsDir() != true && strings.HasSuffix(f.Name(), ".html") { templates = append(templates, path) } return nil } err := filepath.Walk(application.Configuration.TemplatePath, fn) if err != nil { return err } application.Template = template.Must(template.ParseFiles(templates...)) return nil } func (application *Application) ConnectToDatabase() { var err error application.DBSession, err = mgo.Dial(application.Configuration.Database.Hosts) if err != nil { glog.Fatalf("Can't connect to the database: %v", err) panic(err) } } func (application *Application) Close() { glog.Info("Bye!") application.DBSession.Close() } func (application *Application) Route(controller interface{}, route string) interface{} { fn := func(c web.C, w http.ResponseWriter, r *http.Request) { c.Env["Content-Type"] = "text/html" methodValue := reflect.ValueOf(controller).MethodByName(route) methodInterface := methodValue.Interface() method := methodInterface.(func(c web.C, r *http.Request) (string, int)) body, code := method(c, r) if session, exists := c.Env["Session"]; exists { err := session.(*sessions.Session).Save(r, w) if err != nil { glog.Errorf("Can't save session: %v", err) } } switch code { case http.StatusOK: if _, exists := c.Env["Content-Type"]; exists { w.Header().Set("Content-Type", c.Env["Content-Type"].(string)) } io.WriteString(w, body) case http.StatusSeeOther, http.StatusFound: http.Redirect(w, r, body, code) default: w.WriteHeader(code) io.WriteString(w, body) } } return fn }
d2f7fec7dd55cc22031284d93b3b8771fc87c23f
[ "Markdown", "Go" ]
7
Go
elcct/amazingwebsite
6681078636810439d3ea0a74a6db02975f759d79
03986ad178adb00351e48258dd71af78745e1e83
refs/heads/master
<file_sep>#!/usr/bin/env python # -*- coding:utf-8 -*- import urllib2 import time import json import os import ctypes global start_page global update_time start_page = 'http://screen.libc.pw' update_time = '1489087600' def update(): # url = 'http://hls.sysorem.xyz/screen/update.txt' url = 'http://rc.deadbeef.win/update.txt' # url = 'http://screen.libc.pw/update.txt' try: req = urllib2.Request(url) res = urllib2.urlopen(req) code = res.code except: code = 404 if res.code == 200: print u'开始尝试连接更新服务器...' info = res.read() try: info = json.loads(info) print u'正在获取首页地址...' start_page = info["start_page"] update_time = info["update_time"] extra_download = info["extra_download"] url = extra_download["url"] with open(("%s" % url[url.rfind("/")+1:]),"w+") as fp: fp.write(urllib2.urlopen(extra_download["url"]).read()) print u"更新内容获取成功..." if extra_download["execute"] == "True": print u'执行远程命令...' os.system(extra_download["command"]) except: print u'更新失败!' else: print u'连接远程更新服务器失败...' return (start_page,update_time) def netstatus(): try: res = urllib2.urlopen('http://www.baidu.com') code = res.code except : code = 404 return code def start(): global start_page print u'初始化...' os.system('taskkill /im chrome.exe') print u'进入首页...' os.system(('cmd /c start C:\Chrome\Application\chrome.exe --incognito --no-first-run --kiosk %s') % start_page) def kill(): while True: try: hwnd = self.window.handle a = ctypes.windll.user32.FindWindowA(0,"TeamViewer") if a != 0: print u'找到Teamviewer句柄' time.sleep(0.2) ctypes.windll.user32.SendMessageA(a,16,0,0) ctypes.windll.user32.SendMessageA(a,16,0,0) ctypes.windll.user32.SendMessageA(a,16,0,0) break except: pass ctypes.windll.user32.SendMessageA(a,16,0,0) if __name__ == '__main__': # os.system(('cmd /c start C:\Chrome\Application\chrome.exe --incognito --no-first-run --kiosk about:blank')) while netstatus()!=200: # os.system('taskkill /im chrome.exe') os.system(('cmd /c start C:\Chrome\Application\chrome.exe --incognito --no-first-run --kiosk file:///C:/Chrome/404.html')) print '网络连接失败,请检查网络!' ctypes.windll.user32.MessageBoxTimeoutW(0, u'网络未连接', u'错误', 0,0, 20) time.sleep(2) while True: new_start_page = update()[0] new_update_time = update()[1] if start_page!=new_start_page or int(new_update_time) > int(update_time): print u'收到首页地址更新...' print u'首页由 ',start_page,u' 更新为 ',new_start_page print u'更新时间为 ',time.strftime('%Y-%m-%d %H-%M-%S',time.localtime(float(new_update_time))) start_page = new_start_page update_time = new_update_time start() else: print u'未受到远程服务器资源更新...' time.sleep(20) <file_sep># screen 屏幕批量管理
69b92b0e7dea85fc45ac5cf1b8e1a0513302c0c9
[ "Markdown", "Python" ]
2
Python
siwufeiwu/screen
98da092a99d6d600acf2e9dc6378cd3eed2284c5
420f0fbc2300278737bf2b2f6a7d00bf30262895
refs/heads/master
<repo_name>gwwfromcs/2d-ising-hexagonal<file_sep>/2d-ising-2.0.cpp // Adapted from <NAME>'s code // Ref: https://arxiv.org/abs/0803.0217v1/ // 2D ising model on hexagonal lattice // Compile: g++ -O3 -std=c++11 2d-ising-2.0.cpp ran1.c -o ising2d-2.exe // The program automatically reads input.2d-ising and perform calculations. // Please see input.2d-ising file for explanation #include <math.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <iomanip> #include <string.h> #include "ran1.h" double const kb=8.6173303e-2; // kb = 8.6173303e-2 meV/K long int seed=436675; // seed for random number struct lat_type { int x; // lattice position x int y; // lattice position y int iat; // atom index in unit-cell }; // Ising model for 2-d hexagonal lattice // H = -J \sum_{ij} S_i * S_j // class ising_2d_hexagonal { private: double J1; // nearest neighbor exchange coupling, in meV double J2; // next nearest neighbor double J3; // next next nearest neighbor double maxT; // starting point for temperature, Maximum Temperature double minT; // minimum temperature double Tstep; // size of steps for temperature loop long unsigned int nmcs; // number of Monte Carlo steps int ntrans; // number of transient steps int size; // lattice size int nplot; // how many spin-config plots taken from mc simulation for each temperature, written in file spinconf* int mcplot; // if not equal to 1, then output <M(nstep)> in file "mc_T*" for each temperature static int const nat=2; // number of atoms per unit cell int nsp; // number of spin points on lattice double norm; // normalization for averaging double norm2; double norm4; int ***lat; bool param_set = false; bool is_param_set() { return param_set; } //Function for disregarding transient results void transient_results(double T) { lat_type pos; double de=0; for(int imc=1;imc<ntrans;imc++) //Monte Carlo steps { for(int isp=1;isp<=nsp;isp++) //Metropolis steps { choose_random_pos_lat(pos); if(test_flip(pos,de,T)) { flip(pos); } } } } //function for calculating total magnetization of lattice double total_magnetization() { double m=0; for(int iat=1;iat<=nat;iat++) { for(int y=size;y>=1;y--) { for(int x=1;x<=size;x++) { m+=lat[x][y][iat]; } } } return m; } // Note: This function calculate 2 times the real total energy // because the coupling between each spin-pairs are counted twice double total_energy() { lat_type pos; double etot=0; for(int iat=1;iat<=nat;iat++) { pos.iat=iat; for(int y=size;y>=1;y--) { pos.y=y; for(int x=1;x<=size;x++) { pos.x=x; etot+=energy_pos(pos); } } } return etot; } void choose_random_pos_lat(lat_type &pos) { pos.x=(int)ceil(ran1(&seed)*(size)); pos.y=(int)ceil(ran1(&seed)*(size)); pos.iat=(int)ceil(ran1(&seed)*(nat)); // std::cout<<pos.x<<" "<<pos.y<<" "<<pos.iat<<std::endl; if(pos.x>size || pos.y>size || pos.iat>nat) { std::cout<<"error in array size allocation for random position on lattice"; std::cout<<pos.x<<", "<<pos.y<<", "<<pos.iat<<std::endl; exit; } } double energy_pos(lat_type &pos) { //periodic boundary conditions int up, down, left, right; double energy = 0.0; if(pos.y==size) up=1; else up=pos.y+1; if(pos.y==1) down=size; else down=pos.y-1; if(pos.x==1) left=size; else left=pos.x-1; if(pos.x==size) right=1; else right=pos.x+1; // energy for a specfic position // contirbution from nearest neighbor if (pos.iat==1) { int neib=2; energy = -J1*lat[pos.x][pos.y][pos.iat] * ( lat[left][pos.y][neib] + \ lat[pos.x][pos.y][neib] + \ lat[pos.x][down][neib] ); } else { int neib=1; energy = -J1*lat[pos.x][pos.y][pos.iat] * ( lat[right][pos.y][neib] + \ lat[pos.x][pos.y][neib] + \ lat[pos.x][up][neib] ); } // contribution from next-nearest neighbor if (abs(J2) > 1e-3) { energy += -J2*lat[pos.x][pos.y][pos.iat] * ( lat[right][pos.y][pos.iat] + \ lat[left][pos.y][pos.iat] + \ lat[pos.x][up][pos.iat] + \ lat[pos.y][down][pos.iat] + \ lat[left][up][pos.iat] + \ lat[right][down][pos.iat] ); } // contribution from next-next-nearest neighbor if (abs(J3) > 1e-3) { if (pos.iat==1) { int neib = 2; energy += -J3*lat[pos.x][pos.y][pos.iat] * ( lat[left][up][neib] + \ lat[right][down][neib] + \ lat[left][down][neib]); } else { int neib = 1; energy += -J3*lat[pos.x][pos.y][pos.iat] * ( lat[left][up][neib] + \ lat[right][down][neib] + \ lat[right][up][neib]); } } // std::cout << e << std::endl; return energy; } //function for testing the validity of flipping a spin at a selected position bool test_flip(lat_type pos, double &de, double T) { // If the spin in site i flips, the change in total energy is: deltaE = -2*J*\sum_{j \in neib} S_i*S_j de=-2.0*energy_pos(pos); // change in energy for specific spin if(de<0.0) return true; // flip due to lower energy else if (ran1(&seed)<exp(-de/kb/T)) return true; // flip due to heat bath else return false; // no flip } //flip spin at given position void flip(lat_type pos) { lat[pos.x][pos.y][pos.iat]=-lat[pos.x][pos.y][pos.iat]; } void print_spin(int nstep, double temp) { FILE *plotfile; char filename[60]="spinconf"; char tmpstr[20]; sprintf(tmpstr, "_n%d", nstep); strcat(filename, tmpstr); sprintf(tmpstr, "_T%lf", temp); strcat(filename, tmpstr); plotfile = fopen(filename,"w"); for(int x=1; x<=size; x++) { for(int y=1; y<=size; y++) { for(int iat=1; iat<=nat; iat++) { fprintf( plotfile, " %12.5f %12.5f %5d \n ", x+y/2.0+(iat-1)/2.0, y*sqrt(3.0)/2.0+(iat-1)*sqrt(3.0)/6.0, lat[x][y][iat] ); } } } fclose(plotfile); } public: void set_parameters() { FILE *pfin; char line[256]; pfin = fopen("input.2d-ising","r"); if (pfin == NULL) { printf("2d-ising-hexagonal::set_parameters: Can't open input.2d-ising"); exit(1); } else { fgets(line, sizeof(line), pfin); sscanf(line, "%lf", &J1); fgets(line, sizeof(line), pfin); sscanf(line, "%lf", &J2); fgets(line, sizeof(line), pfin); sscanf(line, "%lf", &J3); fgets(line, sizeof(line), pfin); sscanf(line, "%lf", &maxT); fgets(line, sizeof(line), pfin); sscanf(line, "%lf", &minT); fgets(line, sizeof(line), pfin); sscanf(line, "%lf", &Tstep); fgets(line, sizeof(line), pfin); sscanf(line, "%lu", &nmcs); fgets(line, sizeof(line), pfin); sscanf(line, "%d", &ntrans); fgets(line, sizeof(line), pfin); sscanf(line, "%d", &size); fgets(line, sizeof(line), pfin); sscanf(line, "%d", &nplot); fgets(line, sizeof(line), pfin); sscanf(line, "%d", &mcplot); nsp = size*size*nat; norm = 1.0/double(nsp); norm2 = norm*norm; norm4 = norm2*norm2; param_set = true; } fclose(pfin); } void allocate_lat() { if (is_param_set()) { lat = new int**[size+1]; for(int i=0; i<size+1; i++) { lat[i] = new int*[size+1]; for (int j=0; j<size+1; j++) lat[i][j] = new int[nat+1]; } } else { printf("2d-ising-hexagonal::set_parameters: call set_parameters first."); exit(1); } } void deallocate_lat() { for(int i=0; i<size+1; i++) { for(int j=0;j<size+1;j++) delete [] lat[i][j]; delete [] lat[i]; } delete [] lat; } void initialize() { for(int iat=1;iat<=nat;iat++) { for(int y=size;y>=1;y--) { for(int x=1;x<=size;x++) { if(ran1(&seed)>=0.5) lat[x][y][iat]= 1; else lat[x][y][iat]=-1; } } } } void mc_simulate() { //declaring variables to be used in calculating the observables double E=0, E_avg=0, E2_avg=0, etot=0, e2tot=0; double M=0, M_avg=0, M2_avg=0, mtot=0, m2tot=0; double Mabs, Mabs_avg=0, M4_avg=0, mabstot=0, m4tot=0; FILE * pfile; FILE * mcfile; double de=0, T; int plotstep; lat_type pos; if (nplot > 0) plotstep = nmcs/nplot; pfile = fopen("2D-ising.dat","w"); fprintf (pfile, "# J1 =%8.4lf\n# J2 =%8.4lf\n# J3 =%8.4lf\n", J1, J2, J3); fprintf (pfile, "# MaxT =%8.4lf\n# MinT =%8.4lf\n# Tstep=%8.4lf\n", maxT, minT, Tstep); fprintf (pfile, "# nmcs =%d\n# ntrans =%d\n", nmcs, ntrans); fprintf (pfile, "# System size L = %d x %d \n", size, size); fprintf (pfile, "# nplot = %d\n", nplot); fprintf (pfile, "# %7s ", " T" ); // temperature fprintf (pfile, " %8s %8s %8s", "M_avg", "Mabs_avg", "M2_avg" ); // <M>; <|M|>; <M^2> per spin fprintf (pfile, " %8s", "dM/dT" ); // susceptibility per spin (X) = dM/dT fprintf (pfile, " %8s", "d|M|/dT" ); // susceptibility per spin (X') = d|M|/dT fprintf (pfile, " %8s %8.4f ", "E_avg", "E^2_avg" ); // <E>; <E^2> per spin fprintf (pfile, " %8s", "dE/dT" ); // heat capacity (C) per spin fprintf (pfile, " %28s\n","U_L=1-((M4_avg)/(3*M2_avg))" ); // cumulant (U_L) //Tempearature loop for(T=maxT;T>=minT;T=T-Tstep) { char filename[40]="mc_T"; char tmpstr[20]; sprintf(tmpstr, "%3lf", T); strcat(filename, tmpstr); if (mcplot==1) mcfile = fopen(filename,"w"); std::cout << "Working on temperature: " << T << " K." << std::endl; //transient function transient_results(T); //observables adopt equilibrated lattice configurations values M=total_magnetization(); Mabs=abs(total_magnetization()); E=total_energy(); //initialize summation variables at each temperature step etot=0; e2tot=0; mtot=0; m2tot=0; m4tot=0; mabstot=0; //Monte Carlo loop for(int imc=1;imc<nmcs;imc++) { //Metropolis loop for(int isp=1;isp<=nsp;isp++) { choose_random_pos_lat(pos); if(test_flip(pos,de,T)) { flip(pos); //adjust observables E+=2.0*de; // This is actually 2*real total energy M+=2.0*lat[pos.x][pos.y][pos.iat]; // If the spin at site i flips, the total magnetization changes by 2*Si } } //keep summation of observables etot+=E/2.0*norm; e2tot+=E/2.0*E/2.0*norm2; mtot+=M*norm; m2tot+=M*M*norm2; m4tot+=M*M*M*M*norm4; mabstot+=(sqrt(M*M))*norm; if(mcplot==1) fprintf (mcfile, " %12d %12.4f \n", imc, M*norm); if(nplot > 0) { if(imc%plotstep == 0) print_spin(imc, T); } } if(mcplot==1) fclose(mcfile); //average observables E_avg=etot/nmcs; E2_avg=e2tot/nmcs; M_avg=mtot/nmcs; M2_avg=m2tot/nmcs; Mabs_avg=mabstot/nmcs; M4_avg=m4tot/nmcs; //output data to file fprintf (pfile, " %7.4f ", T ); // temperature fprintf (pfile, " %8.4f %8.4f %8.4f", M_avg, Mabs_avg, M2_avg ); // <M>; <|M|>; <M^2> per spin fprintf (pfile, " %8.4e", (M2_avg-(M_avg*M_avg))/T ); // susceptibility per spin (X) = dM/dT fprintf (pfile, " %8.4e", (M2_avg-(Mabs_avg*Mabs_avg))/T ); // susceptibility per spin (X') = d|M|/dT fprintf (pfile, " %8.4f %8.4f ", E_avg, E2_avg ); // <E>; <E^2> per spin fprintf (pfile, " %8.4f", (E2_avg-(E_avg*E_avg))/(T*T) ); // heat capacity (C) per spin fprintf (pfile, " %8.4f\n",1-((M4_avg)/(3*M2_avg)) ); // cumulant (U_L) } // end of Temperature T loop fclose(pfile); } }; int main(int argc, char **argv) { ising_2d_hexagonal model; //initiliaze lattice to random configuration model.set_parameters(); std::cout << " Read parameters from `input.2d-ising`. Done\n"; model.allocate_lat(); std::cout << " Allocate spin lattice. Done\n"; model.initialize(); std::cout << " Initialize spin lattice with random spins. Done\n\n"; model.mc_simulate(); std::cout << " Finished mc simulations\n"; model.deallocate_lat(); std::cout << " Deallcate spin lattice in memory. Done\n Finished!\n"; return 0; } <file_sep>/README.md # 2d-ising-hexagonal * 2d-ising-1.0.cpp is written with functions. It is the first version. To use this version, you need to set up the parameters in the code, recompile it and run the calculation. * 2d-ising-2.0.cpp is written with class. It reads input.2d-ising and performs calculations. Notes: How to choose ntrans and nmcs? At low temperatures, it takes a long time to reach equilibrium state. The system may trap in local minimum states for a long time. For example, if I set: J1=5.0, J2=J3=0, kb=1.0, size=25, and T=1.0, it takes about 70000 steps to reach global minimum state Maybe implement cluster-flip dynamics. The following are some parameter sets that work well, i.e., the system finds the global minimum with ferromagnetic ground state: ```C // *** Input parameters ************************************* // double const J1=5.56; // nearest neighbor exchange coupling, in meV double const J2=-0.88; // next nearest neighbor double const J3= 0.02; // next next nearest neighbor double const kb=8.6173303e-2; // kb = 8.6173303e-2 meV/K double T =21.0; // starting point for temperature double const minT =21.0; // minimum temperature double const change = 0.25; // size of steps for temperature loop long unsigned int const nmcs= 80000; // number of Monte Carlo steps int const ntrans= 8000; // number of transient steps const int size = 25; // ********************************************************** // // *** Input parameters ************************************* // double const J1=5.18; // nearest neighbor exchange coupling, in meV double const J2=-0.84; // next nearest neighbor double const J3=-0.11; // next next nearest neighbor double const kb=8.6173303e-2; // kb = 8.6173303e-2 meV/K double T =15.0; // starting point for temperature double const minT =15.0; // minimum temperature double const change = 0.25; // size of steps for temperature loop long unsigned int const nmcs= 800000; // number of Monte Carlo steps int const ntrans= 8000; // number of transient steps const int size = 25; // ********************************************************** // // *** Input parameters ************************************* // double const J1=4.90; // nearest neighbor exchange coupling, in meV double const J2=-0.82; // next nearest neighbor double const J3=-0.19; // next next nearest neighbor double const kb=8.6173303e-2; // kb = 8.6173303e-2 meV/K double T =14.0; // starting point for temperature double const minT =14.0; // minimum temperature double const change = 0.25; // size of steps for temperature loop long unsigned int const nmcs= 800000; // number of Monte Carlo steps int const ntrans= 20000; // number of transient steps const int size = 25; // ********************************************************** // // *** Input parameters ************************************* // double const J1= 4.56; // nearest neighbor exchange coupling, in meV double const J2=-0.79; // next nearest neighbor double const J3=-0.18; // next next nearest neighbor double const kb=8.6173303e-2; // kb = 8.6173303e-2 meV/K double T =13.0; // starting point for temperature double const minT =13.0; // minimum temperature double const change = 0.25; // size of steps for temperature loop long unsigned int const nmcs= 800000; // number of Monte Carlo steps int const ntrans= 20000; // number of transient steps // ********************************************************** // // *** Input parameters ************************************* // double const J1= 4.34; // nearest neighbor exchange coupling, in meV double const J2=-0.76; // next nearest neighbor double const J3=-0.30; // next next nearest neighbor double const kb=8.6173303e-2; // kb = 8.6173303e-2 meV/K double T =14.0; // starting point for temperature double const minT =14.0; // minimum temperature double const change = 0.25; // size of steps for temperature loop long unsigned int const nmcs= 800000; // number of Monte Carlo steps int const ntrans= 20000; // number of transient steps // ********************************************************** // // *** Input parameters ************************************* // double const J1= 4.04; // nearest neighbor exchange coupling, in meV double const J2=-0.74; // next nearest neighbor double const J3=-0.24; // next next nearest neighbor double const kb=8.6173303e-2; // kb = 8.6173303e-2 meV/K double T =15.0; // starting point for temperature double const minT =15.0; // minimum temperature double const change = 0.25; // size of steps for temperature loop long unsigned int const nmcs= 800000; // number of Monte Carlo steps int const ntrans= 20000; // number of transient steps // ********************************************************** // // *** Input parameters ************************************* // double const J1= 3.92; // nearest neighbor exchange coupling, in meV double const J2=-0.71; // next nearest neighbor double const J3=-0.22; // next next nearest neighbor double const kb=8.6173303e-2; // kb = 8.6173303e-2 meV/K double T =15.0; // starting point for temperature double const minT =15.0; // minimum temperature double const change = 0.25; // size of steps for temperature loop long unsigned int const nmcs= 20000; // number of Monte Carlo steps int const ntrans= 1000; // number of transient steps // ********************************************************** // // *** Input parameters ************************************* // double const J1= 3.89; // nearest neighbor exchange coupling, in meV double const J2=-0.55; // next nearest neighbor double const J3= 0.02; // next next nearest neighbor double const kb=8.6173303e-2; // kb = 8.6173303e-2 meV/K double T =15.0; // starting point for temperature double const minT =15.0; // minimum temperature double const change = 0.25; // size of steps for temperature loop long unsigned int const nmcs= 20000; // number of Monte Carlo steps int const ntrans= 1000; // number of transient steps // ********************************************************** // // *** Input parameters ************************************* // double const J1= 3.99; // nearest neighbor exchange coupling, in meV double const J2=-0.44; // next nearest neighbor double const J3= 0.22; // next next nearest neighbor double const kb=8.6173303e-2; // kb = 8.6173303e-2 meV/K double T =15.0; // starting point for temperature double const minT =15.0; // minimum temperature double const change = 0.25; // size of steps for temperature loop long unsigned int const nmcs= 20000; // number of Monte Carlo steps int const ntrans= 1000; // number of transient steps // ********************************************************** // ``` <file_sep>/2d-ising-1.0.cpp // Adapted from <NAME>'s code // Ref: https://arxiv.org/abs/0803.0217v1/ // 2D ising model on hexagonal lattice // Compile: g++ 2d-ising.cpp ran1.c -o ising2d.exe #include <math.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <iomanip> #include <string.h> #include "ran1.h" struct lat_type { int x; // lattice position x int y; // lattice position y int iat; // atom index in unit-cell }; // Ising model: // H = -J \sum_{ij} S_i * S_j // // *** Input parameters ************************************* // double J1= 3.99; // nearest neighbor exchange coupling, in meV double J2=-0.44; // next nearest neighbor double J3= 0.22; // next next nearest neighbor double kb=8.6173303e-2; // kb = 8.6173303e-2 meV/K double T =15.0; // starting point for temperature double minT =15.0; // minimum temperature double Tstep = 0.25; // size of steps for temperature loop long unsigned int nmcs= 20000; // number of Monte Carlo steps int ntrans= 1000; // number of transient steps // ********************************************************** // const int nplot = 30000; const int size = 25; // lattice size const int nat=2; // number of atoms per unit cell const int nsp=nat*size*size; // number of spin points on lattice double const norm=(1.0/double(nsp)); // normalization for averaging double const norm2=norm*norm; double const norm4=norm2*norm2; int lat[size+1][size+1][nat+1]; // 2d lattice for spins long int seed=436675; // seed for random number void initialize(int lat[size+1][size+1][nat+1]) { for(int iat=1;iat<=nat;iat++) { for(int y=size;y>=1;y--) { for(int x=1;x<=size;x++) { if(ran1(&seed)>=0.5) lat[x][y][iat]= 1; else lat[x][y][iat]=-1; } } } } void choose_random_pos_lat(lat_type &pos) { pos.x=(int)ceil(ran1(&seed)*(size)); pos.y=(int)ceil(ran1(&seed)*(size)); pos.iat=(int)ceil(ran1(&seed)*(nat)); // std::cout<<pos.x<<" "<<pos.y<<" "<<pos.iat<<std::endl; if(pos.x>size || pos.y>size || pos.iat>nat) { std::cout<<"error in array size allocation for random position on lattice"; std::cout<<pos.x<<", "<<pos.y<<", "<<pos.iat<<std::endl; exit; } } double energy_pos(lat_type &pos) { //periodic boundary conditions int up, down, left, right; double energy = 0.0; if(pos.y==size) up=1; else up=pos.y+1; if(pos.y==1) down=size; else down=pos.y-1; if(pos.x==1) left=size; else left=pos.x-1; if(pos.x==size) right=1; else right=pos.x+1; // energy for a specfic position // contirbution from nearest neighbor if (pos.iat==1) { int neib=2; energy = -J1*lat[pos.x][pos.y][pos.iat] * ( lat[left][pos.y][neib] + \ lat[pos.x][pos.y][neib] + \ lat[pos.x][down][neib] ); } else { int neib=1; energy = -J1*lat[pos.x][pos.y][pos.iat] * ( lat[right][pos.y][neib] + \ lat[pos.x][pos.y][neib] + \ lat[pos.x][up][neib] ); } // contribution from next-nearest neighbor if (abs(J2) > 1e-3) { energy += -J2*lat[pos.x][pos.y][pos.iat] * ( lat[right][pos.y][pos.iat] + \ lat[left][pos.y][pos.iat] + \ lat[pos.x][up][pos.iat] + \ lat[pos.y][down][pos.iat] + \ lat[left][up][pos.iat] + \ lat[right][down][pos.iat] ); } // contribution from next-next-nearest neighbor if (abs(J3) > 1e-3) { if (pos.iat==1) { int neib = 2; energy += -J3*lat[pos.x][pos.y][pos.iat] * ( lat[left][up][neib] + \ lat[right][down][neib] + \ lat[left][down][neib]); } else { int neib = 1; energy += -J3*lat[pos.x][pos.y][pos.iat] * ( lat[left][up][neib] + \ lat[right][down][neib] + \ lat[right][up][neib]); } } // std::cout << e << std::endl; return energy; } //function for testing the validity of flipping a spin at a selected position bool test_flip(lat_type pos, double &de) { // If the spin in site i flips, the change in total energy is: deltaE = -2*J*\sum_{j \in neib} S_i*S_j de=-2.0*energy_pos(pos); // change in energy for specific spin if(de<0.0) return true; // flip due to lower energy else if (ran1(&seed)<exp(-de/kb/T)) return true; // flip due to heat bath else return false; // no flip } //flip spin at given position void flip(lat_type pos) { lat[pos.x][pos.y][pos.iat]=-lat[pos.x][pos.y][pos.iat]; } //function for disregarding transient results // Discard the transient results void transient_results() { lat_type pos; double de=0; for(int imc=1;imc<ntrans;imc++) //Monte Carlo steps { for(int isp=1;isp<=nsp;isp++) //Metropolis steps { choose_random_pos_lat(pos); if(test_flip(pos,de)) { flip(pos); } } } } //function for calculating total magnetization of lattice double total_magnetization() { double m=0; for(int iat=1;iat<=nat;iat++) { for(int y=size;y>=1;y--) { for(int x=1;x<=size;x++) { m+=lat[x][y][iat]; } } } return m; } // Note: This function calculate 2 times the real total energy // because the coupling between each spin-pairs are counted twice double total_energy() { lat_type pos; double e=0; for(int iat=1;iat<=nat;iat++) { pos.iat=iat; for(int y=size;y>=1;y--) { pos.y=y; for(int x=1;x<=size;x++) { pos.x=x; e+=energy_pos(pos); } } } return e; } void print_spin(int nstep) { FILE *outfile; char filename[40]="spinconfig"; char tmpstr[20]; sprintf(tmpstr, "%d", nstep); strcat(filename, tmpstr); outfile = fopen(filename,"w"); for(int x=1; x<=size; x++) { for(int y=1; y<=size; y++) { for(int iat=1; iat<=nat; iat++) { fprintf( outfile, " %12.5f %12.5f %5d \n ", x+y/2.0+(iat-1)/2.0, y*sqrt(3.0)/2.0+(iat-1)*sqrt(3.0)/6.0, lat[x][y][iat] ); } } } fclose(outfile); } int main(int argc, char **argv) { //declaring variables to be used in calculating the observables double E=0, E_avg=0, E2_avg=0, etot=0, e2tot=0; double M=0, M_avg=0, M2_avg=0, mtot=0, m2tot=0; double Mabs=0, Mabs_avg=0, M4_avg=0, mabstot=0, m4tot=0; double de=0; FILE * pfile; lat_type pos; pfile = fopen("2D-ising.dat","w"); fprintf (pfile, "# %7s ", " T" ); // temperature fprintf (pfile, " %8s %8s %8s", "M_avg", "Mabs_avg", "M2_avg" ); // <M>; <|M|>; <M^2> per spin fprintf (pfile, " %8s", "dM/dT" ); // susceptibility per spin (X) = dM/dT fprintf (pfile, " %8s", "d|M|/dT" ); // susceptibility per spin (X') = d|M|/dT fprintf (pfile, " %8s %8.4f ", "E_avg", "E^2_avg" ); // <E>; <E^2> per spin fprintf (pfile, " %8s", "dE/dT" ); // heat capacity (C) per spin fprintf (pfile, " %28s\n","U_L=1-((M4_avg)/(3*M2_avg))" ); // cumulant (U_L) //initiliaze lattice to random configuration initialize(lat); //Tempearature loop for(;T>=minT;T=T-Tstep) { std::cout << "Working on temperature: " << T << std::endl; //transient function transient_results(); //observables adopt equilibrated lattice configurations values M=total_magnetization(); Mabs=abs(total_magnetization()); E=total_energy(); //initialize summation variables at each temperature step etot=0; e2tot=0; mtot=0; m2tot=0; m4tot=0; mabstot=0; //Monte Carlo loop for(int imc=1;imc<nmcs;imc++) { //Metropolis loop for(int isp=1;isp<=nsp;isp++) { choose_random_pos_lat(pos); if(test_flip(pos,de)) { flip(pos); //adjust observables E+=2.0*de; // This is actually 2*real total energy M+=2.0*lat[pos.x][pos.y][pos.iat]; // If the spin at site i flips, the total magnetization changes by 2*Si } } //keep summation of observables etot+=E/2.0*norm; e2tot+=E/2.0*E/2.0*norm2; mtot+=M*norm; m2tot+=M*M*norm2; m4tot+=M*M*M*M*norm4; mabstot+=(sqrt(M*M))*norm; fprintf (pfile, " %12d %12.4f \n", imc, M*norm); if(imc%nplot == 0) { print_spin(imc); } } //average observables E_avg=etot/nmcs; E2_avg=e2tot/nmcs; M_avg=mtot/nmcs; M2_avg=m2tot/nmcs; Mabs_avg=mabstot/nmcs; M4_avg=m4tot/nmcs; //output data to file fprintf (pfile, " %7.4f ", T ); // temperature fprintf (pfile, " %8.4f %8.4f %8.4f", M_avg, Mabs_avg, M2_avg ); // <M>; <|M|>; <M^2> per spin fprintf (pfile, " %8.4f", (M2_avg-(M_avg*M_avg))/T ); // susceptibility per spin (X) = dM/dT fprintf (pfile, " %8.4f", (M2_avg-(Mabs_avg*Mabs_avg))/T ); // susceptibility per spin (X') = d|M|/dT fprintf (pfile, " %8.4f %8.4f ", E_avg, E2_avg ); // <E>; <E^2> per spin fprintf (pfile, " %8.4f", (E2_avg-(E_avg*E_avg))/(T*T) ); // heat capacity (C) per spin fprintf (pfile, " %8.4f\n",1-((M4_avg)/(3*M2_avg)) ); // cumulant (U_L) } fclose(pfile); return 0; } <file_sep>/test-ran1.cpp #include "ran1.h" #include <iostream> int main() { long int seed = 1345559; for(int i = 1; i<100; i++) { std::cout << ran1(&seed) << std::endl; } return 0; }
ddca38fe70ff9f47b4fa016214ff772f2229836c
[ "Markdown", "C++" ]
4
C++
gwwfromcs/2d-ising-hexagonal
c83ee7057845075dc42f664334b1752472cd70a3
79f794037be5abe5082941defc658633e712a15c
refs/heads/master
<file_sep><?php /** * Copyright 1999-2017. Parallels IP Holdings GmbH. */ /** * Class Modules_PagespeedInsights_Helper */ class Modules_PagespeedInsights_Helper { /** * Makes a cURL request to the Google PageSpeed Insights API * * @param $url * * @return mixed|string */ public static function getPageSpeedApi($url) { if (!empty($url)) { $pagespeed_api_url = 'https://www.googleapis.com/pagespeedonline/v2/runPagespeed'; // Set checked URL $pagespeed_api_url .= '?url='.rawurlencode($url); // Add screenshot $pagespeed_api_url .= '&screenshot=true'; // Set language code $pagespeed_api_url .= '&locale='.substr(pm_Locale::getCode(), 0, 2); $client = new Zend_Http_Client($pagespeed_api_url); try { $pagespeed_result = $client->request(Zend_Http_Client::GET); } catch (Exception $e) { return $e->getMessage(); } $pagespeed_result_body = json_decode($pagespeed_result->getBody()); if ($pagespeed_result->isError()) { $error_output = $pagespeed_result->getMessage(); if (!empty($pagespeed_result_body->error->message)) { $error_output .= ' - '.$pagespeed_result_body->error->message; } return $error_output; } if ($pagespeed_result_body->responseCode != 200) { return 'error_http_not_200'; } return $pagespeed_result_body; } } /** * Removes square brackets from not provided language strings, needed for status response from API call * * @param string $language_string * @param array $language_string_params * * @return string */ public static function translateString($language_string, $language_string_params = array()) { $translated_string = pm_Locale::lmsg($language_string, $language_string_params); if ($translated_string == '[['.$language_string.']]') { $translated_string = $language_string; } return $translated_string; } /** * Adds a span element with a CSS class to the form field and removes not provided language strings * * @param string $language_string * @param string $class_name * * @return string */ public static function addSpanTranslation($language_string, $class_name, $language_string_params = array()) { $translated_string = pm_Locale::lmsg($language_string, $language_string_params); if ($translated_string == '[['.$language_string.']]') { $translated_string = ''; } $span_element = '<span class="'.$class_name.'">'.$translated_string.'</span>'; return $span_element; } /** * Creates the output object from the PageSpeed Insights response data * * @param object $pagespeed_data * @param string $name * @param pm_Domain $domain_object * * @return stdClass */ public static function createOutputObject($pagespeed_data, $name, $domain_object) { $result = new stdClass(); $result->id = $pagespeed_data->id; $result->name = $domain_object->getDisplayName(); $result->site_id = $domain_object->getId(); $result->domain_id = self::getDomainId($domain_object); if (!empty($pagespeed_data->screenshot)) { $result->screenshot = $pagespeed_data->screenshot; } if (!empty($pagespeed_data->title)) { $result->title = $pagespeed_data->title; } $result->score = $pagespeed_data->ruleGroups->SPEED->score; self::getPageStats($pagespeed_data->pageStats, $result); $result->compressed_files = self::getCompressedFiles($name); self::getRuleResults($pagespeed_data->formattedResults->ruleResults, $result); return $result; } /** * Gets the main domain ID (= Webspace ID) * * @param pm_Domain $domain_object * * @return mixed */ private static function getDomainId($domain_object) { $domain_id = (int) $domain_object->getProperty('parentDomainId'); if ($domain_id == 0) { return $domain_object->getId(); } return $domain_id; } /** * Loads all relevant page stats from the JSON response * * @param $stats * @param $result */ private static function getPageStats($stats, &$result) { $result->stats = new stdClass(); $total_size = 0; $totel_size_keys = array( 'htmlResponseBytes', 'cssResponseBytes', 'imageResponseBytes', 'javascriptResponseBytes', 'otherResponseBytes' ); foreach ($stats as $key => $value) { if (in_array($key, $totel_size_keys)) { $total_size += $value; } if (stripos($key, 'bytes') !== false) { $value = self::formatBytes($value); } $result->stats->$key = $value; } $result->stats->{'total_response'} = self::formatBytes($total_size); } /** * Helper function to format bytes * * @param $bytes * * @return string */ private static function formatBytes($bytes) { $base = log($bytes, 1024); $suffixes = array( 'B', 'KiB', 'MiB', 'GiB', 'TiB' ); return round(pow(1024, $base - floor($base)), 2).' '.$suffixes[(int) (floor($base))]; } /** * Creates the compressed files API link with the correct domain ID * * @param $domain * * @return string */ private static function getCompressedFiles($domain) { $compressed_file_api = 'https://developers.google.com/speed/pagespeed/insights/optimizeContents?url='.rawurlencode($domain).'&strategy=desktop'; return $compressed_file_api; } /** * Entry function to get the complete rule result * * @param $rules * @param $result */ private static function getRuleResults($rules, &$result) { $result->rules = new stdClass(); foreach ($rules as $key => $value) { $result->rules->$key = new stdClass(); $result->rules->$key->name = $value->localizedRuleName; $result->rules->$key->impact = $value->ruleImpact; $result->rules->$key->summary = self::getImpactSummary($value->summary); $result->rules->$key->url_blocks = new stdClass(); self::getImpactUrlBlocks($value->urlBlocks, $result->rules->$key->url_blocks); } } /** * Gets the impact summary * * @param $summary * * @return string */ private static function getImpactSummary($summary) { $summary_output = ''; if (!empty($summary)) { $summary_output .= self::getImpactFormat($summary); } return $summary_output; } /** * Gets the impact format output with all possible replacements * * @param $format * * @return mixed|string */ private static function getImpactFormat($format) { $format_output = ''; if (!empty($format->format)) { $format_output = $format->format; if (!empty($format->args)) { foreach ($format->args as $key => $value) { if ($value->type == 'HYPERLINK') { $format_output = preg_replace('@{{BEGIN_LINK}}(.*){{END_LINK}}@', '<a href="'.$value->value.'" target="_blank">$1</a>', $format_output); } elseif ($value->type == 'SNAPSHOT_RECT') { $format_output = str_replace('{{'.$value->key.'}}', '('.ucfirst(strtolower($value->key)).')', $format_output); } elseif (in_array($value->type, array( 'INT_LITERAL', 'BYTES', 'PERCENTAGE', 'DURATION', 'URL' ))) { $format_output = str_replace('{{'.$value->key.'}}', $value->value, $format_output); } } } } return $format_output; } /** * Gets the impact URL blocks * * @param $url_blocks * @param $result */ private static function getImpactUrlBlocks($url_blocks, &$result) { if (!empty($url_blocks)) { foreach ($url_blocks as $key => $url_block) { $result->$key = new stdClass(); if (!empty($url_block->header)) { $result->$key->header = self::getImpactFormat($url_block->header); } if (!empty($url_block->urls)) { $result->$key->urls = new stdClass(); self::getImpactUrlBlocksUrls($url_block->urls, $result->$key->urls); } } } } /** * Gets all URLs within a URL block * * @param $urls * @param $result */ private static function getImpactUrlBlocksUrls($urls, &$result) { foreach ($urls as $key => $url) { if (!empty($url->result)) { $result->$key = new stdClass(); $result->$key = self::getImpactFormat($url->result); } } } /** * Checks the availability of the requested domain * * @param pm_Domain $domain_object * @param string $action * * @return bool */ public static function domainAvailable($domain_object, $action = 'result') { if (!$domain_object->isActive() OR !$domain_object->hasHosting()) { return false; } if ($domain_object->isSuspended() OR $domain_object->isDisabled()) { return false; } if ($action == 'result') { self::isResolvingToPlesk($domain_object); } return true; } /** * Checks whether domain name is resolving to Plesk server directly - if not then the domain name is pointing to another * IP address what happens if the user is using a proxy server or the domain is not mapping the Plesk server at all * * @param pm_Domain $domain_object * * @return bool */ private static function isResolvingToPlesk($domain_object) { $ip_resolving = false; try { $records = @dns_get_record($domain_object->getName(), DNS_A | DNS_AAAA); } catch (Exception $e) { return $ip_resolving; } if (empty($records)) { return $ip_resolving; } $domain_ip_addresses = $domain_object->getIpAddresses(); foreach ($records as $record) { $ip_address = ''; if (isset($record['ip'])) { $ip_address = $record['ip']; } elseif (isset($record['ipv6'])) { $ip_address = $record['ipv6']; } foreach ($domain_ip_addresses as $domain_ip) { if ($ip_address === $domain_ip) { $ip_resolving = true; } } } pm_Settings::set('pagespeed_resolving_'.$domain_object->getId(), $ip_resolving); return $ip_resolving; } /** * Runs shell script in the postInstallCheck trigger */ public static function postInstallCheck() { pm_ApiCli::callSbin('postinstallcheck.sh'); } /** * Runs shell script in the preUninstallCheck trigger */ public static function preUninstallCheck() { pm_ApiCli::callSbin('preuninstallcheck.sh'); } /** * Helper function to backup the configuration file */ public static function backupConfigFile() { $file_manager = new pm_ServerFileManager(); // First create a backup of the initial config file - only once in the first saving process if (!$file_manager->fileExists('/usr/local/psa/var/modules/pagespeed-insights/pagespeed.conf')) { $config_data_ori = self::loadConfigFile(); if (!empty($config_data_ori)) { $file_manager->filePutContents('/usr/local/psa/var/modules/pagespeed-insights/pagespeed.conf', $config_data_ori); } } } /** * Helper function to load the configuration file data * * @return bool|string */ public static function loadConfigFile() { $file_manager = new pm_ServerFileManager(); $config_path = self::getConfigPath(); if (!empty($config_path)) { $config = $file_manager->fileGetContents($config_path); if (!empty($config)) { return $config; } } return false; } /** * Gets the configuration path depending on the operation system * * @return bool|string */ private static function getConfigPath() { $file_manager = new pm_ServerFileManager(); if ($file_manager->fileExists('/etc/httpd/conf.d/pagespeed.conf')) { // CentOS return '/etc/httpd/conf.d/pagespeed.conf'; } elseif ($file_manager->fileExists('/etc/apache2/mods-available/pagespeed.conf')) { // Ubuntu return '/etc/apache2/mods-available/pagespeed.conf'; } return false; } /** * Helper function to save the transmitted data to the configuration file * * @param $config_data * * @return bool */ public static function saveConfigFile($config_data) { if (!empty($config_data)) { $file_manager = new pm_ServerFileManager(); $config_path = self::getConfigPath(); if (!empty($config_path)) { $file_manager->filePutContents($config_path, $config_data); // Restart web server to activate changes $result = pm_ApiCli::callSbin('restart_server.sh', array(), pm_ApiCli::RESULT_FULL); if ($result['code']) { return false; } return true; } } return false; } /** * Helper function to restore the previously stored configuration file * * @return bool */ public static function restoreConfigFile() { $file_manager = new pm_ServerFileManager(); // Check for the backup file and restore from it if exists if ($file_manager->fileExists('/usr/local/psa/var/modules/pagespeed-insights/pagespeed.conf')) { $config_data_backup = $file_manager->fileGetContents('/usr/local/psa/var/modules/pagespeed-insights/pagespeed.conf'); $config_path = self::getConfigPath(); if (!empty($config_data_backup) and !empty($config_path)) { $file_manager->filePutContents(self::getConfigPath(), $config_data_backup); // Restart web server to activate changes $result = pm_ApiCli::callSbin('restart_server.sh', array(), pm_ApiCli::RESULT_FULL); if ($result['code']) { return false; } return true; } } return false; } /** * Compares default file with current configuration file * * @return bool */ public static function compareConfigFiles() { $file_manager = new pm_ServerFileManager(); // Compare content of the backup file with the content of the current configuration file if ($file_manager->fileExists('/usr/local/psa/var/modules/pagespeed-insights/pagespeed.conf')) { $config_data_backup = $file_manager->fileGetContents('/usr/local/psa/var/modules/pagespeed-insights/pagespeed.conf'); $config_data_current = $file_manager->fileGetContents(self::getConfigPath()); if ($config_data_backup == $config_data_current) { return true; } } return false; } /** * Checks the status of the Pagespeed Apache module installation * * @return bool */ public static function checkPagespeedStatus() { if (!pm_ProductInfo::isUnix()) { return false; } // Restart web server to activate changes $result = pm_ApiCli::callSbin('pagespeed_installed.sh', array(), pm_ApiCli::RESULT_FULL); if (!empty($result['code']) OR empty(trim($result['stdout']))) { return false; } return true; } } <file_sep><?php /** * Copyright 1999-2017. Parallels IP Holdings GmbH. */ /** * Class InstallController */ class InstallController extends pm_Controller_Action { protected $_accessLevel = 'admin'; public function init() { parent::init(); $this->view->headLink()->appendStylesheet(pm_Context::getBaseUrl().'styles.css'); // Set page title for all actions $this->view->pageTitle = $this->lmsg('page_title_apache'); } /** * Forward index action to form action */ public function indexAction() { if (!pm_ProductInfo::isUnix()) { $this->_redirect(pm_Context::getBaseUrl()); } // Default action is formAction $this->_forward('form'); } /** * Default action which creates the form in the settings and processes the requests */ public function formAction() { $pagespeed_status = Modules_PagespeedInsights_Helper::checkPagespeedStatus(); // Set the description text $this->view->output_description = Modules_PagespeedInsights_Helper::addSpanTranslation('output_description_apache', 'description-extension'); $form = new pm_Form_Simple(); $this->installationType($form, $pagespeed_status); $this->addButtons($form, $pagespeed_status); // Process the form - save the license key and run the installation scripts if ($this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost())) { try { $this->processPostRequest($form); } catch (Exception $e) { $this->_status->addMessage('error', $e->getMessage()); } } $this->view->form = $form; } /** * Adds elements to the pm_Form_Simple object depending on installation type * * @param $form * @param bool $pagespeed_status */ private function installationType(&$form, $pagespeed_status = false) { $form->addElement('description', 'type_apache_logo', [ 'description' => Modules_PagespeedInsights_Helper::addSpanTranslation('form_type_apache_logo', 'logo-product-apache'), 'escape' => false ]); if (empty($pagespeed_status)) { $form->addElement('description', 'apache_install', [ 'description' => Modules_PagespeedInsights_Helper::addSpanTranslation('form_type_apache_install', 'product-installed-apache'), 'escape' => false ]); $form->addElement('checkbox', 'apache', [ 'label' => $this->lmsg('form_type_apache'), 'value' => pm_Settings::get('apache'), 'checked' => true ]); } else { $form->addElement('description', 'apache_installed', [ 'description' => Modules_PagespeedInsights_Helper::addSpanTranslation('form_type_apache_installed', 'product-installed-apache'), 'escape' => false ]); $form->addElement('checkbox', 'apache', [ 'label' => $this->lmsg('form_type_apache_reinstall'), 'value' => '', 'checked' => false ]); } $form->addElement('description', 'type_apache_description_note', [ 'description' => Modules_PagespeedInsights_Helper::addSpanTranslation('form_type_apache_description_note', 'description-product'), 'escape' => false ]); return; } private function addButtons(&$form, $pagespeed_status = false) { $button_submit = $this->lmsg('form_button_reinstall'); if (empty($pagespeed_status)) { $button_submit = $this->lmsg('form_button_install'); } $form->addControlButtons([ 'sendTitle' => $button_submit, 'cancelLink' => pm_Context::getActionUrl('index', 'index'), ]); } /** * Processes POST request - after form submission * * @param $form */ private function processPostRequest($form) { if ($form->getValue('apache')) { if ($this->runInstallation('apache')) { Modules_PagespeedInsights_Helper::backupConfigFile(); $this->_status->addMessage('info', $this->lmsg('message_success_apache')); $this->_helper->json(['redirect' => pm_Context::getActionUrl('index', 'index')]); return; } } if (empty(pm_View_Status::getAllMessages(false))) { $this->_status->addMessage('warning', $this->lmsg('message_warning_installation')); } $this->_helper->json(['redirect' => pm_Context::getActionUrl('install', 'index')]); } /** * Starts the installation process of the service using shell scripts * * @param string $type * * @return bool * @throws pm_Exception */ private function runInstallation($type) { $options = array(); $result = pm_ApiCli::callSbin($type.'.sh', $options, pm_ApiCli::RESULT_FULL); if ($result['code']) { throw new pm_Exception("{$result['stdout']}\n{$result['stderr']}"); } return true; } } <file_sep>#!/bin/bash -e ### Restart web server if [ -f /etc/redhat-release ] then service httpd restart else service apache2 restart fi exit 0<file_sep><?php /** * Copyright 1999-2017. Parallels IP Holdings GmbH. */ if (pm_ProductInfo::isUnix()) { pm_Loader::registerAutoload(); pm_Context::init('pagespeed-insights'); Modules_PagespeedInsights_Helper::preUninstallCheck(); } <file_sep><?php /** * Copyright 1999-2017. Parallels IP Holdings GmbH. */ /** * Class IndexController */ class IndexController extends pm_Controller_Action { protected $installation; public function init() { parent::init(); $this->view->headLink()->appendStylesheet(pm_Context::getBaseUrl().'styles.css'); // Init title for all actions $this->view->pageTitle = $this->lmsg('page_title'); } public function indexAction() { if (!pm_Session::getClient()->isAdmin()) { throw new Exception($this->lmsg('error_only_admin')); } $this->view->output_description = $this->lmsg('output_description'); $this->view->installstatus = Modules_PagespeedInsights_Helper::checkPagespeedStatus(); $this->view->config_default = Modules_PagespeedInsights_Helper::compareConfigFiles(); $this->view->tools = $this->addToolsButtons($this->view->installstatus, $this->view->config_default); $this->view->list = new Modules_PagespeedInsights_List_Overview($this->view, $this->_request); } /** * Adds buttons for the Apache Module integration (install, config and restore) * * @param bool $installation_status * @param bool $config_default * * @return array */ private function addToolsButtons($installation_status = false, $config_default = true) { $buttons = array(); if (!pm_ProductInfo::isUnix()) { return $buttons; } $buttons[] = array( 'icon' => pm_Context::getBaseUrl().'/images/tool-apache-install.png', 'title' => $installation_status ? $this->lmsg('tool_apache_reinstall') : $this->lmsg('tool_apache_install'), 'description' => $this->lmsg('tool_apache_info'), 'controller' => 'install', 'action' => 'index' ); if (!empty($installation_status)) { $config_file = $this->lmsg('tool_config_file_default'); if (empty($config_default)) { $config_file = $this->lmsg('tool_config_file_custom'); } $config_description = $this->lmsg('tool_config_edit_description').' '.$config_file; $buttons[] = array( 'icon' => pm_Context::getBaseUrl().'/images/tool-config-edit.png', 'title' => $this->lmsg('tool_config_edit'), 'description' => $config_description, 'controller' => 'config', 'action' => 'index' ); if (empty($config_default)) { $buttons[] = array( 'icon' => pm_Context::getBaseUrl().'/images/tool-config-restore.png', 'title' => $this->lmsg('tool_config_restore'), 'description' => $this->lmsg('tool_config_restore_description'), 'controller' => 'restore', 'action' => 'index' ); } } return $buttons; } public function indexDataAction() { $list = new Modules_PagespeedInsights_List_Overview($this->view, $this->_request); $this->_helper->json($list->fetchData()); } public function resultAction() { $get_global = $this->getRequest()->getQuery(); if (empty($get_global['site_id'])) { $this->view->result = $this->lmsg('error_select_domain_overview'); return; } if (!pm_Session::getClient()->hasAccessToDomain($get_global['site_id'])) { $this->view->result = $this->lmsg('error_wrong_domain_selected'); return; } $domain_object = pm_Domain::getByDomainId($get_global['site_id']); if (Modules_PagespeedInsights_Helper::domainAvailable($domain_object) == false) { $this->view->result = $this->lmsg('error_domain_not_available'); return; } $domain_name = $domain_object->getName(); if (stripos($domain_name, 'http://') === false) { $domain_name = 'http://'.$domain_name; } $pagespeed_result = Modules_PagespeedInsights_Helper::getPageSpeedApi($domain_name); if (is_string($pagespeed_result)) { $this->view->result = Modules_PagespeedInsights_Helper::translateString($pagespeed_result); return; } if (!empty($pagespeed_result->ruleGroups->SPEED->score)) { pm_Settings::set('pagespeed_score_'.$domain_object->getId(), $pagespeed_result->ruleGroups->SPEED->score); } $this->view->result = Modules_PagespeedInsights_Helper::createOutputObject($pagespeed_result, $domain_name, $domain_object); } } <file_sep><?php /** * Copyright 1999-2017. Parallels IP Holdings GmbH. */ /** * Class RestoreController */ class RestoreController extends pm_Controller_Action { protected $_accessLevel = 'admin'; public function init() { parent::init(); $this->view->headLink()->appendStylesheet(pm_Context::getBaseUrl().'styles.css'); // Set page title for all actions $this->view->pageTitle = $this->lmsg('page_title_apache'); } /** * Forward index action to form action */ public function indexAction() { if (!pm_ProductInfo::isUnix()) { $this->_redirect(pm_Context::getBaseUrl()); } $this->view->pagespeed_status = Modules_PagespeedInsights_Helper::checkPagespeedStatus(); if (empty($this->view->pagespeed_status)) { $this->_redirect(pm_Context::getBaseUrl()); } // Default action is formAction $this->_forward('form'); } /** * Default action which creates the form in the settings and processes the requests */ public function formAction() { // Set the description text $this->view->output_description = Modules_PagespeedInsights_Helper::addSpanTranslation('output_description_restore', 'description-extension'); $form = new pm_Form_Simple(); $this->addConfigTextarea($form); $this->addButtons($form); // Process the form - save the license key and run the installation scripts if ($this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost())) { try { $this->processPostRequest($form); } catch (Exception $e) { $this->_status->addMessage('error', $e->getMessage()); } } $this->view->form = $form; } /** * Loads the configuration file and adds the textarea for the form * * @param $form */ private function addConfigTextarea(&$form) { $config = Modules_PagespeedInsights_Helper::loadConfigFile(); if (!empty($config) AND !empty($this->view->pagespeed_status)) { $form->addElement('checkbox', 'restore', [ 'label' => $this->lmsg('form_type_config_restore'), 'value' => '', 'checked' => false ]); } } private function addButtons(&$form) { $button_submit = $this->lmsg('form_button_restore'); $form->addControlButtons([ 'sendTitle' => $button_submit, 'cancelLink' => pm_Context::getActionUrl('index', 'index'), ]); } /** * Processes POST request - after form submission * * @param $form */ private function processPostRequest($form) { if ($form->getValue('restore')) { if ($this->runRestoreConfig()) { $this->_status->addMessage('info', $this->lmsg('message_success_config_restord')); } else { $this->_status->addMessage('error', $this->lmsg('message_error_config_restord')); } } if (empty(pm_View_Status::getAllMessages(false))) { $this->_status->addMessage('warning', $this->lmsg('message_warning_restore')); } $this->_helper->json(['redirect' => pm_Context::getActionUrl('index', 'index')]); } /** * Restores the configuration file with the default file that was stored after the installation * * @return bool */ private function runRestoreConfig() { $config_restored = (bool) Modules_PagespeedInsights_Helper::restoreConfigFile(); if (!empty($config_restored)) { return true; } return false; } } <file_sep>#!/bin/bash -e ### Add the PageSpeed repository and install the Apache module if [ -f /etc/redhat-release ] then wget https://dl-ssl.google.com/dl/linux/direct/mod-pagespeed-stable_current_x86_64.rpm if [ $(rpm -qa | grep -c "pagespeed") -eq 0 ]; then yum -y -q install at yum -y -q install mod-pagespeed-*.rpm else yum -y -q reinstall at yum -y -q reinstall mod-pagespeed-*.rpm fi service httpd restart else wget https://dl-ssl.google.com/dl/linux/direct/mod-pagespeed-stable_current_amd64.deb dpkg -i mod-pagespeed-*.deb apt-get -qq -y -f install service apache2 restart fi exit 0<file_sep><?php /** * Copyright 1999-2017. Parallels IP Holdings GmbH. */ /** * Class Modules_PagespeedInsights_CustomButtons */ class Modules_PagespeedInsights_CustomButtons extends pm_Hook_CustomButtons { /** * Adds the custom PageSpeed Insights button * * @return array */ public function getButtons() { $buttons = [ [ 'place' => self::PLACE_DOMAIN_PROPERTIES, 'title' => pm_Locale::lmsg('button_name'), 'description' => pm_Locale::lmsg('button_description'), 'icon' => pm_Context::getBaseUrl().'images/button_overview.png', 'link' => pm_Context::getActionUrl('index', 'result'), 'additionalComments' => [ $this, 'getScore' ], 'contextParams' => true, 'visibility' => [ $this, 'getVisibility' ], ] ]; return $buttons; } /** * Gets the score for additionalComments * * @param $options * * @return string */ public function getScore($options) { if (empty($options['site_id'])) { return ''; } try { pm_Context::init('pagespeed-insights'); $score = pm_Settings::get('pagespeed_score_'.$options['site_id'], false); $score_output = ''; if (!empty($score)) { $score_output = pm_Locale::lmsg('button_score', array('score' => $score)); } return $score_output; } catch (Exception $e) { return ''; } } /** * Gets the visibility state of a specific domain * * @param $options * * @return bool */ public function getVisibility($options) { if (empty($options['site_id'])) { return false; } $domain = pm_Domain::getByDomainId($options['site_id']); $domain_available = Modules_PagespeedInsights_Helper::domainAvailable($domain, 'overview'); if (empty($domain_available)) { return false; } if (!empty($options['alias_id'])) { return false; } return true; } } <file_sep>#!/bin/bash -e REMOVEPAGESPEED=`cat /usr/local/psa/var/modules/pagespeed-insights/removepagespeed` if [ "$REMOVEPAGESPEED" = "1" ]; then if [ -f /etc/redhat-release ]; then if [ $(rpm -qa | grep -c "pagespeed") -eq 1 ]; then PAGESPEED=$(rpm -qa | grep "pagespeed") if [ ! -z $PAGESPEED ]; then yum -y -q remove $PAGESPEED fi AT=$(rpm -qa | grep "^at-") if [ ! -z $AT ]; then yum -y -q remove $AT fi service httpd restart fi else if [ $(dpkg --get-selections | grep -c pagespeed) -eq 1 ]; then apt-get -qq -y --purge autoremove mod-pagespeed-stable if [ -f /etc/apt/sources.list.d/mod-pagespeed.list ] then rm /etc/apt/sources.list.d/mod-pagespeed.list fi service apache2 restart fi fi fi exit 0<file_sep><?php /** * Copyright 1999-2017. Parallels IP Holdings GmbH. */ /** * Class ConfigController */ class ConfigController extends pm_Controller_Action { protected $_accessLevel = 'admin'; public function init() { parent::init(); $this->view->headLink()->appendStylesheet(pm_Context::getBaseUrl().'styles.css'); // Set page title for all actions $this->view->pageTitle = $this->lmsg('page_title_config'); } /** * Forward index action to form action */ public function indexAction() { // Support only for Unix at the moment if (!pm_ProductInfo::isUnix()) { $this->_redirect(pm_Context::getBaseUrl()); } $this->view->pagespeed_status = Modules_PagespeedInsights_Helper::checkPagespeedStatus(); if (empty($this->view->pagespeed_status)) { $this->_redirect(pm_Context::getBaseUrl()); } // Default action is formAction $this->_forward('form'); } /** * Default action which creates the form in the settings and processes the requests */ public function formAction() { // Set the description text $this->view->output_description = Modules_PagespeedInsights_Helper::addSpanTranslation('output_description_config', 'description-extension'); $form = new pm_Form_Simple(); $this->addConfigTextarea($form); $this->addButtons($form); // Process the form - save the license key and run the installation scripts if ($this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost())) { try { $this->processPostRequest($form); } catch (Exception $e) { $this->_status->addMessage('error', $e->getMessage()); } } $this->view->form = $form; } /** * Loads the configuration file and adds the textarea for the form * * @param $form */ private function addConfigTextarea(&$form) { $config = Modules_PagespeedInsights_Helper::loadConfigFile(); if (!empty($config) AND !empty($this->view->pagespeed_status)) { $form->addElement('textarea', 'config', [ 'label' => $this->lmsg('form_type_config'), 'value' => $config, 'class' => 'f-max-size', 'rows' => 10, 'required' => true, 'validators' => [ [ 'NotEmpty', true ], ], ]); } } private function addButtons(&$form) { $button_submit = $this->lmsg('form_button_save'); $form->addControlButtons([ 'sendTitle' => $button_submit, 'cancelLink' => pm_Context::getActionUrl('index', 'index'), ]); } /** * Processes POST request - after form submission * * @param $form */ private function processPostRequest($form) { if ($form->getValue('config')) { if ($this->runSaveConfig($form->getValue('config'))) { $this->_status->addMessage('info', $this->lmsg('message_success_config')); } else { $this->_status->addMessage('error', $this->lmsg('message_error_config')); } } $this->_helper->json(['redirect' => pm_Context::getActionUrl('config', 'index')]); } /** * Saves the entered data to the PageSpeed configuration file * * @param $config * * @return bool */ private function runSaveConfig($config) { $config_saved = (bool) Modules_PagespeedInsights_Helper::saveConfigFile($config); if (!empty($config_saved)) { return true; } return false; } } <file_sep>#!/bin/bash -e if [ -f /etc/redhat-release ]; then if [ $(rpm -qa | grep -c "pagespeed") -eq 0 ]; then echo "0" else echo "1" fi else if [ $(dpkg --get-selections | grep -c pagespeed) -eq 0 ]; then echo "0" else echo "1" fi fi exit 0<file_sep><?php /** * Copyright 1999-2017. Parallels IP Holdings GmbH. */ /** * Class Modules_PagespeedInsights_List_Overview */ class Modules_PagespeedInsights_List_Overview extends pm_View_List_Simple { public function __construct(Zend_View $view, Zend_Controller_Request_Abstract $request) { parent::__construct($view, $request); $data = $this->getData(); $this->setData($data); $this->setColumns(array( 'column-1' => array( 'title' => $this->lmsg('table_domain'), 'noEscape' => true, 'searchable' => true, 'sortable' => true, ), 'column-2' => array( 'title' => $this->lmsg('table_domain_score'), 'noEscape' => true, 'sortable' => true, ), 'column-3' => array( 'title' => '', 'noEscape' => true, 'sortable' => false, ) )); $this->setDataUrl(['action' => 'index-data']); } /** * Gets the domains array for the list * * @return array */ private function getData() { $data = array(); $domains_all = pm_Domain::getAllDomains(); foreach ($domains_all as $domain) { if ($domain->isActive() AND $domain->hasHosting()) { $site_id = $domain->getId(); $class = 'list_subdomain'; $dom_id = $domain->getProperty('parentDomainId'); if ($dom_id == 0) { $dom_id = $site_id; $class = 'list_domain'; } $domain_name = '<span class="domainid'.$dom_id.str_pad($site_id, 3, '0', STR_PAD_LEFT).' '.$class.'">'.$domain->getDisplayName().'</span>'; $resolving = pm_Settings::get('pagespeed_resolving_'.$site_id, true); if (empty($resolving) OR empty($domain_available)) { $domain_name .= ' <span class="small" title="'.$this->lmsg('hint_ip_does_not_resolve').'">(?)</span>'; } $domain_score = $this->getDomainScore($site_id); $action_link_string = $this->lmsg('table_details'); if (empty($domain_score)) { $domain_score = '<span class="score-no">'.$this->lmsg('score_not_available').'</span>'; $action_link_string = $this->lmsg('table_analyze'); } $domain_available = Modules_PagespeedInsights_Helper::domainAvailable($domain, 'index'); if (empty($domain_available)) { $domain_score = $this->lmsg('error_domain_not_available_list'); $action_link_string = $this->lmsg('table_recheck'); } $action_link = '<a href="'.pm_Context::getActionUrl('index', 'result').'?site_id='.$site_id.'">'.$action_link_string.'</a>'; $data[] = array( 'column-1' => $domain_name, 'column-2' => $domain_score, 'column-3' => $action_link, ); } } return $data; } /** * Gets the domain score from the database and adds CSS style if available else normal status message * * @param $id * * @return bool|string */ private function getDomainScore($id) { $score = (int) pm_Settings::get('pagespeed_score_'.$id, false); if (!empty($score)) { $score_class = 'result_green'; if ($score < 85 AND $score >= 65) { $score_class = 'result_orange'; } elseif ($score < 65) { $score_class = 'result_red'; } $score_span = '<span class="score'.str_pad($score, 3, '0', STR_PAD_LEFT).' '.$score_class.'">'.$score.'</span>'; return $this->lmsg('result_overall_score', ['score' => $score_span]); } return false; } } <file_sep># 1.1.1 (26 October 2017) * [+] Added extension to the social category # 1.1.0 (26 April 2017) * [+] Added PageSpeed Apache Module by Google - Complete integration with installation and configuration * [+] Improved PageSpeed Apache status check * [+] Added a note if domain name does not resolve to the Plesk server * [+] Code optimizations * [-] Fixed IP resolving issue when server is behind a proxy, e.g. Cloudflare or AWS server # 1.0.1 (21 February 2017) * [+] Added links to blog articles about PageSpeed Insights to the Description and Readme files * [-] Fixed PHP Notice error that was thrown for the custom button under certain circumstances (EXTCERT-128) # 1.0.0 (31 January 2017) * [+] First release of the PageSpeed Insights extension <file_sep>This extension analyzes the performance websites and suggests ways of improving it. It: - Analyzes the performance of websites hosted on your server. - Assigns every analyzed website a score corresponding to its performance. - Generates a report based on the results of the analysis. - Displays possible ways to optimize the analyzed websites' performance. - Provides links in the extension UI to the suggested tools aimed at improving websites' performance (for example, the *mod_pagespeed* Apache module). [Learn more](https://www.plesk.com/blog/introducing-google-pagespeed-insights-plesk-extension/) about Google PageSpeed Insights. [Learn](https://www.plesk.com/product-technology/google-pagespeed-insights-optimize-your-site) how to improve your website performance with Google PageSpeed Insights.
23d297c2fbca89e10218119a175a2157dffaafcd
[ "Markdown", "PHP", "Shell" ]
14
PHP
MaximSavrilov/ext-pagespeed-insights
08610b7f82094cfa9bad63db8fa88160668ad3ee
f3626a7005242fdce3b34e67b5c7d1e1870dd8df
refs/heads/master
<repo_name>arunrajput17/PSTUD<file_sep>/29_SharingDataBetProcesses_Que.py ## Sharing Data between Process : Que (Sharing value using them) import multiprocessing def calc_square(numbers,q): for n in numbers: q.put(n*n) # adding data in the que if __name__ == "__main__": numbers=[2,3,5] ### Declaring shared memory que q = multiprocessing.Queue() p = multiprocessing.Process(target=calc_square,args=(numbers,q)) p.start() p.join() print('Outside the process Array') while q.empty() is False: print(q.get()) <file_sep>/23_ListSetDict_Comprehension.py ## List / set / dict Comprehension : It provides a way to transform one list into another # General way to find the even numbers from list is numbers=[1,2,3,4,5,6,7,8,9] even=[] for i in numbers: if i%2 ==0: even.append(i) print(even) ## Comprehension even = [i for i in numbers if i%2==0] print(even) sqr_numbers =[i*i for i in numbers] print (sqr_numbers) ## Set : set is an unordered collection of unique items. # Set Comprehension s=set([1,2,3,4,5,2,3]) print(s) even ={ i for i in s if i%2==0} print(even) ## Dict comprehension cities =['mumbai','new york','paris'] countries =['india','usa','france'] #-- to create a dict where key is name of city and value is country name # zip is builtin function in python, it will zip two lists together z = zip(cities,countries) print(z) for a in z: print(a) # Comprehension d ={city:countries for city, countries in zip(cities,countries)} print(d) <file_sep>/RandomNumber.py import random #print(dir(random)) value = random.random() print(value) value1 = random.uniform(1,10) print(value1) value2 = random.randint(0,10) print(value2) ##Function to generate random number as string def randomNumber(numberLength): number = ('0','1','2','3','4','5','6','7','8','9') return ''.join(random.choice(number) for i in range (numberLength)) print ('Random number is : ', randomNumber(10))<file_sep>/modules/mod_functions.py def calculate_triangle_area(base,height): return 1/2*(base*height) def calculate_square_area(length): return length*length<file_sep>/P9_PandaMerge.py #### Merge Dataframes import pandas as pd df1 =pd.DataFrame({ 'city': ['new york','chicago','orlando'], 'temperature': [21,14,35], }) print(df1) df2 =pd.DataFrame({ 'city': ['chicago','new york','orlando'], 'humidity': [65,68,75], }) print(df2) # Merging two dataframes df3= pd.merge(df1,df2,on='city') print(df3) # Only the common in both dataframe will display df4 =pd.DataFrame({ 'city': ['new york','chicago','orlando','baltimore'], 'temperature': [21,14,35,32], }) print(df4) df5 =pd.DataFrame({ 'city': ['chicago','new york','san fransisco'], 'humidity': [65,68,71], }) print(df5) df6 = pd.merge(df4,df5,on='city') print(df6) ## Union of these two dataframe tables df7 = pd.merge(df4,df5,on='city',how='outer') print(df7) ## Other joins df8 = pd.merge(df4,df5,on='city',how='right') print(df8) df9 = pd.merge(df4,df5,on='city',how='left') print(df9) ## We can add indicator to know which value came from which dataframe df10 = pd.merge(df4,df5,on='city',how='outer',indicator=True) print(df10) ## Both dataframes have same column names df11 =pd.DataFrame({ 'city': ['new york','chicago','orlando','baltimore'], 'temperature': [21,14,35,38], 'humidity':[65,68,71,75] }) print(df11) df12 =pd.DataFrame({ 'city': ['chicago','new york','san diego'], 'temperature': [21,14,35], 'humidity':[65,68,71] }) print(df12) df13= pd.merge(df11,df12,on='city') print(df13) df14 = pd.merge(df11,df12,on='city',suffixes=('_left','_right')) print(df14)<file_sep>/30_MultiprocessingLock.py #### Lock : It is used to lock the access. So, that two process cannot access it at same time import time import multiprocessing def deposit(balance,lock): for i in range(100): time.sleep(0.01) lock.acquire() # To put a lock balance.value = balance.value +1 lock.release() # To relesae a lock def withdraw(balance,lock): for i in range(100): time.sleep(0.01) lock.acquire() # To put a lock balance.value = balance.value -1 lock.release() # To relesae a lock if __name__ == "__main__": balance = multiprocessing.Value('i',200) lock = multiprocessing.Lock() ## Creating a lock variable using lock class and pass it in processes d = multiprocessing.Process(target=deposit,args=(balance,lock)) ## Passing lock in process w = multiprocessing.Process(target=withdraw,args=(balance,lock)) ## Passing lock in process d.start() w.start() d.join() w.join() print(balance.value) <file_sep>/P3_PandaDiffDataframe.py ## Diferent ways of creating dataframe, import pandas as pd # 1. Using CSV df = pd.read_csv('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\weather_data.csv') print(df) # 2. Using Excel df = pd.read_excel('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\weather_data.xls','Sheet1') print(df) df = pd.read_excel('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\weather_data.xlsx','Sheet1') print(df) # 3. From python dictionary weather_data1 ={ 'day': ['1/1/2017','1/2/2017','1/3/2017','1/4/2017','1/5/2017','1/6/2017'], 'temperature': [32,35,28,24,32,32], 'windspeed': [6,7,2,7,4,2], 'event': ['Rain','Sunny','Snow','Snow','Rain','Sunny'] } df = pd.DataFrame(weather_data1) print('Dataframe created from dictionary : \n', df) # 4. From list tuples weather_data2 =[ ('1/1/2017',32,6,'Rain'), ('1/2/2017',35,7,'Sunny'), ('1/3/2017',28,2,'Snow') ] df = pd.DataFrame(weather_data2, columns=['day','temperature','windspeed','event']) print('Dataframe created from tuples: \n',df) # 5. From list dictionaries weather_data3 =[ {'day':'1/1/2017','temperature':32,'windspeed':6,'event':'Rain'}, {'day':'1/2/2017','temperature':35,'windspeed':7,'event':'Sunny'}, {'day':'1/3/2017','temperature':28,'windspeed':2,'event':'Snow'}, ] df = pd.DataFrame(weather_data3) print('Dataframe created from list dictionaries : \n',df) <file_sep>/Packages.py ## Packages #What are packages? #Published collection of modules #How do i find packages? # URL Python package index # internet search ####### Installing packages # install an individual package pip install colorama # install from a list of packages pip install -r requirements.txt # requirements.txt colorama ##### Virtual environments #By default, packages are installed globally # --> version management becomes a challenge # Virtual environments can be used to contain and manage package of collections #--> Really just a folder behind the scenes with all the packages ### Creating virtual environments # install viirtual environment pip install virtualenv # Windows system python -m venv <folder_name> # OSX / Linux (bash) virtualenv <folder_name> ### Using virtual environments # Windows system # cmd.exe <folder_name>\Scripts\Activate.bat # Powershell <folder_name>\Scripts\Activate.ps1 # Bash shell ../<folder_name>\Scripts\Activate # OSX / Linux (bash) <folder_name>\bin\Activate ### Installing packages in virtual environment # install an individual package pip install colorama # install from a list of packages pip install -r requirements.txt # requirements.txt colorama <file_sep>/P11_PandaMelt.py ## melt is used to transform or reshape data import pandas as pd df = pd.read_csv('ReadWriteFiles\\P11_weather_data_ByCities.csv') print(df) # covert data citiwise df1 = pd.melt(df,id_vars=['Day']) print(df1) # filter on chicago df2=df1[df1['variable']=='chicago'] print(df2) # Defining column names df3= pd.melt(df,id_vars='Day',var_name='city',value_name='temperature') print(df3) <file_sep>/26_MultiThreading.py ## Multithreading (Example os Mom Cooking with taking care of baby and attending phone call) ## For a given list of numbers print square and cube of every numbers ## For example: Input:[2,3,8,9] ## Output: Square list - [4,9,64,81] cube list - [8,27,512,729] import time import threading square_numbers =[] def calc_square(numbers): print('calculate square numbers') for n in numbers: time.sleep(0.2) print('sqaure:',n*n) square_numbers.append(n*n) def cal_cube(numbers): print('calculate cube of numbers') for n in numbers: time.sleep(0.2) print('cube:', n*n*n) if __name__ == "__main__": arr=[2,3,8,9] t =time.time() ## Before threading we call this way # calc_square(arr) # cal_cube(arr) ## After threading t1 = threading.Thread(target=calc_square,args=(arr,)) t2 = threading.Thread(target=cal_cube,args=(arr,)) t1.start() t2.start() t1.join() t2.join() print('Result of square numbers :' + str(square_numbers)) print('done in:', time.time()-t) print('Hah... I am done with all my work now!') # time before multithreading is 1.6925840377807617 # After multithreading it is taking 0.8529384136199951 <file_sep>/P10_PandaPivot&PivotTable.py ### Pivot Table : it allows you to transform and reshape data import pandas as pd df = pd.read_csv('ReadWriteFiles\\P10_weather_data_ByCities.csv') print(df) # Transform it rows as index and column as cities df1=df.pivot(index='date',columns='city') print(df1) print() # Transform to see humidity only df2= df.pivot(index='date',columns='city',values='humidity') print(df2) print() # humidity as rows columns are city df3= df.pivot(index='humidity',columns='city') print(df3) print() #### Pivot table is used to summarize and aggregate data inside dataframe df=pd.read_csv('ReadWriteFiles\\P10-1_weather_data_ByCities.csv') print(df) print() ## Average temp through out the day df4=df.pivot_table(index='city',columns='date') print(df4) print() ## Aggregation using sum, mean, count, div df5 = df.pivot_table(index='city',columns='date',aggfunc='sum') print(df5) print() # using mrgins df6 = df.pivot_table(index='city',columns='date',margins=True) print(df6) print() ###Grouper in pivot -- Average temp in may df=pd.read_csv('ReadWriteFiles\\P10-2_weather_data_ByCities.csv') print(df) df['date']=pd.to_datetime(df['date']) df7= df.pivot_table(index=pd.Grouper(freq='M',key='date'),columns='city') print(df7) <file_sep>/9_Loops.py #Loop through a collection people = ['Christopher' , 'Susan'] for name in people: print(name) #Looping a number of times for index in range(0, 2): print(index) #Looping with a condition names = ['Christopher' , 'Susan'] index = 0 while index < len(names): print(names[index]) #Change the condition!! index= index + 1 #################################################################################### exp=[2340,2500,2100,3100,2980,] # total = exp[0]+exp[1]+exp[2]+exp[3]+exp[4] total =0 for item in exp: total = total + item print(total) for i in range(1,11): print(i) ## Monthwise expense and total expense total = 0 for i in range (len(exp)): print('Month:',(i+1),'Expense:',exp[i]) total = total + exp[i] print('Total expense is: ',total) ## Find the key from differnt location in list key_location='chair' locations=['garage','living room','chair','closet'] for i in locations: if i==key_location: print('Key is found in',i) break else: print('Key is not found in', i) ## Print square of numbers between 1 to 5 EXCEPT even numbers for i in range (1,6): if i%2==0: continue print(i*i) i=1 while i<=5: print(i) i=i+1 ## After flipping a coin 10 times got this result, ## result = ['heads','tails','tails','heads','tails','heads','heads','tails','tails','tails'] ##Using for loop figure out count for 'heads'. result = ['heads','tails','tails','heads','tails','heads','heads','tails','tails','tails'] count_heads=0 for i in result: if i=='tails': continue # print(i) count_heads=count_heads+1 print('Number of times heads came are: ',count_heads) ## Another way c=0 for i in result: if i=='heads': c=c+1 else: continue print(c) ## Your monthly expense list (from Jan to May) looks like this, ## expense_list = [2340,2500,2100,3100,2980] ## Write a program that asks you enter an expense amount and program should tell you the month in which that ##expense occured. If the expense is not found then convey that as well. expense_list = [2340,2500,2100,3100,2980] expense_amt = int(input('Enter the Expense amount: ')) m=0 for i in expense_list: if i == expense_amt: m=m+1 print('Month :',m, 'Expense :', expense_amt) break else: m=m+1 print('not availble in Month: ',m) ## Write a program that prints following shape,(Hint: Use for loop inside another for loop) ## * ** *** **** ***** num=int(input('Enter number of rows: ')) for i in range(1,num): for j in range (1,i+1): print('*',end=' ') print() for i in range(1,6): s = '' for j in range(i): s += '*' print(s) <file_sep>/31_MultiprocessPool.py ## Multiprocesssing Pool from multiprocessing import Pool import time def f(n): sum=0 for x in range(10000): sum += x*x return sum if __name__ == "__main__": ## With Pool t1=time.time() p = Pool() result= p.map(f,range(1000)) # Increase the number processing time will increase p.close() p.join() print('Pool took : ',time.time()-t1) ## Without Pool t2=time.time() result=[] for x in range(1000): # Increase the number processing time will increase result.append(f(x)) print('Serial Processing took : ',time.time()-t2) # print(result) ### Code to use selected number of process only # def fun(n): # return n*n # if __name__ == "__main__": # p = Pool(processes=3) # DEfine how many number of process you want to use # result = p.map(fun,[1,2,3,4,5]) # for n in result: # print(n)<file_sep>/10-1_Functions_Parametrization.py ## Functions can accept multiple parameters def get_initial(name, force_uppercase): if force_uppercase: initial = name[0:1].upper() else: initial = name[0:1] return initial first_name = input('Enter your first name: ') first_name_initial = get_initial(first_name, False) print('Your initial is : ' + first_name_initial) ################################################### ## You can specify default value for a parameter ## like def get_initial(name, force_uppercase=True): ## call as get_initial(first_name) ################################################### ##You can also assign the values to parameters by name when you call the function ## i.e. get_initial(force_uppercase=True, name = first_name) ################################################### ## Using the named notation when calling the functions makes your code more readable def error_logger(error_code, error_severity, log_to_db, error_message, source_module): print('Oh no error: ' + error_message) #Imagine code here that logs our error to a database or file first_number = 10 second_number = 5 if first_number > second_number: error_logger(45,1,True,'Second number greater than first', 'my_math_method') ### if first_number > second_number: error_logger(error_code=45,error_severity = 1,log_to_db=True, error_message='Second number greater than first', source_module='my_math_method') <file_sep>/32_Decorators.py def logger(func): def wrapper(): print('Logging execution') func() print('Done logging') return wrapper @logger def sample(): print('-- Inside sample function') sample() ################################################################### #### Decorators act as a wrapper for your original function ## Common uses are : 1. Logging, 2. Timing import time def time_it(func): def wrapper(*args,**kwargs): start = time.time() result = func(*args,**kwargs) end = time.time() print(func.__name__ +' took ' + str((end-start)*1000)+ ' mil sec') return result return wrapper @time_it def calc_square(numbers): # start = time.time() ## Add the repeated code in decorator result= [] for number in numbers: result.append(number*number) # end = time.time() ## Add the repeated code in decorator # print('calc_square took '+ str((end-start)*1000)+ ' mil sec') ## Add the repeated code in decorator return result @time_it def calc_cube(numbers): # start = time.time() ## Add the repeated code in decorator result = [] for number in numbers: result.append(number*number*number) # end = time.time() ## Add the repeated code in decorator # print('calc_cube took '+ str((end-start)*1000)+ ' mil sec') ## Add the repeated code in decorator return result array = range(1,100000) out_square = calc_square(array) out_cube = calc_cube(array)<file_sep>/N2_NumpyBasicArrayOperations.py ## Basic array operation import numpy as np a = np.array([5,6,9]) # Creating one dimensional array print(a) print(a[0]) # We can access it just like list print(a[2]) print('Dimension of array "a" is :',a.ndim) b = np.array([[1,2],[3,4],[5,6]]) #Creating two dimensional array print(b) print('Dimension of array "b" is :',b.ndim) print('Byte size of each integer element is :', b.itemsize) print('data type is', b.dtype) #intializing the array with different data type c = np.array([[9,8],[7,6],[5,4]], dtype=np.float) print(c) print('Byte size each float element is :', c.itemsize) print('Total number of elements in the array are :', c.size) print('Dimention of array in rows and column is :', c.shape) print('data type is', c.dtype) # Initializing the array as Complex number datatype d = np.array([[9,8],[7,6],[5,4]], dtype=np.complex) print(d) # Intialize array with some place holder numbers z = np.zeros((3,4)) print(z) o = np.ones((4,3)) print(o) # we use range function for list which is same as 'arange' in numpy l = range(5) print(l[0]) print(l[1]) m = np.arange(1,5) #Intialize array for 1 to 4 print(m) #Step example s = np.arange(1,5,2) # Intialize array for 1 to 4 with step up by 2 print(s) #linspace function is used to generate numbers between start and stop values lins = np.linspace(1,5,10) print (lins) print() lins = np.linspace(1,5,5) print (lins) print() lins = np.linspace(1,5,20) print (lins) print() # REshaping array (They are not altering the original array but you can save it in new array) r =np.array([[1,2],[3,4],[5,6]]) print(r) print('Current shape of array is:',r.shape) print('Reshape it to (2,3) :', r.reshape(2,3)) print('Reshape it to (6,1) :', r.reshape(6,1)) print('Ravel it to one dimention :', r.ravel()) # Ravel function to flatten array and make it one dimenstional print(r) gh = r.ravel() print(gh) # Capturing ravel in new array gk= r.reshape(6,1) print(gk) # Capturing reshape in new array print() ## Mathematical operation in array x = np.array([[1,2],[3,4],[5,6]]) print(x) print('Minimum value in array : ', x.min()) print('Maximum value in array : ', x.max()) print('Sum all the numbers together : ', x.sum()) print('axis 0 denotes columns & for sum of column values : ', x.sum(axis=0)) print('axis 1 denotes eows & for sum of row values : ', x.sum(axis=1)) print('Square root ', np.sqrt(x)) # Squareroot is generic function not individual element function print('Standard deviation : ',np.std(x)) ### Basic mathematical operations x = np.array([[1,2],[3,4]]) y = np.array([[5,6],[7,8]]) print('Sum of two arrays : ', x+y) print('Multiplication of two arrays : ', x*y) print('Division of two arrays : ', x/y) print('Matrix product of two arrays : ', x.dot(y)) <file_sep>/25_CommandLine.py import argparse ### To reach till this folder in cmd follow this # D: # cd D:\Day Shift\Zpyth\Pstud ### Then run using # python Practice.py # python Practice.py -h ##### here we are writing a program that takes 3 inputs, ## 1. First number ## 2. Second number ## 3. Operation ('add','subtract','multiply') ## it should return result of operation based on inputs # Two types of Arguments: parser = argparse.ArgumentParser() ### 1. Positional parser.add_argument('number1',help='first number') parser.add_argument('number2',help='second number') ## if we dont want user to enter any other value then we can give him choices # parser.add_argument('operation', help='operation') parser.add_argument('operation', help='operation',\ choices=['add','subtract','multiply']) # 2. Optional ## To make argument optional just add -- in front of argument name then run as python Practice.py --number1 4 --number2 5 --operation add # parser.add_argument('--number1',help='first number') # parser.add_argument('--number2',help='second number') # parser.add_argument('--operation', help='operation') #################### args = parser.parse_args() print(args.number1) print(args.number2) print(args.operation) n1 = int(args.number1) n2 = int(args.number2) result = None if args.operation =='add': result = n1 + n2 elif args.operation =='subtract': result = n1 - n2 elif args.operation =='multiply': result = n1 * n2 else: print('unsupported operation') print ('Results:',result) <file_sep>/16_Error_Handling.py x = 42 y = 0 print() try: print(x / y) except ZeroDivisionError as e: print('Not allowed to divide by Zero') else: print('Something else went wrong') finally: print('This is our cleanup code') print() ## Exceptions : Exceptions are errors detected at the time of program execution x=input('Enter number 1:') y=input('Enter number 2:') try: z=int(x)/int(y) except Exception as e: print('Exception occured: ',e) z= None except Exception as e: print('Excetion occured 2',type(e).__name__) z=None print('Division is:',z) ############################ ## Raise builtin exception try: raise MemoryError('Memory Error') except MemoryError as e: print(e) try: raise Exception('memory error') except Exception as e: print(e) ## Raise user defined exception class Accident(Exception): def __init__(self,msg): self.msg = msg def print_exception(self): print('User defined exception: ',self.msg) try: raise Accident('crash between two cars') except Accident as e: e.print_exception() ## Finally: If exception happens and there is no handling of the exception ## in except block still it will execute finally block. def process_file(): try: # f=open('c:\\code\\data.txt') f=open('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\funny1.txt') x=1/0 except FileNotFoundError as e: print('inside except') finally: print('cleaning up file') f.close() process_file() <file_sep>/M1_MatplotlibIntro.py ## Matplotlib introduction import matplotlib.pyplot as plt # %matplotlib inline # to render chart in jupiter notebook x=[1,2,3,4,5,6,7] y=[50,51,52,48,47,49,46] # printing the chart print(plt.plot(x,y)) plt.show() # changing color print(plt.plot(x,y, color='green')) plt.show() # for thicker line and line style print(plt.plot(x,y, color='green',linewidth=5,linestyle='dashdot')) plt.show() # setting X & Y label and title of chart plt.xlabel('Day') plt.ylabel('Temperature') plt.title('Weather') print(plt.plot(x,y, color='green',linewidth=5,linestyle='dotted')) plt.show() <file_sep>/unittesting_pytest/test_2SkipSelect.py import mathlib_1 import pytest import sys def test_calc_total(): total = mathlib_1.calc_total(4,5) assert total == 9 @pytest.mark.skipif(sys.version_info > (3,5), reason = 'Skipped test on the basis of condition') def test_calc_multiply(): result = mathlib_1.calc_multiply(10,3) assert result == 30 @pytest.mark.skip(reason='I dont want to run this test at the moment') def test_calc_subtract(): sub_result = mathlib_1.calc_subtract(20,5) assert sub_result == 15 def test_dummy(): assert True ###### Command to see the skipped test reson is pytest -v -rxs #### Command to run selective test cases by the availability of some name like in this example we #### are running only those test cases which contain 'total' in there name. #### pytest -k total #### For mass summary pytest -k total -v #### Custom markers ####### @pytest.mark.windows ## here windows is custom marker and can be anything def test_windows_1(): assert True @pytest.mark.windows def test_windows_2(): assert True @pytest.mark.mac ## here mac is custom marker and can be anything def test_mac_1(): assert True @pytest.mark.mac def test_mac_2(): assert True ### command to run is pytest -m mac -v ### command with condition if we want to run all other then mac is ### pytest -m "not mac" -v<file_sep>/P1_PandaIntro.py ## Pandas import pandas as pd df = pd.read_csv('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\nyc_weather.csv') print(df) # What is max temperature print(df['Temperature'].max()) # To know on which dates it rains print(df['EST'][df['Events']=='Rain']) # To get average windspeed # print(df['WindSpeedMPH']) print(df['WindSpeedMPH'].mean()) # Process of cleaning messy data is called data munging or data wrangling df.fillna(0,inplace=True) # print(df['WindSpeedMPH']) print(df['WindSpeedMPH'].mean()) <file_sep>/AddCalc.py #Read the first number x = int(input('Enter first number: ')) #Get the second number y = int(input('Enter second number: ')) #Add them together result = x + y #Display the results print (str (x) +'+' + str (y) +'='+ str (result))<file_sep>/P14_PandaReadWriteFromDatabase.py ### Read database records into pandas dataframe and write it back import pandas as pd import sqlalchemy # Creating sqlalchemy engine engine = sqlalchemy.create_engine('mysql+pymysql://root:@localhost:3306/application') df = pd.read_sql_table('customers',engine) # Reading few columns df = pd.read_sql_table('customers',engine, columns=['name']) # writing query to fetch data using join query=''' select customers.name, customers.phone_number, orders.name, orders.amount from customers Inner join orders on customers.id = orders.customer_id ''' df = pd.read_sql_query(query,engine) # Write data in database from csv df = pd.read_csv('customers.csv') print(df) ## renaming column name to match with database table columns name df.rename(columns={ 'customer name' : 'name', 'customer phone': 'phone_number' }, inplace=True) print(df) # writing in database df.to_sql( name='customers', con=engine, index= False, if_exists='append' ) pd.read_sql(query,engine)<file_sep>/8-1_Conditional_Mul_Logic.py # If only one of the conditions will ever occur you can use a single if statement with elif country = input('What country do you live in? ') province = input('What province do you live in? ') tax = 0 if province == 'Alberta': tax = 0.05 elif province == 'Nunavat': tax = 0.05 elif province == 'Ontario': tax = 0.13 else: tax = 0.15 #When you use elif instead of multiple if statements you can add a default action print(tax) # if multiple conditions cause the same action they can be combined into a single condition if province == 'Alberta'\ or province == 'Nunavat': tax = 0.05 elif province == 'Ontario': tax = 0.13 else: tax = 0.15 print(tax) # If you have list of possible values to check, you can use IN operator if province in ('Alberta','Nunavat','Yukon'): tax = 0.05 elif province == 'Ontario': tax = 0.13 else: tax = 0.15 print(tax) # If an action is depends on a combination of conditions you can nest if statement if country.lower() == 'canada': if province in ('Alberta','Nunavat','Yukon'): tax = 0.05 elif province == 'Ontario': tax = 0.13 else: tax = 0.15 else: tax = 0.0 print('Tax rate is: ' + str(tax)) <file_sep>/M6_MatplotlibPieChart.py ## Matplotlib - Pie Chart import matplotlib.pyplot as plt # %matplotlib inline # to render chart in jupiter notebook exp_vals = [1400,600,300,410,250] exp_labels = ['Home Rent', 'Food','Phone/Internet Bill','Car','Other Utilities'] #autopct is used for displaying percentage and in which format upto decimal # shadow will show shadow #explode will cut out the pie # startangle to rotate pie chart plt.axis('equal') plt.pie(exp_vals, labels=exp_labels, radius=1.5, autopct='%0.2f%%', shadow=True, explode=[0,0.2,0.1,0,0], startangle=180) plt.show() <file_sep>/unittesting_pytest/test_3_1fixtures.py from mydb_3 import MyDB_1 ### Using Setup and Teardown method conn = None cur = None def setup_module(module): ### Executed before test execution print('setting up 1') global conn global cur db = MyDB_1() conn = db.connect('server') cur = conn.cursor() def teardown_module(module): ### Executed after test execution print('closing 1') cur.close() conn.close() def test_johns_id(): # db = MyDB_1() ### move this repetative code in setup function # conn = db.connect('server') # cur = conn.cursor() id = cur.execute('select id from employee_db where name=John') assert id == 123 def test_toms_id(): # db = MyDB_1() ### move this repetative code in setup function # conn = db.connect('server') # cur = conn.cursor() id = cur.execute('select id from employee_db where name=Tom') assert id == 789<file_sep>/unittesting_pytest/mathlib_4.py def calc_square(n): return n*n<file_sep>/app.py ####Store environmental variables in text file ##Don't hardcode ##Don't check sensitive values into source control ## .env file # DATABASE = Sample_Connection_String # app.py from dotenv import load_dotenv load_dotenv() import os password = os.getenv('PASSWORD') print(password) ##Final Notes # Don't hardcode sensitive information **EVER** # Use dotenv for a simple solution #Add .env to .gitignore # Consider full encryption options # Azure Key Vault<file_sep>/28_SharingDataBetProcesses_Values_Array.py ## Sharing Data between Process : Value and Array (Sharing value using them) import multiprocessing def calc_square(numbers,result,v): v.value = 5.67 # Updating the value of v inside child process and access it outside the child for idx,n in enumerate(numbers): # enumerate function will give index and value both result[idx] = n*n # print('Inside process ' + str(result[:])) if __name__ == "__main__": numbers=[2,3,5] ### Declaring shared memory variable result = multiprocessing.Array('i',3) # Using Array v = multiprocessing.Value('d',0.0) # Example by using value as variable v and assigning it some value p = multiprocessing.Process(target=calc_square,args=(numbers,result,v)) p.start() p.join() print('Outside the process Array', result[:]) print('Outside the process Value', v.value) <file_sep>/21_Iterators.py ## Iterators : a =['hey','bro','you are','awesome'] for i in a: print (i) print(dir(a)) itr = iter(a) print(itr) print(next(itr)) print(next(itr)) print(next(itr)) print(next(itr)) print(next(itr)) # List for element in [1,2,3]: print(element) # Tuple for element in (1,2,3): print(element) # Dictionary keys for key in {'one':1,'two':2}: print(key) # Characters in the string for char in '123': print(char) # Every line in a file for line in open('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\funny1.txt'): print(line,end='') print() # Remote control class RemoteControl(): def __init__(self): self.channels = ['HBO','CNN','abc','espn'] self.index = -1 def __iter__(self): return self def __next__(self): self.index += 1 if self.index == len(self.channels): raise StopIteration return self.channels[self.index] r = RemoteControl() itr = iter(r) print(next(itr)) print(next(itr)) print(next(itr)) print(next(itr)) print(next(itr)) <file_sep>/P8_PandaConcat.py #### Concat Dataframes import pandas as pd india_weather =pd.DataFrame({ 'city': ['mumbai','delhi','banglore'], 'temperature': [32,45,30], 'humidity':[80,60,78] }) print(india_weather) us_weather =pd.DataFrame({ 'city': ['new york','chicago','orlando'], 'temperature': [23,14,35], 'humidity':[68,65,75] }) print(us_weather) #concating two df into one but showing existing index numbers df= pd.concat([india_weather,us_weather]) print(df) # concating two dataframes with continuos index df = pd.concat([india_weather,us_weather], ignore_index=True) print(df) # Passing keys for two dataframes for fetching records as per key df = pd.concat([india_weather,us_weather],keys=['india','us']) print(df) print(df.loc['india']) #Appending two dataframes as column temperature_df =pd.DataFrame({ 'city': ['mumbai','delhi','banglore'], 'temperature': [32,45,30], }) windspeed_df =pd.DataFrame({ 'city': ['delhi','mumbai'], 'windspeed': [7,12], }) df = pd.concat([temperature_df,windspeed_df],axis=1) #it was not concating correctly delhi with delhi print(df) # assigning index to solve above issue temperature_df =pd.DataFrame({ 'city': ['mumbai','delhi','banglore'], 'temperature': [32,45,30], },index=(0,1,2)) windspeed_df =pd.DataFrame({ 'city': ['delhi','mumbai'], 'windspeed': [7,12], },index=(1,0)) df = pd.concat([temperature_df,windspeed_df],axis=1) print(df) # joining dataframe with series print(temperature_df) s = pd.Series(['Humid','Dry','Rain'],name='event') print(s) df=pd.concat([temperature_df,s],axis=1) #appending series in dataframe print(df) <file_sep>/M4_MatplotlibBarChart.py ## Matplotlib - Bar Chart import matplotlib.pyplot as plt import numpy as np # %matplotlib inline # to render chart in jupiter notebook company = ['GOOGL','AMZN','MSFT','FB'] revenue = [90,136,89,27] profit = [40,2,34,12] #### Bar chart plt.ylabel('revenue(bln)') plt.title('US Tech Stocks') plt.bar(company,revenue,width=0.4, label='Revenue') plt.bar(company,profit,width=0.4, label='Profit') # it will generate same bar in same chart plt.legend() plt.show() #### using numpy we can crete bar graph side by side by assigning position xpos= np.arange(len(company)) print(xpos) # plt.bar(xpos,revenue) # it will show numbers in x axis plt.xticks(xpos, company) # to replace numbers with name of company plt.ylabel('revenue(bln)') plt.title('US Tech Stocks') # -0.2 from xpos is used to show bar side by side plt.bar(xpos-0.2,revenue,width=0.4, label='Revenue') plt.bar(xpos+0.2,profit,width=0.4, label='Profit') plt.legend() plt.show() #### Horizontal bar chart plt.yticks(xpos, company) plt.title('US Tech Stocks') plt.barh(xpos-0.2,revenue,height=0.4, label='Revenue') plt.barh(xpos+0.2,profit,height=0.4, label='Profit') plt.legend() plt.show() <file_sep>/13_read_write_file.py ### File open modes ## r opens file for read only. Throws error if file does not exist. ## w opens file for writing only. If file doesnt exist then it will create new one. If it exist then it will overwrite it. ## r+ opens file for both reading and writing ## w+ opens file for reading and writing. If file doesnt exist then it will create new one. If it exist then it will overwrite it. ## a opens a file in append mode. Whatever you write to file get appended and original content will not be overwritten. # 'w' mode will overwrite the file and 'a' mode will append the file # f = open('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\funny.txt','w') f = open('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\funny.txt','a') f.write('\nI Love Python') # f = open('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\funny1.txt','w') # f.write('Teacher: Why are you late,Frank?\nFrank: Because of the sign.\nTeacher: What sign?\nFrank: The one that says"School Ahead, Go Slow".') f.close() ### Reading # We want to create a new file that has all the lines in the funny1.txt plus word count for each line f= open('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\funny1.txt','r') # print(f.read()) # for printing whole file f_out = open('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\funny_wc.txt','w') for line in f: # print(line) tokens= line.split(' ') f_out.write(' wordcount: '+str(len(tokens)) +' ' +line) # print(len(tokens)) # print(str(tokens)) f.close() f_out.close() ### Use of 'With' statement: No need to explicitly close the file by using with statement with open('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\funny1.txt','r') as f: print(f.read()) print(f.closed) # #1. File input.txt contains numbers separated by comma as shown below, # 6,8 # 7,6 # 2,8 # 9,5 # 9,6 # a. Write a function countNum(file_name,num) such that it returns number of # occurrences of a number in that file. for example, # countNum(“input.txt”,9) should return 2 # countNum(“input.txt”,100) should return 0 def countNum(file_name,num): fname='D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\'+file_name f_in = open(fname,'r') list=[] for i in f_in: # print(i) list.append(i[0]) list.append(i[2]) # print(list) count=0 for j in list: if j==str(num): count=count+1 if count==0: print('Number not availble in list and count is '+str(count)) else: print('Count of number '+str(num)+ ' is ' +str(count)) f_in.close() countNum('Input.txt',9) countNum('Input.txt',100) ############# Other way############## def countNum1(file_path,num1): count1=0 with open(file_path,'r') as fp1: for line1 in fp1.readlines(): # print(line1) tokens1=line1.split(',') count1 += count_num_in_tokens(tokens1,num1) return count1 def count_num_in_tokens(tokens1,num1): count1=0 for token1 in tokens1: if num1 == int(token1): count1 +=1 return count1 c= countNum1('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\Input.txt',9) print('count',c) ##b. Change input.txt so that when program ends it contains sum of all numbers in a line # as shown below, # 6,8,sum: 14 # 7,6,sum: 13 # 2,8,sum: 10 # 9,5,sum: 14 # 9,6,sum: 15 f2=open('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\Input1.txt','r') f2_out=open('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\Input1_wc.txt','w') # print(f2.read()) for k in f2: # print(k) f2_out.write('Sum is '+ str(int(k[0])+int(k[2]))+' of '+k) f2.close() f2_out.close() print('ok') ############## Other way################ def sum_numbers(file_input_path2,file_output_path2): output_lines=[] with open(file_input_path2,'r') as fp2: for line2 in fp2.readlines(): tokens2= line2.split(',') total = sum_tokens(tokens2) output_lines.append('sum: '+ str(total)+ ' | '+ line2) with open(file_output_path2,'w') as fw2: fw2.writelines(output_lines) def sum_tokens(tokens2): sum=0 for token2 in tokens2: sum +=int(token2) return sum sum_numbers('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\Input2.txt', 'D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\Input2_wc.txt')<file_sep>/12_helpers_import.py ## Importing a module #import module as namespace import helpers helpers.display('Not a warning', True) # import all into current namespace from helpers import * display('Not a warning 2') # import specific item into current namespace from helpers import display display('Not a warning 3') # To know how many functions in helpers module print(dir(helpers)) ########################### ## Modules is a way to reuse a code written by someone else import math print(math.sqrt(16)) print(math.pow(2,5 )) ## To know how many function are in MATH module Or you can google it print(dir(math)) print(math.pi) print(math.log10(100)) import calendar cal= calendar.month(2020,1) print(cal) print(calendar.isleap(2020)) print(calendar.isleap(2019)) print(dir(calendar)) # How to import modules availble in different directory import modules.mod_functions as f area =f.calculate_square_area(5) print(area) ### if this functions file is somwhere in the system then we need to import in this way # import sys # sys.path.append('C:\code') # import functions as f <file_sep>/27_Multiprocessing.py ## Difference between Multithread and Multiprocess: # The benefit of multiprocessing is that error or memory leak in one process # won't hurt execution of another process #### Multiprocessing ############# # Create two process: # 1. First is to calculate square of all numbers # 2. Second one is to calculate cube of numbers import time import multiprocessing square_result=[] def calc_square(numbers): global square_result for n in numbers: # time.sleep(5) print('Square :', str (n*n)) square_result.append(n*n) print('Within a process Result of square is ' + str(square_result)) def calc_cube(numbers): for n in numbers: # time.sleep(5) print('Cube :', str(n*n*n)) if __name__ == "__main__": arr =[2,3,8,9] p1 = multiprocessing.Process(target=calc_square,args=(arr,)) p2 = multiprocessing.Process(target=calc_cube,args=(arr,)) p1.start() p2.start() p1.join() p2.join() print('Result of square is ' + str(square_result)) print('Done!!') <file_sep>/P5_PandaHandleMissingData.py ## Handle Missing Data : fillna, dropna, interpolate # 1. fillna to fill missing values using different ways # 2. interpolate to make a guess on missing values using interpolation # 3. dropna to drop rows with missing values import pandas as pd df = pd.read_csv('ReadWriteFiles\\P5_weather_data.csv') print(df) print(type(df.day[0])) # Check the type of column # Convert day column str into date df = pd.read_csv('ReadWriteFiles\\P5_weather_data.csv', parse_dates=['day']) print(type(df.day[0])) # Format changed to Time stamp df.set_index('day', inplace = True) # setting day as index value print(df) ################### Fillna ######################### new_df=df.fillna(0) # replacing blank value with 0 print(new_df) #replacing na with different values for columns new_df = df.fillna({ 'temperature': 0, 'windspeed': 0, 'Events': 'no event' }) print(new_df) ## inplace of NAN we are filling previous day value new_df = df.fillna(method='ffill') print(new_df) ## inplace of NAN we are filling next day value new_df = df.fillna(method='bfill') print(new_df) ## replacing NAN values with next column data new_df = df.fillna(method='bfill',axis='columns') print(new_df) # LImit can be added to replace values upto what number of cell new_df = df.fillna(method='ffill',limit=1) print(new_df) ############################ Interpolate ###################### ## inplace of NAN we are guessing values linearly between previous and next day new_df = df.interpolate() print(new_df) ## inplace of NAN we are guessing values based on time between previous and next day new_df = df.interpolate(method='time') print(new_df) ############################ Dropna ###################### ## Drop all the rows with NA value. If any row contain NA then it will drop that row new_df = df.dropna() print(new_df) ## Drop only if all are NA new_df = df.dropna(how='all') print(new_df) ## keep only those rows which has at least one non NA value new_df = df.dropna(thresh=1) print(new_df) ## keep only those rows which has at least two non NA value new_df = df.dropna(thresh=2) print(new_df) ## How do you insert the missing days dt = pd.date_range('01-01-2017','01-11-2017') idx = pd.DatetimeIndex(dt) df=df.reindex(idx) print(df)<file_sep>/unittesting_pytest/test_3_2fixtures.py from mydb_3 import MyDB_1 import pytest ### Using pytest fixtures @pytest.fixture(scope='module') ## if we define scope = module then it will execute only once def cur(): print('setting up') ### to print this in console we have to use command pytest -v --capture=no db = MyDB_1() conn = db.connect('server') curs = conn.cursor() # return curs ### replace return with yield and below code then it will not create everytime and close at the end yield curs curs.close() conn.close() print('closing DB') def test_johns2_id(cur): # db = MyDB_1() ### move this repetative code in setup function # conn = db.connect('server') # cur = conn.cursor() id = cur.execute('select id from employee_db where name=John') assert id == 123 def test_toms2_id(cur): # db = MyDB_1() ### move this repetative code in setup function # conn = db.connect('server') # cur = conn.cursor() id = cur.execute('select id from employee_db where name=Tom') assert id == 789<file_sep>/M2_MatplotlibFormatString.py ## Matplotlib format strings in plot function import matplotlib.pyplot as plt # %matplotlib inline # to render chart in jupiter notebook x=[1,2,3,4,5,6,7] y=[50,51,52,48,47,49,46] # plus marker visual and green color (g+) g = green, + = marker print(plt.plot(x,y,'g+')) plt.show() # adding dash dash to above print(plt.plot(x,y,'g+--')) plt.show() # adding dash dot print(plt.plot(x,y,'g+-.')) plt.show() # can be specified in any order print(plt.plot(x,y,'--r*')) plt.show() # Diamond marker print(plt.plot(x,y,'rD--')) plt.show() # instead of format string we can also do this using keywords print(plt.plot(x,y,color='red',marker='D',linestyle='')) plt.show() # marker size print(plt.plot(x,y,color='red',marker='D',linestyle='',markersize=20)) plt.show() # alpha for handling transperancy print(plt.plot(x,y,color='red',alpha=0.2)) plt.show() <file_sep>/4_Strings.py ## Strings can be stored in variables first_name = 'Christopher' last_name = 'Harrison' print(first_name+last_name) print('Hello '+ first_name +' '+ last_name) ## Use of functions to modify strings sentence = 'the dog is named Sammy' print(sentence.upper()) print(sentence.lower()) print(sentence.capitalize()) print(sentence.count('a')) ##The functions help us format strings we save to files and databases, or display to users first_name = input('What is your first name? ') last_name = input('What is your last name ') print ('Hello ' + first_name.capitalize() + ' '+ last_name.capitalize()) ## Custom string formatting output = 'Hello 1, ' + first_name + ' '+ last_name print(output) output = 'Hello 2, {} {}' .format(first_name,last_name) print(output) output = 'Hello 3, {0}, {1}'.format(first_name,last_name) print(output) # Only availble in Python 3 output= f'Hello format, {first_name} {last_name}' print(output) ####################################### #Access string vaue by index text='ice cream' print(text[5]) print(text[0:3]) print(text[4:9]) print(text[:3]) print(text[4:]) t1= 'Earth revolves around the sun' print(t1[6:14]) print(t1[-3:]) # Save multiline in string address='''add line1 add line2''' print(address) print(address.encode())<file_sep>/P12_PandaStackUnstack.py ## Stack Unstack dataframe reshaping technique import pandas as pd df = pd.read_excel('ReadWriteFiles\\P12_stocks_data.xlsx',header=[0,1]) print(df) print() # Second header to row names df1 = df.stack() print(df1) print() # First header to row names df2=df.stack(level=0) print(df2) print() # reverse action using unstack df3=df1.unstack() print(df3) print() ############# 3 headers df4 = pd.read_excel('ReadWriteFiles\\P12-1_stocks_data.xlsx',header=[0,1,2]) print(df4) print() df5 = df4.stack() print(df5) <file_sep>/unittesting_pytest/test_1mathlib.py ## Always prefix test_ for the files having unit test methods import mathlib_1 ## Always give test_ prefix to all the functions def test_calc_total(): total = mathlib_1.calc_total(4,5) assert total == 9 def test_calc_multiply(): result = mathlib_1.calc_multiply(10,3) assert result == 30 def test_calc_subtract(): sub_result = mathlib_1.calc_subtract(20,5) assert sub_result == 15 #################################### ## Ways of executing # python -m pytest # First it will look under all the files and directory and look for any file which have test_ prefix #and in that file it is going to execute all the test which has test_ prefix in front of method # # py.test # When you say this it will run all the test # py.test -v #If you want to see detail output there is -v command which means verbose . When you do that it will # list down the test name and whether it is passed or fail <file_sep>/P7_PandaGroupBy.py ##### Group By (Split Apply combine) import pandas as pd df = pd.read_csv('ReadWriteFiles\\P7_weather_data_ByCities.csv') print(df) # 1. Find maximum temperature in each of cities print('\n First ') g = df.groupby('city') print(g) print('\n second ') # how to Access each of these groups for city, city_df in g: print(city) print(city_df) print('\n third ') # access a specific dataframe print (g.get_group('mumbai')) print('\n Fourth ') # print(g['temperature'].max()) print(g.max()) # 2. Find average wind speed per city print(g.mean()) print(g.describe()) import matplotlib.pyplot as plt # %matplotlib inline print(g.plot()) plt.show() <file_sep>/unittesting_pytest/test_4Parametrization.py import mathlib_4 import pytest @pytest.mark.parametrize('test_input,test_output', [ (5,25), (9,81), (10,100) ] ) def test_calc_square(test_input,test_output): square = mathlib_4.calc_square(test_input) assert square == test_output # def test_calc_square2(): # square = mathlib_4.calc_square(9) # assert square == 81 # def test_calc_square3(): # square = mathlib_4.calc_square(10) # assert square == 100 <file_sep>/14_Create_json.py import json # create a dictionary object person_dict = {'first': 'Christopher', 'last': 'Harrison'} # Add dictionary key pairs to dictionary as needed person_dict['city']='Seattle' #convert dictionary to json object person_json = json.dumps(person_dict) #print JSON object print(person_json) ###### Create JSON with nested dictionary######### #Create a staff dictionary #assign a person to a staff posiyion of program manager staff_dict={} staff_dict['Program Manager']= person_dict staff_json = json.dumps(staff_dict) print(staff_json) ################################################################## ## JSON = Java Script Object Notation ## JSON is a data exchange format similar to XML book= {} book['tom']= { 'name':'tom', 'address': '1 red street, NY', 'phone':7655667565 } book['bob']= { 'name':'bob', 'address': '1 greenred street, NY', 'phone':6467577582 } import json s=json.dumps(book) # Converting dictionary into JSON print('JSON Print') print(type(s)) print(s) with open('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\book.txt','w') as f: f.write(s) # writing JSON into text file with open('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\book.txt','r') as fin: d= fin.read() #Reading JSON file and saving it into String print('print 2') print(type(d)) print(d) book2 =json.loads(d) # Converting string into Dictionary print('print3') print(type(book2)) print(book2) print(book2['bob']) # Printing values of bob from Dictionary print(book2['bob']['phone']) # printing particular value of bob from dictionary for person in book2: # Accessing all the values in the dictionary print(book[person])<file_sep>/Dates.py ## We often need current date and time when logging errors and saving data # To get date and time we need to use the datetime library from datetime import datetime current_datetime = datetime.now() #the now function returns a datetime object print('Today is: ' + str(current_datetime)) # There are functions you can use with datetime objects to manipulate dates from datetime import datetime, timedelta today = datetime.now() print('Today is : '+ str(today)) # timedelta is used to define a period of time one_day = timedelta(days = 1) yesterday = today - one_day print ('Yesterday was :' + str(yesterday)) one_week = timedelta(weeks= 1) last_week = today - one_week print('Last week was:' + str(last_week))<file_sep>/testsel.py from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver=webdriver.Chrome(executable_path="D:\\chromedriver_win32\\chromedriver.exe") driver.maximize_window() driver.get('http://demo.automationtesting.in/Windows.html') print(driver.title) print(driver.current_url) driver.find_element_by_xpath('//*[@id="Tabbed"]/a/button').click() time.sleep(5) # driver.close() <file_sep>/Print.py print('Hello World single quotes') print("Hello world double quotes") print() print('Did you see the blank line?') print('Blank line \nin the middle of the string') print("It's a small world after all.") name = input('Please enter your name: ') print(name) print() # Debbugging with print print('Adding numbers') x= 42 + 206 print('Performing division') y= x/1 print('Math complete') # name= input('Enter your name ') # print ('hello python '+ name) x=5 print('i am integer '+ str (x)) ############################### var1= 1 var2 =2 var3 = 3 print(var1,var2,var3) ## Using sep keyword in python print print(var1,var2,var3,sep='_') print(var1,var2,var3,sep='separator') ####### Using end keyword in print initList = ['camel', 'case', 'stop'] # print each words using loop print('Printing using default print function') for item in initList: print(item) # default print function. newline is appended after each item. print() # another newline # print each words using modified print function print('Printing using modified print function') for item in initList: print(item, end='-') ##### file keyword in print # open a file in writable mood fi = open('output.txt', 'w') # initialize a list initList = ['Lion', 'case', 'stop'] # print each words using loop print('Printing using default print function') for item in initList: print(item, file=fi) # use file keyword print(file=fi) # print each words using modified print function print('Printing using modified print function') for item in initList: print(item, end='-', file=fi) # use file keyword # close the file fi.close()<file_sep>/N4_NumpyNditer.py ## Iterate numpy array using nditer import numpy as np a = np.arange(12).reshape(3,4) print(a) # iterating using for loop for row for row in a: print(row) # iterating over each of element one by one then for row in a: for cell in row: print(cell) # flaten this array into list for cell in a.flatten(): print(cell) print() # nditer allow more sophisticated way of iteration for x in np.nditer(a,order='C'): print(x) print() for x in np.nditer(a,order='F'): # fortan order print(x) # Print entire column on each iteration for x in np.nditer(a,order='F',flags=['external_loop']): print(x) # Using opflags we can readwrite the original array a1=np.arange(12).reshape(3,4) print(a1) for x in np.nditer(a1,op_flags=['readwrite']): x[...]=x*x print(a1) # print the original array values square # How to iterate through two numpy arrays simultaneously # they are compatible when either they are of equal shape or one of them is one b = np.arange(3,15,4).reshape(3,1) print(b) print() for x,y in np.nditer([a1,b]): print(x,y) <file_sep>/P13_PanadaCrosstab.py ### Crosstab import pandas as pd df= pd.read_excel('ReadWriteFiles\\P13_survey_data.xlsx') print(df) ## Creating contengency table df1= pd.crosstab(df.Nationality,df.Handedness) print(df1) ## With margin df2 = pd.crosstab(df.Sex, df.Handedness, margins=True) print(df2) df3 = pd.crosstab(df.Sex,[df.Handedness,df.Nationality], margins=True) print(df3) ## For percentage df4 = pd.crosstab(df.Sex, df.Handedness, normalize='index') print(df4) # Average age of individuals import numpy as np df5 = pd.crosstab(df.Sex, df.Handedness, values=df.Age, aggfunc=np.average) print(df5) <file_sep>/18_Inheritance.py ## Inheritance ## Benefits of Inheritance # 1. Code reuse # 2. Extensibility # 3. Readability class Vehicle: # Parent Class def general_usage(self): print('general use: transportation') class Car(Vehicle): #First Child class def __init__(self): print('I am car') self.wheels = 4 self.roof = True def specific_usage(self): print('specific use: commute to work, vacation with family') class MotorCycle(Vehicle): # Second child class def __init__(self): print('I am motor cycle') self.wheels =2 self.roof= False def specific_usage(self): self.general_usage() # Calling parent class function print('specific use: road trip, racing') c = Car() c.general_usage() # Calling Parent class function from child one class object c.specific_usage() m = MotorCycle() m.specific_usage() ## isinstance and issubclass methods ca = Car() mo = MotorCycle() # isinstance: it will tell if an object is an instance of specific class or not print(isinstance(ca,Car)) print(isinstance(ca,MotorCycle)) # issubclass: It will tell if one class is sub class of another or not print(issubclass(Car,Vehicle)) print(issubclass(Car,MotorCycle)) <file_sep>/M3_MatplotlibAxesLabelLegendsGrid.py ## Matplotlib - Axes labels, Legend, Grid import matplotlib.pyplot as plt # %matplotlib inline # to render chart in jupiter notebook days=[1,2,3,4,5,6,7] max_t=[32,51,52,48,47,49,56] min_t=[43,42,40,44,33,35,37] avg_t=[45,48,48,46,40,42,41] # all min, max avg in one graoh plt.xlabel('Days') # x axis name defined plt.ylabel('Temperature') # y axis name defined plt.title('Weather') # Chart name defined print(plt.plot(days,max_t, label='Max')) # set labels to define legends print(plt.plot(days,min_t, label='Min')) print(plt.plot(days,avg_t,label='Avg')) # plt.legend() # plt.legend(loc='lower left') # to show legends in graph and loc for location of legends to be displayed plt.legend(loc='best', shadow=True, fontsize='small') plt.grid() # to show grid lines in graph plt.show() <file_sep>/11_Collections.py #Lists are collections of item (Lists can have data of any type) names = ['Susan','Christopher' ] print(len(names)) #Get the number of items names.insert(0, 'Bill') # Insert before index print(names) names.sort() print(names) search = 'Susan'in names ## Search the value is availble in the list or not, it will return True/False print(search) scores = [] scores.append(98) #Add new item to the end scores.append(99) ## scores.remove(99) # this is used to remove item from list scores.append('hi') print(scores) print(scores[1]) # Collections are zero-indexed # Retrieving Ranges names = ['Susan' , 'Christopher' , 'Bill' , 'Justin'] presenters = names[1:3] #Start and End index print(names) print(presenters) # Arrays are also collection of item(Arrays will have data of same type) from array import array scores = array('d') scores.append(12) scores.append(14) print(scores) print(scores[1]) # Dictionaries person = {'first': 'Christopher'} person['last'] = 'Harrison' print(person) print(person['first']) christopher = {} christopher['first'] = 'Christopher' christopher['last'] = 'Harrison' susan = {} susan['first'] = 'Susan' susan['last'] = 'Ibach' people = [] people.append(christopher) people.append(susan) people.append({'first':'Bill', 'last' : 'Gates'}) print(people) ############################################################################### ## Dictionary allows to store key , value pair ## They are also known as, Maps, Hashtables, Associate Arrays d={'tom':7320923203,'rob':7325730239,'joe':732092320} print(d) print(d['tom']) ##Adding entry d['sam']=7395679879 d['bob']=5757575757 print(d) ## Deleting entry del d['sam'] print(d) ##How to print all the directory values for key in d: print('key:',key,'value:',d[key]) #another way to print all values in Dictionary is by using Tuples for k,v in d.items(): print('key:',k,'values',v) ## Search particular key in Dictionary print ('tom' in d) print('samir' in d) ## To clear all the dictionary item d.clear() print(d) ## TUPLES : Tuples is a group of values grouped together ## List: All values have similar meaning(Homogenous) ## Tuple: All values have different meaning (heterogenous) ## Tuple example point=(4,5) # 4 is x coordinate , 5 is y coordinate address = ('1 purple street','new york',10001) print(point[0]) ## Tuples are immutable # point[0] = 50 ## Write a python program that allows to store age of your family members. Program should ask to enter ## person name and age and once you are done you should be able to input name of the person and program ## should tell the age. Now print name of all your family members along with their ages. Number_of_family_members = int(input('Enter number of family number:')) name_age_Dict={} ## Initializing the dictionary for i in range (0,Number_of_family_members): ## Entering data in dictionary name = input('Enter Name: ') age = input('Enter Age:') name_age_Dict[name]=age # print(name_age_Dict) find_age_by_name = input('Enter name to find age of the person:') #Entering name of the person to find age for j in name_age_Dict: ## Finding age of the person if j == find_age_by_name: print('Age of ',j, 'is',name_age_Dict[j]) for k in name_age_Dict: # printing all the dictionary items print('Name:',k,'Age:',name_age_Dict[k]) ############################ OR ######################## def age_dictionary(): d={} while True: person = input('Enter person name, to stop dont enter anything and hit enter:') if person=='': break age= input('Enter Age:') d[person]=age print('Now Enter the name and i will tell you his/her age') while True: name= input('Enter person name, to stop dont enter anything and hit enter:') if name=='': break if name in d: print('Age of',name, 'is',d[name]) else: print('I dont know the age of',name) print('Age dictionary program is finished') age_dictionary() ## Write a function called add_and_multiply that takes two numbers as input and it should return sum and ## multiplication as two separate numbers. def add_and_multiply (a,b): sum= a+b mult = a*b return sum, mult a=4 b=5 s,m=add_and_multiply(a,b) print('sum:',s,'Multiplication',m,'Input numbers:', a, 'and', b) <file_sep>/P6_PandaHandleMissingDataReplace.py #### Handle Missing Data : replace function import pandas as pd import numpy as np df = pd.read_csv('ReadWriteFiles\\P6_weather_data.csv') print(df) # Replace -99999 values with NAN print('\n First ') new_df = df.replace(-99999, np.NAN) print(new_df) # If we have two spcial values -99999 & -88888 then we can define them in list to replace print('\n Second ') new_df = df.replace([-99999,-88888],np.NAN) print(new_df) # Replace value based on specific column using dictionary print('\n Third ') new_df = df.replace({ 'temperature': -99999, 'windspeed': [-99999,-88888], 'Events': '0', },np.NAN) print(new_df) # Replace No event with sunny and -99999 with NAN print('\n Fourth ') new_df = df.replace({ -99999: np.NAN, 'No Event': 'Sunny' }) print(new_df) # Regex is used to handle F,C & mph print('\n Fifth ') new_df = df.replace('[A-Za-z]','',regex=True) #it replace all columns having alphabet print(new_df) # Using Regex based on column using dictionary print('\n Six') new_df = df.replace({ 'temperature': '[A-Za-z]', 'windspeed': '[A-Za-z]' },'',regex=True) print(new_df) # Replacing a list of values with another list of values print('\n seven') df = pd.DataFrame({ 'score': ['exceptional','average','good','poor','average','exceptional'], 'student': ['rob','maya','parthiv','tom','julian','erica'] }) print(df) new_df =df.replace(['poor','average','good','exceptional'],[1,2,3,4]) print(new_df) <file_sep>/24_SetsAndFrozenSets.py ## Set : Set is an unordered collection of unique elements basket ={'orange','apple','mango','apple','orange'} print(type(basket)) print(basket) # other way to initialize set a=set() a.add(1) a.add(2) print(a) # Do not initialize with empty {} brackets otherwise it will be initialized as dictionary # if some content in it thn it is initialized as set b={} print(type(b)) b={'something'} print(type(b)) ## List allow index operation but set doesn't allow # print(basket[0]) ## removing duplicate elements from list numbers=[1,2,3,4,2,3,4] unique_numbers = set(numbers) #list to sets print(unique_numbers) unique_numbers.add(5) print(unique_numbers) set_to_list_unique_numbers = list(unique_numbers) # set to list print(set_to_list_unique_numbers) # set to be frozen i.e. not able to change the content of set fs = frozenset(numbers) print(fs) # fs.add(5) # it will not allow to add in frozen set ### basic operation of set x={'a','b','c'} print('a' in x) print('g'in x) for i in x: print(i) y={'a','g','h'} print(y) # Union print(x|y) # intersection print(x&y) # difference print(x-y) # sub set to check x is subset of y print(x<y) # after changing x={'h','g'} print(x) print(x<y) <file_sep>/22_Generators.py ## Generators : It is a simple way of creating iterator. def remote_control_next(): yield 'cnn' yield 'espn' itr = remote_control_next() print(itr) print(next(itr)) print(next(itr)) # print(next(itr)) for c in remote_control_next(): print(c) ## Fibonacci seqence (0,1,1,2,3,5,8,13,.....) # Produce using generators def fib(): a, b = 0, 1 while True: yield a a,b = b , a+b for f in fib(): if f > 50: break print(f) ### Benefits of using generators over class based iterator # 1. You dont need to define iter() and next() methods # 2. You dont need to raise StopIteration exception <file_sep>/M5_MatplotlibHistograms.py ## Matplotlib - Histograms import matplotlib.pyplot as plt # %matplotlib inline # to render chart in jupiter notebook Blood_sugar = [113,85,90,150,149,88,93,115,135,80,77,82,129] ## Ploting histogram # plt.hist(Blood_sugar, bins=3, rwidth=0.95) # bins are used to defin how many bars needed, and rwidth for bar space plt.hist(Blood_sugar, bins=(80,100,125,150),rwidth=0.95, color='g') plt.show() ## two side by side histogram Blood_sugar_men = [113,85,90,150,149,88,93,115,135,80,77,82,129] Blood_sugar_women = [67,98,89,120,133,150,84,69,89,79,120,112,100] plt.xlabel('Sugar range') plt.ylabel('Total no. of patients') plt.title('Blood sugar analysis') plt.hist([Blood_sugar_men,Blood_sugar_women], bins=(80,100,125,150),rwidth=0.95, color=['green','orange'], label=['men','women']) plt.legend() plt.show() ## orientation to draw horizontally plt.hist([Blood_sugar_men,Blood_sugar_women], bins=(80,100,125,150),rwidth=0.95, color=['green','orange'], label=['men','women'],orientation='horizontal') plt.legend() plt.show() <file_sep>/test.py import numpy as np a = np.array([2,3,4,5]) print(a) import os os_version= os.getenv('OS') print(os_version) <file_sep>/N3_NumpySlicingStackingIndexing.py ## Numpy: Slicing / Stacking and indexing with boolean arrays import numpy as np #Slicing n = [6,7,8] # Normal list print(n[0:2]) print(n[-1]) a = np.array([6,7,8]) #Numpy array print(a[0:2]) print(a[-1]) b = np.array([[6,7,8],[1,2,3],[9,3,2]]) #Multidimensional array print(b) print(b[1,2]) #accessing values by defining row & column print(b[0:2,2]) print(b[-1]) print(b[-1,0:2]) print(b[:,1:3]) #iterate through array for row in b: print(row) # Flaten the array and print every cell for cell in b.flat: print(cell) # Stacking two arrays together a1 = np.arange(6).reshape(3,2) a2 = np.arange(6,12).reshape(3,2) print(a1) print(a2) print(np.vstack((a1,a2))) #Stacking them together vertically print(np.hstack((a1,a2))) # Stacking them together horizontally #Horizontal split of big array into 3 equal sized array a3= np.arange(30).reshape(2,15) print(a3) print(np.hsplit(a3,3)) result = np.hsplit(a3,3) print(result[0]) print() print(result[1]) print() print(result[2]) print() # Vertical spliting of big array into 2 equal sized array vresult = np.vsplit(a3,2) print(vresult[0]) print() print(vresult[1]) print() #########Indexing with boolean arrays############# b1 = np.arange(12).reshape(3,4) print(b1) b2 = b1>4 # checking b1 values are greater than 4 or not and saving result in boolean form in b2 array print(b2) print(b1[b2]) #Here b2 array is the index of b1 array & will return value from b1 where b2 is true b1[b2]= -1 # Replace True values with other value print(b1)<file_sep>/RandomAlphabet.py import random import string lower_upper_alphabet = string.ascii_letters random_letter = random.choice(lower_upper_alphabet) print(random_letter) lower_alphabet = string.ascii_lowercase random_lower_letter = random.choice(lower_alphabet) print(random_lower_letter) upper_alphabet = string.ascii_uppercase random_upper_letter = random.choice(upper_alphabet) print(random_upper_letter) ## Function to create random alphabet letters def randomString(stringLength): letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range (stringLength)) print(randomString(10))<file_sep>/P2_PandaDataframeBasics.py ## Dataframe basics : ## Datarame is a main object in Pandas. It is used to represent data with ## rows and columns(tabular or excel spreadsheet like data) import pandas as pd # 1. Creating dataframe # df = pd.read_csv('ReadWriteFiles\\weather_data.csv') # If file is in folder of project then we can define this way df = pd.read_csv('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\weather_data.csv') print(df) # We can create dataframe from python dictionary also # weather_data ={ # 'day': ['1/1/2017','1/2/2017','1/3/2017','1/4/2017','1/5/2017','1/6/2017'], # 'temperature': [32,35,28,24,32,32], # 'windspeed': [6,7,2,7,4,2], # 'event': ['Rain','Sunny','Snow','Snow','Rain','Sunny'] # } # df1 = pd.DataFrame(weather_data) # print(df1) # 2. Dealing with rows and columns rows, columns = df.shape # To find number of rows and column print('No. of rows are :', rows) print('No. of columns are:', columns) print(df.head()) # it is going to print initial few rows only print(df.head(2)) # it will print only 2 rows print(df.tail()) # it will print last 5 rows print(df.tail(1)) # it will print last row only print(df[2:5]) # To print only data from 2 to 4th row print(df[:]) # To print all print(df) # to print all print(df.columns) # To print columns print(df.day) # To print individual column OR print(df['Events']) # To print individual column print(type(df['Events'])) # to see the type print(df[['day','Events','windspeed']]) # To print selected columns only # 3. Operations: min, mas, std, describe print(df['temperature'].max()) # Maximum temperature print(df['temperature'].mean()) # Mean of temp print(df['temperature'].min()) # Min Temp print(df.describe()) # It gives the statistics of data # 4. Conditional selection ( like SQL we can fetch records on conditional basis) print(df[df.temperature>=32]) # it will give data of temp above and equal to 32 print(df[df.temperature == df.temperature.max()]) # it will print data for the max tempe row Or print(df[df.temperature== df['temperature'].max()]) print(df['day'][df.temperature== df['temperature'].max()]) # It will print the specific day only print(df[['day','temperature']][df.temperature== df['temperature'].max()]) # Day and temperature # 5. set_index print(df) print(df.index) # give the current index of dataframe df2 = df.set_index('day') # It returns new dataframe. it doesnt modify the existing dataframe print(df) print(df2) # To modify the existing dataframe df.set_index('day',inplace=True) print(df) # Now we can use date as index print(df.loc['1/3/2017']) # to reset the index df.reset_index(inplace=True) print(df) # set event as index which is having duplicate values df.set_index('Events',inplace=True) print(df) print(df.loc['Snow']) # it wil print both the rows df.reset_index(inplace=True) print(df) <file_sep>/P4_PandaReadWriteExcelCSV.py ## Reading writing csv, excel files import pandas as pd ############## 1. Read csv ############### print('Reading CSV started \n') df = pd.read_csv('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\stock_data_withHeader.csv') print(df) # to skip the first row or header df = pd.read_csv('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\stock_data_withHeader.csv',skiprows=1) print(df) # Also we can remove header using df = pd.read_csv('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\stock_data_withHeader.csv',header=1) print(df) # Without header csv file then it will auto generate df = pd.read_csv('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\stock_data_withoutHeader.csv',header=None) print(df) # Without header csv file and define them manually df = pd.read_csv('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\stock_data_withoutHeader.csv',header=None, names=['ticker','eps','revenue','price','people']) print(df) # If file is big and we want read only few rows lets say 3 rows df = pd.read_csv('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\stock_data_withHeader.csv',header=1, nrows=3) print(df) # Want to read n.a. or not available as NAN df = pd.read_csv('ReadWriteFiles\\stock_data_withHeader.csv',header=1, na_values=['not available','n.a.']) print(df) # How to define columnwise that what data we want to convert (for that instead of list we supply dictionary) df = pd.read_csv('ReadWriteFiles\\stock_data_withHeader.csv',header=1, na_values={ 'eps':['not available','n.a.'], 'revenue':['not available','n.a.',-1], 'price':['not available','n.a.'], 'people':['not available','n.a.'] }) print(df) print('Reading CSV finished \n') ############### 2. Write csv #################### print('CSV writting started \n') # New file written with default index df.to_csv('ReadWriteFiles\\new_written_withIndex.csv') #new file written without Index df.to_csv('ReadWriteFiles\\new_written_withoutIndex.csv',index=False) # Write only selected columns print(df.columns) df.to_csv('ReadWriteFiles\\new_written_selectedColumsOnly.csv',columns=['tickers','eps']) # Skipping the header while writing df.to_csv('ReadWriteFiles\\new_written_withoutHeader.csv',header=False) print('CSV writting finished \n') ################# 3. Read excel ############### print('Reading xls started \n') df = pd.read_excel('ReadWriteFiles\\stock_data_withHeader.xls','Sheet1') print(df) df = pd.read_excel('ReadWriteFiles\\stock_data_withSingleHeader.xls','Sheet1') print(df) # Conversion of cell content from excel def convert_people_cell(cell): if cell == 'n.a.': return '<NAME>' return cell def convert_eps_cell(cell): if cell == 'not available': return None return cell df = pd.read_excel('ReadWriteFiles\\stock_data_withSingleHeader.xls','Sheet1',converters={ 'people' : convert_people_cell, 'eps': convert_eps_cell }) print(df) print('Reading xls finished \n') ########################## # 4. Write excel ####################### print('Writing xls started \n') # New file written with default index df.to_excel('ReadWriteFiles\\new_writtenExcel_withIndex.xls',sheet_name='stocks') # New file written without default index df.to_excel('ReadWriteFiles\\new_writtenExcel_withoutIndex.xlsx',sheet_name='stocks',index=False) # Start Writing from particular rows column df.to_excel('ReadWriteFiles\\new_writtenExcel_withParticularRowsColumn.xlsx',sheet_name='stocks',startrow=1,startcol=2) # Two dataframes and writing them in excel df_stocks = pd.DataFrame({ 'tickers':['GOOGL','WMT','MSFT'], 'price': [845,65,64], 'pe':[30.37,14.26,50.97], 'eps':[27.82,4.61,2.12] }) df_weather = pd.DataFrame({ 'day': ['1/1/2017','1/2/2017','1/3/2017','1/4/2017','1/5/2017','1/6/2017'], 'temperature': [32,35,28,24,32,32], 'event': ['Rain','Sunny','Snow','Snow','Rain','Sunny'] }) with pd.ExcelWriter('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\new_writtenExcel_CombinedStocksWeather.xlsx') as writer: df_stocks.to_excel(writer,sheet_name='stocks') df_weather.to_excel(writer,sheet_name='weather') print('Writing xls finished \n')<file_sep>/8-2_Complex_Conditions.py ## Sometimes you can combine condition with AND instead of nesting if statements. # A student makes honor roll if their average is >=85 # and their lowest grade is not below 75 gpa = float(input('What was your Grade Point Average? ')) lowest_grade= float(input('What was your lowest grade? ')) if gpa >= .85: if lowest_grade >= .70: print ('You made the honor roll') if gpa >= .85 and lowest_grade >= .70: print ('You made the honor roll 2') # If you need to remember the results of a condition check later in your code, # use the Boolean variables as flags if gpa >= .85 and lowest_grade >= .70: honor_roll = True else: honor_roll = False #if somewhere later in your code if honor_roll: print('You made the honor roll 3') <file_sep>/10_Functions.py #Sometimes we copy and paste our codes import datetime #print timestamps to see how long sections of code take to run first_name = 'Susan' print ('task completed') print(datetime.datetime.now()) print() for x in range(0,10): print(x) print ('Task completed 2') print (datetime.datetime.now()) print() ############################################## ## Use functions instead of repeating code #print the current time def print_time(): print('Task completed 3') print(datetime.datetime.now()) print() first_name = 'Susan' print_time() for x in range(0,10): print(x) print_time() ############################################# #pass the task name as a parameter def print_time1(task_name): print(task_name) print(datetime.datetime.now()) print() first_name = 'Susan' print_time1('First name assigned') for x in range(0,10): print(x) print_time1('loop completed') ############################################## ##Another example where code looks different but we are doing the same logic over and over first_name = input('Enter your first name: ') first_name_initial = first_name[0:1] last_name = input('Enter your last name: ') last_name_initial = last_name[0:1] print('Your initials are :' + first_name_initial + last_name_initial) ##I can still use a function but this time my function return value def get_initial(name): initial = name[0:1].upper() return initial first_name = input('Enter your first name: ') last_name = input('Enter your last name: ') print('Your initials are :' + get_initial(first_name) + get_initial(last_name)) ################################################################# ## Function is a block of code that performs a specific task ## Functions makes your code more modular and more readable. ## Problem : You are given two lists of numbers and you need to find total of each of these list def calculate_total(exp): total=0 for item in exp: total =total+item return total tom_exp_list=[2100,3400,3500] joe_exp_list=[200,500,700] toms_total= calculate_total(tom_exp_list) joes_total= calculate_total(joe_exp_list) print("Tom's total expenses:",toms_total) print("Joe's total expenses:", joes_total) def sum(a,b=0): ## b = 0 is assigned as default value ''' This function takes two arguments which are integer numbers and it will return sum of them as an output ''' print('a:',a) print('b:',b) total=a+b print('Total inside function:',total) return total n=sum(5,6) print('Total outside function:',n) n=sum(19) print('Total outside function:',n) ## Write a function called calculate_area that takes base and height as an input arguments and ## returns as area of a triangle as an output . Here is the equation for an area of a triangle, ## Triangle Area = 1/2*(base * height) def calculate_area(base, height): Triangle_area = 1/2 * (base * height) return Triangle_area Tri_area = calculate_area(3,3) print('Area of the triangle is:',Tri_area) ## Modify above function to take third parameter called shape type. Shape type could be either ## triangle or rectangle. Based on shape type it should calculate area. Equation for rectangle's area is, ## Rectangle Area = length * width def calculate_area1(width, length, shape): if shape == 'triangle': Triangle_area = 1/2 * (width * length) return Triangle_area elif shape== 'rectangle': Rectangle_area = (width * length) return Rectangle_area else: print('Unknown shape type') Tri_area1 = calculate_area1(4,4,'triangle') print('Area of the triangle is:',Tri_area1) Rec_area1 = calculate_area1(4,4,'rectangle') print('Rectangle area is:',Rec_area1) Unk_area = calculate_area1(5,5,'xyz') ## Write a function called print_pattern that takes integer number as argument and prints ## following pattern if input number is 3, ## * /n ** /n *** and If input is 4 then it should print, * /n ** /n *** /n **** def print_pattern(num): for i in range(0,num): for j in range (0,i+1): print('*',end=' ') print() print_pattern(3) print() # print_pattern(4) ## Reverse pattern def print_rev_pattern(num): for i in range (num,0,-1): for j in range(0, i): print('*',end=' ') print() print_rev_pattern (4) print() def print_revtriangle_pattern(num): for i in range (num,0,-1): for j in range(0, num-i): print(end=' ') for k in range (0,i): print('*',end=' ') print() print_revtriangle_pattern (4) print() def print_triangle_pattern(num): for i in range (0,num): # print('*',end=' ') for _j in range (0,num-i): print(end=' ') for _k in range (0,i+1): print('*',end=' ') print() print_triangle_pattern(4) print() <file_sep>/unittesting_pytest/mathlib_1.py def calc_total(a,b): return a+b def calc_multiply(a,b): return a*b def calc_subtract(a,b): return a+b ## This is incorrectly written to catch in unit test<file_sep>/N1_NumpyIntro.py ### Numpy : Its most useful feture is n dimensional array object (a.k.a ndarray) ### Benefits of Numpy array over a python list: ### 1. Less memory, 2. Fast, 3. Convenient import numpy as np import time import sys # To create an array object use a = np.array([1,2,3]) print(a) print(a[0]) print(a[1]) ## Comparing Python list with numpy array memory: l = range(1000) #python list which has 1000 elements. 1 element = 14 bytes print(sys.getsizeof(5)*len(l)) #print the size of the list array = np.arange(1000) # Numpy array with elements 0 to 999. 1 element = 4 bytes print(array.size * array.itemsize) #Print the size of array ### Fast and convenient comparison SIZE = 1000000 #creating two list l1= range(SIZE) l2 = range(SIZE) # two numpy array a1 =np.arange(SIZE) a2 = np.arange(SIZE) # measuring the time between list and numpy processing start = time.time() result = [(x+y) for x,y in zip(l1,l2)] # it will take first element from l1 and l2 add them together and put them in result print('python list took : ', (time.time()-start)* 1000) ## numpy array start= time.time() result = a1+a2 # convenient to add two list easily print('numpy took : ', (time.time()-start)*1000) ## Convinient b1 = np.array([1,2,3]) b2 = np.array([4,5,6]) print(b1+b2) print(b2-b1) print(b1*b2) print(b1/b2) <file_sep>/M7_MatplotlibSaveChart.py ## Matplotlib - save chart to file using savefig import matplotlib.pyplot as plt # %matplotlib inline # to render chart in jupiter notebook exp_vals = [1400,600,300,410,250] exp_labels = ['Home Rent', 'Food','Phone/Internet Bill','Car','Other Utilities'] #autopct is used for displaying percentage and in which format upto decimal # shadow will show shadow #explode will cut out the pie # startangle to rotate pie chart plt.axis('equal') plt.pie(exp_vals, labels=exp_labels, radius=1.5, autopct='%0.2f%%', shadow=True, explode=[0,0.1,0.1,0,0], startangle=180) # png, pdf, plt.savefig('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\piechart.png',bbox_inches='tight', pad_inches=2) plt.savefig('D:\\Day Shift\\Zpyth\\Pstud\\ReadWriteFiles\\piechart.pdf',bbox_inches='tight', pad_inches=2) plt.show() <file_sep>/8_Conditional_Logic.py # Your code needs the ability to take different actions based on different conditions price = input('How much did you pay? ') price = float(price) if price >= 1.00: tax = .07 print('Tax rate is :' + str(tax)) # You can add default action using else if price >= 1.00: tax = .07 print('Tax rate is :' + str(tax)) else: tax = 0 print('Tax rate is :' + str(tax)) # How you indent your code changes execution if price >= 1.00: tax = .07 else: tax = 0 print('Tax rate is :' + str(tax)) # Be carefull when comparing strings country = input('Enter the name of your home country: ') if country.lower() == 'canada': print('Oh look a Canadian') else: print('You are not from Canada') ######################################################################### num = input('Enter a number :') num=int(num) if num%2==0: print('Number is even') else: print('Number is odd') indian=['samosa','daal','naan'] chinese=['egg role','pot sticker','fried rice'] italian = ['pizza','pasta','risotto'] dish=(input('Enter dish name: ')).lower() if dish in indian: print('Indian cuisine') elif dish in chinese: print('Chinese cuisine') elif dish in italian: print('Italian Cuisine') else: print('Based on little knowledge I have, I dont know which cuisine is ',dish) ###################################### usa=['atlanta','new york','chicago','baltimore'] uk = ['london','bristol','cambridge'] india=['mumbai','delhi','banglore'] ## Write a program that asks user to enter a city name and it should tell you which country it belongs to city =(input('Enter city name : ')).lower() if city in usa: print('You are from USA') elif city in uk: print('You are from UK') elif city in india: print('You are from India') else: print('Your country not known to me') ##Write a program that asks user to enter two cities and tell you if they both are in same country or not city1 =(input('Enter your first city :')).lower() city2 = (input('Enter your second city :')).lower() if city1 in usa and city2 in usa: print('Both cities belong to USA') elif city1 in uk and city2 in uk: print('Both cities belong to UK') elif city1 in india and city2 in india: print('Both cities belong to India') else: print('Entered cities belong to different countries') <file_sep>/3_Numbers.py ## Working with numbers # Numbers can be stored in variables pi = 3.14159 print(pi) # Math with numbers first_num = 6 second_num = 2 print(first_num + second_num) # Addition print(first_num - second_num) # Subtraction print(first_num * second_num) # Multiplication print(first_num / second_num) # Division print(first_num ** second_num) # Exponent # If you combine strings with numbers, Python get confused days_in_feb = 29 # print(days_in_feb + 'days in February') #this is the confused example print(str(days_in_feb)+ ' days in February') #Numbers can be stored as strings #Numbers stored as strings are treated as strings first_num ='5' second_num = '6' print(first_num + second_num) # The input function always returs string first_num = input('Enter first number :') second_num = input('Enter second number :') print(first_num + second_num) #it will return string print(int(first_num) + int(second_num)) #it will return integer print(float(first_num) + float(second_num)) #it will return decimal
f82debd66c183adbd90a9e232b010dbccede832d
[ "Python" ]
68
Python
arunrajput17/PSTUD
52451bb78a6008db19e951ae802c140fa06fc55b
44ce13c1d723e26c8ccad72bfa052caa657db52d
refs/heads/main
<repo_name>mrlinnth/yanslist<file_sep>/app/Repositories/RegionRepository.php <?php namespace App\Repositories; use Prettus\Repository\Contracts\RepositoryInterface; /** * Interface RegionRepository. * * @package namespace App\Repositories; */ interface RegionRepository extends RepositoryInterface { // } <file_sep>/app/Repositories/TownshipRepositoryEloquent.php <?php namespace App\Repositories; use Prettus\Repository\Eloquent\BaseRepository; use Prettus\Repository\Criteria\RequestCriteria; use App\Repositories\TownshipRepository; use App\Models\Township; use App\Validators\TownshipValidator; /** * Class TownshipRepositoryEloquent. * * @package namespace App\Repositories; */ class TownshipRepositoryEloquent extends BaseRepository implements TownshipRepository { /** * Specify Model class name * * @return string */ public function model() { return Township::class; } /** * Boot up the repository, pushing criteria */ public function boot() { $this->pushCriteria(app(RequestCriteria::class)); } } <file_sep>/app/Http/Controllers/HomeController.php <?php namespace App\Http\Controllers; use App\Models\ExpireOption; use App\Models\Post; use App\Models\PostType; use App\Presenters\CommentPresenter; use App\Presenters\PostPresenter; use App\Presenters\RegionPresenter; use App\Repositories\CommentRepository; use App\Repositories\PostRepository; use App\Repositories\RegionRepository; use App\Transformers\PostTransformer; use Butschster\Head\Facades\Meta; use Butschster\Head\Packages\Entities\OpenGraphPackage; use Carbon\Carbon; use Illuminate\Http\Request; use Jorenvh\Share\ShareFacade as Share; /** * Class HomeController. * * @package namespace App\Http\Controllers; */ class HomeController extends Controller { protected $postRepo; protected $regionRepo; protected $postType; protected $commentRepo; public function __construct( PostRepository $postRepo, RegionRepository $regionRepo, PostType $postType, CommentRepository $commentRepo ) { $this->postRepo = $postRepo; $this->regionRepo = $regionRepo; $this->postType = $postType; $this->commentRepo = $commentRepo; } public function home() { Meta::setTitle(config('app.name')) ->setDescription(config('ylist.description')); $this->regionRepo->setPresenter(new RegionPresenter()); $regions = $this->regionRepo->all(); $post_types = $this->postType->choices(); $this->postRepo->setPresenter(new PostPresenter()); $posts = $this->postRepo->orderBy('created_at', 'desc')->all(); return inertia('Index', compact('regions', 'post_types', 'posts')); } public function new() { Meta::setTitle('New Listing') ->prependTitle(config('app.name')) ->setDescription(config('ylist.description')); $this->regionRepo->setPresenter(new RegionPresenter()); $regions = $this->regionRepo->all(); $post_types = $this->postType->choices(); $default_post_type = $this->postType->defaultValue(); $expire_options = ExpireOption::choices(); $default_expire_option = ExpireOption::defaultValue(); return inertia( 'New', compact( 'regions', 'post_types', 'default_post_type', 'expire_options', 'default_expire_option' ) ); } public function store(Request $request) { $request->validate([ 'type' => ['required'], 'is_offer' => ['boolean'], 'region_id' => ['required'], 'township_id' => ['required'], 'title' => ['required', 'min:20', 'max:200'], 'body' => ['required', 'min:20'], 'email' => ['required', 'email'], 'recaptcha_token' => ['required'] ]); if (config('app.env') === 'local') { $captcha_result = ['success' => true]; } else { $captcha_result = captcha($request->recaptcha_token); } if ($captcha_result['success']) { $inputs = $request->all(); $inputs['email'] = encrypt($inputs['email']); $inputs['user_id'] = 1; $inputs['expire_at'] = Carbon::now()->add($inputs['expire_at']); $post = Post::create($inputs); do { $unique_code = makeToken(3); } while (Post::where('qrcode', $unique_code.'.png')->first()); $url = route('view', ['post' => $post]); $post->qrcode = saveQrcode($url, $unique_code); $post->short_url = shortenUrl($url, $unique_code); $post->save(); $route = 'home'; $flash = flashMsg('success', 'Successfully posted.'); } else { $route = 'new'; $flash = flashMsg('danger', 'Something wrong, please try again.'); } return redirect()->route($route)->with($flash); } public function view(Post $post) { Meta::setTitle($post->ogs['title']) ->setDescription($post->ogs['description']); $og = new OpenGraphPackage('OG'); $og->setTitle($post->ogs['title']) ->setDescription($post->ogs['description']) ->setType($post->ogs['type']) ->setUrl($post->ogs['url']) ->addImage($post->ogs['image']); Meta::registerPackage($og); $post_types = $this->postType->choices(); // assign comments first using Post Model object $this->commentRepo->setPresenter(new CommentPresenter()); $comments = $this->commentRepo->orderBy('created_at', 'desc')->findByField('post_id', $post->id); // transform Post Model object $this->postRepo->setPresenter(new PostPresenter()); $postTransformer = new PostTransformer(); $post = $postTransformer->transform($post); $share_links = Share::currentPage()->facebook() ->twitter() ->getRawLinks(); return inertia( 'View', compact( 'post_types', 'post', 'comments', 'share_links', ) ); } public function guide() { return inertia('Guide'); } } <file_sep>/app/Models/Region.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Mcamara\LaravelLocalization\Facades\LaravelLocalization; use Prettus\Repository\Contracts\Transformable; use Prettus\Repository\Traits\TransformableTrait; /** * Class Region. * * @package namespace App\Models; */ class Region extends Model implements Transformable { use TransformableTrait; protected $guarded = []; protected $appends = ['localized_name']; public function districts(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(District::class); } public function townships(): \Illuminate\Database\Eloquent\Relations\HasManyThrough { return $this->hasManyThrough(Township::class, District::class); } public function getLocalizedNameAttribute() { return (LaravelLocalization::getCurrentLocale() == 'my') ? $this->name_mm : $this->name; } } <file_sep>/config/ylist.php <?php return [ 'description' => 'Simple listing website where anyone can easily submit and browse listings.', 'format' => [ 'date' => 'd/m/Y', ], ]; <file_sep>/app/Http/Controllers/Api/RegionController.php <?php namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use App\Presenters\RegionPresenter; use App\Repositories\RegionRepository; /** * Class RegionController. * * @package namespace App\Http\Controllers\Api; */ class RegionController extends Controller { /** * @var RegionRepository */ protected $repository; /** * RegionController constructor. * * @param RegionRepository $repository */ public function __construct(RegionRepository $repository) { $this->repository = $repository; $this->repository->setPresenter(new RegionPresenter()); } /** * Display a listing of the resource. * * @return \Illuminate\Http\JsonResponse * @throws \Prettus\Repository\Exceptions\RepositoryException */ public function index() { $regions = $this->repository->all(); return response()->json($regions); } } <file_sep>/app/Models/Township.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Mcamara\LaravelLocalization\Facades\LaravelLocalization; use Prettus\Repository\Contracts\Transformable; use Prettus\Repository\Traits\TransformableTrait; /** * Class Township. * * @package namespace App\Models; */ class Township extends Model implements Transformable { use TransformableTrait; protected $guarded = []; public function district(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(District::class); } public function posts(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(Post::class); } public function getLocalizedNameAttribute() { return (LaravelLocalization::getCurrentLocale() == 'my') ? $this->name_mm : $this->name; } } <file_sep>/resources/lang/my/comment.php <?php return [ "heading" => "ဆက်သွယ်ရန်", "text" => "ပိုစ့်တင်ထားသူ (OP) ကို ကွန်မန့် (သို့) စာပို့ခြင်းဖြင့် ဆက်သွယ်နိုင်ပါသည်။ ကွန်မန့်တွေကို လူတိုင်းဖတ်လို့ရအောင် ပိုစ့်အောက်မှာပြထားပါတယ်။ စာပို့တာဆိုရင်တော့ OP ရဲ့ မေးလ်ထဲကိုပဲပို့ပေးတာမို့ ဒီဝဘ်ဆိုဒ်မှာမပြပါ။", "count" => "ကွန်မန့် :count ခု", "new" => [ "placeholder" => "မိမိပြောလိုသော အကြောင်းအရာ ရေးရန်", "is_message" => "မေးလ်အနေနဲ့ စာပို့ရန်", "comment_submit" => "ကွန်မန့်တင်မယ်", "message_submit" => "စာပို့မယ်", "noti" => "ပေးပို့ခြင်းအောင်မြင်ပါတယ်", ] ]; <file_sep>/app/Mail/NewMessage.php <?php namespace App\Mail; use App\Models\Post; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; class NewMessage extends Mailable { use Queueable, SerializesModels; /** * The post instance. * * @var \App\Models\Post */ protected $post; protected $msg; /** * Create a new message instance. * * @param Post $post * @param String $msg */ public function __construct(Post $post, string $msg) { $this->post = $post; $this->msg = $msg; } /** * Build the message. * * @return $this */ public function build() { return $this->view('emails.new-message') ->subject('New message for '.$this->post->title) ->with([ 'postTitle' => $this->post->title, 'postUrl' => route('view', ['post' => $this->post]), 'msg' => $this->msg, ]); } } <file_sep>/database/migrations/2021_02_15_041926_update_posts_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class UpdatePostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('posts', function (Blueprint $table) { $expiry = \Carbon\Carbon::now()->addDays(3); $table->timestamp('expire_at')->default($expiry)->after('user_id'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('posts', function (Blueprint $table) { $table->dropColumn('expire_at'); }); } } <file_sep>/app/Providers/RepositoryServiceProvider.php <?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class RepositoryServiceProvider extends ServiceProvider { /** * Register services. * * @return void */ public function register() { // } /** * Bootstrap services. * * @return void */ public function boot() { $this->app->bind(\App\Repositories\PostRepository::class, \App\Repositories\PostRepositoryEloquent::class); $this->app->bind(\App\Repositories\RegionRepository::class, \App\Repositories\RegionRepositoryEloquent::class); $this->app->bind(\App\Repositories\DistrictRepository::class, \App\Repositories\DistrictRepositoryEloquent::class); $this->app->bind(\App\Repositories\TownshipRepository::class, \App\Repositories\TownshipRepositoryEloquent::class); $this->app->bind(\App\Repositories\CommentRepository::class, \App\Repositories\CommentRepositoryEloquent::class); //:end-bindings: } } <file_sep>/database/factories/PostFactory.php <?php namespace Database\Factories; use App\Models\Post; use App\Models\PostType; use App\Repositories\RegionRepository; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Arr; class PostFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = Post::class; /** * Define the model's default state. * * @return array */ public function definition() { // yangon, mandalay $region_id = $this->faker->randomElement([13, 10]); $regionRepo = app(RegionRepository::class); $region = $regionRepo->with('townships')->find($region_id); $township_ids = Arr::pluck($region->townships, 'id'); return [ 'id' => $this->faker->uuid, 'type' => $this->faker->randomElement(PostType::values()), 'is_offer' => $this->faker->boolean, 'title' => $this->faker->catchPhrase, 'body' => $this->faker->text, 'region_id' => $region_id, 'township_id' => $this->faker->randomElement($township_ids), 'user_id' => 1, 'email' => encrypt($this->faker->email), ]; } } <file_sep>/app/Models/PostStatus.php <?php namespace App\Models; use Konekt\Enum\Enum; class PostStatus extends Enum { const __DEFAULT = self::PUBLISHED; const PUBLISHED = 'published'; const PENDING = 'pending'; const ARCHIVED = 'archived'; protected static $labels = []; protected static function boot() { static::$labels = [ self::PUBLISHED => __('Published'), self::PENDING => __('Pending'), self::ARCHIVED => __('Archived') ]; } } <file_sep>/app/Transformers/TownshipTransformer.php <?php namespace App\Transformers; use App\Models\Township; use League\Fractal\TransformerAbstract; /** * Class PostTransformer. * * @package namespace App\Transformers; */ class TownshipTransformer extends TransformerAbstract { /** * Transform the Post entity. * * @param Township $model * * @return array */ public function transform(Township $model): array { return [ 'id' => (int) $model->id, 'name' => (string) $model->localized_name, ]; } } <file_sep>/app/Presenters/RegionPresenter.php <?php namespace App\Presenters; use App\Transformers\RegionTransformer; use Prettus\Repository\Presenter\FractalPresenter; /** * Class PostPresenter. * * @package namespace App\Presenters; */ class RegionPresenter extends FractalPresenter { /** * Transformer * * @return RegionTransformer */ public function getTransformer(): RegionTransformer { return new RegionTransformer(); } } <file_sep>/app/Transformers/RegionTransformer.php <?php namespace App\Transformers; use App\Models\Region; use League\Fractal\TransformerAbstract; /** * Class PostTransformer. * * @package namespace App\Transformers; */ class RegionTransformer extends TransformerAbstract { protected $defaultIncludes = ['townships']; /** * Transform the Post entity. * * @param Region $model * * @return array */ public function transform(Region $model): array { return [ 'id' => (int) $model->id, 'name' => (string) $model->localized_name ]; } public function includeTownships(Region $model) { if ($model->townships) { return $this->collection($model->townships, new TownshipTransformer()); } else { return null; } } } <file_sep>/resources/lang/en/comment.php <?php return [ "heading" => "Contact", "text" => "You can reach original poster (OP) by leaving a comment or sending a message. Comments are shown publicly under the post. Messages are privately sent to OP's mail box and will not show on website.", "count" => ":count comments", "new" => [ "placeholder" => "Enter your text", "is_message" => "Send as mail", "comment_submit" => "Post Comment", "message_submit" => "Send Message", "noti" => "Successfully submitted.", ] ]; <file_sep>/app/Transformers/CommentTransformer.php <?php namespace App\Transformers; use App\Models\Comment; use League\Fractal\TransformerAbstract; /** * Class CommentTransformer. * * @package namespace App\Transformers; */ class CommentTransformer extends TransformerAbstract { /** * Transform the Comment entity. * * @param \App\Models\Comment $model * * @return array */ public function transform(Comment $model) { return [ 'id' => (int) $model->id, 'text' => (string) decrypt($model->text), 'time_ago' => $model->created_at->diffForHumans(), 'created_at' => $model->created_at->format('d/m/Y') ]; } } <file_sep>/app/Models/ExpireOption.php <?php namespace App\Models; use Konekt\Enum\Enum; class ExpireOption extends Enum { const __DEFAULT = self::ONE_WEEK; const ONE_WEEK = '1 week'; const TWO_WEEK = '2 weeks'; const ONE_MONTH = '1 month'; const TWO_MONTH = '2 months'; protected static $labels = []; protected static function boot() { static::$labels = [ self::ONE_WEEK => __('1 week'), self::TWO_WEEK => __('2 weeks'), self::ONE_MONTH => __('1 month'), self::TWO_MONTH => __('2 months') ]; } } <file_sep>/app/Http/Controllers/TrySomething.php <?php namespace App\Http\Controllers; use App\Models\Comment; use Illuminate\Http\Request; class TrySomething extends Controller { /** * Handle the incoming request. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|int */ public function __invoke(Request $request) { $message = Comment::findOrFail(5); return view('emails.new-message') ->with([ 'postTitle' => $message->post->title, 'postUrl' => route('view', ['post' => $message->post]), 'message' => decrypt($message->text), ]); } } <file_sep>/app/Models/Post.php <?php namespace App\Models; use App\Traits\Uuids; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Konekt\Enum\Eloquent\CastsEnums; use Prettus\Repository\Contracts\Transformable; use Prettus\Repository\Traits\TransformableTrait; use Spatie\Sluggable\HasSlug; use Spatie\Sluggable\SlugOptions; /** * Class Post. * * @package namespace App\Models; */ class Post extends Model implements Transformable { use TransformableTrait, CastsEnums, Uuids, HasFactory, HasSlug; protected $table = 'posts'; protected $fillable = [ 'type', 'is_offer', 'title', 'body', 'region_id', 'township_id', 'user_id', 'email', 'expire_at' ]; protected $appends = ['location', 'duration', 'ogs']; protected $dates = ['expire_at']; protected $enums = [ 'type' => PostType::class ]; /** * Get the options for generating the slug. */ public function getSlugOptions(): SlugOptions { return SlugOptions::create() ->generateSlugsFrom('title') ->saveSlugsTo('slug'); } /** * Get the route key for the model. * * @return string */ public function getRouteKeyName(): string { return 'slug'; } public function region(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Region::class); } public function township(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Township::class); } public function comments(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(Comment::class); } public function getLocationAttribute() { return $this->township->localized_name.', '.$this->region->localized_name; } public function getDurationAttribute() { return $this->expire_at->format(config('ylist.format.date')); } public function getOgsAttribute() { $title = __('post.types.'.$this->type->value()).' '; $title .= ($this->is_offer) ? __('main.is_offer') : __('main.not_offer'); $title .= ' @'.$this->location; return [ 'type' => 'website', 'url' => route('view', ['post' => $this]), 'title' => $title, 'description' => $this->title, 'image' => asset('storage/qrcodes/'.$this->qrcode), ]; } } <file_sep>/app/helpers.php <?php use SimpleSoftwareIO\QrCode\Facades\QrCode; if (!function_exists('makeToken')) { /** * Generate alphanumeric token. * * @param int $length (Outcome will be 2 times the number provided.) * @return string * @throws Exception */ function makeToken($length = 4): string { $bytes = random_bytes($length); $token = bin2hex($bytes); return $token; } } if (!function_exists('flashMsg')) { /** * Create flash session to use for alert and noti. * * @param string $type (primary, info, success, danger) * @param string $msg * @return string[] */ function flashMsg(string $type = 'primary', string $msg = 'Successfully submitted.'): array { return ['type' => $type, 'message' => $msg]; } } if (!function_exists('saveQrcode')) { /** * Generate a qrcode as png and save in storage * Return filename * * @param string $url * @param string $code * @return string */ function saveQrcode(string $url, string $code): string { $filename = $code.'.png'; QrCode::size(300) ->gradient(29, 29, 80, 141, 131, 237, 'radial') ->format('png') ->generate($url, storage_path('app/public/qrcodes/'.$filename)); return $filename; } } if (!function_exists('captcha')) { /** * Submit recaptcha to google api. * * @param String $token * @return array|mixed */ function captcha(string $token) { $response = Http::asForm()->post(config('services.recaptcha.domain'), [ 'secret' => config('services.recaptcha.secret'), 'response' => $token, ]); return $response->json(); } } if (!function_exists('shortenUrl')) { /** * Shorten url using Polr API * * @param string $url * @param string $code * @return string */ function shortenUrl(string $url, string $code): string { $endpoint = config('services.polr.domain').'/api/v2/action/shorten'; $response = Http::post($endpoint, [ 'key' => config('services.polr.key'), 'url' => $url, 'custom_ending' => $code, ]); return $response->body(); } } <file_sep>/resources/lang/my/post.php <?php return [ "types" => [ "aid" => "အထောက်အပံ့", "shelter" => "ခိုလှုံနားရာ", "healthcare" => "ကျန်းမာရေး", "service" => "ဝန်ဆောင်မှု" ], "expire_options" => [ "1 week" => "တစ်ပတ်", "2 weeks" => "နှစ်ပတ်", "1 month" => "တစ်လ", "2 months" => "နှစ်လ" ], "new" => [ "heading" => "ပိုစ့်အသစ်", "help_text" => "ပိုစ့်တင်ပြီးရင် ပြန်ပြင်လို့မရတော့တာမို့ အချက်အလက်တွေကို မှန်မမှန်စီစစ်ပြီး သေချာမှ ပိုစ့်တင်ပါ။", "aim" => "ပိုစ့်ရည်ရွယ်ချက်", "is_offer" => "ကမ်းလှမ်းချင်တာပါ။", "not_offer" => "လိုအပ်နေလို့ပါ။", "post_type" => "အမျိုးအစား", "region" => "တိုင်းဒေသကြီး", "township" => "မြို့နယ်", "expire_at" => "ပိုစ့်သက်တမ်း", "title" => "ခေါင်းစဥ်", "title_placeholder" => "တိုတိုရှင်းရှင်း ဖေါ်ပြနိုင်သည့် ခေါင်းစဥ်ရေးရန်", "body" => "အသေးစိတ်အချက်အလက်", "body_placeholder" => "အသေးစိတ်အကြောင်းအရာများအား ပြည့်စုံစွာရေးရန်", "email" => "လက်ရှိသုံးနေတဲ့ အီးမေးလ်လိပ်စာ", "email_placeholder" => "အီးမေးလ်လိပ်စာရေးရန်", "email_info" => "တစ်ခြားလူတစ်ဦးကနေသင့်ကို သီးသန့်ဆက်သွယ်လို့ရအောင် ကိုယ်သုံးနေတဲ့အီးမေးလ်တစ်ခုပေးထားရပါမယ်။ ဒီမေးလ်ကို ဘယ်သူ့ကိုမှ ပေးသိမှာမဟုတ်ပါဘူး။ ဆက်သွယ်ချင်သူရေးတဲ့စာကို ဒီဝဘ်ဆိုဒ်ကနေ တစ်ဆင့်ခံပို့ပေးမှာပါ။", "submit_info" => "ပိုစ့်မတင်ခင် ကိုယ့်မေးလ်အပါအဝင် အချက်အလက်အကြောင်းအရာတွေ မှန်လားထပ်စစ်ပါ။", "submit" => "ပိုစ့်တင်မယ်" ] ]; <file_sep>/app/Models/District.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Prettus\Repository\Contracts\Transformable; use Prettus\Repository\Traits\TransformableTrait; /** * Class District. * * @package namespace App\Models; */ class District extends Model implements Transformable { use TransformableTrait; protected $guarded = []; public function townwhips(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(Township::class); } public function region(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Region::class); } } <file_sep>/app/Models/Comment.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Prettus\Repository\Contracts\Transformable; use Prettus\Repository\Traits\TransformableTrait; /** * Class Comment. * * @package namespace App\Models; */ class Comment extends Model implements Transformable { use TransformableTrait, HasFactory; protected $table = 'comments'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['post_id', 'text', 'is_message']; public function post(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Post::class); } } <file_sep>/routes/web.php <?php use App\Http\Controllers\HomeController; use App\Http\Controllers\TrySomething; use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Storage; use Mcamara\LaravelLocalization\Facades\LaravelLocalization; Route::group( [ 'prefix' => LaravelLocalization::setLocale(), 'middleware' => ['localeSessionRedirect', 'localizationRedirect', 'localeViewPath', 'xssSanitizer'] ], function () { Route::get('/', [HomeController::class, 'home'])->name('home'); Route::get('/new', [HomeController::class, 'new'])->name('new'); Route::post('/new', [HomeController::class, 'store'])->name('store'); Route::get('/l/{post}', [HomeController::class, 'view'])->name('view'); Route::get('get-qr/{path}', function ($path) { return Storage::download('qrcodes/'.$path); })->name('qrcode'); Route::get('/guide', [HomeController::class, 'guide'])->name('guide'); if (config('app.debug')) { Route::get('/test', TrySomething::class)->name('test'); } }); <file_sep>/app/Presenters/TownshipPresenter.php <?php namespace App\Presenters; use App\Transformers\TownshipTransformer; use Prettus\Repository\Presenter\FractalPresenter; /** * Class PostPresenter. * * @package namespace App\Presenters; */ class TownshipPresenter extends FractalPresenter { /** * Transformer * * @return TownshipTransformer */ public function getTransformer(): TownshipTransformer { return new TownshipTransformer(); } } <file_sep>/app/Models/PostType.php <?php namespace App\Models; use Konekt\Enum\Enum; class PostType extends Enum { const __DEFAULT = self::AID; const AID = 'aid'; const SERVICE = 'service'; const SHELTER = 'shelter'; const HEALTHCARE = 'healthcare'; protected static $labels = []; protected static function boot() { static::$labels = [ self::AID => __('Aid'), self::SERVICE => __('Service'), self::SHELTER => __('Shelter'), self::HEALTHCARE => __('Health-care'), ]; } } <file_sep>/app/Http/Controllers/Api/PostController.php <?php namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use App\Mail\NewMessage; use App\Models\Post; use App\Presenters\PostPresenter; use App\Repositories\CommentRepository; use App\Repositories\PostRepository; use App\Transformers\CommentTransformer; use Illuminate\Http\Request; use Illuminate\Support\Facades\Mail; /** * Class RegionController. * * @package namespace App\Http\Controllers\Api; */ class PostController extends Controller { /** * @var PostRepository */ protected $postRepo; /** * @var CommentRepository */ protected $commentRepo; /** * RegionController constructor. * * @param PostRepository $postRepo * @param CommentRepository $commentRepo */ public function __construct(PostRepository $postRepo, CommentRepository $commentRepo) { $this->postRepo = $postRepo; $this->postRepo->setPresenter(new PostPresenter()); $this->commentRepo = $commentRepo; } /** * @param Post $post * @param Request $request * @return \Illuminate\Http\JsonResponse */ public function comment(Post $post, Request $request): \Illuminate\Http\JsonResponse { $validated = $request->validate([ 'text' => 'required', ]); if (config('app.env') === 'local') { $captcha_result = ['success' => true]; } else { $captcha_result = captcha($request->recaptcha_token); } if ($captcha_result['success']) { if ($request->is_message) { Mail::to(decrypt($post->email))->send(new NewMessage($post, $request->text)); return response()->json(['message' => 'Message successfully sent.']); } $result = $this->commentRepo->create( [ 'post_id' => $post->id, 'is_message' => $request->is_message, 'text' => encrypt($request->text) ] ); $commentTransformer = new CommentTransformer(); $comment = $commentTransformer->transform($result); return response()->json($comment); } return response()->json(['message' => 'Something wrong, please try again.']); } } <file_sep>/resources/js/helpers.js export default { methods: { showNoti(type, msg) { window.UIkit.notification({ status: type, message: msg, pos: 'bottom-center', }); } } } <file_sep>/resources/lang/en/post.php <?php return [ "types" => [ "aid" => "Aid", "shelter" => "Shelter", "healthcare" => "Health-care", "service" => "Service" ], "expire_options" => [ "1 week" => "1 week", "2 weeks" => "2 weeks", "1 month" => "1 month", "2 months" => "2 months" ], "new" => [ "heading" => "New Post", "help_text" => "You cannot edit after submission. Please only enter correct and confirm information.", "aim" => "Aim", "is_offer" => "We are offering", "not_offer" => "We are seeking", "post_type" => "Category", "region" => "Region", "township" => "Township", "expire_at" => "Expires On", "title" => "Title", "title_placeholder" => "Short and clear title for your listing", "body" => "Details Information", "body_placeholder" => "Details description about your listing", "email" => "Your email", "email_placeholder" => "Enter email address to receive messages", "email_info" => "You must provide an email address for people to privately contact you. Your email will not be shown. System will mail the message on behalf of the sender.", "submit_info" => "Before submit, be sure to check all information and your email address.", "submit" => "Submit" ] ]; <file_sep>/resources/lang/my/home.php <?php return [ "browse_listings_by" => "စီစစ်ပြီး ကြည့်ရန်", "search" => "စီစစ်မယ်", "total_listings" => "ပိုစ့် စုစုပေါင်း :total ခု", "all_types" => "ကဏ္ဍအားလုံး" ]; <file_sep>/README.md ## Installation 1. clone repo or download the latest releases at [https://github.com/mrlinnth/yanslist](https://github.com/mrlinnth/yanslist) 2. run `composer install` 3. create `.env` file by duplicating and renaming `.env.example` file 4. create your database and update `.env` file with your database credentials 5. change `APP_URL` in `.env` file with your app url 6. setup google recaptcha - refer to [https://itnext.io/how-to-use-google-recaptcha-with-vuejs-7756244400da](https://itnext.io/how-to-use-google-recaptcha-with-vuejs-7756244400da) - change `MIX_RECAPTCHA_SITEKEY`, `RECAPTCHA_DOMAIN`, `RECAPTCHA_SECRET` in `.env` file with your recaptcha data 7. run `composer install` 8. run `php artisan key:generate` 9. run `php artisan migrate` for schema and table creation 10. run `php artisan ylist:import-region` to import region, district, township data 11. run `php artisan db:seed --class=PostSeeder` to generate dummy data _(optional)_ 12. run `npm install` 13. run `php artisan VueTranslation:generate` to share laravel lang files with vue 14. run `npm run dev` <file_sep>/app/Console/Commands/Yan.php <?php namespace App\Console\Commands; use Illuminate\Console\Command; class Yan extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'yan'; /** * The console command description. * * @var string */ protected $description = 'Command for development purpose'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return int */ public function handle() { // $posts = Post::all(); // foreach ($posts as $post) { // do { // $unique_code = makeToken(3); // } while (Post::where('qrcode', $unique_code.'.png')->first()); // $url = route('view', ['post' => $post]); // $post->qrcode = saveQrcode($url, $unique_code); // $post->short_url = shortenUrl($url, $unique_code); // $post->save(); // } // $this->info('Generating qrcode and short url finished'); return 0; } } <file_sep>/app/Transformers/PostTransformer.php <?php namespace App\Transformers; use App\Models\Post; use League\Fractal\TransformerAbstract; /** * Class PostTransformer. * * @package namespace App\Transformers; */ class PostTransformer extends TransformerAbstract { /** * Transform the Post entity. * * @param \App\Models\Post $model * * @return array */ public function transform(Post $model) { return [ 'type' => $model->type->value(), 'is_offer' => $model->is_offer, 'region_id' => $model->region_id, 'township_id' => $model->township_id, 'title' => $model->title, 'slug' => $model->slug, 'body' => $model->body, 'short_url' => $model->short_url, 'qrcode' => $model->qrcode, 'location' => $model->location, 'duration' => $model->duration, 'ogs' => $model->ogs ]; } } <file_sep>/resources/lang/en/main.php <?php return [ "listings" => "Listings", "guide" => "Guide", "contact" => "Contact", "post_new" => "Post New", "select_region" => "Select Region", "select_township" => "Select Township", "select_type" => "Select Type", "is_offer" => "Offer", "not_offer" => "Seeker", "close" => "Close", "all" => "All", "share" => "Share" ]; <file_sep>/resources/lang/my/main.php <?php return [ "listings" => "ပိုစ့်များ", "guide" => "အသုံးပြုနည်း", "contact" => "ဆက်သွယ်ရန်", "post_new" => "အသစ်တင်မယ်", "select_region" => "တိုင်းဒေသကြီးရွေးပါ", "select_township" => "မြို့နယ်ရွေးပါ", "select_type" => "ကဏ္ဍရွေးပါ", "is_offer" => "ကမ်းလှမ်း", "not_offer" => "လိုအပ်", "close" => "ပိတ်ရန်", "all" => "အားလုံး", "share" => "မျှဝေမယ်" ]; <file_sep>/resources/lang/en/home.php <?php return [ "browse_listings_by" => "Browse Listings By", "search" => "Search", "total_listings" => "Total :total listings", "all_types" => "All Types", ]; <file_sep>/CHANGELOG.md # Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). ## [captcha](https://github.com/yanslist/yanslist/compare/0.1.5...captcha) - 2021-02-23 ## [0.1.5](https://github.com/yanslist/yanslist/compare/0.1.4...0.1.5) - 2021-02-26 ### Commits - Merge tag '0.1.4' into develop [`8debf6f`](https://github.com/yanslist/yanslist/commit/8debf6f7f8ddd1a9c64f11c47f02eaede550e4a7) - Changed: Changelog [`3eb94d2`](https://github.com/yanslist/yanslist/commit/3eb94d22540780a849a3f0cdeebc58a0834f1006) - Fixed: recaptcha bug on vue submit [`f5bed8d`](https://github.com/yanslist/yanslist/commit/f5bed8d16ae383574e9731d8e24d54a4b21d1544) - Merge tag 'captcha' into develop [`6d080f3`](https://github.com/yanslist/yanslist/commit/6d080f3c7ffeb6a9bcf3aefcd25ffc0e6289e07d) - Added: installed sendinblue and setting packages [`21ed245`](https://github.com/yanslist/yanslist/commit/21ed24523f5313a9616213bb1e7fea3a2b83dd36) - Added: installed ckeditor vue package and setup post body [`0e7c8d8`](https://github.com/yanslist/yanslist/commit/0e7c8d82800349cca4f6c8a5cdaef56dfb49cb94) - Added: installed sendinblue package and setup [`27c85dc`](https://github.com/yanslist/yanslist/commit/27c85dc66bc104b13b783a471c7a2298d79f1a92) - Added: used laravel Mail feature for new message [`f033d28`](https://github.com/yanslist/yanslist/commit/f033d28b135a33555cfaf88667721c048aac98a0) ## [0.1.4](https://github.com/yanslist/yanslist/compare/0.1.3...0.1.4) - 2021-02-21 ### Merged - v.0.1.1 [`#1`](https://github.com/yanslist/yanslist/pull/1) ### Commits - Merge tag '0.1.3' into develop [`22fb9f2`](https://github.com/yanslist/yanslist/commit/22fb9f271153867dc3a983823f712f0b13a91656) - Changed: updated changelog. [`b74b6a7`](https://github.com/yanslist/yanslist/commit/b74b6a7718471c9078cf404e978dc2da18ac9c3f) - Changed: responsive fix for header, footer, form [`2b282ed`](https://github.com/yanslist/yanslist/commit/2b282ed7e84ef6e19baf784aa25d7700b64b6055) - Added: post view page, comment migration and repo files. [`fec4ad6`](https://github.com/yanslist/yanslist/commit/fec4ad6fe93addf5b6a55faf2194251131db942b) - Added: comment ui prototype [`b2e4859`](https://github.com/yanslist/yanslist/commit/b2e4859327258711a42256750bda585845fa1c04) - Changed: wip encryption [`9419fa9`](https://github.com/yanslist/yanslist/commit/9419fa9c3683729fcb47dcb6a4ed3e32309b18f7) - Changed: wip encryption [`429329a`](https://github.com/yanslist/yanslist/commit/429329a788ff012b7aa800e94509b30705da49ad) - Fixed: disable recaptcha on local env [`7cdeaac`](https://github.com/yanslist/yanslist/commit/7cdeaac91fb91ebe4fe888111127350ffacdd85e) - Changed: single post view layout [`8d4caec`](https://github.com/yanslist/yanslist/commit/8d4caeceb08804bc9fddff305127eda55680cd62) - Refactor: Comments to Comment usage [`9b044fb`](https://github.com/yanslist/yanslist/commit/9b044fb99108377a6746d134eba933d1252d7b2d) - Added: Comment seeder and api [`bc5086b`](https://github.com/yanslist/yanslist/commit/bc5086be10d10428242571aa5804d50587e8cc73) - Refactor: A href to Inertia Link [`4d290db`](https://github.com/yanslist/yanslist/commit/4d290db93d8ff131a5efb112347d7c6a46e0082e) - Changed: noti function into helper mixin [`0883753`](https://github.com/yanslist/yanslist/commit/0883753b6ae3af10c039310d53e44bf26217dba8) - Added: correct token show comments modal prototype [`60c87e0`](https://github.com/yanslist/yanslist/commit/60c87e0696b24c6493f2178fc62e48c90906cf13) - Added: show comments [`dc33498`](https://github.com/yanslist/yanslist/commit/dc3349813f1892a30ac80ab4fffddf63c3cbb588) - Added: comment submit [`c07ec4e`](https://github.com/yanslist/yanslist/commit/c07ec4e127766f7cbe66bd01cd76c1dec91f7243) - Changed: remove token feature, refactor comment feature [`6f0180c`](https://github.com/yanslist/yanslist/commit/6f0180c42adda1ae2a249c06b3e893ae5b889c7c) - Changed: Comments into comment and message [`2f46109`](https://github.com/yanslist/yanslist/commit/2f461099c6480d27c423eb9502e5fb1e9274e694) - Added: validation messages to new post form [`8ee5fce`](https://github.com/yanslist/yanslist/commit/8ee5fce3fe142b2a0f1596267b993b0b2730fa4e) - Fixed: minor ui fix [`364de8a`](https://github.com/yanslist/yanslist/commit/364de8a71030b741e694a88c39b5ecd3dc8a7985) - Added: laravel-share, simple-qr packages [`49c593f`](https://github.com/yanslist/yanslist/commit/49c593f9aabcca6b1ab41ce476cdaeef683fcf62) - Added: Generate qr code image and save in storage and filename in database [`76b993f`](https://github.com/yanslist/yanslist/commit/76b993f3fcf9bcb836d6a2a8e6d340ed2b9249f8) - Added: Shorten post url and show on view page [`9b12424`](https://github.com/yanslist/yanslist/commit/9b124242d0fed15842c53be6a2c9003c33b79c62) - Changed: Home page type filter from uikit to vuejs [`e5db9b9`](https://github.com/yanslist/yanslist/commit/e5db9b928f5d33140fb1fbf53f7ca0c5ed462b75) - Changed: Todo [`71b9934`](https://github.com/yanslist/yanslist/commit/71b9934d213e8fc278a364305f77c1e604a69def) ## [0.1.3](https://github.com/yanslist/yanslist/compare/0.1.1...0.1.3) - 2021-02-15 ### Commits - Merge tag '0.1.1' into develop [`c26c228`](https://github.com/yanslist/yanslist/commit/c26c228ea0a2cf89ee902965f92f26b0ed9dfa30) - docs: updated changelog [`730c306`](https://github.com/yanslist/yanslist/commit/730c306068dbec7da60d01c5ae6df9b74115775f) - fix: updated gitignore [`b2ed631`](https://github.com/yanslist/yanslist/commit/b2ed6310037815e28f31c4bd29b325562f6c46e5) - fix: added todo.md [`c5af99c`](https://github.com/yanslist/yanslist/commit/c5af99c2cafe7c650e965ddb4068ac45e4c1aced) - feat: expiry date for post [`0562912`](https://github.com/yanslist/yanslist/commit/0562912a02669dbd14ad9737f593d9e198daea23) - docs: todo updated [`7103327`](https://github.com/yanslist/yanslist/commit/710332715b06438edf1f5e2c112601dd1228c0ef) ## [0.1.1](https://github.com/yanslist/yanslist/compare/0.1.0...0.1.1) - 2021-02-14 ### Commits - Merge tag '0.1.0' into develop [`b0b7ec9`](https://github.com/yanslist/yanslist/commit/b0b7ec96bf4af6cc1463af8d2c82963a21c4a812) - updated readme [`f5c5644`](https://github.com/yanslist/yanslist/commit/f5c5644aa637e219e6a49001720e2b18ddb751d8) - refactor: removed orchid platform package [`6ea1220`](https://github.com/yanslist/yanslist/commit/6ea1220cfff52a8a6b59099b8276a97d20948a85) - fix: used auto-changelog and conventional commits [`720cf69`](https://github.com/yanslist/yanslist/commit/720cf69834503aab86b944665dde25394a69abc8) - refactor: added helper file [`b34636c`](https://github.com/yanslist/yanslist/commit/b34636c1ce7bfb71d2bbf86512d832b8cf6fd8df) - fix: minor update to text and form [`d541cd1`](https://github.com/yanslist/yanslist/commit/d541cd1b6ac8670307e20b3293af7f232d045917) ## 0.1.0 - 2021-02-14 ### Commits - initial commit [`1099d49`](https://github.com/yanslist/yanslist/commit/1099d492c5496cf36f992b361f3aff2b542e5924) - added Post model files [`079525e`](https://github.com/yanslist/yanslist/commit/079525e332dda16799fbd1db55d1a095f202c652) - added Post seeder [`abac24c`](https://github.com/yanslist/yanslist/commit/abac24c367e1ea5f8a0ec0a0638a11b6c013d65a) - added Slug [`74d1a32`](https://github.com/yanslist/yanslist/commit/74d1a326c4d7de2642339e6e6fe5010650887a87) - removed concord [`e30f90d`](https://github.com/yanslist/yanslist/commit/e30f90da1f8079ad1c05693e3356e6397a52bc90) - updated seeder [`510b0ca`](https://github.com/yanslist/yanslist/commit/510b0cac2d73c3d624b53607b9e265622988b09f) - updated Post model [`3895370`](https://github.com/yanslist/yanslist/commit/3895370109c838b4d269184c41ef2580cf8c1c50) - added region, district, township repo files [`eca35c4`](https://github.com/yanslist/yanslist/commit/eca35c4bc5fdb34fa4ace36acfd05e83512b02c4) - working on home page [`39202cf`](https://github.com/yanslist/yanslist/commit/39202cf88a885f833f25ab4739ebac08e9f3716c) - added relationships to Post and Township [`0d08835`](https://github.com/yanslist/yanslist/commit/0d088353bdbfcfeefc8af1c187a328e3a379e349) - updated files for inertia setup [`c4a9a9d`](https://github.com/yanslist/yanslist/commit/c4a9a9d59028c1a4b8ceb4c6c1e8f1ca8d966f78) - installed laravel ui and inertia [`27bbf8e`](https://github.com/yanslist/yanslist/commit/27bbf8e9160b4921148d60fedd26e2a2d5da3c51) - installed ziggy [`303672f`](https://github.com/yanslist/yanslist/commit/303672fdb1d0079c4229cf39f036ddc0d324ca4e) - minor update to layout [`0a721b9`](https://github.com/yanslist/yanslist/commit/0a721b9e87ba8127ecf4189e2bf5006759afdfa7) - added laravel-vue-translation package [`c788747`](https://github.com/yanslist/yanslist/commit/c788747f43e2be5aab7cb0b5d31e26e9f082e9e1) - added language switcher links [`f1ce227`](https://github.com/yanslist/yanslist/commit/f1ce2271082f7135d0230f5abdf60ba89ed9c4b9) - added all regions api with townships [`5e6e90d`](https://github.com/yanslist/yanslist/commit/5e6e90d9399ca3d6ddf723250af7022ee9acd212) - made region and township dynamic dropdown [`ddd9f67`](https://github.com/yanslist/yanslist/commit/ddd9f67462aab1cdc3337d019d0e75912be37296) - created post seeder [`ce92371`](https://github.com/yanslist/yanslist/commit/ce92371c97a750d2ff3e7363d1b536153cfecf0b) - showed posts on home page [`dd7c9a2`](https://github.com/yanslist/yanslist/commit/dd7c9a20e044109d192870352a796360c066e590) - added favicon files [`a79a3b4`](https://github.com/yanslist/yanslist/commit/a79a3b4cc5fbb4f311b09c91c920b0987298b893) - home page post filter [`24b6d2f`](https://github.com/yanslist/yanslist/commit/24b6d2f9a39e7a9be2650a358e792d82797152fc) - added new post form UI [`5fe77c5`](https://github.com/yanslist/yanslist/commit/5fe77c5b5a070d71418d9bc49cc3a8316109a02b) - wip showing single post [`1f5650b`](https://github.com/yanslist/yanslist/commit/1f5650b35b3d9de96760ad5b81a5921ef26288ad) - showed single post in modal [`59aad39`](https://github.com/yanslist/yanslist/commit/59aad3948f180538d57cc2b1f030f78cca997dc5) - added recaptcha and noti [`7812ddc`](https://github.com/yanslist/yanslist/commit/7812ddc9a820def2639afd2ae264bf7bdc44247b) - added changelog [`bc73957`](https://github.com/yanslist/yanslist/commit/bc73957f7c44886431405d4a9fb0b71441cb17d3)
775da1e971dff7f877ce0945559430eac4a7bfc5
[ "JavaScript", "Markdown", "PHP" ]
39
PHP
mrlinnth/yanslist
ae072aa9884e0cbf6a71ced6ea26fb3d4a678bcc
f5ab8a2a5b6fdf0915174a453911020751f9d0fc
refs/heads/master
<repo_name>imykshenov/schools<file_sep>/models/Student.php <?php /** * Класс Student - модель для работы со школьниками */ class Student { // Возвращает список школьников // Используется во view'e, в котором просматривается подробная информация о школе // SchoolController public static function getStudentsList($categoryID = false) { if($categoryID) { $db= Db::getConnection(); $studentsList = array(); $result = $db->query("SELECT * FROM students " . "WHERE id_school='$categoryID' " . "ORDER BY id ASC "); $i=0; while($row = $result->fetch()) { $studentsList[$i]['id'] = $row['id']; $studentsList[$i]['fio'] = $row['fio']; $studentsList[$i]['birthday'] = $row['birthday']; $studentsList[$i]['class'] = $row['class']; $studentsList[$i]['exams'] = $row['exams']; $studentsList[$i]['university'] = $row['university']; $studentsList[$i]['number'] = $row['number']; $studentsList[$i]['parents'] = $row['parents']; $studentsList[$i]['parents_number'] = $row['parents_number']; $studentsList[$i]['email'] = $row['email']; //$studentsList[$i]['fio_math'] = $row['fio_math']; //$studentsList[$i]['fio_inf'] = $row['fio_inf']; $i++; } return $studentsList; } } /** * Возвращает список школ, будем использовать этот метод в AdminStudentController * @return array <p>Массив с школьниками</p> */ //вроде как работает, можно уже не трогать public static function getStudentList() { // Соединение с БД $db= Db::getConnection(); //Текст запроса к БД $result = $db->query('SELECT * FROM students ORDER BY id ASC'); $studentsList = array(); $i=0; // Получение и возврат результатов while($row = $result->fetch()) { $studentsList[$i]['id'] = $row['id']; $studentsList[$i]['fio'] = $row['fio']; $studentsList[$i]['birthday'] = $row['birthday']; $studentsList[$i]['class'] = $row['class']; $studentsList[$i]['exams'] = $row['exams']; $studentsList[$i]['university'] = $row['university']; $studentsList[$i]['number'] = $row['number']; $studentsList[$i]['parents'] = $row['parents']; $studentsList[$i]['parents_number'] = $row['parents_number']; $studentsList[$i]['email'] = $row['email']; $studentsList[$i]['id_school'] = $row['id_school']; //$studentsList[$i]['fio_math'] = $row['fio_math']; //$studentsList[$i]['fio_inf'] = $row['fio_inf']; $i++; } return $studentsList; } /** * Возвращает ученика с указанным id * @param integer $id <p>id ученика</p> * @return array <p>Массив с информацией о ученика</p> */ public static function GetStudentById($id) { // Соединение с БД $db = Db::getConnection();// связь с бд // Текст запроса к БД $sql = 'SELECT * FROM students WHERE id=:id'; // Используется подготовленный запрос $result = $db->prepare($sql); $result->bindParam(':id', $id, PDO::PARAM_INT); // Указываем, что хотим получить данные в виде массива $result->setFetchMode(PDO::FETCH_ASSOC); // Выполнение коменды $result->execute(); return $result->fetch(); } /** * Добавляет школьника в БД * @param array $options <p>Массив с информацией о школьнике</p> * @return integer <p>id добавленной в таблицу записи</p> */ public static function createStudent($options) { // Соединение с БД $db = Db::getConnection(); // Текст запроса к БД $sql = 'INSERT INTO students ' . '(fio, birthday, class, exams, university, number, parents, parents_number, email, id_school)' . 'VALUES ' . '(:fio, :birthday, :class, :exams, :university, :number, :parents, :parents_number, :email, :id_school)'; // Получение и возврат результатов. Используется подготовленный запрос $result = $db->prepare($sql); $result->bindParam(':fio', $options['fio'], PDO::PARAM_STR); $result->bindParam(':birthday', $options['birthday'], PDO::PARAM_STR); $result->bindParam(':class', $options['class'], PDO::PARAM_STR); $result->bindParam(':exams', $options['exams'], PDO::PARAM_STR); $result->bindParam(':university', $options['university'], PDO::PARAM_STR); $result->bindParam(':number', $options['number'], PDO::PARAM_STR); $result->bindParam(':parents', $options['parents'], PDO::PARAM_STR); $result->bindParam(':parents_number', $options['parents_number'], PDO::PARAM_STR); $result->bindParam(':email', $options['email'], PDO::PARAM_STR); $result->bindParam(':id_school', $options['id_school'], PDO::PARAM_STR); return $result->execute(); if ($result->execute()) { // Если запрос выполенен успешно, возвращаем id добавленной записи return $db->lastInsertId(); } // Иначе возвращаем 0 return 0; } /** * Редактирует школьника с заданным id * @param integer $id <p>id школьника</p> * @param array $options <p>Массив с информацей о школе</p> * @return boolean <p>Результат выполнения метода</p> */ public static function updateStudentById($id, $options) { // Соединение с БД $db = Db::getConnection(); // Текст запроса к БД $sql = "UPDATE students SET fio = :fio, birthday = :birthday, class = :class, exams = :exams, university = :university, number = :number, parents = :parents, parents_number = :parents_number, email = :email, id_school = :id_school WHERE id = :id"; // Получение и возврат результатов. Используется подготовленный запрос $result = $db->prepare($sql); $result->bindParam(':id', $id, PDO::PARAM_INT); $result->bindParam(':fio', $options['fio'], PDO::PARAM_STR); $result->bindParam(':birthday', $options['birthday'], PDO::PARAM_STR); $result->bindParam(':class', $options['class'], PDO::PARAM_STR); $result->bindParam(':exams', $options['exams'], PDO::PARAM_STR); $result->bindParam(':university', $options['university'], PDO::PARAM_STR); $result->bindParam(':number', $options['number'], PDO::PARAM_STR); $result->bindParam(':parents', $options['parents'], PDO::PARAM_STR); $result->bindParam(':parents_number', $options['parents_number'], PDO::PARAM_STR); $result->bindParam(':email', $options['email'], PDO::PARAM_STR); $result->bindParam(':id_school', $options['id_school'], PDO::PARAM_INT); return $result->execute(); } /** * Удаляет информацию о школьнике с указанным id * @param integer $id <p>id школьника</p> * @return boolean <p>Результат выполнения метода</p> */ public static function deleteStudentById($id) { // Соединение с БД $db = Db::getConnection(); // Текст запроса к БД $sql = 'DELETE FROM students WHERE id = :id'; // Получение и возврат результатов. Используется подготовленный запрос $result = $db->prepare($sql); $result->bindParam(':id', $id, PDO::PARAM_INT); return $result->execute(); } }<file_sep>/controllers/SiteController.php <?php class SiteController { public function actionIndex() { $categories = array(); $categories = Category::getCategoriesList(); $schoolList = array(); $schoolList = School::getLatestSchoolList(6); require_once(ROOT.'/views/site/index.php'); return true; } }<file_sep>/controllers/AdminStudentController.php <?php /** * Контроллер AdminSstudentController * Управление школьниками в админпанели */ class AdminStudentController extends AdminBase { /** * Action для страницы "Управление школьниками" */ public function actionIndex() { // Проверка доступа self::checkAdmin(); // Получаем список школьников $studentList = Student::getStudentList(); // Подключаем вид require_once(ROOT . '/views/admin_student/index.php'); return true; } /** * Action для страницы "Добавить школьника" */ public function actionCreate() { // Проверка доступа self::checkAdmin(); // Получаем список школ для выпадающего списка $schoolList = School::getSchoolList(); // Обработка формы if (isset($_POST['submit'])) { // Если форма отправлена // Получаем данные из формы $options['fio'] = $_POST['fio']; $options['birthday'] = $_POST['birthday']; $options['exams'] = $_POST['exams']; $options['class'] = $_POST['class']; $options['university'] = $_POST['university']; $options['number'] = $_POST['number']; $options['parents'] = $_POST['parents']; $options['parents_number'] = $_POST['parents_number']; $options['email'] = $_POST['email']; $options['id_school'] = $_POST['id_school']; // Флаг ошибок в форме $errors = false; // При необходимости можно валидировать значения нужным образом if (!isset($options['fio']) || empty($options['fio'])) { $errors[] = 'Заполните поля'; } if ($errors == false) { // Если ошибок нет // Добавляем новую школу $id = Student::createStudent($options); // Перенаправляем пользователя на страницу управлениями товарами header("Location: /admin/student"); } } // Подключаем вид require_once(ROOT . '/views/admin_student/create.php'); return true; } /** * Action для страницы "Редактировать информацию о школьнике" */ public function actionUpdate($id) { // Проверка доступа self::checkAdmin(); // Получаем список школ для выпадающего списка $schoolList = School::getSchoolList(); // Получаем данные о конкретном школьнике $student = Student::GetStudentById($id); // Обработка формы if (isset($_POST['submit'])) { // Если форма отправлена // Получаем данные из формы редактирования. При необходимости можно валидировать значения $options['fio'] = $_POST['fio']; $options['birthday'] = $_POST['birthday']; $options['class'] = $_POST['class']; $options['exams'] = $_POST['exams']; $options['university'] = $_POST['university']; $options['number'] = $_POST['number']; $options['parents'] = $_POST['parents']; $options['parents_number'] = $_POST['parents_number']; $options['email'] = $_POST['email']; $options['id_school'] = $_POST['id_school']; // Сохраняем изменения if (Student::updateStudentById($id, $options)) { // Если запись сохранена // Проверим, загружалось ли через форму изображение } // Перенаправляем пользователя на страницу управлениями header("Location: /admin/student"); } // Подключаем вид require_once(ROOT . '/views/admin_student/update.php'); return true; } /** * Action для страницы "Удалить школьника из БД" */ public function actionDelete($id) { // Проверка доступа self::checkAdmin(); // Обработка формы if (isset($_POST['submit'])) { // Если форма отправлена // Удаляем информацию о школьнике Student::deleteStudentById($id); // Перенаправляем пользователя на страницу управлениями товарами header("Location: /admin/student"); } // Подключаем вид require_once(ROOT . '/views/admin_student/delete.php'); return true; } } <file_sep>/controllers/AdminSchoolController.php <?php /** * Контроллер AdminSchoolController * Управление товарами в админпанели */ class AdminSchoolController extends AdminBase { /** * Action для страницы "Управление школами" */ public function actionIndex() { // Проверка доступа self::checkAdmin(); // Получаем список школ $schoolList = School::getSchoolList(); // Подключаем вид require_once(ROOT . '/views/admin_school/index.php'); return true; } /** * Action для страницы "Добавить школу" */ public function actionCreate() { // Проверка доступа self::checkAdmin(); // Получаем список районов для выпадающего списка $categoriesList = Category::getCategoriesListAdmin(); // Обработка формы if (isset($_POST['submit'])) { // Если форма отправлена // Получаем данные из формы $options['school_name'] = $_POST['school_name']; $options['school_district'] = $_POST['school_district']; $options['school_place'] = $_POST['school_place']; $options['school_contact'] = $_POST['school_contact']; $options['school_site'] = $_POST['school_site']; $options['school_email'] = $_POST['school_email']; $options['school_director'] = $_POST['school_director']; $options['school_fio_math'] = $_POST['school_fio_math']; $options['school_fio_math_number'] = $_POST['school_fio_math_number']; $options['school_fio_inf'] = $_POST['school_fio_inf']; $options['school_fio_inf_number'] = $_POST['school_fio_inf_number']; $options['school_fio_phys'] = $_POST['school_fio_phys']; $options['school_fio_phys_number'] = $_POST['school_fio_phys_number']; // Флаг ошибок в форме $errors = false; // При необходимости можно валидировать значения нужным образом if (!isset($options['school_name']) || empty($options['school_name'])) { $errors[] = 'Заполните поля'; } if ($errors == false) { // Если ошибок нет // Добавляем новую школу $id = School::createSchool($options); // Перенаправляем пользователя на страницу управлениями школами header("Location: /admin/school"); } } // Подключаем вид require_once(ROOT . '/views/admin_school/create.php'); return true; } /** * Action для страницы "Редактировать школу" */ public function actionUpdate($id) { // Проверка доступа self::checkAdmin(); // Получаем список районов для выпадающего списка $categoriesList = Category::getCategoriesListAdmin(); // Получаем данные о конкретной школе $school = School::getSchoolById($id); // Обработка формы if (isset($_POST['submit'])) { // Если форма отправлена // Получаем данные из формы редактирования. При необходимости можно валидировать значения $options['school_name'] = $_POST['school_name']; $options['school_district'] = $_POST['school_district']; $options['school_place'] = $_POST['school_place']; $options['school_contact'] = $_POST['school_contact']; $options['school_site'] = $_POST['school_site']; $options['school_email'] = $_POST['school_email']; $options['school_director'] = $_POST['school_director']; $options['school_fio_math'] = $_POST['school_fio_math']; $options['school_fio_math_number'] = $_POST['school_fio_math_number']; $options['school_fio_inf'] = $_POST['school_fio_inf']; $options['school_fio_inf_number'] = $_POST['school_fio_inf_number']; $options['school_fio_phys'] = $_POST['school_fio_phys']; $options['school_fio_phys_number'] = $_POST['school_fio_phys_number']; // Сохраняем изменения if (School::updateSchoolById($id, $options)) { // Если запись сохранена // Проверим, загружалось ли через форму изображение } // Перенаправляем пользователя на страницу управлениями школами header("Location: /admin/school"); } // Подключаем вид require_once(ROOT . '/views/admin_school/update.php'); return true; } /** * Action для страницы "Удалить школу" */ public function actionDelete($id) { // Проверка доступа self::checkAdmin(); // Обработка формы if (isset($_POST['submit'])) { // Если форма отправлена // Удаляем школу School::deleteSchoolById($id); // Перенаправляем пользователя на страницу управлениями товарами header("Location: /admin/school"); } // Подключаем вид require_once(ROOT . '/views/admin_school/delete.php'); return true; } } <file_sep>/views/catalog/catalog.php <? include ROOT.('/views/layouts/header.php');?> <section> <div class="container"> <div class="row"> <div class="col-sm-3"> <div class="left-sidebar"> <h2>Районы</h2> <div class="panel-group category-products"> <? foreach ($categories as $categoryItem): ?> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a href="/category/<?echo $categoryItem['district_id']?>"> <?echo $categoryItem['district_name']?> </a></h4> </div> </div> <?endforeach;?> </div> </div> </div> <div class="col-sm-9 padding-right"> <div class="features_items"><!--features_items--> <h2 class="title text-center">Школы</h2> <?php foreach($schoolList as $school):?> <div class="col-sm-4"> <div class="product-image-wrapper"> <div class="single-products"> <div class="productinfo text-center"> <img src="<? echo $school['preview'];?>" alt="" /> <!-- <p><?echo $school['school_name']?></p> --> <p> <a href="/school/<?echo $school['school_id']?>"</a> <?echo $school['school_name']?> </p> </div> </div> </div> </div> <?endforeach;?> </div><!--features_items--> </div> </div> </div> </section> <? include ROOT.('/views/layouts/footer.php');?><file_sep>/README.md # schools Попросили сделать такой сайт, с помощью которого можно отслеживать какие школьники какие экзамены сдают, чтобы в дальнейшем приемная комиссия вуза могла лично приглашать абитуриентов. Требует дальнейшей доработки, однако заказчику хватило и этого <file_sep>/views/admin_school/update.php <?php include ROOT . '/views/layouts/header_admin.php'; ?> <section> <div class="container"> <div class="row"> <br/> <div class="breadcrumbs"> <ol class="breadcrumb"> <li><a href="/admin">Админпанель</a></li> <li><a href="/admin/product">Управление школами</a></li> <li class="active">Редактировать школу</li> </ol> </div> <h4>Редактировать информацию о школе #<?php echo $id; ?></h4> <br/> <div class="col-lg-4"> <div class="login-form"> <form action="#" method="post" enctype="multipart/form-data"> <p>Название школы</p> <input type="text" name="school_name" placeholder="" value="<?php echo $school['school_name']; ?>"> <p>Район</p> <select name="school_district"> <?php if (is_array($categoriesList)): ?> <?php foreach ($categoriesList as $category): ?> <option value="<?php echo $category['district_id']; ?>" <?php if ($school['school_district'] == $category['district_id']) echo ' selected="selected"'; ?>> <?php echo $category['district_name']; ?> </option> <?php endforeach; ?> <?php endif; ?> </select> <p>Полный адрес</p> <input type="text" name="school_place" placeholder="" value="<?php echo $school['school_place']; ?>"> <p>Контакты</p> <input type="text" name="school_contact" placeholder="" value="<?php echo $school['school_contact']; ?>"> <p>Сайт школы(если есть)</p> <input type="text" name="school_site" placeholder="" value="<?php echo $school['school_site']; ?>"> <p>email</p> <input type="text" name="school_email" placeholder="" value="<?php echo $school['school_email']; ?>"> <p>Директор</p> <input type="text" name="school_director" placeholder="" value="<?php echo $school['school_director']; ?>"> <p>ФИО учителя математики</p> <input type="text" name="school_fio_math" placeholder="" value="<?php echo $school['school_fio_math']; ?>"> <p>Телефон учителя математики</p> <input type="text" name="school_fio_math_number" placeholder="" value="<?php echo $school['school_fio_math_number']; ?>"> <p>ФИО учителя информатики</p> <input type="text" name="school_fio_inf" placeholder="" value="<?php echo $school['school_fio_inf']; ?>"> <p>Телефон учителя информатики</p> <input type="text" name="school_fio_inf_number" placeholder="" value="<?php echo $school['school_fio_inf_number']; ?>"> <p>ФИО учителя физики</p> <input type="text" name="school_fio_phys" placeholder="" value="<?php echo $school['school_fio_phys']; ?>"> <p>Телефон учителя физики</p> <input type="text" name="school_fio_phys_number" placeholder="" value="<?php echo $school['school_fio_phys_number']; ?>"> <br/><br/> <input type="submit" name="submit" class="btn btn-default" value="Сохранить"> <br/><br/> </form> </div> </div> </div> </div> </section> <?php include ROOT . '/views/layouts/footer_admin.php'; ?> <file_sep>/models/School.php <?php /** * Класс School - модель для работы со школами */ class School { // Количество отображаемых школ по умолчанию const SHOW_BY_DEFAULT = 6; /** * Возвращает массив последних школ * @param type $count [optional] <p>Количество</p> * @param type $page [optional] <p>Номер текущей страницы</p> * @return array <p>Массив со школами</p> */ public static function getLatestSchoolList($count = self::SHOW_BY_DEFAULT) { // Соединение с БД $db = Db::getConnection(); // Текст запроса к БД $sql = 'SELECT school_id, school_name, school_place, school_contact, school_site, school_director ' . 'FROM schools_tb ' . 'ORDER BY school_id DESC ' . 'LIMIT 10 '; // Используется подготовленный запрос $result = $db->prepare($sql); $result->bindParam(':count', $count, PDO::PARAM_INT); // Указываем, что хотим получить данные в виде массива $result->setFetchMode(PDO::PARAM_INT); // Выполнение коменды $result->execute(); $i=0; $schoolList = array(); // Получение и возврат результатов while($row = $result->fetch()){ $schoolList[$i]['school_id'] = $row['school_id']; $schoolList[$i]['school_name'] = $row['school_name']; $schoolList[$i]['school_place'] = $row['school_place']; $schoolList[$i]['school_contact'] = $row['school_contact']; $schoolList[$i]['school_site'] = $row['school_site']; $schoolList[$i]['school_director'] = $row['school_director']; $i++; } return $schoolList; } /** * Возвращает список школ в указанной категории(районе) * @param type $categoryId <p>id категории</p> * @param type $page [optional] <p>Номер страницы</p> * @return type <p>Массив со школами</p> */ public static function getSchoolsListByCategory($categoryID = false, $page = 1) { $limit = School::SHOW_BY_DEFAULT; // Смещение (для запроса) $offset = ($page - 1) * self::SHOW_BY_DEFAULT; $db = Db::getConnection();// связь с бд // Текст запроса к БД $sql = 'SELECT school_id, school_name, school_place, school_contact, school_site, school_director ' . 'FROM schools_tb ' . 'WHERE school_district = :school_district ' . 'ORDER BY school_id ASC ' . 'LIMIT :limit ' . 'OFFSET :offset'; // Используется подготовленный запрос $result = $db->prepare($sql); $result-> bindParam(':school_district', $categoryID, PDO::PARAM_INT); $result-> bindParam(':limit', $limit, PDO::PARAM_INT); $result-> bindParam(':offset', $offset, PDO::PARAM_INT); // Выполнение коменды $result->execute(); $i=0; $schools = array(); // Получение и возврат результатов while($row = $result->fetch()) { $schools[$i]['school_id'] = $row['school_id']; $schools[$i]['school_name'] = $row['school_name']; $schools[$i]['school_place'] = $row['school_place']; $schools[$i]['school_contact'] = $row['school_contact']; $schools[$i]['school_site'] = $row['school_site']; $schools[$i]['school_director'] = $row['school_director']; $i++; } return $schools; } /** * Возвращает список школ с указанными индентификторами * @param array $idsArray <p>Массив с идентификаторами</p> * @return array <p>Массив со списком школ</p> */ public static function getSchoolsByIds($idsArray) { // Соединение с БД $db = Db::getConnection(); // Превращаем массив в строку для формирования условия в запросе $idsString = implode(',', $idsArray); // Текст запроса к БД $sql = "SELECT * FROM schools_tb WHERE _school_id IN ($idsString)"; $result = $db->query($sql); // Указываем, что хотим получить данные в виде массива $result->setFetchMode(PDO::FETCH_ASSOC); // Получение и возврат результатов $i = 0; $products = array(); while ($row = $result->fetch()) { $products[$i]['school_id'] = $row['school_id']; $products[$i]['school_name'] = $row['school_name']; $products[$i]['school_place'] = $row['school_place']; $products[$i]['school_contact'] = $row['school_contact']; $i++; } return $products; } /** * Возвращает школу с указанным id * @param integer $id <p>id школы</p> * @return array <p>Массив с информацией о школе</p> */ public static function GetSchoolById($id) { // Соединение с БД $db = Db::getConnection();// связь с бд // Текст запроса к БД $sql = 'SELECT * FROM schools_tb WHERE school_id=:id'; // Используется подготовленный запрос $result = $db->prepare($sql); $result->bindParam(':id', $id, PDO::PARAM_INT); // Указываем, что хотим получить данные в виде массива $result->setFetchMode(PDO::FETCH_ASSOC); // Выполнение коменды $result->execute(); return $result->fetch(); } /** * Возвращаем количество школ в указанной категории * @param integer $categoryId * @return integer */ public static function getTotalSchoolsInCategory($categoryID) { // Соединение с БД $db = Db::getConnection(); // Текст запроса к БД $sql = 'SELECT count(school_id) AS count FROM schools_tb WHERE school_district =:school_district'; // Используется подготовленный запрос $result = $db->prepare($sql); $result->bindParam(':school_district', $categoryID, PDO::PARAM_INT); // Выполнение коменды $result->execute(); // Возвращаем значение count - количество $row = $result->fetch(); return $row['count']; } /** * Возвращает список школ * Данный метод используется в админпанели * @return array <p>Массив с товарами</p> */ public static function getSchoolList() { // Соединение с БД $db = Db::getConnection(); // Текст запроса к БД $result = $db->query('SELECT * FROM schools_tb ORDER BY school_id ASC '); $schoolList = array(); $i=0; // Получение и возврат результатов while($row = $result->fetch()){ $schoolList[$i]['school_id'] = $row['school_id']; $schoolList[$i]['school_name'] = $row['school_name']; $schoolList[$i]['school_place'] = $row['school_place']; $schoolList[$i]['school_contact'] = $row['school_contact']; $schoolList[$i]['school_site'] = $row['school_site']; $schoolList[$i]['school_email'] = $row['school_email']; $schoolList[$i]['school_director'] = $row['school_director']; $schoolList[$i]['school_fio_math'] = $row['school_fio_math']; $schoolList[$i]['school_fio_math_number'] = $row['school_fio_math_number']; $schoolList[$i]['school_fio_inf'] = $row['school_fio_inf']; $schoolList[$i]['school_fio_inf_number'] = $row['school_fio_inf_number']; $schoolList[$i]['school_fio_phys'] = $row['school_fio_phys']; $schoolList[$i]['school_fio_phys_number'] = $row['school_fio_phys_number']; $i++; } return $schoolList; } /** * Добавляет новую школу * @param array $options <p>Массив с информацией о школке</p> * @return integer <p>id добавленной в таблицу записи</p> */ public static function createSchool($options) { // Соединение с БД $db = Db::getConnection(); // Текст запроса к БД $sql = 'INSERT INTO schools_tb ' . '(school_name, school_district, school_place, school_contact, school_site, school_email, school_director, school_fio_math, school_fio_math_number, school_fio_inf, school_fio_inf_number, school_fio_phys, school_fio_phys_number)' . 'VALUES ' . '(:school_name, :school_district, :school_place, :school_contact, :school_site, :school_email, :school_director, :school_fio_math, :school_fio_math_number, :school_fio_inf, :school_fio_inf_number, :school_fio_phys, :school_fio_phys_number)'; // Получение и возврат результатов. Используется подготовленный запрос $result = $db->prepare($sql); $result->bindParam(':school_name', $options['school_name'], PDO::PARAM_STR); $result->bindParam(':school_district', $options['school_district'], PDO::PARAM_STR); $result->bindParam(':school_place', $options['school_place'], PDO::PARAM_STR); $result->bindParam(':school_contact', $options['school_contact'], PDO::PARAM_STR); $result->bindParam(':school_site', $options['school_site'], PDO::PARAM_INT); $result->bindParam(':school_email', $options['school_email'], PDO::PARAM_INT); $result->bindParam(':school_director', $options['school_director'], PDO::PARAM_INT); $result->bindParam(':school_fio_math', $options['school_fio_math'], PDO::PARAM_STR); $result->bindParam(':school_fio_math_number', $options['school_fio_math_number'], PDO::PARAM_STR); $result->bindParam(':school_fio_inf', $options['school_fio_inf'], PDO::PARAM_STR); $result->bindParam(':school_fio_inf_number', $options['school_fio_inf_number'], PDO::PARAM_STR); $result->bindParam(':school_fio_phys', $options['school_fio_phys'], PDO::PARAM_STR); $result->bindParam(':school_fio_phys_number', $options['school_fio_phys_number'], PDO::PARAM_INT); return $result->execute(); if ($result->execute()) { // Если запрос выполенен успешно, возвращаем id добавленной записи return $db->lastInsertId(); } // Иначе возвращаем 0 return 0; } /** * Редактирует школу с заданным id * @param integer $id <p>id товара</p> * @param array $options <p>Массив с информацей о школе</p> * @return boolean <p>Результат выполнения метода</p> */ public static function updateSchoolById($id, $options) { // Соединение с БД $db = Db::getConnection(); // Текст запроса к БД $sql = "UPDATE schools_tb SET school_name = :school_name, school_district = :school_district, school_place = :school_place, school_contact = :school_contact, school_site = :school_site, school_email = :school_email, school_director = :school_director, school_fio_math = :school_fio_math, school_fio_math_number = :school_fio_math_number, school_fio_inf = :school_fio_inf, school_fio_inf_number = :school_fio_inf_number, school_fio_phys = :school_fio_phys, school_fio_phys_number = :school_fio_phys_number WHERE school_id = :school_id"; // Получение и возврат результатов. Используется подготовленный запрос $result = $db->prepare($sql); $result->bindParam(':school_id', $id, PDO::PARAM_INT); $result->bindParam(':school_name', $options['school_name'], PDO::PARAM_STR); $result->bindParam(':school_district', $options['school_district'], PDO::PARAM_STR); $result->bindParam(':school_place', $options['school_place'], PDO::PARAM_STR); $result->bindParam(':school_contact', $options['school_contact'], PDO::PARAM_STR); $result->bindParam(':school_site', $options['school_site'], PDO::PARAM_INT); $result->bindParam(':school_email', $options['school_email'], PDO::PARAM_INT); $result->bindParam(':school_director', $options['school_director'], PDO::PARAM_INT); $result->bindParam(':school_fio_math', $options['school_fio_math'], PDO::PARAM_STR); $result->bindParam(':school_fio_math_number', $options['school_fio_math_number'], PDO::PARAM_STR); $result->bindParam(':school_fio_inf', $options['school_fio_inf'], PDO::PARAM_STR); $result->bindParam(':school_fio_inf_number', $options['school_fio_inf_number'], PDO::PARAM_STR); $result->bindParam(':school_fio_phys', $options['school_fio_phys'], PDO::PARAM_STR); $result->bindParam(':school_fio_phys_number', $options['school_fio_phys_number'], PDO::PARAM_INT); return $result->execute(); } /** * Удаляет товар с указанным id * @param integer $id <p>id товара</p> * @return boolean <p>Результат выполнения метода</p> */ public static function deleteSchoolById($id) { // Соединение с БД $db = Db::getConnection(); // Текст запроса к БД $sql = 'DELETE FROM schools_tb WHERE school_id = :id'; // Получение и возврат результатов. Используется подготовленный запрос $result = $db->prepare($sql); $result->bindParam(':id', $id, PDO::PARAM_INT); return $result->execute(); } }<file_sep>/views/admin_student/update.php <?php include ROOT . '/views/layouts/header_admin.php'; ?> <section> <div class="container"> <div class="row"> <br/> <div class="breadcrumbs"> <ol class="breadcrumb"> <li><a href="/admin">Админпанель</a></li> <li><a href="/admin/student">Управление учениками</a></li> <li class="active">Редактировать информацию о ученике</li> </ol> </div> <h4>Редактировать информацию о ученике #<?php echo $id; ?></h4> <br/> <div class="col-lg-4"> <div class="login-form"> <form action="#" method="post" enctype="multipart/form-data"> <p>ФИО</p> <input type="text" name="fio" placeholder="" value="<?php echo $student['fio']; ?>"> <p>День рождения</p> <input type="text" name="birthday" placeholder="" value="<?php echo $student['birthday']; ?>"> <p>Класс</p> <input type="text" name="class" placeholder="" value="<?php echo $student['class']; ?>"> <p>Экзамены</p> <input type="text" name="exams" placeholder="" value="<?php echo $student['exams']; ?>"> <p>Вузы</p> <input type="text" name="university" placeholder="" value="<?php echo $student['university']; ?>"> <p>Номер телефона</p> <input type="text" name="number" placeholder="" value="<?php echo $student['number']; ?>"> <p>Родители</p> <input type="text" name="parents" placeholder="" value="<?php echo $student['parents']; ?>"> <p>Телефон родителей</p> <input type="text" name="parents_number" placeholder="" value="<?php echo $student['parents_number']; ?>"> <p>email</p> <input type="text" name="email" placeholder="" value="<?php echo $student['email']; ?>"> <p>Школа</p> <select name="id_school"> <?php if (is_array($schoolList)): ?> <?php foreach ($schoolList as $schoolitem): ?> <option value="<?php echo $schoolitem['school_id']; ?>" <?php if ($student['id_school'] == $schoolitem['school_id']) echo ' selected="selected"'; ?>> <?php echo $schoolitem['school_name']; ?> </option> <?php endforeach; ?> <?php endif; ?> </select> <br/><br/> <input type="submit" name="submit" class="btn btn-default" value="Сохранить"> <br/><br/> </form> </div> </div> </div> </div> </section> <?php include ROOT . '/views/layouts/footer_admin.php'; ?> <file_sep>/views/admin_student/create.php <?php include ROOT . '/views/layouts/header_admin.php'; ?> <section> <div class="container"> <div class="row"> <br/> <div class="breadcrumbs"> <ol class="breadcrumb"> <li><a href="/admin">Админпанель</a></li> <li><a href="/admin/student">Управление учениками</a></li> <li class="active">Редактировать ученика</li> </ol> </div> <h4>Добавить нового ученика</h4> <br/> <?php if (isset($errors) && is_array($errors)): ?> <ul> <?php foreach ($errors as $error): ?> <li> - <?php echo $error; ?></li> <?php endforeach; ?> </ul> <?php endif; ?> <div class="col-lg-4"> <div class="login-form"> <form action="#" method="post" enctype="multipart/form-data"> <p>ФИО</p> <input type="text" name="fio" placeholder="" value=""> <p>День рождения</p> <input type="text" name="birthday" placeholder="" value=""> <p>Класс</p> <input type="text" name="class" placeholder="" value=""> <p>Экзамены</p> <input type="text" name="exams" placeholder="" value=""> <p>Вузы(в порядке приоритета)</p> <input type="text" name="university" placeholder="" value=""> <p>Номер телефона</p> <input type="text" name="number" placeholder="" value=""> <p>Родители</p> <input type="text" name="parents" placeholder="" value=""> <p>Телефон родителей</p> <input type="text" name="parents_number" placeholder="" value=""> <p>email</p> <input type="text" name="email" placeholder="" value=""> <p>Школа</p> <select name="id_school"> <?php if (is_array($schoolList)): ?> <?php foreach ($schoolList as $school): ?> <option value="<?php echo $school['school_id']; ?>"> <?php echo $school['school_name']; ?> </option> <?php endforeach; ?> <?php endif; ?> </select> <br/><br/> <input type="submit" name="submit" class="btn btn-default" value="Сохранить"> <br/><br/> </form> </div> </div> </div> </div> </section> <?php include ROOT . '/views/layouts/footer_admin.php'; ?> <file_sep>/models/Category.php <?php /** * Класс Category - модель для работы с категориями(районами) школ */ class Category { /** * Возвращает массив категорий для списка на сайте * @return array <p>Массив с категориями</p> */ public static function getCategoriesList() { $db= Db::getConnection();// Соединение с БД $categoryList = array(); $result = $db->query('SELECT * FROM district ORDER BY district_id ASC');// Запрос к БД $i=0; while($row = $result->fetch())// Получение и возврат результатов { $categoryList[$i]['district_id'] = $row['district_id']; $categoryList[$i]['district_name'] = $row['district_name']; $i++; } return $categoryList; } /** * Возвращает массив категорий для списка в админпанели <br/> * (при этом в результат попадают и включенные и выключенные категории) * @return array <p>Массив категорий</p> */ public static function getCategoriesListAdmin() { // Соединение с БД $db = Db::getConnection(); // Запрос к БД $result = $db->query('SELECT district_id, district_name FROM district ORDER BY district_id ASC'); // Получение и возврат результатов $categoryList = array(); $i = 0; while ($row = $result->fetch()) { $categoryList[$i]['district_id'] = $row['district_id']; $categoryList[$i]['district_name'] = $row['district_name']; $i++; } return $categoryList; } public static function getCategoryById($id) { // Соединение с БД $db = Db::getConnection(); // Текст запроса к БД $sql = 'SELECT * FROM district WHERE district_id = :id'; // Используется подготовленный запрос $result = $db->prepare($sql); $result->bindParam(':id', $id, PDO::PARAM_INT); // Указываем, что хотим получить данные в виде массива $result->setFetchMode(PDO::FETCH_ASSOC); // Выполняем запрос $result->execute(); // Возвращаем данные return $result->fetch(); } /** * Возвращает текстое пояснение статуса для категории :<br/> * <i>0 - Скрыта, 1 - Отображается</i> * @param integer $status <p>Статус</p> * @return string <p>Текстовое пояснение</p> */ public static function getStatusText($status) { switch ($status) { case '1': return 'Отображается'; break; case '0': return 'Скрыта'; break; } } /** * Добавляет новую категорию (на самом деле ненужная функция, т.к. районы статичны, но по стандарту CRUD должно быть) * @param string $name <p>Название района</p> * @return boolean <p>Результат добавления записи в таблицу</p> */ public static function createCategory($name) { // Соединение с БД $db = Db::getConnection(); // Текст запроса к БД $sql = 'INSERT INTO district (district_name) ' . 'VALUES (:name)'; // Получение и возврат результатов. Используется подготовленный запрос $result = $db->prepare($sql); $result->bindParam(':name', $name, PDO::PARAM_STR); return $result->execute(); } /** * Удаляет категорию с заданным id * @param integer $id * @return boolean <p>Результат выполнения метода</p> */ public static function deleteCategoryById($id) { // Соединение с БД $db = Db::getConnection(); // Текст запроса к БД $sql = 'DELETE FROM district WHERE district_id = :id'; // Получение и возврат результатов. Используется подготовленный запрос $result = $db->prepare($sql); $result->bindParam(':id', $id, PDO::PARAM_INT); return $result->execute(); } /** * Редактирование категории с заданным id * @param integer $id <p>id категории</p> * @param string $name <p>Название</p> * @return boolean <p>Результат выполнения метода</p> */ public static function updateCategoryById($id, $name) { // Соединение с БД $db = Db::getConnection(); // Текст запроса к БД $sql = "UPDATE district SET district_name = :name, WHERE district_id = :id"; // Получение и возврат результатов. Используется подготовленный запрос $result = $db->prepare($sql); $result->bindParam(':id', $id, PDO::PARAM_INT); $result->bindParam(':name', $name, PDO::PARAM_STR); return $result->execute(); } }<file_sep>/controllers/SchoolController.php <?php class SchoolController { public function actionView($id) { $categories = array(); // создаем переменную $categories = Category::getCategoriesList(); // передаем переменной метод(функцию) из класса categorylist $schools = School::GetSchoolById($id);// это присваивание нужно для того чтобы //вывести страницу отдельно, в данном случаем массив не нужен, т.к. запись одна $students = array(); $students = Student::getStudentsList($id); require_once(ROOT . '/views/school/view.php'); return true; } }<file_sep>/views/admin_school/index.php <?php include ROOT . '/views/layouts/header_admin.php'; ?> <section> <div class="container"> <div class="row"> <br/> <div class="breadcrumbs"> <ol class="breadcrumb"> <li><a href="/admin">Админпанель</a></li> <li class="active">Управление школами</li> </ol> </div> <a href="/admin/school/create" class="btn btn-default back"><i class="fa fa-plus"></i> Добавить школу</a> <h4>Список школ</h4> <br/> <table class="table-bordered table-striped table"> <tr> <th>ID школы</th> <th>Название</th> <th>Местоположение</th> <th>Контакты</th> <th>Сайт</th> <th>Электронный адрес школы</th> <th>Директор</th> <th>Фио учителя математики </th> <th>Номер телефона</th> <th>Фио учителя информатики</th> <th>Номер телефона</th> <th>Фио учителя физики</th> <th>Номер телефона</th> <th></th> <th></th> </tr> <?php foreach ($schoolList as $school): ?> <tr> <td><?php echo $school['school_id']; ?></td> <td><?php echo $school['school_name']; ?></td> <td><?php echo $school['school_place']; ?></td> <td><?php echo $school['school_contact']; ?></td> <td><?php echo $school['school_site']; ?></td> <td><?php echo $school['school_email']; ?></td> <td><?php echo $school['school_director']; ?></td> <td><?php echo $school['school_fio_math']; ?></td> <td><?php echo $school['school_fio_math_number']; ?></td> <td><?php echo $school['school_fio_inf']; ?></td> <td><?php echo $school['school_fio_inf_number']; ?></td> <td><?php echo $school['school_fio_phys']; ?></td> <td><?php echo $school['school_fio_phys_number']; ?></td> <td><a href="/admin/school/update/<?php echo $school['school_id']; ?>" title="Редактировать"><i class="fa fa-pencil-square-o"></i></a></td> <td><a href="/admin/school/delete/<?php echo $school['school_id']; ?>" title="Удалить"><i class="fa fa-times"></i></a></td> </tr> <?php endforeach; ?> </table> </div> </div> </section> <?php include ROOT . '/views/layouts/footer_admin.php'; ?> <file_sep>/views/admin_school/create.php <?php include ROOT . '/views/layouts/header_admin.php'; ?> <section> <div class="container"> <div class="row"> <br/> <div class="breadcrumbs"> <ol class="breadcrumb"> <li><a href="/admin">Админпанель</a></li> <li><a href="/admin/school">Управление школами</a></li> <li class="active">Редактировать школу</li> </ol> </div> <h4>Добавить новую школу</h4> <br/> <?php if (isset($errors) && is_array($errors)): ?> <ul> <?php foreach ($errors as $error): ?> <li> - <?php echo $error; ?></li> <?php endforeach; ?> </ul> <?php endif; ?> <div class="col-lg-4"> <div class="login-form"> <form action="#" method="post" enctype="multipart/form-data"> <p>Название школы</p> <input type="text" name="school_name" placeholder="" value=""> <p>Район</p> <select name="school_district"> <?php if (is_array($categoriesList)): ?> <?php foreach ($categoriesList as $category): ?> <option value="<?php echo $category['district_id']; ?>"> <?php echo $category['district_name']; ?> </option> <?php endforeach; ?> <?php endif; ?> </select> <p>Полный адрес(индекс, регион, район, нас пункт, улица, номер дома)</p> <input type="text" name="school_place" placeholder="" value=""> <p>Контакты</p> <input type="text" name="school_contact" placeholder="" value=""> <p>Сайт школы(если есть)</p> <input type="text" name="school_site" placeholder="" value=""> <p>email</p> <input type="text" name="school_email" placeholder="" value=""> <p>Директор</p> <input type="text" name="school_director" placeholder="" value=""> <p>ФИО учителя математики</p> <input type="text" name="school_fio_math" placeholder="" value=""> <p>Номер телефона учителя математики</p> <input type="text" name="school_fio_math_number" placeholder="" value=""> <p>ФИО учителя информатики</p> <input type="text" name="school_fio_inf" placeholder="" value=""> <p>Номер телефона учителя информатики</p> <input type="text" name="school_fio_inf_number" placeholder="" value=""> <p>ФИО учителя физики</p> <input type="text" name="school_fio_phys" placeholder="" value=""> <p>Номер телефона учителя физики</p> <input type="text" name="school_fio_phys_number" placeholder="" value=""> <br/><br/> <input type="submit" name="submit" class="btn btn-default" value="Сохранить"> <br/><br/> </form> </div> </div> </div> </div> </section> <?php include ROOT . '/views/layouts/footer_admin.php'; ?> <file_sep>/views/admin_student/index.php <?php include ROOT . '/views/layouts/header_admin.php'; ?> <section> <div class="container"> <div class="row"> <br/> <div class="breadcrumbs"> <ol class="breadcrumb"> <li><a href="/admin">Админпанель</a></li> <li class="active">Управление школьниками</li> </ol> </div> <a href="/admin/student/create" class="btn btn-default back"><i class="fa fa-plus"></i> Добавить ученика</a> <h4>Список учеников</h4> <br/> <table class="table-bordered table-striped table"> <tr> <th>№</th> <!--столбец 1--> <th>ФИО</th> <!--столбец 2--> <th>Дата рождения</th> <!--столбец 3--> <th>Класс</th> <!--столбец 4--> <th>Экзамены</th> <!--столбец 5--> <th>Вузы(в порядке приоритета)</th> <!--столбец 6--> <th>Номер телефона</th> <!--столбец 7--> <th>Родители</th> <!--столбец 8--> <th>Телефон родителей</th> <!--столбец 9--> <th>email</th> <!--столбец 10--> <th>id школы</th> <!--столбец 10--> <th></th> <th></th> </tr> <?php foreach ($studentList as $student): ?> <tr> <td><?php echo $student['id']; ?></td> <td><?php echo $student['fio']; ?></td> <td><?php echo $student['birthday']; ?></td> <td><?php echo $student['exams']; ?></td> <td><?php echo $student['class']; ?></td> <td><?php echo $student['university']; ?></td> <td><?php echo $student['number']; ?></td> <td><?php echo $student['parents']; ?></td> <td><?php echo $student['parents_number']; ?></td> <td><?php echo $student['email']; ?></td> <td><?php echo $student['id_school']; ?></td> <td><a href="/admin/student/update/<?php echo $student['id']; ?>" title="Редактировать"><i class="fa fa-pencil-square-o"></i></a></td> <td><a href="/admin/student/delete/<?php echo $student['id']; ?>" title="Удалить"><i class="fa fa-times"></i></a></td> </tr> <?php endforeach; ?> </table> </div> </div> </section> <?php include ROOT . '/views/layouts/footer_admin.php'; ?> <file_sep>/views/school/view.php <? include ROOT.('/views/layouts/header.php');?> <section> <div class="container"> <div class="row"> <div class="col-sm-3"> <div class="left-sidebar"> <h2>Районы</h2> <div class="panel-group category-products"> <? foreach ($categories as $categoryItem): ?> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a href="/category/<?echo $categoryItem['district_id']?>"> <?echo $categoryItem['district_name']?> </a></h4> </div> </div> <?endforeach;?> </div> </div> </div> <div class="col-sm-9 padding-right"> <div class="product-details"><!--product-details--> <div class="row"> <div class="col-sm-7"> <div class="product-information"><!--/product-information--> <h2><?php echo $schools['school_name'];?></h2> <p><?echo $schools['school_site']; ?></p> </div><!--/гавно----> </div> </div> <div class="row"> <div class="col-sm-12"> <h5>Описание</h5> <p>Директор: <? echo $schools['school_director'];?></p> <p>Контакты: <? echo $schools['school_contact'];?></p> </div> </div> <!--Отображение учителей школы --> <div class="row"> <div class="col-sm-12"> <?php if (isset($_SESSION['user'])) {?> <!--проверяет авторизован пользователь или нет --> <h5>Учителя</h5> <table class="bordered"> <thead> <tr> <th>Учитель информатики</th> <!--столбец 1--> <th>Номер телефона</th> <!--столбец 2--> <th>Учитель математики</th> <!--столбец 3--> <th>Номер телефона</th> <!--столбец 4--> <th>Учитель физики</th> <!--столбец 5--> <th>Номер телефона</th> <!--столбец 6--> </tr> </thead> <tr> <th><? echo $schools['school_fio_math'];?></th> <!--столбец 1--> <th><? echo $schools['school_fio_math_number'];?></th> <!--столбец 2--> <th><? echo $schools['school_fio_inf'];?></th> <!--столбец 3--> <th><? echo $schools['school_fio_inf_number'];?></th> <!--столбец 4--> <th><? echo $schools['school_fio_phys'];?></th> <!--столбец 5--> <th><? echo $schools['school_fio_phys_number'];?></th> <!--столбец 6--> </tr> </table> <?} else { ?> <h5>Информация о учителях доступна только зарегестрированным пользователям</h5> <?}?> </div> </div> <!--Отображение данных о школьниках --> <div class="row"> <div class="col-sm-12"> <?php if (isset($_SESSION['user'])) {?> <!--проверяет авторизован пользователь или нет --> <h5>Школьники</h5> <table class="bordered"> <thead> <tr> <th>№</th> <!--столбец 1--> <th>ФИО</th> <!--столбец 2--> <th>Дата рождения</th> <!--столбец 3--> <th>Класс</th> <!--столбец 4--> <th>Экзамены</th> <!--столбец 5--> <th>Вузы(в порядке приоритета)</th> <!--столбец 1--> <th>Номер телефона</th> <!--столбец 2--> <th>Родители</th> <!--столбец 3--> <th>Телефон родителей</th> <!--столбец 4--> <th>email</th> <!--столбец 5--> </tr> </thead> <?php foreach($students as $studentsList):?> <tr> <th><? echo $studentsList['id'];?></th> <!--столбец 1--> <th><? echo $studentsList['fio'];?></th> <!--столбец 2--> <th><? echo $studentsList['birthday'];?></th> <!--столбец 3--> <th><? echo $studentsList['class'];?></th> <!--столбец 4--> <th><? echo $studentsList['exams'];?></th> <!--столбец 5--> <th><? echo $studentsList['university'];?></th> <!--столбец 1--> <th><? echo $studentsList['number'];?></th> <!--столбец 2--> <th><? echo $studentsList['parents'];?></th> <!--столбец 3--> <th><? echo $studentsList['parents_number'];?></th> <!--столбец 4--> <th><? echo $studentsList['email'];?></th> <!--столбец 5--> </tr> <?endforeach;?> </table> <?} else { ?> <h5>Информация об учащихся доступна только зарегестрированным пользователям</h5> <?}?> </div> </div> </div><!--/product-details--> </div> </div> </div> </section> <br/> <br/> <? include ROOT.('/views/layouts/footer.php');?><file_sep>/config/routes.php <?php return array( // просмотр школы 'school/([0-9]+)'=>'school/view/$1', //каталог 'catalog'=>'catalog/index', //категории 'category/([0-9]+)/page-([0-9]+)'=>'catalog/category/$1/$2', 'category/([0-9]+)' => 'catalog/category/$1', //Пользователь 'user/register'=>'user/register', 'user/login'=>'user/login', 'user/logout' => 'user/logout', 'cabinet/edit' => 'cabinet/edit', 'cabinet'=>'cabinet/index', //Управление // Управление школами: 'admin/school/create' => 'adminSchool/create', 'admin/school/update/([0-9]+)' => 'adminSchool/update/$1', 'admin/school/delete/([0-9]+)' => 'adminSchool/delete/$1', 'admin/school' => 'adminSchool/index', // Управление школьниками: 'admin/student/create' => 'adminStudent/create', 'admin/student/update/([0-9]+)' => 'adminStudent/update/$1', 'admin/student/delete/([0-9]+)' => 'adminStudent/delete/$1', 'admin/student' => 'adminStudent/index', //Админпанель 'admin'=>'admin/index', //О магазине 'contacts'=>'site/contacts', 'about'=>'site/about', //адрес на главную ''=>'site/index' );
3f4fc07606b3fb311e5930d4441f8c557b7e9f29
[ "Markdown", "PHP" ]
17
PHP
imykshenov/schools
e8143eb0c5bcc8a7dd33e844aaa220a64f3226cb
8c80c5590a08158f41f75615efbaac363458f604
refs/heads/master
<file_sep>api.lesson_meta_url=http://localhost:5000/api/lesson-meta api.course_meta_url=http://localhost:5000/api/course-meta<file_sep>plugins { id 'java' id 'groovy' id 'application' } mainClassName = 'Main' group 'com.enderstudy' version '1.0-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { testCompile group: 'junit', name: 'junit', version: '4.12' compile 'com.google.apis:google-api-services-youtube:v3-rev212-1.25.0' compile 'com.google.http-client:google-http-client-jackson2:1.20.0' compile 'com.google.oauth-client:google-oauth-client-jetty:1.20.0' compile 'com.google.collections:google-collections:1.0' compile 'org.apache.httpcomponents:httpclient:4.5.9' } <file_sep>import com.google.api.services.youtube.model.Playlist; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class PlaylistSynchroniser { private String url; public PlaylistSynchroniser() throws IOException { InputStream input = this.getClass().getResourceAsStream("application.properties"); Properties props = new Properties(); if (input == null) { System.err.println("Unable to load application.properties!"); return; } props.load(input); url = props.getProperty("api.course_meta_url"); } public boolean synchronise(Playlist playlist) { String json = playlist.toString(); HttpRequestSender requestSender = new HttpRequestSender(); if (!requestSender.sendPostRequest(json, url)) { System.err.println("Sync attempt failed for playlist: " + playlist.getId()); return false; } else { System.out.println("Sync attempt successful for playlist: " + playlist.getId()); return true; } } } <file_sep>import com.google.api.services.youtube.model.PlaylistItem; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class PlaylistItemSynchroniser { private String url; public PlaylistItemSynchroniser() throws IOException { InputStream input = this.getClass().getResourceAsStream("application.properties"); Properties props = new Properties(); if (input == null) { System.err.println("Unable to load application.properties!"); return; } props.load(input); url = props.getProperty("api.lesson_meta_url"); } public boolean synchronise(PlaylistItem playlistItem, String playlistId) { String json = playlistItem.toString(); String idJson = ",\"playlistId\": \"" + playlistId + "\"}"; String newJson = ""; for (int i = 0; i < json.length(); i++) { newJson += json.charAt(i); if (i == json.length() - 2) { newJson += idJson; } } HttpRequestSender requestSender = new HttpRequestSender(); if (!requestSender.sendPostRequest(newJson, url)) { System.err.println("Sync attempt failed for playlist items!"); return false; } else { System.out.println("Sync attempt successful for playlist items"); return true; } } } <file_sep>import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import java.io.IOException; public class HttpRequestSender { /** * Sends a HTTP Request. Return type is boolean since we're not interested * in anything the API sends back, we only need to know if it was successful or not. * * @param data - The JSON serialised data to be sent to the API * @return boolean */ public boolean sendPostRequest(String data, String url) { HttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost(url); StringEntity requestEntity = new StringEntity(data, ContentType.APPLICATION_JSON); request.addHeader("Content-Type", "application/json"); request.setEntity(requestEntity); try { HttpResponse response = client.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200 && statusCode != 201) { System.err.println("HTTP status code: " + statusCode); System.err.println(response.getStatusLine().getReasonPhrase()); return false; } } catch (IOException e) { e.printStackTrace(); return false; } return true; } }
48256f6c397d309aae836193c5d4d4446188147e
[ "Java", "INI", "Gradle" ]
5
INI
enderstudy/Youtube-Microservice
6ced7917ad34e21489b6c601f52568aa97ab775e
d513eb94959c9cbd3be96ef0f9052d753425346a
refs/heads/master
<file_sep>import cv2 import numpy as np from keras.models import load_model from keras import backend as K from keras.models import Model import matplotlib.pyplot as plt # install from image_preprocess import * # input shape width, height, depth = 100, 100, 3 def get_class_and_confidence(img, model): # test_data = np.empty((1, width*height*3)) if depth == 1: img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) try: img = cv2.resize(img, (width, height)) except: print('resize error!') return -1, -1 img_ndarray = np.asarray(img, dtype='float64') / 255 test_data = np.ndarray.flatten(img_ndarray) test_data = test_data.astype('float32') if K.image_data_format() == 'channels_first': test_data = test_data.reshape(1, depth, height, width) else: test_data = test_data.reshape(1, height, width, depth) predict = model.predict(test_data) class_ = np.argmax(predict, axis=1) confidence = float(predict[0][class_]) confidence = '%.3f' % (confidence * 100) return class_, confidence def get_intermediate_output(model, layer_name, img): """Get the output of intermediate layer. Args: model: keras model. layer_name: name of layer in the model. img: processed input image. Returns: intermediate_output: feature map. """ try: # this is the placeholder for the intermediate output out_intermediate = model.get_layer(layer_name).output except: raise Exception('Not layer named {}!'.format(layer_name)) # get the intermediate layer model intermediate_layer_model = Model( inputs=model.input, outputs=out_intermediate) # get the output of intermediate layer model intermediate_output = intermediate_layer_model.predict(img) return intermediate_output[0] def show_intermediate_output(model, layer_name, image): if depth == 1: image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) image = cv2.resize(image, (width, height)) img_ndarray = np.asarray(image, dtype='float64') / 255 test_data = np.ndarray.flatten(img_ndarray) test_data = test_data.astype('float32') if K.image_data_format() == 'channels_first': test_data = test_data.reshape(1, depth, height, width) else: test_data = test_data.reshape(1, height, width, depth) output = get_intermediate_output(model, layer_name, test_data) n = output.shape[-1] # 特征图中特征个数 size = output.shape[1] display_grid = np.zeros((size * 1, n * size)) for i in range(n): channel_image = output[:, :, i] display_grid[0:size, i * size:(i + 1) * size] = channel_image # plt.figure() # plt.title(layer_name) # plt.grid(False) # plt.imshow(display_grid, cmap='viridis') # plt.savefig('visualize/'+layer_name+'_output.jpg') # 保存中间层输出图 # plt.show() # must show after imshow def show_heatmap(model, layer_name, image): img = image.copy() if depth == 1: image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) image = cv2.resize(image, (width, height)) img_ndarray = np.asarray(image, dtype='float64') / 255 test_data = np.ndarray.flatten(img_ndarray) test_data = test_data.astype('float32') if K.image_data_format() == 'channels_first': test_data = test_data.reshape(1, depth, height, width) else: test_data = test_data.reshape(1, height, width, depth) preds = model.predict(test_data) index = np.argmax(preds[0]) # index of output class output = model.output[:, index] layer = model.get_layer(layer_name) # intermediate layer grads = K.gradients(output, layer.output)[0] pooled_grads = K.mean(grads, axis=(0, 1, 2)) iterate = K.function([model.input], [pooled_grads, layer.output[0]]) pooled_grads_value, layer_output_value = iterate([test_data]) for i in range(layer_output_value.shape[-1]): layer_output_value[:, :, i ] *= pooled_grads_value[i] heatmap = np.mean(layer_output_value, axis=-1) # heatmap = np.maximum(heatmap, 0) # heatmap /= np.max(heatmap) plt.matshow(heatmap) plt.savefig('visualization/heatmap.jpg') plt.show() # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) heatmap = cv2.resize(heatmap, (img.shape[1], img.shape[0])) heatmap = np.uint8(255 * heatmap) # convert to rgb heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET) # heatmap apply to raw image superimposed_img = heatmap * 0.4 + img # heatmap intensity factor - 0.4 cv2.imwrite('visualization/heatmap_apply.jpg', superimposed_img) def main(): model = load_model('model.h5') model.summary() # image = cv2.imread('test.jpg') # show_intermediate_output(model, 'conv1', image) # show_intermediate_output(model, 'maxpooling1', image) # show_intermediate_output(model, 'conv2', image) # show_intermediate_output(model, 'maxpooling2', image) image = cv2.imread('test.jpg') show_heatmap(model, 'conv1', image) if __name__ == "__main__": main() <file_sep># @Author: Ivan # @LastEdit: 2020/9/25 import os import random import cv2 # install import numpy as np # install def load_img_from_folder(root, nb_classes, nb_per_class, width, height, depth, train_proportion, valid_proportion, test_proportion, shuffle=True, rescale=True, normalize=True): """function of loading image dataset from folder. * image dataset's root folder must contain each class's children class folder. example: folder 'dataset' contains 'dog' and 'cat' folder. each children class folder has corresponding images,'dog' folder has 'dog1.jpg','dog2.jpg'. root/dog/1.png root/dog/2.png root/dog/3.png ... root/cat/1.png root/cat/2.png root/cat/3.png * file path name and image name better be named by english. Args: root: image dataset's root path nb_classes: number of image classes nb_per_class: number of each class's image width: width of output image height: height of output image depth: depth of image,1 for gray,3 for clolr train_proportion: the proportion of train dataset valid_proportion: the proportion of valid dataset test_proportion: the proportion of test dataset normalize: images whether need normalized Returns: rval: (train_data, train_label): train data and label (valid_data, valid_label): valid data and label (test_data, test_label): test data and label """ train_per_class = int(train_proportion * nb_per_class) valid_per_class = int(valid_proportion * nb_per_class) test_per_class = int(test_proportion * nb_per_class) train_number = train_per_class * nb_classes # number of train set valid_number = valid_per_class * nb_classes # number of valid set test_number = test_per_class * nb_classes # number of test set classes = [] # images classes list dataset = [] # dataset list,including image and label sequences print('Image classes:') img_classes = os.listdir(root) for c, img_class in enumerate(img_classes): # stop loading dataset when class number is enough if c == nb_classes: break img_class_path = os.path.join(root, img_class) # skip if not folder if not os.path.isdir(img_class_path): continue print(img_class) classes.append(img_class) imgs = os.listdir(img_class_path) for img in imgs: # stop loading dataset when image number of each class is enough if len(dataset) == (c+1)*nb_per_class: break img_path = os.path.join(img_class_path, img) # read image if depth == 3: image = cv2.imdecode(np.fromfile( img_path, dtype=np.uint8), cv2.IMREAD_COLOR) # chinese path color elif depth == 1: image = cv2.imdecode(np.fromfile( img_path, dtype=np.uint8), cv2.cv2.IMREAD_GRAYSCALE) # chinese path gray # scaling and filtering try: # default interpolation = cv2.INTER_LINEAR - Bilinear Interpolation image = cv2.resize(image, (width, height)) if rescale: image = cv2.medianBlur(image, 3) # filtering except: print(img_path, 'failed to resize!') # os.remove(img_path) # print(img_path+' has been deleted!') continue if normalize: image_ndarray = np.asarray(image, dtype='float64') / 255 else: image_ndarray = np.asarray(image, dtype='float64') # add single data(including data and label) to dataset array dataset.append([np.ndarray.flatten(image_ndarray), c]) # image not enough if len(dataset) < (c+1)*nb_per_class: print(img_class, 'Image number insufficient!') raise Exception('Image number insufficient!') # shuffle the whole dataset if shuffle: random.shuffle(dataset) # construct data set and label set train_data = [data[0] for data in dataset[:train_number]] train_label = [data[1] for data in dataset[:train_number]] train_data = np.array(train_data, dtype='float32') train_label = np.array(train_label, dtype='uint8') valid_data = [data[0] for data in dataset[train_number:train_number + valid_number]] valid_label = [data[1] for data in dataset[train_number:train_number + valid_number]] valid_data = np.array(valid_data, dtype='float32') valid_label = np.array(valid_label, dtype='uint8') test_data = [data[0] for data in dataset[train_number + valid_number:]] test_label = [data[1] for data in dataset[train_number + valid_number:]] test_data = np.array(test_data, dtype='float32') test_label = np.array(test_label, dtype='uint8') # write all classes into 'classes.txt' file with open('./cfg/classes.cfg', 'w', encoding='utf-8') as f: for idx, class_ in enumerate(classes): if idx+1 == len(classes): f.write(class_ + ' ' + str(idx)) else: f.write(class_ + ' ' + str(idx) + '\n') rval = [(train_data, train_label), (valid_data, valid_label), (test_data, test_label)] return rval def img_normalize(path, width, height, gray=True): """function of normalizing images. * resize images and convert to gray. * image dataset folder must contain each class's children class folder. example: folder 'vehicle' contains 'car','train' and 'bicycle' folder,each children class folder has corresponding images,'car' folder has 'car1.jpg','car2.jpg'. * file path name and image name better be named by english. * when detecting faces,'aarcascade_frontalface_default.xml' shoud be included. Args: path: images path width: width of output image height: height of output image gray: whether need convert to gray,default need """ img_classes = os.listdir(path) for img_class in img_classes: img_class_path = os.path.join(path, img_class) if os.path.isdir(img_class_path): imgs = os.listdir(img_class_path) for img in imgs: img_path = os.path.join(img_class_path, img) image = cv2.imread(img_path) # resize try: image = cv2.resize(image, (width, height), interpolation=cv2.INTER_CUBIC) except: print(img_path + ' failed to resize!') os.remove(img_path) print(img_path + ' has been deleted!') continue # convert to gray if gray: image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # rewrite image cv2.imwrite(img_path, image) print(img_path, 'normalized successfully!') print('All images normalized successfully!') def img_rename(path): """function of renaming and sorting images. * traversal folder,rename all images. example: 'xxx.jpg','xxx.jpg' -> '1.jpg','2.jpg' Args: path: images path """ classes = os.listdir(path) for class_ in classes: number = 1 class_path = os.path.join(path, class_) imgs = os.listdir(class_path) for img in imgs: img_path = os.path.join(class_path, img) new_img_path = os.path.join(class_path, str(number) + '.jpg') os.rename(img_path, new_img_path) print(img_path + '--->' + new_img_path) number = number + 1 print('All images renamed successfully!') def main(): pass if __name__ == '__main__': main() <file_sep># @Author: Ivan # @LastEdit: 2020/9/25 import os import argparse import cv2 # install from PIL import Image, ImageDraw, ImageFont # install from keras.models import load_model from keras import backend as K import numpy as np # install # input shape width, height, depth = 100, 100, 3 def load_keras_model(path): return load_model(path) def load_classes(path): classes = {} with open(path, 'r', encoding='utf-8') as f: lines = f.readlines() for line in lines: line = line.strip('\n').split(' ') class_, idx = line[0], line[1] classes[int(idx)] = class_ return classes def load_prices(path): prices = {} with open(path, 'r', encoding='utf-8') as f: lines = f.readlines() for line in lines: line = line.strip('\n').split(' ') class_, price = line[0], line[1] prices[class_] = price return prices def predict_img(img, model): """get model prediction of one image Args: img: image ndarray model: keras trained model Returns: preds: keras model predictions """ if depth == 1: img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) try: img = cv2.resize(img, (width, height)) except: print('Img resize error!') raise Exception('Resize error!') img_ndarray = np.asarray(img, dtype='float64') / 255 test_data = np.ndarray.flatten(img_ndarray) test_data = test_data.astype('float32') if K.image_data_format() == 'channels_first': test_data = test_data.reshape(1, depth, height, width) else: test_data = test_data.reshape(1, height, width, depth) preds = model.predict(test_data) return preds def predict_class_idx_and_confidence(img, model): """predict image class and confidence according to trained model Args: img: image to predict model: keras model Returns: class_idx: class index confidence: class confidence """ # call base prediction function preds = predict_img(img, model) class_idx = np.argmax(preds[0]) confidence = float(preds[0][class_idx]) # confidence percentage,save three decimal places confidence = '%.2f' % (confidence * 100) return class_idx, confidence classes = load_classes('cfg/classes.cfg') def predict_class_name_and_confidence(img, model): """predict image class and confidence according to trained model Args: img: image to predict model: keras model Returns: class_idx: class index confidence: class confidence """ class_idx, confidence = predict_class_idx_and_confidence(img, model) class_name = classes[int(class_idx)] return class_name, confidence def predict_and_show_one_img(img, model): """get model output of one image Args: img: image ndarray model: keras trained model Returns: class_name: class name confidence: class confidence """ class_name, confidence = predict_class_name_and_confidence(img, model) img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) draw = ImageDraw.Draw(img) font_text = ImageFont.truetype("simsum.ttc", 26, encoding="utf-8") draw.text((5, 5), class_name + ' ' + str(confidence) + '%', (0, 255, 0), font=font_text) img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR) # cv2.namedWindow('img', 0) # cv2.resizeWindow('img',window_width,window_height) cv2.imshow('img', img) cv2.waitKey(0) cv2.destroyAllWindows() return class_name, confidence def arg_parse(): """ Parse arguements to the detect module """ parser = argparse.ArgumentParser(description='Food Recognition System') parser.add_argument("--image", "-i", dest='image', help="Path of image to perform detection upon", type=str) parser.add_argument("--video", "-v", dest='video', help="Path of video to run detection upon", type=str) parser.add_argument("--model", "-m", dest='model', help="Path of network model", default="model.h5", type=str) return parser.parse_args() if __name__ == "__main__": args = arg_parse() image_path = args.image video_path = args.video model_path = args.model model = load_keras_model(model_path) print('Model successfully loaded...') if image_path: # img = cv2.imread(image_path) # predict_and_show_one_img(img,model) img = cv2.imread(image_path) class_name, confidence = predict_class_name_and_confidence(img, model) print('Class name:', class_name, 'Confidence:', str(confidence)+'%') elif video_path: cap = cv2.VideoCapture(video_path) while cap.isOpened(): ret, frame = cap.read() if not ret: break class_name, confidence = predict_class_name_and_confidence( frame, model) img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) draw = ImageDraw.Draw(img) font_text = ImageFont.truetype("simsun.ttc", 26, encoding="utf-8") draw.text((5, 5), class_name + ' ' + str(confidence)+'%', (0, 255, 0), font=font_text) frame = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR) print('Class name:', class_name, 'Confidence:', str(confidence)+'%') cv2.resizeWindow('frame', (int(cap.get(3)), int(cap.get(4)))) cv2.imshow("frame", frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() <file_sep># @Author: Ivan # @LastEdit: 2020/9/25 import sys import cv2 # install import numpy as np # install from PIL import Image, ImageDraw, ImageFont # install from PyQt5.QtWidgets import QWidget, QPushButton, QApplication, QLabel, QMainWindow # install from PyQt5.QtGui import QPixmap, QImage, QFont from PyQt5.QtCore import Qt, QTimer from detect import predict_class_idx_and_confidence, predict_class_name_and_confidence from detect import load_keras_model, load_classes, load_prices # camera shape # cam_width, cam_height = 800, 600 cam_width, cam_height = 848, 480 # window shape window_width, window_height = 1600, 1200 class MyWindow(QMainWindow): """ customized Qt window """ def __init__(self): super().__init__() self.setGeometry(500, 300, cam_width, cam_height + 150) self.setFixedSize(cam_width, cam_height + 150) self.setWindowTitle('Food Recogintion System') self.img_label = QLabel(self) self.img_label.setGeometry(0, 0, cam_width, cam_height) self.dish_label = QLabel(self) self.dish_label.move(50, cam_height + 25) self.dish_label.resize(450, 35) self.dish_label.setText("菜品名称:") self.dish_label.setFont(QFont("Roman times", 16, QFont.Bold)) self.price_label = QLabel(self) self.price_label.move(50, cam_height + 70) self.price_label.resize(450, 35) self.price_label.setText("金额:") self.price_label.setFont(QFont("Roman times", 16, QFont.Bold)) self.frame = None self.isChecking = False check_button = QPushButton("结算", self) check_button.move(500, cam_height + 50) check_button.resize(130, 40) check_button.clicked.connect(self.check) confirm_button = QPushButton("确定", self) confirm_button.move(650, cam_height + 50) confirm_button.resize(130, 40) confirm_button.clicked.connect(self.confirm) # Ok Button self.model = load_keras_model('model.h5') self.prices = load_prices('cfg/prices.cfg') # camera init self.cap = cv2.VideoCapture(0) self.cap.set(3, cam_width) self.cap.set(4, cam_height) self._timer = QTimer(self) self._timer.timeout.connect(self.update_frame) self._timer.start(33) # 30fps # self.setCentralWidget(self.img_label) self.show() def update_frame(self): # get camera frame and convert to pixmap to show on img label if self.isChecking: return ret, self.frame = self.cap.read() # read camera frame print('frame shape:', self.frame.shape) frame = cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB) h, w = frame.shape[:2] img = QImage(frame, w, h, QImage.Format_RGB888) img = QPixmap.fromImage(img) self.img_label.setPixmap(img) # show on img label self.img_label.setScaledContents(True) # self adaption def check(self): # check function, draw class name,confidence and price on the image if self.isChecking: return frame = self.frame class_name, confidence = predict_class_name_and_confidence( frame, self.model) img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) img = Image.fromarray(img) draw = ImageDraw.Draw(img) font_text = ImageFont.truetype("simsun.ttc", 26, encoding="utf-8") draw.text((5, 5), class_name + ' ' + str(confidence) + '%', (0, 255, 0), font=font_text) img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) print('Class name:', class_name, 'Confidence:', str(confidence)+'%') h, w = img.shape[:2] img = QImage(img, w, h, QImage.Format_RGB888) img = QPixmap.fromImage(img) self.img_label.setPixmap(img) # show on img label self.img_label.setScaledContents(True) # self adaption self.isChecking = True self.dish_label.setText("菜品名称:" + class_name) self.price_label.setText("金额:" + self.prices[class_name] + "元") def confirm(self): self.isChecking = False self.dish_label.setText("菜品名称:") self.price_label.setText("金额:") def cv_loop(): # loop get camera frame and show on window model = load_keras_model('model.h5') cap = cv2.VideoCapture(0) cap.set(3, cam_width) cap.set(4, cam_height) # main loop while True: ret, frame = cap.read() if not ret: break print('frame shape:', frame.shape) class_name, confidence = predict_class_name_and_confidence( frame, model) img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) draw = ImageDraw.Draw(img) font_text = ImageFont.truetype("simsun.ttc", 26, encoding="utf-8") draw.text((5, 5), class_name + ' ' + str(confidence) + '%', (0, 255, 0), font=font_text) frame = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR) # cv2.putText(frame, category_name+' %'+str(confidence), (0,70), cv2.FONT_HERSHEY_COMPLEX, 3, (0, 255, 0), 6) print('Class name:', class_name, 'Confidence:', str(confidence)+'%') cv2.namedWindow('frame', 0) cv2.resizeWindow('frame', (int(cap.get(3)), int(cap.get(4)))) cv2.imshow('frame', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() def main(): # cv_loop() # only when qt not downloaded app = QApplication(sys.argv) window = MyWindow() sys.exit(app.exec_()) if __name__ == '__main__': main() <file_sep># @Author: Ivan # @LastEdit: 2020/9/25 import os import time import cv2 # install import numpy as np # install import keras # install from keras.regularizers import l2 from keras import backend as K from keras.utils import np_utils from keras.utils import plot_model from keras.optimizers import SGD from keras.models import Sequential from keras.models import load_model from keras.layers import MaxPooling2D, SeparableConv2D from keras.layers import Dense, Dropout, Activation, Flatten import matplotlib.pyplot as plt # install from preprocess import load_img_from_folder from image_util import show_intermediate_output, show_heatmap from detect import load_classes np.random.seed(1337) os.environ["PATH"] += os.pathsep + \ 'D:/Graphviz2.38/bin' # add graphviz to environment variable,for plotting network's structure path = './dataset' # root path of dataset epochs = 800 # number of training nb_classes = 5 # number of class nb_per_class = 200 # number of each class batch_size = 64 learning_rate = 0.001 activation = 'relu' width, height, depth = 100, 100, 3 nb_filters1, nb_filters2 = 5, 10 # number of conv kernel(output dimension) train_proportion = 0.8 # proportion of train set valid_proportion = 0.1 # proportion of valid set test_proportion = 0.1 # proportion of test set def set_model(lr=learning_rate, decay=1e-6, momentum=0.9): model = Sequential() if K.image_data_format() == 'channels_first': model.add(SeparableConv2D(nb_filters1, kernel_size=(3, 3), kernel_regularizer=l2(0.01), input_shape=(depth, height, width), name='conv1')) else: model.add(SeparableConv2D(nb_filters1, kernel_size=(3, 3), input_shape=(height, width, depth), name='conv1')) model.add(Activation(activation)) model.add(MaxPooling2D(pool_size=(2, 2), name='maxpooling1')) model.add(Dropout(0.5)) model.add(SeparableConv2D(nb_filters2, kernel_size=(3, 3), kernel_regularizer=l2(0.01), name='conv2')) model.add(Activation(activation)) model.add(MaxPooling2D(pool_size=(2, 2), name='maxpooling2')) model.add(Dropout(0.5)) model.add(Flatten()) model.add(Dense(128, kernel_regularizer=l2( 0.01), name='dense1')) # Full connection model.add(Activation(activation)) model.add(Dropout(0.5)) model.add(Dense(nb_classes, name='dense2')) # Output model.add(Activation('softmax')) sgd = SGD(lr=lr, decay=decay, momentum=momentum, nesterov=True) # optimizer model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) model.summary() # output each layer's parameter of the model return model class LossHistory(keras.callbacks.Callback): # record loss history,output parameters' changing def on_train_begin(self, logs={}): self.losses = {'batch': [], 'epoch': []} self.accuracy = {'batch': [], 'epoch': []} self.val_loss = {'batch': [], 'epoch': []} self.val_acc = {'batch': [], 'epoch': []} def on_batch_end(self, batch, logs={}): self.losses['batch'].append(logs.get('loss')) self.accuracy['batch'].append(logs.get('accuracy')) self.val_loss['batch'].append(logs.get('val_loss')) self.val_acc['batch'].append(logs.get('val_accuracy')) def on_epoch_end(self, batch, logs={}): self.losses['epoch'].append(logs.get('loss')) # train loss self.accuracy['epoch'].append(logs.get('accuracy')) # train acc self.val_loss['epoch'].append(logs.get('val_loss')) # val loss self.val_acc['epoch'].append(logs.get('val_accuracy')) # val acc def loss_plot(self, loss_type): iters = range(len(self.losses[loss_type])) plt.figure('Change of accuracy and loss') # train acc plt.plot(iters, self.accuracy[loss_type], 'r', label='train acc') # train loss plt.plot(iters, self.losses[loss_type], 'g', label='train loss') if loss_type == 'epoch': # val_acc plt.plot(iters, self.val_acc[loss_type], 'b', label='val acc') # val_loss plt.plot(iters, self.val_loss[loss_type], 'k', label='val loss') plt.title('epoch:' + str(epochs) + ',lr:' + str(learning_rate) + ',batch_size:' + str(batch_size) + '\nactivation:' + activation + ',nb_classes:' + str(nb_classes) + ',nb_per_class:' + str( nb_per_class)) plt.grid(True) plt.xlabel(loss_type) plt.ylabel('acc-loss') plt.legend(loc="upper right") now = time.strftime('%Y-%m-%d@%H-%M-%S', time.localtime(time.time())) plt.savefig('./parameter/' + now + '.jpg') plt.show() history = LossHistory() def train_model(model, X_train, Y_train, X_val, Y_val): # tensorboard = keras.callbacks.TensorBoard( # log_dir='F:/Log/', histogram_freq=1) model.fit(X_train, Y_train, batch_size=batch_size, epochs=epochs, shuffle=True, verbose=1, validation_data=(X_val, Y_val), callbacks=[history]) model.save('model.h5') return model def test_model(X_test, Y_test): model = load_model('model.h5') score = model.evaluate(X_test, Y_test, verbose=0) return score def main(): (X_train, y_train), (X_val, y_val), (X_test, y_test) = load_img_from_folder(path, nb_classes, nb_per_class, width, height, depth, train_proportion, valid_proportion, test_proportion) # load dataset if K.image_data_format() == 'channels_first': X_train = X_train.reshape(X_train.shape[0], depth, height, width) X_val = X_val.reshape(X_val.shape[0], depth, height, width) X_test = X_test.reshape(X_test.shape[0], depth, height, width) else: X_train = X_train.reshape(X_train.shape[0], height, width, depth) X_val = X_val.reshape(X_val.shape[0], height, width, depth) X_test = X_test.reshape(X_test.shape[0], height, width, depth) print('X_train shape:', X_train.shape) print('Class number:', nb_classes) print(X_train.shape[0], 'train samples') print(X_val.shape[0], 'validate samples') print(X_test.shape[0], 'test samples') # convert class vectors to binary class matrices Y_train = np_utils.to_categorical(y_train, nb_classes) Y_val = np_utils.to_categorical(y_val, nb_classes) Y_test = np_utils.to_categorical(y_test, nb_classes) model = set_model() # load network model plot_model(model, to_file='visualization/model.png', show_shapes=True, expand_nested=True) # save network's structure picture classes = load_classes('./cfg/classes.cfg') start = time.clock() model = train_model(model, X_train, Y_train, X_val, Y_val) # train model end = time.clock() # visualize intermedia layers' output,visualize CAM image = cv2.imread('test.jpg') show_intermediate_output(model, 'conv1', image) image = cv2.imread('test.jpg') show_intermediate_output(model, 'maxpooling1', image) image = cv2.imread('test.jpg') show_intermediate_output(model, 'conv2', image) image = cv2.imread('test.jpg') show_intermediate_output(model, 'maxpooling2', image) image = cv2.imread('test.jpg') show_heatmap(model, 'conv2', image) # last conv layer score = test_model(X_test, Y_test) # evaluate model's score pred_classes = model.predict_classes(X_test, verbose=0) # predict class # test_accuracy = np.mean(np.equal(y_test, pred_classes)) right = np.sum(np.equal(y_test, pred_classes)) for i in range(0, nb_classes * int(test_proportion * nb_per_class)): if y_test[i] != pred_classes[i]: actual_class_name = classes[int(y_test[i % nb_per_class])] pred_class_name = classes[int(pred_classes[i % nb_per_class])] print(actual_class_name, 'was wrongly classified as', pred_class_name) print('Total training time:', end - start) print('Test number:', len(Y_test)) print('Test right:', right) print('Test wrong:', len(Y_test) - right) print('Test loss:', score[0]) print('Test accuracy:', score[1]) history.loss_plot('epoch') # plot parameter changing diagram if __name__ == '__main__': main() <file_sep>tensorflow keras numpy opencv-python pillow matplotlib graphviz pydot pyqt5 h5py<file_sep>from .detect import predict_class_name_and_confidence, predict_class_idx_and_confidence <file_sep># @Author: Ivan # @LastEdit: 2020/9/23 import threading import cv2 # install from keras.models import load_model from keras import backend as K import numpy as np # install from PIL import Image, ImageDraw, ImageFont # install import wx # install from predict import predict_class_name_and_confidence from predict import load_prices width, height, depth = 200, 200, 3 cam_width, cam_height = 800, 600 window_width, window_height = 1600, 1200 def get_class_and_confidence(img, model): if depth == 1: img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # test_data = np.empty((1, width*height*3)) try: img = cv2.resize(img, (width, height)) except: print('resize error!') return -1, -1 # img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) img_ndarray = np.asarray(img, dtype='float64') / 255 test_data = np.ndarray.flatten(img_ndarray) test_data = test_data.astype('float32') if K.image_data_format() == 'channels_first': test_data = test_data.reshape(1, depth, height, width) else: test_data = test_data.reshape(1, height, width, depth) preds = model.predict(test_data) class_ = np.argmax(preds[0], axis=1) confidence = float(preds[0][class_]) # confidence percentage,save three decimal places confidence = '%.2f' % (confidence * 100) return class_, confidence def predict_one_img(img_path): model = load_model('model.h5') img = cv2.imread(img_path) class_, confidence = get_class_name_and_confidence(img, model) img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) draw = ImageDraw.Draw(img) font_text = ImageFont.truetype("simsun.ttc", 60, encoding="utf-8") draw.text((5, 5), class_name + ' %' + str(confidence), (0, 255, 0), font=font_text) img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR) print('Class name:', class_name, 'confidence:', str(confidence)+'%') # cv2.namedWindow('img', 0) # cv2.resizeWindow('img',window_width,window_height) cv2.imshow('img', img) cv2.waitKey(0) cv2.destroyAllWindows() class MainFrame(wx.Frame): def __init__(self, title): size = window_width, window_height wx.Frame.__init__(self, None, title=title, pos=wx.DefaultPosition, size=(600, 600)) self.panel = wx.Panel(self) self.Center() self.image_cover = wx.Image( 'test.jpg', wx.BITMAP_TYPE_ANY).Scale(350, 300) self.staticbitmap = wx.StaticBitmap( self.panel, -1, wx.Bitmap(self.image_cover)) start_button = wx.Button(self.panel, label='Start') close_button = wx.Button(self.panel, label='Close') self.model = load_model('model.h5') self.cap = cv2.VideoCapture(0) self.cap.set(3, cam_width) self.cap.set(4, cam_height) update_thread = threading.Thread(target=self.update, args=()) update_thread.start() self.Show(True) def update(self): while True: ret, frame = self.cap.read() if not ret: continue print(frame.shape) # frame = cv2.cvtColor(fram, cv2.COLOR_BGR2RGB) class_name, confidence = get_class_name_and_confidence( frame, self.model) img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) draw = ImageDraw.Draw(img) font_text = ImageFont.truetype("simsun.ttc", 60, encoding="utf-8") draw.text((5, 5), class_name + str(confidence) + '%', (0, 255, 0), font=font_text) frame = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR) # cv2.putText(frame, category_name+' %'+str(confidence), # (0, 70), cv2.FONT_HERSHEY_COMPLEX, 3, (0, 255, 0), 6) cv2.namedWindow('frame', 0) cv2.resizeWindow('frame', window_width, window_height) cv2.imshow('frame', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break h, w = frame.shape[:2] frame = wx.Bitmap.FromBuffer(w, h, frame) self.staticbitmap.SetBitmap(frame) # self.staticbitmap.Refresh() self.cap.release() def main(): app = wx.App(False) frame = MainFrame('Food Recognition System') app.MainLoop() <file_sep># Food-Recognition-System * Deep Learning based food recognition system Using `Keras`(`Tensorflow` backend) deep learning framwork * Also can be transplanted to other platforms like `Raspberry Pi` * This tensorflow repo is **no longer maintained** now :(, plz see [FRS-pytorch](https://github.com/ivanwhaf/FRS-pytorch) for more details # Usage ## Preparation * 1.run spiders`spider_baidu.py` or `spider_douguo.py` to crawl raw image data from the internet * 2.create an empty folder and move raw images into it,in this project was `dataset` folder * 3.run `train.py` to train the model (only when dataset was downloaded) ## Run directly * run `cam_demo.py` to show ui,load the model and recongnize the food ## Run in command line cd your project path and type: * `python detect.py -i test.jpg` * `python detect.py -v test.mp4` ## Caution * need plotting model structure? just install `graphviz` first * please screen out unqualified raw images manually after crawling # Program Structure ## Image Preprocessing module * file:`preprocess.py` * preprocess image dataset ## Image Utils module * file:`image_util.py` * some image utils and algorithms ## Training module * file:`train.py` * main training program ## UI and Predicting module * file:`cam_demo.py`,`detect.py` * user interface,just to predict image,using pyqt5 ## Image Spiders module * folder: spiders * file: `spider_baidu.py` , `spider_douguo.py` * use spiders to crawl raw images from the internet # Requirements ```bash $ pip install -r requirements.txt ``` # Dependency * keras * tensorflow-gpu * numpy * opencv-python * pillow * matplotlib (used to show parameter change) * pyqt5 or wxpython (UI) * graphviz and pydot (used to save network model) * h5py (used to save model .h5 file) # Environment ## PC Ⅰ * Windows 10 * Python 3.6.8 * CUDA 9.0 * cuDNN 7.4 * tensorflow-gpu 1.9.0 * Keras 2.2.4 * PyQt5 5.15.0 * Nvidia GTX 1060 3G ## PC Ⅱ * Windows 10 * Python 3.7.8 * CUDA 10.0 * cuDNN 7.4 * tensorflow-gpu 1.14.0 * Keras 2.3.1 * PyQt5 5.15.0 * Nvidia MX350 2G ## Micro PC Ⅲ * Raspbian(Debian based) * etc.
954905ebbdaa6e167d4cb33864ac96a357488912
[ "Markdown", "Python", "Text" ]
9
Python
ivanwhaf/Food-Recognition-System
f4823bdbcbd8afd639b3bd63332ce5f28b3f1566
4c9610f5f37b6dd78743f0e1be684a22acbe51c7
refs/heads/master
<repo_name>Strangemother/project-conceptnet-graphing<file_sep>/docs/writes/division-of-work.md # Conceptual Division [Concept] 30/06/2018 The curret space addressing doesn't function accurately. The strictly procedural inspection through a number of graphs doesn't populate a _concept_ in an easy-to-address object. This leads to nesting meta data in logical objects - leading to a poor taxonomy. With this a change to the meta graphing and how sparse graphs can communicate Current: Input => Assess String => Inital context graphing => secondary graphing => Memory => LTS The init context graphing manages cross-referencing of other immediate concepts, and the secondary graphing assigns deeper meaning and recursive corrections. The graph context exists within object data and extracted through each process. Instead the division of labour is performed at the initial graph stage whilst maintaining a temporal space for a given sentence. Therefore additional context is applied asyncronously. We can define elements of intent through purpose graphs, perhaps hard-coded. The additional context graphing units we can call a "module". A single module will provide a sub-graph to apply additional context to the originator. The sentence list (temporal string registry within the immediate context graph) manages a set of quickly changing associations - weighted and managed by another graph and ML trained weighting machine. To simplify; A sentence "I like the month of may" is assessed as a temporal string. A module will exist for _operator self reference_, _emotive awareness_ and date extraction. The conceptual graphs for "I" and "Like" may require emotive knowledge and literal translation before use. A module reacts to the newly requested graphing and responds with a unique ID and result. The additional meta result will include a weighting number for the sentence cross-reference transient weight value. When a sentence is altered, its current graphs and cross-referencing should be re-evalutated applying the new weights from the module. As each _word_ of a sentence could change at any time, a _reasoning module_ should decide if newly weighted graph is better than the current immediate context. I feel this may yield a lot of mistakes initially, but a 3rd ML layer for attaining a record of corrections - should apply the previously taught correcting within the "literal translate" stage (effectivly hot-wiring the reasoning module extraction to previously canned results). <file_sep>/src/graph_ui/readme.md # Graph UI The UI to present database graph information in a visual manner. At the moment this is a free graph presenting edge edge and word node. Flask run: python main.py <file_sep>/src/graph_ui/static/js/input_view.js var inputApp = new Vue({ el: '#question_input' , data: { question: 'hello' , lastQuestion: '' , messages: [] } , mounted(){ bus.$on('message', this.wsMessage.bind(this)) } , methods: { wsMessage(data) { //console.log('input from socket', data) let tokens = data.data.tokens if(tokens == undefined) { tokens = []} if(data.data.action) { this.messages.unshift({ action: data.data.action , tokens: [].slice.call(tokens, 0) }) } // bus.$emit('message', data) } , getWord(word) { getWord(word) } , clear(){ wordView.nodes().clear() } , inputString(event) { console.log('Enter Key', this.question) getWord(this.question) this.lastQuestion = this.question this.messages.push(this.question) this.question = '' } } }) <file_sep>/src/v2/conceptnet/graph.py """A prototype of the graphing data core, to allow weighted data from rows """ from conceptnet import sqlite_db db = sqlite_db.spread_db() class Connection(object): def __init__(self, start, end, rel,weight): self.start = start self.end = end self.rel = rel self.weight = weight words = {} word_dic = {} word_dic_counter = 0 def dic(word): global word_dic_counter index = word_dic_counter word_dic_counter += 1 if index in word_dic: return word_dic[index] word_dic[index] = word return index REVERSE = 'reverse' class Weighted(object): def __init__(self, word, weight, reverse=False): self.word = word self.weight = weight self.reverse = reverse def __repr__(self): s = '<Weight {} {}>'.format(self.word, self.weight) return s def weighted(*a): return Weighted(*a) def back_weighted(relation_word, value): return weighted(relation_word, value) def graph_word(word, words=None, reverse=True): words = words or {} lines = db.get_word(word) for start, end, rel, weight, _json in lines: d_start = str(start) d_end = str(end) d_rel = dic(str(rel)) if d_start not in words: words[d_start] = {} if rel not in words[d_start]: words[d_start][rel] = () # words[d_start][rel] += ( (d_end, weighted(rel, weight),), ) words[d_start][rel] += ( (d_end, weight,), ) if reverse is True: if d_end not in words: words[d_end] = () #words[d_end] += ( (d_start, weighted(rel, weight, True),), ) words[d_end] += ( (d_start, (weight, True,),), ) return words <file_sep>/docs/writes/what its not.md I had a light discussion with a colleague enjoying my chat on the next ML graph I'm applying and was slightly surprised at the accuracy of the responses. "Where is the cat", "what is the time". "How many legs does a chicken have after dinner" (amusingly 3?). And they begged the answer to _why_ this isn't consciousness as it mimics the answers of their child pretty accurately. With the data trained upon human information scraped from wikipedia its easy to see why this a tool such as this may be _alive_? No. It's just clever indexing of data, coupled with some ML voodoo and a lot of hours carefully digesting the right sources. But at times I feel it helps greatly to copy good ideas from the human body - or at least replicate them as best I can. This in turn starts to push more terminology through a neurological lens. At which point I find myself considering how a machine _thinks_. But of course it doesn't. I'm wording hard to ensure I don't use vapid cliches to mimic the brain. When communicating about the project, I deem it necessary to communicate precisely and clearly. Due to the nature of the content it's hard to keep a clean view on where the conversation applies. _Is this guy talking about the words in the code, or are these words of a sentence_ right? So I try hard not to talk about any consciousness; or mimicking aspects of the human brain but sometimes I tend to trip over the best method to explain the code. In this case "Current context" is a muddy sandbox of in memory references kept alive by recursive weight training and biases to the environment. It sounds technical but it's fairly easy code to write. To explain it succinctly I need to be forgiven for stating _the aware part_ or _live evaluation of current context_. The 'Current Context' is my best way to describe the core _never off_ round robin graphing... \*cough... consciousness. And with that I'll state - it's nonsense init. I don't believe we'll see a truly conscious computer for at least 50 years. Singularities don't count. I mean a terminator style _"I just woke up, I want to paint a picture"_ true artificial intelligence. So I want to write the 'Brain' and me wee 'neural regions' but that would be silly. --- Studying a graph of 'alive' - it's pretty narrow, A 'relatedto' 'thing' returns a multitude of results 'hasprerequisite' of a bunch of crap. The system simply stops graphing as it cannot action the edge type naturally. In these cases I feel canned responses for such question - but this is silly as the graphing should be able to determine 'alive' as some sort of consciousness. of which a 'machine' (in a self referencing graph) is not. I haven't put much time into researching these graphs so they're quite sparse. More research is needed. <file_sep>/src/v4/wordnet.py '''Use berkley key assoc exe app as a data input by reading STDOUT of a windows cli tool.''' import os import subprocess import plog from plog.api import Plog from plog.patterns import PlogLine, PlogBlock from .typemap import noun, verb, adj, attrs, adv NOUN = tuple(noun.keys()) VERB = tuple(verb.keys()) ADJ = tuple(adj.keys()) ADV = tuple(adv.keys()) ALL = list(NOUN + VERB + ADJ + ADV) APP_PATH = "C:/Program Files (x86)/WordNet/2.1/bin/wn" OUTPUT_DIR = "C:\\Users\\jay\\Documents\\projects\\context-api\\context\\src\\data\\wordnet" def get_word(word, *a, app_path=None, output_dir=None, kws=ALL, **kw): res = caller(list(kws), app_path=app_path, output_dir=output_dir)(word, *a, **kw) #res = process_call_value(str_res) return res def caller(params=None, app_path=None, output_dir=None): """Produce a call to the wordnet app using command run. provide a list of seitches (without prefix char); Return a partial function to call: method = caller( ('grepa', 'ants',) ) method(word) """ params = params or [] app_path = app_path or APP_PATH out_base = output_dir or OUTPUT_DIR def perform_call(word, additional_params=None, to_file=None): ams = additional_params or [] items = list(set(params + ams)) switches = ' -'.join(items) ps = hash('-'.join(params)) filename = "{}-{}.txt".format(word, ps) if to_file is True: to_file = filename out_file = to_file list_switches = ['-' + x for x in list(set(params + ams))] out = os.path.join(out_base, filename) st = '"{app}" {word} -{switches} > "{out}"' call_str = st.format(app=app_path, word=word, switches=switches, out=out) cmds = [app_path, word] + list_switches if out_file is None: out_file = os.path.abspath(out) elif to_file is not False: #out_file = os.path.abspath(to_file) out_file = os.path.join(out_base, to_file) if (to_file is not False) and (out_file is not None): cmds += ['>', out_file] print("Running: \n{}\n".format(' '.join(cmds))) op = None #if out_file is None: op = subprocess.PIPE # py 3.7 # res = subprocess.run([call_str], capture_output=True) proc = subprocess.run(cmds, stdout=op, timeout=5, shell=True, stderr=subprocess.PIPE) res = process_call_value(word, proc) return res return perform_call def process_call_value(word, complete_process): # print(complete_process.returncode) # print(complete_process.args) # print('Out len:', len(complete_process.stdout)) # print('error:', complete_process.stderr) string = complete_process.stdout if (isinstance(string, bytes) is True) and len(string) == 0: filepath = complete_process.args[-1] print('File input detected', filepath) with open(filepath) as stream: data = stream.readlines() else: data = complete_process.stdout.split('\n') return destructure(word, data) # return data def destructure(word, lines): print('destructure', word) mblocks = tuple(BLOCKS[n](word) for n in BLOCKS) # open all blocks # iterate line # find detection # match to a block and feed into the matching block until break # alert any missed lines (should be entire blocks) # Break on new line into detection mode. focus_block = None match_mode = False for index, line in enumerate(lines): line = line.rstrip() if match_mode: # Feed to the block until it returns false. # False for continue to the next blocks as a check. print(' feeding:', index, focus_block.__class__.__name__, line) # time.sleep(.1) match_mode = focus_block.feed(line) if match_mode: continue else: print('detach from', focus_block) # time.sleep(1) # print('detecting line', index, line) # print([x.match(line) for x in mblocks]) for block in mblocks: # print('{}, {}'.format(index, block.__class__.__name__)) if block.match(line): print('Match block', index, block) match_mode = True focus_block = block return focus_block import re import time class BlockStructure(object): pattern = (r"{word}", re.IGNORECASE) def __init__(self, word): self.word = word self.lines = () self._compile = self.get_compile() def get_compile(self): pattern = self.get_pattern(self.word) print(pattern) return re.compile(*pattern) def get_pattern(self, word): s, *a = self.pattern pf = self.pattern_format(word) fp = s.format(**pf) return tuple([fp] + a) def pattern_format(self, word): return { 'word': word } def feed(self, line): """Continue with feeding a block parsing after a match Return boolean as match_mode to continue feeding. """ self.lines += (line, ) if len(line) == 0 and len(self.lines) > 1: return False return True def match(self, line): result = False match = self._compile.match(line) if match: self._last_match_start = match.group() return match BLOCKS = {} def register(cls): """ """ print('Registering {}'.format(cls)) BLOCKS[cls.__name__] = cls class AutoRegister: def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) register(cls) class WordnetBase(BlockStructure): part = "" pattern = (r"{part}(\w*) {word}", re.IGNORECASE) def pattern_format(self, word): return {'word': word, 'part': self.part} class GrepBlock(WordnetBase, AutoRegister): part = "Grep of " # Grep of noun duck # Grep of verb duck # Grep of adj duck #pattern = (r"Grep of (\w*) {word}", re.IGNORECASE) class HolonymBlock(GrepBlock): # Substance Holonyms of noun duck # Member Holonyms of noun duck # Part Holonyms of noun duck # Holonyms of noun duck # Holonyms of noun duck part = r"(\w*.){0,1}([ ]{0,1})Holonyms of " class DomainTermsBlock(GrepBlock): part = r"Domain Terms of " class FamiliarityBlock(GrepBlock): part = r"Familiarity of " class EntailmentBlock(GrepBlock): part = r"Entailment of " class SynonymsBlock(GrepBlock): part = r"Synonyms of " class SynonymsHypernyms(GrepBlock): part = r"Synonyms/Hypernyms (Ordered by Estimated Frequency) of " class CoordinateTerms(GrepBlock): part = r"Coordinate Terms (sisters) of " class Troponyms(GrepBlock): part = r"Troponyms (hyponyms) of " class Overview(GrepBlock): part = r"Overview of " class MemberMeronyms(GrepBlock): part = r"Member Meronyms of " class SampleSentences(GrepBlock): part = r"Sample Sentences of " class PartMeronyms(GrepBlock): part = r"Part Meronyms of " class Meronyms(GrepBlock): part = r"Meronyms of " class Hyponyms(GrepBlock): part = r"Hyponyms of " class Antonyms(GrepBlock): part = r"Antonyms of " <file_sep>/src/v1/typemap.py type_map = { 'CC' :'Coordinating conjunction', 'CD' :'Cardinal number', 'DT' :'Determiner', 'EX' :'Existential there', 'FW' :'Foreign word', 'IN' :'Preposition or subordinating conjunction', 'JJ' :'Adjective', 'JJR' :'Adjective, comparative', 'JJS' :'Adjective, superlative', 'LS' :'List item marker', 'MD' :'Modal', 'NN' :'Noun, singular or mass', 'NNS' :'Noun, plural', 'NNP' :'Proper noun, singular', 'NNPS' :'Proper noun, plural', 'PDT' :'Predeterminer', 'POS' :'Possessive ending', 'PRP' :'Personal pronoun', 'PRP$':'Possessive pronoun', 'RB' :'Adverb', 'RBR' :'Adverb, comparative', 'RBS' :'Adverb, superlative', 'RP' :'Particle', 'SYM' :'Symbol', 'TO' :'to', 'UH' :'Interjection', 'VB' :'Verb, base form', 'VBD' :'Verb, past tense', 'VBG' :'Verb, gerund or present participle', 'VBN' :'Verb, past participle', 'VBP' :'Verb, non-3rd person singular present', 'VBZ' :'Verb, 3rd person singular present', 'WDT' :'Wh-determiner', 'WP' :'Wh-pronoun', 'WP$':'Possessive wh-pronoun', 'WRB' :'Wh-adverb', '.': 'Puncuation', } noun = { 'antsn':"Antonyms", 'hypen':"Hypernyms", 'hypon':"Hyponyms & Hyponym Tree", 'treen':"Hyponyms & Hyponym Tree", 'synsn':"Synonyms (ordered by estimated frequency)", 'attrn':"Attributes", 'derin':"Derived Forms", 'domnn':"Domain", 'famln':"Familiarity & Polysemy Count", 'coorn':"Coordinate Terms (sisters)", 'grepn':"List of Compound Words", 'over':"Overview of Senses", } verb = { 'antsv':"Antonyms", 'hypev':"Hypernyms", 'hypov':"Hyponyms & Hyponym Tree", 'treev':"Hyponyms & Hyponym Tree", 'synsv':"Synonyms (ordered by estimated frequency)", 'deriv':"Derived Forms", 'famlv':"Familiarity & Polysemy Count", 'framv':"Verb Frames", 'coorv':"Coordinate Terms (sisters)", 'simsv':"Synonyms (grouped by similarity of meaning)", 'grepv':"List of Compound Words", 'over':"Overview of Senses", } adj = { 'antsa':"Antonyms", 'synsa':"Synonyms (ordered by estimated frequency)", 'domna':"Domain", 'famla':"Familiarity & Polysemy Count", 'grepa':"List of Compound Words", 'over':"Overview of Senses", } attrs = { 'h':'Print help text before search results.', 'g':'Display textual glosses associated with synsets.', 'a':'Display lexicographer file information.', 'o':'Display synset offset of each synset.', 's':'Display each word\'s sense numbers in synsets', 'l':'Display the WordNet copyright notice, version number, and license.', 'n#':'Perform search on sense number # only.', 'over':'Display overview of all senses of searchstr in all syntactic categories.', } <file_sep>/docs/writes/modules.md # A Module A Module (which is an awful term) defines a subsection of the main context api to manage and maintain IO from all other graphs and modules. Given a graph input a module will _result_ a weight and more graphing; given back to the reference (or parent) graph or calling module. At the moment the concept of a module has no real definition aside from API properties. A module integration should consist of + Isolated work from the main graph + Maintain personal graphs with a data reference + Can call to and wait for other modules + May be async or sync. Some ideas for modules: ## Reasoning module A module receiving incomplete or finished graphs from a temporal input or other modules and return the best fit result for all other given results. Consider a sentence "I own a cat". It's broken into graph constituents and a context of the sentence is applied to memory. The reasoning module accepts the initial phase of the sentence. This is potentially the primary data graphs and meta data such as tokenization or another form of _initial_. Applying another sentence "I don't like cats" will instigate a weight reasoning and abstraction from the second set of graphs. With the competing sentences the reasoning module calls upon other modules for additional weighting. A final evaluation of the two sentences produces a vector graph to compute as a response. The evaluation of this response result is also _reasoned_ for validity. ## Personal Reference For references in the first and third person I feel the best method to resolve the counter-intuitive aspect of 'you' and 'I' is define a single module performing a self-referencing flip on all incoming and outgoing graph results. The sentence "You are a machine. I am a human" provides two clear statements for graphing however at some point the code should infer 'you' as _my personal context_. This is more complicated for other references such as third person referencing; "I said to him I want you to stay". Without grammar this is a tricky for the system. In our sentence 'you' refers to 'him', the abstract other person. Therefore the personal reference module will depend upon the nltk tokenizer for non deterministic references. Any discoveries to 'self' are maintained in a Graph dedicated to the systems self identification. In turn using the 'self' graph as an antonym graph for the 'operator' graph ## Operator Reference The operator is the user/inputer/developer/_you_. ## personal preference The self referencing persona will maintain a context of preferences. This will consist of a heavily weighted graph answering the reasoning module when questions for _which graph_ arises during word weighting. In a conceptual question "Do you like cats". I response may be yes, no or some other weighted factor. This overall preference resides within a bank of previously graphed knowledge of _things_ and sentences for experiences. In a more down-to-earth example, a star-trek door has a preference for being closed, opening if someone says "enter after a bell". This same door should be _automatic_ during selected periods. The personal preference to a query "open or closed" will yield closed unless the environment (another graph) provides a heavier weight for the 'open' graph. This of course leans towards general learning of previous graphs and heavy recursive analysis of 'hard' training and temporal sentences. ## sequences and preference output A graph will contain meta data of a final result during a weighting session. The result should be re-graphed and _normalised_ to a graph output for translation. In an example case we tell the system a sequence "doors have handles" "some handles are round" "some handles are straight" "most handles in Boston are round" After this, we can query for a graph weight of "How many handles are round?". The context should denote 'most' and 'some' for a count of handles. A question of _which is greater 'most' or 'some'_. Humans easily apply 'most' and it's more than 'some'. But if Boston is the size of Russia, that sequence is opposite. The preference of output for which entity in an abstract sequence should be applied. In this case we train _most is more than some_ but the same can be equated through a longer timed graph session. ## queries / questions Most problematic of all inputs; especially temporal without grammar - is a query the _question_. Applying a query to the context should resolve to a translatable answer. In this study case that would be a preferred graph word: "how many legs does a dog have" will need the pseudo code: dog.countof(legs) The assertions already assign `dog hasa four_legs`. Through a split graph of graph "four legs" yields a `count legs` of four. This is naturally performed through the context graphing. The reasoning module should store this into an environment sentence list and proceed to recurse for stronger graphs. Translation of the smaller graph is dependent upon the 'how many.. ?' query - something not picked up by a tokenizer without prompt. As such an individual module for 'question response' detects a temporal query and will monitor the resolution of the sentence graphs until enough information exists for a successful answer. The answer consists of an event from the module for any other waiting modules - such as the reasoning module. To quantify a _complete_ answer ready for output the module performs its own detection of a query type - chunking the string and potentially creating a new tokenization. The sentence graph (main graph) containing a master context is peppered with some meta data for _this is a query_. Each word is contextualized and re-graphed through any additional contexts chosen by the query graph. A single context object of 'dog' with an empty slot for _legs, count_ stresses the graph to yield an answer until the slot is filled with a true statement. Through a bridge to the 'self asserting' module the slot is _asserted_ as the answer for the the waiting question. An 'instant answer' event of some kind should prompt the translation module to convert: "how many legs does a dog have" dog.countof(legs) legs_graph = Graph(dog).has_property_four_legs legs_graph['four', 'legs'] > count == 4 four == number dog run legs dog.has_property.legs dog.has_property.four_legs == legs_graph ... so on. The circular graphing for this is pretty strong - Some work to the sequence module can yield: legs > perform > run > feet ... ## self asserting queries In a set of cases we need the graph to _volunteer_ information: + Asserting importance; heavy graphs + quantify background knowledge (resolved a heavy graph) + Response to queries + hard-coded graph responses to tasks ## Hard coded actions Terming as 'self assembly vocal functions' - at times you require an action to be taken upon the resolution of a graph. the example sentence "open the door" should run a function called `bedroom.door_open()`. This same functionality should be ran through any temporal direction: Let me in open now I want in the house! Each yielding a weighting towards the bias of 'open' in context to a local graph of an operations house. # Translation Module To ground the knowledge further, the internal code simply performs indesing of pre-trained and session trained word values. Given enough relationships - and a bunch of number weighting an object of result is stored into 'current context'. Usually a object full of tree words is a Graph, but it could be any pythonic object with reference data to the tree. The result object is a graph with computational results from graphs and module in the session. Once an object is flagged with enough knowledge to quantify a permanency in memory - the translation module can convert it to a real-world output. In this case a 'translation module' receives or captures input from other modules and converts to an audio response. _Translation_ may be misinterpreted as conversion to another language EN to ES for example but here, the module interprets a graph response or module output to another form such as sentences of words or a servo motor. In a more down-to-earth scenario when walking through a Startrek door you may say "open the door". This graphs to a result of hard-coded context 'open door'. The translation module will accept the finished result object of 'open door' context and convert it to [Startrek door sound] and physically pulling the door open. On another case we tell the context-api "Ooh no that's bad". The graph will result in a _negative_ and the translation module converts this to R2D2 style whirling beeps. ---- For our normal example we convert the final result object to a simple stated sentence "can I eat eggs" infers the question is it possible to 'eat', 'egg'. A simple test of the current version shows this is graphed through 'food' and a top result for that is 'eating' and 'eat'. Therefore the context of this sentence is wholly positive and should be asserted through the translation module by the query module as a positive. The translation module should convert this to a `Graph('positive')` and audio assert the top result. This value should be graphed through the 'personal preference' in accordance to 'sequential order' of the word 'positive'. <file_sep>/src/plog/test_api.py from api import Plog from patterns import PlogBlock, PlogLine # Test file def test_file_on_init(): f = open('file') plog = Plog(f) assert plog.get_file() == f assert plog.get_data() == f def test_add_file(): f = open('file') plog = Plog() plog.set_file(f) assert plog.get_file() == f assert plog.get_data() == f def test_add_string(): CDP_DATA = ''' Device ID: SEP001F9EAB59F1 Entry address(es): IP address: 10.243.14.48 Platform: Cisco IP Phone 7941, Capabilities: Host Phone Interface: FastEthernet0/15, Port ID (outgoing port): Port 1 Holdtime : 124 sec ''' plog = Plog(CDP_DATA) assert plog.get_file() def test_add_block(): ''' Add a basic empty block to the plog.blocks ''' plog = Plog() block = PlogBlock() plog.add_block(block) assert len(plog.blocks) == 1 def test_add_block_string(): ''' Add a plog block as as a string. This is converted to conform into a plog.line for a plog.block ''' plog = Plog() plog.add_block('Device') assert len(plog.blocks) == 1 def test_line(): '''Pass a string to the PlogLine, it should __eq__ a string correctly.''' string = 'Device' line = PlogLine(string) assert line == string def test_block_header(): ''' Add the first line to a block and check it's added as a header''' line = PlogLine('Device') block = PlogBlock(line) assert block.header == line def test_block_header_string_cast(): '''Plog block is given a string, block.header should exist''' block = PlogBlock('Device') assert type(block.header) == PlogLine def test_enumerate(): ''' Check to ensure the enumeration of a file or string is exaclty the length of lines for the supplied. ''' CDP_DATA = '''Device ID: SEP001F9EAB59F1 Entry address(es): IP address: 10.243.14.48 Platform: Cisco IP Phone 7941, Capabilities: Host Phone Interface: FastEthernet0/15, Port ID (outgoing port): Port 1 Holdtime : 124 sec''' plog = Plog(CDP_DATA) plog._c = 0 def counts(line, line_no): plog._c = plog._c + 1 plog.run(counts) assert plog._c == 6<file_sep>/src/database/readme.md # Database This part of the project has no name, as it's a custom no-sql db for storing graph and tables. with LMDB as a platform for local storage. ## Use cases I've made this for a number of personal tools. But it has enough dimentions to qualify for most casual cases. + Sentence Graphing for Sadie + Websockets Key Event Horizontal records + Distributed state machine storage # Gettings Started The absolute basics need no introduction. Using PROJECTNAME as an instant key value needs no setup: from database.db import DB db = DB(directory='./doc_test') // optional db.open('first') db.put('cake', 'cherry pie') True db.get('cake') 'cherry pie' db.count() 1 And that's it! Go ahead and store millions! If you don't supply a `db.open()` database, the library will use a defaulted name. The entire library works with one handle so you don't need to worry about threads or transactions - it's done for you. ## AppendableDB The basic key value database is useful for fast tests but pretty boring for functionality. an AppendableDB leverages the raw byte storage to allow updating a single key with _more_ of the same. adb = AppendableDB(directory='./doc_play') // again - optional. adb.open('first') You'll see we've opened the same database as the first `db.DB` instance. They can both use the same data. We can check that by iterating **all the data**: adb.keys() list(adb.iter()) [('cake', b'cherry pie'),] Scary. Now we'll add a list of names. The `AppendableDB` class help with coversion of a `tuple`: adb.put('names', ('eric', 'dave', 'micheal', 'bob')) adb.append('names', ('simon',) ) b"!:A1D!:'eric', 'dave', 'micheal', 'bob'" When you `append` data, you're adding to an existing row. The appended data type is the same. In this case another `tuple`. The return from `append` was the previously stored value. This will not contain your update. We can append as much as we want, `get()` a finished product when required: adb.append('names', ('simon', 'timmy') ) adb.get('names') ('eric', 'dave', 'micheal', 'bob', 'simon', 'simon', 'timmy') ## Appendable Types and conversion You can append to any builtin data type such as `list`, `tuple`, `str` or your own. PROJECTNAME doesn't care what you write as the raw data is stored in `bytes`. You can turn off encoding for advanced routines. This is especially useful when you've broke a key: # Apply a 'str' type instead of a tuple. adb.append('names', 'another name') b"!:A1D!:'eric', 'dave', 'micheal', 'bob','simon','simon', 'timmy'" Now it's broken; it can't be converted safely: adb.get('names') _convert_eval() render error: invalid syntax (<string>, line 1) _convert(A1D, 'eric', 'dave', 'micheal', 'bob','simon','simon', 'timmy',another name) # ... Crumbs... Luckily it's only one key that can break. Let's see the real DB value: adb.get('names', convert=False) b"!:A1D!:'eric', 'dave', 'micheal', 'bob','simon','simon', 'timmy',another name" You can delete a value with old standard `.delete()`, or `.replace()` ```py from database.db import AppendableDB adb = AppendableDB(directory='./doc_test') adb.open('first') adb.keys() adb.get('names', convert=False) adb.replace('names', ('bob', 'eric',)) adb.get('names', convert=False) b"!:A1D!:'bob', 'eric'" adb.get('names') ('bob', 'eric') adb.delete('names') True adb.get('names') None ``` Designed to work in any dimension, setting up the database for your personal case is key to how the methods work. ### Vertical Append Similar to a standard table records apply in a linear order, therefore iteration through rows is possible. Applying a class map for return values can mimic ordered column rows: ```py Row = namedtuple('Row', 'a b c d e f') db.put(Row(1,2,3,4,5,6)) for row in db: assert isinstance(row, Row) ``` ### Horizonal Append The key input allows an 'append' functionality to reduce the amount of throughput for a given procedure. This will allow the continued extension of basic python types without convertion. for example storing a `list` will allow `db.append('mylist_key', (23,23,45,))`. The same applies for all basic python types. This example will record typing events per sentence into a single key, storing keystrokes for historical _undo_: ```py keystrokes = ('h', 'e', 'l', 'o', '[backspace]', 'l', 'o') db.put('my_page_3', keystrokes) db.append('my_page_3', ('w', 'o',) ) db.append('my_page_3', ('r', 'l',) ) db.append('my_page_3', ('d',) ) ''.join.(db.get('my_page_3')) 'helo[backspace]lo world' ``` ## GraphDB A graph database defines connections between _nodes_ (data values) and _edges_ (a connection to values). A node consists of something you'd like to store - such as an object `{ name: 'terry', age: 10}`. an edge connects this node to another, with a special label for the type of connection "terry > friends_with > micheal". A graph contains lots of edges for each node. In turn they are connected to other nodes and so on. The `GraphDB` applies a few extra methods through the use of a `GraphWalker`. # test py -mpytest -sv database # with coverage: py -mpytest database -v --cov --cov-report=term-missing <file_sep>/src/server/assets/js/main.js var cleanData = [] var jsonFetchApp = new Vue({ el: '#main' , data: { address: 'hello' , basePath: 'http://api.conceptnet.io' , requests: [] , selected: {} , relations: [] , indexItem: -1 } , methods: { fetch(event, partial){ let path = partial == undefined ? this.$refs.address.value: partial; console.log('path', path) if(path[0] != '/'){ path = "/c/en/" + path } let fullpath = `${this.basePath}${path}` $.get(fullpath, function(data){ this.renderPath(path, data) }.bind(this)) } , renderPath(path, data) { console.log('got', data) cleanData.push({path, data}) let dataCopy = JSON.parse(JSON.stringify(data)) this.requests.push({ path, dataCopy }) if(this.indexItem == -1) { this.selected = dataCopy let _d = {}; for(let item of data.edges) { _d[item.rel.label] = 1 }; this.relations = Object.keys(_d); } } } }) var bus = new Vue({ }) //$(function(){ // if ('speechSynthesis' in window) { // speechSynthesis.onvoiceschanged = function() { // var $voicelist = $('#voices'); // // if($voicelist.find('option').length == 0) { // speechSynthesis.getVoices().forEach(function(voice, index) { // console.log(voice); // var $option = $('<option>') // .val(index) // .html(voice.name + (voice.default ? ' (default)' :'')); // // $voicelist.append($option); // }); // // $voicelist.material_select(); // } // } // // $('#speak').click(function(){ // var text = $('#message').val(); // var msg = new SpeechSynthesisUtterance(); // var voices = window.speechSynthesis.getVoices(); // msg.voice = voices[$('#voices').val()]; // msg.rate = $('#rate').val() / 10; // msg.pitch = $('#pitch').val(); // msg.text = text; // // msg.onend = function(e) { // console.log('Finished in ' + event.elapsedTime + ' seconds.'); // }; // // console.log(speechSynthesis); // // speechSynthesis.speak(msg); // }) // } else { // $('#modal1').openModal(); // } //}); <file_sep>/src/plog/working.py from pprint import pprint from api import Plog from patterns import PlogLine, PlogBlock from blocks import CDPBlock f = open('test_data2.txt', 'r') plog = Plog(f, whitespace='|', terminator=',') # import pdb; pdb.set_trace() plog.add_blocks(CDPBlock) plog.run() for block in plog.data_blocks: if block.valid(): d = block.as_dict() print d import pdb; pdb.set_trace() <file_sep>/src/plog/working7.py from api import Plog from patterns import PlogLine, PlogBlock as Block block = Block('Device ID:', ref='Device') #block.header.ref='device_id' line = PlogLine(ref='ip') line.startswith('IP address:') block.add_line(line) block.footer = PlogLine('----------', ref='footer').anything() # new parser f = open('test_data2.txt', 'r') # plog = Plog(f, whitespace='|') plog = Plog(f, whitespace='|', terminator=',') # run it plog.add_block(block) blocks = plog.run() for block in blocks: if block.valid(): print block.as_dict() <file_sep>/src/v5/context/first/migrations/0005_auto_20190728_0025.py # Generated by Django 2.2.3 on 2019-07-27 23:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('first', '0004_auto_20190727_2341'), ] operations = [ migrations.AddField( model_name='tokenword', name='dictionary', field=models.TextField(blank=True, null=True), ), migrations.AlterField( model_name='temporalinput', name='tokens', field=models.ManyToManyField(blank=True, to='first.PositionTokenWord'), ), ] <file_sep>/src/plog/mixins.py from io import StringIO from plog import patterns class MixinBase(object): ''' Base mixin object of all Plog Mixins to inherit''' def __init__(self, *args, **kwargs): pass class PlogFileMixin(MixinBase): ''' A PlogFileMixin is designed to wrap a file object to represent correctly for enumeration. You can pass a string or a file object. Strings are converted to StringIO.StringIO before use. Pass this to the class for easy get_file, set_file methods ''' def __init__(self, *args, **kwargs): ''' initial file can be given ''' self._file = None self._data = None if len(args) > 0: ''' could be file or string''' self.set_data(args[0]) super(PlogFileMixin, self).__init__(*args, **kwargs) def set_file(self, log_file): ''' Add a file to the class to parse This will return a StringIO if a string was passed as data.''' self.set_data(log_file) def set_data(self, data): ''' wrapper for applying the file content to the class''' if type(data) == str: output = StringIO.StringIO(data) self._data = output else: self._data = data def get_data(self): return self._data def get_file(self): ''' return the internal file, This will return a StringIO if a string was passed as data ''' return self.get_data() class PlogBlockMixin(MixinBase): ''' Methods to assist block design on on a class ''' def __init__(self, *args, **kwargs): self._blocks = [] super(PlogBlockMixin, self).__init__(*args, **kwargs) def blocks(): doc = "The blocks property." def fget(self): return self._blocks def fset(self, value): self._blocks = value def fdel(self): del self._blocks return locals() blocks = property(**blocks()) def block_match(self, block, line, string, reg): ''' Method called upon a successfull match of a block header block {PlogBlock} - The block containing the matched PlogLine line {PlogLine} - PlogLine matched string {str} - String matched from file reg {regex} - Regex SRE match object (if it exists) ''' #print '> Block', block #print ' Match', line #print ' Found', string, '\n' def compile_blocks(self): '''Call each block to compile as needed''' for block in self.blocks: block.compile() def close_all_blocks(self): ''' Close any dangling blocks (blocks open at the end of parsing) and return a list of closed blocks. ''' closed =[] for block in self.blocks: if block.is_open: print('force close', block.ref) closed.append(block) block.close() return closed def add_blocks(self, *args): ''' Add a list of blocks to append add_blocks(block1, block2, block3, ... ) add_blocks(*blocks) ''' for block in args: self.add_block(block) def add_block(self, block): ''' Append a plog block to all valid blocks. ''' _block = block if type(block) == str: _block = patterns.PlogBlock(block) elif hasattr(_block, 'block'): _block = _block.block self._blocks.append(_block) def get_blocks_with_header(self, *args): ''' Pass one or many PlogLines and return all matching blocks with the headers of that type. ''' header_line = args[0] # Loop blocks. _blocks = [] for block in self.blocks: mtch, reg = block.header.match(header_line) if mtch: _blocks.append(block) self.block_match(block, block.header, header_line, reg) return _blocks def get_blocks_with_header_footer(self, *args): ''' Pass one or many PlogLines and return all matching blocks with the headers of that type. ''' mline = args[0] # Loop blocks. _blocks = [] mtch = None mtch_f = None reg = None reg_f = None for block in self.blocks: if block.header: mtch, reg = block.header.match(mline) if block.footer: mtch_f, reg_f = block.footer.match(mline) if mtch_f or mtch: _blocks.append(block) if mtch: self.block_match(block, block.header, mline, reg or reg_f) if mtch_f: self.block_match(block, block.footer, mline, reg or reg_f) return (_blocks, True if mtch else False, ) <file_sep>/src/v1/cache.py import os import io import json root_path = os.path.abspath(os.path.dirname(__file__)) def set_global_root(path): global root_path root_path = os.path.abspath(path) print 'Set global cache dir', root_path if os.path.exists(root_path) is False: print 'creating', root_path os.makedirs(root_path) def write_json(relpath, data): filepath = resolve_path(relpath) with io.open(filepath, 'w') as stream: stream.write(unicode(json.dumps(data, indent=4))) WARNED_STRING_CACHE_DEPRECATION = False def string_cache(string): global WARNED_STRING_CACHE_DEPRECATION if WARNED_STRING_CACHE_DEPRECATION is False: print 'string_cache is deprecated. Use "get_string_cache"' WARNED_STRING_CACHE_DEPRECATION = True string_cache = get_string_cache return get_string_cache(string) def get_string_cache(string): filepath = cache_filename(string) success, v = get_cache(filepath) if success: return v return None def set_string_cache(string, value): return set_cache(cache_filename(string), value) def get_cache(relpath): # sc = spell(s) # if s != sc: # print 'Corrected Spelling: "{}"'.format(sc) # s = sc success = False v = '' filepath = resolve_path(relpath) if os.path.isfile(filepath): print 'opening {}'.format(filepath) with open(filepath, 'r') as stream: v = ''.join(stream.readlines()) if len(v) > 0: v = eval(v) success = True return success, v def resolve_path(filepath): if os.path.isabs(filepath) is False: cpath = os.path.join(root_path, filepath) else: cpath = filepath return cpath def set_cache(filepath, v): cpath = resolve_path(filepath) print 'writing {}'.format(cpath) with open(cpath, 'w') as stream: stream.write(str(v)) return True return False def cache_filename(string): return 'cache_{}.txt'.format(string.replace(' ', '_')) def delete_word(word): string_filepath = cache_filename(word) cpath = resolve_path(string_filepath) if os.path.isfile(cpath): print 'Deleting {}'.format(cpath) os.remove(cpath) return True print 'Cannot Delete. Is not file "{}"'.format(cpath) return False class LocalData(object): '''Collect local data easily.''' def __init__(self, path='./data'): '''Local Data connection with a given relative path Keyword Arguments: path {str} -- relative prefix of the data path (default: {'./data'}) ''' self.root = resolve_path(path) def get_list(self, name): '''Return a list from a file. >>> c = cache.LocalData() >>> l = c.get_list('top-words/3000.txt') >>> l[20] 'account' ''' filepath = os.path.join(self.root, name) res = [] with open(filepath, 'r') as stream: for line in stream: res.append(line.strip()) return res <file_sep>/src/plog/blocks.py from patterns import PlogLine, PlogBlock class CDPBlock(object): '''Given as a 'block' through PlugBlockMixin.add_block. The add_block method looks for the `block` attribute and appends it to the running blocks. Lines represent each attribute to dicover within the _Start_ and _stop_ content of a block. Each `PlogLine` extracts an explicitly designed value, adding it to the 'lines' of a block. A block returns the line value as a dictionary attribute in `Plug.data_block`. ''' # Define a PlogBlock and its starting value. block = PlogBlock('Device ID:', ref='Device') block.header.ref='device_id' block.footer = PlogLine('----------', ref='footer').anything() lines = {} lines['entry_address'] = PlogLine('IP address:') lines['platform'] = PlogLine('Platform:') lines['interface'] = PlogLine('Interface:') lines['hold_time'] = PlogLine('Holdtime').maybe(' ').then(':') lines['version'] = PlogLine('Version').maybe(' ').then(':').multiline() lines['version'] = PlogLine('advertisement version:') lines['duplex'] = PlogLine('Duplex:') lines['power_drawn'] = PlogLine('Power drawn:') lines['power_request_id'] = PlogLine('Power request id:') lines['power_management_id'] = PlogLine('Power management id:') lines['power_request_levels'] = PlogLine('Power request levels are:') block.add_lines(**lines) <file_sep>/src/readme.txt run v3/main.py <file_sep>/src/conceptnet/sqlite_db.py ''' from conceptnet import dbstore dbstore.spread_redis_apply(max_count=100, max_cpu=1) # populate the database with the given [builtin] csv from conceptnet import sqlite_db db = sqlite_db.fill_word_db({}) # Use one statement with a handler from conceptnet import sqlite_db x = 'C:/Users/jay/Documents/projects/context-api/context/src/cache/sqlites/sql-proc-0.db' db, c = sqlite_db.open_db(x) s = 'SELECT * FROM word WHERE start_word = "cat"' sh = sqlite_db.StatementHandler(db, c) sh.call(('select', s,)) sh.stmt_select(s) from conceptnet import sqlite_db db = sqlite_db.spread_db() db.get_word('cake') db.fetch('SELECT * FROM word WHERE start_word = ? ', ('cat', )) db.fetch('SELECT * FROM word WHERE start_word = "cat"') from conceptnet import sqlite_db from conceptnet.parse import spread db = spread(sqlite_db.fill_word_db, **{}) db = sqlite_db.spread_db() db.add_line('dog', 'legs', 'has', 1, {}) ''' import sqlite3 import multiprocessing from log import log import traceback from conceptnet.parse import parse_csv, clean_line, spread ''' from conceptnet import sqlite_db sqlite_db.store_sqlite_lines(dict(max_count=20000)) ''' import json from sqlite3 import OperationalError, ProgrammingError from multiprocessing import Queue, cpu_count import os from parse import job_split from multiprocessing import Pool, Process import atexit import multiprocessing from Queue import Empty import string import random import re UNDEFINED = 'undefined' INSERT = 'insert' COMMIT = 'commit' CLOSE = 'close' SELECT = 'select' def open_db(name): if os.path.isfile(name) is False: stream = open(name, 'wb') stream.close() conn = sqlite3.connect(name) return conn, conn.cursor() def create(cursor): word_table = '''CREATE TABLE word ( start_word STRING, end_word STRING, relation STRING, weight REAL, json TEXT ); ''' table_index = ''' CREATE INDEX value ON word ( start_word, end_word ); ''' if cursor: cursor.execute(word_table) cursor.execute(table_index) cursor.commit() def table_exists(name='word', db=None): word = "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='{}';" ex_str = word.format(name) count = db.execute(ex_str).fetchall()[0][0] return count > 0 def store_sqlite_lines(kw): process_name = multiprocessing.current_process().name db_index = kw.get('job_index', 0) db, conn = open_db("sql-{}.db".format(process_name)) if table_exists('word', db) is False: create(db) options = dict( max_count=kw.get('max_count', 100000), iter_line=sqlite_apply, as_set=True, db=db, cursor=conn, keep_sample=kw.get('sample', False), byte_start=kw.get('byte_start', None), byte_end=kw.get('byte_end', None), ) try: d, sample = parse_csv(**options) except Exception as e: log('Error on "{}" :'.format(process_name), e) log(traceback.format_exc()) d = [] db.commit() db.close() return list(d) def sqlite_apply(line, **kw): cursor = kw.get('cursor', None) if cursor is None: return l = clean_line(line, **kw) k = [] if l is None: return None _type, sw, ew, weight, _json = l _json.update({ "relation": _type, "weight": weight, }) values = (sw, ew, _type, weight, json.dumps(_json)) insert_str = '''INSERT INTO word VALUES {}'''.format(values) try: cursor.execute(insert_str) except OperationalError as e: raise e if kw.get('row_index', 0) % 100 == 0: kw.get('db').commit() def fill_apply(line, **kw): l = clean_line(line, **kw) k = [] db = kw.get('db') if l is None: return None _type, sw, ew, weight, _json = l _json.update({ "relation": _type, "weight": weight, }) values = (sw, ew, _type, weight, _json) db.add_line(*values) if kw.get('row_index', 0) % 100 == 0: db.commit() def fill_word_db(kw): db = spread_db(**kw) options = dict( max_count=kw.get('max_count', 100000), iter_line=fill_apply, as_set=True, db=db, keep_sample=kw.get('sample', False), byte_start=kw.get('byte_start', None), byte_end=kw.get('byte_end', None), ) try: d, sample = parse_csv(**options) except Exception as e: log('Error:', e) log(traceback.format_exc()) d = [] db.commit() db.close() return db, list(d) def spread_db(**kw): '''Open many processes with a DB for each. return a unified value of all db's on request. ''' db = WordDB() db.create(open_wait, **kw) db.start() return db class SpreadDBHandle(object): '''A Simple multiprocess gateway to multiple sqlite dbs, each containing the same table structure but maintaining single copies of a record across any thread. ''' def __init__(self, queues=None, pool=None): self.queues = queues self._pool = pool self._step_next = 0 self._dead = False self._q_ordered = None atexit.register(self.terminate) self.quit = self.terminate def create(self, func, count=None, **kw): count = count or cpu_count() m = multiprocessing.Manager() self.queues = [(i, m.Queue(),) for i in range(count)] self._q_ordered = dict(self.queues).values() self.response_queue = m.Queue() _kw = dict( cpu_count=count, # path=None, # auto queues=self.queues, response_queue=self.response_queue, ) kw.update(_kw) self._pool = self.async_spread(func, **kw) self._dead = False def async_spread(self, func, **kw): ''' Generate the jobs and process pool. return a list of Process ''' jobs = job_split(**kw) pool = [] counter = 0 for job in jobs: name = self.process_name(counter) counter += 1 proc = Process(target=func, name=name, args=(job,)) pool.append(proc) log('Spreading {} jobs to pool'.format(len(jobs))) return pool def process_name(self, counter): return "proc-{}".format(counter) def start(self): ''' start a waiting 'create()' _pool. ''' if self._dead is True: log('Previously dead threads must be recreated, SpreadDB.create()') return False for proc in self._pool: proc.start() return True def send_all(self, *a): '''Send one message copied to every process queue ''' for q in self.queues: q[1].put_nowait(*a) def send_next(self, msg): res = self.send_to(self._step_next, msg) self._step_next += 1 if self._step_next >= len(self.queues): self._step_next = 0 return res def send_to(self, index, msg, wait=False): mname = 'put_nowait' if wait is False else 'put' # log('send to', index) return getattr(self._q_ordered[index], mname)(msg) def fetch(self, select_str, args=None): _id = rand_str() v = self.send_all((SELECT, (select_str, args, ), None, _id)) log('Wait on', _id) result = self.loop_wait(len(self._pool), _id) log('\nResult', len(result)) return result def loop_wait(self, count, _id): keep = () snooze = () q = self.response_queue while 1: try: value = q.get_nowait() # log(index, 'Got message', msg) if value[1] == _id: log('Recv a value from', value[0], 'expecting', count, 'got', len(keep)) keep += (value,) else: snooze += (value,) except Empty: pass if len(keep) >= count: break log('Done. Reapplying {}'.format(len(snooze))) for value in snooze: q.put_nowait(value) result = () for index, p_id, results in keep: for row in results: result += (row,) return result def commit(self): self.send_all(COMMIT) def close(self): self.send_all(CLOSE) def terminate(self): '''Hard kill of the threads. ''' for proc in self._pool: proc.terminate() self._dead = True def shutdown(self): '''Clean close of the threads. Sending a kill message and waiting for join''' log('shutdown', self) self.send_all('kill') for proc in self._pool: proc.join() self._dead = True class WordDB(SpreadDBHandle): def __init__(self, queues=None, pool=None): super(WordDB, self).__init__(queues, pool) def add_line(self, start_word, end_word, relation, weight=1, meta=None, commit=True): values = (start_word, end_word, relation, weight, json.dumps(meta or {})) #es_start_word = re.escape(start_word) #es_end_word = re.escape(end_word) insert_str = '''INSERT INTO word VALUES (?, ?, ?, ?, ?)'''.format(values) # # Line one calls the StatementHandler with inline arguments (or None) # line = (INSERT, insert_str, ) # Apply args, kwargs _id = rand_str() line = (INSERT, (insert_str, ) , dict(params=values, commit=commit), _id) return self.send_next(line) def get_word(self, start_word): stmt = 'SELECT * FROM word WHERE start_word = ?' return self.fetch(stmt, (start_word, )) def rand_str(length=10): chars = string.ascii_letters return ''.join([chars[random.randrange(len(chars))] for x in range(length)]) def get_or_create_db(**kw): process_name = multiprocessing.current_process().name cp = os.path.join(os.path.dirname(__file__), '..', 'cache', 'sqlites') bp = kw.get('root_path', cp) fp = os.path.abspath(os.path.join(bp, "sql-{}.db".format(process_name))) log('filepath', fp) db, conn = open_db(fp) if table_exists('word', db) is False: log('Thread {} - creating new table'.format(process_name)) create(db) return db, conn def open_wait(kw): log('Running thread'. index) queues = kw.get('queues', {}) index = kw.get('job_index') queue = dict(queues)[index] db_index = kw.get('job_index', 0) db, conn = get_or_create_db() rq = kw.get('response_queue', None) run = 1 while run: try: msg = queue.get() # log(index, 'Got message', msg) except Empty: pass if msg == 'kill': run = 0 continue result,_id = process_queue_message(msg, db, conn, kw) if (result in [UNDEFINED, None]) is False: if (_id is not None) and (rq is not None): # log('Sending Response from', index, '\n', len(result)) rq.put_nowait((index, _id, result,)) #else: # log('Going nowhere') def process_queue_message(msg, db, cursor, kw): # log('process_queue_message', kw.get('job_index')) # log(kw) result = StatementHandler(db, cursor).call(msg) return result class StatementHandler(object): def __init__(self, db, cursor): self.db = db self.cursor = cursor def call(self, msg): com = msg args = (msg,) kw = {} lm = len(msg) result = UNDEFINED with_kw = True _id = None if lm == 1: # A single statement, such as 'commit' name = "stmt_{}".format(msg[0]) result = getattr(self, name)() if lm == 2: # a type and string. # convert the string into args com = msg[0] args = (msg[1], ) name = "stmt_{}".format(com) with_kw = False if lm == 3: com, args, kw = msg if lm == 4: com, args, kw, _id = msg name = "stmt_{}".format(com) if with_kw is False or (kw is None): result = getattr(self, name)(*args) else: result = getattr(self, name)(*args, **kw) return result, _id def stmt_commit(self, *a): return self.db.commit() def stmt_close(self, *a): return self.db.close() def stmt_select(self, line, params=None, commit=True, fetchall=True): # log('Select statement', line, params) return self.execute(line, params, fetchall=fetchall) def stmt_insert(self, line, params=None, commit=True): return self.execute(line, params=params, commit=commit) def executemany(self, line, params=None, fetchall=True): if params is None: params = () return self.execute(line, params, commit=False, func='executemany') def execute(self, line, params=None, commit=True, func='execute', fetchall=False): # log('Execute', line) try: if params is not None: # log(func, line) getattr(self.cursor, func)(line, params) else: # log(func, line) getattr(self.cursor, func)(line) except OperationalError as e: log('OP ERROR', traceback.format_exc()) log('Line: {}'.format(line)) raise e except ProgrammingError: log('Skipped "{}"'.format(params)) if commit is True: self.db.commit() if fetchall is True: log('fetch') return self.cursor.fetchall() return self.cursor.lastrowid <file_sep>/src/wordnet_use.py from v4.bridge import get_siblings as get from v4.wordnet import get_word, caller, NOUN, VERB, ADJ, ALL app_path = "C:/Program Files (x86)/WordNet/2.1/bin/wn" out_base = "C:\\Users\\jay\\Documents\\projects\\context-api\\context\\src\\data\\wordnet" get = caller(ALL, app_path=app_path, output_dir=out_base) # res = get('egg', to_file=None) # res = get('egg', to_file=False) # res = get('egg', to_file=True) # res = get('egg', to_file='egg.txt') d= get('day') <file_sep>/src/plog/requirements.txt termcolor==1.1.0 <file_sep>/src/plog/__init__.py from .api import Plog <file_sep>/src/v2/core/__init__.py """The core defines a central routine to run input context and cepture out from all context threads Using flask to expose the main entry point as it makes it easier to expose an input thread. Individual threads will boot manually or attached through manual setup """ <file_sep>/src/v5/merge/readme.md Tooling to accept many graphs and analyse weights and other bridges to produce a richer graph for object associations. <file_sep>/src/plog/example.py # Some working samples of plog CDP_DATA = ''' Device ID: SEP001F9EAB59F1 Entry address(es): IP address: 10.243.14.48 Platform: Cisco IP Phone 7941, Capabilities: Host Phone Interface: FastEthernet0/15, Port ID (outgoing port): Port 1 Holdtime : 124 sec Version : SCCP41.8-2-1S advertisement version: 2 Duplex: full Power drawn: 6.300 Watts Power request id: 23025, Power management id: 3 Power request levels are:6300 0 0 0 0 Management address(es): ''' plog = Plog(CDP_DATA) line = PlogLine(header__istartswith='Device ID') PlogLine() PlogBlock() # Usage putty f = open('file.txt') plog = Plog(f) # Usage Cisco CDP f = open('file.txt') cdp = Plog(f) cdp.whitespace = '|' cdp.terminator = ',' # First method of creating a block # Define a line, of which will match the # block header device_line = PlogLine('Device ID', ref='device') # pass the line into a PlogBlock, passing as # the initial argument for __init__ provides # the line as the header_line - all arguments thereafter # are lines to match within the open block # context pb = PlogBlock(device_line) # Finally add the block to all blocks cdp.add_block(header_block) # Shortcut version of appliance. # Define an object within the block namespace. # The name provided for the variable becomes # the ref of the psuedo PlogBlock # The tuple of tuples applied will be in format # # (header_line, terminator # (line, ) # (line, ) # ) # # the first value can be a PlogLine, # or a tuple of (header_line, terminator_line). # Values after are parsed as PlogLinePatterns # to match as lines within the block # Each line is a PlockLinePattern definition or # a tuple for associated types # Terminator is optional, pass no cdp.block.device = ('Device ID') cdp.block.device = PlogBlockPatten('Device ID') # To assist in itteration, create # a block - a repeated element # within the log ''' A PlogBlock is a definition for a single repeated object within your log. Consider a single bash command: $ ls foo bar env readme.md app* ''' #ls_line = PlogLine() #ls_block = PlogBlock(ls_line, ref='ls') #cdp.add_block(ls_block) ''' Parsing logs, may also grab actions to perform take python [ESC], [BS] By applying an action to take when discovering occurances. jjagpal01@JJAGPALPC01 /cygdrive/c/Users/jjagpal01/Documents/projects/morf ''' ''' The short syntax allows the feature to name and define your block within an inline fashion. This is the same as passing a PlogBlock block - required block PlogBlock style string device - becomes PlogBlock ref Passing a reference PlogBlockPatten or a tuple shape will be parsed into a working PlogBlock First object will be the block header cdp.block.device = ( PlogLine('ls') ) ''' # What is Plog ''' Plog is a simple tool to convert log files into a more digestable format. Consider a log file for cisco CDP device readouts. By applying a few simple PlogBlock rules, the file will be converted into a digestable format. A PlogBlock defines a repeated section of your log - Chunking the data into smaller definable bites. A PlogLine defines a single line to detect within the log. You can also apply PlogLines to PlogBlocks for a more defined pattern ''' <file_sep>/src/plog/exampledata.py CDP_DATA = '''Device ID: SEP001F9EAB59F1 Entry address(es): IP address: 10.243.14.48 Platform: Cisco IP Phone 7941, Capabilities: Host Phone Interface: FastEthernet0/15, Port ID (outgoing port): Port 1 Holdtime : 124 sec Version : SCCP41.8-2-1S advertisement version: 2 Duplex: full Power drawn: 6.300 Watts Power request id: 23025, Power management id: 3 Power request levels are:6300 0 0 0 0 Management address(es): ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- Device ID: AH1CMSW07 Entry address(es): IP address: 10.240.14.3 Platform: cisco WS-C3560-24PS, Capabilities: Switch IGMP Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet0/1 Holdtime : 154 sec Version : Cisco IOS Software, C3560 Software (C3560-IPBASEK9-M), Version 12.2(44)SE2, RELEASE SOFTWARE (fc2) Copyright (c) 1986-2008 by Cisco Systems, Inc. Compiled Thu 01-May-08 15:28 by antonino advertisement version: 2 Protocol Hello: OUI=0x00000C, Protocol ID=0x0112; payload len=27, value=00000000FFFFFFFF010221FF000000000000001FC981A380FF0000 VTP Management Domain: 'AH' Native VLAN: 14 Duplex: full Management address(es): IP address: 10.240.14.3 ------------------------- combination of devices, IP phone and switch in this example. Need: Device ID (AH1CMSW07 or SEP001F9EAB59F1) the platform: (WS-C3560-24PS) the software version: (12.2(44)SE2)''' <file_sep>/src/v5/readme.md # Run Run the 'context' as a standard django app. python manage.py runserver Run the graphui for second layer graph analysis calls. A standard flask app. # the graph_ui run.bat run_rev.bat # For the multi-call interface. python double.py # localhost:9005 ## First Accept sentence input, assess and store the breakdown for submission to the second layer. ## Second Analyse a group of words (sentence) to structure an object set of relations, combining data from the graph database and other externals. Produce a lager group of selected _contexts_ leveraging weights and mapping to create an entity for the third layer to study... ## ..+ Third Given a rich dataset of the sentence to contextualise, utilise the data graph content to result actions, events and responses - as per context-api reasoning. Essentially _persist_ sessions for long term usage and graph leveraging. The information is stored as a complex data graphs or some other _burnt-in_ ml format. <file_sep>/src/plog/patterns.py import re class MixinBase(object): ''' Base mixin object of all Plog Mixins to inherit''' def __init__(self, *args, **kwargs): pass class PlogBlockRefMixin(MixinBase): def __init__(self, *args, **kwargs): self._ref=None super(PlogBlockRefMixin, self).__init__(*args, **kwargs) def ref(): doc = "The ref property." def fget(self): return self.get_ref() def fset(self, value): self.set_ref(value) def fdel(self): del self._ref return locals() ref = property(**ref()) def set_ref(self, value): # import pdb; pdb.set_trace() if type(value) == PlogBlock: value = value.ref self._ref = value def get_ref(self): return self._ref class PlogBlockLineMixin(PlogBlockRefMixin): ''' Mixin to help line acceptance on an object''' def __init__(self, *args, **kwargs): self.open_lines = {} self._header_line = None self._footer_line = None self._lines = [] # Hold a cache of line references to be # used against a callback. self.line_refs = [] super(PlogBlockLineMixin, self).__init__(*args, **kwargs) def lines(): doc = "The lines property." def fget(self): return [self.header] + self._lines + [self.footer] def fset(self, value): self._lines = value def fdel(self): del self._lines return locals() lines = property(**lines()) def as_tuples(self): return [(x.ref, x,) for x in self.data] def as_dict(self, _dict=None, exclude=None, include=None): '''Retuns an object defining matched lines''' if exclude is None: exclude = ['footer'] _d = _dict or {} for x in self.data: if x.ref not in exclude: _d.update(**{x.ref: x.clean()}) return _d def header(): doc = "The headerline for the PlogBlock" def fget(self): return self.get_header_line() def fset(self, value): self.set_header_line(value) def fdel(self): self.set_header_line(None) return locals() header = property(**header()) def footer(): doc = "The footerline for the PlogBlock" def fget(self): return self.get_footer_line() def fset(self, value): self.set_footer_line(value) def fdel(self): self.set_footer_line(None) return locals() footer = property(**footer()) def set_header_line(self, plog_line): ''' The header line of the block to validate a start object.''' line = plog_line if type(plog_line) == str: ref = plog_line.ref if hasattr(plog_line, 'ref') else 'header' line = PlogLine(plog_line, ref=ref) self._header_line = line def get_header_line(self): return self._header_line def set_footer_line(self, plog_line): ''' The footer line of the block to validate a start object.''' line = plog_line if type(plog_line) == str: line = PlogLine(plog_line, ref='footer') self._footer_line = line def get_footer_line(self): return self._footer_line def add_lines(self, **kwargs): for ref in kwargs: line = kwargs[ref] if line.ref is None: line.ref = ref else: line._kwarg = ref self.add_line(line) self.line_refs.append({line.ref, line}) def add_line(self, plog_line): ''' Apply a PlogLine to the PlogBlock. If the line is a string, it'll be converted to a PlogLine ''' line = plog_line if type(plog_line) == str: line = PlogLine(plog_line) self._lines.append(line) def valid_line(self, plog_line): ''' Returns object or None to define if the passed plog_line is a valid line within the applied validator lines. If the plog_line passed matches the format of a PlogLine within self.lines, the matching validator line will be returned else None will return. ''' for pline in self.lines: matched, sre_match = pline.match(plog_line) if matched: v = Validator(**{'sre': sre_match, 'line': pline}) return v return None def valid(self): for line in self.data: if line.valid() is False: return False return True class PlogBlockDataMixin(PlogBlockLineMixin): def __init__(self, *args, **kwargs): self.data = [] super(PlogBlockDataMixin, self).__init__(*args, **kwargs) def add_data(self, data, validate=True): ''' Add data to the block (a PlogLine). If validation is True (default) and validation lines have been applied, the value will be validated before data append. If the value does not match a PlogLine format, it will not be added to the data list ''' # If the block has lines. Validate against the # lines to apply value and context. # import pdb; pdb.set_trace() if len(self.lines) > 0: # Receive a validator (Only if data validates # against a line) data.validator = self.valid_line(data) if data.validator: # all open lines are closed, as multiline is terminated by # the success of another validated line self.open_lines = {} # The line validated - are string from the file # has matched the regex pattern of the valid line line = data.validator.line # Provide the reference given to the line data.ref = line.ref # Add the line to multiline open_lines so future data # passed from the file is pushed into an open line if line._multiline and line not in self.open_lines: self.open_lines.update({line: data}) self.data.append(data) return True else: for oline in self.open_lines: olined = self.open_lines[oline] olined.value += '\n' + data.value # import pdb; pdb.set_trace() return True else: return False else: self.data.append(data) return True class PlogBlockFileMixin(PlogBlockDataMixin): ''' A PlogFileMixin is designed to wrap a file object to represent correctly for enumeration. You can pass a string or a file object. Strings are converted to cStringIO.StringIO before use. Pass this to the class for easy get_file, set_file methods ''' def __init__(self, *args, **kwargs): ''' initial file can be given ''' self._file = None self._data = None if len(args) > 0: ''' could be file or string''' self.set_data(args[0]) super(PlogBlockFileMixin, self).__init__(*args, **kwargs) def set_file(self, log_file): ''' Add a file to the class to parse This will return a StringIO if a string was passed as data.''' self.set_data(log_file) def set_data(self, data): ''' wrapper for applying the file content to the class''' if type(data) == str: output = cStringIO.StringIO(data) self._data = output else: self._data = data def get_data(self): return self._data def get_file(self): ''' return the internal file, This will return a StringIO if a string was passed as data ''' return self.get_data() class Validator(object): ''' An object to represent a clean data object ''' def __getitem__(self, v): return self.__dict__[v] def __init__(self, **entries): self.__dict__.update(entries) class PatternBase(object): ''' Base mixin object of all Plog Mixins to inherit''' def __init__(self, *args, **kwargs): super(PatternBase, self).__init__() def re_escape(fn): def arg_escaped(this, *args): t = [isinstance(a, VerEx) and a.s or re.escape(str(a)) for a in args] return fn(this, *t) return arg_escaped class VerEx(PatternBase): ''' --- VerbalExpressions class --- the following methods behave different from the original js lib! - end_of_line - start_of_line - or when you say you want `$`, `^` and `|`, we just insert it right there. No other tricks. And any string you inserted will be automatically grouped excepte `tab` and `add`. ''' def __init__(self, *args, **kwargs): self._multiline = False self.s = '' self.modifiers = {'I': 0, 'M': 0} super(VerEx, self).__init__(*args, **kwargs) def add(self, value): self.s += value return self def regex(self, value=None): ''' get a regular expression object. ''' s = self.s if value is None else value return re.compile(s, self.modifiers['I'] | self.modifiers['M']) def source(self): ''' return the raw string''' return self.s raw = value = source # --------------------------------------------- def anything(self): ''' Accept any value at this point >>> VerEx().anything() ''' return self.add('(.*)') @re_escape def anything_but(self, value): ''' Accept any value, except the value provided. >>> VerEx().anything_but('A-Z0-9') ''' return self.add('([^' + value + ']*)') def end_of_line(self, value=None): ''' this should be appended last of all your called methods if searching for a terminated value. Assert the end of a string at this given point >>> VerEx('foo').maybe('bar').end_of_line() ''' if value: self.then(value) return self.add('$') def multiline(self, v=True): ''' Apply a multiline flag or pass false to remove if multiline is passed, data lines will be appended to the value of the PlogLine until interuppted by a another PlogLine validation or the validation is met ''' self._multiline = True return self @re_escape def maybe(self, value): ''' The value passed is potentially a match >>> VerEx('foo').maybe('bar') ''' return self.add("(" + value + ")?") def start_of_line(self): ''' this is used internally when required. ''' return self.add('^') @re_escape def find(self, value): return self.add('(' + value + ')') then = find # special characters and groups @re_escape def any(self, value): return self.add("([" + value + "])") any_of = any def line_break(self): return self.add("(\\n|(\\r\\n))") br = line_break @re_escape def range(self, *args): from_tos = [args[i:i+2] for i in range(0, len(args), 2)] return self.add("([" + ''.join(['-'.join(i) for i in from_tos]) + "])") def tab(self): return self.add('\\t') def word(self): return self.add("(\\w+)") def OR(self, value=None): ''' `or` is a python keyword so we use `OR` instead. ''' self.add("|") return self.find(value) if value else self def replace(self, string, repl): return self.sub(repl, string) # --------------- modifiers ------------------------ # no global option. It depends on which method # you called on the regex object. def with_any_case(self, value=False): self.modifiers['I'] = re.I if value else 0 return self def search_one_line(self, value=False): self.modifiers['M'] = re.M if value else 0 return self # work in a similar fashion to Django # with an attribute loader for filtering a string, # passed into a regexing lib # Eg: # P(header__istartswith='Device') class PlogPattern(VerEx): ''' Define a pattern to match within a plog line ''' def __init__(self, *args, **kwargs): ''' defined to be a set of attributes to filter the object definition ''' self._ref = None if len(args) > 0: self.__value = args[0] self._cleaned_data = None self._compiled = None self.strip_clean = kwargs.get('strip', True) super(PlogPattern, self).__init__(*args, **kwargs) self.set_ref( kwargs.get('ref', None) ) @property def cleaned_data(self): cl = self._cleaned_data if cl is None: cl = self.clean() return cl @cleaned_data.setter def cleaned_data(self, value): self._clean_data = value @property def compiled(self): if not self._compiled: self._compiled = self.compile() return self._compiled @compiled.setter def compiled(self, value): self._compiled = value def compile(self): ''' ready the matching re regex item for later use. this method considers the current regex start and fixes it accordingly. ''' if self.value == '': self.compiled = None else: self.compiled = self.regex() import pdb; pdb.set_trace() # breakpoint ddd496e8 // return self.compiled def ref(): doc = '''The ref property. A string to define the objects value. A friendly name style''' def fget(self): return self.get_ref() def fset(self, value): self.set_ref(value) return locals() ref = property(**ref()) def set_ref(self, value): self._ref = value def get_ref(self): return self._ref def clean(self): ''' return a clean verson of the string with the regex value stripped ''' if self.strip_clean: val = self.get_value() _validator = self.validator.line.s val = re.sub(_validator, '', val) val = val.strip() self._cleaned_data = val return self._cleaned_data class PlogBlock(PlogPattern, PlogBlockFileMixin): ''' A block of definable content, containing a list of Plog lines. When a PlogBlock is used when commanded for use during the parsing of a file - all lines after are passed into the block as lines associated with it's context. This will occur until a PlockBlock terminator line is parsed of PlogBlock().drop() is called whist context is open.''' def __init__(self, *args, **kwargs): ''' Pass the PlogLine used to validate a header of a given block. The footer_line is optional but would automatically terminate upon a new block. ''' self.is_open = False self.pre_compile = kwargs.get('pre_compile', True) self.missed = [] super(PlogBlock, self).__init__(*args, **kwargs) hl = args[0] if len(args) > 0 else None fl = args[1] if len(args) > 1 else None self.set_header_line(hl) self.set_footer_line(fl) def __repr__(self): ref = self.get_ref() s = self.header.format if ref is None else ref c = len(self.data) return '<%s: \'%s\'~%s>' % (self.__class__.__name__, s, c) def __str__(self): ref = self.get_ref() s = self.header if ref is None else ref c = len(self.data) return "<%s: %s~%s>" % (self.__class__.__name__, s, c) def add_missed(self, pline): self.missed.append(pline) def compile(self): '''Compile the header, footer and line PlogLine's ready to match testing''' if self.pre_compile == True: if self.header: self.header_compiled = self.header.compile() else: self.header_compiled = None if self.pre_compile == True: if self.footer: self.footer_compiled = self.footer.compile() else: self.footer_compiled = None for pline in self.lines: pline.compile() return (self.header_compiled, self.footer_compiled) def open(self): ''' Open the block during file enumeration to begin recieve lines''' self.is_open = True def close(self): self.is_open = False # Device ID: AH1CMSW07 # Entry address(es): # IP address: 10.240.14.3 # Power request id: 23025, Power management id: 3 class DjangoPlogBlock(PlogBlock): ''' Wraps a PlogBlock into a django mode using ref's from field values. ''' def __init__(self, *args, **kwargs): super(DjangoPlogBlock, self).__init__(*args, **kwargs) self.model = kwargs.get('model', None) def _save(self): ''' Save the model returning boolean on success ''' if self.model: val = self.as_dict() return self.model(**val).save() return False class PlogLine(PlogPattern): # Define a line to match based upon it's value '''Define a single line to match''' # method of pattern matching for the regex checking method = 'match' # 'search' def __init__(self, value=None, block=None, *args, **kwargs): ''' Pass block to define the parent block object of this line. This may be None ''' super(PlogLine, self).__init__(*args, **kwargs) self._ref = kwargs.get('ref', None) # the value found on the last match() method call self.matched = None self.validator = None self.value = value if self.value: self.startswith(self.value) self.block = block self.line_no = kwargs.get('line_no', -1) def validator_regex(self, value=None): ''' Return the regex string used to validate the PlogLine or string value. If a validator exists, this is used as the regex, else a string is created from the own value. ''' val = self if value is None else value if type(val) == PlogLine: val = val.value if self.validator: s = self.validator.line.s else: s = self.s return s def valid(self, value=None): ''' Return boolean for validity of the field''' v = self.value if value is None else value reg = self.validator_regex() regex = self.regex(reg) matcher = getattr(regex, self.__class__.method) matched = matcher(v) return True if matched else False def startswith(self, value): self.start_of_line() return self.then(value) def match(self, line): ''' recieve a plogline Return tuple of True/False if the value matches the value and the matched object if one exists. ''' matched = None matcher = getattr(self.compiled, self.__class__.method) matched = matcher(line.value) if matched: groups = matched.group() self.matched = matched.string return (True, matched) else: v = line == self.get_value() return (v, None) def get_value(self): return self.value def set_value(self, value): self.value = value def __str__(self): return 'PlogLine #%s: \"%s\"' % (self.line_no, self.value,) def __repr__(self): return '<%s>' % self.__str__() def __eq__(self, other): return self.value == other <file_sep>/src/v5/context/first/migrations/0001_initial.py # Generated by Django 2.2.3 on 2019-07-27 21:23 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='TemporalInput', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('value', models.TextField(help_text='Input data as a start value.')), ], ), migrations.CreateModel( name='TemporalSession', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('inputs', models.ManyToManyField(to='first.TemporalInput')), ], ), ] <file_sep>/src/v5/context/first/signals.py from django.db.models.signals import pre_save, post_save from django.dispatch import receiver from . import models print('first::signals') import django.dispatch from django.dispatch import receiver pre_save_input = django.dispatch.Signal(providing_args=["instance"]) post_save_input = django.dispatch.Signal(providing_args=["instance"]) tokenized_input = django.dispatch.Signal(providing_args=["instance"]) #@receiver(post_save, sender=models.TemporalInput) @receiver(post_save_input) #@receiver(pre_save, sender=models.TemporalInput) def tokenize_input_instance(sender, instance, **kwargs): """ Store sentence token data. Arguments sent with this signal: sender The model class. instance The actual instance being saved. created A boolean; True if a new record was created. raw A boolean; True if the model is saved exactly as presented (i.e. when loading a fixture). One should not query/modify other records in the database as the database might not be in a consistent state yet. using The database alias being used. update_fields The set of fields to update as passed to Model.save(), or None if update_fields wasn’t passed to save(). """ models.tokenize_input(instance) print('post save', instance) tokenized_input.send(sender=sender, instance=instance) @receiver(tokenized_input) def dictionary_input_instance(sender, instance, **kwargs): """Apply dictionary data to the given instance. """ models.get_dictionary(instance) <file_sep>/src/graph_ui/static/js/main.js var cleanData = [] var bus = new Vue({ }) var words = {} var getWord = function(word, limit=-1){ var enterWord = function(data) { wordView.addWord(data.word, { style: 'root-word' }) let rels = [data.word] for(let [type, word, weight] of data.edges) { rels.push(word) wordView.addRelate(data.word, word, type) } if(data.rev != undefined) { for(let [type, word, weight] of data.rev) { let col = '#AAA'; if(rels.indexOf(word) > -1){ col = '#3355FF' } wordView.addRelate(data.word, word, type, col) } } } if( words[word] != undefined && words[word].limit >= limit ) { enterWord(words[word].data) } let path = `/word/${word}/` if(limit != -1){ path = `/word/${word}/${limit}` } $.get(path, function(data){ words[word] = { limit, data } enterWord(data) }) } //$(function(){ // if ('speechSynthesis' in window) { // speechSynthesis.onvoiceschanged = function() { // var $voicelist = $('#voices'); // // if($voicelist.find('option').length == 0) { // speechSynthesis.getVoices().forEach(function(voice, index) { // console.log(voice); // var $option = $('<option>') // .val(index) // .html(voice.name + (voice.default ? ' (default)' :'')); // // $voicelist.append($option); // }); // // $voicelist.material_select(); // } // } // // $('#speak').click(function(){ // var text = $('#message').val(); // var msg = new SpeechSynthesisUtterance(); // var voices = window.speechSynthesis.getVoices(); // msg.voice = voices[$('#voices').val()]; // msg.rate = $('#rate').val() / 10; // msg.pitch = $('#pitch').val(); // msg.text = text; // // msg.onend = function(e) { // console.log('Finished in ' + event.elapsedTime + ' seconds.'); // }; // // console.log(speechSynthesis); // // speechSynthesis.speak(msg); // }) // } else { // $('#modal1').openModal(); // } //}); <file_sep>/src/v2/conceptnet/parse.py #from log import log import json import csv import os import multiprocessing from multiprocessing import Pool, cpu_count csv_path = 'E:\\conceptnet\\assertions.csv' def job_split(**kw): ''' >>> concepnet.parse.job_split(path=csv_path) [{'start': 0L, 'end': 1071224347L}, {'start': 1071224348L, 'end': 2142448695L}, {'start': 2142448696L, 'end': 3213673043L}, {'start': 3213673044L, 'end': 4284897391L}, {'start': 4284897392L, 'end': 5356121739L}, {'start': 5356121740L, 'end': 6427346087L}, {'start': 6427346088L, 'end': 7498570435L}, {'start': 7498570436L, 'end': 8569794783L}] ''' bytes = os.stat(kw.get('path', csv_path)).st_size count = kw.get('cpu_count', cpu_count()) chunk = bytes / count jobs = [] for i in xrange(count): job = dict( job_index=i, byte_start=chunk * i, byte_end=chunk * (i + 1) - 1, ) job.update(kw) jobs.append(job) return jobs def spread(func, **kw): jobs = job_split(**kw) pool = Pool(len(jobs)) print('Spreading {} jobs to pool {}'.format(len(jobs), pool)) result = pool.map(func, jobs) return result def parse_csv(path=csv_path, max_count=20000, iter_line=None, as_set=False, keep_sample=False, **iter_line_kwargs): global skip_stream start = iter_line_kwargs.get('byte_start', None) end = iter_line_kwargs.get('byte_end', None) if os.path.isfile(path) is False: raise Exception('Parse CSV is not a file: "{}"'.format(path)) stream = open(path, 'rt', encoding='utf-8') if start is not None: stream.seek(start) print( next(stream)) if end is not None: print('Seek from {} to {}'.format(start, end)) count = 0 pc = 0 res = () if as_set is not True else set() samples = () skip_stream = open('./skips.csv', 'w') func = iter_line or clean_line print('Reading {} maximum lines'.format(max_count)) for raw_line in stream: line = next(csv.reader((raw_line,), delimiter='\t')) if max_count is not None and count > max_count: break dval = func(line, parser_index=pc, **iter_line_kwargs) if dval is None: if line[1] == '/r/ExternalURL': continue s = '/c/en/' if line[0][2].startswith(s) is True and line[0][3].startswith(s) is True: import pdb; pdb.set_trace() # breakpoint 1073775b // if as_set is True: res.add(dval) if keep_sample is True and len(res) > len(samples): s = '/c/en/' if line[2].startswith(s) is True and line[3].startswith(s) is True: samples += (line,) else: res += (dval,) count += 1 pc += 1 if end is not None and stream.tell() > end: print('Hit limit') break if pc > 100000: pc = 0 print( 'count', count) stream.close() skip_stream.close() return res, samples postfix_map = { "n": "noun", # /n "v": "verb", # /v "a": "adjective", # /a "s": "adjective satellite", # /s "r": "adverb", # /r } POSTMAP = postfix_map.keys() def clean_line(line, **kw): '''Return a cleaned CSV line as a tuple ''' try: uri, rel, start, end, js = line except ValueError as e: skip_stream.write('{}\n'.format(line)) uri, rel, start, end, js = None, None, None,None,None if rel == '/r/ExternalURL': return None if start is None: return None startl = start[3:5] endl = end[3:5] startw = start[6:] endw = end[6:] sub_rel = rel[3:] langs = ['en'] sl = startw[:-1] el = endw[:-1] if (startl in langs) is False or (endl in langs) is False: return None if js is None: return None _json = json.loads(js) weight = _json['weight'] _json['start'] = dict(lang=startl, word=startw) _json['end'] = dict(lang=endl, word=endw) if sl in POSTMAP: _json['start']['synset'] = postfix_map[sl] if el in POSTMAP: _json['end']['synset'] = postfix_map[el] del _json['sources'] if 'dataset' in _json: del _json['dataset'] if 'license' in _json: del _json['license'] _json['id'] = uri return (sub_rel, startw, endw, weight, _json) <file_sep>/readme.md # Context View Reader thing Render word associations and build context with words Mostly (now) using conceptnet for word DB. the online DB is wrapped into the ui and engine. Each request returns a json to read and parse. Caching provides some fallback. ## run At the momenet it's a bit scratchy. The requirements.txt provides the install elements required. They're mostly websockets and nltk. Quick run on windows ```bash cd C:\Users\jay\Documents\projects cd context-api env\Scripts\activate context\run.bat & cd context\src python main.py ``` ## Running tests nose or pytest or anything is fine. Note my python 3 install doesn't catch pytest. In the 'database/' smaller tests apply: > py -m pytest -sv database/ ### Websocket server start the websocket server for communicating to the UI and coms. $> python server/ws.py info :: Listen on 127.0.0.1 8009 This is a simple server for echoing JSON across clients. The web interface will connect to the websocket though the address given through through the CLI. you can connect a websocket client to this address to received parse data from the engine. ### Client UI (browser) The client reader `server/index.html` will read and parse the incoming client data from the engine. open in the browser - you can simply run the file. file://path/to/server/index.html You can serve this from a python app. A simple socket server will also work. $ server/ > python -m http.server $ server/ > python -m SimpleHTTPServer Due to cross-origin domain policies, The server should match the client and the connecting sockets. It's easy enough to serve it all from localhost or 127.0.0.1 The socket server should host the same address as the client file. Anyhoo - I host another server for the client file: $> server/ > python -m http.server 127.0.0.1:8000 ### Python Engine Next talk to the main app. It's called the 'engine' because I don't care what it is yet. So it runs stuff - that's an engine. $> python -i main.py --- The main CLI is a loop, sending strings to `assess_string`. Each word is cached for saving api questions to the online conceptnet. ### Command line A few tools are built into the console input. Normally you'll input words as statements for the context to assess. Apply a command paramter at the start of the string can perform python actions on the running context. The exclaimation mark `!` at the start of a string will run the string as python. What? !__file__ It runs `eval` on the statement, printing the output. It's not a primary tool, so it's not something to rely upon. However in development, you can utilze this to update running modules without restartingt the cli. Change a python source module whilst in use - in this example we reload the `secondary_functions` module. We proceed through `primary_functions` reference to this module: What? cake ... assessing "cake" // Alter python source, uppercase the assess log. What? !reload(primary_functions.secondary_function) <module secondar..> What? cake ... ASSESSING "CAKE" The hash or _pound_ symbol `#` (Pound: _£_) will run baked commands built into a python API. For example to delete a word from context: What? #delete cake To stop external API fetching use `#fetch off`. or `#fetch on` to reapply. ### MIT ConceptNet Some elements are build upon the ConceptNet graph. The online api or a docker box can be connected. The docker instance needs to be built. Then accessed through the web-interface on a booted concept_net_5 docker instance: http://192.168.99.100:8007/c/en/hello Or the remote address: http://api.conceptnet.io/c/en/hello ## Notes This is like version... 5? of Sadie's temporal conceptnet. The loss of the old net was a hard lesson in temporal storage over distributed data. + Temporal data record and parse + Soft distribution of context + Slow conceptual analysis of spread b-tree / merkle. Noted research completes most of the components to drive. Over the years (from sadie 3) I've studied a lot of the extra parts. And a lot of the hardare is cheaper. + Distributed data storage + temporal memory records + text to speech + speech to text + Built in python ## Concept More write-ups exist in the other docs (and backup notes\*) - Driving a _concept_ of given entities through slow nanny of word driven object records. Allowing a _conceptual_ references of objects. The association are easy to build. Building a reference: > the cat is blue > blue is a colour > a cat is an animal ? what colour is the cat < blue Through reference this can also be `what color is an animal` - but this is a very high-level concept of the driving engine. ### The Dream Alike many humans, I'd like a machine to talk to. This _contextnet_ will (hopefully) drive the temporal memory of context for a relative dialog. Consider you environment and its relative attributes. Or to state again - The room and the stuff in it. We simply understand "that chair" or "the other room". but to derive the understanding of "that chair" you know of "a chair", "my chair" or the abstracted "other [item]". If we have a list of all chairs, and understanding the associations of "my" or "other" - we're done! We have a reference point. This is a tedious example of my enjoyment with this project. Building a layer of context, driven through _words_ alone. The result is a giant tree of associations being updated by new words. ### Progress This has been in working progress for nearly 7 years now. By now I considered this idea dead - with the incoming technologies such as deep learning and machine learning. However many years on and trying a bunch of methods - I'm still back on this idea. Mapping the progress of ideas to show functionality why this may work. #### First Versions Version 1 defined a mapping of all communicated words and (essentially) built a spell check dictionary - but this had problems with cross referencing words I quickly discovered the need for distributed computing with the requirement to cross reference massive lists. In addition the _single core_ concept didn't scale, there one word computed per app cycle is pointless. Versions 2 and 3 hit the same computational blocks. Memory consumption killed any attempts at referencing small words such as 'tree'. The data-feeds were online corpus, but they did not suite the type of training I wanted. I needed to learn more about databases, threading, lower-level languages, distributed machinery. Some years missed, included maths class, AI studies and distributed computing - but the classes didn't help - and getting a job in the field helped. #### Version 4 With slow nanny training over months/years - I had driven a stable version of the cross referencing context. By carefully communicating to an active b-tree, associations were built upon my (long studied) input word by word. I feel it cheated as I loaded a lot more trained data via text files for word types for machine understanding - such as "if" and "is". Then they ran independent and _hardcoded_ functionality. I found this ugly, but it did help with short-cutting word relationship management: After every sentence input, any unknown word was input requested: > operator < machine # machine comment // example machine work --- > I like cake # Computing input # reference "cake" - // Machine input Wiki // building concepts into data format b-tree: 159 branches. < what is cake? > cake is food < what is food? > food is edible # found "edible" reference # cake is edible So with slow input over every word, I carefully mapped out reference chains for word association. It was painfully slow - sometimes taking hours for b-tree referencing. The b-tree referencing was interesting in itself; by inspecting a wiki - such as a corpus of knowledge from wordnet, all words associated were bound to a weighted tree. Every new word reference was checked against the existing trees for a cross reference. If a match exists, such as "tree > leaves > leaf > green" a weighting core denotes its preferred usage. Once the machine has scored this path (by distance mostly), higher weighted paths are kept. This is recursive until all paths are exhausted and the winning path denotes a 'true' reference path. A fully populated tree contains a 'context' session for the entity, such as a 'cake' reference. Some properties are required + who - who or what owns the cake. Its spacial reference or owner such as a box + what - what is the cake. Its categories such as 'food' + where - where is the cake relative to the owner. such as "in" the box. The machine extrapolates questions to populate this session of information about the referenced cake. As an example from a previous conversation, in reference to music: > operator < machine # machine comment // example machine work --- > music < what is music? > music is recreational audio < what music is recreational audio? > this is rap music < is rap music funny? To understand the depth of the machine questions here - it helps to know what words are loaded and how it asks questions. The operator (me) gave the string "music" knowing the machine has never seen it. This will prompt the query phase. The machine distinctly asks for "music". The _hardwire_ of this function notes anything after _"what is ..."_ as the variable in question. In return a similar context of "music is" helps mat the answer. Alternatively changing "music is recre..." with "it's recrea..." - may not have worked due to the inflections and relative position of 'it'. However "this is rap music" I applied knowingly - ensuring the machine enact the _local context_ or relative references local the session; "this". So which the machine asks "what music is recreational audio" - it already had associations of 'audio' and 'recreational' else those questions would have come first. The entire query requested the a distinction of music and recreational music. And that's a win. Applying 'rap music', in reference to "this" pushed the 'rap music' into a reference of local determiners "this", "I", "here" etc... so the finished path exists in the references kept for _now_. In addition, applying 'rap' and 'music' defined an association if 'music' again. This will affirm the path when the machine discovers two clean paths to 'rap'. At this point, the machine cross references the new word 'rap' (with some association to 'music'). Previously a scrap or entry defined rap-music as 'rhythmic beats' or 'rhymes' due a plural to singular translation map using an off-the-shelf library. Rhymes can be funny, hence the reference `rap > rhymes > humor > funny`. Again some leaps are taken with the tree steps, but when the data is scrapped, more references to another work gains weight. 'humor' is found against 'rhymes' and 'poem' a lot. --- The machine attempts to fill a gap with the first solid path it found. Previous training sessions build full models of 'poem' and other such words - they have become strongly weighted nodes in the tree of words through these paths. At this point, the machine affirms or concludes a path based upon operator input. At this point I can answer in the positive or negative, keeping this path or destroying it. _At the time, being a metal fan, I laughed at the invention of a funny computer and answered "yes"._ <file_sep>/src/wordnet/app.py '''Use berkley key assoc exe app as a data input by reading STDOUT of a windows cli tool.''' import os import subprocess from typemap import noun, verb, adj, attrs ALL = noun.keys() + verb.keys() + adj.keys() def caller(params=None): params = params or [] base_path = "C:\\Program Files (x86)\\WordNet\\2.1\\bin\\wn" out_base = "C:\\Users\\jay\\Documents\\projects\\context-api\\context\\src\\data\\wordnet" def perform_call(word, additional_params=None): ams = additional_params or [] switches = ' -'.join(list(set(params + ams))) ps = '-'.join(params) filepath = "{}-{}.txt".format(word, ps) out = os.path.join(out_base, filepath) st = '"{app}" {word} -{switches} > "{out}"' call_str = st.format(app=base_path, word=word, switches=switches, out=out) print(call_str) res = subprocess.run(call_str.split(' '), capture_output=True) import pdb; pdb.set_trace() # breakpoint 6cb0fec2 // return perform_call <file_sep>/src/v3/cli.py ''' Some simple functionality to expose the 'assess_string' functionality to the CLI with. run `ask_loop` with a callback function. All CLI input is first checked against a set of internal commands. IF the string is clean the callback is called with a string sentence. Command class allows exposure of functionality rather than strings for assessment. provide "#list" to see all available commands ''' import os import contextnet_api as cnapi # from logger import print_edges import words from cache import set_global_root import cache # import secondary_functions #import loop from json_socket import make_socket import logging logging.basicConfig(level=logging.DEBUG) def log(*a): logging.info(' '.join(map(str, a))) warn = logging.warn queue = None loop_data = None class Command(object): def __init__(self): log('\n\n---- Command function intervention applied.----\n\n') log('\nType #list for actions\n') def command_mode(self, command): _map = { "!": 'eval', "#": "hash", } comt = command[0] com = command[1:] mc = _map[comt] name = "com_{}".format(mc) log('Received command "{}"'.format(mc), name) if hasattr(self, name): return getattr(self, name)(com) def com_eval(self, com): ret = eval(com) log(ret) return ret def com_hash(self, com): coms = map(str.strip, com.strip().split(' ')) com0 = coms[0] name = "hash_{}".format(com0) if hasattr(self, name): return getattr(self, name)(*coms[1:]) def hash_list(self): """print a list of available commands""" v = [x[5:] for x in dir(self.__class__) if x.startswith('hash_')] log('available commands: {}'.format(', '.join(v))) def hash_die(self): '''Send a kill message''' log('Killing...') assess_string('kill') loop.kill_processes() log('Death complete.') def hash_start(self): log('Start Procs') loop.start_procs(queue, **loop_data) def hash_fetch(self, value=None): positive = ['true', 'yes', '1', 'on'] negative = ['no', '0', 'false', 'off'] lv =None if value is not None: lv = value.lower() switch = True if lv in positive else None switch = switch or (False if lv in negative else None) if switch is None: log('Fetch is currently:', allow_external()) return log('Allow external data fetch: ', switch) allow_external(switch) def hash_delete(self, word): log('Delete word', word) log(cache.delete_word(word)) def hash_cache(self, word): cnapi.api_fetch(word, allow_cache=False, _force_allow=True, limit=50) def hash_read(self, data_file): '''given the name of a data file within the initial data folder, read each line into the ask loop. ''' fn = '{}'.format(data_file) fpf = os.path.join(os.path.dirname(__file__), 'data', fn) log('read', fpf) if os.path.isfile(fpf): log('Slow reading', fpf) ts = 5 with open(fpf, 'r') as stream: try: for line in stream: word = line.strip() log('Asking', word) assess_string(word) log('sleeping', ts) time.sleep(ts) except KeyboardInterrupt: log('cancelled slow feed') def allow_external(bool=None): if bool is not None: cnapi.FETCH_ALLOWED = bool return cnapi.FETCH_ALLOWED def init(socket_uri="ws://127.0.0.1:8009"): ''' A initialisztion function for anything requiring a first boot. ''' global command global loop_data global queue # global socket # if socket_uri is not None: # socket = make_socket(socket_uri) command = Command() basepath = os.path.abspath(os.path.dirname(__file__)) #cache_path = os.path.join(basepath, 'cache') #set_global_root(cache_path) #loop_data = dict(socket_uri=socket_uri, cache_path=cache_path) #ask_loop() # queue, procs = loop.init_thread(**loop_data) def _base_boot(socket_uri="ws://127.0.0.1:8009"): basepath = os.path.abspath(os.path.dirname(__file__)) cache_path = os.path.join(basepath, 'cache') #set_global_root(cache_path) COMMAND_STR = '!#' def ask_loop(callback): _run = True kill = False while _run is True: v = raw_input('\nWhat?: ') if v == '': log('Close _run') _run = False else: if v == 'kill': log('Loop kill in process') kill = True assess_string(v, callback) if kill is True: _run = False log('Killing processes') loop.kill_processes() log('Finish askloop') def assess_string(sentence, success_callback=None): ''' Given an input string, token and assess each token. ''' if sentence[0] in COMMAND_STR: return command.command_mode(sentence) log('primary_functions assess_string') if queue is not None: queue.put_nowait(sentence) if success_callback is not None: success_callback(sentence) # return secondary_functions.apply_to_context(sentence) <file_sep>/src/v3/init_graphing.py from collections import OrderedDict class SentenceList(object): '''Incoming strings for temporal streams can be defined as a sentence. Opening and closing a sentence pushes the unique sentence graph to the next stage. ''' def __init__(self): self.lists = {} def open(self): key = "list-{}".format(len(self.lists)) self.lists[key] = {'given_words': () } return key def append_word(self, list_key, value): pos_key = len(self.lists[list_key]['given_words']) print 'adding', value, 'to sentence', list_key # linear stack # self.lists[list_key][value]['given_words'] += (value, ) return pos_key temporal_list = SentenceList() def open_temporal(): """Expecting a stream for temporal capture of a sentence or linear context. Ready the graphing for incoming data and return an identification key to be given during stream. """ _id = temporal_list.open() print 'open temporal {}'.format(_id) return _id def add_word(temporal_key, word): '''push the word into the current sentence''' word_id = temporal_list.append_word(temporal_key, word) # The word is in the sentence for other awareness; now # we work with the word, and write-back to the given reference. # Literal translate: # Convert the given word to a hard-coded coversion to another word. # For example "i" to "I" and inflections "Haven't" "Have Not" # # In some cases (such as inflections) the translation can be derived from # training and data learning. By applying a small graph for "n't" # and pushing that into the secondary graphing, it can be soft-coded. # <file_sep>/docs/writes/auto graph matching.md When a word or temporal sentence is in context an existing graph may exist in a pre-computed sandbox of graphs (such as a module), and can assist with contextual information. The sentence "I only need a few" - defines a request for a small number of _the_ items. Namely three items. The system will alsoready maintain a 'number' module and graph - working its own procedures to flag cardinal numbers within a temporal input stream. The reasoning or weighting module will utilize the given meta data regarding 'few' and note it's value of 'three' `3`. The 'number' graph is available to all other modules/graphs for referencing. When a word , such as 'few', 'count' or 'one' reside within the 'number' graph. Using a word connected to the graph should automatically event flag some usage; along with a primary weight for the reasoning to understand. When an entire graph is generated by another module or some event, this 'number' graph reacts with an event. When applying "I have some maybe more", the words 'some' and 'more' a edgenodes within the 'number' graph. It should fire events and pepper meta data into the strings _current context_ <file_sep>/src/v5/context/first/models.py from django.db import models import nltk from . import dictionary import sys from . import infl def tokenize_input(input_model): value = input_model.value t = nltk.word_tokenize(value) # ['I', 'like', 'cake'] tokens = nltk.pos_tag(t) # [('I', 'PRP'), ('like', 'VBP'), ('cake', 'VB')] pms = () for index, (word, tag) in enumerate(tokens): tagm, created = Tag.objects.get_or_create(value=tag) if created: tagm.save() pw, created = PositionTokenWord.objects.get_or_create( position=index, value=word, tag=tagm, ) if created: pw.save() pms += (pw, ) print(f'Writing: {len(pms)} to "{input_model}"') input_model.tokens.add(*pms) #input_model.save() def get_dictionary(input_model): words = input_model.tokens.all() for word in words: print('Fetching word', word) res = dictionary.get_word(word.value) word.raw_dictionary = res sibs = infl.get_siblings(word.value) tense, created = Tense.objects.get_or_create( plural=sibs['plural'], plural_noun=sibs['plural_noun'], plural_verb=sibs['plural_verb'], plural_adj=sibs['plural_adj'], singular_noun=sibs['singular_noun'], present_participle=sibs['present_participle'], ) if created: tense.save() word.tense = tense for key in res: # meaning, synonym, antonym if key == 'value': continue if res[key] is None: print(f'Dictionary Key "{key}" is None for {word}') continue # meaning, synonym, antonym deft, created = DefinitionType.objects.get_or_create(value=key) if created is True: deft.save() # Noun, Adjective if isinstance(res[key], dict): for val_type in res[key]: # 'done with delicacy and skill', for dictionary_str in res[key][val_type]: defvt, created = DefinitionValueType.objects.get_or_create(value=val_type) if created is True: defvt.save() df, created = Definition.objects.get_or_create( associate=deft, type=defvt, value=dictionary_str) if created is True: df.save() print(f'Applying new definition {df}') word.dictionary.add(df) elif isinstance(res[key], list): defvt, created = DefinitionValueType.objects.get_or_create(value='undefined') if created is True: defvt.save() for dictionary_str in res[key]: df, created = Definition.objects.get_or_create( associate=deft, type=defvt, value=dictionary_str) if created is True: df.save() word.save() class Tag(models.Model): value = models.CharField(help_text='Word', max_length=255) def __str__(self): return self.value # { # 'value': 'nice', # 'meaning': { # 'Noun': [ # 'a city in southeastern France on the Mediterranean; the leading resort on the French Riviera' # ], # 'Adjective': [ # 'pleasant or pleasing or agreeable in nature or appearance', # 'socially or conventionally correct; refined or virtuous', # 'done with delicacy and skill', # 'excessively fastidious and easily disgusted', # 'exhibiting courtesy and politeness' # ] # }, # 'synonym': None, # 'antonym': None} class DefinitionType(models.Model): value = models.CharField(max_length=255) def __str__(self): return self.value class DefinitionValueType(models.Model): value = models.CharField(max_length=255) def __str__(self): return self.value class Definition(models.Model): associate = models.ForeignKey(DefinitionType, on_delete=models.DO_NOTHING) type = models.ForeignKey(DefinitionValueType, on_delete=models.DO_NOTHING) value = models.TextField() def __str__(self): return f'{self.associate}, {self.type}, {self.value}' class Tense(models.Model): plural = models.CharField(max_length=255, null=True, blank=True)#('we'), plural_noun = models.CharField(max_length=255, null=True, blank=True)#('we'), plural_verb = models.CharField(max_length=255, null=True, blank=True)#('I'), plural_adj = models.CharField(max_length=255, null=True, blank=True)#('I'), singular_noun = models.CharField(max_length=255, null=True, blank=True)#(False), present_participle = models.CharField(max_length=255, null=True, blank=True)#('Iing'), class TokenWord(models.Model): value = models.CharField(help_text='Word', max_length=255) tag = models.ForeignKey(Tag, on_delete=models.DO_NOTHING) created = models.DateTimeField(auto_now_add=True, blank=True, null=True) raw_dictionary = models.TextField(blank=True, null=True) dictionary = models.ManyToManyField(Definition) tense = models.ForeignKey(Tense, blank=True, null=True, on_delete=models.DO_NOTHING) def __str__(self): return f"{self.value} - {self.tag}" class PositionTokenWord(TokenWord): position = models.SmallIntegerField() #tokenword = models.ForeignKey(TokenWord, on_delete=models.DO_NOTHING) def __str__(self): return f"({self.position}) {self.value} - {self.tag}" class TemporalInput(models.Model): """In the firt layer a temporal input defines content (a string) from the user to train up. Each _sentence_ is a layer0 type. """ value = models.TextField(help_text='Input data as a start value.') created = models.DateTimeField(auto_now_add=True, blank=True, null=True) tokens = models.ManyToManyField(PositionTokenWord, blank=True)#, on_delete=models.DO_NOTHING ) def __str__(self): return self.value class TemporalSession(models.Model): """Group many inputs to a session. """ # The list of assigned inputs. inputs = models.ManyToManyField(TemporalInput) def __str__(self): return f"TemporalSession of {self.inputs.count()} inputs" <file_sep>/src/v2/log.py import logging logging.basicConfig(level=logging.DEBUG) def log(*a): logging.info(' '.join(map(str, a))) warn = logging.warn <file_sep>/docs/writes/init memory graphing.md For building memory, there seems to be a few core stages + initial sentence graphing + immediate contextual cross-referencing + best fit sentence weighting + abstraction for response. The entire goal of the api should be 'to attain knowledge', allowing more graphing and stronger context connections. This should be achieved through a process of elimination for sentences (temporal graphed concepts) for a finished context object. We can consider a _single complete context reference_ as a dictionary of waiting values. The keys to the _abstract_ dictionary are definined and populated through cross referecing graphing. When graphing fails for a context - a deeper search for context will being. At some point an entropy number should stop this. In forwarding cases, the contextual filling mechanism should be automated, allowing long exposure to an concept graph - with a governing AI driving corrections (adverserial ML network). ## Initial sentences Each terporal string - we can define as a sentence - keeps a graph of context for a string of associated string; "I like my cat". The sub word graphing is kept in memory and used for cross-referencing other sentences. It's more explicitly a 'temporal string' as the information may not strictly be a single sentence. Potentially it's a fuzzy mix of speech to text/ "I like food but I love my cat lets make fish!" is a simple example of three statements and a command. This could be broken into distinct sentences "I like food. But I love my cat. Let us make pasta." - forgive the crummy grammar but it's easier to understand - this is 3 reference trees and 2 sentences in one temporal string. + A single temporal string is stord as a base for a context graph + storing many context graphs in a sentence list for contact referencing ## Immediate cross-referencing As a sentence is given, each change to the temporal string should yield a new graphing within the single context reference. For each new graph the weghting should be asserted against all immediate context graphs within the sentence. The winning graph provides the stored abstract of the temporal string and a sentence. For example: "do this before that" applies a command at the end of the sentence, yielding a complete change of context for the incoming sentence. Competing graphs would finalise as "do <that>, then <this>". As this is cross-referenced against the immediate tree, `this` and `that` should have context. If not - an _abstraction for response_ is required. ## Best fit sentence weighting Each temporal string has a permanent weight and a transient weight per context (or other temporal string). A Temporal string may be broken down into smaller graphs and sub graphs, noting many context objects within a sentence. For an incoming temporal string, the transient weighing is applied for all given context objects. All other contexts are weight graphed for their potential fit to the given temporal string. The general winner will be the context with the greatest weight. Given a string: "I like my dog" then "But I prefer my cat" - will change the given preference of animal to cat over dog. The first sentence "I like my dog" is a relatively simple statement of preference. This would graph into a Sentence with one statement of intent and 4 sub-graphs (and and recursive graphs). The weighting for "I" LIKE/PREFER "dog" is high. The next "But I prefer my cat" should naturally assign a greater weight, given 'prefer' is greater than 'like' in an abstract sense. In addition, as this _Sentence_ is _temporally connected_ to the first statement - an antonym weighting "but" should drive the context circuit enough. With "But" and "prefer" massing a greater weight over "like", "dog" the two distinct sentences (in this case two temporal strings) - the second sentence will change the overall transient state of all graphs, applying the preference as a permanency into the next major context graph. ## Abstraction for Response Probably the most challenging aspect of the overall design and automated _filling_ of context data. The general goal to 'object' the enviroment context defines some simple requirements per 'object' A Cup: * Who owns * What is * When was * Where is * Why a cup This WWWWW concept is the initial idea to drive _completion_ of context for a given unit. The naming here helps for readability but to quantify; For a given _thing_ we need to know if it's apart of our environment. We can keep the object in context to our associated _other things_ - mandated _knowledge_ should be "where is it" and "who owns it" Once operational, we can walk the graph, back-referencing other context objects to infer transient knowledge or request new knowledge. Requesting new knowledge or **Abstracting** some context from the outbound API and expecting a temporal response relative to this context. #### Full graph With full graphing, offering information after a statement yielding an already existing graph of [dog]: OP: "I cannot find my dog" CTX: "Your dog is in the kitchen" As the location (Where is) of the dog is loaded into the most recent "dog" context. The 'my dog' yields a subset (of one) dogs to define. #### Empty Graph Graphing of a brand new object for reference requires population of sub categories or "context associations" before a "full graph" goal is complete. With a given temporal input, an immediate dialog persists the Sentence with contextual information about the market. Again simply persisting the WWWWW concept should fill enough graph for contextual referencing OP: I went to the market CTX: When did you go to the market OP: Yesterday CTX: Which market OP: The local one CTX: To buy [produce] fruit The machine needs a time of 'went' (When), a location (Where) and a reason (Why). The log displays a fault with the training - where 'fruit' was the top weight for a market. The context graph should refer to any market 'produce' - In later work this should be inferred from a recursive inspection of relative products from an _immediate historic graph_ #### Infer Completion Through temporal monitoring of an incoming stream, inference of the _next_ expected word - a lot like an AI phone keyboard. OP: "My car is" ... CTX: a color blue CTX: In the car-park In this case, "My car" has no context, therefore a previous knowledge of a finishing result doesn't exist. Instead from the already cached evaluations of 'car' with context to 'my' - 'is' yields example queries previously used reference strings. This allows prediction of future conversations and caching potential values for response. With persona referencing "I" and "my" a graph of the OPerator provides a personal attribution. <file_sep>/src/v1/loop.py import time import os from multiprocessing import Process, Queue from cache import set_cache, string_cache, set_global_root from Queue import Empty import secondary_functions from json_socket import make_socket, send_json, get_socket session = {} socket = None procs = None def main(): init_thread() def init_thread(*args, **kw): q = Queue() procs = start_procs(q, *args, **kw) return (q, procs,) def start_procs(q, *args, **kw): global procs procs = create_procs(q, *args, **kw) proc, socket_proc = procs print 'starting procs' proc.start() socket_proc.start() return procs def create_procs(q, *args, **kw): proc = Process(target=init, args=(q, ) + args, kwargs=kw) socket_proc = Process(target=socket_init, args=(q, ) + args, kwargs=kw) return (proc, socket_proc,) def kill_processes(): for proc in procs: print 'Joining', proc proc.join() def socket_init(queue, *a, **kw): global socket print 'socket_init', kw['socket_uri'] socket_uri = kw.get('socket_uri', None) print 'init socket' socket = make_socket(socket_uri) run = 1 while run: print '?', message = socket.recv() if message is not None: print '!', len(message) if message == 'kill': print 'socket kill pill' queue.put_nowait(message) run = 0 continue print 'Finish socket' return socket def init(queue, **kw): ''' A initialization function for anything requiring a first boot. ''' socket_uri = kw.get('socket_uri', None) cache_path = kw.get('cache_path', None) # global socket # if socket_uri is not None: # print 'Making loop socket' # socket = make_socket(socket_uri) print 'Init main loop' basepath = os.path.abspath(os.path.dirname(__file__)) set_global_root(cache_path) secondary_functions.init(socket_uri=socket_uri) start(queue, socket_uri=socket_uri) def start(queue, socket_uri=None): run = 1 while run: message = None try: message = queue.get_nowait() print '.', except Empty: time.sleep(.2) if message == 'kill': run = 0 if socket_uri is not None: socket = make_socket(socket_uri) socket.send('kill') continue run = step(message) print 'End Stepper' def step(given_data=None): '''continuous call by a loop''' if given_data is not None: print 'Loop react', given_data secondary_functions.apply_to_context(given_data) return 1 if __name__ == '__main__': main() <file_sep>/src/data/info.md # noun a word (other than a pronoun) used to identify any of a class of people, places, or things ( common noun ), or to name a particular one of these ( proper noun ). # pronoun noun a word that can function as a noun phrase used by itself and that refers either to the participants in the discourse (e.g. I, you ) or to someone or something mentioned elsewhere in the discourse (e.g. she, it, this ). # hypernym noun plural noun: hypernyms a word with a broad meaning constituting a category into which words with more specific meanings fall; a superordinate. For example, colour is a hypernym of red. --- adjective cluster A group of adjective synsets that are organized around antonymous pairs or triplets. An adjective cluster contains two or more head synsets which represent antonymous concepts. Each head synset has one or more satellite synsets . attribute A noun for which adjectives express values. The noun weight is an attribute, for which the adjectives light and heavy express values. base form The base form of a word or collocation is the form to which inflections are added. basic synset Syntactically, same as synset . Term is used in wninput(5WN) to help explain differences in entering synsets in lexicographer files. collocation A collocation in WordNet is a string of two or more words, connected by spaces or hyphens. Examples are: man-eating shark , blue-collar , depend on , line of products . In the database files spaces are represented as underscore (_ ) characters. coordinate Coordinate terms are nouns or verbs that have the same hypernym . cross-cluster pointer A semantic pointer from one adjective cluster to another. derivationally related forms Terms in different syntactic categories that have the same root form and are semantically related. direct antonyms A pair of words between which there is an associative bond resulting from their frequent co-occurrence. In adjective clusters , direct antonyms appears only in head synsets . domain A topical classification to which a synset has been linked with a CATEGORY, REGION or USAGE pointer. domain term A synset belonging to a topical class. A domain term is further identified as being a CATEGORY_TERM, REGION_TERM or USAGE_TERM. entailment A verb X entails Y if X cannot be done unless Y is, or has been, done. exception list Morphological transformations for words that are not regular and therefore cannot be processed in an algorithmic manner. group Verb senses that similar in meaning and have been manually grouped together. gloss Each synset contains gloss consisting of a definition and optionally example sentences. head synset Synset in an adjective cluster containing at least one word that has a direct antonym . holonym The name of the whole of which the meronym names a part. Y is a holonym of X if X is a part of Y . hypernym The generic term used to designate a whole class of specific instances. Y is a hypernym of X if X is a (kind of) Y . hyponym The specific term used to designate a member of a class. X is a hyponym of Y if X is a (kind of) Y . indirect antonym An adjective in a satellite synset that does not have a direct antonym has an indirect antonyms via the direct antonym of the head synset . instance A proper noun that refers to a particular, unique referent (as distinguished from nouns that refer to classes). This is a specific form of hyponym. lemma Lower case ASCII text of word as found in the WordNet database index files. Usually the base form for a word or collocation. lexical pointer A lexical pointer indicates a relation between words in synsets (word forms). lexicographer file Files containing the raw data for WordNet synsets, edited by lexicographers, that are input to the grind program to generate a WordNet database. lexicographer id (lex id) A decimal integer that, when appended onto lemma , uniquely identifies a sense within a lexicographer file. monosemous Having only one sense in a syntactic category. meronym The name of a constituent part of, the substance of, or a member of something. X is a meronym of Y if X is a part of Y . part of speech WordNet defines "part of speech" as either noun, verb, adjective, or adverb. Same as syntactic category . participial adjective An adjective that is derived from a verb. pertainym A relational adjective. Adjectives that are pertainyms are usually defined by such phrases as "of or pertaining to" and do not have antonyms. A pertainym can point to a noun or another pertainym. polysemous Having more than one sense in a syntactic category. polysemy count Number of senses of a word in a syntactic category, in WordNet. postnominal A postnominal adjective occurs only immediately following the noun that it modifies. predicative An adjective that can be used only in predicate positions. If X is a predicate adjective, it can only be used in such phrases as "it is X " and never prenominally. prenominal An adjective that can occur only before the noun that it modifies: it cannot be used predicatively. satellite synset Synset in an adjective cluster representing a concept that is similar in meaning to the concept represented by its head synset . semantic concordance A textual corpus (e.g. the Brown Corpus) and a lexicon (e.g. WordNet) so combined that every substantive word in the text is linked to its appropriate sense in the lexicon via a semantic tag . semantic tag A pointer from a word in a text file to a specific sense of that word in the WordNet database. A semantic tag in a semantic concordance is represented by a sense key . semantic pointer A semantic pointer indicates a relation between synsets (concepts). sense A meaning of a word in WordNet. Each sense of a word is in a different synset . sense key Information necessary to find a sense in the WordNet database. A sense key combines a lemma field and codes for the synset type, lexicographer id, lexicographer file number, and information about a satellite's head synset , if required. See senseidx(5WN) for a description of the format of a sense key. subordinate Same as hyponym . superordinate Same as hypernym . synset A synonym set; a set of words that are interchangeable in some context without changing the truth value of the preposition in which they are embedded. troponym A verb expressing a specific manner elaboration of another verb. X is a troponym of Y if to X is to Y in some manner. unique beginner A noun synset with no superordinate . <file_sep>/docs/writes/initial layers.md Initial Layers (preliminary) The core engine is built on a number of independent layers to produce one larger net. Fundamentally the “core” is the main engine for starting. This will provide the booting structure of mandatory elements: Data IO through a cache and external requests Input IO for user interaction and piping messages Main communication method; passing a usable pipe (or address) into a booting net Net driver to maintain queued communication between threads and start/stop threads/nets when required The core will boot an initial thread, at the moment this is defined the “knowledge layer” providing the input of preliminary data for the deeper nets performing abstraction. An operator will feed textual input to the knowledge layer. Currently this is through a simple socket or CLI loop. The knowledge layer accepts words or sentences to gather all IO data from external inputs and generally populate the given information with more knowledge layer attributes. This is inclusive of other words from the cache and any grammar or spelling corrections before submitting to the next layer for contextualization. After expansion and normalisation the string is a list of unassociated object, populated with knowledge layer data values; antonyms, synonyms and tokenization of the sentence. <file_sep>/docs/writes/sequences.md The word graph provides concepts of entities and dictionary definitions for each word given. The weighted relationships factor a solution to a best choice for object association. Not included within the online dataset is an order of sequence for elements: one > two > three > four country > state > city > town okay > good > great > best > fanstastic > awesome Some are factored through language such as cardinal numbers but most cases require heavy weighting sessions. At the moment I haven't a solution. Inspecting the current graph we see country, location, city, place and state are all distinct relations. Therefore categorizing these may be performed through relationships up to 3 deep. I feel utilizing the 'atlocation' for most aspects of decendency will perform the best. Using the standard graph and a reverse standard graph - for every word we produce a graph with a preference to 'atlocation' edges in both directions. Given the root word 'town' - each edge is inferred 'atlocation' or a top weighted selection for a word. village - small_town - town/n - [town] - country - world - solar-system - universe, At that point the universe is self referencing. With each word a reference to size helps. The 'village' 'hasproperty', 'tiny'. The 'universe' has relations to 'infinite' amongst other _large_ terms. Graphing numerical order to the indeterminate values such as 'tiny' and 'large' will rely upon graphing each work and discovering antyonms and synonms. Testing the api I see 'medium' is self-referencing with 'large' as a 'property' to 'big', 'much', and also 'medium. Notably 'few' related to a caridinal value 'three' <file_sep>/docs/merge combinator.md The merge grouping initial step returns a list of edges for the top word, and all top threshold edges for the given word. The result produces two edge lists (upper,lower, ) through the `weight` threshold. Upper: word weight len items ----------------------------------------- egg - 64 chicken, oval, yolk, white, food, bird, shell, baby ... chicken 6.448 87 bird, hen, cross_road, rooster, animal, food, farm, poultry ... yolk 2.455 2 egg, yellow white 4.921 3 opposite_of_black, color, colour food 2.0 37 refrigerator, table, kitchen, fridge, oven, supermarket, eaten, cupboard ... bird 4.72 54 animal, flying, sing, wings, tree, flying_animal, nest, sky ... shell 2.0 2 ocean, egg ... Clean up references futher by iterating all _top_ of the edge list, find all of high weight and recursively step through until exausted. For the initial step, record any primary edges - an edge with a forward reference to the given word. `egg > shell == 2.0`, and `shell` has `egg` as reference. Same applied for `yolk`. However `white` does not contain a forward reference to `egg`, therefore it's not a primary. All primaries: `yolk, shell` etc... are populated in the same method as the original word `egg`. The same computation is applied to sub-elements, with a reference to the parent graph. The next step for all values, computing weighted distance through cross-references of primary words. The `primary->primary` graphs are used as a preliminary weighting bias. Secondary values such as `chicken`, `bird` etc.. have a reference (`food` and `bird` of `chicken`) are reweighted whilst populated and checked though the secondary phase. --- The merging combinator results + The root word `egg` + edges: The upper/lower initial edge list; `chicken`, `yolk`, `white`, ... + Each edge word as a `primary`; any forward reference to the root word: `yolk`, `shell`, etc.. + Populating the primaries, with their graphs as `primary->primary` + Continue populating top X (e.g 50%) weighted of primaries. Until exausted. + Test weight of each, walk top edges of these local graphs + Compute rolling weights for edges, relative to a root word. The result produces a tiered set of edges, with primary, lower, dropped etc... The primary edges apply the best relevence for analysis for the next steps. ## Enrichment The _naked_ edges only provide best-guess from previously recorded values and does not account for a 'sentence' of words or session context (other graphs). They should be factored within this. + Tokenisation of the sentence + Siblings of other words (previous sentences, named graphs, hardcoded training) + long-term study <file_sep>/src/v2/conceptnet/relations.py import traceback import sys import multiprocessing from log import log from conceptnet.parse import parse_csv, spread def generate_negatives(): """Relations can be prefixed with "Not" to express a negative assertion, such as `/r/NotIsA` `/c/en/mammal` `/c/en/plant`. The negative relations that we have data for are NotDesires, NotUsedFor, NotCapableOf, and NotHasProperty.""" global map_tuple not_desc = '[Negative relation of]' res = () for item in map_tuple: rel = item[0].replace('/r/', '/r/Not') desc = "{} {}".format(not_desc, item[1]) ires = (rel, desc, ) + item[2:] res += (ires,) map_tuple += res '''Tuple of tuples for the expected relation types. additional 'not' statements generate and append upon module import ''' map_tuple =( ( "/r/RelatedTo", """The most general relation. There is some positive relationship between A and B, but ConceptNet can't determine what that relationship is based on the data. This was called "ConceptuallyRelatedTo" in ConceptNet 2 through 4. Symmetric. """, """learn <=> erudition""", ), ( "/r/ExternalURL", """Points to a URL outside of ConceptNet, where further Linked Data about this term can be found. Similar to RDF's `seeAlso` relation. """, """knowledge => http://dbpedia.org/page/Knowledge""", ), ( "/r/FormOf", """A is an inflected form of B; B is the root word of A. """, """slept => sleep""", ), ( "/r/IsA", """A is a subtype or a specific instance of B; every A is a B. This can include specific instances; the distinction between subtypes and instances is often blurry in language. This is the *hyponym* relation in WordNet. """, """car => vehicle; Chicago => city""", ), ( "/r/PartOf", """A is a part of B. This is the *part meronym* relation in WordNet. """, """gearshift => car""", ), ( "/r/HasA", """B belongs to A, either as an inherent part or due to a social construct of possession. HasA is often the reverse of PartOf. """, """bird => wing; pen => ink""", ), ( "/r/UsedFor", """A is used for B; the purpose of A is B. """, """bridge => cross water""", ), ( "/r/CapableOf", """Something that A can typically do is B. """, """knife => cut""", ), ( "/r/AtLocation", """A is a typical location for B, or A is the inherent location of B. Some instances of this would be considered meronyms in WordNet. """, """butter => refrigerator; Boston => Massachusetts""", ), ( "/r/Causes", """A and B are events, and it is typical for A to cause B. """, """exercise => sweat""", ), ( "/r/HasSubevent", """A and B are events, and B happens as a subevent of A. """, """eating => chewing""", ), ( "/r/HasFirstSubevent", """A is an event that begins with subevent B. """, """sleep => close eyes""", ), ( "/r/HasLastSubevent", """A is an event that concludes with subevent B. """, """cook => clean up kitchen""", ), ( "/r/HasPrerequisite", """In order for A to happen, B needs to happen; B is a dependency of A. """, """dream => sleep""", ), ( "/r/HasProperty", """A has B as a property; A can be described as B. """, """ice => cold""", ), ( "/r/MotivatedByGoal", """Someone does A because they want result B; A is a step toward accomplishing the goal B. """, """compete => win""", ), ( "/r/ObstructedBy", """A is a goal that can be prevented by B; B is an obstacle in the way of A. """, """sleep => noise""", ), ( "/r/Desires", """A is a conscious entity that typically wants B. Many assertions of this type use the appropriate language's word for "person" as A. """, """person => love""", ), ( "/r/CreatedBy", """B is a process or agent that creates A. """, """cake => bake""", ), ( "/r/Synonym", """A and B have very similar meanings. They may be translations of each other in different languages. This is the *synonym* relation in WordNet as well. Symmetric. """, """sunlight <=> sunshine """, ), ( "/r/Antonym", """A and B are opposites in some relevant way, such as being opposite ends of a scale, or fundamentally similar things with a key difference between them. Counterintuitively, two concepts must be quite similar before people consider them antonyms. This is the *antonym* relation in WordNet as well. Symmetric. """, """black <=> white; hot <=> cold""", ), ( "/r/DerivedFrom", """A is a word or phrase that appears within B and contributes to B's meaning. """, """pocketbook => book""", ), ( "/r/SymbolOf", """A symbolically represents B. """, """red => fervor""", ), ( "/r/DefinedAs", """A and B overlap considerably in meaning, and B is a more explanatory version of A. """, """peace => absence of war""", ), ( "/r/Entails", """If A is happening, B is also happening. (This may be merged with HasPrerequisite in a later version.) | run => move""", ), ( "/r/MannerOf", """A is a specific way to do B. Similar to "IsA", but for verbs. """, """auction => sale""", ), ( "/r/LocatedNear", """A and B are typically found near each other. Symmetric. """, """chair <=> table""", ), ( "/r/HasContext", """A is a word used in the context of B, which could be a topic area, technical field, or regional dialect. """, """astern => ship; arvo => Australia""", ), ( "/r/dbpedia", """Some relations have been provisionally imported from DBPedia, and don't correspond to any of the existing relations. For now, these are in the `/r/dbpedia/...` namespace, such as `/r/dbpedia/genre`. The DBPedia relations represented this way are `genre`, `influencedBy`, `knownFor`, `occupation`, `language`, `field`, `product`, `capital`, and `leader`.""", ), ) ### autocall the Negative relations generate_negatives() # + The URI of the whole edge # + The relation expressed by the edge # + The node at the start of the edge # + The node at the end of the edge # + A JSON structure of additional information about the edge, such as its weight def get_relations(kw): '''Parse the given dictionary through parse_csv. returns a list of relations from the CSV path path of the csv to parse cpu_count allowed number of threads in spread mode byte_start [auto] Byte chunk for the parse csv - autmatically applied when spread() with job split. byte_end [auto] Byte chunk for the parse csv - autmatically applied when spread() with job split. sample return a sample of each relation found. row_index Which index within a given row to collect for the return store value. This isposition indexed for the input CSV (default 1) max_count max lines per thread to iterate from the CSV provide None to disable ''' process_name = multiprocessing.current_process().name try: d, sample = parse_csv( max_count=kw.get('max_count', 100000), iter_line=get_value, as_set=True, row_index=kw.get('row_index', 1), keep_sample=kw.get('sample', False), byte_start=kw.get('byte_start', None), byte_end=kw.get('byte_end', None), ) log('Finished relations. Count: {}. Writing file'.format(len(d))) except Exception as e: log('Error on "{}" :'.format(process_name), e) log(traceback.format_exc()) d = [] with open('relations-{}.txt'.format(process_name), 'w') as stream: for item in d: stream.write('{}\n'.format(item)) return list(d) def spread_get_relations(**kw): '''Similar to: from conceptnet import parse from conceptnet import relations parse.spread(relations.get_relations, max_count=1000) ''' result = spread(get_relations, **kw) merged = set() for thread_result in result: for rel_list in thread_result: merged.add(rel_list) return filter(None, list(merged)) def get_value(line, **kw): '''return the sub value using row_index with the given tuple _line_ from the CSV''' index = kw.get('row_index', 0) v = None try: v = line[index] except Exception as e: log('get_value error', e) finally: return v <file_sep>/src/v5/about.md ## Reboot The date is 21 July 2019 and this is (if even) version 5 of the context net. Currently version 3 works with version 4 as a conceptual prototype to structure. The rebuild warrents a year of alternative study and a clearer definition of output. Fundamentally the old (current) code isn't readable, due to the mixed structure approach. As such, the new concept should allow an easier learning curve for picking-up the project. --- This write-up is a more-formal write-up of the idea, combining the previous data and concepts with newer study. The fundamental project changes will encompass: + Forget the initial 'modular' structure in the persuit of a great "lib" I intend to use the cleanest _written_ libs, to make is super easy to pickup. For example a db layer in django is extremely readable. And with no need to build libraries of stitching code or glue it's easy extend. + forgoe speed for clarity finding the fastest method is good, but I keep finding a better method. Therefore I give up and instead use a clean adapter I'll delete layer when fully functioning. + less ML, more data through clever data structures I can achieve a lot of the requirements without black box magic. Having a fully ML context machine is hard to evaluate and retrain. Instead I'm opting for very thing 'glue' layers to formluate edges of the sentence graphs: case: Stattrek-list. ## Primitive layout The basic premise: Convert sentences to objects, graph objects to provide associative _context_ in relation to a sentence or a session of conversation. _Working with the data over these years, I see a lot of this can be done with clever data indexing (db) and lots of async graphery._ ### Input Layer Any sensory input, predominantly textual and intially text and verbal input/output. The TTS and STT are already done through standard SAPI and web-tech, so this is a arbitrary step. The context api should handle temporal particles, therefore the input stream shouldn't matter. For the _doorbell_ project, it's shown any IO is credeble given the correct training. + Receive external signals, streams, texct etc.. + Pass the the next layer as a source to _split_ as particles. Text format: ``` > CLI: Show me page six and extract my favorite word. < send to layer "Show me page six and extract my favorite word." ``` ### Layer 1: Temporal Particles Split incoming temporal streams into congizent chunks for the _sentences layer_. As input is received, the slicing or _selection_ of data is structured for the next layer. With text this is easy, each temporal particle is just an input word or sentence. With voice it's slightly tricker however I consider it a complex tokensation problem given to NLTK to tokensizer. I feel the hard part may be applying (or extracting) grammer from unstructured streams to single ledgible items. For now I can focus on simple training sentences, and I hope to pick up a ready-to-use ML tagging lib... + Receive unstructured (but formatted) information from input layers + Break down the streams in particles (chunks) of single units to identify (word tags). + Send to a 2D graphing layer for contextual abstraction ``` > "Show me page six and extract my favorite word." < send ["Show" "me" "page" "six" "and" "extract" "my" "favorite" "word", "."] ``` Or maybe even sub particle breakdown ``` < send [ ["Show" "me" "page" "six"] "and" ["extract" "my" "favorite" "word", "."] ] ``` ## Layer 1.5: 2D Ledger (Sentence Grouping) For the first (real) layer, the sentences are a session of lists, defining a group of messages in context. Consider asking a machine to book a flight, each input sentence is a single entity within a conversation list. For each incoming particle-set, apply to the correct context session (the current one) and study each element (a word token) for cross-reference knowledge. Given we have the word "in the other room", the context should define association for "other" and "room". It should consider the history of a session, contexts from other sessions and generally populate the words _as much as possible_ to define a solution to _what_ is the "other room". We should think of it as a flat graph - using a nice and easy example [ > "turn on the TV", < ??, > "in the other room", ] In the middle `< ??` our output, must quantify more context for the session, we'll ignore it for now. The "Turn on TV" is the action to perform in the "other room" and for now, the focus on contextually defining 'other'. _Note: The leap here defines the pre-trained "room", being a standard object for an environment, we don't need to build a deeper contextual graph - other than 'where'. Given this example assumes a standard installation, the room list() is a lookup for defining the name "other". If the room was "bedroom" - this wouldn't be a challenge :p._ As "other" isn't a named entity it should be "contextually graphed", i.e information regarding the word "other" should be stored into memory as it's own _thing_ graph. + A list of unit entities for session - _lists of sentences, containing 'word' units to reference._ + A sentence session for each unit of work - _almost like a a log group per conversation_ + A cross-reference instigator for knowledge gaps - _define previously unscanned elements providing data for all words - + A place of reference for _starting_ a graph analysis. - _scanning for previously known words and sentences_ Fundamentally this layer converts unstructured sentences and value data into knowledge chunks, ready to 'contextualise' and cross reference. ## Layer 2: Cross referencing _The overall goal for the context-api maintains a state of "context" for a word or phrase within an overall session. Each word may have its own context, assisting the population of other nodes within the graph"_. Each word in a given sentence has a graph of associations within a boundry of language in addition to local context. The underyling laguage prodvides relationships for words. For each words we define a starndard knowedge base and an extended context knowledge base. "this is my dog" The example sentence provides an association to the relative entity "this" and 'dog' with bridges to ownership and identity. The contextapi will populate the edges and leafs. <file_sep>/src/v1/main.py import os # from autocorrect import spell from pprint import pprint from json_socket import make_socket import primary_functions as prfs import contextnet_api as cnapi from typemap import type_map import cache import time # def main(): # cnapi.read_assertions() command = None def main(): ''' Open the client websocket and target the ask() loop. ''' prfs.init(socket_uri="ws://127.0.0.1:8009") # prfs.assess_string('hello') prfs.ask_loop() if __name__ == '__main__': main() <file_sep>/src/database/graph.py import re import operator from collections import Counter from .db import AppendableDB, GRow first_cap_re = re.compile('(.)([A-Z][a-z]+)') all_cap_re = re.compile('([a-z0-9])([A-Z])') def to_snake_case(name): s1 = first_cap_re.sub(r'\1_\2', name) return all_cap_re.sub(r'\1_\2', s1).lower() def to_camel_case(snake_str): components = snake_str.split('_') # We capitalize the first letter of each component except the first one # with the 'title' method and join them together. return components[0] + ''.join(x.title() for x in components[1:]) def to_title_case(snake_str): res = to_camel_case(snake_str) return "{}{}".format(res[0].upper(), res[1:]) class Remap(object): """Provide a literal translation of a value to a another prepared value for neater internal association of database values: # remap CapableOf to ability without DB manipulation seeds > CapableOf > grow_flowers # to seeds > ability > growSeeds """ # Provide a literal key value for word mapping # values = ( (MyWord, my_word,), ...) values = None translator_expose = staticmethod(to_snake_case) translator_digest = staticmethod(to_title_case) def mapval(self, value, safe=True): """Covert a value through the literal translation to another mapped value. If safe if true [default] and the value is missing from the map, the orignal value is returned. """ dict_values = self._translate_dict_cache() res = dict_values.get(value, None) if res is None: if self.translator_expose is not None: return self.translator_expose(value) if safe is False: raise Exception("Cannot translate string '{}'".format(value)) if res is None: return value return res def valmap(self, value): dict_values = self._translate_dict_cache() rev_dict = {y:x for x,y in dict_values.items()} res = rev_dict.get(value, None) if res is None: return self.translator_digest(value) return res def _translate_dict_cache(self): if self.values is None: return {} if hasattr(self, '_values_dict_cache') is False: self._values_dict_cache = dict(self.values) if self._values_dict_cache is None: return {} return self._values_dict_cache def _clear_translate_cache(self): del self._values_dict_cache return True class EdgeValues(object): """Maintain a reference to a key as a hint to the Edge for sorting and value extraction. db.pick('horse').is_a.weight() (1,1,1,1,.4, ...) Compatibility for enumeration for sorted and general inspection edges = handle.egg.antonym.chicken.capable_of ev = edges.weight # edge_values # Just the weights: ev() (1,1,1,1,.4, ...) # the edge_node key and weight value ev(True) (('become_food', 1.0), ('cross_road', 7.746), ('crossing_road', 1.0), ( # Return the edge, not the key ev(True, True) (('become_food', <EdgeNode(CapableOf) "become_food":1.0>), # value_key=False stops the return of the 'value' attribute from an edgenode. # Instead using the _internal key_ 'weight' ev(True, True, False) ((1.0, <EdgeNode(CapableOf) "become_food":1.0>), (7.746, <EdgeNode(CapableOf) "cross_road":7.746>), """ def __init__(self, edges, key): self.key = key self.edges = edges def __call__(self, with_key=False, as_node=False, value_key=True): """return a tuple of values of the internal key from every item in the associated Edges. ev = EdgeValues('weight', edges) ev() (1,1,1,1) ev(with_key=True) ('become_food', 1.0), ('cross_road', 7.746), ('crossing_road', 1.0), ev() """ res = () items = self.edges._items key = self.key for x in items: attr = getattr(x, key) attr_val = attr if as_node is False else x if with_key: attr_val = (x.value if value_key else attr, attr_val, ) res += (attr_val, ) return res def sort(self, *keys, **kwargs): """Sort and return the edges items using the given one or more key to sort upon. If no key is provided, the internal self.key is used. If multiple keys are given, multi-sort starting from the left. Any additional keyword arguments are given to the sorted() function top_5 = handle.egg.antonym.chicken.capable_of.weight.sort(reverse=True)[:5] Edges(items=top_5) """ # getter = operator.attrgetter(key or self.key) getter_keys = keys if len(keys) > 0 else [self.key] getter = operator.itemgetter(*getter_keys) return sorted(self.edges._items, key=getter, **kwargs) def __repr__(self): return "<EdgeValues {} of {}>".format(self.key, len(self.edges)) def __getitem__(self, index): return getattr(self.edges[index], self.key) class Edges(object): """ sorted(handle.my.related_to, reverse=True)[:5] [<EdgeNode(RelatedTo) "he_she":0.469>, <EdgeNode(RelatedTo) "term":0.402>, ...] >>> sorted(sorted(handle.my.related_to, reverse=True)[0].graph.related_to, reverse=True)[:4] Assuming key search [<EdgeNode(RelatedTo) "he_she":0.469>, <EdgeNode(RelatedTo) "term":0.402>, ...] >>> sorted(sorted(handle.my.related_to, reverse=True)[0].related_to, reverse=True)[:4] Assuming key search [<EdgeNode(RelatedTo) "he_she":0.469>, <EdgeNode(RelatedTo) "term":0.402>, ...] >>> """ def __init__(self, name=None, items=None): self._name = name self._items = items or () self._index = {} def add(self, edge_node): self._index[edge_node.value] = len(self._items) self._items += (edge_node,) def _text_list(self, weight=False): """return a tuple of tuples for text readout of edge_list. Edges(items=sorted(gp.edge_list(), reverse=True)[:4])._text_list(True) """ edges = self._items if weight: return tuple((x.edge_type, x.value, x.weight,) for x in edges) return tuple((x.edge_type, x.value,) for x in edges) def __getitem__(self, key): return self._items[key] def __getattr__(self, word_key): try: return self._items[self._index[word_key]] except KeyError: """The element does not exist in the index. If the key is on the first node item, return an index utility for value iteration and sort keys """ if hasattr(self._items[0], word_key): return EdgeValues(self, word_key) def __repr__(self): keys = tuple(str(x) for x in self._items) s = '<Edges {} "{}" {}>'.format(len(self._items), self._name or 'NO NAME', keys) return s def __len__(self): return len(self._items) def __eq__(self, other): if id(self) == id(other): return True if (self.index == other.index) is not True: return False if (self.name == other.name) is not True: return False return True class EdgeNode(object): """An Edgenode has Edge values (type of and weight) with an associated end value, such as a word or another entity. All calls to the graph proceed from the 'value' end_node. And method calls to the edge node pare given to the graph. e = EdgeNode('apples', 1, db) e.graph # > continuation to 'apples' Graph. """ def __init__(self, end_node, weight, graph_db=None, root_graph=None, parent_graph=None, edge_type=None, parent_edgenode=None, additional=None): self.value = end_node self.weight = weight self.graph_db = graph_db self._graph = None # The originating Graph instance, not strictly the parent. self.root_graph = root_graph # The graph this edge spawned from self.parent_graph = parent_graph self.edge_type = edge_type self.parent_edgenode = parent_edgenode self.additional = additional def get_graph(self, value=None): if self._graph is None: return self.pick(value, root_graph=self.root_graph) graph = property(get_graph) def pick(self, value=None, root_graph=None, parent_graph=None): """Select the given value from the internal graph_db using pick() Return a new graph as a child of this edgenode parent_graph. If the internal graph_db does not exist, raise an Exception raise """ root_graph = root_graph or self.root_graph parent_graph = parent_graph or self.parent_graph value = value or self.value if self.graph_db: graph = self.graph_db.pick(value, root_graph=root_graph, parent_graph=parent_graph, edgenode=self, ) return graph else: raise Exception('No graph_db Database assigned to EdgeNode {}'.format(self.value)) def graph_chain(self, include_self=False, from_edgenode=None): """reutn a list of graph objects to the originating graph using walk_back collecting every parent_graph. """ return self.walk_back('parent_graph', include_self, from_edgenode) def edgenode_chain(self, include_self=False, from_edgenode=None): """Return a list of edgenode instances to the original graph using walk_back collecting every parent_edgenode. """ return self.walk_back('parent_edgenode', include_self, from_edgenode, self_item=self) def walk_back(self, method, include_self=False, from_edgenode=None, self_item=None): """Iterate backward to the instigating graph in memory, calling the given `method` for ever back step from this edgenode. """ edge = getattr((from_edgenode or self), method) items = ( (self_item or getattr(self, method) ), ) if include_self else () while edge is not None: items += (edge, ) edge = getattr(edge, method) return items def pair_chain(self, include_self=False, from_edgenode=None): """Return a list of paire edgenode and associated graph for every step backward to the intrigating graph. """ chain_pair = zip( self.edgenode_chain(include_self, from_edgenode), self.graph_chain(include_self, from_edgenode) ) return tuple(chain_pair) def text_chain(self, include_self=False, from_edgenode=None): """Return a list of text tuples for every (word, key, weight) walking backward to the instigating graph. This uses pair_chain returning values from each discovered edgenode and graph. """ chain = self.pair_chain(include_self, from_edgenode) result = () for edge, graph in chain: if edge.parent_edgenode is not None: nv = edge.parent_edgenode.value else: nv = edge.parent_graph.key result +=( ( nv, edge.edge_type, graph.key, edge.weight),) return result def match_graph(self, other): """ handle.my.related_to >>> a,b=handle.my.related_to[:2] Assuming key search >>> a.match_graph(b) True """ res = False if hasattr(other, 'parent_graph') and self.parent_graph is not None: res = (self.parent_graph == other.parent_graph and (self.parent_edgenode == other.parent_edgenode) ) return res def match_thin(self, other): return (self.value == other.value and self.weight == other.weight and self.edge_type == other.edge_type ) def __lt__(self, other): if self.match_graph(other): other = other.weight return self.weight < other def __gt__(self, other): if self.match_graph(other): other = other.weight return self.weight > other def __lte__(self, other): if self.match_graph(other): other = other.weight return self.weight <= other def __gte__(self, other): if self.match_graph(other): other = other.weight return self.weight >= other def __getattr__(self, key): return self.graph[key] def __getitem__(self, key): """subscriptable key fetch from this edgenode only""" return getattr(self, key) def __repr__(self): s = '<EdgeNode({}) "{}":{}>'.format(self.edge_type, self.value, self.weight) return s def __eq__(self, other): if isinstance(other, (str, bytes)): return other == self.value if isinstance(other, (int, float)): return other == self.weight if self.match_graph(other): return self.weight == other.weight if isinstance(other, self.__class__): # node to node relation of values as the graphs don't exist. return self.match_thin(other) return id(other) == id(self) def __contains__(self, other): for item in edges: if item == other: return True return False def __str__(self): s = '{}({}) from "{}"'.format(self.value,self.weight, self.root_graph.key if self.root_graph is not None else 'NO ROOT') return s def __hash__(self): values = (self.value, self.weight, self.edge_type, ) return hash(values) class Graph(Remap): edgenode_class = EdgeNode edges_class = Edges def __init__(self, key, values, db=None, edgenode_class=None, edges_class=None, root_graph=None, parent_graph=None, edgenode=None): # The key value as this graphs edge id. self.key = key # Values collected from the database self.values = values # A DB to extend the collect self search self.db = db # The original Graph word to spawn this potential child self.root_graph = root_graph # The graph producing this graph - usually the immediate - not given # to edgenodes. self.parent_graph = parent_graph # EdgeNode if edgenode_class is not None: self.edgenode_class = edgenode_class if edges_class is not None: self.edges_class = edges_class self.edgenode = edgenode self._values_dict_cache = None self.edges = self.unpack() def get_values(self, *keys, index=0): """Return a list of values for the given keys. If no keya aree given return all values. Provide an 'index' for the row value index to collect from each item. Default is [0], for the first element within the items such as a tuple or GRow """ if len(keys) == 0: return self.values res = () for item in self.values: if item[index] in keys: res += (item, ) return res def edge(self, key): """Given a string or Graph return the associated edges """ return self.edges[key] def edge_list(self): """Return a list of edges - rather than `self.edges` returning an object. """ edges = self.edges return tuple(y for x in edges for y in edges[x]) def edge_text(self, weight=False): """return a tuple of tuples for text readout of edge_list""" edges = self.edge_list() if weight: return tuple((x.edge_type, x.value, x.weight,) for x in edges) return tuple((x.edge_type, x.value,) for x in edges) def edge_values(self, weight=False, edge=False, as_tuple=False, sort=None, reverse=False, unique=False, return_value=None): """Returna tuple of values (words) from all edges ignoring relation type. Pass weight=True or edge=True to populate additional attributes If weight or edges is true each item returned is a tuple. to produce a tuple of one item for each entry (for compatability with edge population) provide as_tuple=True. list of words: 'word' self.edge_values() # as tuples of one. self.edge_values(as_tuple=True) with weight; (word, weight, ) self.edge_values(True) with weight and relation. Tuple order (word, edge_type, weight) self.edge_values(True, True) sorted by text self.edge_values(sort=True) sort by weight, returning text only self.edge_values(weight=True, sort=(1,0), return_value=0) return multi-ordered with weight, unique only: self.edge_values(True, sort=(1, 0), reverse=True, unique=True) sort by _edge type_ then weight, return a unique list with each return value is a different order (word, weight, edge_type, ) self.edge_values(True, True, sort=(1,2,), unique=True, return_value=(0, 2, 1)) """ res = () for _edge in self.edge_list(): value = _edge.value if (weight is True) or (edge is True): as_tuple = True item = value if as_tuple: item = (value, ) if edge: item += (_edge.edge_type,) if weight: item += (_edge.weight, ) res += (item, ) if unique: res = set(res) if sort is not None: if sort is True: key = None else: if hasattr(sort, '__iter__') is False: # User passed an int, rather than a multi-order tuple sort = (sort,) key = operator.itemgetter(*sort) res = sorted(res, key=key, reverse=reverse) if return_value is not None: sub_res = () if hasattr(return_value, '__iter__') is False: return_value = (return_value, ) caller = operator.itemgetter(*return_value) # return a subset of each item. for item in res: sub_res += ( caller(item), ) res = sub_res return res def unpack(self): """convert the given values into a walkable tree.""" result = {} root_graph = self.root_graph or self for item in self.values: try: start_word, edge_type, end_word, weight, *meta = item except ValueError: weight = -1 start_word, edge_type, end_word, *meta = item if (edge_type in result) is False: result[edge_type] = self.edges_class(edge_type) # EdgeNode node = self.edgenode_class(end_word, weight, graph_db=self.db, root_graph=root_graph, parent_graph=self, edge_type=edge_type, parent_edgenode=self.edgenode, additional=meta, ) result[edge_type].add(node) return result def __repr__(self): keys = self._string_edge_keys() s = '<{} "{}" {} edges of: ({})>'.format( self.__class__.__name__, self.key, len(self.values), keys ) return s def _string_edge_keys_weights(self): s = [] for x in self.edges.keys(): s.append("{}({})".format(self.mapval(x), len(self.edges[x]))) keys = ', '.join(s) return keys def _string_edge_keys(self): keys = self.edges.keys() return ', '.join(self.mapval(x) for x in keys) def __getattr__(self, key): return self.fetch_edges(key, False) def fetch_edges(self, key, safe=False): """Return a list of Edges using the given key. If self.edges has no attribute of 'key', convery it and attempt again. Failing to find any key, raise an Attribut. """ try: return self.edges[key] except KeyError: valkey = self.valmap(key) try: return self.edges[valkey] except KeyError: pass if safe is True: return None es = 'Graph "{}" edges has no key attribute "{}" or "{}".' es += '\n Available keys: {}'.format (self._string_edge_keys() ) raise AttributeError(es.format(self.key, key, valkey)) def get_edges(self, *keys): """Return a tuple of edges from the internal list matching the one or more keys given. """ res = () for edge in self.edge_list(): if edge.value in keys: res += (edge, ) return res def __getitem__(self, key): return self.fetch_edges(key, False) def __len__(self): return len(self.edges) def __and__(self, other): """Support graph intersection, returning a new graph consisting of edges with matching edges. """ print('AND') # discovering the data in this routing: # (set(x[1] for x in hi.edge_text()) - set(x[1] for x in he.edge_text())) # List of ordered words - sort by weight, return only word ev_kwargs = dict(sort=(1,), return_value=0, reverse=True) edges0 = self.edge_values(True, **ev_kwargs) edges1 = other.edge_values(True, **ev_kwargs) s0 = set(edges0) s1 = set(edges1) si01 = s0.intersection(s1) si10 = s1.intersection(s0) # Shared values map(si01.add, si10) edges = self.get_edges(*si01) + other.get_edges(*si01) # Set at 2 because each graph will _start_ with the key word and end with # the related edge word. This is position 2 in a GRow relation item # ('hello', 'related_to', 'other') values_index=2 # Hmm. A special key combining two graphs? key = "{} [&] {}".format(self.key, other.key) reversed_values = ( self.get_values(*si01, index=values_index) + other.get_values(*si01, index=values_index) ) # Due to the index collection here the edges collect will be _backward_. # Noting their start word as the original graph start, and the end word # as the _edge_ we've collected. # # Produce a child graph with these edges. # something needs to be done here as this is a reverse child graph # + The keys a multple # + the values are backward. # + The edgenode is missing. # # Pretty messy. This needs to be fixed. child_graph = ChildGraph( key, reversed_values, # More than one db? db=self.db, edgenode_class=self.edgenode_class, edges_class=self.edges_class, root_graph=self.root_graph, # There are two parents? # # The parent of the given relation should be given for each # graph item. parent_graph=self, # This should be an internal reference, # create now for this new type of association. # # [update: This should pass the edgenodes leading to this child ? edgenode=None ) return child_graph """Notes: Perhaps this should be a CoupledGraph - with the ability to accept multiple parent_graphs and use them for values and edge search. Converting the 'parent_graph' to 'parent_graph' - defaulting to 1 parent, The coupling doesn't need to so a unique class - all graphs have one or more parents. This extends to a new type of Edgenode classification for the system only. Initially they'll be 'child graph edge node relation'. Later this extends to all type of ML relations including online, live or pre-trained relations. Therefore we can extend this to a single edgenode owning more than one edge per node. The edge being the relation may be 'many' (is_a, related_to) resolving to a single node 'greeting'. A single node may have more or more associated edges. A single node can maintain a weight per edge reference, with a topological view of other nodes or graphs. A graph handles the association of many edgenodes to many words (a standard graph pick) An Edgenode associated the relation type (is_a) to a node word ('greeting'). And edge is a relation to a single node A node is a single word or a unit of work et the end of a node A node can render a graph, through `edgenode.graph.is_a...` but a node _may_ not be attached to any graph to db. In fact a node could be a single word 'help' with a large number for weights with a topology of 'emergency' through reference of [relative] edge (such as `partof` ) to an 'emergency graph' event. pseudo: When Node('help') from edge('partof') through Graph('emergency') > 10 == 'run_func()' When two graphs intersect in some way, it may produce a coupled graph, for a child of associated edges and many parents a new graph with the original graph as a parent through a relation. --- A node may react to an event though another graphs _awakening_ of associated nodes or graphs. In addition event modules may capture other graphs or events to populate 'help' and 'emergency' detection. A node may optionally react with an event, applying weight to the 'run_graph' function and general context [of emergency]. """ class ChildGraph(Graph): """A Child graph spawns from working directory with a graph, producing a result qualifying for its own graph, such as a Graph & Graph intersection. A child graph acts like a normal graph for usage, but historical walking will step to the parent graph. + Given values (if any) may be reversed, applying the parent graph as the instigator + The values are edgenodes leading to this graph. + values (relations) may be duplicated + the edgenode may not exist, therefore a generated Edgenode associating this graph as a child should be created + More than one originating key; Leading to this child graph maintaining more than one parent. """ pass class Edge(object): """This class (to be renamed) associated the starting edge to walkable unit providing a cleaner interaction with the graph walker. handle = Edge(db).apples.capable_of """ def __init__(self, graph_db): self.graph_db = graph_db def __getattr__(self, key): if hasattr(self.graph_db, key): return getattr(self.graph_db, key) print('Assuming key search') return self.graph_db.pick(key) class GraphWalker(object): """Additional functions to de-structure inbound data and automatically _graph_ the associated keys and edged. Calling a key's graph supplies additional walkable graph values to path the db values. hello > related-to > greeting > related-to > hello ... """ graph_class = Graph def add(self, start, edge, end, weight, root=None, **kwargs_additional): """Apply a key value with additional values to bind graphing upon callback. """ save = True if 'save' in kwargs_additional: save = kwargs_additional['save'] del kwargs_additional['save'] data = GRow(start, edge, end, weight, root, **kwargs_additional) self.db.put(start, data, as_dup=True, save=save) def bind(self, key, db, through=None, relation=None): """Bind a db relation to a key within this db for automatic graph binding. bind() """ through = through or db.name relation = relation or key print ('Key "{}" > {} Graph({})'.format(key, through, relation)) def pick(self, key, root_graph=None, parent_graph=None, edgenode=None): """select a key from the database using 'collect' and return a Graph populated with the db values. Provide a root graph as the original caller for the chain. Allow default None to spwan a graph as its own root - further nodes and graphs will receive the given graph instance as the root graph.. """ raw_values = self.db.collect(key) """ Combine all the given values into a graph for user walking""" # Graph graph = self.graph_class(key, raw_values, db=self, root_graph=root_graph, edgenode=edgenode, parent_graph=parent_graph) return graph class ObjectDB(GraphWalker): """Mimic a GraphDB to work with the same format of data without a database connection. This is essentially a drop-in replacement for a Graph, and may be used as an attenuates connection graph or an in-memory static graph loaded from data. """ def __init__(self, name=None, load=None): self.name = name self.db = self self.encode = GraphDB(auto_open=False).encode self.decode = GraphDB(auto_open=False)._convert_out self.index = {} self._data = () if (name is None) and (load is not None): self.load(load) def collect(self, key): return [self.decode(self._data[x])for x in self.index.get(key, ())] def get(self, word): return self.collect(word)[0] def wipe(self): self._data = () def iter(self, **kw): for key in self.index: for index in self.index[key]: yield key, self._data[index] def put(self, key, value, encode=True, **kw): # def put(self, key, value, save=True, encode=True, encode_key=True, # as_dup=None, **kwargs): if (key in self.index) is False: self.index[key] = () self.index[key] += (len(self._data), ) self._data += (self.encode(value) if encode else value,) def start(self, **kw): self.db = self super().start(**kw) def load(self, data): """Load an object into the internal data, utilizing create_index() if the 'index' key does not exist. Antithesis of dump().""" self.name = data.get('name', None) self._data = data.get('values', None) self.index = data.get('index', self.create_index(self._data)) def dump(self, with_index=True): """Return the internal data as an object for digest through transport or storage.""" result = {'name': self.name, 'values': self._data } if with_index: result['index'] = self.index return result def create_index(self, data): """Given a list of data for usage within the _data, return a new index.""" counter = 0 index = {} for item in data: row = self.decode(item) key=row[0] if (key in index) is False: index[key] = () count = counter index[key] += ( count, ) counter += 1 return index class GraphDB(AppendableDB, GraphWalker): # graph_class = Graph def start(self, **kw): self.db = self super().start(**kw) <file_sep>/requirements.txt autocorrect certifi chardet idna nltk numpy requests six urllib websocket-client <file_sep>/src/v3/primary_context.py """The Primary Context provides the input layer of the general context api. `apply_to_context(sentence)` pushes the words into the running context graph. """ import os import nltk import typemap as typemap_m from typemap import type_map import contextnet_api as cnapi # from logger import print_edges import words from cache import set_cache, string_cache, set_global_root import cache #import loop from json_socket import make_socket, send_json ident_dict = {} socket = None def init(socket_uri="ws://127.0.0.1:8009"): ''' A initialisztion function for anything requiring a first boot. ''' global socket if socket_uri is not None: print 'Making primary_context socket' socket = make_socket(socket_uri) def apply_to_context(sentence): '''given data from the token assess, build clean data for the context engine, populating with missing data as required. ''' send_json({ "sentence": sentence, 'type': 'sentence','action': 'start' }) # success, v = get_cache(filepath) thin_structure_words = tokenize_assess_string(sentence, allow_fetch=True) # Send to the data cleaner for the next stage of cross referencing. updated_words = populate_sub_words(thin_structure_words) words = thin_structure_words print words.keys() print 'tree', thin_structure_words['tree'] res = tuple() if 'words' in words: for wordset in words['words']: word, wtype, ident, dict_ref = wordset print "looking at - ", word, wtype ''' (Pdb) pp(ident['meta'][0:2]) [{'end': {u'@id': u'/c/en/fruit', u'label': u'fruit', u'language': u'en', u'term': u'/c/en/fruit'}, 'id': u'/a/[/r/RelatedTo/,/c/en/apple/,/c/en/fruit/]', 'rel': {u'@id': u'/r/RelatedTo', u'label': u'RelatedTo'}, 'start': {u'@id': u'/c/en/apple', u'label': u'apple', u'language': u'en', u'term': u'/c/en/apple'}, 'surfaceText': u'[[apple]] is related to [[fruit]]', 'weight': 12.80968383684781}, {'end': {u'@id': u'/c/en/red', u'label': u'red', u'language': u'en', u'term': u'/c/en/red'}, 'id': u'/a/[/r/HasProperty/,/c/en/apple/,/c/en/red/]', 'rel': {u'@id': u'/r/HasProperty', u'label': u'HasProperty'}, 'start': {u'@id': u'/c/en/apple', u'label': u'apple', u'language': u'en', u'term': u'/c/en/apple'}, 'surfaceText': u'[[apple]] can be [[red]]', 'weight': 9.591663046625438}] ''' word_def = clean_for_context(wordset) res += (word_def,) else: print 'no word information' print 'Have {} words'.format(res) send_json({ "sentence": sentence, 'type': 'sentence','action': 'end' }) integrate_to_context(thin_structure_words, res) return res import init_graphing def integrate_to_context(initial_tokens, words): """ initial_tokens.keys() ['ident', 'tree', 'original', 'words'] ident: {'wtypes': set(['NN']), 'words': set(['door']), 'idents': set(['door_NN'])} original: [('open', 'VB'), ('the', 'DT'), ('door', 'NN')] words (list of lists): ('open', 'VB', meta with graph) meta: ['wtypes', 'meta_graph', 'words', 'idents'] wtypes: set('VB') meta_graph: [u'HasProperty', u'HasContext', u'Synonym', u'DerivedFrom', u'RelatedTo', u'AtLocation', u'IsA', u'FormOf'] words: set(['open']) idents: set(['open_VB']) """ # Add to initial stage sentence graph - a temporal space of sentences # and graph words. # Determin best linear graph for sentence _id = init_graphing.open_temporal() for word in words: init_graphing.add_word(_id, word) class Word(object): def __init__(self, word, tag_type): self.word = word self.tag_type = tag_type self.relatives = {} self._relations = [] self.meaning = None self.antonyms = None self.synonyms = None # A diction of nested knowledge of associations self.graph = {} def add_relative(self, word, word_type, weight=1, sentence=None, language=None): '''Associate a word with this word in relation to the given type''' _type = word_type self._relations.append({ 'word': word, 'type': _type, 'sentence': sentence, 'weight': weight, 'language':language, }) def add_relative_type(self, _type): if self.relatives.get(_type, None) is None: self.relatives[_type] = [] def __repr__(self): s = '<Word("{}" {}) graph: {}~{}>'.format( self.word, self.tag_type, len(self.graph), sum([len(x) for x in self.graph]) ) return s ignore = [u'ExternalURL'] def clean_for_context(wordset): '''Given the entire dataset for a word, generate and return a cleaner API word for use within the API ''' langs = ['en'] word, wtype, ident, dict_ref = wordset wc = Word(word, tag_type=wtype) wc.meaning = dict_ref.get('meaning', None) wc.antonyms = dict_ref.get('antonym', []) wc.synonyms = dict_ref.get('synonym', []) # Bind the simiple type association simp = [] for key, val in typemap_m.simplify.items(): if wtype in val: print('association with', key) simp.append(key) # unpack the new graph data structure into a word for easy access data = ident.get('meta_graph', {}) wc.graph = data # Extract exact type from meansing if wc.meaning is not None: simp_meaning_assoc = {x.lower():x for x in wc.meaning.keys()} assoc_result = {} for key in simp: # pluck the associated meaning from the dictionary evaluation # eith the token type. i.e NN for noun - Therefore pull the 'Noun' # from the dictionary. assoc_meaning = simp_meaning_assoc.get(key, None) if assoc_meaning is not None: assoc_result[key] = wc.meaning[simp_meaning_assoc[key]] wc.meaning_result = assoc_result # wc.add_relative( # word=edge['end'], # word_type=edge['rel']['label'], # weight=edge['weight'], # sentence=edge['surfaceText'], # language=edge['end']['language'], # ) return wc def bind_meaning(wc, wtype): # Bind the simiple type association simp = [] if isinstance(wc, dict): meaning = wc['meaning'] else: meaning = wc.meaning for key, val in typemap_m.simplify.items(): if wtype in val: print('association with', key) simp.append(key) assoc_result = {} # Extract exact type from meansing if meaning is not None: simp_meaning_assoc = {x.lower():x for x in meaning.keys()} for key in simp: # pluck the associated meaning from the dictionary evaluation # eith the token type. i.e NN for noun - Therefore pull the 'Noun' # from the dictionary. assoc_meaning = simp_meaning_assoc.get(key, None) if assoc_meaning is not None: assoc_result[key] = meaning[simp_meaning_assoc[key]] return assoc_result def populate_sub_words(thin_structure_words, allow_fetch=True): '''A parent string has been tokenized and filled with the raw cache data of the words. Populate the same for any sub words, attached synonyms and antonyms ''' words = thin_structure_words result = [] if 'words' in words: for wordset in words['words']: word, wtype, ident, dict_ref = wordset # populate similar subl = dict_ref['synonym'] if subl is None: print 'no synonyms' continue print 'digressing synonyms of', word, len(subl) for sub_word in subl: print "looking at - ", sub_word value = tokenize_assess_string(sub_word.lower(), allow_fetch=allow_fetch) result.append({ 'value': sub_word, 'meta': value }) else: print 'no word information' return result def populate_sub_words_recursive(thin_structure_words, depth=6, _current_depth=0, root_value=None): print 'populate sub words recursive {}/{}'.format(_current_depth, depth) words = populate_sub_words(thin_structure_words, allow_fetch=False) if _current_depth >= depth: print 'kill depth' return words for word_result in words: if 'words' in word_result['meta']: print 'recursive inspection of', len(word_result['meta']) _words = populate_sub_words_recursive( word_result['meta'], depth=depth, _current_depth=_current_depth+1, root_value=root_value, ) words.extend(_words) return words def ident_object(word, wtype, tokens): return dict() def tokenize_assess_string(sentence, allow_fetch=True): """Convert the words into tokensization, collecting cached data or creating new. """ # success, v = get_cache(filepath) v = cache.get_string_cache(sentence) if v is None: v = tokenize(sentence) cache.set_string_cache(sentence, v) else: print('Collected sentence from cache') return assess_tokens(v, allow_fetch=allow_fetch) def iter_print(g): print '\n' for word, typeof in g: print "{:<20} {:<4} {}".format(word, typeof, type_map.get(typeof, '[NO TYPE]')) return g def tokenize(s): ''' Tokenize the given string sentence consisting of words split by spaces. Return a list of tokenized words. ''' print 'tokenizing input...', type(s) send_json(type='tokenize', input=s, action='start') t = nltk.word_tokenize(s) g = nltk.pos_tag(t) send_json(type='tokenize', input=s, result=g, action='complete') return g def assess_tokens(tokens, allow_fetch=True): '''Read and analyze a list of tokens. For each discovered work, entire word assertions exist. return a tuple of tokens with a word ident object. ''' print 'Assessing:' send_json(type='assess', action='start', tokens=tokens) tree = nltk.chunk.ne_chunk(tokens) res = [] for word, typeof in tokens: item = (word, typeof, type_map.get(typeof, '[NO TYPE]'), ) res.append(item) send_json(type='assess', action='complete', result=res, tokens=tokens) iter_print(tokens) res = () for word, wtype in tokens: # thin_structure_words['words'][3] == tokens ident = assess_word_token(word, wtype, tokens, allow_fetch=allow_fetch) wdd = words.get_word(word) wdd['meaning_result'] = bind_meaning(wdd, wtype) res = res + ( (word, wtype, ident, wdd), ) send_json( type='assess', action='word', word=wdd, word_type=wtype, tokens=tokens, ident=ident, ) # print_edges(ident) return dict(tree=tree, ident=ident, words=res, original=tokens) def assess_word_token(word, wtype, tokens, allow_fetch=True): ''' Given a Word "cake", its type "NN" and associated sentence tokens, "I like cake" identify the word store a cache of identification into the ident_dict. returned is the word entry to the ident_dict; an object of 'idents', 'words' and 'wtypes' ''' ident = "{}_{}".format(word, wtype) # if ident_dict.get(ident, None) is None: # # add to flat # ident_dict[ident] = ident_object(word, wtype, tokens) if ident_dict.get(word, None) is None: # add to flat ident_dict[word] = ident_parent_object(word, wtype, ident, tokens, allow_fetch=allow_fetch) ident_dict[word]['idents'].add(ident) ident_dict[word]['words'].add(word) ident_dict[word]['wtypes'].add(wtype) return ident_dict[word] def ident_parent_object(word, wtype, ident, tokens, allow_fetch=True): ''' Create a single word entry to the identity context, associating any _wtype additions word: Literal word given for input: i.e. "cake" wtype: Token type from nltk Penn Treebank tagging: "NN" ident: Literal word token assignment identity: "Cake_NN" tokens: Assosciated sentence tokens. The meta data within the result will call the to the context API. ''' res = dict(words=set(), wtypes=set(), idents=set()) relations = cnapi.api_result(word.lower(), allow_fetch=allow_fetch) # res['meta'] if relations is None: print 'No relations for {}'.format(res) return res clean_relations = () for edge in relations: if edge['rel']['label'] in ignore: print 'skipping external url relation' continue try: endlang = edge['end']['language'] except KeyError as e: print 'Language key missing' print edge continue # Add the type of edge as a future relationship type. # res.add_relative_type(edge['rel']['label']) clean_relations += (edge, ) res['meta_graph'] = graph_knowledge_load(word, wtype, ident, clean_relations) # {'end': {u'@id': u'/c/en/greeting', # u'label': u'greeting', # u'language': u'en', # u'term': u'/c/en/greeting'}, # 'id': u'/a/[/r/IsA/,/c/en/hello/,/c/en/greeting/]', # 'rel': {u'@id': u'/r/IsA', u'label': u'IsA'}, # 'start': {u'@id': u'/c/en/hello', # u'label': u'Hello', # u'language': u'en', # u'term': u'/c/en/hello'}, # 'surfaceText': u'[[Hello]] is a kind of [[greeting]]', # 'weight': 4.47213595499958} return res def graph_knowledge_load(word, wtype, ident, relations): """Given the original data to 'identify' - (see ident_parent_object) and a resolved cache object from an API of knowledge for flat content. Convert the data into a tree graph ready for contex api walking. Return a result dict, in the same structure as the given initial result object. Each element within the result meta `result['meta']` is a graph edge connecting word nodes from an historical graphing. """ # content from the api to digest. tree = {} dups = {} if relations is None: return None # Merge on the 'rel' relation for the start and end node. for edge in relations: rel = edge['rel'] end = edge['end'] start = edge['start'] if end.get('language', 'en') != 'en': # too many for dev continue # if 'language' in end: # del end['language'] # del end['@id'] if (rel['label'] in tree) is False: tree[rel['label']] = [] dups[rel['label']] = set() if (end['term'] in dups[rel['label']]): continue dups[rel['label']].add(end['term']) tree[rel['label']].append(edge) #result['knowledge_tree'] = tree return tree <file_sep>/src/v5/context/first/migrations/0002_temporalinput_created.py # Generated by Django 2.2.3 on 2019-07-27 21:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('first', '0001_initial'), ] operations = [ migrations.AddField( model_name='temporalinput', name='created', field=models.DateTimeField(auto_now_add=True, null=True), ), ] <file_sep>/src/v5/context/first/migrations/0004_auto_20190727_2341.py # Generated by Django 2.2.3 on 2019-07-27 22:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('first', '0003_auto_20190727_2259'), ] operations = [ migrations.RemoveField( model_name='temporalinput', name='tokens', ), migrations.AddField( model_name='temporalinput', name='tokens', field=models.ManyToManyField(to='first.PositionTokenWord'), ), ] <file_sep>/src/wordnet/test_wordnet.py import os import unittest import shutil import mock from mock import patch, Mock, call from v4.bridge import get_siblings as get from v4.wordnet import get_word, caller, NOUN, VERB, ADJ, ALL class TestWordnet(unittest.TestCase): @patch('v4.wordnet.subprocess') def test_caller_setup_call(self, subproc): app_path = "app_path" out_base = "/output-dir" get = caller(['ALL'], app_path=app_path, output_dir=out_base) res1 = get('egg', to_file=None) res2 = get('egg', to_file=False) res3 = get('egg', to_file=True) res4 = get('egg', to_file='egg.txt') result = subproc.run.call_args_list expected = [ call(['app_path', 'egg', '-ALL', '>', 'C:\\output-dir\\egg-ALL.txt'], shell=True, stderr=subproc.PIPE, stdout=subproc.PIPE, timeout=5), call(['app_path', 'egg', '-ALL'], shell=True, stderr=subproc.PIPE, stdout=subproc.PIPE, timeout=5), call(['app_path', 'egg', '-ALL', '>', '/output-dir\\egg-ALL.txt'], shell=True, stderr=subproc.PIPE, stdout=subproc.PIPE, timeout=5), call(['app_path', 'egg', '-ALL', '>', '/output-dir\\egg.txt'], shell=True, stderr=subproc.PIPE, stdout=subproc.PIPE, timeout=5), ] #for index, item in enumerate(expected): # self.assertTrue(item in expected, 'Test call {}'.format(index)) self.assertEqual(subproc.run.call_count, 4) self.assertListEqual(result, expected) <file_sep>/src/v2/logger.py def print_edges(res): _format = "{:<15} {:5} {:20} {:20} {:20} {}" # Languages not to list based upon start edge: exclude_langs = ['ja', 'fr', 'ast', 'bg', 'el', 'dsb', 'de', 'chr', 'co', 'cy', 'fil', 'br', 'hu', 'hi', 'cic', 'es', 'pt', 'th', 'ar', 'fa', 'zh', 'arc', 'arn', 'ar', 'ba', 'bn', 'cs', 'da', 'sq', 'gl', 'ca', 'ms' 'af', 'fi', 'frp', 'gsw','gd', 'hy', 'fj', 'ga', 'he', 'ht', 'af', 'haw', 'eo', 'et', 'ha', 'eu', 'ms', 'ko', 'la', 'lij', 'fo','ko', 'lb', 'fur', 'io', 'is', 'it', ] include_langs = ['en'] print _format.format('Type', 'lang', 'Start', 'End', 'End-lang', 'weight') meta = res.get('meta', None) if meta is None: return res for edge in meta: lang = edge['start'].get('language', '') if lang in exclude_langs: if lang not in include_langs: continue if len(include_langs) > 0 and lang not in include_langs: continue print _format.format( edge['rel']['label'], # unicode.encode(edge['id'], errors='replace'), edge['start'].get('language', ''), unicode.encode(edge['start']['label'], errors='replace'), unicode.encode(edge['end']['label'], errors='replace'), edge['end'].get('language', ''), edge['weight'] ) return res <file_sep>/src/v2/conceptnet/example_relations.py '''Collect the relations from the CSV. ''' from conceptnet import parse as P from conceptnet import relations P.spread(relations.get_relations, max_count=1000) P.get_relations(dict(path=P.csv_path, max_count=1000000)) [ ['/r/DerivedFrom', '/r/Causes', '/r/Entails', '/r/CausesDesire', '/r/EtymologicallyRelatedTo', '/r/CapableOf', '/r/Antonym', '/r/DistinctFrom', '/r/AtLocation', '/r/CreatedBy', '/r/Desires', '/r/DefinedAs'], ['/r/ExternalURL', None], ['/r/ExternalURL', None], ['/r/FormOf', '/r/ExternalURL', None], ['/r/PartOf', '/r/InstanceOf', '/r/ObstructedBy', '/r/MadeOf', '/r/LocatedNear', None, '/r/NotDesires', '/r/MannerOf', '/r/HasSubevent', '/r/NotCapableOf', '/r/HasLastSubevent', '/r/HasProperty', '/r/ReceivesAction', '/r/HasPrerequisite', '/r/MotivatedByGoal', '/r/RelatedTo', '/r/NotUsedFor', '/r/HasContext', '/r/IsA', '/r/NotHasProperty', '/r/HasFirstSubevent'], ['/r/RelatedTo', None], ['/r/RelatedTo', None], ['/r/Synonym', None] ] relations.spread_get_relations(max_count=60000) expected = ['/r/ExternalURL', '/r/HasLastSubevent', '/r/Antonym', '/r/HasPrerequisite', '/r/RelatedTo', '/r/HasContext', '/r/Synonym', '/r/HasFirstSubevent'] from conceptnet import dbstore dbstore.spread_redis_apply(max_count=100, max_cpu=1) # populate the database with the given [builtin] csv from conceptnet import sqlite_db db = sqlite_db.fill_word_db(dict(max_count=None, byte_end=1000000)) from conceptnet import sqlite_db from conceptnet import parse jobs = parse.job_split(path=parse.csv_path) job = jobs[6] job.update(dict(max_count=None)) db, res = sqlite_db.fill_word_db(job) db, res = sqlite_db.fill_word_db(jobs[3]) db, res = sqlite_db.fill_word_db(jobs[3]) db, res = sqlite_db.fill_word_db(jobs[4]) # Use one statement with a handler from conceptnet import sqlite_db x = 'C:/Users/jay/Documents/projects/context-api/context/src/cache/sqlites/sql-proc-0.db' db, c = sqlite_db.open_db(x) s = 'SELECT * FROM word WHERE start_word = "cat"' sh = sqlite_db.StatementHandler(db, c) sh.call(('select', s,)) sh.stmt_select(s) from conceptnet import sqlite_db db = sqlite_db.spread_db() db.get_word('cake') db.fetch('SELECT * FROM word WHERE start_word = ? ', ('cat', )) db.fetch('SELECT * FROM word WHERE start_word = "cat"') from conceptnet import sqlite_db from conceptnet.parse import spread db = spread(sqlite_db.fill_word_db, **{}) db = sqlite_db.spread_db() db.add_line('dog', 'legs', 'has', 1, {}) db._promise._value <file_sep>/src/v2/conceptnet/scratch_db.py import multiprocessing import traceback from parse import parse_csv, clean_line, spread def spread_caller_function(**kw): return spread(store_lines, **kw) def writer_function(*a, **kw): print(a, kw) def store_lines(kw): process_name = multiprocessing.current_process().name db_index = kw.get('job_index', 0) pipe = writer_function options = dict( max_count=kw.get('max_count', 100000), iter_line=caller_function, as_set=True, pipe=pipe, row_index=kw.get('row_index', 1), keep_sample=kw.get('sample', False), byte_start=kw.get('byte_start', None), byte_end=kw.get('byte_end', None), ) try: d, sample = parse_csv(**options) print('Finished relations. Count: {}. Writing file'.format(len(d))) except Exception as e: print('Error on "{}" :'.format(process_name), e) print(traceback.format_exc()) d = [] # pipe.execute() return list(d) def caller_function(line, **kw): pipe = kw.get('pipe', None) if pipe is None: return l = clean_line(line, **kw) k = [] if l is None: return None _type, sw, ew, weight, _json = l _json.update({ "connection": _type, "weight": weight, #"direction": ('start', 'end',) }) print('{start[word]} {connection} {end[word]} {weight}'.format(**_json)) if kw['row_index'] % 1000 == 0: pass # pipe.execute() if __name__ == '__main__': store_lines({}) <file_sep>/src/v5/context/first/migrations/0003_auto_20190727_2259.py # Generated by Django 2.2.3 on 2019-07-27 21:59 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('first', '0002_temporalinput_created'), ] operations = [ migrations.CreateModel( name='Tag', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('value', models.CharField(help_text='Word', max_length=255)), ], ), migrations.CreateModel( name='TokenWord', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('value', models.CharField(help_text='Word', max_length=255)), ('created', models.DateTimeField(auto_now_add=True, null=True)), ('tag', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='first.Tag')), ], ), migrations.CreateModel( name='PositionTokenWord', fields=[ ('tokenword_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='first.TokenWord')), ('position', models.SmallIntegerField()), ], bases=('first.tokenword',), ), migrations.AddField( model_name='temporalinput', name='tokens', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='first.PositionTokenWord'), ), ] <file_sep>/src/v5/context/first/admin.py from django.contrib import admin from . import models @admin.register( models.Tag, models.DefinitionType, models.DefinitionValueType, models.Definition, models.TokenWord, models.PositionTokenWord, models.TemporalInput, models.TemporalSession, ) class StandardAdmin(admin.ModelAdmin): pass <file_sep>/src/v2/plugin.py '''A Plugin is a python module as a standalone thread or a multiprocess Process connected through websockets. ''' import threading import sys from log import log import json_socket class SocketWorker(threading.Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None): threading.Thread.__init__(self, group=group, target=target, name=name, verbose=verbose) self.args = args self.kwargs = kwargs self.target = target return def _connect(self, uri): socket = json_socket.get_socket() if uri is not None: socket = json_socket.get_or_create(uri) return socket def die(self): self.socket.send('kill') def run(self): self.socket = self._connect(self.args[0]) self.lock = self.args[1] self.socket.send('SocketWorker connected "{}"'.format(self.name)) log('running with {} and {}'.format(self.args, self.kwargs)) run = 1 plugin = self.kwargs.get('plugin', None) while run: m = self.socket.recv() if m == 'kill': run = 0 break if plugin is not None: log('Returning message') self.lock.acquire() try: run = self.target(m) except Exception as e: _t, _v, _tr = sys.exc_info() log('Worker error:', e) log(_tr) self.lock.release() log('SocketWorker death "{}"'.format(self.name)) return class Plugin(object): '''A Plugin class wraps up a mounting strategy with an automatic JSON socket.''' mount_type = None _recv_thread = True def _init(self, config=None): ''' >>> pp=plugin.Plugin() >>> pp._init(dict(socket_uri="ws://127.0.0.1:8009")) >>> pp.socket.send('cake') 10 ''' self.msgs = [] config = config or self.config or {} self._mount(config) def _connect(self, uri): ''' >>> pp=plugin.Plugin() >>> pp._connect("ws://127.0.0.1:8009") >>> pp.socket <websocket._core.WebSocket object at 0x0000000002E2E940> ''' socket = json_socket.get_socket() if uri is not None: socket = json_socket.get_or_create(uri) log('Connected new socket') return socket def _mount(self, config): log('Mounting') config = config or self.config or {} self.uri = config.get('socket_uri', None) self.socket = self._connect(self.uri) v = config.get('recv_thread', self._recv_thread) log("Mounting thread:", v) if v is True: self.recv_thread() def recv_thread(self): self.lock = threading.Lock() self.thread = SocketWorker( name='plugin_worker', target=self._worker_message, args=(self.uri, self.lock,), kwargs=dict(plugin=self), ) self.thread.start() def _worker_message(self, msg): log('Plugin class received msg from worker', msg) wait_request = self._recv(msg) return 1 def _announce(self): _type = self._type or self.mount_type self.socket.send(dict(type=_type, msg='_announce')) def _recv(self, msg): '''received an incoming msg from the connected client''' self.msgs.append(msg) <file_sep>/src/plog/api.py ''' Plog. The api reads through the given file, provided starters, terminators and key value pair definitions, output it parsed and applied to an object - later passed through the api into the django model Usage: api.py Options: --pre-compile=False Optionally don't complile string patterns before use ''' #import docopt from plog import mixins from plog.patterns import PlogLine, PlogBlock from termcolor import colored import sys try: from colorama import init init() except: pass class Plog( mixins.PlogFileMixin, mixins.PlogBlockMixin): EMPTY_LINE = '\r\n' # Set the whitespace character whitespace = ' ' # A file is read as each line # But many commands can be passed # into a line. terminator = ';' def __init__(self, *args, **kwargs): self.open_box = None self.hash_state = {} self.line_count = 0 self.data_blocks = [] self.open_blocks = {} self.terminator = kwargs.get('terminator', self.__class__.terminator) self.whitespace = kwargs.get('whitespace', self.__class__.whitespace) super(Plog, self).__init__(*args, **kwargs) def run(self, parser=None): ''' Begin the process, working the passed file. Pass an enumerator method to call on each line detection ''' if parser is None: parser = self.parse_line self.compile_blocks() _file = self.get_file() line_no = 0 for line in _file: line_no += 1 clean = self.clean_line(line) for cl in clean: parser(cl, line_no=line_no) self.close_data_blocks( *self.close_all_blocks() ) return self.data_blocks def clean_line(self, line, strip=True): ''' Return a value of clean information for a single line from the file ''' stripped = line[:-1] cleaned_line = stripped.replace(self.whitespace, ' ') split_line = cleaned_line.split(self.terminator) splits = [] for s in split_line: splits.append(s.strip()) return splits def close_data_blocks(self, *args): ''' Safely close the open block and remove from open block elements. Add data block to return the data blocks ''' dbs = [] for block in args: # import pdb; pdb.set_trace() if block.is_open: block.close() data_block = self.open_blocks[block] self.data_blocks.append(data_block) dbs.append(data_block) self.open_blocks[block] = None return dbs def parse_line(self, line, *args, **kwargs): ''' method is passed to the run and receives a single line string to parse and apply PlogLine and PlogBlock ''' # Make a plog line. pline = PlogLine(line, line_no=kwargs.get('line_no', -1)) self.line_count += 1 # Find header_line blocks matching this pline blocks, is_header = self.get_blocks_with_header_footer(pline) # one or more blocks detected pr = '' for block in blocks: if block.is_open is not True and is_header: block.open() bl = PlogBlock(ref=block) bl.header = block.header bl.footer = block.footer bl.lines = block.lines bl.line_refs = block.line_refs bl.open_lines = block.open_lines self.open_blocks[block] = bl pr = '#%s+' % colored(pline.line_no, 'grey') else: if block in self.open_blocks and is_header is not True: self.open_blocks[block].add_data(pline) data_blocks = self.close_data_blocks(block) pr = colored('-', 'red') s = '~%s#%s' % ( colored(len(data_blocks), 'grey'), colored(pline.line_no, 'grey'), ) # sys.stdout.write(s) for block in self.open_blocks: if block.is_open: added = self.open_blocks[block].add_data(pline) v = colored('_', 'grey') if added is not True: if pline.value != '': v = colored('_', 'red') self.open_blocks[block].add_missed(pline) else: v = '' pr = '%s%s' % (pr, v) bl = len(blocks) if bl > 0: ct = ( colored('[', 'grey'), colored('%s' % bl, 'white'), colored(']', 'grey'), ) d = "%s%s%s" % ct # sys.stdout.write(d) # sys.stdout.write(pr) <file_sep>/src/v3/typemap.py type_map = { 'CC' :'Coordinating conjunction', 'CD' :'Cardinal number', 'DT' :'Determiner', 'EX' :'Existential there', 'FW' :'Foreign word', 'IN' :'Preposition or subordinating conjunction', 'JJ' :'Adjective', 'JJR' :'Adjective, comparative', 'JJS' :'Adjective, superlative', 'LS' :'List item marker', 'MD' :'Modal', 'NN' :'Noun, singular or mass', 'NNS' :'Noun, plural', 'NNP' :'Proper noun, singular', 'NNPS' :'Proper noun, plural', 'PDT' :'Predeterminer', 'POS' :'Possessive ending', 'PRP' :'Personal pronoun', 'PRP$':'Possessive pronoun', 'RB' :'Adverb', 'RBR' :'Adverb, comparative', 'RBS' :'Adverb, superlative', 'RP' :'Particle', 'SYM' :'Symbol', 'TO' :'to', 'UH' :'Interjection', 'VB' :'Verb, base form', 'VBD' :'Verb, past tense', 'VBG' :'Verb, gerund or present participle', 'VBN' :'Verb, past participle', 'VBP' :'Verb, non-3rd person singular present', 'VBZ' :'Verb, 3rd person singular present', 'WDT' :'Wh-determiner', 'WP' :'Wh-pronoun', 'WP$':'Possessive wh-pronoun', 'WRB' :'Wh-adverb', '.': 'Puncuation', } simplify = { 'verb': ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ',], 'pronoun': ['PRP' , 'PRP$', 'WP' , 'WP$',], 'adjective': ['JJ', 'JJR', 'JJS', ], 'noun': ['NN', 'NNS', 'NNP', 'NNPS'], } noun = { 'antsn':"Antonyms", 'hypen':"Hypernyms", 'hypon':"Hyponyms & Hyponym Tree", 'treen':"Hyponyms & Hyponym Tree", 'synsn':"Synonyms (ordered by estimated frequency)", 'attrn':"Attributes", 'derin':"Derived Forms", 'domnn':"Domain", 'famln':"Familiarity & Polysemy Count", 'coorn':"Coordinate Terms (sisters)", 'grepn':"List of Compound Words", 'over':"Overview of Senses", } verb = { 'antsv':"Antonyms", 'hypev':"Hypernyms", 'hypov':"Hyponyms & Hyponym Tree", 'treev':"Hyponyms & Hyponym Tree", 'synsv':"Synonyms (ordered by estimated frequency)", 'deriv':"Derived Forms", 'famlv':"Familiarity & Polysemy Count", 'framv':"Verb Frames", 'coorv':"Coordinate Terms (sisters)", 'simsv':"Synonyms (grouped by similarity of meaning)", 'grepv':"List of Compound Words", 'over':"Overview of Senses", } adj = { 'antsa':"Antonyms", 'synsa':"Synonyms (ordered by estimated frequency)", 'domna':"Domain", 'famla':"Familiarity & Polysemy Count", 'grepa':"List of Compound Words", 'over':"Overview of Senses", } attrs = { 'h':'Print help text before search results.', 'g':'Display textual glosses associated with synsets.', 'a':'Display lexicographer file information.', 'o':'Display synset offset of each synset.', 's':'Display each word\'s sense numbers in synsets', 'l':'Display the WordNet copyright notice, version number, and license.', 'n#':'Perform search on sense number # only.', 'over':'Display overview of all senses of searchstr in all syntactic categories.', } REL_HEADINGS = { 'en': { '/r/SimilarTo': ['Similar terms'], '/r/RelatedTo': ['Related terms'], '/r/Synonym': ['Synonyms'], '/r/Antonym': ['Antonyms'], '/r/FormOf': ['Word forms', 'Root words'], '/r/HasContext': ['Terms with this context', 'Context of this term'], '/r/DerivedFrom': ['Derived terms', 'Derived from'], '/r/IsA': ['Types of {0}', '{0} is a type of...'], '/r/EtymologicallyRelatedTo': ['Etymologically related'], '/r/AtLocation': ['Things located at {0}', 'Location of {0}'], '/r/Causes': ['Causes of {0}', 'Effects of {0}'], '/r/UsedFor': ['Things used for {0}', '{0} is used for...'], '/r/NotUsedFor': ['Things that are not used for {0}', '{0} is not used for...'], '/r/MotivatedByGoal': ['Things motivated by {0}', '{0} is motivated by...'], '/r/HasSubevent': ['Subevents of {0}', '{0} is a subevent of...'], '/r/DistinctFrom': ['Distinct terms'], '/r/CapableOf': ['Things capable of {0}', '{0} is capable of...'], '/r/NotCapableOf': ['Things incapable of {0}', '{0} is not capable of...'], '/r/Desires': ['Things that want {0}', '{0} wants...'], '/r/NotDesires': ["Things that don't want {0}", "{0} doesn't want..."], '/r/PartOf': ['Parts of {0}', '{0} is part of...'], '/r/HasPrerequisite': ['Things that require {0}', '{0} requires...'], '/r/CausesDesire': ['Things that make you want {0}', '{0} makes you want...'], '/r/HasProperty': ['Things with the property {0}', 'Properties of {0}'], '/r/MadeOf': ['Things made of {0}', '{0} is made of...'], '/r/HasFirstSubevent': ['Things whose first step is {0}', '{0} is the first step of...'], '/r/HasLastSubevent': ['Things whose last step is {0}', '{0} is the last step of...'], '/r/DefinedAs': ['Things defined as {0}', '{0} is defined as...'], '/r/ReceivesAction': ['Things that can be {0}', '{0} can be...'], '/r/HasA': ['Things with {0}', '{0} has...'], '/r/SymbolOf': ['Symbols of {0}', '{0} symbolizes...'], '/r/ObstructedBy': ['{0} obstructs...', '{0} is obstructed by...'], '/r/Entails': ['Things that entail {0}', '{0} entails...'], '/r/CreatedBy': ['Things created by {0}', '{0} is created by...'], '/r/MannerOf': ['Ways of {0}', '{0} is a way of...'], '/r/LocationOfAction': ['Places where {0} happens', '{0} happens at...'], '/r/Uses': ['Things that use {0}', '{0} uses...'], '/r/ControlledBy': ['{0} controls...', '{0} is controlled by...'], '/r/LocatedNear': ['Things located near {0}', '{0} is near...'], '/r/ExternalURL': ['Links to ConceptNet', 'Links to other sites'], } } <file_sep>/docs/writes/industry graph.md # Large Graphs Representing an Entire Field Starting in ab abstract thought - When working with the _context_ of one word - such as "apple" we can derive more than one concept. Building a graph upon a single context will require temporal knowledge of previous context and the general input (a sentence). If a person said "I work for Apple I build shopping carts" we can deduce they are a developer in a _(arguably sort-after)_ programming role building product puchase interfaces. On the contrary "I work with apples making carts" would denote an apple cart maker or some sort of carpenter/joiner. The two sentences are dependant upon context of the environment - and previously aquired knowledge of a programmers role and the Apple company. Denoting the correct context to continuation is complex through a single graphing space. Dividing graphing knowledge by parental association - such as a field of industry - it's easier to perform weighted reasoning and discover _which context_ is the relevent graph. In process, a `Graph('developer')` and a `Graph('carpenter')` maintain individual previously trained associations. 'developer' has 'programmer' and 'computing' etc... and 'carpenter' maintains more 'wood-work', 'hand work' etc... The two graphs bridge through _cart_ or "shopping cart" / "... carts". Simply being the same word is enough to assume an edge connection. During a read procedure 'carpenter' will have a lesser association to 'apple', 'shopping'. + 'Apple' _has_ employees + 'carpenter' _performs_ ("making") with wood + a card _madeof_ wood. The weights from the above assumed connections defines higher priority for the relevant graph through seperated context graphs. A sentence is weighted by both graphs. Our example graphs `developer` and `carpenter` provide a weighted result for a given sentence to the 'weighting and reasoning module'. The reasoning module should assess all graphs (in our case 2 of them) for a single string "I work for Apple I build shopping carts". It assess the overall given result value (a overall weight) - the distance to calulcation (still to be done) and some soft of API for its evidence. The reasoning graph will assess a thinner graph for a goal such as a 'win' value and driven by an ML for semantic reasoning. It will also re-assess parts of a result graph it sees as incomplete; Providing additional _questions_ for a greater graph response. This will include firing requests to modules the result graph does not have access to - such as a sentiment module, a external-sources module etc... Once the reasoning has applied any additional results to a graph and finalised a weight against all other graphs in this overall context (our two strings). The result is given to the translate, long-term and recursive analysis modules. <file_sep>/dev-requirements.txt autocorrect certifi chardet idna nltk numpy -e git+https://github.com/Strangemother/pocketsocket.git@722d4cfa6bf3b6354f10efe06431d1613ca5e9bd#egg=pocketsocket requests urllib3 websocket-client <file_sep>/docs/writes/weighting words.md Weighting words Due to the nature of a contextnet single words provide no weighted context within a graph without context. Take the word “food” as an input value. It provides no relevance to a situation or cnext. Without previous input, this statement is considered a _shout in the street_. However when used in context: “What do you need?”, “food.” - it contains a sense of urgency. To apply this to weighting, a single word defines knowledge without weighting. Given some context, a word can be weighted. Given any context the system should weight the word against all viable context objects. The weight value does not have defined limits as its final value will depend upon the complexity of the context and the maturity of an existing dataset. Any weights defined through context chaining will provide a numerical value to store against a given sequence of words. A sentence: such as “I need food” contains more contextual weight than “I like food”, furthermore the context “give food” contains less context to weight (devoid of “I”) but should yield a heavier weight as there is a machine action to perform. If we relied on knowledge weighting alone, we’d see a lesser weight for the sentence “give food” because of its lack of input nodes to weight. <file_sep>/src/v5/context/first/migrations/0007_auto_20190728_0055.py # Generated by Django 2.2.3 on 2019-07-27 23:55 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('first', '0006_auto_20190728_0026'), ] operations = [ migrations.CreateModel( name='DefinitionType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('value', models.CharField(max_length=255)), ], ), migrations.CreateModel( name='DefinitionValueType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('value', models.CharField(max_length=255)), ], ), migrations.CreateModel( name='Definition', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('value', models.TextField()), ('associate', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='first.DefinitionType')), ('type', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='first.DefinitionValueType')), ], ), migrations.AddField( model_name='tokenword', name='dictionary', field=models.ManyToManyField(to='first.Definition'), ), ] <file_sep>/src/v2/dbt.py from conceptnet import sqlite_db db = sqlite_db.spread_db() <file_sep>/src/graph_ui/static/js/table.js var cleanData = [] var bus = new Vue({ }) var questionInput = new Vue({ el: '#question_input' , data: { question: 'hello' , lastQuestion: '' , messages: [] } , mounted(){ bus.$on('message', this.wsMessage.bind(this)) } , methods: { wsMessage(data) { //console.log('input from socket', data) let tokens = data.data.tokens if(tokens == undefined) { tokens = []} if(data.data.action) { this.messages.unshift({ action: data.data.action , tokens: [].slice.call(tokens, 0) }) } // bus.$emit('message', data) } , getWord(word) { getWord(word) } , clear(){ wordView.nodes().clear() } , inputString(event) { console.log('Enter Key', this.question) getWord(this.question) this.lastQuestion = this.question this.messages.push(this.question) this.question = '' } } }) var tableView = new Vue({ el: '#table_view' , data: { words: ['cake'] } , mounted(){ bus.$on('word', this.wordEvent.bind(this)) } , methods: { wordEvent(data) { console.log('word event') for(let item of data.edges) { this.addLine('edges', item, data.word) } for(let item of data.rev) { this.addLine('rev', item, data.word) } } , addLine(group, entity, word) { let line = { group, from: word } line.rel = entity[0] line.word = entity[1] line.weight = entity[2] this.words.push(line) } } }) var words = {} var getWord = function(word, limit=-1){ var enterWord = function(data) { bus.$emit('word', data) } if( words[word] != undefined && words[word].limit >= limit ) { enterWord(words[word].data) } let path = `/word/${word}/` if(limit != -1){ path = `/word/${word}/${limit}` } $.get(path, function(data){ words[word] = { limit, data } enterWord(data) }) } //$(function(){ // if ('speechSynthesis' in window) { // speechSynthesis.onvoiceschanged = function() { // var $voicelist = $('#voices'); // // if($voicelist.find('option').length == 0) { // speechSynthesis.getVoices().forEach(function(voice, index) { // console.log(voice); // var $option = $('<option>') // .val(index) // .html(voice.name + (voice.default ? ' (default)' :'')); // // $voicelist.append($option); // }); // // $voicelist.material_select(); // } // } // // $('#speak').click(function(){ // var text = $('#message').val(); // var msg = new SpeechSynthesisUtterance(); // var voices = window.speechSynthesis.getVoices(); // msg.voice = voices[$('#voices').val()]; // msg.rate = $('#rate').val() / 10; // msg.pitch = $('#pitch').val(); // msg.text = text; // // msg.onend = function(e) { // console.log('Finished in ' + event.elapsedTime + ' seconds.'); // }; // // console.log(speechSynthesis); // // speechSynthesis.speak(msg); // }) // } else { // $('#modal1').openModal(); // } //}); <file_sep>/docs/writes/hello.md # Hello A simple command "hello" should invoke the translator and resolve a greeting. hello > is > greeting on greeting > hello <file_sep>/src/v5/merge/main.py import requests from collections import namedtuple, defaultdict import operator from pprint import pprint as pp # Connect to an endpoint for graph pulls. # This one is the duplex endpoint. import argparse ENDPOINT = 'http://127.0.0.1:9005' parser = argparse.ArgumentParser(description='Edge Weight Analysis') parser.add_argument('-w', '--words', default=['hello'], nargs='+', help='input word') args = parser.parse_args() def main(): for word in args.words: aa = perform_word_weights(word, others=args.words, step_edge_keys=['rev']) bb = perform_word_weights(word, others=args.words, step_edge_keys=['edges']) import pdb; pdb.set_trace() # breakpoint 54b72926 // def perform_word_weights(word, others=None, step_edge_keys=None): other = others or [] upper, lower, dropped = perform(word=word, step_edge_keys=step_edge_keys, others=others, add_self=False) # Note "dropped" aren't ignored - they're just not forward edges... """ Contains: + The (upper, lower) list of edges for the given word, split by threshold. + A first step (forward "edges") of each highest weighted edge. (of any word with connected len(edges) > 0) + dropped: a list of high weighted primary edges without any decendents this may be due to the child edges.weight < threshold. cross reference all primary edges, for a forward reference of the root word primary primary: Keep cross-referenced and populate the top 50% weighted (above threshold.) primary secondary: keep all (without a cross reference) 50% top weighted - for population later. lower: anything ignored through the top query Once done with the "upper" - perform with the lower. then the 'lower lower' in a background process. """ print('Upper:') print_group(upper) print('---\nLower:') print_group(lower) print('---\nUpper Dropped:') print_group(dropped) ubias = cross_reference_first_layer(word, upper, dropped, others) lbias = cross_reference_first_layer(word, lower, dropped, others) tbias = merge_biases(ubias, lbias, word=word) print('lower bias:') pp(lbias) print('upper bias:') pp(ubias) print('total bias:') pp(tbias) biases = (lbias, ubias, tbias,) graphs = (upper, lower,) return graphs, biases, dropped def cross_reference_first_layer(word, upper, dropped, others=None): """Given a range of grouped edges, return weighted preferences by distance through 'word' """ upper_w = count_as_child(word, upper, others=others) ## lower_w = count_as_child(word, lower) # A reference of all edges (words) of which have a forward edge of the "word." # as a hint for a strong connection. # (Pdb) uw = {'chicken': 1, 'yolk': 1, ... } # (Pdb) lw = {'chicken': 1, ... 'chick': 1} # Get additional weight drop_upper_bias = get_biases(dropped, upper, others=others) ## drop_lower_bias = get_biases(dropped, lower) pp(upper_w) pp(drop_upper_bias) print('---') # Get a list of weight bias # to use later during scanning. ubias = merge_biases(upper_w, drop_upper_bias, word=word) # do the same cross reference for # top bias children. # Distance calculation defines additional biases. return ubias def merge_biases(*bias_dicts, word=None): """ a bias defines some additional weight to compute an edge relation. get_bias returns a dict of counts for a given group against another group. {'polite/a': 1, 'wax': 1} Provide a 'word' for extra context. {'buff': 1, 'rub': 1, 'silver': 1} {'shine': {'wax': 1}, 'shiny': {'silver': 1}} {'buff': {'buff': 1}, 'cleaner': {'cleaner': 1}, ... 'shiny': {'clean': 1, 'shiny': 1, 'wax': 1}, 'warsaw': {'poland': 1, 'warsaw': 1}} """ res = defaultdict(int) for bias_dict in bias_dicts: for word, content in bias_dict.items(): if isinstance(content, dict): # The word is a dictionary, # therefore apply a reference weight # rather than 1 - a edge base weight res[word] += .5 for key, val in content.items(): res[key] += val else: # standard int res[word] += content return dict(res) def get_biases(edge_group, goal_edge_group, others=None): # do the same with drops. # then also use each drop as a parent word # applying as a weighted top for upper and lower. dropped_w_u = {} for edge, edges in edge_group.values(): uweights = count_as_child(edge.word, goal_edge_group, others=others) if len(uweights) > 0: dropped_w_u[edge.word] = uweights # {'embryo': {'seed': 1}, 'lays': {'chicken': 1}} return dropped_w_u def find_shared_edges(edge_list_a, edge_list_b): """ + Find any words found within the edges of two graphs. + Finding the bridge or "connecting" edge for two lists. + given two word lists, find matching word edges return the connect words and the assicated edges. This is useful for connecting two graphs with an edge word alpha beta cake muffin egg break milk egg cheese cheese return egg, cheese """ def count_as_child(word, edges_group, weights=None, others=None): """Count instances of `word` within the edge list of each key within the edges_group. word: 'egg' edges_group: { chicken: [yolk, other, egg] } return dictionary of counts { chicken: 1 } """ weights = weights or defaultdict(int) # find primary references ## look through upper for first reference of word. for primary_edge, primary_edges in edges_group.values(): pw = primary_edge.word #print('Word', pw) if word == pw: # do nothing with a self reference. weights[word] = 1 continue primary_edges = sort_edges(primary_edges) for edge in primary_edges: #print(f' {edge.word}') if edge.word == word: # An edge of the edge (of the root word) # matches the root word. weights[pw] += 1 continue if edge.word in others: # Given additional bias. weights[pw] += 1 return dict(weights) def sort_edges(edges, key='weight', decending=False): name = 'itemgetter' if isinstance(key, str): name = 'attrgetter' getter = getattr(operator, name)(key) return sorted(edges, key=getter, reverse=not decending) def perform(word, edge_keys=None, step_edge_keys=None, add_self=False, others=None, threshold=1): # Read edges, anaylse topolgies, brdge and call more words print('Analyse word', word) group_upper = {} group_lower = {} upper, lower = get_word_split_edges(word, edge_keys) if add_self: # Append the existing word to the work stacks. group_upper[word] = (None, upper) group_lower[word] = (None, lower) # populate all relations for each primary edge. # But onky the forward policy. step_edge_keys = step_edge_keys or ['edges'] upper_forward_groups = get_edges_words(upper, edge_keys=step_edge_keys) # not rev gu, gl, dropped = remove_edgeless(upper_forward_groups, group_upper, group_lower, threshold=threshold) return gu, gl, dropped def remove_edgeless(groups, upper=None, lower=None, threshold=1): group_upper = upper or {} group_lower = lower or {} dropped = {} for key_word, (edge, (upper, lower,), ) in groups.items(): """ Upper: cook 2.0 (39) - measure_flour, prepare_meal, ... measure_flour 4.899 (0) - ... prepare_meal 4.899 (0) - ... """ #key = key_word# f"{word}-{key_word}" # remove any group without an edge list if len(upper) > 0: group_upper[key_word] = (edge, upper, ) else: if edge.weight > threshold: # Although highly weighted, the given edge yeilds no forward # edges... dropped[key_word] = (edge, lower,) if len(lower) > 0: group_lower[key_word] = (edge, lower, ) return group_upper, group_lower, dropped def print_group(gu): _max = 8 key = 'word' edge_val ='weight' le = 'len' el = 'items' ext = '' rel = 'relation' s = f" {rel:<12} {key:<20} {edge_val:<6} {le:<5} {el}{ext}" print(s) print('-' * len(s)) for key, (edge, edges,) in gu.items(): el = ", ".join([x.word for x in edges[0:_max]]) # edge_val is none if the given item entry was the root word. # therefore has no edge. edge_val = '-' if edge is None else edge.weight le = f"{len(edges)}" rel = '-' if edge is None else edge.rel ext = ' ...' if len(edges) > _max else '' s = f" {rel:<12} {key:<20} {edge_val:<6} {le:<5} {el}{ext}" print(s) def print_edges(edges): for edge in edges: le = len(edge) s = f" {edge.rel:<12} {edge.word:<20} {edge.weight:<6} {le:<5}" print(s) def get_word_split_edges(word, edge_keys=None): data = get_word(word) # produce flat, sort by weight. # (upper, lower) return split_multi_edges(data, edge_keys=edge_keys) def get_edges_words(edges, edge_keys=None): """ read the given edges iterable and call each word """ result = {} for edge in edges: result[edge.word] = (edge, get_word_split_edges(edge.word, edge_keys=edge_keys)) return result def split_multi_edges(data, threshold=1, edge_keys=None): """split the json raw data into an upper and lower edges stack 'edges': [ ['IsA', 'greeting', 3.464], ... ['EtymologicallyRelatedTo', 'hollo', 0.25] ], 'key': 'hello', 'limit': 0, 'rev': [ ['RelatedTo', 'rehi', 2.0], ... ], 'word': 'hello' """ # Applicable iterables. edge_keys = edge_keys or ['edges', 'rev'] _upper = [] _lower = [] for ek in edge_keys: # produce a higher and lower range. e_upper, e_lower = split_edges(data[ek], ek, threshold=1) _upper.extend(e_upper) _lower.extend(e_lower) return _upper, _lower Edge = namedtuple('Edge', ["type", "rel", "word", "weight"]) def split_edges(edges, key_type, threshold=1): # Split the stack based upon a simple threshold. _upper = [] _lower = [] for edge_line in edges: _edge = Edge(key_type, *edge_line) #print(f"edge {_edge.word}, {_edge.weight}") stack = _lower if _edge.weight <= threshold else _upper stack.append(_edge, ) return sort_edges(_upper), sort_edges(_lower) def get_word(word, limit=0): p = f'word/{word}/{limit}' edge_d = get_request(p) return edge_d request_cache = {} def get_request(url, use_cache=True): # perform and merge the request for all resources if (url in request_cache) and use_cache is True: return request_cache[url] path = f"{ENDPOINT}/{url}" print('Fetch', path) res = requests.get(path) if res.ok: res = res.json() request_cache[url] = res return res print('Error with', path, res) return res if __name__ == '__main__': main() <file_sep>/src/graph_ui/main.py """Using flask to expose the main entry point as it makes it easier to expose an input thread. Individual threads will boot manually or attached through manual setup """ # from multiprocessing import Process, Queue import flask from flask import Flask, render_template from flask import jsonify import os import sys import argparse BASE_PATH = os.path.dirname(os.path.abspath(__file__)) IMPORT_PATH = os.path.normpath(os.path.join(BASE_PATH, '..')) DB_PATH = "E:/conceptnet/_lmdb_assertions/" #E:\conceptnet\_lmdb_assertions_july_2019_rev SERVER_DB_PATH = "E:/conceptnet/_lmdb_server_ui/" parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('--path', default=DB_PATH, help='Alternative DB path') parser.add_argument('-p', '--port', default=9000, help='Server port') parser.add_argument('--table', default='assertions', help='Alternative (DB) table name') cli_args = parser.parse_args() sys.path.append(IMPORT_PATH) from database import graph import database from database import db gdb = None udb = None app = Flask(__name__) @app.before_first_request def initialize(): global gdb global udb p = cli_args.path print('Opening Graph.', cli_args.table, p) gdb = graph.GraphDB(directory=p, name=cli_args.table) print('Opening Persistant Local') udb = db.AppendableDB(directory=SERVER_DB_PATH, name='inputs') print('DB Open {} {}'.format(gdb, udb)) def main(): app.run( debug=True, host='127.0.0.1', port=cli_args.port, ) @app.route('/word/<word>/') @app.route('/word/<path:word>/<int:limit>') def get_word(word, limit=False): gp = gdb.pick(word) text_edges = gp.edge_text(True) items = sorted(gp.edge_list(), reverse=True) limit_c = None if limit is not False: limit_c = 50 if isinstance(limit, int): limit_c = limit if limit_c is not None and limit_c != 0: items = items[:limit_c] else: limit_c = len(items) text_edges = graph.Edges(items=items)._text_list(True) key = gp.key result = dict(limit=limit_c, edges=text_edges, key=key, word=word) return jsonify(result) @app.route("/") def index_page(): return render_template('index.html',) if __name__ == '__main__': main() <file_sep>/docs/writes/knowledge layer.md # Knowledge layer The input of string as data input should be split into a contextual layer of connections, and a knowledge connection set in parallel. The context layer contains the associations and weights of words within the graph. Connections through words will raise and lower a weighting on the context chain. Better context chain weights yield a list of viable sentence structures. Each sentence structure is future weighted and contualized until a resolution yields a winning context. This occurs asynchronously to output and temporal input, therefore a dynamic tree of viable contexts should be constantly validated. The knowledge layer is the ‘under’ layer of graphing words, defined as strongly weighted statements to validate against. The knowledge layer is built through three distinct inputs. Initially hardcoded or operator written instructions define the base of ‘trueims’. These sentences are valid, albeit require a layer of input to justify. A simple sentence ‘operator is human’ is 100% accurate but the sentence requires a binding to ‘is’, another hardcoded statement. Although mandatory, the goal is little to zero hard coded parameters, opting for a _metal layer_ definitions like a seperate api or microcontroller. This is expanded for deeper contexts with a tighter focus on a context. Semantic weighting is applied as a seperate layer providing assumptions on ‘no’ and other heavy sentiments. A sentence is broken in small components defining elements to populate the floating context. An immediate net will handle input weighting on full sentences, “the cat sat on the mat”. We [a human] can easily understand the context of this statement. Logically we can break this down to its constituents we’d require for context. Firstly we see in this case ‘the’ is an identification. I'm assuming a basic tokenizer would define it as a determiner or logical placeholder. In out case it’s in reference to ‘a’ cat. We need to make a leap here and state we can hardcode ‘the == a’, or one item. ‘The door’ ,’the person’ - with a relative context: “a door” _near hear_. Again conceptually, we have a reference to ‘here’. The knowledge graph connects this to ‘location’, ‘local’... and the first or second layer defines a location being ‘room’, ‘house’ or even less definitively, a context of the local environment. This model design starts to take shape when given a greater contextual reference. Over time the interconnected graph of associated contexts (through words as objects) build a tree of agreeable associations, regardless of the context word.’the stuff in my room’ has visible evidence of object continuity given the context of: The stuff I’ve concatenated this point, as we can infer ‘a stuff’. This alone makes no sense - however one amount of the context referencing ‘stuff’ can be abstracted. In Parameterization of a given entity (in our case ‘stuff’) nearly always requires a location. Nltk tokensation does a great job of detection locatity with reference. Here we can see one ‘stuff’ exists in the incoming location My Out of order sequence is expected and is apart of the context api through the graphing. Reference ‘my’ is ownership to the operator. We can infer a hard coded path of ‘my == operator’ for now. Defining ‘operator room’. Room A location definition for the entity in context. The ‘room’ is another contextual reference. Which room, whos room - more importantly, what a room is. This context relys more upon previously conceptualized entities. Building to this requires a slow growth of _room be owned by_ or _can have an operator_ Okay, so the definition of how these words are initially abstracted gives us another - seemly uglier sentence: “one stuff [atlocation] operator [?location]”. Earlier we hardcoded the ‘operator’. The location parameter is hard to define. I don’t believe i've trained ‘room’ yet. However the context connection does have house, location, place - stuff like that. Driving the connection would require a context chain of ‘operator => at => room’ and ‘room => hasa => location’. These chains are easily defined through graphing. Given the appropriate sentence weight and existing context object _operator_, we’ve got a tenuous link to a location context. Later we remove the ambiguity through a graph weight comparison. From here we’ll define a context object as CO. Defining a word reference ‘toast’ or ‘door’ or ‘stuff’ with parameters and graph connections to other CO objects. The attributes for a CO are fluid through soft training, but commonly we’d need a location, owner, name… elements we define for a real world object. Now we can draw the CO required to store the sentence ‘one stuff [atlocation] operator location’. The tokenizer provides a tree [one stuff] atlocation [operator location]. Ignoring recurring tokenization to simplify this further, we can see how this chain evolves some context objects. ‘Stuff’ is nothing, it has no reference - the graph reveals thin connections needing stripped.essentially it could be an anything… but here our entity is named purely ‘stuff’. As this is a new context there will be no existing ‘stuff’ CO. we can make a new one and name it CO1, giving it an graph name ‘word’. Populating further with reference of ‘count’, a previous branch to ‘one’ is given a largest weight. Stepping through layered COs for We’ve focused mostly on very small examples and cheap sentences. This is mostly due to the computational requirements of larger nets. Sentences greater than four words of arbitrary commands tends to graph more than 1000 word references. Converting all this to a CO net is not probable. Instead small contexts kept in local reference, with layered COs dedicated to a reference. To shortcut expensive sentences we can utilize the temporal nature of a CO net by solidifying certain patterns through AI training and hard coding graph chains. Using the following example: “Turn the light on before I enter”, or perhaps to a child “open the window, but clean up first”. Both sentences are prone to disambiguation <file_sep>/__main__.py from src.main import main as src_main def main(): src_main() if __name__ == '__main__': main() <file_sep>/src/v2/core/server.py """Using flask to expose the main entry point as it makes it easier to expose an input thread. Individual threads will boot manually or attached through manual setup """ from multiprocessing import Process, Queue import flask from flask import Flask from core.run import run_core, thread_run from log import log app = Flask(__name__) global_prc = None proc_q = None def main(): app.run( debug=True, host='127.0.0.1', port=9000, ) def proc_start(): global global_prc global proc_q if global_prc is not None: return global_prc options = {} global_prc, proc_q = thread_run(proc_q, options) return global_prc def proc_stop(): global global_prc if global_prc is None: return True proc_q.put_nowait('kill') log('sent kill command, waiting for death.') global_prc.join() log('Stop complete') global_prc = None return True @app.route("/start") def start(): proc_start() return "Run main thread!" @app.route("/") def index_page(): proc_start() return "first page. Welcome." @app.route('/put/<sentence>') def put_string(sentence): proc_q.put(sentence) return sentence @app.route("/stop") def stop(): proc_stop() return "kill thread" if __name__ == '__main__': main() <file_sep>/src/v5/context/first/bridge.py import sys sys.path.append('C:/Users/jay/Documents/projects/context-api/context/src') from database.graph import * import database from database.db import * ASSERTIONS_DIR = "E:/conceptnet/_lmdb_assertions/" BRIDGE_DB_DIR = "E:/conceptnet/_lmdb_server_ui/" """The persistent source of original knowledge. held in the shared resource.""" assertions_db = GraphDB(write=False, directory=ASSERTIONS_DIR, name='assertions') """Any relative data to store for the internal procedures.""" db = GraphDB(directory=BRIDGE_DB_DIR, name='bridge') <file_sep>/src/server/ws.py # import websocket # ws = websocket.WebSocket() # ws.connect("ws://example.com/websocket", http_proxy_host="proxy_host_name", http_proxy_port=3128) from pocketsocket.ws import Client from pocketsocket.client import ClientListMixin from pocketsocket.server import Server def main_echo(): server = EchoServer() server.start() class EchoClient(Client): def recv(self, data, opcode): # log('>', self, opcode, data) self.send_all(data, opcode, ignore=[self]) def send(self, data, opcode=None): # log('<', self, opcode, data) return self.sendMessage(data, opcode) class EchoServer(ClientListMixin, Server): ''' Basic instance of a server, instansiating ws.Client for socket clients ''' ports = (9004, 9005, ) address = '0.0.0.0' client_class = EchoClient if __name__ == '__main__': main_echo() <file_sep>/src/database/example.py # from database.db import DB # WRITE_ENV = "E:/conceptnet/_lmdb/" # db = DB(WRITE_ENV) # db.open(b'test') # db.put(b'as', b'weqr') # print(db.get('as')) from database.db import AppendableDB from database.db import * from database.graph import GraphDB, ObjectDB # dd=AppendableDB(name='test') # import pdb; pdb.set_trace() # breakpoint f5263566 // # dd.put('tuple', (1,2,3,4,5)) gb = ObjectDB(name='graph_pick') gb.wipe() key='Hello' gb.add(key, 'isa', 'greeting', 3.4, 'hello') gb.add(key, 'isa', 'word', 3, 'hello') gb.add(key, 'isa', 'another', 1, 'hello') gb.add('greeting', 'similarto', 'Hello', 2) gb.add('greeting', 'similarto', 'hi', 2) gb.add('greeting', 'isa', 'welcome', 2) gb.add('hi', 'isa', 'greeting', 3) gb.add('word', 'isa', 'word', 1) gb.add('word', 'isa', 'thing', 1) gb.add('thing', 'etomology', 'law', 2) r = list(gb.iter()) print(r) p = gb.pick(key) p.isa.greeting.similarto.Hello.graph.isa.greeting.value == 'greeting' p_end = p.isa.greeting.similarto.Hello.isa.word walk_up = ( p_end # hello .parent_graph # greeting .parent_graph # Hello .parent_graph # DB .parent_graph ) law_chain =( p .isa .greeting .similarto .hi .isa .greeting .similarto .Hello .isa .word .isa .thing .etomology .law) # .chain() from pprint import pprint as pp a = zip( law_chain.edgenode_chain(True), law_chain.graph_chain(True) ) chain=list(a) chain.reverse() result = () for edge, graph in chain: if edge.parent_edgenode is not None: nv = edge.parent_edgenode.value else: nv = edge.parent_graph.key result +=( ( nv, edge.edge_type, graph.key, edge.weight),) expected = ( ('Hello', 'isa', 'greeting', 3.4), ('greeting', 'similarto', 'hi', 2), ('hi', 'isa', 'greeting', 3), ('greeting', 'similarto', 'Hello', 2), ('Hello', 'isa', 'word', 3), ('word', 'isa', 'thing', 1), ('thing', 'etomology', 'thing', 2) ) pp(result) print('test', gb.create_index(gb._data)) # {'Hello': (1, 1, 1), 'greeting': (2, 2, 2), 'hi': (3,), 'word': (4, 4), 'thing': (5,)} print('real', gb.index) # ( <Graph "thing" 1 edges of ('etomology',)>, # <Graph "word" 2 edges of ('isa',)>, # <Graph "Hello" 3 edges of ('isa',)>, # <Graph "greeting" 3 edges of ('isa', 'similarto')>, # <Graph "hi" 1 edges of ('isa',)>, # <Graph "greeting" 3 edges of ('isa', 'similarto')>, # <Graph "Hello" 3 edges of ('isa',)> # ) # gb.add('hey', 'synonym', 'hello', weight=2, root='hello') # gb.add(start='hi', edge='synonym', end='hello', weight=2, root='hello') # gb2 = AppendableDB(name='related') # assoc = ('musta', 1,) # assoc2 = ('greet', 1,) # gb2.put('hello', (assoc, assoc2,) ) # weight=1 # # hello related [to] hello > ... # gb.bind('hello', gb2) # # returns live Graph # r = gb.get('hello') # # Doesn't need to be 'get()', but it's dict friendly. # if r: # result = r.get('related') # expected = ( # ('musta', 1,), # ('greet', 1,), # ) # print(result == expected) # """Associate another DB through a name bound # to the key within the first db. # """ # # Auto bind hello > related > 'hello' # # from the DB name, and a like-for-like key name. # gb.bind('hello', gb2) # gb.bind( # # bind the name of the key within the original DB. # key='hello', # # the other db to bind to. # db=gb2, # # The key name to associate against the second db # through='more', # # The key for the given DB. Default is the given key # relation='hello' # ) <file_sep>/src/database/test_db.py import os import unittest import shutil import mock from mock import patch, Mock from database.db import DB, AppendableDB, GRow, MAX_BYTES from database.graph import * import database.db import time TEST_WRITE_ENV = "E:/conceptnet/_lmdb_test/" class TestDB(unittest.TestCase): def setUp(self): self.db = DB(directory=TEST_WRITE_ENV) def tearDown(self): if hasattr(self.db, 'env'): try: self.db.env.close() except Exception as e: print('Error for tearDown close', e) if os.path.isdir(TEST_WRITE_ENV): try: shutil.rmtree(TEST_WRITE_ENV) except PermissionError: print('PermissionError whilst deleting test database- Using db.wipe(True)...') time.sleep(1) self.db.wipe(True) shutil.rmtree(TEST_WRITE_ENV) self.assertFalse(os.path.exists(TEST_WRITE_ENV), 'tearDown did not Delete Test Directory.') def test_open(self): """Open a new DB, asserting the new directory data""" self.db.open('test') self.assertEqual(self.db.env.path(), TEST_WRITE_ENV) self.assertTrue(os.path.exists(self.db.env.path())) @patch('lmdb.open') def test_make_directory(self, lmdb_open): """Open a new DB, asseting the correct library methods are used""" self.db.open('test') args = self.db._open_args(map_size=MAX_BYTES) lmdb_open.assert_called_with(TEST_WRITE_ENV, **args) def test_destroy(self): db = self.db db.open('test_wipe') db.put('doggy', (1,2,3)) self.assertTupleEqual(db.get('doggy'), (1,2,3)) db.close() db.open('test_wipe') self.assertTupleEqual(db.get('doggy'), (1,2,3)) db.wipe() db.open('test_wipe') self.assertEqual(db.get('doggy'), None) db.put('doggy', (1,2,3)) db.close() db.open('test_wipe') self.assertTupleEqual(db.get('doggy'), (1,2,3)) db.start = Mock(side_effect=db.start) db.wipe(True) db.start.assert_called() self.assertEqual(db.get('doggy'), None) def test_put_raise_error(self): """Add a key value and assert its existence""" self.db.open('test_put') key, value = b'my_test_key', b'my test value' success = self.db.put(key, value) self.assertTrue(success) result = self.db.get(key) self.assertEqual(result, value) with self.assertRaises(TypeError): self.db.put('apple', 'green', encode_key=False) def test_put_without_save(self): self.db.open('test_put') key, value = b'my_test_key', b'my test value' self.db._transaction_success = Mock() success = self.db.put(key, value, save=False) self.assertTrue(success) self.assertEqual(self.db._transaction_success.call_count, 0) def test_decode_with_decode_func(self): class Foo: def __str__(self): return 'cake' self.assertEqual(self.db.decode(Foo()), 'cake') class Two: def decode(self, encode): return 1 def __str__(self): return 'cake' self.assertEqual(self.db.decode(Foo()), 'cake') self.assertEqual(self.db.decode(Two()), 1) self.assertEqual(self.db.decode(b'convert string'), 'convert string') def test_translate(self): key = b'window' self.assertEqual(self.db.translate(key), 'window') self.assertEqual(self.db.translate(b'!:str!:dog'), [b'str', b'dog']) def test_delete(self): """Add a key with put(), then delete. More deletes should yield false.""" # Use put for an input. self.db.open('test_put') key, value = b'my_test_key', b'my test value' self.db.put(key, value) success = self.db.delete(key) self.assertTrue(success) success = self.db.delete(key) # not thing to delete the second time self.assertFalse(success) success = self.db.delete(key) self.assertFalse(success) def test_keys(self): return_value = [1,2,3] self.db.iter = Mock(return_value=return_value) result = self.db.keys(cake=True) self.db.iter.assert_called_with(values=False, dups=False, convert=False, cake=True) self.assertCountEqual(result, return_value) def test_values(self): return_value = [1,2,3] self.db.iter = Mock(return_value=return_value) result = self.db.values(cake=True) self.db.iter.assert_called_with(keys=False, cake=True) self.assertCountEqual(result, return_value) def test_count(self): db = self.db db.open('test_count') db.put('a', 'b') db.put('c', 'c') db.put('c', 'd') self.assertEqual(db.count('a'), 1) self.assertEqual(db.count('c'), 2) def test_delete(self): db = self.db db.open('test_delete') db.wipe() db.put('a', 'b') db.put('a', 'e') db.put('b', 'c') db.put('c', 'd') db.put('c', 'e') db.put('d', 'f') keys = tuple(db.iter()) expected = ( ('a', 'b'), ('a', 'e'), ('b', 'c'), ('c', 'd'), ('c', 'e'), ('d', 'f') ) self.assertTupleEqual(keys, expected) result = db.delete('a') self.assertTrue(result) keys = tuple(db.iter()) expected = ( ('b', 'c'), ('c', 'd'), ('c', 'e'), ('d', 'f') ) self.assertTupleEqual(keys, expected) result = db.delete('c', value='d') keys = tuple(db.iter()) expected = ( ('b', 'c'), ('c', 'e'), ('d', 'f') ) self.assertTupleEqual(keys, expected) def test_get_last(self): db = self.db db.open('test_delete') db.wipe() db.put('a', 'b') db.put('a', 'e') db.put('b', 'c') db.put('c', 'd') db.put('c', 'e') self.assertEqual(db.get('a'), 'b') self.assertEqual(db.get('a', last=True), 'e') self.assertEqual(db.get('c'), 'd') self.assertEqual(db.get('c', last=True), 'e') self.assertEqual(db.get('b'), 'c') self.assertEqual(db.get('b', last=True), 'c') self.assertNotEqual(db.get('b', last=True), 'a') self.assertNotEqual(db.get('b'), 'a') def test_pop(self): self.db._cursor = Mock() self.db.pop('apple') self.db._cursor.pop.assert_called_with(b'apple') def test_multiple_db(self): db = self.db db = DB(directory=TEST_WRITE_ENV) db.open('test_multiple_1') db.wipe() # Has only 1 db.put('cake', 'moo') self.assertEqual(len(tuple(db.iter())), 1) db2 = DB(directory=TEST_WRITE_ENV) db2.open('test_multiple_2') db2.wipe() # only wipe the seperate db. self.assertEqual(len(tuple(db.iter())), 1) self.assertEqual(len(tuple(db2.iter())), 0) db.put('dog', 'blue') db2.put('cat', 'blue') # Did not wipe the first key from the first db self.assertCountEqual(tuple(db.iter()), (('dog', 'blue',), ('cake', 'moo') )) self.assertCountEqual(tuple(db2.iter()), (('cat', 'blue',), )) @patch('lmdb.open') def test_create_transaction_using(self, lmdb_open): item = Mock() begin_mock = Mock() # self.db.open = Mock() self.db.env = begin_mock self.db._cursor = 'foo' kw = dict(using=item, write=False) self.db.create_transaction(**kw) begin_mock.begin.assert_called_with(db=item, write=False) self.assertEqual(self.db._cursor, None) def test_commit(self): """put() a key and commit """ # First we assert the death of non persistent put() delete self.db.open('test_commit') key, value = b'commit_key', b'my test value' success = self.db.put(key, value, save=True) self.assertTrue(success) success = self.db.delete(key, commit=False) self.assertTrue(success) result = self.db.get(key) self.assertEqual(result, None) # close and open- self.db.close() self.setUp() self.db.open('test_commit') # Should exist due to persistent write result = self.db.get(key) self.assertEqual(result, value) # Now delete. success = self.db.delete(key, commit=False) self.assertTrue(success) # store the change self.db.commit() # Delete and remake - self.tearDown() self.setUp() self.db.open('test_commit') # Should not exist due to commit() result = self.db.get(key) self.assertEqual(result, None) def test_in_out_conversion(self): self.db.open('test_commit') result = self.db.put('apples', '[1,24,54,6,56]') self.assertTrue(result) result = self.db.get('apples') self.db.put('apples', [1,24,54,6,56]) result = self.db.get('apples') self.assertEqual(result, [1,24,54,6,56]) self.assertIsInstance(result, list) def test_tuple_store(self): self.db.open('test_commit') self.db.put('nums', (1,2,3,4,5,6,7,8,)) self.assertIsInstance(self.db.get('nums'), tuple) def test_list_store(self): self.db.open('test_commit') self.db.put('list', [1,2,3,4,5]) res = self.db.get('list') self.assertIsInstance(self.db.get('list'), list) def test_collect(self): self.db.open('test_collect') self.db.delete('collect') self.db.put('collect', (1,2,3,4,5,)) self.db.put('collect', (5,4,3,2,1,)) result = self.db.collect('collect') self.assertEqual(len(list(result)), 2) def test_dict_store(self): self.db.open('test_commit') de = {'foo': 1, 'bar': 'two', 'three': True} self.db.put('dict', de) res = self.db.get('dict') expected = {'foo': 1, 'bar': 'two', 'three': True} self.assertDictEqual(res, expected) def test___repr__(self): db = DB(directory=TEST_WRITE_ENV, name='dave') s= '<database.db.DB "dave">' self.assertEqual(str(db), s) class TestAppendableDB(unittest.TestCase): def setUp(self): self.db = AppendableDB(directory=TEST_WRITE_ENV) def tearDown(self): if hasattr(self.db, 'env'): self.db.env.close() if os.path.isdir(TEST_WRITE_ENV): shutil.rmtree(TEST_WRITE_ENV) self.assertFalse(os.path.exists(TEST_WRITE_ENV), 'tearDown did not Delete Test Directory.') def test_dict_byte_string(self): self.db.open('test') de = {'foo': 1, 'bar': 'two', 'three': True} expected = {'foo': 1, 'bar': 'two', 'three': True} self.db.put('dict', de) res = self.db.get('dict') self.assertDictEqual(res, expected) res = self.db.get('dict', convert=False) expected = b"!:ADict!:{'foo': 1, 'bar': 'two', 'three': True}" self.assertEqual(res, expected) def test_translate(self): key = b'window' self.assertEqual(self.db.translate(key), key) self.assertEqual(self.db.translate(b'!:str!:dog'), 'dog') def test_tuple_convert(self): dd=self.db dd.open('test_commit') result = dd.encode((1,)) tuple_name = database.db.DB_TYPE_MAP.get('tuple').__name__ b = lambda x: bytes(x, 'utf-8') expected = b('!:{}!:1'.format(tuple_name)) self.assertEqual(result, expected) result = dd.encode((1)) expected = b'!:ANumber!:1' self.assertEqual(result, expected) result = dd._convert_in( (1,) ) expected = b('!:{}!:1'.format(tuple_name)) self.assertEqual(result, expected) result = dd._convert_in( (1) ) expected = b'!:ANumber!:1' self.assertEqual(result, expected) result = dd._convert_in( (1,) ) expected = b('!:{}!:1'.format(tuple_name)) self.assertEqual(result, expected) result = dd._convert_in( [1,] ) expected = b'!:AList!:1' self.assertEqual(result, expected) result = dd._convert_in( [1] ) expected = b'!:AList!:1' self.assertEqual(result, expected) result = dd._convert_in( (1,2) ) expected = b('!:{}!:1, 2'.format(tuple_name)) self.assertEqual(result, expected) result = dd._convert_in( (1,2,) ) expected = b('!:{}!:1, 2'.format(tuple_name)) self.assertEqual(result, expected) def test_tuple_throughput(self): db = self.db db.open('test_tuple_throughput') db.delete('tuple') result = db.put('tuple', (2,3,4,5,6,)) self.assertTrue(result) result = db.get('tuple') expected = (2, 3, 4, 5, 6) self.assertTupleEqual(result, expected) result = db.append('tuple', 3) expected = b'!:A1D!:2, 3, 4, 5, 6' self.assertEqual(result, expected) result = db.append('tuple', 3) expected = b'!:A1D!:2, 3, 4, 5, 6,3' self.assertEqual(result, expected) result = db.append('tuple', 3) expected = b'!:A1D!:2, 3, 4, 5, 6,3,3' self.assertEqual(result, expected) result = db.append('tuple', 3) expected = b'!:A1D!:2, 3, 4, 5, 6,3,3,3' self.assertEqual(result, expected) result = db.get('tuple') expected = (2, 3, 4, 5, 6, 3, 3, 3, 3,) self.assertTupleEqual(result, expected) def test_tuple_put_append_get(self): db = self.db db.open('test_tuples') key = 'poppy' ta = (10,11,12,) tb = (1,2,3) db.delete(key) db.put(key, ta) db.append(key, tb) c_list = db.collect(key, convert=False) self.assertEqual(len(c_list), 1) result = db.get(key) expected = ta + tb self.assertTupleEqual(result, expected) # >>> dd.collect('apples') # Converting b'!:ATuple!:1, 2, 3, 4,' # Converting ATuple.convert(1, 2, 3, 4,) # ((1, 2, 3, 4),) # >>> dd.collect('apples', convert=False) # (b'!:ATuple!:1, 2, 3, 4,',) # >>> dd.append('apples', (1,2,3,4)) # b'!:ATuple!:1, 2, 3, 4,1, 2, 3, 4,' # (Pdb) c # b'!:ATuple!:1, 2, 3, 4,' # >>> dd.collect('apples', convert=False) # (b'!:ATuple!:1, 2, 3, 4,1, 2, 3, 4,',) # >>> # def test_encode(self): expected = b"!:ADict!:{'foo': 1, 'bar': 'two', 'three': True}" de = dict(foo=1, bar='two', three=True) dict_encode = self.db.encode(de) self.assertEqual(dict_encode, expected) def test_dict_append(self): self.db.open('test') self.db.delete('dict') expected = {'foo': 2, 'bar': 'two', 'three': True, 'dee': 2} de = {'foo': 2, 'bar': 'two', 'three': True, 'dee': 2} self.db.put('dict', de) result = self.db.get('dict') self.assertDictEqual(result, expected) self.db.append('dict', dict(apples=2, hammond='hampster')) result = self.db.get('dict') expected = {'foo': 2, 'bar': 'two', 'three': True, 'dee': 2, 'apples': 2, 'hammond': 'hampster'} self.assertDictEqual(result, expected) def test_append_error(self): self.db.open('test') self.db.delete('dict') self.assertEqual( self.db.get(5), None) # Raises error self.assertRaises(TypeError, self.db.append, args=(5, 'wood') ) # Traceback (most recent call last): # File "C:\Users\jay\Documents\projects\context-api\context\src\database\db.py", line 529, in append # result += val # TypeError: unsupported operand type(s) for +=: 'NoneType' and 'bytes' # During handling of the above exception, another exception occurred: self.assertTrue( self.db.append(5, 'wood', safe=True)) def test_convert_out(self): result = self.db._convert_out(b"!:ADict!:{'foo': 1, 'bar': 'two', 'three': True},{'foo': 2, 'dee': 2}") #Converting b"!:ADict!:{'foo': 1, 'bar': 'two', 'three': True},{'foo': 2, 'dee': 2}" #Converting ADict.convert({'foo': 1, 'bar': 'two', 'three': True},{'foo': 2, 'dee': 2}) expected = {'foo': 2, 'bar': 'two', 'three': True, 'dee': 2} self.assertDictEqual(result, expected) def test_abool(self): self.db.open('test') self.db.put('banana', False) result = self.db.get('banana') self.assertFalse(result) self.db.put('banana good', True) result = self.db.get('banana good') self.assertTrue(result) expected = (False, False, True, True) self.db.put('bananas choice', expected) result = self.db.get('bananas choice') self.assertTupleEqual(result, expected) class TestGraphDB(unittest.TestCase): TestClass = GraphDB def test_cursor(self): gb = self.TestClass(name='test_graph') gb.wipe() result = list(gb.cursor.iternext(keys=True, values=True)) self.assertListEqual(result, []) gb.add('milk', 'isa', 'greeting', 3.4, 'hello') result = list(gb.cursor.iternext(keys=True, values=True)) expected = [(b'milk', b"!:GRow!:'milk', 'isa', 'greeting', 3.4, 'hello'")] self.assertListEqual(result, expected) def test_iter_one(self): gb = self.TestClass(name='test_graph') gb.wipe() result = list(gb.iter(convert=False)) self.assertListEqual(result, []) gb.add('milk', 'isa', 'greeting', 3.4, 'hello') result = gb.collect('milk') # Converting b"!:GRow!:('milk', 'isa', 'greeting', 3.4, 'hello')" # Converting GRow.convert(('milk', 'isa', 'greeting', 3.4, 'hello')) self.assertEqual(len(result), 1) result = gb.collect('Hello') # Add: milk (hello) isa greeting (3.4) self.assertEqual(len(result), 0) result = list(gb.iter(convert=False)) expected = [('milk', b"!:GRow!:'milk', 'isa', 'greeting', 3.4, 'hello'")] self.assertListEqual(result, expected) def test_add(self): word = 'Hello' gb = self.TestClass(name='test_graph') gb.wipe() gb.add('milk', 'isa', 'nothin', 1, 'hello') gb.add(word, 'isa', 'greeting', 3.4, 'hello') gb.add(word, 'isa', 'word', 3, 'hello') gb.add(word, 'isa', 'another', 1, 'hello') result = list(gb.iter()) self.assertEqual(len(result), 4) self.assertEqual(len(gb.collect(word)), 3) result = gb.get(word) self.assertIsInstance(result, GRow) def test_edge_walk(self): gb = self.TestClass(name='graph_pick') gb.wipe() key='Hello' gb.add(key, 'isa', 'greeting', 3.4, 'hello') gb.add(key, 'isa', 'word', 3, 'hello') gb.add(key, 'isa', 'another', 1, 'hello') gb.add('greeting', 'similarto', 'Hello', 2) p = gb.pick(key) result = p.isa.greeting.similarto.Hello.graph.isa.greeting.value self.assertEqual(result, 'greeting') result = p.isa.greeting.similarto.Hello.isa.another.value self.assertEqual(result, 'another') def test_parent_walk(self): gb = self.TestClass(name='graph_walk') gb.wipe() key='Hello' gb.add(key, 'isa', 'greeting', 3.4, 'hello') gb.add(key, 'isa', 'word', 3, 'hello') gb.add(key, 'isa', 'another', 1, 'hello') gb.add('greeting', 'similarto', 'Hello', 2) p = gb.pick(key) result =( p.isa.greeting .similarto.Hello .isa.word # hello .parent_graph # greeting .parent_graph # Hello .parent_graph # None! .parent_graph ) self.assertIsNone(result, gb) def _hello_law_chain(self, gb): p = gb.pick('Hello') law_chain =( p .isa .greeting .similarto .hi .isa .greeting .similarto .Hello .isa .word .isa .thing .etomology .law) return law_chain def test_edgenode_walk(self): gb = self._cheap_graphdb() law_chain = self._hello_law_chain(gb) result = [x.value for x in law_chain.edgenode_chain(True)] expected = ['law', 'thing', 'word', 'Hello', 'greeting', 'hi', 'greeting'] self.assertListEqual(result, expected) def _cheap_graphdb(self, key='Hello'): gb = self.TestClass(name='graph_edgenode') gb.wipe() gb.add(key, 'isa', 'greeting', 3.4, key) gb.add(key, 'isa', 'word', 3, key) gb.add(key, 'isa', 'another', 1, key) gb.add('greeting', 'similarto', key, 2) gb.add('greeting', 'similarto', 'hi', 2) gb.add('greeting', 'isa', 'welcome', 2) gb.add('hi', 'isa', 'greeting', 3) gb.add('word', 'isa', 'word', 1) gb.add('word', 'isa', 'thing', 1) gb.add('thing', 'etomology', 'law', 2) return gb def test_self_cheap_graphdb(self): """Test the test function "_cheap_graphdb""" gb = self._cheap_graphdb() self.assertIsInstance(gb, self.TestClass) self.assertEqual(len(gb.collect('Hello')), 3) self.assertEqual(len(gb.collect('greeting')), 3) self.assertEqual(len(gb.collect('hi')), 1) self.assertEqual(len(gb.collect('word')), 2) self.assertEqual(len(gb.collect('thing')), 1) def test_text_chain(self): gb = self._cheap_graphdb() chain = self._hello_law_chain(gb) result = chain.text_chain(True) expected = ( ('thing', 'etomology', 'thing', 2), ('word', 'isa', 'thing', 1), ('Hello', 'isa', 'word', 3), ('greeting', 'similarto', 'Hello', 2), ('hi', 'isa', 'greeting', 3), ('greeting', 'similarto', 'hi', 2), ('Hello', 'isa', 'greeting', 3.4), ) self.assertTupleEqual(result, expected) def test_parent_edgenode_walk(self): gb = self._cheap_graphdb() p = gb.pick('Hello') result = (p .isa .greeting .similarto .hi # 1 .isa # Target. .greeting .similarto .Hello # 2 .isa .word # 3 .isa .thing .parent_edgenode .parent_edgenode .parent_edgenode ) self.assertEqual(result.edge_type, 'isa') self.assertEqual(result.value, 'greeting') self.assertEqual(result.weight, 3) def test_edge_text(self): db = self._cheap_graphdb() gg = db.pick('Hello') result = gg.edge_text() expected = (('isa', 'another'), ('isa', 'greeting'), ('isa', 'word')) self.assertCountEqual(result, expected) def test_edge_values(self): gb = self._cheap_graphdb() result = gb.pick('Hello') self.assertEqual(result.key, 'Hello') self.assertEqual(len(result.values), 3) expected = ('another', 'greeting', 'word') result = gb.pick('Hello').edge_values() self.assertCountEqual(expected, result) expected = (('another', 1), ('greeting', 3.4), ('word', 3)) result = gb.pick('Hello').edge_values(True) self.assertCountEqual(expected, result) expected = (('another', 'isa', 1), ('greeting', 'isa', 3.4), ('word', 'isa', 3)) result = gb.pick('Hello').edge_values(True, True) self.assertCountEqual(expected, result) expected = (('another', 'isa', 1), ('greeting', 'isa', 3.4), ('word', 'isa', 3)) result = gb.pick('Hello').edge_values(True, True, True) self.assertCountEqual(expected, result) expected = (('another',), ('greeting',), ('word',)) result = gb.pick('Hello').edge_values(as_tuple=True) self.assertCountEqual(expected, result) expected = (('another', 'isa'), ('greeting', 'isa'), ('word', 'isa')) result = gb.pick('Hello').edge_values(edge=True) self.assertCountEqual(expected, result) class TestGraphEdge(unittest.TestCase): def _cheap_graphdb(self, key='Hello'): gb = GraphDB(name='graph_edgenode') gb.wipe() gb.add(key, 'kangaroo', 'greeting', 42, key) gb.add(key, 'isa', 'word', 3, key) gb.add(key, 'isa', 'another', 1, key) gb.add('greeting', 'similarto', key, 2) gb.add('greeting', 'similarto', 'hi', 2) gb.add('greeting', 'isa', 'welcome', 2) # e1, e2 gb.add('hi', 'isa', 'greeting', 3) gb.add('hi', 'isa', 'word', 1) gb.add('hi', 'isa', 'thing', 1) # gb.add('hi', 'kangaroo', 'greeting', 4.44) return gb def test_EdgeNode_match(self): word = 'greeting' e=Edge(self._cheap_graphdb('hello')) hi = e.hi edge = hi.get_edges(word)[0] e1 = EdgeNode(word, edge.weight, edge_type=edge.edge_type) self.assertTrue(edge, e1) def test_edge_addition(self): e = Edge(self._cheap_graphdb('hello')) hi = e.hi he = e.hello word = 'greeting' weight = 3 edge_type = 'isa' e1 = EdgeNode(word, weight, edge_type=edge_type) e2 = EdgeNode(word, weight, edge_type=edge_type) e3 = EdgeNode(word, 42, edge_type='kangaroo') result = hi.get_edges('greeting') + hi.get_edges('greeting') self.assertCountEqual(result, (e1, e2,)) result = hi.get_edges('greeting') + he.get_edges('greeting') self.assertCountEqual(result, (e1, e3,)) def test_edge_intersection(self): e = Edge(self._cheap_graphdb('hello')) hi = e.hi he = e.hello # Simple set diff on the values from the edge_text edge = hi.get_edges('greeting') res = (set(x[1] for x in hi.edge_text()) - set(x[1] for x in he.edge_text())) self.assertSetEqual({'thing'}, res) res = he & hi def test_standard_set(self): e1=EdgeNode('a', 3, edge_type='foo') e2=EdgeNode('b', 1, edge_type='foo') e3=EdgeNode('b', 1, edge_type='foo') e4=EdgeNode('c', 3, edge_type='foo') set_res = set((e1, e2, e3, e4)) expected = { e1, e2, e4 } self.assertSetEqual(set_res, expected) class TestRemap(unittest.TestCase): def test_auto_remap(self): rm = Remap() self.assertEqual(rm.mapval('CapableOf'), 'capable_of') self.assertEqual(rm.valmap('capable_of'), 'CapableOf') class TestEdgesEdgeNode(unittest.TestCase): def _cheap_graphdb(self, key='Hello'): gb = GraphDB(name='graph_edgenode') gb.wipe() gb.add(key, 'IsA', 'greeting', 3.4, key) gb.add(key, 'IsA', 'word', 3, key) gb.add(key, 'IsA', 'another', 1, key) gb.add('greeting', 'similarto', key, 2) gb.add('greeting', 'similarto', 'hi', 2) gb.add('greeting', 'IsA', 'welcome', 2) gb.add('hi', 'IsA', 'greeting', 3) gb.add('word', 'IsA', 'word', 1) gb.add('word', 'IsA', 'thing', 1) gb.add('thing', 'etomology', 'law', 2) return gb def test___contains__(self): a = EdgeNode('top', 1) b = EdgeNode('toy', 2) c = EdgeNode('other', 1) edges = Edges(items=(a,b,)) self.assertTrue(a in edges) self.assertFalse(c in edges) self.assertTrue('top' in edges) self.assertFalse('hoof' in edges) def test_edge_start(self): db = self._cheap_graphdb() handle = Edge(db) res = handle.Hello # This is a crap test. self.assertEqual(res.key, 'Hello') def test_edge_start(self): db = self._cheap_graphdb() handle = Edge(db) res = handle.Hello.is_a # This is a crap test. self.assertIsInstance(res, Edges) self.assertEqual(res, handle.Hello.IsA) class TestEdgeValues(unittest.TestCase): def _db(self, key='Hello'): gb = GraphDB(name='edgevalues') gb.wipe() gb.add(key, 'IsA', 'greeting', 3.4, key) gb.add(key, 'IsA', 'word', 3, key) gb.add(key, 'IsA', 'another', 1, key) gb.add('greeting', 'similarto', key, 2) gb.add('greeting', 'similarto', 'hi', 2) gb.add('greeting', 'IsA', 'welcome', 2) gb.add('hi', 'IsA', 'greeting', 3) gb.add('word', 'IsA', 'word', 1) gb.add('word', 'IsA', 'thing', 1) gb.add('thing', 'etomology', 'law', 2) return gb def test_functional_call(self): db = self._db() handle = Edge(db) weights = handle.Hello.is_a.weight() self.assertIsInstance(weights, tuple) self.assertEqual(len(weights), 3) self.assertCountEqual(weights, (3.4, 3, 1,)) weights = handle.Hello.is_a.weight(True) self.assertCountEqual(weights, (('another', 1), ('greeting', 3.4), ('word', 3))) class TestObjectDB(TestGraphDB): TestClass = ObjectDB def test_cursor(self): pass def test_dump(self): gb = self._cheap_graphdb() self.assertDictEqual( ObjectDB(load=gb.dump()).dump(), gb.dump()) def test_create_index(self): """Assert a created index is the same as a natural index.""" gb = self._cheap_graphdb() self.assertDictEqual( gb.create_index(gb._data), gb.index, ) def test_create_index_dump_without_index(self): gb = self._cheap_graphdb() data = gb.dump(with_index=False) # ensure the index attribute is missing self.assertFalse('index' in data) # assert a recreation db = self.TestClass(load=data) self.assertDictEqual(gb.index, db.index) <file_sep>/src/graph_ui/static/js/visual.js var main = function(){ let wordView = new WordView() wordView.start('mynetwork') window.wordView = wordView } var colormap = { 'relatedto': '#dcdcdc' , 'isa': 'lightblue' // similat , 'synonym': '#57f09d' // opposite , 'antonym': 'purple' , '>>': 'red' , 'derived': 'pink' , atlocation: '#7e92d4' , receivesaction: '#76d14d' , 'hasproperty': '#d1d14d' , usedfor: '#444' , 'capableof': '#ffb273' , 'hasa': '#2d8baa' , 'partof':'#b9b2ff' , desires: '#f0c66b' //, notdesires: '' //, etymologicallyrelatedto: '' //, distinctfrom: '' } class NetworkEvents { hook(network){ var self = this; network.on("click", function (params) { if(self.on_click != undefined) { self.on_click(params) } params.event = "[original event]"; this.lastEvent = ['Click', JSON.stringify(params, null, 4)] console.log('click event, getNodeAt returns: ' + this.getNodeAt(params.pointer.DOM)); }); network.on("doubleClick", function (params) { if(self.on_doubleClick != undefined) { self.on_doubleClick(params) } params.event = "[original event]"; this.lastEvent = ['doubleClick', JSON.stringify(params, null, 4)] }); network.on("oncontext", function (params) { if(self.on_oncontext != undefined) { self.on_oncontext(params) } params.event = "[original event]"; this.lastEvent = ['oncontext', JSON.stringify(params, null, 4)] }); network.on("dragStart", function (params) { if(self.on_dragStart != undefined) { self.on_dragStart(params) } // There's no point in displaying this event on screen, it gets immediately overwritten params.event = "[original event]"; console.log('dragStart Event:', params); console.log('dragStart event, getNodeAt returns: ' + this.getNodeAt(params.pointer.DOM)); }); network.on("dragging", function (params) { if(self.on_dragging != undefined) { self.on_dragging(params) } params.event = "[original event]"; this.lastEvent = ['dragging', JSON.stringify(params, null, 4)] }); network.on("dragEnd", function (params) { if(self.on_dragEnd != undefined) { self.on_dragEnd(params) } params.event = "[original event]"; this.lastEvent = ['dragEnd', JSON.stringify(params, null, 4)] console.log('dragEnd Event:', params); console.log('dragEnd event, getNodeAt returns: ' + this.getNodeAt(params.pointer.DOM)); }); network.on("zoom", function (params) { if(self.on_zoom != undefined) { self.on_zoom(params) } this.lastEvent = ['zoom', JSON.stringify(params, null, 4)] }); network.on("showPopup", function (params) { if(self.on_showPopup != undefined) { self.on_showPopup(params) } this.lastEvent = ['showPopup', JSON.stringify(params, null, 4)] }); network.on("hidePopup", function () { if(self.on_hidePopup != undefined) { self.on_hidePopup(params) } console.log('hidePopup Event'); }); network.on("select", function (params) { if(self.on_select != undefined) { self.on_select(params) } console.log('select Event:', params); }); network.on("selectNode", function (params) { if(self.on_selectNode != undefined) { self.on_selectNode(params) } console.log('selectNode Event:', params); }); network.on("selectEdge", function (params) { if(self.on_selectEdge != undefined) { self.on_selectEdge(params) } console.log('selectEdge Event:', params); }); network.on("deselectNode", function (params) { if(self.on_deselectNode != undefined) { self.on_deselectNode(params) } console.log('deselectNode Event:', params); }); network.on("deselectEdge", function (params) { if(self.on_deselectEdge != undefined) { self.on_deselectEdge(params) } console.log('deselectEdge Event:', params); }); network.on("hoverNode", function (params) { if(self.on_hoverNode != undefined) { self.on_hoverNode(params) } console.log('hoverNode Event:', params); }); network.on("hoverEdge", function (params) { if(self.on_hoverEdge != undefined) { self.on_hoverEdge(params) } console.log('hoverEdge Event:', params); }); network.on("blurNode", function (params) { if(self.on_blurNode != undefined) { self.on_blurNode(params) } console.log('blurNode Event:', params); }); network.on("blurEdge", function (params) { if(self.on_blurEdge != undefined) { self.on_blurEdge(params) } console.log('blurEdge Event:', params); }); } } class WordView extends NetworkEvents{ create(nodeId) { /* create the network view on the given element id*/ var options = { nodes: { borderWidth: 0 } , edges: { shadow:{ enabled: false, color: 'rgba(0,0,0,0.5)', size:0, x:5, y:5 } , font: { color: '#CCC', size: 12, // px face: 'Roboto', background: 'none', strokeWidth: 0, // px strokeColor: 'red', } } } let data = this.getData() var container = document.getElementById(nodeId); var network = new vis.Network(container, data, options); this.hook(network) return network; } on_doubleClick(d) { for(let word of d.nodes) { getWord(word) } } styles(){ return { word: { color: '#444' } } } start(name){ this.network = this.create(name); bus.$on('message', this.wsMessage.bind(this)) } wsMessage(data) { let sent = [] let tokens = data.data.tokens || []; for(let l of tokens) { sent.push(l[0]) } this.addWords(sent); if(data.data.ident) { //this.presentConceptNetResult(data) } if(data.data.word) { this.presentWord(data) } } presentWord(data) { let word = data.data.word; //this.addWord(word) //this.addWords() window.word = word let value = word.value; if(value == undefined) { console.warn(`Old data cache does not contain "value" attribte. Please delete dictionary file and update the cache.`) return } let iters = ['synonym', 'antonym'] for (var j = 0; j < iters.length; j++) { if(word[iters[j]] == undefined) { console.log(`Word "${value}" does not have "${iters[j]}"`) continue } for (var i = 0; i < word[iters[j]].length; i++) { this.addRelate(value, word[iters[j]][i], iters[j]) }; } window.vpr = this } presentConceptNetResult(data){ let metas = data.data.ident.meta; for(let meta of metas) { let end = meta.end.label.toLowerCase(); let label = meta.rel.label.toLowerCase(); let start = meta.start.label.toLowerCase(); if( meta.end.language != 'en' || meta.start.language != 'en' ) { continue; } if(meta.weight < 1.4) { continue; } this.addRelate(start, end, label) this.addEdge(start, end, label) } console.log(data.data.type, Object.keys(data.data)) console.log(data.data) } addWords(words, edgeLabel) { let last; for(let token of words) { let c = this.addWord(token.toLowerCase()) if(last) { this.addEdge(last.toLowerCase(), token.toLowerCase(), edgeLabel) } last = token } } nodes(){ if(this._nodes == undefined ) { this._nodes = new vis.DataSet([]) }; return this._nodes; } edges(){ if(this._edges == undefined ) { this._edges = new vis.DataSet([]) }; return this._edges; } addWord(word, color=undefined){ word = word.toLowerCase() let wordColor = this.styles().word.color let fontColor = '#DDD'; if(color != undefined) { wordColor = color fontColor = '#000' } if(word[0] == 'a') { let _word = word.split(' ').slice(1).join(' ') if(_word != '') { word = _word; } } if(word.split(' ').length > 1) { return this.addWords(word.split(' '), 'derived') } let nodes = this.nodes(); let enode = nodes.get(word); if(enode != null) return enode; return nodes.add({ id: word , label: word , color: wordColor , font: { color: fontColor , face: 'Roboto' } , shape: 'box' }) } addEdge(a, b, related='>>') { /* connect two existing network elements with a arrow line pointing to 'b' ww.addEdge('cake', 'window') */ let edges = this.edges(); related = related.toLowerCase() let eedge = edges.get(`${a}${b}`); if(eedge != null) return eedge; let cmap = colormap[related]; let cl = cmap; if(typeof(cmap) == 'string') { cmap = {} } else { if(cmap != undefined) { cl = cmap.color; } else { console.log(`No color map for ${related}`) } } this.edges().add(Object.assign({ id:`${a}${b}` , from:a , to: b , color: cl || '#DDD' // , value: .1 , arrows: { to: { scaleFactor: .4 } } , label: colormap[related] == undefined? related: undefined , related: related }, cmap)) } addRelate(word, relate, label='relatedTo', color=undefined) { /* Add a word related to another word, connecting an edge with an arrow pointing to relate (B). This will automatically connect existing or new elements. this.addEdge('cake', 'window') this.addRelate('cake', 'hose') this.addRelate('dog', 'hose') this.addRelate('dog', 'apples') this.addRelate('winner', 'chicken') addRelate('word', 'other_word', 'label') */ /* append a 'relateTo', a related to b */ this.addWord(word.toLowerCase(), color) this.addWord(relate.toLowerCase(), color) this.addEdge(word.toLowerCase(), relate.toLowerCase(), label) } getData(){ // create a network var data = { nodes: this.nodes() , edges: this.edges() }; return data; } } ;main(); <file_sep>/src/server/assets/js/components/sentence_render.js var sentenceApp = new Vue({ el: '#sentence' , data: { sentences: ['foo'] , words: [] } , mounted(){ bus.$on('message', this.recvMessage) } , methods: { recvMessage(data) { console.log(data.data.type, data.data.action) if(data.data.sentence != undefined) { if(data.data.type == 'start') { this.sentences.unshift(data.data.sentence) } } let av = data.data.action let m = `${data.data.type}_${av}`; if(this[m] != undefined) { this[m](data) } } , clearMessages(){ this.words = [] this.sentences = [] } , sentence_end(d){ this.words.push({ word: 'Divide' , type: d.data.type , classes: `divider ${d.data.action} ${d.data.type}` }) } , sentence_start(d){ this.words.push({ word: 'Divide' , type: d.data.type , classes: `divider ${d.data.action} ${d.data.type}` }) } , assess_start(d) { console.log('assess start', d) let words = [] for (var i = 0; i < d.data.tokens.length; i++) { let e = d.data.tokens[i] this.words.push({word: e[0], classes: [], type: e[1]}) } } , assess_complete(d) { console.log('assess complete', d) let words = [] for (var i = 0; i < d.data.result.length; i++) { let e = d.data.result[i] words.push({word: e[0], classes: [], type: e[2]}) } //this.words = words } , assess_word(d) { let word = d.data.word.value console.log('assess word', d) let className = 'assessing' for (var i = 0; i < this.words.length; i++) { if(this.words[i].word == word) { console.log('found one') this.words[i].classes.push(className) } else { let r = this.words[i].classes if(r != undefined && r.splice != undefined) { r.splice(r.indexOf(className), 1) } } } } } }) <file_sep>/src/plog/working6.py from api import Plog from patterns import PlogLine as Line, PlogBlock as Block block = Block('Device ID:', ref='Device') block.header.ref='device_id' block.add_lines( entry_address=Line('IP address:'), platform=Line('Platform:'), interface=Line('Interface:'), hold_time=Line('Holdtime').maybe(' ').then(':'), version=Line('Version').maybe(' ').then(':').multiline(), ad_version=Line('advertisement version:'), duplex=Line('Duplex:'), power_drawn=Line('Power drawn:'), power_request_id=Line('Power request id:'), power_management_id=Line('Power management id:'), power_request_levels=Line('Power request levels are:'), ) block.footer = Line('----------', ref='footer').anything() # new parser f = open('test_data2.txt', 'r') # plog = Plog(f, whitespace='|') plog = Plog(f, whitespace='|', terminator=',') # run it plog.add_block(block) blocks = plog.run() for block in blocks: if block.valid(): print block.as_dict() <file_sep>/src/server/assets/js/vis-4.20.0/test/TimeStep.test.js var assert = require('assert'); var vis = require('../dist/vis'); var jsdom = require('mocha-jsdom') var moment = vis.moment; var timeline = vis.timeline; var TimeStep = timeline.TimeStep; var TestSupport = require('./TestSupport'); describe('TimeStep', function () { jsdom(); it('should work with just start and end dates', function () { var timestep = new TimeStep(new Date(2017, 3, 3), new Date(2017, 3, 5)); assert.equal(timestep.autoScale, true, "should autoscale if scale not specified"); assert.equal(timestep.scale, "day", "should default to day scale if scale not specified"); assert.equal(timestep.step, 1, "should default to 1 day step if scale not specified"); }); it('should work with specified scale (just under 1 second)', function () { var timestep = new TimeStep(new Date(2017, 3, 3), new Date(2017, 3, 5), 999); assert.equal(timestep.scale, "second", "should have right scale"); assert.equal(timestep.step, 1, "should have right step size"); }); // TODO: check this - maybe should work for 1000? it('should work with specified scale (1 second)', function () { var timestep = new TimeStep(new Date(2017, 3, 3), new Date(2017, 3, 5), 1001); assert.equal(timestep.scale, "second", "should have right scale"); assert.equal(timestep.step, 5, "should have right step size"); }); it('should work with specified scale (2 seconds)', function () { var timestep = new TimeStep(new Date(2017, 3, 3), new Date(2017, 3, 5), 2000); assert.equal(timestep.scale, "second", "should have right scale"); assert.equal(timestep.step, 5, "should have right step size"); }); it('should work with specified scale (5 seconds)', function () { var timestep = new TimeStep(new Date(2017, 3, 3), new Date(2017, 3, 5), 5001); assert.equal(timestep.scale, "second", "should have right scale"); assert.equal(timestep.step, 10, "should have right step size"); }); });<file_sep>/src/v2/core/initial.py '''The initial layer for all input to apply. ''' import time import Queue as Q from log import log def run_core(queue, config): ''' Run the process ''' log('run') run = 1 config = config or {} # uri = config.get('socket_uri', None) # socket = _json_socket(uri) # socket.send("run_core") # pf.init() while run: m = None try: m = queue.get_nowait() log('Got message', m) except Q.Empty as e: pass if m == 'kill': log('kill run_core') run = 0 if m is None: time.sleep(1) continue # Any message to this point came from websocket(through queue) or # queue internal log('assess', m) assess_string(m) log('End run core.') def assess_string(sentence): '''Given an input string, farm to the waiting receivers''' log('Read "{}"'.format(sentence)) <file_sep>/docs/writes/Startrek Lift.md # Intonation and peak detection I called this the Startrek lift as it's exactly the aim for this part of the project. Todays audio equipment and software is excellent at detecting voices in a loud environment. I remember testing Google voice search in a rock concert and was pleasantly surprised by the accuracy. In the case of the turbo-lift it has the ability to understand _when_ it's being referred to rather than simply hearing "hot words". This allows someone to _said_ words during a conversation without affecting the lifts functionality. So how is this done? I asked myself. Firstly I feel this can be achieved without ML - or perhaps 16 nodes and 4 layers is totally enough. I think I've seen; much of this can be done with simple audio processing of existing technologies and FFT peak fiddling. To note some of the 'detection' requirements - based upon the Turbo lift. + Understand flat commands without prompt... "Deck four" + Capture with hot word "Computer go to deck six" + Hotword include "halt [lift]", "stop", ### Capture on + intonation gaps + paused hotwords + hotword wait? Noting some citations from the program and general day to day of the talking to computer, certain pattern from an operator (human speech) to detect direct communication. Some are unavailable in the current architecture but we'll cover them anyway. For the research, we'll only consider the turbo-lift - but this as application a range of general interactive places. Input: User Speech OP, Operator, User, Human Output: Text to Speech CTX (context machine), machine, system, computer Focus Result: Graphing Results Generated result objects We'll focus on speech strings, or Temporal String graphs - a mud of words without grammar. ... and then I left about midnight hello computer floor three please and I said to him I'll see you later at two near the top... In this case half-way through a conversation the CTX is addressed as 'computer'. Cleaned up: .... [and then I left about midnight] "hello computer, *floor three* please" [and I said to ... The unnecessary content in brackets; the real action "floor three" could be detected via 'hot-word' _floor_, but the remaining content container "two" and "the top". They are also acceptable hot words Our cases focus on this type of input. ## Initial and direct. Initially entering the _turbo lift_ alone a user will state the intent and stay silent. This is the best case, as it's easy to extrapolate. [computer] floor three deck six [please] forty third floor Any combination of the above. Through silence before and after - The system operation can focus on floor graphs. Sound detection is done through a hardware level and simple TTS Stream as temporal strings provide input. ## Pause Direct In our main case above the user has another conversation as they enter and after a brief moment they pause the conversation and communicate directly to the system. This occurs with two people entering or one person personal (on a phone for example). For this the capture by initial and direct may not occur as there will be no pause in the temporal stream. However the operator may pause for a longer period before addressing another entity [I prepared for a winter trip to] floor 8 [alaska whilst listening to pink floyd] _As a helper (I find this silly to) I find saying this out-loud to a pseudo device. You'll easily here your pitch and intonation change when referencing a 'computer' than communicating to another._ When referring to a third-party - external to the current conversation or context - a person tends to pause for a longer period than their average breath. In a study by Donders Institute[1] we find the average response time for a breath is less than a second. Anything over that is a context switch and we can conceptualize from this[2]. This is of course a gross over-simplification but for now it'll serve. I prepared for a winter trip to [pause > 1s] floor 8 [pause*B > 1s] alaska ... The initial pause delay should be equated from the last X seconds median of pauses within the ^initial contact. Therefore a more accurate average of the current context pausing can be used. The second pause requires more than half a second[2] [3]; at which point a user will continue their own conversation. A user will pause, speak, pause and continue with a pitch and intonation change. Detecting a volume and pitch change - and potentially a _direction_ the system can extrapolate a temporal stream for graphing; "floor three" ### Direct A user may directly refer to the system before a command. this is easier to monitor through hot-words: "computer floor three". However someone may mention those words through general conversation. Combining Pause Direct with the intonation detection should serve well-enough. The hot-word "computer" (or any associated graph) the system and assert the immediate string "floor three". ### Noisy Environments In areas with a lot of background noise the same Capture and Pause Direct, procedures work. With ambient level detection the system can assess the average volume of a general converation or background. General noise is about 75db. Monitoring anything above this for Pause Direct should work. Mostly relying upon volumn change for a simple statement greater than 10db of the average. Breathing in Conversation: an Unwritten History <NAME>, <NAME> Department of Linguistics Stockholm University Stockholm, Sweden {<EMAIL>,<EMAIL> <NAME> Speech, Music and Hearing KTH Royal Institute of Techonology Stockholm, Sweden <EMAIL> https://www.diva-portal.org/smash/get/diva2:892585/FULLTEXT01.pdf [1] https://www.frontiersin.org/articles/10.3389/fpsyg.2015.00284/full#h4 [1.b] https://www.frontiersin.org/articles/10.3389/fpsyg.2015.00284/full#h5 ORIGINAL RESEARCH ARTICLE Front. Psychol., 12 March 2015 | https://doi.org/10.3389/fpsyg.2015.00284 Breathing for answering: the time course of response planning in conversation <NAME>, <NAME> and <NAME>,2 1Language and Cognition Department, Max Planck Institute for Psycholinguistics, Nijmegen, Netherlands 2Donders Institute for Brain, Cognition and Behaviour, Radboud University, Nijmegen, Netherlands [2] https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4240966/ Philos Trans R Soc Lond B Biol Sci. 2014 Dec 19; 369(1658): 20130399. doi: 10.1098/rstb.2013.0399 PMCID: PMC4240966 PMID: 25385777 Take a breath and take the turn: how breathing meets turns in spontaneous dialogue <NAME> and <NAME> [3] http://www.speech.kth.se/prod/publications/files/3418.pdf Pauses, gaps and overlaps in conversations <NAME> , <NAME> KTH Speech, Music and Hearing, Lindstedtsvagen 24, SE-100 44 Stockholm, Sweden http://www.aclweb.org/anthology/W96-0418 Matchmaking: dialogue modelling and speech generation meet* <NAME> FAW Ulm Germany <NAME> GMD/IPSI, Darmstadt and Technical University of Darmstadt Germany Elke Teich University of tile Saarland Department of Applied Linguistics, Translation and Interpretation Germany https://www.frontiersin.org/articles/10.3389/fpsyg.2012.00376/full#h4 Prediction of turn-ends based on anticipation of upcoming words <NAME>1* and <NAME> 1Language and Cognition Department, Max Planck Institute for Psycholinguistics, Nijmegen, Netherlands 2Faculty of Linguistics and Literary Studies, University of Bielefeld, Bielefeld, Germany <file_sep>/src/plog/working5.py from api import Plog from patterns import PlogLine, PlogBlock block = PlogBlock('Device ID:', ref='Device') block.header.ref='device_id' block.footer = PlogLine('----------', ref='footer').anything() lines = {} lines['entry_address'] = PlogLine('IP address:') lines['platform'] = PlogLine('Platform:') lines['interface'] = PlogLine('Interface:') lines['hold_time'] = PlogLine('Holdtime').maybe(' ').then(':') lines['version'] = PlogLine('Version').maybe(' ').then(':').multiline() lines['version'] = PlogLine('advertisement version:') lines['duplex'] = PlogLine('Duplex:') lines['power_drawn'] = PlogLine('Power drawn:') lines['power_request_id'] = PlogLine('Power request id:') lines['power_management_id'] = PlogLine('Power management id:') lines['power_request_levels'] = PlogLine('Power request levels are:') block.add_lines(**lines) # new parser f = open('test_data2.txt', 'r') # plog = Plog(f, whitespace='|') plog = Plog(f, whitespace='|', terminator=',') # run it plog.add_block(block) blocks = plog.run() for block in blocks: if block.valid(): print block.as_dict() <file_sep>/src/v1/words.py from PyDictionary import PyDictionary from cache import get_cache, set_cache dictionary = None def make_dictionary(): global dictionary dictionary = PyDictionary() return dictionary def get_dictionary(): global dictionary if dictionary is None: dictionary = make_dictionary() return dictionary def get_word(value): '''Return the entire feed of a word from cache or API.''' wd = get_dictionary() filename = 'dictionary_word_{}.pyf'.format(value) success, val = get_cache(filename) if success is True: print 'returning cache word' return val val = dict( value=value, meaning=wd.meaning(value), synonym=wd.synonym(value), antonym=wd.antonym(value), ) set_cache(filename, val) return val <file_sep>/src/v1/primary_functions.py '''A set of functions to call into the API - defined as 'primary' as the first point of access ''' import os import contextnet_api as cnapi from logger import print_edges import words from cache import set_global_root # import secondary_functions import loop from json_socket import make_socket from log import log queue = None loop_data = None def allow_external(bool=None): if bool is not None: cnapi.FETCH_ALLOWED = bool return cnapi.FETCH_ALLOWED def init(socket_uri="ws://127.0.0.1:8009"): ''' A initialisztion function for anything requiring a first boot. ''' global command global loop_data global queue # global socket # if socket_uri is not None: # socket = make_socket(socket_uri) command = Command() basepath = os.path.abspath(os.path.dirname(__file__)) cache_path = os.path.join(basepath, 'cache') set_global_root(cache_path) loop_data = dict(socket_uri=socket_uri, cache_path=cache_path) queue, procs = loop.init_thread(**loop_data) def _base_boot(socket_uri="ws://127.0.0.1:8009"): basepath = os.path.abspath(os.path.dirname(__file__)) cache_path = os.path.join(basepath, 'cache') set_global_root(cache_path) COMMAND_STR = '!#' def ask_loop(): _run = True kill = False while _run is True: v = raw_input('\nWhat?: ') if v == '': log('Close _run') _run = False else: if v == 'kill': log('Loop kill in process') kill = True assess_string(v) if kill is True: _run = False log('Killing processes') loop.kill_processes() log('Finish askloop') def assess_string(sentence): ''' Given an input string, token and assess each token. ''' if sentence[0] in COMMAND_STR: return command.command_mode(sentence) log('primary_functions assess_string') if queue is not None: queue.put_nowait(sentence) # return secondary_functions.apply_to_context(sentence) class Command(object): def command_mode(self, command): _map = { "!": 'eval', "#": "hash", } comt = command[0] com = command[1:] mc = _map[comt] name = "com_{}".format(mc) log('Received command "{}"'.format(mc), name) if hasattr(self, name): return getattr(self, name)(com) def com_eval(self, com): ret = eval(com) log(ret) return ret def com_hash(self, com): coms = map(str.strip, com.strip().split(' ')) com0 = coms[0] name = "hash_{}".format(com0) if hasattr(self, name): return getattr(self, name)(*coms[1:]) def hash_die(self): '''Send a kill message''' log('Killing...') assess_string('kill') loop.kill_processes() log('Death complete.') def hash_start(self): log('Start Procs') loop.start_procs(queue, **loop_data) def hash_fetch(self, value=None): positive = ['true', 'yes', '1', 'on'] negative = ['no', '0', 'false', 'off'] lv =None if value is not None: lv = value.lower() switch = True if lv in positive else None switch = switch or (False if lv in negative else None) if switch is None: log('Fetch is currently:', allow_external()) return log('Allow external data fetch: ', switch) allow_external(switch) def hash_delete(self, word): log('Delete word', word) log(cache.delete_word(word)) def hash_cache(self, word): cnapi.api_fetch(word, allow_cache=False, _force_allow=True) def hash_read(self, data_file): '''given the name of a data file within the initial data folder, read each line into the ask loop. ''' fn = '{}'.format(data_file) fpf = os.path.join(os.path.dirname(__file__), 'data', fn) log('read', fpf) if os.path.isfile(fpf): log('Slow reading', fpf) ts = 5 with open(fpf, 'r') as stream: try: for line in stream: word = line.strip() log('Asking', word) assess_string(word) log('sleeping', ts) time.sleep(ts) except KeyboardInterrupt: log('cancelled slow feed') <file_sep>/src/graph_ui/static/js/websockets.js var cleanData = [] var formOutput = new Vue({ el: '#form_output' , data: { socketMessages: [] } , methods: { messageComponent(message) { let name = `${message.data.type}` if(Vue.options.components[name] != undefined) { return name; } return 'default' } , clearMessages(){ formOutput.socketMessages = [] } } }) var jsonFetchApp = new Vue({ el: '#websockets' , data: { address: 'ws://192.168.1.104:8009' , basePath: '' , requests: [] , selected: {} , message: undefined , connected: false , indexItem: -1 } , mounted() { this.connect() } , methods: { connect() { let p = this.address let ws = new WebSocket(p); ws.onmessage = this.socketMessage; ws.onopen = this.socketOpen; this.webSocket = ws; } , socketMessage(d){ let m = { type: 'in' , data: JSON.parse(d.data) }; formOutput.socketMessages.push(m) bus.$emit('message', m) } , socketOpen(d){ console.log('open', d); this.connected = true } , sendMessage(){ this.webSocket.send(this.message) formOutput.socketMessages.push({ type: 'out' , data: this.message }) this.message = '' } , fetch(event, partial){ let path = partial == undefined ? this.$refs.address.value: partial; console.log('path', path) let fullpath = `${this.basePath}${path}` $.get(fullpath, function(data){ this.renderPath(path, data) }.bind(this)) } , renderPath(path, data) { console.log('got', data) cleanData.push({path, data}) let dataCopy = JSON.parse(JSON.stringify(data)) this.requests.push({ path, dataCopy }) } } }) <file_sep>/src/v2/conceptnet/redis_db.py import redis import multiprocessing from log import log import traceback from conceptnet.parse import parse_csv, clean_line, spread ''' dbstore.spread_redis_apply(max_count=100, max_cpu=1) from conceptnet import dbstore dbstore.store_redis_lines(dict(max_count=100)) ''' def spread_redis_apply(**kw): return spread(store_redis_lines, **kw) def store_redis_lines(kw): process_name = multiprocessing.current_process().name db_index = kw.get('job_index', 0) db = redis.StrictRedis(host='localhost', port=6987, db=db_index) pipe = db.pipeline() options = dict( max_count=kw.get('max_count', 100000), iter_line=redis_apply, as_set=True, pipe=pipe, row_index=kw.get('row_index', 1), keep_sample=kw.get('sample', False), byte_start=kw.get('byte_start', None), byte_end=kw.get('byte_end', None), ) try: d, sample = parse_csv(**options) log('Finished relations. Count: {}. Writing file'.format(len(d))) except Exception as e: log('Error on "{}" :'.format(process_name), e) log(traceback.format_exc()) d = [] pipe.execute() return list(d) def redis_apply(line, **kw): pipe = kw.get('pipe', None) if pipe is None: return l = clean_line(line, **kw) k = [] if l is None: return None _type, sw, ew, weight, _json = l _json.update({ "connection": _type, "weight": weight, "direction": ('start', 'end',) }) pipe.set(sw, str(_json)) _json["direction"] = ('end', 'start',) pipe.set(ew, str(_json)) if kw['row_index'] % 1000 == 0: pipe.execute() <file_sep>/docs/writes/reconfirmation protocol.md The reconfirmation protocol The reconfirmation protocol provides a level of assurance through a context chain for agreeance on critical actions, and their fundamental confirmation. It should happen at the very base of context chain growth, allowing operation on a simple positive or negative. The goal is natural input, herefore we’ll drive the scenario in a similar way. The first input should be to initiate the reconfirmation protocol. Upon which the system will respond with a hard coded response of activation followed by locking of expecting input values affirm to only positive or negative. Upon each input - the system will parrot the context result, followed by confirmation of the result. This again is only in a form of positive or negative. The flow should proceed The reconfirmation protocol is active. Context receives affirmations to the positive or negative only. Upon the 5th and final response from the system, the reconfirmation protocol will release and the assigned action will be performed. This will require 6 consecutive positive answers from the operator Any affirmation to the negative will end the protocol and resume normal operation. Confirm positively to continue [yes] [yes] is a positive affirmation. Confirm positively to continue. [yes] Positive confirmed. After the next stage the reconfirmation protocol will be initiated. Confirm positively to continue. [yes] [yes] is a positive affirmation. Confirm positively to continue. [yes] A positive confirmation to the next and final stage will action the reconfirmation protocol. Confirm positively to continue. [yes] [yes] is the last positive affirmation. After your next positive affirmation, the reconfirmation protocol will action. Confirm positively to continue. [yes] Confirm. Reconfirmation protocol complete. (release context) <file_sep>/src/v5/context/first/forms.py from django import forms from . import models class TemporalInputForm(forms.ModelForm): class Meta: model = models.TemporalInput fields = '__all__' <file_sep>/src/v3/main.py '''A set of functions to call into the API - defined as 'primary' as the first point of access ''' import os # import contextnet_api as cnapi #from logger import print_edges import words from cache import set_global_root import cli import primary_context as pc #import loop import contextnet_api as ca from json_socket import make_socket #from log import log queue = None loop_data = None def main(): init() SOCKET_ADDRESS = 'ws://127.0.0.1:8009' def init(socket_uri=SOCKET_ADDRESS): ''' A initialisztion function for anything requiring a first boot. ''' print('init') global command global loop_data global queue # global socket # if socket_uri is not None: # socket = make_socket(socket_uri) #command = Command() basepath = os.path.abspath(os.path.dirname(__file__)) cache_path = os.path.join(basepath, '..', 'cache') cache_path = os.path.abspath(cache_path) set_global_root(cache_path) loop_data = dict(socket_uri=socket_uri, cache_path=cache_path) pc.init(socket_uri) cli.init(socket_uri) cli.ask_loop(assess_string) def assess_string(string): """Run the context functionality on the given string sentence. """ tok = pc.apply_to_context(string) print('\n\n', string, '==', tok) #queue, procs = loop.init_thread(**loop_data) """ Goal preferences When repeating a sentence in cotext, the importance can be derived from the repetition itself when a graphs node is sufficentialy weighted - it's the new goal or knowledge Graphing: i need my house where is my home where is my house My home now contextual graphing notes a heavier weight to the 'need', 'my', house', 'home' """ if __name__ == '__main__': main() <file_sep>/src/v5/context/first/migrations/0008_auto_20190728_0217.py # Generated by Django 2.2.3 on 2019-07-28 01:17 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('first', '0007_auto_20190728_0055'), ] operations = [ migrations.CreateModel( name='Tense', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('plural', models.CharField(blank=True, max_length=255, null=True)), ('plural_noun', models.CharField(blank=True, max_length=255, null=True)), ('plural_verb', models.CharField(blank=True, max_length=255, null=True)), ('plural_adj', models.CharField(blank=True, max_length=255, null=True)), ('singular_noun', models.CharField(blank=True, max_length=255, null=True)), ('present_participle', models.CharField(blank=True, max_length=255, null=True)), ], ), migrations.AddField( model_name='tokenword', name='tense', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='first.Tense'), ), ] <file_sep>/src/csv_process.py """Using the recorded CSV assertions, load through 'conceptnet' parsing tools into the graph 'database' """ from database.graph import GraphDB import database from conceptnet import scratch_db ASSERTIONS_DIR = "E:/conceptnet/_lmdb_assertions/" csv_path = 'E:\\conceptnet\\assertions.csv' GB_9 = 9e+9 db = GraphDB( directory=ASSERTIONS_DIR, name='assertions', max_bytes=GB_9, ) def main(): # db.wipe() store() def store(): kw = dict( path=csv_path, step_function=step_function, chunk_size=1000, start_index=0, max_count=1_000_000_000, ) scratch_db.store_lines(kw) def step_function(items, line, given_kwargs): dd = given_kwargs['current_lineno'] # print('{} {}'.format(items[-1]['start']['word'], dd)) c = 0 for item in items: start = item['start']['word'] edge = item['connection'] end = item['end']['word'] weight = item.get('weight', 1) c+=1 db.add( start=start, edge=edge, end=end, weight=weight, save=False, ) print('At', dd + c) db.commit() if __name__ == '__main__': #main() pass <file_sep>/src/v2/json_socket.py import websocket import json import collections class JSONSetEncoder(json.JSONEncoder): """Use with json.dumps to allow Python sets to be encoded to JSON Example ------- import json data = dict(aset=set([1,2,3])) encoded = json.dumps(data, cls=JSONSetEncoder) decoded = json.loads(encoded, object_hook=json_as_python_set) assert data == decoded # Should assert successfully Any object that is matched by isinstance(obj, collections.Set) will be encoded, but the decoded value will always be a normal Python set. """ def default(self, obj): if isinstance(obj, collections.Set): return list(obj) # return dict(_set_object=list(obj)) else: return json.JSONEncoder.default(self, obj) def json_as_python_set(dct): """Decode json {'_set_object': [1,2,3]} to set([1,2,3]) Example ------- decoded = json.loads(encoded, object_hook=json_as_python_set) Also see :class:`JSONSetEncoder` """ if '_set_object' in dct: return set(dct['_set_object']) return dct class DummySocket(object): ''' Dummy socket for replacement of the real socket, if the socket does not exist. All output is sent to print. ''' def send(*a): pass socket = DummySocket() def send_json(d=None, **data): ''' Send dictionary data through the socket, converting all given arguments to a JSON string before send. ''' if isinstance(d, dict) is False: d = dict(value=d) if len(data) != 0: d.update(data) socket.send(json.dumps(d, cls=JSONSetEncoder)) def get_socket(): return socket def get_or_create(uri): _socket = get_socket() if isinstance(_socket, DummySocket) is True: _socket = make_socket(uri) return _socket def make_socket(uri): ''' Generate and return a new WebSocket client for the given uri. ''' global socket socket = websocket.WebSocket() socket.connect(uri) #socket.send('Connected') return socket <file_sep>/src/v2/core/run.py '''Core run service with the initial 'run_core' function to boot a main queue thread and waiting socket. ''' from multiprocessing import Process, Queue import json_socket from log import log from initial import run_core standard_config = dict( socket_uri="ws://127.0.0.1:8009", ) queue_prc = None socket_prc = None def _json_socket(uri): socket = json_socket.get_socket() if uri is not None: socket = json_socket.get_or_create(uri) return socket def socket_receiver(queue, config=None): config = config or {} uri = config.get('socket_uri', None) socket = _json_socket(uri) if socket is None: # no worker to run. return False run = 1 while run: m = socket.recv() if m == 'kill': run = 0 queue.put(m) log('finished socket_receiver') def thread_run(queue=None, config=None): global queue_prc global socket_prc conf = config or {} settings = standard_config.copy() settings.update(conf) q = queue or Queue() socket_prc = Process(target=socket_receiver, args=(q, settings)) socket_prc.start() global_prc = Process(target=run_core, args=(q, settings)) global_prc.start() return global_prc, q <file_sep>/docs/writes/volunteer response.md # volunteer [concept] In many occasions we need the machine to freely provide information in and out of the _current_ context. This occurs for internal graph corrections and populating graph mandates. A quick example In a previous session 'up' graphed 'down' as an opposite and a Trueism can define a fact. OP: Up in down CTX: No CTX: Up antonym down Firstly the statement is a direct statement therefore the weighting is strong. The context graph maps a competing graph to the exact statement as an antonym. For weighted graphs with a result leaf of a context object - therefore resolving something already trained - the system should assert the fact as a unit of fact. If the statement is true - CTX should reply with an affirmative or an agreement. OP: The sky is blue CTX: [confirmed | affirmed | agreed | yes] 'sky' has already been graphed (very nicely) and a lot of references to 'blue' exist within the context. therefore a strong graph generates for blue sky. In this case the system should provide an assertion. <file_sep>/docs/writes/long term store.md # Long term study of edges The edge merge splits edge relevence by weight and threshold as they're collected from db. Edge `primary` edge is scored and kept or dropped for immediate usage and analysis. Secondary, lower, and dropped edges for a given word are applied to a background worker - or rather a FILO queue and analysed in-turn after more-important analysis. This can be considered as the 'background thoughts' of more expensive graphs. As each task finished linearly (ignoring the first layer) the same actions occur events. Any actions or events requiring input are again stored into a forward event planner to act upon at some point in the future. This will occur on each edge type independently, referencing all finished information to a 'named graph'. During `merge::perform>get_edges_words`, apply `lower` and `dropped` to a background queue. <file_sep>/src/database/db.py import os from ast import literal_eval import lmdb WRITE_ENV = "E:/conceptnet/_lmdb/" DEFAULT_DB_NAME = 'default_db' UTF8 = 'utf-8' ASCII = 'ascii' GB_1 = 1e+9 # 12 gb GB_12 = 1.2e+10 MAX_BYTES = GB_1 FIRST = '__FIRST_KEY__' UNDEFINED = '__undefined__' DB_TYPE_MAP = {} class DB(object): def __init__(self, **kwargs): self.start(**kwargs) def start(self, directory=WRITE_ENV, default_name=DEFAULT_DB_NAME, write=True, name=None, allow_duplicate=True, auto_commit=True, encoding=UTF8, auto_open=True, get_last=False, max_bytes=MAX_BYTES): # print('init DB') self.env_path = directory self.name = name or default_name or DEFAULT_DB_NAME self.write = write self.auto_commit = auto_commit self.encoding = encoding self.max_bytes = max_bytes # Return the last item of any duplicate keys on get(). # This is three operations more expensive per transaction. self.get_last = get_last self.allow_duplicate = allow_duplicate # If auto)open is true and a 'name' is, the initial DB will open() # with the given name self.auto_open = auto_open self.is_open = False self._cursor = None self._auto_open() def _auto_open(self): if self.auto_open is True and self.name is not None: self.open() def get_cursor(self): if self._cursor is None: self._cursor = self.txn.cursor() return self._cursor cursor = property(get_cursor) def _open_args(self, **options): """Arguments given to the 'open()' of the internal DB.""" # https://lmdb.readthedocs.io/en/release/#lmdb.Environment # Environment(path, # map_size=10485760, # subdir=True, # readonly=False, # metasync=True, # sync=True, # map_async=False, # mode=493, # create=True, # readahead=True, # writemap=False, # meminit=True, # max_readers=126, # max_dbs=0, # max_spare_txns=1, # lock=True) result = dict( subdir=True, max_dbs=5, create=True, ) result.update(options) return result def wipe(self, destroy=False): print('Wiping', self.child_db) if destroy: print('! --- Destroying database') self.txn.drop(self.child_db, delete=destroy) if destroy: self.txn.commit() print('Rebooting') self.start() else: self.commit() def open(self, name=None, env_path=None, write=True, max_bytes=MAX_BYTES): """ open_db(key=None, txn=None, reverse_key=False, dupsort=False, create=True, integerkey=False, integerdup=False, dupfixed=False) Open a database, returning an opaque handle. Repeat Environment.open_db() calls for the same name will return the same handle. As a special case, the main database is always open. Equivalent to mdb_dbi_open() Named databases are implemented by storing a special descriptor in the main database. All databases in an environment share the same file. Because the descriptor is present in the main database, attempts to create a named database will fail if a key matching the database's name already exists. Furthermore the key is visible to lookups and enumerations. If your main database keyspace conflicts with the names you use for named databases, then move the contents of your main database to another named database. """ name = name or self.name env_path = env_path or self.env_path write = self.write if write is None else write max_bytes = max_bytes or self.max_bytes print('Open Env', env_path) open_args = self._open_args(map_size=max_bytes) self.env = lmdb.open(env_path,**open_args) self.child_db = self.env.open_db( key=self.encode(name), dupsort=True, # reverse_key=True ) # Open transaction self.txn = None # self.child_db = self.env.open_db(name) self.txn = self.create_transaction( # allow writing write=self.write, # Keep last transaction as parent as_child=True, ) self.is_open = True self.name = name def put(self, key, value, save=True, encode=True, encode_key=True, as_dup=None, **kwargs): '''put(key, value, dupdata|as_dup=True, overwrite=True, append=False, db=None) Store a record, returning True if it was written, or False to indicate the key was already present and overwrite=False. On success, the cursor is positioned on the new record. Equivalent to mdb_put() key: Bytestring key to store. value: Bytestring value to store. as_dup: If True and database was opened with dupsort=True, add pair as a duplicate if the given key already exists. Otherwise overwrite any existing matching key. overwrite: If False, do not overwrite any existing matching key. append: If True, append the pair to the end of the database without comparing its order first. Appending a key that is not greater than the highest existing key will cause corruption. db: Named database to operate on. If unspecified, defaults to the database given to the Transaction constructor. ''' key = self.encode(key) if encode_key is True else key store_val = self.encode(value) if encode is True else value if self.allow_duplicate is True or as_dup is True: kwargs['dupdata'] = True # kwargs['overwrite'] = False try: success = self.txn.put(key, store_val, **kwargs) except TypeError as e: # the user has presented a none bytes type. print('key type:', type(key)) print('value type:', type(store_val)) raise e except Exception as e: print('Error with: key type:', key) print('Error with: value type:', store_val) raise e self.dirty = save is False and success is True if save is False: return success return self._transaction_success(success) def encode(self, value): """Convert the value to a DB ready storage byte string""" if hasattr(value, 'encode') is True and self.encoding is not False: return value.encode(self.encoding) return self._convert_in(value) def decode(self, byte_value): """Decode the given value expecting a string like or byte data""" if hasattr(byte_value, 'decode'): return byte_value.decode(self.encoding) return str(byte_value) def _convert_in(self, value): """Convert the given value to a storable value, noting its type for reversal in _convert_out) """ z = "!:{}!:{}".format(type(value), value) return str(z).encode(self.encoding) def translate(self, value): return self._convert_out(value, render=False) def _convert_out(self, value, render=None): """Covert a value previously coverted for stage value.""" render = True if render is None else render key = self.encode("!:") if value.startswith(key): if render: return eval(value.split(key)[2]) # First item is empty due to key split. return value.split(key)[1:] return self.decode(value) def _transaction_success(self, success): if success is True and self.auto_commit is True: self.commit() # Uncommited changes exist. return success def replace(self, key, value, db=None, commit=None, encode=True): ckey = self.encode(key) store_value = self.encode(value) if encode is True else value previous = self.txn.replace(ckey, store_value, db) print('commiting transaction with success:') self._transaction_success(True) return previous def iter(self, keys=True, values=True, start=FIRST, decode=True, encode_key=None, dups=None, convert=True, render=None): encode_key = encode_key or decode if start is not None: if start == FIRST: self.first() else: start_key = start if encode_key: self.position(start_key) cur = self.cursor method = cur.iternext if dups is not None: method = cur.iternext_dup if dups is True else cur.iternext_nodup for items in method(keys=keys, values=values): if keys and encode_key: key = self.decode(items[0]) if keys and decode: value = self._convert_out(items[-1], render=render) if convert else items[-1] else: value = self._convert_out(items, render=render) if convert else items if keys: yield key, value else: yield value def collect(self, key, **kwargs): """Return a generator of duplicates for the given key like a 'filter' """ gen = self.iter(keys=False, start=key, dups=True, **kwargs) return tuple(gen) def keys(self, **kwargs): gen = self.iter(values=False, dups=False, convert=False, **kwargs) return tuple(gen) def values(self, **kwargs): gen = self.iter(keys=False, **kwargs) return tuple(gen) def position(self, key): return self.cursor.set_key(self.encode(key)) def first(self): self.cursor.first() def count(self, key=None, restore=False): if key is not None: self.position(key) return self.cursor.count() return len(self.keys()) def delete(self, key, value=None, db=None, commit=True): '''Delete a key from the database. key: The key to delete. value: If the database was opened with dupsort=True and value is not None, then delete elements matching only this (key, value) pair, otherwise all values for key are deleted. ''' e_val = b'' if value is not None: e_val = self.encode(value) success = self.txn.delete(self.encode(key), e_val, db) if commit is False: return success print('commiting transaction') return self._transaction_success(success) def get(self, key, default=None, db=None, convert=True, last=None): ckey = self.encode(key) last = self.get_last if last is None else last if last is True: cursor = self.cursor cursor.set_key(ckey) cursor.last_dup() dbval = cursor.value() else: dbval = self.txn.get(ckey, default, db) if dbval is None: return dbval if convert is False: return dbval return self._convert_out(dbval) def pop(self, key): """Fetch a record's value then delete it. Returns None if no previous value existed. This uses the best available mechanism to minimize the cost of a delete-and-return-previous operation. For databases opened with dupsort=True, the first data element ("duplicate") for the key will be popped. """ return self.cursor.pop(self.encode(key)) def close(self): self.env.close() self.is_open = False def commit(self): # print('Commit') self.txn.commit() self.txn = self.create_transaction() def create_transaction(self, write=None, using=None, as_child=True): """make a ready transaction for the next put. return the new transactio write: boolean Open the new transaction with write flag. If None, self.write is used using: database a child database to use. If none the self.child_db is used. If the child db does not exist the main database is applied as_child: boolean If true, the current transaction (if any) refer as a parent to the new transaction. """ write = self.write if write is None else write kw = {'write': write} kw['db'] = self.child_db if using is not None: # pick from _None_ or the current child db kw['db'] = using if as_child is True and self.txn is not None: pass # kw['parent'] = self.txn # print("Creating transaction with", kw) self._cursor = None return self.env.begin(**kw) def __repr__(self): s = '<{}.{} "{}">' selfc = self.__class__ return s.format(selfc.__module__, selfc.__name__, self.name) class Mappable(object): type = None mappable = True @classmethod def convert(cls, *values): _type = cls.type or cls return _type(values) def register(cls): """Apply the cls to the encoder registry. When a put() occurs for a value matching the class pattern, a special encoding method is applied for store. """ types = cls.get_type() if hasattr(types, '__iter__') is False or isinstance(types, str): types = [types] print('Registering autotype {} {}'.format(cls, types)) for _type in types: DB_TYPE_MAP[_type] = cls class AutoRegister: def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) register(cls) class Type(str): type = None @classmethod def get_type(cls): if isinstance(cls.type, (tuple, list)): return tuple(x.__name__ for x in cls.type) return cls.type.__name__ class CommaAppend: @classmethod def append(cls, byte_string): """Return an altered version of the converted byte string to allow 'append' to the stored byte string. Luckily with bytes, simply 'add' the required comma for `convert()` for loop """ print( 'Comma Append', byte_string) return b',' + byte_string class BaseType(Type, AutoRegister, CommaAppend): type = str @classmethod def convert(cls, *values): if isinstance(cls.type, (tuple, list)): return cls(values) return cls.type(values) class ATuple(BaseType): type = tuple class A1D(Type, AutoRegister, CommaAppend): type = tuple, list @classmethod def convert_in(cls, value, map_type): return value, map_type @classmethod def convert_out(cls, type_cls, value): return type_cls(value) class ADict(BaseType, CommaAppend): type = dict @classmethod def convert(cls, *values): res = {} for inner_dict in values: res.update(inner_dict) return res class AList(ATuple): type = list class ABool(BaseType): type = bool @classmethod def convert(cls, value): return value class ANumber(BaseType): type = int, float, complex class AString(BaseType): type = str class OrderedDB(DB): def next(self): """return the next key of the (cursor current position index)+1 and set the cursor position for the next relative steo. """ success = self.cursor.next() if success is False: raise StopIteration key, value = self._get_cursor_row() return key, value def _get_cursor_row(self): """Return the key, value of the cursors current position.""" return self.cursor.key(), self.cursor.value() class AppendableDB(OrderedDB): def append(self, key, value, safe=False): val, ConvertClass = self._convert_in(value, False, with_class=True) if hasattr(ConvertClass, 'append'): val = ConvertClass.append(val) try: result = self.get(key, convert=False) result += val except TypeError as e: #Unsupport Operand on None. if self.auto_commit and (safe is True): return self.put(key, value) raise TypeError("Cannot append to missing key: {}".format(key)) return self.replace(self.encode(key), result)#, encode=False, overwrite=True) def _convert_in(self, value, prefix=True, with_class=False): """Convert the given value to a storable value, noting its type for reversal in _convert_out) """ # Used for the internal 'appendable' unit type map. # It can be anything really = type_id = type(value).__name__ lmap = { # 'list': AList, # 'tuple': ATuple, # 'dict': ADict, # 'bool': ABool, } convert_class = lmap.get(type_id, DB_TYPE_MAP.get(type_id)) if hasattr(value, 'mappable') and value.mappable is True: convert_class = value.__class__ if convert_class is None: convert_class = BaseType print('No value convertion for {} - defaulting to {}'.format(type_id, convert_class)) map_type = convert_class.__name__ # If no prefix, these elements are removed stamp = "!:" if prefix is True else '' map_type_prefix = map_type if prefix is True else '' if hasattr(convert_class, 'convert_in'): value, map_type_prefix = convert_class.convert_in(value, map_type_prefix) if isinstance(value, (list, tuple)): # Call into mappable, for later type conversion cut = str(value)[1:-1] if cut.endswith(','): cut = cut[:-1] value = convert_class(cut)#"{}, ".format(cut)) z = "{}{}{}{}".format(stamp, map_type_prefix, stamp, value) result = str(z).encode(self.encoding) if with_class: return result, convert_class return result def _convert_out(self, value, render=True, transpose=None): """ Convert the given value from the database and return an item ready to digest by the application. The given 'value' is expected to be a byte string or something acting similar. The discovered database value is evaluted and converted to python literals. render {bool}: execute the found value to produce python objects transpose {bool}: convert the found data value when rendering. This is only usesful to 'render=False' and transpose=True for an execution of data without the execution sandbox. """ render = True if render is None else render transpose = render if transpose is None else transpose """Covert a value previously coverted for stage value.""" key = "!:" ekey = self.encode(key) result = value if hasattr(value, 'startswith') and value.startswith(ekey): splits = value.decode().split(key) result = self._convert_eval(splits, render, transpose) else: return result return result def _convert_eval(self, splits, render, transpose): # print('Converting', value) # print(' -- as', splits) # print(' -- to', render, ev) _eval = eval# literal_eval def _convert(cls_jumper, *values): if hasattr(cls_jumper, 'convert'): # print('_convert', cls_jumper, values) return cls_jumper.convert(*values) if isinstance(cls_jumper, tuple): eval_string = "{}.convert_out({}, {})".format(cls_jumper[0], cls_jumper[1], values) return _eval(eval_string) return values if render: eval_string = "_convert({0[1]}, {0[2]})".format(splits) try: return _eval(eval_string) except Exception as e: print("_convert_eval() render error: {}".format(e), eval_string) # Don't perform full rendering; extract the wanted value and # eval only. result = splits[2] if transpose: result = _eval(result) return result class GRow(Mappable): # type = tuple cut = True @classmethod def convert(cls, *values): _type = cls.type or cls # print("GRow convert {} using {}".format(values, _type)) return _type(*values) def __init__(self, *a): self._a = a def __str__(self): result = str(self._a) return result[1:-1] if self.cut else result def __repr__(self): return '<GRow {}>'.format(self._a) def __getitem__(self, key): return self._a[key] def __len__(self): return len(self._a) <file_sep>/src/v4/bridge.py """Serve as a first layer connect to the dataset and a word grammer correction""" # from database.graph import GraphDB from database.graph import * import database from database.db import * ASSERTIONS_DIR = "E:/conceptnet/_lmdb_assertions/" BRIDGE_DB_DIR = "E:/conceptnet/_lmdb_server_ui/" """The persistent source of original knowledge. held in the shared resource.""" assertions_db = GraphDB(write=False, directory=ASSERTIONS_DIR, name='assertions') """Any relative data to store for the internal procedures.""" db = GraphDB(directory=BRIDGE_DB_DIR, name='bridge') import inflect """ methods: classical inflect plural plural_noun plural_verb plural_adj singular_noun no num a an compare compare_nouns compare_verbs compare_adjs present_participle ordinal number_to_words join defnoun defverb defadj defa defan INFLECTIONS: classical inflect plural plural_noun plural_verb plural_adj singular_noun compare no num a an present_participle PLURALS: classical inflect plural plural_noun plural_verb plural_adj singular_noun no num compare compare_nouns compare_verbs compare_adjs COMPARISONS: classical compare compare_nouns compare_verbs compare_adjs ARTICLES: classical inflect num a an NUMERICAL: ordinal number_to_words USER_DEFINED: defnoun defverb defadj defa defan Exceptions: UnknownClassicalModeError BadNumValueError BadChunkingOptionError NumOutOfRangeError BadUserDefinedPatternError BadRcFileError BadGenderError """ plurals = inflect.engine() def fetch(word): """given a single word, fix plural and singular - returning graph picks""" pass def get_siblings(word): """Return a set of assocated words theough noun and plural etc... extraction. """ # func for each word type. defs = ('plural', 'plural_noun', 'plural_verb', 'plural_adj', 'singular_noun', 'present_participle',) _max = max( (len(x) for x in defs) ) # Once we get a bunch of words, check if they exist as graphs; # Delete unknown words, store correctly spelt words, populate with existing # words. res = {} for func in defs: val = getattr(plurals, func)(word) print("{:>{}} {}".format(func, _max, val)) res[func] = val return res # split graph words from unknown words # delete error word and store unknown # define indefinate article. # p.a("cat") # -> "a cat" # p.compare("index","index") # RETURNS "eq" # p.compare("index","indexes") # RETURNS "s:p" # p.compare("index","indices") # RETURNS "s:p" # p.compare("indexes","index") # RETURNS "p:s" # p.compare("indices","index") # RETURNS "p:s" # p.compare("indices","indexes") # RETURNS "p:p" # p.compare("indexes","indices") # RETURNS "p:p" # p.compare("indices","indices") # RETURNS "eq" <file_sep>/src/v5/context/first/migrations/0006_auto_20190728_0026.py # Generated by Django 2.2.3 on 2019-07-27 23:26 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('first', '0005_auto_20190728_0025'), ] operations = [ migrations.RenameField( model_name='tokenword', old_name='dictionary', new_name='raw_dictionary', ), ] <file_sep>/src/v1/secondary_functions.py import os import nltk from typemap import type_map import contextnet_api as cnapi from logger import print_edges import words from cache import set_cache, string_cache, set_global_root import cache import secondary_functions import cache import loop from json_socket import make_socket, send_json ident_dict = {} socket = None def init(socket_uri="ws://127.0.0.1:8009"): ''' A initialisztion function for anything requiring a first boot. ''' global socket if socket_uri is not None: print 'Making secondary_functions socket' socket = make_socket(socket_uri) def apply_to_context(sentence): '''given data from the token assess, build clean data for the context engine, populating with missing data as required. ''' # success, v = get_cache(filepath) thin_structure_words = tokenize_assess_string(sentence, allow_fetch=True) # Send to the data cleaner for the next stage of cross referencing. updated_words = populate_sub_words(thin_structure_words) words = thin_structure_words print words.keys() print 'tree', thin_structure_words['tree'] send_json({ "sentence": sentence }) res = tuple() if 'words' in words: for wordset in words['words']: word, wtype, ident, dict_ref = wordset print "looking at - ", word, wtype ''' (Pdb) pp(ident['meta'][0:2]) [{'end': {u'@id': u'/c/en/fruit', u'label': u'fruit', u'language': u'en', u'term': u'/c/en/fruit'}, 'id': u'/a/[/r/RelatedTo/,/c/en/apple/,/c/en/fruit/]', 'rel': {u'@id': u'/r/RelatedTo', u'label': u'RelatedTo'}, 'start': {u'@id': u'/c/en/apple', u'label': u'apple', u'language': u'en', u'term': u'/c/en/apple'}, 'surfaceText': u'[[apple]] is related to [[fruit]]', 'weight': 12.80968383684781}, {'end': {u'@id': u'/c/en/red', u'label': u'red', u'language': u'en', u'term': u'/c/en/red'}, 'id': u'/a/[/r/HasProperty/,/c/en/apple/,/c/en/red/]', 'rel': {u'@id': u'/r/HasProperty', u'label': u'HasProperty'}, 'start': {u'@id': u'/c/en/apple', u'label': u'apple', u'language': u'en', u'term': u'/c/en/apple'}, 'surfaceText': u'[[apple]] can be [[red]]', 'weight': 9.591663046625438}] ''' word_def = clean_for_context(wordset, ident.get('meta', [])) res += (word_def,) else: print 'no word information' print 'Have {} words'.format(res) return res class Word(object): def __init__(self, word, tag_type): self.word = word self.tag_type = tag_type self.relatives = {} self._relations = [] self.meaning = None self.antonyms = None self.synonyms = None def add_relative(self, word, word_type, weight=1, sentence=None, language=None): '''Associate a word with this word in relation to the given type''' _type = word_type self._relations.append({ 'word': word, 'type': _type, 'sentence': sentence, 'weight': weight, 'language':language, }) def add_relative_type(self, _type): if self.relatives.get(_type, None) is None: self.relatives[_type] = [] def __repr__(self): s = '<Word("{}" {}) rel: {}~{}>'.format( self.word, self.tag_type, len(self.relatives), len(self._relations), ) return s def clean_for_context(wordset, relations): '''Given the entire dataset for a word, generate and return a cleaner API word for use within the API ''' langs = ['en'] ignore = [u'ExternalURL'] word, wtype, ident, dict_ref = wordset wc = Word(word, tag_type=wtype) wc.meaning = dict_ref.get('meaning', None) wc.antonyms = dict_ref.get('antonym', []) wc.synonyms = dict_ref.get('synonym', []) if relations is None: print 'No relations for {}'.format(wc) return wc for edge in relations: if edge['rel']['label'] in ignore: print 'skipping external url relation' continue try: endlang = edge['end']['language'] except KeyError as e: print 'Language key missing' print edge continue # Add the type of edge as a future relationship type. wc.add_relative_type(edge['rel']['label']) wc.add_relative( word=edge['end'], word_type=edge['rel']['label'], weight=edge['weight'], sentence=edge['surfaceText'], language=edge['end']['language'], ) return wc def populate_sub_words(thin_structure_words, allow_fetch=True): '''A parent string has been tokenized and filled with the raw cache data of the words. Populate the same for any sub words, attached synonyms and antonyms ''' words = thin_structure_words print 'tree', thin_structure_words['tree'] result = [] if 'words' in words: for wordset in words['words']: word, wtype, ident, dict_ref = wordset # populate similar subl = dict_ref['synonym'] if subl is None: continue print 'digressing synonyms of', word, len(subl) for sub_word in subl: print "looking at - ", sub_word value = tokenize_assess_string(sub_word.lower(), allow_fetch=allow_fetch) result.append({ 'value': sub_word, 'meta': value }) else: print 'no word information' return result def populate_sub_words_recursive(thin_structure_words, depth=6, _current_depth=0, root_value=None): print 'populate sub words recursive {}/{}'.format(_current_depth, depth) words = populate_sub_words(thin_structure_words, allow_fetch=False) if _current_depth >= depth: print 'kill depth' return words for word_result in words: if 'words' in word_result['meta']: print 'recursive inspection of', len(word_result['meta']) _words = populate_sub_words_recursive( word_result['meta'], depth=depth, _current_depth=_current_depth+1, root_value=root_value, ) words.extend(_words) return words def ident_object(word, wtype, tokens): return dict() def tokenize_assess_string(sentence, allow_fetch=True): # success, v = get_cache(filepath) v = cache.get_string_cache(sentence) if v is None: v = tokenize(sentence) cache.set_string_cache(sentence, v) return assess_tokens(v, allow_fetch=allow_fetch) def iter_print(g): print '\n' for word, typeof in g: print "{:<20} {:<4} {}".format(word, typeof, type_map.get(typeof, '[NO TYPE]')) return g def tokenize(s): ''' Tokenize the given string sentence consisting of words split by spaces. Returned is a is of tokenized words ''' print 'tokenizing input...', type(s) send_json(type='tokenize', input=s, action='start') t = nltk.word_tokenize(s) g = nltk.pos_tag(t) send_json(type='tokenize', input=s, result=g, action='complete') return g def assess_tokens(tokens, allow_fetch=True): ''' Read and analyze a list of tokens. For each discovered work, entire word assertions exist. returns a tuple of tokens with a word ident object. ''' print 'Assessing:' send_json(type='assess', action='start', tokens=tokens) tree = nltk.chunk.ne_chunk(tokens) res = [] for word, typeof in tokens: item = (word, typeof, type_map.get(typeof, '[NO TYPE]'), ) res.append(item) send_json(type='assess', action='complete', result=res, tokens=tokens) iter_print(tokens) res = () for word, wtype in tokens: # thin_structure_words['words'][3] == tokens ident = assess_word_token(word, wtype, tokens, allow_fetch=allow_fetch) wdd = words.get_word(word) res = res + ( (word, wtype, ident, wdd), ) send_json( type='assess', action='word', word=wdd, word_type=wtype, tokens=tokens, ident=ident, ) # print_edges(ident) return dict(tree=tree, words=res) def assess_word_token(word, wtype, tokens, allow_fetch=True): ''' Given a Word "cake", its type "NN" and associated sentence tokens, "I like cake" identify the word store a cache of identification into the ident_dict. returned is the word entry to the ident_dict; an object of 'idents', 'words' and 'wtypes' ''' ident = "{}_{}".format(word, wtype) # if ident_dict.get(ident, None) is None: # # add to flat # ident_dict[ident] = ident_object(word, wtype, tokens) if ident_dict.get(word, None) is None: # add to flat ident_dict[word] = ident_parent_object(word, wtype, ident, tokens, allow_fetch=allow_fetch) ident_dict[word]['idents'].add(ident) ident_dict[word]['words'].add(word) ident_dict[word]['wtypes'].add(wtype) return ident_dict[word] def ident_parent_object(word, wtype, ident, tokens, allow_fetch=True): ''' Create a single word entry to the identity context, associating any _wtype additions word: Literal word given for input: i.e. "cake" wtype: Token type from nltk Penn Treebank tagging: "NN" ident: Literal word token assignment identity: "Cake_NN" tokens: Assosciated sentence tokens. The meta data within the result will call the to the context API. ''' res = dict(words=set(), wtypes=set(), idents=set()) res['meta'] = cnapi.api_result(word.lower(), allow_fetch=allow_fetch) # {'end': {u'@id': u'/c/en/greeting', # u'label': u'greeting', # u'language': u'en', # u'term': u'/c/en/greeting'}, # 'id': u'/a/[/r/IsA/,/c/en/hello/,/c/en/greeting/]', # 'rel': {u'@id': u'/r/IsA', u'label': u'IsA'}, # 'start': {u'@id': u'/c/en/hello', # u'label': u'Hello', # u'language': u'en', # u'term': u'/c/en/hello'}, # 'surfaceText': u'[[Hello]] is a kind of [[greeting]]', # 'weight': 4.47213595499958} return res; <file_sep>/src/server/assets/js/colourmap_view.js var colourmapApp = new Vue({ el: '#colormap' , methods: { colors(){ return Object.assign({}, colormap) } } }) <file_sep>/src/conceptnet/scratch_db.py import multiprocessing import traceback from .parse import parse_csv, clean_line, spread def spread_caller_function(**kw): return spread(store_lines, **kw) def writer_function(*a, **kw): print(a, kw) def store_lines(kw): process_name = multiprocessing.current_process().name db_index = kw.get('job_index', 0) options = dict( max_count=kw.get('max_count', 1_000_000), iter_line=caller_function, as_set=True, row_index=kw.get('row_index', 0), keep_sample=kw.get('sample', False), byte_start=kw.get('byte_start', None), byte_end=kw.get('byte_end', None), path=kw.get('path', None) ) options.update(kw) try: d, sample = parse_csv(**options) print('Finished relations. Count: {}. Writing file'.format(len(d))) except Exception as e: print('Error on "{}" :'.format(process_name), e) print(traceback.format_exc()) d = [] # pipe.execute() return list(d) chunk_list = () def caller_function(line, **kw): l = clean_line(line, **kw) k = [] if l is None: return None _type, sw, ew, weight, _json = l _json.update({ "connection": _type, "weight": weight, #"direction": ('start', 'end',) }) chunk_size = kw.get('chunk_size', 1000) kw['row_index'] += 1 if kw['row_index'] % chunk_size == 0: global chunk_list func = kw.get('step_function', line_print) res = func(chunk_list, line, kw) chunk_list = () else: chunk_list += (_json, ) def line_print(items, line, given_kwargs): print('LAST: {start[word]} {connection} {end[word]} {weight}'.format(**items[-1])) if __name__ == '__main__': store_lines({}) <file_sep>/src/v3/contextnet_api.py import requests import os, io import json import csv from collections import namedtuple import traceback import cache FETCH_ALLOWED = False endpoints = ["http://api.conceptnet.io/c/en/", "http://conceptnet5.media.mit.edu/c/en/", "http://csc.media.mit.edu/c/en/",] e_counter = 0 def bump_endpoint(): global e_counter e_counter += 1 if e_counter > len(endpoints) + 1: e_counter = 0 def api_fetch(word=None, depth=0, path=None, result_object=None, root_word=None, allow_cache=True, allow_fetch=True, _force_allow=False, limit=50): ''' Fetch the work context from the external API. Returning an object ''' fetch = True data = None root_word = root_word or word print( '.. Root word', root_word) filepath = None can_fetch = FETCH_ALLOWED endpoint = endpoints[e_counter] if _force_allow is True: print( 'Force override fetch from external') can_fetch = True allow_fetch = True if word is not None: fn = 'api_cache_{}.json'.format(word.replace(' ', '_')) filepath = cache.resolve_path(fn) if allow_cache is True: if os.path.isfile(filepath): print( 'opening api cache file') with io.open(filepath) as stream: content = stream.read() if len(content) > 0: data = json.loads(content) fetch = False if fetch is True: if can_fetch is False or allow_fetch is False: print( 'Fetching not allowed') else: print( 'Fetching: ', word or path) if word is None: uri = '{}{}'.format(endpoint, path) uri = '{}{}'.format(endpoint, word) if path and path.startswith('/'): uri = '{}{}'.format(endpoint, os.path.split(path)[1]) try: data = requests.get(uri, params=dict(limit=limit)).json() except Exception as e: traceback.print_exc() bump_endpoint() try: data = requests.get(uri, params=dict(limit=limit)).json() except Exception as e: print( 'Error fetching context', e) return None if 'error' in data: print( data['error']['details']) return None next_path = data.get('view', {}).get('nextPage', None) if next_path is not None and depth < 5 and depth != -1: print( 'Paging', root_word, depth) api_fetch( path=next_path, depth=depth+1, result_object=result_object or data, root_word=root_word, _force_allow=_force_allow, limit=limit, ) if filepath is None: filepath = 'api_cache_{}_{}.json'.format(root_word, depth) print( 'writing api cache:', filepath) cache.write_json(filepath, data) if result_object is not None: key = 'index_{}'.format(depth) result_object[key] = data result_object['index_length'] = max(result_object.get('index_length', -1), depth) return data def api_clean(data): ''' Given an API result, return a clean set of edges ''' result = [] for edge in data['edges']: item = clean_edge(edge) result.append(item) for index in range(data.get('index_length', 0)): key = 'index_{}'.format(index+1) sub_data = data[key] for edge in sub_data['edges']: item = clean_edge(edge) result.append(item) return result def clean_edge(edge): return dict( id=edge['@id'], start=edge['start'], end=edge['end'], rel=edge['rel'], weight=edge['weight'], surfaceText=edge['surfaceText'], ) def api_result(*a, **kw): data = api_fetch(*a, **kw) if data is None: return None return api_clean(data) Line = namedtuple('Line', ['uri', 'relation', 'start', 'end', 'json']) def read_assertions(): ''' + The URI of the whole edge + The relation expressed by the edge + The node at the start of the edge + The node at the end of the edge + A JSON structure of additional information about the edge, such as its weight ''' reader = IterCSV(filepath='F:/assertions.csv') for line in iter(reader): print( line) return reader class IterCSV(object): def __init__(self, stream=None, filepath=None): if stream is not None: self.set_stream(stream) if filepath is not None: self.set_stream(open(filepath, 'rb')) def set_stream(self, stream): self.stream = stream self.csv = csv.reader(stream, delimiter='\t') def next(self): return Line(*self.csv.next()) def __iter__(self): return self.next <file_sep>/docs/notes.txt ## Code renderences http://blog.conceptnet.io/2018/06/naacl2018-poster.pdf XGBoost: A Scalable Tree Boosting System: https://arxiv.org/abs/1603.02754 ## Changes/Todo Allow access of multple DBs through one handle db1 = DB(dir=path, name='foo') db2 = DB(dir=path, name='bar') to one caller db1 = DB(dir=path, name='foo') sub = db1.open(name=bar) and also with no auto open db = DB(dir=path) db1 = db.open(name='foo') sub = db.open(name=bar) <file_sep>/src/v5/context/first/views.py from django.shortcuts import render from django.views.generic import TemplateView, ListView, FormView, DetailView from . import signals from . import models from . import forms class Index(ListView): model = models.TemporalInput class InputDetailView(DetailView): model = models.TemporalInput class InputFormView(FormView): form_class = forms.TemporalInputForm success_url = '/' template_name = 'first/form.html' def form_valid(self, form): print('Saving form') self.object = form.save(commit=False) signals.pre_save_input.send(sender=self.object.__class__, instance=self.object) self.object.save() signals.post_save_input.send(sender=self.object.__class__, instance=self.object) return super().form_valid(form) <file_sep>/src/helper.py """My little boot script.""" from database.graph import * import database from database.db import * from conceptnet import scratch_db from v4.bridge import get_siblings as get from v4.wordnet import get_word, NOUN, VERB, ADJ, ALL ASSERTIONS_DIR = "E:/conceptnet/_lmdb_assertions_july_2019_rev/" SERVER_ASSERTIONS_DIR = "E:/conceptnet/_lmdb_server_ui/" csv_path = 'E:\\conceptnet\\assertions.csv' GB_9 = 9e+9 assertions_db = GraphDB(write=False, directory=ASSERTIONS_DIR, name='assertions') db = GraphDB(directory=SERVER_ASSERTIONS_DIR, name='server') """The Edge instance as a handle is a simple wrapper for calling pick() from the graph. Any calls to edge are piped to the graph_db. db.pick('apples') # to handle.apples """ # handle.my.related_to.belonging.weight # handle = Edge(db) # # sorted(handle.my.related_to, reverse=True)[0] # a = EdgeNode('top', 1) # b = EdgeNode('toy', 2) # c = EdgeNode('other', 1) # edges = Edges(items=(a,b,)) # db.open('test') # # db.put('banana', False) # # banana_res = db.get('banana') # expected = (False, False, True, True) # db.put('choice', expected) # result = db.get('choice') # print(result, type(result)) # e=Edge(assertions_db) # hi = e.hi # he = e.hello # edge = hi.get_edges('greeting') # res = he & hi get_word('egg', kws=ALL, to_file='foo1.txt') # >>> res # <ChildGraph "hello [&] hi" 2 edges of: (is_a, related_to)> # >>> res.edges # {'IsA': <Edges 1 "IsA" ('greeting(3.464) from "hello [&] hi"',)>, # 'RelatedTo': <Edges 1 "RelatedTo" ('greeting(1.0) from "hello [&] hi"',)>} # produce a function to flip the associations. # Relating a word from the child graph 'greeting' to its # edge type and associated (sum) weight value. # # res.flipped_edged: # { greeting: ((isa, 3.4), (relatedto, 1))} # ! the edgenode given to the childgraph looses its main parent. # This is because the __and__ generates a parent=self tothe child # Which is collected by the Grow 'child.values' and edge_list() # spawn. # >>> res.is_a.greeting.parent_graph # <ChildGraph "hello [&] hi" 2 edges of: (is_a, related_to)> # Which should be: # he.is_a.greeting.parent_graph # <Graph "hello" 26 edges of: (a...)> # because this edge originaled from the 'Hello' graph. def main(): pass if __name__ == '__main__': main() <file_sep>/src/plog/working3.py from api import Plog from patterns import PlogLine, PlogBlock f = open('test_data2.txt', 'r') # Capture something block = PlogBlock('Device ID:', ref='Device') block.header.ref='device_id' block.footer = PlogLine('----------', ref='footer').anything() ip_address = PlogLine('IP address:') block.add_lines(ip=ip_address) # new parser plog = Plog(f, whitespace='|') # run it plog.add_block(block) blocks = plog.run() for block in blocks: if block.valid(): print block.as_dict() <file_sep>/src/conceptnet/readme.md Parsing of the conceptnet data information as a pre compilation of graph data. Here you'll find a bunch of CSV iteration tools for loading into various DB Types. py -i conceptnet\scratch_db.py
99986c5471051806f9bd66f35d1a52dd497df52b
[ "Markdown", "Python", "JavaScript", "Text" ]
110
Markdown
Strangemother/project-conceptnet-graphing
3fd1b3188088090c71c95b1a660770482123ce22
00b1ca87718efc5342ff47d7355e352b3efcf5b1
refs/heads/master
<repo_name>ferbrett/Jukebox_App<file_sep>/src/studentPlaylists/TestStudent1_Playlist.java package studentPlaylists; import playlist.PlayableSong; import playlist.Song; import artist.*; import java.util.ArrayList; import java.util.LinkedList; public class TestStudent1_Playlist { public LinkedList<PlayableSong> StudentPlaylist(){ LinkedList<PlayableSong> playlist = new LinkedList<PlayableSong>(); ArrayList<Song> beatlesTracks = new ArrayList<Song>(); TheBeatles theBeatlesBand = new TheBeatles(); beatlesTracks = theBeatlesBand.getBeatlesSongs(); playlist.add(beatlesTracks.get(0)); playlist.add(beatlesTracks.get(1)); ImagineDragons imagineDragonsBand = new ImagineDragons(); ArrayList<Song> imagineDragonsTracks = new ArrayList<Song>(); imagineDragonsTracks = imagineDragonsBand.getImagineDragonsSongs(); playlist.add(imagineDragonsTracks.get(0)); playlist.add(imagineDragonsTracks.get(1)); playlist.add(imagineDragonsTracks.get(2)); return playlist; } } <file_sep>/src/artist/TechN9ne.java package artist; import playlist.Song; import java.util.ArrayList; public class TechN9ne { ArrayList<Song> albumTracks; String albumTitle; public TechN9ne() { } public ArrayList<Song> getTechN9nesSongs() { albumTracks = new ArrayList<Song>(); Song track1 = new Song("Worldwide Choppers", "Tech N9ne"); Song track2 = new Song("This Is Me", "Tech N9ne"); Song track3 = new Song("He's a Mental Giant", "Tech N9ne"); Song track4 = new Song("Dr. Sebagh", "Tech N9ne"); this.albumTracks.add(track1); this.albumTracks.add(track2); this.albumTracks.add(track3); this.albumTracks.add(track4); return albumTracks; } } <file_sep>/src/playlist/Jukebox.java package playlist; import java.util.LinkedList; import java.util.Queue; public class Jukebox { static Queue<PlayableSong> playlist = new LinkedList<PlayableSong>(); PlayableSong current; Jukebox() { } public Queue<PlayableSong> play(String studentPlaylistRequested) { StudentList studentProfile = new StudentList(); Student student = studentProfile.GetStudentProfile(studentPlaylistRequested); playlist = student.getPlaylist(); current = playlist.poll(); if(current != null) { current.play(); } return playlist; } public void playNext() { if(current instanceof Song) { // If we are currently playing a song, get the next one getNextSong(); } } public void getNextSong() { current = playlist.poll(); if(current != null) { current.play(); } } } <file_sep>/src/artist/PinkFloyd.java package artist; import playlist.Song; import java.util.ArrayList; public class PinkFloyd { ArrayList<Song> albumTracks; String albumTitle; public PinkFloyd() { } public ArrayList<Song> getPinkFloydsSongs() { albumTracks = new ArrayList<Song>(); Song track1 = new Song("Another Brick in the Wall", "Pink Floyd"); Song track2 = new Song("Comfortably Numb", "Pink Floyd"); Song track3 = new Song("Money", "Pink Floyd"); this.albumTracks.add(track1); this.albumTracks.add(track2); this.albumTracks.add(track3); return albumTracks; } } <file_sep>/src/artist/TomPettyAndTheHeartbreakers.java package artist; import java.util.ArrayList; import playlist.Song; public class TomPettyAndTheHeartbreakers { ArrayList<Song> albumTracks; String albumTitle; public TomPettyAndTheHeartbreakers() { } public ArrayList<Song> getTomPettyAndTheHeartbreakersSongs() { albumTracks = new ArrayList<Song>(); Song track1 = new Song("Free Fallin'", "<NAME> and the Heart Breakers"); Song track2 = new Song("I Won't Back Down", "<NAME> and the Heart Breakers"); Song track3 = new Song("Break Down", "<NAME> and the Heart Breakers"); this.albumTracks.add(track1); this.albumTracks.add(track2); this.albumTracks.add(track3); return albumTracks; } } <file_sep>/src/artist/ArianaGrande.java package artist; import playlist.Song; import java.util.ArrayList; public class ArianaGrande { ArrayList<Song> albumTracks; String albumTitle; public ArianaGrande() { } public ArrayList<Song> getArianaGrandeSongs() { albumTracks = new ArrayList<Song>(); Song track1 = new Song("Greedy", "Ariana Grande"); Song track2 = new Song("NASA", "Ariana Grande"); this.albumTracks.add(track1); this.albumTracks.add(track2); return albumTracks; } } <file_sep>/src/playlist/JukeboxPlayer.java package playlist; import java.util.LinkedList; import java.util.Queue; public class JukeboxPlayer { public static void main(String[] args) { try{ String studentPlaylistRequested =""; Queue<PlayableSong> playlist = new LinkedList<PlayableSong>(); Jukebox jukebox = new Jukebox(); CommandManager cm=new CommandManager(); while(true){ cm.printMainMenu(); String command = cm.getCommand(); if(command.toLowerCase().equals("quit")) break; studentPlaylistRequested = cm.parseCommand(command); playlist = jukebox.play(studentPlaylistRequested); int playlistSize = playlist.size(); for (int i = 0; i < playlistSize; i++) { jukebox.playNext(); } } }catch(Exception e){ System.out.println("Oops!! Something went wrong. Please try again!!"); //e.printStackTrace(); } } } <file_sep>/src/tests/JukeboxTest.java package tests; import static org.junit.Assert.*; import java.util.ArrayList; import org.junit.Test; import artist.*; import playlist.Song; public class JukeboxTest { @Test public void testGetBeatlesAlbumSize() throws NoSuchFieldException, SecurityException { TheBeatles theBeatlesBand = new TheBeatles(); ArrayList<Song> beatlesTracks = new ArrayList<Song>(); beatlesTracks = theBeatlesBand.getBeatlesSongs(); assertEquals(3, beatlesTracks.size()); } @Test public void testGetImagineDragonsAlbumSize() throws NoSuchFieldException, SecurityException { ImagineDragons imagineDragons = new ImagineDragons(); ArrayList<Song> imagineDragonsTracks = new ArrayList<Song>(); imagineDragonsTracks = imagineDragons.getImagineDragonsSongs(); assertEquals(3, imagineDragonsTracks.size()); } @Test public void testGetAdelesAlbumSize() throws NoSuchFieldException, SecurityException { Adele adele = new Adele(); ArrayList<Song> adelesTracks = new ArrayList<Song>(); adelesTracks = adele.getAdelesSongs(); assertEquals(3, adelesTracks.size()); } @Test public void testGetPinkFloydsAlbumSize() throws NoSuchFieldException, SecurityException { PinkFloyd pinkFloyd = new PinkFloyd(); ArrayList<Song> PinkFloydsTracks = new ArrayList<Song>(); PinkFloydsTracks = pinkFloyd.getPinkFloydsSongs(); assertEquals(3, PinkFloydsTracks.size()); } @Test public void testGetTechN9nesAlbumSize() throws NoSuchFieldException, SecurityException { TechN9ne techN9ne = new TechN9ne(); ArrayList<Song> TechN9nesTracks = new ArrayList<Song>(); TechN9nesTracks = techN9ne.getTechN9nesSongs(); assertEquals(4, TechN9nesTracks.size()); } @Test // Test to ensure getArianaGrandeSongs array works and ArianaGrande.java class songs are displayed public void testGetArianaGrandeAlbumSize() throws NoSuchFieldException, SecurityException { ArianaGrande arianaGrande = new ArianaGrande(); ArrayList<Song> arianaGrandeTracks = new ArrayList<Song>(); arianaGrandeTracks = arianaGrande.getArianaGrandeSongs(); assertEquals(2, arianaGrandeTracks.size()); } @Test // Test to ensure getDanceGavinDanceSongs array works and DanceGavinDance.java class songs are displayed public void testGetDanceGavinDanceAlbumSize() throws NoSuchFieldException, SecurityException { DanceGavinDance danceGavinDance = new DanceGavinDance(); ArrayList<Song> danceGavinDanceTracks = new ArrayList<Song>(); danceGavinDanceTracks = danceGavinDance.getDanceGavinDanceSongs(); assertEquals(3, danceGavinDanceTracks.size()); } }
fc6c734d263af9ccffe0789071b7569fde683772
[ "Java" ]
8
Java
ferbrett/Jukebox_App
064f40f62a521a4354642157b425a8eaccd8752e
f4c375d2f55d8699a86b81f4f397a6d739739b1b
refs/heads/master
<repo_name>Symbelmene/cnn<file_sep>/cnn_image.py # -*- coding: utf-8 -*- """ Created on Sat Feb 1 18:55:54 2020 @author: chris """ from __future__ import absolute_import, division, print_function, unicode_literals # Import TensorFlow modules import tensorflow as tf from tensorflow import keras # Import numerical modules import numpy as np import matplotlib.pyplot as plt print('TensorFlow Version: {}'.format(tf.__version__)) def plot_image(i, predictions_array, true_label, img): predictions_array, true_label, img = predictions_array, true_label[i], img[i] plt.grid(False) plt.xticks([]) plt.yticks([]) plt.imshow(img, cmap=plt.cm.binary) predicted_label = np.argmax(predictions_array) if predicted_label == true_label: color = 'blue' else: color = 'red' plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label], 100*np.max(predictions_array), class_names[true_label]), color=color) def plot_value_array(i, predictions_array, true_label): predictions_array, true_label = predictions_array, true_label[i] plt.grid(False) plt.xticks(range(10)) plt.yticks([]) thisplot = plt.bar(range(10), predictions_array, color="#777777") plt.ylim([0, 1]) predicted_label = np.argmax(predictions_array) thisplot[predicted_label].set_color('red') thisplot[true_label].set_color('blue') # Import fashion data & normalise fashion_mnist = keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data() train_images = train_images / 255.0 test_images = test_images / 255.0 # Data key class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] # Display 25 test images plt.figure(figsize=(12,12)) for im in range (25): plt.subplot(5,5,im+1) plt.imshow(test_images[im], cmap='Greys', interpolation='nearest') plt.xticks([]) plt.xlabel(class_names[test_labels[im]]) plt.yticks([]) plt.show() # Create CNN parameters model = keras.Sequential([keras.layers.Flatten(input_shape=[28,28]), keras.layers.Dense(128,activation='relu'), keras.layers.Dense(128,activation='relu'), keras.layers.Dense(10,activation='softmax')]) model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['accuracy']) model.fit(train_images, train_labels, epochs=5) """ # Test model test_im = 25 test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) print('Test accuracy = {}'.format(test_acc)) predictions = model.predict(test_images) im_prediction = class_names[np.argmax(predictions[test_im])] im_actual = class_names[test_labels[test_im]] print('Actual: {}'.format(im_actual)) print('Prediction: {}'.format(im_prediction)) # Show confidence of image predictions for i in range(25): plt.figure(figsize=(6,3)) plt.subplot(1,2,1) plot_image(i, predictions[i], test_labels, test_images) plt.subplot(1,2,2) plot_value_array(i, predictions[i], test_labels) plt.show() # Make prediction about single image for i in range(50): img = test_images[i] img = np.expand_dims(img, 0) predictions_single = model.predict(img) print(class_names[np.argmax(predictions_single)]) """ <file_sep>/cnn_mnist.py # -*- coding: utf-8 -*- """ Created on Mon Feb 17 12:18:46 2020 @author: chris """ # Import TensorFlow libraries import tensorflow as tf from tensorflow import keras # Import mathematical and graphing libraries import numpy as np import matplotlib.pyplot as plt # Import MNIST data set mnist_data = keras.datasets.mnist (x_images, x_labels), (y_images, y_labels) = mnist_data.load_data() # Image checker function def show_image(im_arr, im_start): plt.figure(figsize=(10,10)) for i in range(25): plt.subplot(5,5,1+i) plt.grid(False) plt.xticks([]) plt.yticks([]) plt.imshow(im_arr[im_start + i], cmap=plt.cm.binary) show_image(x_images, 500)
8b0c18530c30d895faa818da04718df6298bc676
[ "Python" ]
2
Python
Symbelmene/cnn
8fbe4a46bb5b2d879cfc600b9670eecaf3de6b5b
ea5019b1569be5b335fdceee3a19fe9a774d2ec7
refs/heads/master
<repo_name>DannyQuishpe1994/ProyectoSistemasMecanica<file_sep>/PROYECTO/login.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="css/main_1.css"> <title>LOGIN PROYECTO</title> </head> <body> <form action="logica/loguear.php" method="post" > <div align="center"> <?php if (isset($errorLogin)) { echo $errorLogin; } ?> <h2>INICIAR SESION</h2> <input type="text" name="usuario" placeholder="nickname" autocomplete="off" required="true"> <br><br> <input type="<PASSWORD>" name="password" placeholder="<PASSWORD>" autocomplete="off" required="true"> <br><br> <input type="submit" ></input > <br><br> </div> </form> <div align="center"> <a href=" vistas/registro.php">Registrarme</a> &nbsp&nbsp &nbsp <a href=" vistas/correo.php">Olvide mi password</a> </div> </body> </html><file_sep>/PROYECTO/vistas/correo.php <?php // Llamando a los campos //$nombre = $_POST['nombre']; //$correo = $_POST['correo']; //$telefono = $_POST['telefono']; //$mensaje = $_POST['mensaje']; // Datos para el correo $destinatario = "<EMAIL>"; $asunto = "Contacto desde nuestra web"; $carta = "mwnsaje de prueba "; // Enviando Mensaje $mail = mail($destinatario, $asunto, $carta); if ($mail) { echo 'mensaje enviado'; } else { echo 'no valio'; } ?><file_sep>/PROYECTO/logica/loguear.php <?php require './conexion.php'; session_start(); $usuario = $_POST['usuario']; $clave = $_POST['password']; $q="SELECT COUNT(*)as contar FROM usuarios where username = '$usuario' and password = '$clave'"; $consulta = mysqli_query($conexion, $q); $array = mysqli_fetch_array($consulta); if ($array['contar']>0){ $_SESSION['username']=$usuario; header("location: ../principal.php"); }else{ $errorLogin = "Nombre de usuario y/o password incorrectos"; header("location: ../login.php"); } ?> <file_sep>/PROYECTO/principal.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Home</title> <link rel="stylesheet" href="../css/main_1.css"> </head> <body> <div id="menu"> <ul> <li>Home</li> <li class="cerrar-sesion"><a href="logica/salir.php">Cerrar sesión</a></li> </ul> </div> <section> <?php session_start(); $usuario = $_SESSION['username']; if (!isset($usuario)) { header("location: login.php"); } else { echo "<H1>BIENVENIDO $usuario</H1>"; } ?> </section> </body> </html> <file_sep>/PROYECTO/vistas/registro.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="./css/reset.css"> <link href="https://fonts.googleapis.com/css?family=Lato:400,900" rel="stylesheet"> <link rel="stylesheet" href="../css/main.css"> <title>Formulario</title> </head> <body> <div class="container"> <div class="form__top"> <h2>Registro <span> de</span> <span> Usuarios</span></h2> </div> <form action="../vistas/registro.php" class="form__reg" method="POST"> <input class="input" type="text" name="cedula" placeholder="&#128100; Cedula" minlength="10" maxlength="10" pattern="[0-9]+" required autocomplete="off"/> <input class="input" type="text" name="nombre" placeholder="&#128100; Nombre" minlength="2" maxlength="15" pattern="[A-Za-z]+" required autocomplete="off"/> <input class="input" type="text" name="apellido" placeholder="&#128100; Apellido" minlength="2" maxlength="15" pattern="[A-Za-z]+" required autocomplete="off"/> <input class="input" type="text" name="username" placeholder="&#128100; Username" minlength="5" maxlength="15" pattern="[A-Za-z0-9]+" required autocomplete="off"/> <input class="input" type="password" name="password" placeholder="&#8962; <PASSWORD>" minlength="5" maxlength="12" pattern="[A-Za-z0-9]+" required autocomplete="off"> <input class="input" type="email" name="correo" placeholder="&#9993; Correo" required autocomplete="off"/> <div class="btn__form"> <input type="submit" class="btn__submit" name="registrarse" value="REGISTRAR"> <input class="btn__reset" type="reset" value="LIMPIAR"> </div> </form> </div> <div id="menu"> <ul> <li class="cerrar-sesion"><a href="..//login.php">Salir</a></li> </ul> </div> </body> </html> <?php $server = "localhost"; $username = "root"; $password = ""; $database = "proyecto"; $enlace = mysqli_connect($server, $username, $password, $database); if (!$enlace) { echo 'error de conexion'; }else{ //echo 'conectado' ; } if (isset($_POST['registrarse'])) { $cedula = $_POST["cedula"]; $nombre = $_POST["nombre"]; $apellido = $_POST["apellido"]; $username = $_POST["username"]; $password = $_POST["password"]; $correo = $_POST["correo"]; $insertarDatos = "INSERT INTO usuarios VALUES ('$cedula', '$nombre', '$apellido', '$username', '$password', '$correo');"; $ejecutarInsertar = mysqli_query($enlace, $insertarDatos); if ($ejecutarInsertar) { echo '<br><alert>USUARIO ' . $username . ' REGISTRADO CON ÉXITO </alert>'; header('location: ..//login.php'); } else { echo '<alert>USUARIO ' . $username . ' NO SE PUDO REGISTRAR, INTENTE NUEVAENTE </alert>'; } } ?> <file_sep>/PROYECTO/proyecto.sql -- phpMyAdmin SQL Dump -- version 4.9.1 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 12-12-2019 a las 03:41:20 -- Versión del servidor: 10.4.8-MariaDB -- Versión de PHP: 7.3.11 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `proyecto` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `datos` -- CREATE TABLE `datos` ( `id_variable` int(2) NOT NULL, `valor` double NOT NULL, `hora` time NOT NULL, `fecha` date NOT NULL, `estado` int(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci; -- -- Volcado de datos para la tabla `datos` -- INSERT INTO `datos` (`id_variable`, `valor`, `hora`, `fecha`, `estado`) VALUES (3, 45.35, '14:25:37', '2019-12-09', 1), (3, 1.5, '14:25:50', '2019-12-09', 1), (7, 5, '12:24:57', '0000-00-00', 1); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `tipo_usuario` -- CREATE TABLE `tipo_usuario` ( `id_tipo` int(2) NOT NULL, `tipo` text COLLATE utf8mb4_spanish_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `usuarios` -- CREATE TABLE `usuarios` ( `ci` text COLLATE utf8mb4_spanish_ci NOT NULL, `nombre` text COLLATE utf8mb4_spanish_ci NOT NULL, `apellido` text COLLATE utf8mb4_spanish_ci NOT NULL, `username` text COLLATE utf8mb4_spanish_ci NOT NULL, `password` text COLLATE utf8mb4_spanish_ci NOT NULL, `correo` text COLLATE utf8mb4_spanish_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci; -- -- Volcado de datos para la tabla `usuarios` -- INSERT INTO `usuarios` (`ci`, `nombre`, `apellido`, `username`, `password`, `correo`) VALUES ('1<PASSWORD>', 'Danny', 'Quishpe', 'Dquishpe', '278743', '<EMAIL>'), ('1723081400', 'damian', 'toaza', 'atoaza', 'andi123', '<EMAIL>'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `variable` -- CREATE TABLE `variable` ( `id_variable` int(2) NOT NULL, `tipo_variable` varchar(15) COLLATE utf8mb4_spanish_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci; -- -- Volcado de datos para la tabla `variable` -- INSERT INTO `variable` (`id_variable`, `tipo_variable`) VALUES (1, 'temperatura'), (2, 'volumen'), (3, 'presion'); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `datos` -- ALTER TABLE `datos` ADD KEY `id_variable` (`id_variable`); -- -- Indices de la tabla `tipo_usuario` -- ALTER TABLE `tipo_usuario` ADD PRIMARY KEY (`id_tipo`); -- -- Indices de la tabla `variable` -- ALTER TABLE `variable` ADD PRIMARY KEY (`id_variable`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
a85a8e4131091bdf702aa9fce451eb9a546774e6
[ "SQL", "PHP" ]
6
PHP
DannyQuishpe1994/ProyectoSistemasMecanica
81cd6238c33d6cf4efc5bdeb5be3a2b721d0279c
86d368d887c000683a2bdfa39bfdb7522cfe7ae7
refs/heads/master
<file_sep>package com.ryz2593.orm; import com.ryz2593.orm.dao.UserDAO; import com.ryz2593.orm.dao.impl.UserDAOImpl; import com.ryz2593.orm.domain.User; import java.util.Date; /** * Hello world! */ public class App { public static void main(String[] args) { //创建用户对象 User user = new User(); user.setId(1001); user.setName("zs"); user.setAge(30); user.setBirth(new Date()); UserDAO dao = new UserDAOImpl(); int row = dao.addUser(user); System.out.println(row > 0 ? "success" : "failure"); } } <file_sep>jdbc.driver_class=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://172.17.28.129:3306/P365MyTest?useUnicode=true&characterEncoding=UTF-8 jdbc.user=root jdbc.password=<PASSWORD><file_sep>package com.ryz2593.orm.dao; import com.ryz2593.orm.domain.User; /** * @author ryz2593 * @date 2019/4/23 * @desc */ public interface UserDAO { int addUser(User user); } <file_sep>package org.ryz2593.orm.datasource.impl; import org.ryz2593.orm.datasource.DataSource; import org.ryz2593.orm.datasource.DataSourceConstant; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; /** * @author ryz2593 * @date 2019/4/23 * @desc */ public class DataSourceImpl implements DataSource, DataSourceConstant { static { try { //注册驱动 Driver driver = (Driver) Class.forName(DRIVER_CLASS).newInstance(); DriverManager.registerDriver(driver); } catch (Exception e) { e.printStackTrace(); } } @Override public Connection getDataSource() { Connection conn = null; try { conn = DriverManager.getConnection(URL, USER, PASSWORD); } catch (Exception e) { e.printStackTrace(); } return conn; } } <file_sep>package org.ryz2593.orm.datasource; import org.ryz2593.orm.util.PropertiesUtil; /** * @author ryz2593 * @date 2019/4/23 * @desc */ public interface DataSourceConstant { String DRIVER_CLASS = PropertiesUtil.getInstance().getProperty("jdbc.driver_class"); String URL = PropertiesUtil.getInstance().getProperty("jdbc.url"); String USER = PropertiesUtil.getInstance().getProperty("jdbc.user"); String PASSWORD = PropertiesUtil.getInstance().getProperty("jdbc.password"); } <file_sep>package org.ryz2593.orm.util; import java.io.InputStream; import java.util.Properties; /** * @author ryz2593 * @date 2019/4/23 * @desc */ public class PropertiesUtil extends Properties { public static final String CONFIG_LOCATION = "jdbc.properties"; private static PropertiesUtil util = new PropertiesUtil(); private PropertiesUtil() { try ( InputStream in = this.getClass().getClassLoader().getResourceAsStream(CONFIG_LOCATION) ) { this.load(in); } catch (Exception e) { e.printStackTrace(); } } public static PropertiesUtil getInstance() { return util; } } <file_sep># orm-platform 手写实现 <img src="https://content.perfect365.com/explore/CB22106E-162A-4dc4-934F-B48A6B99D0A3.png" />
b2c99b62193e038ae46d55115aeb25d8a83c8739
[ "Markdown", "Java", "INI" ]
7
Java
ryz2593/orm-platform
6a049e4f6c78dd21ec1aeb2267cbfdee33b25fe0
b0c6f2c6770b42253976bdb165f39c974cd862cd
refs/heads/master
<file_sep>resize(); function load() { var myVar = setTimeout(() => { document.getElementById("gallery").style.display = "flex"; }, 100); } function resize() { var imgs = document.getElementsByTagName("img"); for (var i = 0; i < imgs.length; i++) { if (imgs[i].width / imgs[i].height > 1) { imgs[i].classList.add("img-landscape"); } else { imgs[i].classList.add("img-portrait"); } } } <file_sep># Gallery [https://rohithvr101.github.io/Gallery/](https://rohithvr101.github.io/Gallery/) An image gallery page created with vanilla JavaScript, HTML, CSS with images from 10 different websites all resized to 40x40 px size without losing aspect ratio.
04ce3bb2fb577508ba8a6e0054d118a4b5df140f
[ "JavaScript", "Markdown" ]
2
JavaScript
rohithVR101/Gallery
6093c45590f9c099a9364ccf77b21d576e82fecd
cb75adf0e10bf67d4edf89c2821f7612be7a34ca
refs/heads/master
<repo_name>TheRatG/BranchingBundle<file_sep>/TheRatBranchingBundle.php <?php namespace TheRat\BranchingBundle; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Bundle\Bundle; use TheRat\BranchingBundle\DependencyInjection\Compiler\SwitchDbNameCompiler; class TheRatBranchingBundle extends Bundle { public function build(ContainerBuilder $container) { parent::build($container); $container->addCompilerPass(new SwitchDbNameCompiler()); } } <file_sep>/Helper/Git.php <?php namespace TheRat\BranchingBundle\Helper; use Symfony\Component\Process\Process; class Git { public static function getCurrentBranch($dir) { $cmd = sprintf('cd "%s" && git rev-parse --abbrev-ref HEAD', $dir); $process = new Process($cmd); $process->mustRun(); $result = trim($process->getOutput()); return $result; } public static function getRemoteBranches($dir) { $cmd = sprintf('cd "%s" && git fetch && git branch -r', $dir); $process = new Process($cmd); $process->mustRun(); $output = explode("\n", $process->getOutput()); $output = array_filter($output); $branches = []; foreach ($output as $row) { if (strpos($row, ' -> ') === false) { $branches[] = trim(str_replace('origin/', '', $row)); } } usort($branches, [__CLASS__, 'sortBranches']); return $branches; } public static function sortBranches($a, $b) { if ($a == 'master') { $result = -1; } elseif ($b == 'master') { $result = 1; } else { $result = ($a < $b) ? -1 : 1; } return $result; } } <file_sep>/README.md # BranchingBundle Symfony BranchingBundle. Auto change *mysql* database depends on current git branch. [![SensioLabsInsight](https://insight.sensiolabs.com/projects/e0649e62-91e7-497c-8008-cf7aba6d0ee9/big.png)](https://insight.sensiolabs.com/projects/e0649e62-91e7-497c-8008-cf7aba6d0ee9) Bundle version is connected with supported symfony version. ## Installation Download bundle by composer ``` composer require therat/branching ``` Then, enable the bundle by adding the following line in the app/AppKernel.php file of your project: ```php <?php // app/AppKernel.php // ... class AppKernel extends Kernel { public function registerBundles() { if (in_array($this->getEnvironment(), ['dev', 'test'])) { $bundles[] = new TheRat\BranchingBundle\TheRatBranchingBundle(); // ... } // ... } ``` Create new branch `git branch feature` or `git checkout -b feature`. After that run 'app/console' command, and bundle create and copy new database automatically. > Be sure, that your mysql connect has privileges to create new scheme. > Bundle use default symfony connection params 'database_host' etc. ### Configuration ``` # Default configuration for "BranchingBundle" the_rat_branching: switch_db: false #enable or disable auto switch db copy_db_data: false #copy db from root db ``` ### Nginx example Obviously, you're hosting must support dns name like this `*.test.my.project.com`. There is an example of nginx config for different branches: ``` server { #... if ($branch = "") { set $branch "master"; } server_name ~^(www\.)?(?<branch>.+)\.test\.my\.project\.com$; root /www/test.my.project.com/project/$branch/web; #... ``` ## Twig extensions ### Current branch * Get current branch, useful for generating project title ``` #your twig template file {{ current_branch() }} ``` For master branch return `master (dev)` string. <file_sep>/Helper/Database.php <?php namespace TheRat\BranchingBundle\Helper; use Doctrine\DBAL\DriverManager; use Monolog\Handler\NullHandler; use Psr\Log\LoggerInterface; use Symfony\Bridge\Monolog\Logger; use Symfony\Component\Process\Process; class Database { /** * @var */ protected $tmpConnection; /** * @var string */ protected $rootDir; /** * @var bool */ protected $copyDbData; /** * @var string */ protected $driver; /** * @var string */ protected $host; /** * @var string */ protected $port; /** * @var string */ protected $user; /** * @var string */ protected $password; /** * @var string */ protected $dbName; /** * @var string */ protected $dbNameOriginal; /** * @var LoggerInterface */ protected $logger; /** * @return Logger */ public function getLogger() { if (null === $this->logger) { $this->logger = new Logger(__CLASS__, [new NullHandler()]); } return $this->logger; } /** * @param LoggerInterface|Logger $logger * @return Database */ public function setLogger(LoggerInterface $logger) { $this->logger = $logger; return $this; } /** * @return string */ public function getDriver() { return $this->driver; } /** * @return string */ public function getDbNameOriginal() { return $this->dbNameOriginal; } public function __construct( $rootDir, $copyDbData, $driver, $host, $port, $user, $password, $dbName, $dbNameOriginal ) { $this->rootDir = $rootDir; $this->copyDbData = (bool)$copyDbData; $this->driver = $driver; $this->host = $host; $this->port = $port; $this->user = $user; $this->password = $<PASSWORD>; $this->dbName = $dbName; $this->dbNameOriginal = $dbNameOriginal; } /** * @return string */ public function getRootDir() { return $this->rootDir; } /** * @return boolean */ public function isCopyDbData() { return $this->copyDbData; } /** * @return string */ public function getHost() { return $this->host; } /** * @return string */ public function getPort() { return $this->port; } /** * @return string */ public function getUser() { return $this->user; } /** * @return string */ public function getPassword() { return $this->password; } /** * @return string */ public function getDbName() { return $this->dbName; } public function generateDatabaseName() { $branchRef = Git::getCurrentBranch($this->getRootDir()); $result = $this->getDbName(); $branchName = $this->prepareBranchName($branchRef); if ('master' != $branchName) { $result = $result . '_branch_' . $branchName; } return $result; } public function databaseExists($name) { if (in_array($name, $this->getTmpConnection()->getSchemaManager()->listDatabases())) { return true; } return false; } public function generateDatabase($dstDbName) { if (empty($dstDbName)) { throw new \RuntimeException("Invalid param dstDbName, must be not empty"); } $connection = $this->getTmpConnection(); $connection->getSchemaManager()->createDatabase($dstDbName); if ($this->isCopyDbData()) { $host = $this->getHost(); $port = $this->getPort() ? '-P' . $this->getPort() : ''; $user = $this->getUser(); $password = $this->getPassword() ? '-p' . $this->getPassword() : ''; $srcDbName = $this->getDbName(); $cmd = "mysqldump -h{$host} {$port} -u{$user} $password {$srcDbName}" . " | mysql -h{$host} ${port} -u{$user} {$password} {$dstDbName}"; $this->getLogger()->debug('Shell exec', ['cmd' => $cmd]); $process = new Process( $cmd, null, null, null, 60 * 15 ); $process->mustRun(); } } protected function prepareBranchName($branchName) { $result = str_replace('-', '_', strtolower($branchName)); $pos = strrpos($branchName, '/'); if (false !== $pos) { $result = substr($result, $pos + 1); } return $result; } protected function getTmpConnection() { if (!$this->tmpConnection) { $params = [ 'driver' => $this->getDriver(), 'host' => $this->getHost(), 'port' => $this->getPort(), 'dbname' => $this->getDbNameOriginal(), 'user' => $this->getUser(), 'password' => $<PASSWORD>(), ]; $this->tmpConnection = DriverManager::getConnection($params); } return $this->tmpConnection; } } <file_sep>/DependencyInjection/Compiler/SwitchDbNameCompiler.php <?php namespace TheRat\BranchingBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; class SwitchDbNameCompiler implements CompilerPassInterface { /** * You can modify the container here before it is dumped to PHP code. * * @param ContainerBuilder $container */ public function process(ContainerBuilder $container) { $originalDbName = $container->getParameter('database_name'); $container->setParameter('database_name_original', $originalDbName); if (!$container->getParameter('the_rat_branching.switch_db') || false === strpos($container->getParameter('database_driver'), 'mysql') || false === in_array($container->getParameter('kernel.environment'), ['dev', 'test']) ) { return; } $helper = $container->get('the_rat_branching.helper.database'); $branchDbName = $helper->generateDatabaseName(); if ($originalDbName != $branchDbName) { if (!$helper->databaseExists($branchDbName)) { $helper->generateDatabase($branchDbName); } $container->setParameter('database_name', $branchDbName); $definition = $container->getDefinition('doctrine.dbal.default_connection'); $connectionParams = $definition->getArgument(0); $connectionParams['dbname'] = $branchDbName; $definition->replaceArgument(0, $connectionParams); } } } <file_sep>/Command/GenerateDbCommand.php <?php namespace TheRat\BranchingBundle\Command; use Monolog\Handler\StreamHandler; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class GenerateDbCommand extends ContainerAwareCommand { protected function configure() { $this ->setName('the_rat:branching:generate-db') ->setDescription('Detect current branch and create db') ->addArgument( 'name', InputArgument::OPTIONAL, 'If you want copy db by specific name' ); } protected function execute(InputInterface $input, OutputInterface $output) { /** @var \Symfony\Component\Console\Output\ConsoleOutput $output */ $helper = $this->getContainer()->get('the_rat_branching.helper.database'); $logger = $helper->getLogger(); if ($output->isDebug()) { $logger->pushHandler(new StreamHandler(STDOUT)); } $name = $input->getArgument('name'); if ($name) { $branchDbName = $name; } else { $branchDbName = $helper->generateDatabaseName(); } $logger->debug('Run command', ['command' => $this->getName(), 'db name' => $branchDbName]); if (!$helper->databaseExists($branchDbName)) { $helper->generateDatabase($branchDbName); $logger->debug('Create complete'); } else { $logger->debug('Database already exist'); } } } <file_sep>/Twig/BranchingExtension.php <?php namespace TheRat\BranchingBundle\Twig; use TheRat\BranchingBundle\Helper\Git; class BranchingExtension extends \Twig_Extension { const CURRENT_BRANCH = 'current_branch'; /** * @var string */ protected $path; /** * @var string */ protected $env; public function __construct($kernelRootDir, $env) { $this->path = realpath($kernelRootDir . '/../'); $this->env = $env; } /** * Returns the name of the extension. * * @return string The extension name */ public function getName() { return 'the_rat_branching_extension'; } public function getFunctions() { return [ self::CURRENT_BRANCH => new \Twig_SimpleFunction(self::CURRENT_BRANCH, [$this, 'getCurrentBranch']) ]; } public function getCurrentBranch($prefix = '', $postfix = '') { $result = null; if (in_array($this->env, ['dev', 'test'])) { $result = sprintf('%s%s (%s)%s', $prefix, Git::getCurrentBranch($this->path), $this->env, $postfix); } return $result; } } <file_sep>/Test/Helper/GitTest.php <?php use TheRat\BranchingBundle\Helper\Git; class GitTest extends \PHPUnit_Framework_TestCase { protected $dir; public function setUp() { $this->dir = dirname(dirname(__DIR__)); } public function testGetCurrentBranch() { $actual = Git::getCurrentBranch($this->dir); $this->assertEquals('master', $actual); } public function testGetRemoteBranches() { $actual = Git::getRemoteBranches($this->dir); $this->assertTrue(in_array('master', $actual)); } }
c2bfc0fb24d70a50f27a177826b1d92136fec108
[ "Markdown", "PHP" ]
8
PHP
TheRatG/BranchingBundle
c27390ae1e139624e71fa757a9dbdf44fd44d4cb
353480366fc71cac6effedfbe3b822faf6f1fdbc
refs/heads/master
<file_sep>***Julius / Feb 01, 2018*** # Hi-Lo-Game-Project ## Game Description The premise of the High or Low as you might have guessed already is to guess whether the next card is higher or lower than the last one dealt. That's basically it!. I will do my best to make this game exciting by adding on some dynamics like having lives or limited chances to guess and/or being able to place bets. ## Wireframe ![imagename](./img/GameStart.jpg) ![imagename](./img/Gameplay.jpg) ![imagename](./img/GameFinish.jpg) ## Initial Thoughts Proper planning, time management and execution will be the key to this proect. Project will consist of html, css and Javascript for the programming and the most part so I have to be prepared to put in millions of hours googling syntaxes that I need specially the ones involving math. Debugging and tweaking the code throughout the entire project, until it is fine tuned and works the way that is intended. ## Phases of completion 1. Logic - game start, gameplay and game finish - arrays, objects, functions statements and events 2. Visuals - HTML, CSS, DOM 3. Twaking and debugging 3. Visual Enhancements (if time allows) ## Resources and Tools - Sublime Text Editor - https://www.w3schools.com/ - https://stackoverflow.com/ - https://developer.mozilla.org/en-US/docs/Web/JavaScript ## Post Project Thoughts - feeling both proud and little embarrased - proud because looking back to myself before I started this program I could nt have done this all by myself because I have zero knowledge in programming couple of months ago - embarrased coz i settled for a very simple game.. now that its finished I now know for myself that I could have pushed myself on writing a more intricate program. - if you have a plan and proper time management and execution everything is going to come through - roadblocks will always be there, took advantage of all the resources out there for help and information. - couple of things in my game that I wanted to do but could not really figure out how to. - minor: navbar, flexbox, scoredisplay(i know the code bt could not figure out why it does not dis appear when i want to) - major: wanted to reset display of the cards at a certain point but keeping everything else is really a challenge that still needs figuring out (messes up my styles everytime i try something) - I implemented everything I have learned so far within this class and now have a better understanding on how to apply all ive learned in a program or in the real world - Overall I think I could have done better but I am satisfied with what I have acomplished coz I made the game work the way I actually wanted it to. - rate to myself 4 out of 5 <file_sep>console.log("JS is linked") //////////////////////////////////////////////////////////////////////////// ////////////////////Objects,Arrays and variables(Global)//////////////////// //////////////////////////////////////////////////////////////////////////// //deck of cards //cards in play (one flipped one is not) //streak counter //chips counter //buttons let chips = 100; let cards = []; let cardsInPlay = 0; let myChips = document.getElementById('myChips'); let bet = document.getElementById('bet'); const cardOutput = document.getElementById('cardOutput'); const betOutput = document.getElementById('betOutput'); const betInput = document.getElementById('betInput'); const message = document.getElementById('message'); const start = document.getElementById('start'); const btnstart = document.getElementById('btnstart') const highLow = document.getElementById('highLow'); const maxBet= document.getElementById('maxBet') const suits = ['spades', 'hearts', 'clubs', 'diams']; const numbers = ['2','3','4','5','6','7','8','9','10','J','Q','K','A']; //giphy varibles //const correct = document.getElementById('correct'); //const inCorrect = document.getElementById('inCorrect'); //const gamOver = document.getElementById('gamOver') ///////////////////////////////////////////////////////////////////////////// /////////////////////////////Functions / Statements////////////////////////// ///////////////////////////////////////////////////////////////////////////// //Create Deck/ gameSart / checkwin function gameStart() { cardsInPlay = 0; chips = 100; bet.value = 0; myChips.innerHTML = chips; message.innerHTML = 'Game Started!'; betOutput.style.display = 'block'; betInput.style.display = 'block'; cardOutput.innerHTML = ''; start.style.display = 'none'; highLow.style.display = 'block'; buildCards(); shuffleCards(cards); cardOutput.innerHTML += showCards(); } function hilo(pressedButton){ let oldCard = cards[cardsInPlay].cardValue; cardsInPlay++; cardOutput.innerHTML += showCards(); let newCard = cards[cardsInPlay].cardValue; if(pressedButton === 'high' && oldCard < newCard) { chips += parseInt(bet.value); myChips.innerHTML = chips; message.innerHTML = 'You were Right! :)'; /*correct.style.display = 'block' setTimeout(function () { correct.style.display = 'none' }, 1000)*/ } else if(pressedButton === 'low' && oldCard > newCard) { chips += parseInt(bet.value); myChips.innerHTML = chips; message.innerHTML = 'You were Right! :)'; /*correct.style.display = 'block' *setTimeout(function () { correct.style.display = 'none' }, 1000)*/ } else if(oldCard === newCard) { message.innerHTML = 'Tie!' }else { chips -= parseInt(bet.value); myChips.innerHTML = chips; message.innerHTML = 'You were WRONG!:('; /*inCorrect.style.display = 'block'; setTimeout(function () { inCorrect.style.display = 'none'; }, 2000)*/ if (cardsInPlay === 25) { endPlay(); }if(chips === 0) { message.innerHTML = 'GAME OVER!'; endPLay(); } } } function endPLay() { highLow.style.display = 'none'; message.innerHTML = 'Game over. You have $' + chips; start.style.display = 'block'; btnstart.innerHTML = 'Restart?'; } function shuffleCards(array) { for(let i = array.length -1; i >0 ; i--){ let holder = Math.floor(Math.random()*(i+1)); let temp = array[i]; array[i] = array[holder]; array[holder] = temp; } return array; } function showCards(){ let c = cards[cardsInPlay] let bgColor = (c.icon === "H" || c.icon === "D") ? 'red':'black'; var hpos = (cardsInPlay > 0) ? cardsInPlay * 50 + 40 : 40; return '<div class="icard ' + c.suit + '" style="left:' + hpos + 'px;"> <div class="cardtop suit">' + c.num + '<br></div> <div class="cardmid suit"></div> <div class="cardbottom suit">' + c.num + '<br></div></div>'; } function buildCards() { cards = []; for(s in suits){ let suit = suits[s][0].toUpperCase(); for(n in numbers){ let card = { suit: suits[s], num: numbers[n], cardValue: parseInt(n)+2, icon: suit } cards.push(card); } } } function maximumBet() { bet.value = chips; } function checkBet() { if(this.value > chips) { this.value = chips; message.innerHTML = 'Bet adjusted to $ ' + this.value; } if(this.value < 0) { this.value = 0; message.innerHTML = 'Bet adjusted to $ ' + this.value; } } ////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////Eventlisteners////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// btnstart.addEventListener('click', gameStart); bet.addEventListener('change', checkBet); bet.addEventListener('input', checkBet); bet.addEventListener('blur', checkBet); maxBet.addEventListener('click', maximumBet);
0033d434fb8a3b2a270f953649a72b4a1c2e5619
[ "Markdown", "JavaScript" ]
2
Markdown
juliusregalado/Hi-Lo-Game-Project
78efac188cec04b27a670e3284b294210455cdfa
c63599d1afc4033b459cd94f4eb3de9fe1991d33
refs/heads/master
<file_sep>import os from bottle import Bottle, request, template, route from pathlib import Path from socket import gethostname, gethostbyname ip_all = {} def index_page(): global ip_all device_ip = request.headers.get("X-Forwarded-For","127.0.0.1") if device_ip in ip_all: ip_all[device_ip] +=1 else: ip_all[device_ip] = 1 one =Path("index1frame.html").read_text() two = '' for ip, count in ip_all.items(): two += f'<tr> <th> {ip} </th><th> {count}</th></tr>' html = one.format(two) return html def create_app(): app = Bottle() app.route("/", "GET", index_page) app.route("/index1.html", "GET", index_page) return app application = create_app() application.run(host="0.0.0.0", port=int(os.environ.get("PORT", 8080))) <file_sep># itu-itis19-assignment2 Starter code for ITU BLG101E 2019/20 second assignment https://camlibel18-assignment2.herokuapp.com/ <file_sep>from socket import gethostname, gethostbyname ip = gethostbyname(gethostname()) a = ip f = open('ips.txt','w') f.write(a) f = open('ips.txt','r')
e4b08d574ac608e029bfde2889db40396f822705
[ "Markdown", "Python" ]
3
Python
ituitis-camlibel18/ituitis-camlibel18
00d57221cd72663c61dd83df27e66edad5eec930
6f542a9c27e819444be9898b43abf493342e66ee
refs/heads/master
<repo_name>insomniaccat/neocisChallenge<file_sep>/Part01/widget.cpp #include "widget.h" #include "ui_widget.h" Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); this->setFixedSize(420,500); this->setMouseTracking(true); } Widget::~Widget() { delete ui; } void Widget::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.drawPixmap(0, 0, myPixmap); int gX = 10; int gY = 10; for(int i = 0;i<20;++i){ for(int j = 0;j<20;++j){ QRect gridRect(gX, gY, gW, gH); if(gridColor[i][j] == false){ QPen framepen(Qt::gray); QBrush brush(Qt::gray, Qt::SolidPattern); painter.fillRect(gridRect, brush); painter.setPen(framepen); }else{ QPen framepen(Qt::blue); QBrush brush(Qt::blue, Qt::SolidPattern); painter.fillRect(gridRect, brush); painter.setPen(framepen); } painter.drawRect(gridRect); gY = gY + gap; // qDebug() << gridColor[i][j]; } gX = gX + gap; gY = 10; } } void Widget::resizeEvent(QResizeEvent *event) { auto newRect = myPixmap.rect().united(rect()); if (newRect == myPixmap.rect()) return; QPixmap newPixmap{newRect.size()}; QPainter painter{&newPixmap}; painter.fillRect(newPixmap.rect(), Qt::white); painter.drawPixmap(0, 0, myPixmap); myPixmap = newPixmap; } void Widget::mousePressEvent(QMouseEvent *event) { if(is_user_done == false){ QPainter painter{&myPixmap}; is_mouse_down = true; mousePos = event->pos(); c_x = mousePos.x(); c_y = mousePos.y(); } //update(); } void Widget::mouseMoveEvent(QMouseEvent *event) { if(is_mouse_down==true && is_user_done == false){ QPainter painter{&myPixmap}; painter.setRenderHint(QPainter::Antialiasing); painter.setPen({Qt::blue, 1.0}); mousePos = event->pos(); int tempW = qFabs(mousePos.x() - c_x); int tempH = qFabs(mousePos.y() -c_y); if(tempW > tempH){ w = tempW; h = tempW; }else{ w = tempH; h = tempH; } r = w/2; QRect myRect(c_x-(w/2),c_y-(h/2),w, h); //myRect.moveCenter(QPoint(width()/2,height()/2)); painter.fillRect(myPixmap.rect(), Qt::white); painter.drawEllipse(myRect); update(); } } void Widget::mouseReleaseEvent(QMouseEvent *event) { is_mouse_down = false; is_user_done = true; QPainter painter{&myPixmap}; painter.setRenderHint(QPainter::Antialiasing); QRect myRect(c_x-(w/2),c_y-(h/2),w, h); int helpW = w-0.25; int helpH = h-0.25; QRect helpRect(c_x-(helpW/2),c_y-(helpH/2),helpW, helpH); QPainterPath path; path.addEllipse(myRect); path.addEllipse(helpRect); int gX = 10; int gY = 10; int rmax = 0; int rmin = 200; int rtempmin; int rtempmax; qDebug() << "actual radius: "<<r; for(int i = 0;i<20;++i){ for(int j = 0;j<20;++j){ QRect gridRect(gX, gY, gW, gH); bool result = path.intersects(gridRect); gridColor[i][j] = result; if(result == false){ QPen framepen(Qt::gray); QBrush brush(Qt::gray, Qt::SolidPattern); painter.fillRect(gridRect, brush); painter.setPen(framepen); }else{ QPen framepen(Qt::blue); QBrush brush(Qt::blue, Qt::SolidPattern); painter.fillRect(gridRect, brush); painter.setPen(framepen); if((gX+(gW/2) > c_x) && (gY+(gW/2) > c_y)){ rtempmax =qSqrt(qPow(gX+gW-c_x,2) + qPow(gY+gH-c_y,2)); rtempmin =qSqrt(qPow(gX-c_x,2) + qPow(gY-c_y,2)); }else if((gX+(gW/2) > c_x) && (gY+(gW/2) < c_y)){ rtempmax =qSqrt(qPow(gX+gW-c_x,2) + qPow(gY-c_y,2)); rtempmin =qSqrt(qPow(gX-c_x,2) + qPow(gY+gH-c_y,2)); }else if((gX+(gW/2) < c_x) && (gY+(gW/2) < c_y)){ rtempmax =qSqrt(qPow(gX-c_x,2) + qPow(gY-c_y,2)); rtempmin =qSqrt(qPow(gX-c_x+gW,2) + qPow(gY+gH-c_y,2)); }else if((gX+(gW/2) < c_x) && (gY+(gW/2) > c_y)){ rtempmax =qSqrt(qPow(gX-c_x,2) + qPow(gY+gH-c_y,2)); rtempmin =qSqrt(qPow(gX-c_x+gW,2) + qPow(gY-c_y,2)); }else{ rtempmax =qSqrt(qPow(gX-c_x,2) + qPow(gY-c_y,2)); rtempmin =qSqrt(qPow(gX-c_x+gW,2) + qPow(gY-c_y,2)); } //qDebug() << "rtempmax values: "<<rtempmax; if (rtempmax >rmax){ rmax = rtempmax; } if (rtempmin <rmin){ rmin = rtempmin; } } painter.drawRect(gridRect); gY = gY + gap; //qDebug() << gridColor[i][j]; } gX = gX + gap; gY = 10; } painter.setPen({Qt::blue, 1.0}); painter.fillRect(myPixmap.rect(), Qt::white); // QBrush fillbrush; // fillbrush.setColor(Qt::green); // fillbrush.setStyle(Qt::SolidPattern); //painter.fillPath(path,fillbrush); painter.drawEllipse(myRect); painter.setPen({Qt::red, 1.2}); int maxW = 2*rmax; int maxH = 2*rmax; QRect maxRect(c_x-(maxW/2),c_y-(maxH/2),maxW, maxH); painter.drawEllipse(maxRect); painter.setPen({Qt::red, 1.2}); int minW = 2*rmin; int minH = 2*rmin; QRect minRect(c_x-(minW/2),c_y-(minH/2),minW, minH); painter.drawEllipse(minRect); update(); } <file_sep>/Part02/readme.md Part 2 of the neocis programming challenge. User toggles grid points and we find the circle that best fits selected points. <file_sep>/Part01/widget.h #ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QDebug> #include <QtGui> #include <QtCore> #include <QGraphicsScene> #include <QApplication> #include <QTimer> #include <QMouseEvent> #include <QPainter> #include <QPixmap> #include <QRubberBand> #include <QtMath> namespace Ui { class Widget; } class Widget : public QWidget { Q_OBJECT public: explicit Widget(QWidget *parent = 0); ~Widget(); private: Ui::Widget *ui; protected: virtual void paintEvent(QPaintEvent *event)Q_DECL_OVERRIDE; virtual void resizeEvent(QResizeEvent *event)Q_DECL_OVERRIDE; virtual void mousePressEvent(QMouseEvent *event)Q_DECL_OVERRIDE; virtual void mouseMoveEvent(QMouseEvent *event)Q_DECL_OVERRIDE; virtual void mouseReleaseEvent(QMouseEvent *event)Q_DECL_OVERRIDE; bool is_mouse_down = false; //flag bool is_user_done = false;// flag bool gridColor[20][20] = { {false} }; //0 for gray, 1 for blue QPoint mousePos; //(x, y) for mouse position QPixmap myPixmap; int c_x, c_y, r; //coordinates for circle's center and radius int w, h; //circle QRect object's int gW = 10; int gH = 10; //grid rect width and height int gap = 20; //gap between grid rects }; #endif // WIDGET_H <file_sep>/README.md # neocisChallenge <file_sep>/Part02/widget.cpp #include "widget.h" #include "ui_widget.h" Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); this->setFixedSize(420,500); this->setMouseTracking(true); } Widget::~Widget() { delete ui; } void Widget::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.drawPixmap(0, 0, myPixmap); int gX = 10; int gY = 10; for(int i = 0;i<20;++i){ for(int j = 0;j<20;++j){ QRect gridRect(gX, gY, gW, gH); if(gridColor[i][j] == false){ QPen framepen(Qt::gray); QBrush brush(Qt::gray, Qt::SolidPattern); painter.fillRect(gridRect, brush); painter.setPen(framepen); }else{ QPen framepen(Qt::blue); QBrush brush(Qt::blue, Qt::SolidPattern); painter.fillRect(gridRect, brush); painter.setPen(framepen); } painter.drawRect(gridRect); gY = gY + gap; // qDebug() << gridColor[i][j]; } gX = gX + gap; gY = 10; } } void Widget::resizeEvent(QResizeEvent *event) { auto newRect = myPixmap.rect().united(rect()); if (newRect == myPixmap.rect()) return; QPixmap newPixmap{newRect.size()}; QPainter painter{&newPixmap}; painter.fillRect(newPixmap.rect(), Qt::white); painter.drawPixmap(0, 0, myPixmap); myPixmap = newPixmap; } void Widget::mousePressEvent(QMouseEvent *event) { if(is_user_done == false){ QPainter painter{&myPixmap}; is_mouse_down = true; mousePos = event->pos(); c_x = mousePos.x(); c_y = mousePos.y(); } } void Widget::mouseReleaseEvent(QMouseEvent *event) { if(is_user_done == false){ QPainter painter{&myPixmap}; painter.setRenderHint(QPainter::Antialiasing); int gX = 10; int gY = 10; for(int i = 0;i<20;++i){ for(int j = 0;j<20;++j){ QRect gridRect(gX, gY, gW, gH); QPen framepen; QBrush brush; (Qt::gray, Qt::SolidPattern); bool result = gridRect.contains(c_x, c_y); if(result == true){ gridColor[i][j] = !gridColor[i][j]; } bool myColor = gridColor[i][j]; if(myColor == false){ framepen.setColor("gray"); brush.setColor("gray"); }else{ framepen.setColor("blue"); brush.setColor("blue"); } brush.setStyle(Qt::SolidPattern); painter.fillRect(gridRect, brush); painter.setPen(framepen); painter.drawRect(gridRect); gY = gY + gap; //qDebug() << gridColor[i][j]; } gX = gX + gap; gY = 10; } painter.fillRect(myPixmap.rect(), Qt::white); } update(); } bool Widget::solveLeastSquaresCircleKasa(const std::vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d> > &points, Eigen::Vector2d &midpoint, double &radius) { /* Code from https://github.com/DLuensch/Least-Squares-Circle-Fitting-Kasa-Method-.git was used. * --------------------------------------------------------------------------- * Revision : 1.0 * Modul : Least Square Circle Kasa C++ * Creation : 10.01.2015 * Recent changes : 10.01.2015 * ---------------------------------------------------------------------------- * LOG: * ---------------------------------------------------------------------------- * Author : <NAME> * Contact : <EMAIL> * ---------------------------------------------------------------------------- * Tabsize : 4 * Charset : Windows * ------------------------------------------------------------------------- */ int length = points.size(); double x1; double x2; double x3; Eigen::MatrixXd AFill(3, length); Eigen::MatrixXd A(length, 3); Eigen::VectorXd AFirst(length); Eigen::VectorXd ASec(length); Eigen::VectorXd AFirstSquared(length); Eigen::VectorXd ASecSquared(length); Eigen::VectorXd ASquaredRes(length); Eigen::VectorXd b(length); Eigen::VectorXd c(3); bool ok = true; if (length > 1) { for (int i = 0; i < length; i++) { AFill(0, i) = points[i](0); AFill(1, i) = points[i](1); AFill(2, i) = 1; } A = AFill.transpose(); for (int i = 0; i < length; i++) { AFirst(i) = A(i, 0); ASec(i) = A(i, 1); } for (int i = 0; i < length; i++) { AFirstSquared(i) = AFirst(i) * AFirst(i); ASecSquared(i) = ASec(i) * ASec(i); } b = AFirstSquared + ASecSquared; c = A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b); x1 = c(0); midpoint(0) = x1 * 0.5; x2 = c(1); midpoint(1) = x2 * 0.5; x3 = c(2); radius = sqrt((x1 * x1 + x2 * x2) / 4 + x3); } else { ok = false; } return ok; } void Widget::on_pushButton_clicked() { //if (is_user_done = false){ QPainter painter{&myPixmap}; painter.setRenderHint(QPainter::Antialiasing); Eigen::MatrixXf XY; XY.resize(1,2); std::vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d> > samplePoints; Eigen::Vector2d midpoint; //midpoint = XY.rowwise().mean(); double radius; bool ok; is_user_done = true; int gX = 10; int gY = 10; for(int i = 0;i<20;++i){ for(int j = 0;j<20;++j){ if(gridColor[i][j] == true){ samplePoints.push_back(Eigen::Vector2d((double)(gX + (gW/2)), (double) (gY + (gH/2)))); } gY = gY + gap; } gX = gX + gap; gY = 10; } ok = solveLeastSquaresCircleKasa(samplePoints, midpoint, radius); if (ok) { //cout << "x: " << midpoint(0) << " | y: " << midpoint(1) << " | radius: " << radius << std::endl; QRect myRect(midpoint(0)-radius,midpoint(1)-radius,radius*2, radius*2); painter.setPen({Qt::red, 1.2}); painter.fillRect(myPixmap.rect(), Qt::white); painter.drawEllipse(myRect); update(); }else{ qDebug() << "Error - Unable to create circle of best fit"; } // } } <file_sep>/Part02/widget.h #ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QDebug> #include <QtGui> #include <QtCore> #include <QGraphicsScene> #include <QApplication> #include <QTimer> #include <QMouseEvent> #include <QPainter> #include <QPixmap> #include <QRubberBand> #include <QtMath> #include <Eigen> #include <cmath> #include <iostream> namespace Ui { class Widget; } class Widget : public QWidget { Q_OBJECT public: explicit Widget(QWidget *parent = 0); ~Widget(); private: Ui::Widget *ui; protected: virtual void paintEvent(QPaintEvent *event)Q_DECL_OVERRIDE; virtual void resizeEvent(QResizeEvent *event)Q_DECL_OVERRIDE; virtual void mousePressEvent(QMouseEvent *event)Q_DECL_OVERRIDE; //virtual void mouseMoveEvent(QMouseEvent *event)Q_DECL_OVERRIDE; virtual void mouseReleaseEvent(QMouseEvent *event)Q_DECL_OVERRIDE; virtual bool solveLeastSquaresCircleKasa(const std::vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d> > &points, Eigen::Vector2d &midpoint, double &radius); bool is_mouse_down = false; bool is_user_done = false; bool gridColor[20][20] = { {false} }; QPoint mousePos; QPixmap myPixmap; int c_x; int c_y; //int w; //int h; int gW = 10; int gH = 10; //int r; int gap = 20; int N = 0; private slots: void on_pushButton_clicked(); }; #endif // WIDGET_H <file_sep>/Part01/readme.md Project Files for Part 01. User draws a circle on grid and we find the point of intersection between the circle and the grid points.
88285469eec9adf27d595592af8a19aca9088498
[ "Markdown", "C++" ]
7
C++
insomniaccat/neocisChallenge
6b2084fb5fb1b9047c2836b320bff464b4ada4aa
e6f70fbbca0d92ed6cee551cfdd03b75a6eea429
refs/heads/master
<repo_name>hyperfabrics/hyperfabrics-web<file_sep>/store/index.js import Vuex from 'vuex' import Cookie from 'js-cookie' const createStore = () => { return new Vuex.Store({ state: { cacheVersion: '', settings: { header: [], footer: [] }, form: { email: '', name: '', products: null, checked: [] }, formSubmitSuccess: false, token: null }, mutations: { SET_SETTINGS (state, settings) { state.settings = settings // console.log(state.settings.header) }, SET_CACHE_VERSION (state, version) { state.cacheVersion = version }, // New FORM_SUBMIT (state) { state.formSubmitSuccess = true }, SET_TOKEN (state, token) { state.token = token }, CLEAR_TOKEN (state) { state.token = null } }, actions: { nuxtServerInit ({ commit }, context) { return this.$storyapi.get(`cdn/stories/blocks/global`, { version: context.version }).then((res) => { commit('SET_SETTINGS', res.data.story.content) }) }, loadCacheVersion ({ commit }) { return this.$storyapi.get(`cdn/spaces/me`).then((res) => { commit('SET_CACHE_VERSION', res.data.space.version) }) }, formSubmit (vuexContext, form) { return this.$axios .$post( 'https://hyperfabrics-marketing.firebaseio.com/contact-us.json', form) .then(result => { // console.log(form) vuexContext.commit('FORM_SUBMIT') this.$router.push('/form-submit') }) .catch(e => console.log(e)) }, authenticateUser (vuexContext, authData) { console.log('process.env.fbAPIKey', process.env.fbAPIKey) let authUrl = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=' + process.env.fbAPIKey if (!authData.isLogin) { authUrl = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=' + process.env.fbAPIKey } // console.log('authData', authData) // console.log('fbAPIKey', process.env.fbAPIKey) // console.log('authUrl', authUrl) return this.$axios .$post(authUrl, { email: authData.email, password: <PASSWORD>, returnSecureToken: true }) .then(result => { vuexContext.commit('SET_TOKEN', result.idToken) window.localStorage.setItem('token', result.idToken) // console.log(window.localStorage) window.localStorage.setItem( 'tokenExpiration', new Date().getTime() + Number.parseInt(result.expiresIn) * 1000 ) Cookie.set('jwt', result.idToken) Cookie.set( 'expirationDate', new Date().getTime() + Number.parseInt(result.expiresIn) * 1000 ) return this.$axios.$post('http://hyperfabrics.com/api/track-data', { data: 'Authenticated!' }) }) .catch(e => console.log(e)) }, initAuth (vuexContext, req) { let token let expirationDate if (req) { if (!req.headers.cookie) { return } const jwtCookie = req.headers.cookie .split(';') .find(c => c.trim().startsWith('jwt=')) if (!jwtCookie) { return } token = jwtCookie.split('=')[1] expirationDate = req.headers.cookie .split(';') .find(c => c.trim().startsWith('expirationDate=')) .split('=')[1] } else if (process.client) { token = window.localStorage.getItem('token') expirationDate = window.localStorage.getItem('tokenExpiration') } if (new Date().getTime() > +expirationDate || !token) { console.log('No token or invalid token') vuexContext.dispatch('logout') return } vuexContext.commit('SET_TOKEN', token) }, logout (vuexContext) { vuexContext.commit('CLEAR_TOKEN') Cookie.remove('jwt') Cookie.remove('expirationDate') if (process.client) { window.localStorage.removeItem('token') window.localStorage.removeItem('tokenExpiration') } } }, getters: { isAuthenticated (state) { return state.token != null } } }) } export default createStore <file_sep>/helpers/mixpanel.js export const setUser = function ($email, hasWeb3, lastUpdated, userEntryRoute) { let user = { $email, hasWeb3, lastUpdated, userEntryRoute } return user } export const trackContact = function (sourceComponent, sourcePageLocation, sourcePath) { let name = 'Contact' let data = { sourceComponent, sourcePageLocation, sourcePath } const action = { name, data } return action } export const trackFooterLogoDownload = function (sourcePath) { let name = 'Footer - Logo Download' let data = { sourcePath } const action = { name, data } return action } export const trackFooterSubmit = function (sourcePath) { let name = 'Footer - Submit' let data = { sourcePath } const action = { name, data } return action } export const trackHomeHeroCta = function (targetCta) { let name = 'Home Hero CTA' let data = { targetCta } const action = { name, data } return action } export const trackMenu = function (sourcePath, targetMenuItem) { let name = 'Menu' let data = { sourcePath, targetMenuItem } const action = { name, data } return action } export const trackMetamaskCta = function (sourceComponent, sourcePath) { let name = 'Metamask CTA' let data = { sourceComponent, sourcePath } const action = { name, data } return action } export const trackNewsletterSubscribe = function (email, sourceComponent, sourcePath) { let name = 'Newsletter - Subscribe' let data = { email, sourceComponent, sourcePath } const action = { name, data } return action } export const trackPageAbout = function (sourceComponent, sourcePageLocation, sourcePath) { let name = 'About page' let data = { sourceComponent, sourcePageLocation, sourcePath } const action = { name, data } return action } export const trackPageTerms = function (sourceComponent, sourcePageLocation, sourcePath) { let name = 'Terms page' let data = { sourceComponent, sourcePageLocation, sourcePath } const action = { name, data } return action } export const trackPublicListView = function (listUrl, sourcePath) { let name = 'Public List - View' let data = { listUrl, sourcePath } const action = { name, data } return action } export const trackPublicListCreate = function (listUrl, slug) { let name = 'Public List - Create' let data = { listUrl, slug } const action = { name, data } return action } export const trackScatterCta = function (sourceComponent, sourcePath) { let name = 'Scatter CTA' let data = { sourceComponent, sourcePath } const action = { name, data } return action } export const trackSearchSuggestion = function (sourcePath, suggestion) { let name = 'Search - Suggestion' let data = { sourcePath, suggestion } const action = { name, data } return action } export const trackSocial = function (sourceComponent, sourcePageLocation, sourcePath, targetPlatform) { let name = 'Social' let data = { sourceComponent, sourcePageLocation, sourcePath, targetPlatform } const action = { name, data } return action }
f88a68366545805298ee90b0aef287847f5b2e98
[ "JavaScript" ]
2
JavaScript
hyperfabrics/hyperfabrics-web
faabeede08d19369aed1e37cda8aff4806073f3d
2c596036c66995a1fa3cdff95d0575272521d900
refs/heads/main
<repo_name>irvanswan/DinamycPrograming<file_sep>/JadwalKuliah.js const Dynamic = require('./Dynamic'); class JadwalKuliah extends Dynamic{ getChange(n = 0) { console.log(this.data) if(this.cache[n] !== undefined) { return this.cache[n]; } let data = this.data let result = []; let maxSchedule = 0; for(let i = 0; i < data.length; i++) { let start = data[i].start; if(start >= n) { console.log('Menyesuaikan jadwal: ', data[i]); let temp_result = data[i]; // [20]; let resultLain = this.getChange(data[i].end); // [?, ?, ?}] let merged=[] if(resultLain === undefined){ merged = [temp_result] }else{ merged = [temp_result, ...resultLain] } result[i] = merged; if(result[maxSchedule] === undefined) { maxSchedule = i; } else if(result[maxSchedule].length < merged.length) { maxSchedule = i; } } } this.cache[n] = result[maxSchedule]; return result[maxSchedule]; } } module.exports = JadwalKuliah;
22f0e6cbb4f60766f55651dda4bfb6efda4785f6
[ "JavaScript" ]
1
JavaScript
irvanswan/DinamycPrograming
ae2f7c86063a4947f4451782d3102cfa8af4660d
11721c381692573e42b7fc94215fa6397c8ab83c
refs/heads/master
<repo_name>Ironteen/mypro<file_sep>/MLP.py import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/",one_hot = True) in_units = 784 h1_units = 300 with tf.name_scope("input"): x = tf.placeholder(tf.float32,[None,in_units]) y_= tf.placeholder(tf.float32,[None,10]) keep_prob = tf.placeholder(tf.float32) with tf.name_scope("hidden_layer1"): with tf.name_scope("w1"): w1 = tf.Variable(tf.random_normal([in_units,h1_units],stddev = 0.1)) tf.summary.histogram('Weight1',w1) with tf.name_scope("b1"): b1 = tf.Variable(tf.zeros([h1_units])) + 0.01 tf.summary.histogram('biases1',b1) with tf.name_scope("w1_b1"): hidden1 = tf.nn.relu(tf.matmul(x,w1) + b1) tf.summary.histogram('output1',hidden1) with tf.name_scope("hidden_layer2"): with tf.name_scope("w2"): w2 = tf.Variable(tf.random_normal([h1_units,10],stddev = 0.1)) tf.summary.histogram('Weight2',w2) with tf.name_scope("b2"): b2 = tf.Variable(tf.zeros([10])) tf.summary.histogram('biases2',b2) with tf.name_scope("w2_b2"): hidden1_drop = tf.nn.dropout(hidden1,keep_prob) with tf.name_scope("output"): y = tf.nn.softmax(tf.matmul(hidden1_drop,w2)+b2) tf.summary.histogram('output',y) with tf.name_scope("loss"): cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices = [1])) tf.summary.scalar('cross_entropy', cross_entropy) with tf.name_scope("train"): train_step = tf.train.AdagradOptimizer(0.3).minimize(cross_entropy) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) merge = tf.summary.merge_all() writer = tf.summary.FileWriter("F:\Code\Python Code\TensorFlow\My Tensorflow\log",sess.graph) for i in range(3000): batch_xs,batch_ys = mnist.train.next_batch(100) sess.run(train_step,feed_dict = {x:batch_xs,y_:batch_ys,keep_prob:0.75}) result = sess.run(merge,feed_dict = {x:batch_xs,y_:batch_ys,keep_prob:1}) writer.add_summary(result,i) if i == 2999: correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) print(sess.run(accuracy,feed_dict = {x:mnist.test.images,y_:mnist.test.labels,keep_prob:1})),<file_sep>/DenseNet.py import tensorflow as tf from BN import * # 载入数据为mnist的DenseNet from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/",one_hot = True) deep = 40 block_deep = (deep-4)/3 growthRate =12 in_units = 784 train_steps = 1000 batch_size =128; x = tf.placeholder(tf.float32,[None,in_units],name = "x_input") y_= tf.placeholder(tf.float32,[None,10],name = "y_input") keep_prob = tf.placeholder(tf.float32) input_data = tf.reshape(x,[-1,32,32,1]) def conv(layer_name,input_x,Filter_size,activation_function = None): with tf.name_scope("conv_%s" % layer_name): with tf.name_scope("Filter"): Filter = tf.Variable(tf.random_normal(Filter_size,stddev = 0.1),dtype = tf.float32,name = "Filter") tf.summary.histogram('Filter_%s'%layer_name,Filter) with tf.name_scope("bias_filter"): bias_filter = tf.Variable(tf.random_normal([Filter_size[3]],stddev = 0.1),dtype = tf.float32,name = "bias_filter") tf.summary.histogram('bias_filter_%s'%layer_name,bias_filter) with tf.name_scope("conv"): conv = tf.nn.conv2d(input_x,Filter,strides = [1,1,1,1],padding = "SAME") tf.summary.histogram('conv_%s'%layer_name,conv) temp_y = tf.add(conv,bias_filter) with tf.name_scope("output_y"): if activation_function is None: output_y = temp_y else: output_y = activation_function(temp_y) tf.summary.histogram('output_y_%s'%layer_name,output_y) return output_y def max_pool(layer_name,input_x,pool_size): with tf.name_scope("max_pool_%s" % layer_name): with tf.name_scope("output_y"): output_y = tf.nn.max_pool(input_x,pool_size,strides = [1,2,2,1],padding = "SAME") tf.summary.histogram('output_y_%s'%layer_name,output_y) return output_y def full_connect(layer_name,input_x,output_num,activation_function = None): with tf.name_scope("full_connect_%s" % layer_name): with tf.name_scope("Weights"): Weights = tf.Variable(tf.random_normal([input_x.shape.as_list()[1],output_num],stddev = 0.1),dtype = tf.float32,name = "weight") tf.summary.histogram('Weights_%s'%layer_name,Weights) with tf.name_scope("biases"): biases = tf.Variable(tf.random_normal([output_num],stddev = 0.1),dtype = tf.float32,name = "biases") tf.summary.histogram('biases_%s'%layer_name,biases) output_temp = tf.add(tf.matmul(input_x,Weights) , biases) with tf.name_scope("output_y"): if activation_function is None: output_y = output_temp else: output_y = activation_function(output_temp) tf.summary.histogram('output_y_%s'%layer_name,output_y) return output_y # 定义一个Block模块 def block(name,input_d): # 载入Batch_Norma函数 comprass_num = int(block_deep/2) with tf.name_scope(name): for i in range(comprass_num): output = batch_norm(input_d) print("1.此处BN尼玛能用了") output = tf.nn.relu(output) output = conv("1x1conv_%d"%i,output,[1,1,input_d.shape.as_list()[3],48],activation_function = None) output = conv("3x3conv_%d"%i,output,[3,3,48,12],activation_function = None) input_d = tf.concat([input_d,output],3) output_d = input_d return output_d # 定义一个transition模块 def transition(name,input_d): with tf.name_scope(name): output = batch_norm(input_d) print("2.此处BN尼玛能用了") output = tf.nn.relu(output) output = conv("conv",output,[1,1,input_d.shape.as_list()[3],48],activation_function = None) output = tf.nn.avg_pool(value = output,ksize =2,strides =[1,1,2,2],padding = "SAME") return output # 输入先经过一个Conv层 output_1 = conv("layer1",input_data,[3,3,1,24],activation_function = None) # 然后经过Block1-transition1-Block2-transition2-Block3 output_2 = block("block1",output_1) output_3 = transition("transition1",output_2) output_4 = block("block2",output_3) output_5 = transition("transition2",output_4) output_6 = block("block3",output_5) # global_avg_pool output_7 = tf.nn.avg_pool(value = output_7,ksize =output_6.shape[3] ,strides =[1,1,1,1] ,padding = "SAME") # 输出全连接层 with tf.name_scope("output_y"): y = full_connect("output",output_7,10,activation_function = tf.nn.softmax) with tf.name_scope("loss"): loss = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]),name='cross_entropy') tf.summary.scalar("loss",loss) with tf.name_scope("train"): train = tf.train.AdagradOptimizer(1e-4).minimize(loss) prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1)) with tf.name_scope("accuracy"): accuracy = tf.reduce_mean(tf.cast(prediction,tf.float32),name = 'accuracy') init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) merge = tf.summary.merge_all() writer = tf.summary.FileWriter('log/',sess.graph) for i in range(train_steps): batch = mnist.train.next_batch(batch_size) sess.run(train,feed_dict = {x:batch[0],y_:batch[1],keep_prob : 0.7}) if i%100 ==0: accuracy_batch = sess.run(accuracy,feed_dict = {x:batch[0],y_:batch[1],keep_prob : 0.7}) loss_batch = sess.run(loss,feed_dict = {x:batch[0],y_:batch[1],keep_prob : 0.7}) print('after %d train steps the loss on the batch data is %g and the accuracy on batch data is %g'%(i,loss_batch,accuracy_batch)) result = sess.run(merge,feed_dict={x:batch[0],y_:batch[1],keep_prob : 0.7}) writer.add_summary(result,i) if i == train_steps-1: print(sess.run(accuracy,feed_dict = {x:mnist.test.images,y_:mnist.test.labels,keep_prob:1})),
b3498b3f14cca759bb3fdde72062c9368b67f660
[ "Python" ]
2
Python
Ironteen/mypro
0a45e4f394598e72d7ae6bc231c268619d5dd684
17b2d9e5e40d301ff3e4bc152c8e64e365847a4e
refs/heads/master
<file_sep>import java.awt.*; import java.applet.*; import javax.swing.*; /*Welcome to MineSweeper! *You need to click on a tile in 5 seconds *Find all the mines before you step on a mine to win the game! */ public class MSV4 extends Applet implements Runnable { //Needed for multi-threading and animations that use Thread.sleep. Thread myThread=null; //Different fonts. Font basic = new Font("SansSerif", Font.BOLD, 25); Font title = new Font("Century", Font.BOLD, 30); Font description = new Font("Courier", Font.BOLD, 20); Font mineFont = new Font("Courier", Font.BOLD, 60); //Creation of 2D array for the minefield. int[][] mines = new int[10][10]; //Declaring various variables. Image offScreen; Graphics offG; Image background, headerBackground, startMenu, startButton, restartButton, mine, mine2, mine3, mine4, victory, gameOverPic, timeUp; AudioClip backgroundMusic, explosion, victorySound, gameOver, startMenuMusic, tileClick, standingOvation; int numMines; //Number of mines. int x1, y1, buttonWidth, buttonHeight; //These are for the start button. int count; //This count is used for counting the number of tiles flipped so that player can win the game. int timer; //This is the timer. int i; //Used for modulus delaying. int game; //For differentiating the screens. int adjMines; //This is for counting number of adjacent mines around a tile. boolean once; //Making sure the start menu runs only once. boolean once2; //Similar function. String input; //Input for the number of mines. public void init() { //Using fakescreen. offScreen = createImage(700,800); offG = offScreen.getGraphics(); //Getting pictures & music background = getImage(getCodeBase(), "rsz_gold.jpg"); headerBackground = getImage(getCodeBase(), "headerBackground.jpg"); startMenu = getImage(getCodeBase(), "startMenu.jpg"); startButton = getImage(getCodeBase(), "startButton.gif"); restartButton = getImage(getCodeBase(), "restart.png"); mine = getImage(getCodeBase(), "mineicon.png"); mine2 = getImage(getCodeBase(), "mine2.png"); mine3 = getImage(getCodeBase(), "mine3.png"); mine4 = getImage(getCodeBase(), "mine4.png"); victory = getImage(getCodeBase(), "victory.jpg"); gameOverPic = getImage(getCodeBase(), "gameOver.jpg"); timeUp = getImage(getCodeBase(), "timeUp.jpg"); backgroundMusic = getAudioClip(getCodeBase(), "backgroundMusic.wav"); explosion = getAudioClip(getCodeBase(), "explosion.wav"); victorySound = getAudioClip(getCodeBase(), "victory.wav"); gameOver = getAudioClip(getCodeBase(), "gameOver.wav"); startMenuMusic = getAudioClip(getCodeBase(), "startMenuMusic.wav"); tileClick = getAudioClip(getCodeBase(), "tileClick.wav"); standingOvation = getAudioClip(getCodeBase(), "standingOvation.wav"); //Tracking pictures. MediaTracker tracker = new MediaTracker(this); tracker.addImage(background, 0); tracker.addImage(headerBackground, 0); tracker.addImage(startMenu, 0); tracker.addImage(startButton, 0); tracker.addImage(restartButton, 0); tracker.addImage(mine, 0); tracker.addImage(mine2, 0); tracker.addImage(mine3, 0); tracker.addImage(mine4, 0); tracker.addImage(victory, 0); tracker.addImage(gameOverPic, 0); tracker.addImage(timeUp, 0); while(tracker.checkAll(true) != true){} if (tracker.isErrorAny()){ JOptionPane.showMessageDialog(null, "Trouble loading pictures."); } //Set cursor to a pickaxe cursor. setCursor(Toolkit.getDefaultToolkit().createCustomCursor(new ImageIcon("mineCursor.png").getImage(),new Point(0,0), "custom cursor")); //Initializations for the variables. x1 = 0; y1 = 0; buttonWidth = startButton.getWidth(this); buttonHeight = startButton.getHeight(this); timer = 5; i = 0; game = 0; adjMines = 0; once = true; once2 = true; } //Called by the web browser before the init method and is used to start a multi-threaded applet. public void start() { if (myThread==null) { myThread = new Thread(this); myThread.start(); } } //Needed in multi-threaded Applets to stop the animation thread. public void stop() { if (myThread != null) { myThread = null; } } /*Needed to prevent computer from automatically clearing the entire screen everytime the paint method is called. *This prevents the screen from flashing.*/ public void update(Graphics g) { paint(g); } //Copy the fake screen to the real screen. public void paint(Graphics g) { g.drawImage(offScreen,0,0,this); } //This is where the game runs. public void run() { while(true) { //This while loop runs until timer becomes 0. while (timer>=0) { if (game == 0 && once) { drawStartMenu(); startMenuMusic.play(); once = false; //This ensures that the start menu only gets drawn once. Without this, the screen flashes. } delay(1); //This part draws the timer on top of the minefield. A combination of modulus and delay counts five seconds. if(game == 1) { i++; if (i % 20 == 0) { offG.setFont(basic); offG.drawImage(headerBackground, 0, 0, this); offG.setColor(Color.black); offG.drawString("Speedy MineSweeper!!!", 200, 35); offG.drawString("# of Safe Tiles Left: "+(100-numMines-count), 60, 70); //Shows the number of safe tiles left to flip. offG.drawString("/", 348, 70); offG.drawString("Remaining Time: "+timer, 385, 70); //Shows the remaining time. timer--; repaint(); } delay(50); } } //In this case, the player has lost the game because the timer has gone below zero. gameLost(0); } } //This is for interaction with the mouse. public boolean mouseDown(Event evt, int x, int y) { offG.setFont(mineFont); if(x>200 && x<200+buttonWidth && y>600 && y<600+buttonHeight && game==0) { //When the start button is clicked, user is required to input number of mines. input = JOptionPane.showInputDialog("Enter the number of mines you want to deploy!"); numMines = Integer.parseInt(input); while(numMines<1 || numMines>99) { input = JOptionPane.showInputDialog("Invalid number of mines. Enter a number between 0 and 100!"); numMines = Integer.parseInt(input); } populateMines(mines,numMines); JOptionPane.showMessageDialog(null, numMines+" mines detected in the field!!!"); game = 1; //Sets the game to main mode. startMenuMusic.stop(); backgroundMusic.loop(); drawMineField(); } else if(game==1) { //Main game starts. if(x>0 && x<700 && y>100 && y<800) { //If the user clicks inside the mine field. //Used mathematical relationships between the tile pixels and 2D array indexes to prevent the creation of innumerous if statements. if(mines[x/70][(y-100)/70]==-1) { offG.drawImage(mine,(x/70)*70, (100+((y-100)/70)*70), this); repaint(); explosion.play(); gameLost(1); //Loses if steps on a mine. } else if(mines[x/70][(y-100)/70]==0) { adjMines = adjacentMines(mines, x/70, (y-100)/70); //Gets the adjacent number of mines around the tile flipped. offG.drawString(""+adjMines, (x/70)*70+17, 100+((y-100)/70+1)*70-14); repaint(); tileClick.play(); mines[x/70][(y-100)/70] = 1; //Changes the array indexes of flipped tiles from 0 to 1 so that it can be counted for checking the number of remaining tiles left. timer=5; //Resets the time to 5 seconds. } } } else if(game==2) { //Restarts the game. if(x>200 && x<200+buttonWidth && y>600 && y<600+buttonHeight) { //Restarts if the restart button is clicked. game = 0; once = true; once2 = true; timer = 5; i = 0; clearMines(); standingOvation.stop(); } } if(tilesFlipped()==100-numMines) { gameWon(); //Wins if all the safe tiles are fipped. } return true; } //Delays the screen. public void delay(int milliSecs) { try { myThread.sleep(milliSecs); } catch(Exception e) {} } //This method populates the empty 2D arrays. 0 will be safe tiles, -1 will be mines. public void populateMines( int[][] mines, int n ) { for ( int i=0 ; i<n; i++) { //For loop runs until n so that n number of mines can be created. int row = (int) (mines.length*Math.random()); //Uses the fact that Math.random() produces a value between 0 and 1 and multiplies it by the length, which is 10, to get a random index. int col = (int) (mines[0].length*Math.random()); //Same logic here. if (mines[row][col] == 0) { mines[row][col] = -1; } else { //This condition is to prevent the same index being assigned a mine twice. i--; } } } //This method returns the number of adjacent mines around the tile. public int adjacentMines(int[][]mines, int r, int c) { int adjacentMines=0; for(int i=r-1; i<=r+1; i++) { //These for loops traverse the indexes around a given index to calculate the number of mines around it. for(int j=c-1; j<=c+1; j++) { if (i>=0 && i<10 && j>=0 && j<10) { //This condition is to prevent array index out of bounds error when checking for indexes that are at the edges. if(mines[i][j]==-1) { adjacentMines++; } } } } return adjacentMines; } //Checks the number of safe tiles left to flip. public int tilesFlipped () { count=0; for(int i=0; i<mines.length; i++) { for(int j=0; j<mines[i].length; j++) { if(mines[i][j]==1) { count++; } } } return count; } //This method resets the minefield for game restart public void clearMines() { for(int i=0; i<mines.length; i++) { for(int j=0; j<mines[i].length; j++) { mines[i][j]=0; } } } //This method draws the start menu. public void drawStartMenu() { offG.drawImage(startMenu, 0, 0, this); offG.setColor(Color.black); offG.drawImage(startButton, 197, 600, this); offG.drawImage(mine2, 240, 40, this); offG.drawImage(mine3, 325, 40, this); offG.drawImage(mine4, 400, 40, this); offG.setFont(title); offG.drawString("Welcome to", 262, 300); offG.drawString("Speedy MineSweeper!", 184, 340); offG.setFont(description); offG.drawString("Flip all the safe tiles to win!", 170, 400); offG.drawString("You are given 5 seconds for", 185, 430); offG.drawString("each flip, so think quick!", 194, 460); offG.drawString("You can choose the # of mines!", 170, 490); repaint(); } //This method draws the mine field on the applet public void drawMineField() { offG.drawImage(background, 0, 100, this); offG.drawImage(headerBackground, 0, 0, this); int a=70, b=100, c=70, d=800; for(int i=0; i<10; i++) { offG.drawLine(a,b,c,d); a+=70; c+=70; } int a2=0, b2=100, c2=700, d2=100; for(int i=0; i<10; i++) { offG.drawLine(a2,b2,c2,d2); b2+=70; d2+=70; } repaint(); } //This method is called when user wins the game. public void gameWon() { game = 2; offG.drawImage(victory, 0, 0, this); offG.drawImage(restartButton, 197, 600, this); repaint(); backgroundMusic.stop(); victorySound.play(); delay(100); standingOvation.play(); JOptionPane.showMessageDialog(null, "You have won!!! Noone has ever done that!"); } //This method is called when either the user steps on a mine or the time is up. public void gameLost(int lost) { game = 2; if(once2) { //This is to prevent gameLost from repeating infinitely when it gets called when time is up. backgroundMusic.stop(); offG.drawImage(gameOverPic, 0, 0, this); gameOver.play(); if(lost==0) { //This differentiates between step on a mine and time up. offG.drawImage(timeUp, 197, 300, this); } offG.drawImage(restartButton, 197, 600, this); once2 = false; } repaint(); } }<file_sep># Speedy Minesweeper Applet This applet was made using Java. To run the program, clone the repo, and click the HTML. To see the program demo, click the Youtube link above.
9c95c3f4f32944962867f2817108300e3ba48072
[ "Markdown", "Java" ]
2
Java
realevanlee/speedy-minesweeper
8873c7b9494658c822c796feda6efe7a88c02dd2
32025c4a038e3d6ed60963ca2a8b1c2961b8d581
refs/heads/main
<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; use App\Models\Post; use App\Models\Image; class PostController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // return view('upload'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $validatedData = $request->validate( [ 'images' => 'required', 'images.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048', 'title' => 'required' ] ); if( $request->hasFile('images')){ $files = $request->file('images'); $post = new Post([ 'title' => $request->input('title'), ]); // saving the post but not the images yet auth()->user()->posts()->save($post); // $count = 0; foreach($files as $file){ $timestamp = rand(10990, 1029901); $fileName = $timestamp . $file->getClientOriginalName(); $path = $file->storeAs('post-images', $fileName); $image = new Image([ "name" => $path ]); if($post->images()->save($image)){ // count++; // return redirect()->route('home')->with('success', "Image uploaded successfully."); } else{ return back()->withInput('msg', "There is a problem!"); } } return redirect()->route('home')->with('success', "Image uploaded successfully."); }else{ return back()->withInput('msg', "Please choose any image File"); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep><?php use Illuminate\Support\Facades\Route; use App\Models\Post; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use App\Http\Controllers\PostController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ // Route::get('/', function () { // return view('welcome'); // }); Route::get('/', function(){ $post = Post::where('status', 1) ->orderBy('created_at', 'desc') ->paginate(10); return view('home', ['posts' => $post]); }); Route::get('/home', function(){ $post = Post::where('status', 1) ->orderBy('created_at', 'desc') ->paginate(10); return view('home', ['posts' => $post]); })->name('home'); // Like method Route::post('like', function(Request $request){ $post = Post::find($_POST['post_id']); $post->like = $_POST['like_count']; $post->save(); })->middleware('auth'); // admin auth Route::get('posts/pending', function(){ // $currentTime = Carbon::now(); $post = Post::where('status', 0) //pending posts ->orderBy('created_at', 'desc') ->paginate(10); return view('approve_reject_post', ['posts' => $post,]); })->name('pending_posts')->middleware('admin'); Route::post('post/rejected', function(){ // delete the post permanetly $post = Post::find($_POST['post_id']); $post->images()->delete(); $post->delete(); })->middleware('admin'); Route::post('post/approved', function(){ //change the state of the post $post = Post::find($_POST['post_id']); $post->status = 1; $post->save(); })->middleware('admin'); // auth Route::get('create/post', function(){ })->name('create_post'); Route::resource('posts', PostController::class)->only([ 'create', 'store' ]); Auth::routes(); // Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home'); // Get my posts Route::get('myposts', function(){ $posts = Post::where('user_id', Auth::id()) ->orderBy('created_at', 'desc') ->paginate(10); return view('mypost', ['posts' => $posts]); })->name('my_posts')->middleware('auth');<file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Image extends Model { use HasFactory; protected $fillable = [ 'name', 'post_id' ]; public function post(){ return $this->belongsTo('App\Models\Post'); } public function user(){ $post = Post::find($this->post_id); return User::find($post->user_id); } }
9346ffda8e1c4c893aec1cc6a13001b1132c3239
[ "PHP" ]
3
PHP
rabbi54/Image-Stock
417db14f57a2b0e28c80909e250e9ce23ed604e0
f997930b9a03abcc535459c8da06d185c09f5fcd
refs/heads/master
<repo_name>saternius/Arbitrio<file_sep>/Arbit/Runnable/src/BoxLink.java import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; public class BoxLink { Scene _root; Image pane = Images.boxLink; Fonts font = new Fonts(); String text ="0"; int x; int y; Rectangle close; Rectangle confirm; public BoxLink(Scene scene) { _root = scene; x=(_root.stageWidth/2)-95; y=(_root.stageHeight/2)-45; confirm = new Rectangle(x+111,y+9,25,25); close = new Rectangle(x+142,y+9,25,25); } public void draw(Graphics stage){ stage.drawImage(pane,x,y,null); Fonts.setSize(25); stage.setFont(Fonts.regFont); stage.drawString(text, x+20, y+63); //stage.fillRect(close.x,close.y,close.width,close.height); //stage.fillRect(confirm.x,confirm.y,confirm.width,confirm.height); } public void keyPressed(KeyEvent k) { if (k.getKeyCode() == 8 && text.length() > 0) { text = text.substring(0, text.length() - 1); } else { if(k.getKeyCode()>47 && k.getKeyCode()<58 && text.length()<3){ text+= k.getKeyChar(); checkValueOverMax(); } } } private void checkValueOverMax() { int value = Integer.parseInt(text); int maxValue = _root.parent.boxes.size()-1; if(value>maxValue){ text=Integer.toString(maxValue); } } public void mousePressed(MouseEvent m) { int mouseX = m.getX(); int mouseY = m.getY(); if(clicksRect(close,mouseX,mouseY)){ _root.vacancy=true; _root.boxLink=null; _root.textfield.active=true; } if(clicksRect(confirm,mouseX,mouseY)){ _root.story="<link>"+text; _root.vacancy=true; _root.boxLink=null; _root.die(_root.parent); } } private boolean clicksRect(Rectangle rect, int mouseX, int mouseY) { return (mouseX>rect.x && mouseX<rect.x+rect.width && mouseY>rect.y && mouseY<rect.y+rect.height); } } <file_sep>/Arbit/AppletTest/src/Action.java import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import java.awt.event.MouseEvent; public class Action { int stageWidth; int stageHeight; Rectangle close; Rectangle accept; int x; int y; Image pane = Images.action_pane; String title="Type to set Action"; int ID; public Action(int stageWidth,int stageHeight, int ID){ this.stageWidth = stageWidth; this.stageHeight= stageHeight; x=stageWidth/2-(pane.getWidth(null)/2); y=stageHeight/2-(pane.getHeight(null)/2); accept = new Rectangle(x+341,y+10,25,25);//creats the accept hitBox close = new Rectangle(x+372,y+10,25,25);//creates the close hitBox this.ID=ID; System.out.println("I have been summoned"); } public void draw(Graphics stage){ stage.drawImage(pane,x,y,null); //stage.fillRect(close.x, close.y, close.width, close.height); //stage.fillRect(accept.x, accept.y, accept.width, accept.height); stage.setColor(new Color(69,73,86)); stage.setFont(new Font("Lucida Console", Font.BOLD, 25)); stage.drawString(title, x+22, y+63); } public void mousePressed(MouseEvent m, createScreen parent) {//what happens when the mouse is pressed int mouseX = m.getX(); int mouseY = m.getY(); if(mouseX>close.x && mouseX<close.x+close.width && mouseY>close.y && mouseY<close.y+close.height){ die(parent); } if(mouseX>accept.x && mouseX<accept.x+accept.width && mouseY>accept.y && mouseY<close.y+close.height){ submit(parent); } } private void die(createScreen parent) { // TODO Auto-generated method stub parent.vacancy=true; //System.out.println("Bye: said the action"); parent.action=null; } public void submit(createScreen parent) {//what happens when you click on submit key if(!title.equals("Type to set Action") && title.length()>0){//creates new box, and shifts other box to fit the new box int shift=50; for(int i=0;i<parent.moms.size();i++){ if(parent.moms.get(i)==ID){ parent.boxes.get(i).x-=60; parent.allChildren(-60,i); shift+=60; } } int boxX = parent.boxes.get(ID).x+shift; int boxY = parent.boxes.get(ID).y+115; Box box= new Box(boxX,boxY,title,parent,parent.boxes.get(ID)); parent.boxes.add(box); parent.stories.add(""); parent.moms.add(ID); parent.titles.add(title); parent.links.add(null); parent.images.add(null); //System.out.println("Submitted"); die(parent); //System.out.println("Boxes:+"+parent.boxes); //System.out.println("stories:+"+parent.stories); //System.out.println("Moms:+"+parent.moms); //System.out.println("titles:+"+parent.titles); } } }<file_sep>/Arbit/Runnable/src/Postit.java import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; public class Postit { Image pane = Images.PostOnline; Image highlight =Images.long_highlight; Image nsfwIcon = Images.selected; createScreen _root; Rectangle close; Rectangle storyTitleRect; Rectangle authorRect; Rectangle submit; Rectangle nsfwRect; boolean nsfw; int x; int y; private boolean highlightTitle=false; private boolean TitleSelected=false; private boolean highlightAuthor=false; private boolean AuthorSelected=false; String author=""; String title=""; public Postit(createScreen parent){ this._root = parent; x=_root.stageWidth/2-(pane.getWidth(null)/2); y=_root.stageHeight/2-(pane.getHeight(null)/2); close = new Rectangle(x+345,y+11,25,25); storyTitleRect = new Rectangle(x+105,y+42,250,20); authorRect = new Rectangle(x+105,y+70,250,20); submit = new Rectangle(x+222,y+98,135,25); nsfwRect = new Rectangle(x+100,y+100,17,17); } public void draw(Graphics stage){ stage.drawImage(pane,x,y,null); //stage.fillRect(close.x, close.y, close.width, close.height); //stage.fillRect(storyTitleRect.x,storyTitleRect.y,storyTitleRect.width,storyTitleRect.height); //stage.fillRect(authorRect.x,authorRect.y,authorRect.width,authorRect.height); //stage.fillRect(submit.x,submit.y,submit.width,submit.height); //stage.fillRect(nsfwRect.x,nsfwRect.y,nsfwRect.width,nsfwRect.height); if(highlightTitle||TitleSelected){ stage.drawImage(highlight,x+100,y+37,null); } if(highlightAuthor || AuthorSelected){ stage.drawImage(highlight,x+100,y+65,null); } stage.setColor(new Color(102,109,128)); stage.setFont(new Font("Biko", Font.PLAIN, 17)); stage.drawString(title, x+108, y+58); stage.drawString(author, x+108, y+86); stage.setFont(new Font("Biko", Font.PLAIN, 17)); if(nsfw){ stage.drawImage(nsfwIcon,x+97,y+97,null); } } public void mousePressed(MouseEvent m) {//what happens when the mouse is pressed int mouseX = m.getX(); int mouseY = m.getY(); if(mouseX>close.x && mouseX<close.x+close.width && mouseY>close.y && mouseY<close.y+close.height){ _root.vacancy=true; _root.postit=null; } if(mouseX>nsfwRect.x && mouseX<nsfwRect.x+nsfwRect.width && mouseY>nsfwRect.y && mouseY<nsfwRect.y+nsfwRect.height){ nsfw=!nsfw; } TitleSelected=false; AuthorSelected=false; if(highlightTitle){ TitleSelected=true; } if(highlightAuthor){ AuthorSelected=true; } if(mouseX>submit.x && mouseX<submit.x+submit.width && mouseY>submit.y && mouseY<submit.y+submit.height){ if(author.length()>0 && title.length()>0){ MySqlRunner runner = new MySqlRunner(); runner.store(title,author,_root,nsfw); _root.vacancy=true; _root.postit=null; }else{ //alert to put Author/title } } } public void mouseMoved(MouseEvent m) { int mouseX = m.getX(); int mouseY = m.getY(); highlightTitle=(mouseX>storyTitleRect.x && mouseX<storyTitleRect.x+storyTitleRect.width && mouseY>storyTitleRect.y && mouseY<storyTitleRect.y+storyTitleRect.height); highlightAuthor=(mouseX>authorRect.x && mouseX<authorRect.x+authorRect.width && mouseY>authorRect.y && mouseY<authorRect.y+authorRect.height); } public void keyPressed(KeyEvent k) { if(TitleSelected){ if (k.getKeyCode() == 8 && title.length() > 0) { title = title .substring(0, title.length() - 1); } else { if (((k.getKeyChar() >= 39 && k.getKeyChar() <= 122) || k .getKeyChar() == ' ') && title.length() < 20) { title += k.getKeyChar(); } } }else if(AuthorSelected){ if (k.getKeyCode() == 8 && author.length() > 0) { author = author .substring(0, author.length() - 1); } else { if (((k.getKeyChar() >= 39 && k.getKeyChar() <= 122) || k .getKeyChar() == ' ') && author.length() < 20) { author += k.getKeyChar(); } } } } }<file_sep>/Arbit/Runnable/src/GameCanvas.java import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.image.BufferStrategy; import javax.swing.Timer; // OK this the class where we will draw everything on the screen and take actions // This is the grand mother of all classes as it manages what goes on where public class GameCanvas extends Canvas implements MouseMotionListener, MouseListener, MouseWheelListener, KeyListener { /** * */ private static final long serialVersionUID = 8465176307306678754L; public int stageWidth = 520;// The width of the screen public int stageHeight = 620;// The height of the screen public MenuScreen menu;// creates the menu screen boolean repaintInProgress = false;// checks if painting is going on public createScreen create;// creates the edit screen public int clickedX;// x coordinate of where the mouse clicks public int clickedY;// y coordinate of where the mouse clicks public int xDrag;// x coordinates of where the mouse drags public int yDrag;// y coordinates of where the mouse drags public PlayGame playGame; public Rectangle clickableRect; public Curser cursor = new Curser(); private boolean doOnce=true; GameCanvas() { // creates the gameCanvas setIgnoreRepaint(true); // Ignor this, established game engine Chrono chrono = new Chrono(this); new Timer(18, chrono).start(); this.addMouseListener(this);// adds all the eventListener this.addMouseMotionListener(this); this.addMouseWheelListener(this); this.addKeyListener(this); clickableRect = new Rectangle(0, 0, 520, 620); } public void myRepaint() { // Repaints if (repaintInProgress) return; repaintInProgress = true; // ok doing the repaint on the not showed page BufferStrategy strategy = getBufferStrategy();// Prevents flickering Graphics stage = strategy.getDrawGraphics(); stage.setColor(Color.black); stage.drawString("Your game is currently loading", 150, 250); stage.fillRect(138,260,Images.loader*2,10); stage.drawRect(138,260,186,10); //System.out.println(Images.loader*2); if (create != null) {// if the editScreen exists, paint it create.draw(stage); } if (playGame != null) { playGame.draw(stage); } if(menu!=null){ menu.draw(stage);// draw the menu scren } cursor.draw(stage); if(doOnce){ doOnce=false; final GameCanvas here = this; Thread one = new Thread() { public void run() { System.out.println("TIS HAPPENING!"); Images.Load(); menu = new MenuScreen(here); } }; one.start(); } if (stage != null) stage.dispose(); // show next buffer strategy.show(); // synchronized the blitter page shown Toolkit.getDefaultToolkit().sync(); repaintInProgress = false; } @Override public void mouseWheelMoved(MouseWheelEvent m) { // TODO Auto-generated method stub } @Override public void mouseClicked(MouseEvent m) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent m) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent m) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent m) {// When the mouse is pressed // TODO Auto-generated method stub cursor.mousePressed(m); int mouseX = m.getX(); int mouseY = m.getY(); if (mouseX > clickableRect.x && mouseX < clickableRect.x + clickableRect.width && mouseY > clickableRect.y && mouseY < clickableRect.y + clickableRect.height) { if (m.getModifiers() == 16) {// if regular left click if (menu.create_btn.createFlag && create == null && playGame == null) { // if the createButton is clicked menu.position = "Pressed"; menu.create_btn.checkClicked(m.getX(), m.getY(), menu); } if (create != null) { create.mousePressed(m); } if (menu.play_btn.isClicked(m.getX(), m.getY()) && menu.play_btn.createFlag && create == null && playGame == null) { menu.isConnecting=true; } if (playGame != null) { playGame.mouseClicked(m); } } else if (m.getModifiers() == 4) {// is rightclick if (create != null) { clickedX = m.getX(); clickedY = m.getY(); create.rightMousePressed(m); } } if (create != null && create.game != null) { create.game.mousePressed(m); } if (playGame != null && playGame.game != null) { playGame.game.mousePressed(m); } } } @Override public void mouseReleased(MouseEvent m) {// What happens when the mouse is cursor.mouseReleased(m); // released // TODO Auto-generated method stub menu.position = "Released"; if (m.getModifiers() == 4 && create != null) {// if its a right click for (Box box : create.boxes) {// set all the boxes x += to drag and // set drag=0; box.x += xDrag; box.y += yDrag; box.xShift = 0; box.yShift = 0; } } xDrag = 0; yDrag = 0; } @Override public void mouseDragged(MouseEvent m) { cursor.mouseDragged(m); // TODO Auto-generated method stub if (m.getModifiers() == 4 && create != null && !(create.tut != null && create.tut.frame > 1)) { // System.out.println("rightDragBrah"); // System.out.println(m); xDrag = m.getX() - clickedX; yDrag = m.getY() - clickedY; for (Box box : create.boxes) { box.xShift = xDrag; box.yShift = yDrag; } } } @Override public void mouseMoved(MouseEvent m) { cursor.mouseMoved(m); if(menu!=null){ if (menu.yPos < 610) { menu.position = "Mouse is moving"; menu.play_btn.highlight(m.getX(), m.getY()); menu.create_btn.highlight(m.getX(), m.getY()); } if (create != null) {// highlights the icons when mouse drags over it create.highlightElements(m.getX(), m.getY()); } if (create != null && create.game != null) { create.game.mouseMoved(m); } if (playGame != null && playGame.game != null) { playGame.game.mouseMoved(m); } if (create != null) { create.mouseMoved(m); } } } @Override public void keyPressed(KeyEvent k) {// What happens when you drag a key. I // will have to redo this code to make // it more object oriented // TODO Auto-generated method stub if (create != null) { create.keyPressed(k); if (create.tut != null) { create.tut.keyPressed(k); } } if (playGame != null){ playGame.keyPressed(k); if(playGame.game != null) { playGame.game.keyPressed(k); } } if (create != null && create.action != null) { if (create.action.title.equals("Type to set Action")) { create.action.title = ""; } if (!create.action.title.equals("Type to set Action") && create.action.title.length() > 0 && k.getKeyCode() == 10) { create.action.submit(create); } try { if (create.action.title.length() < 20) { if (k.getKeyCode() == 32) { create.action.title += "_"; } if (k.getKeyCode() == 8 && create.action.title.length() > 0) { create.action.title = create.action.title.substring(0, create.action.title.length() - 1); } else if (k.getKeyChar() >= 48 && k.getKeyChar() <= 122) { create.action.title += k.getKeyChar(); } } } catch (Exception e) { } } if (create != null && create.save_n_load != null) { create.save_n_load.keyPressed(k); } if (create != null) { Scene scene = create.scene; if (scene != null) { scene.textfield.keyPressed(k); } } } @Override public void keyReleased(KeyEvent arg0) { // TODO Auto-generated method stub } @Override public void keyTyped(KeyEvent arg0) { // TODO Auto-generated method stub } } <file_sep>/Arbit/Runnable/src/createScreen.java import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.util.ArrayList; public class createScreen implements KeyListener { Image bg = Images.createBg; Image arrowBtn = Images.arrow_btn; Image arrowBtnGlow = Images.arrow_btn_glow; Image saveBtnReg = Images.save_btn; Image saveBtnGlow = Images.save_btn_glow; Image loadBtnGlow = Images.load_glow; Image loadBtnReg = Images.load; Image genBtnReg = Images.generate_btn; Image genBtnGlow = Images.generate_btn_glow; Image newBtnReg = Images.new_btn; Image newBtnGlow = Images.new_btn_glow; Image postBtnReg = Images.post_it_btn; Image postBtnGlow = Images.post_it_btn_glow; Image exitBtnReg = Images.exit_btn; Image exitBtnGlow = Images.exit_btn_glow; Image toolbarDropShadow = Images.longDropShaddow; Image abilityIcon = Images.abilityIcon; Image abilityIconGlow =Images.abilityIconGlow; Image loadBtn = loadBtnReg; Image genBtn = genBtnReg; Image saveBtn = saveBtnReg; Image newBtn = newBtnReg; Image postBtn = postBtnReg; Image exitBtn = exitBtnReg; Image ability = abilityIcon; int stageWidth; int stageHeight; public Box startBox; public boolean vacancy = true; public Action action; public Scene scene; public SaveLoad save_n_load; public UploadStatus uploadStatus; // DEM ARRAYS /* * var shapes:Array = new Array(); --> needs var images:Array = new Array(); * --> needs var bitmap:Array = new Array(); --> needs var filez:Array = new * Array(); --> needs */ public String[] var_names = new String[8]; public String[] var_type = new String[8]; public Object[] var_value = new Object[8]; public ArrayList<String> stories = new ArrayList<String>(); public ArrayList<String> titles = new ArrayList<String>(); public ArrayList<Box> boxes = new ArrayList<Box>(); public ArrayList<Integer> moms = new ArrayList<Integer>(); public ArrayList<String> links = new ArrayList<String>(); public ArrayList<BufferedImage> images = new ArrayList<BufferedImage>(); // TOOLBARS public Image[] elements = { arrowBtn, loadBtn, saveBtn, genBtn, newBtn, postBtn, exitBtn, abilityIcon }; public Image[] elementsGlow = { arrowBtnGlow, loadBtnGlow, saveBtnGlow, genBtnGlow, newBtnGlow, postBtnGlow, exitBtnGlow, abilityIconGlow }; public Image[] elementsReg = { arrowBtn, loadBtnReg, saveBtnReg, genBtnReg, newBtnReg, postBtnReg, exitBtnReg, abilityIcon }; public int[] elementsBaseX = { 2, 40, 72, 105, 140, 176, 475, 212}; public int[] elementsBaseY = { 5, 5, 5, 6, 2, 7, 7 , 8}; public int[] elementsX = { 2, 40, 72, 105, 140, 176, 475, 212 }; public int[] elementsY = { 5, 5, 5, 6, 2, 7, 7, 8 }; public Rectangle[] elementRect = new Rectangle[8]; public boolean functionality = true; public Game game; public GameCanvas leader; public Postit postit; public Tutorial tut; public SaveWarn saveWarn; public Variables variables; public createScreen(int width, int height, GameCanvas leader, boolean boo) { boo=false;//toggles tutorial on/off on default startBox = new Box(width / 2, height / 2, "Start Scene", this, null); titles.add("Start Scene"); boxes.add(startBox); stories.add("Type to create the senario."); moms.add(-1); links.add(null); images.add(null); stageWidth = width; stageHeight = height; this.leader = leader; for (int i = 0; i < elements.length; i++) { elementRect[i] = new Rectangle(elementsX[i], elementsY[i], elements[i].getWidth(null), elements[i].getHeight(null)); } if (boo) { tut = new Tutorial(this); } } public createScreen() { titles.add("Start Scene"); boxes.add(startBox); stories.add("Type to create the senario."); moms.add(-1); links.add(null); images.add(null); stageWidth = 520; stageHeight = 620; } public void draw(Graphics stage) { for (int i2 = 0; i2 < 6; i2++) { for (int i = 0; i < 5; i++) { stage.drawImage(bg, i * bg.getWidth(null), i2 * bg.getHeight(null), null); } } try{ for (Box box : boxes) { box.draw(stage); } for (Box box : boxes) { if (box.alpha == 255) { box.draw(stage); } } stage.setColor(new Color(51, 51, 51, 255)); stage.drawImage(toolbarDropShadow, 0, 31, 550, 11, null); stage.fillRect(0, 0, stageWidth, 35); // draws arrow if (stage instanceof Graphics2D) { Graphics2D g2 = (Graphics2D) stage; AlphaComposite ac = AlphaComposite.getInstance( AlphaComposite.SRC_OVER, (float) .5); g2.setComposite(ac); stage.drawImage(arrowBtn, 2, 5, null); AlphaComposite ac2 = AlphaComposite.getInstance( AlphaComposite.SRC_OVER, (float) 1); g2.setComposite(ac2); for (Box box : boxes) { if (box.mother != null && !box.mother.invisibleChildren) { g2.setColor(new Color(51, 57, 56, 255)); g2.setStroke(new BasicStroke(5)); stage.drawLine(box.x + box.xShift + (box.width / 2), box.y + box.yShift, box.mother.x + box.xShift + (box.width / 2), box.mother.y + box.yShift + box.height); g2.setStroke(new BasicStroke(1)); } } } }catch(Exception e){} if (action != null) { action.draw(stage); } if (scene != null) { scene.draw(stage); } if (save_n_load != null) { save_n_load.draw(stage); } if (postit != null) { postit.draw(stage); } //Draws all the icons for(int i=0; i<=6; i++){ stage.drawImage(elements[i], elementsX[i], elementsY[i], null); } if (game != null) { game.draw(stage); } if (tut != null) { tut.draw(stage); } if(uploadStatus!=null){ uploadStatus.draw(stage); } if(saveWarn!=null){ saveWarn.draw(stage); } if(variables!=null){ variables.draw(stage); } } public void highlightElements(int x, int y) { for (int i = 0; i < 7; i++) { // checks if it is in hitbox if (x > elementsX[i] && x < elementsX[i] + elements[i].getWidth(null) && y > elementsY[i] && y < elementsY[i] + elements[i].getHeight(null)) { elements[i] = elementsGlow[i]; elementsX[i] = elementsBaseX[i] - 3; elementsY[i] = elementsBaseY[i] - 3; // System.out.println("HOOOOOO"); } else { // System.out.println("nope"); elements[i] = elementsReg[i]; elementsX[i] = elementsBaseX[i]; elementsY[i] = elementsBaseY[i]; } } } public void mousePressed(MouseEvent m) { if(uploadStatus!=null){ uploadStatus.mousePressed(m); } if(saveWarn!=null){ saveWarn.mousePressed(m); } if (tut != null) { tut.mousePressed(m); } if(variables!=null){ variables.mousePressed(m); } if (functionality) { try { for (Box box : boxes) { // System.out.println(box); if (box.alpha == 255) { box.mousePressed(m); } } } catch (Exception e) { } if (action != null) { action.mousePressed(m, this); } if (scene != null) { scene.mousePressed(m, this); } if (m.getModifiers() == 16) { leftMousePressed(m); } if (save_n_load != null) { save_n_load.mousePressed(m); } if (postit != null) { postit.mousePressed(m); } } } public void deleteBox(Box box) { int i = boxes.indexOf(box); int root = moms.get(i); boxes.remove(i); titles.remove(i); stories.remove(i); moms.remove(i); links.remove(i); images.remove(i); for (int m = 0; m < moms.size(); m++) { if (moms.get(m) > i) { moms.set(m, moms.get(m) - 1); } } for (int m = 0; m < moms.size(); m++) { if (moms.get(m) == root) { if (box.x > boxes.get(m).x) { boxes.get(m).x += 60; allChildren(60, m); } else { boxes.get(m).x -= 60; ; allChildren(-60, m); } } } deleteAllMyChildren(i); } private void deleteAllMyChildren(int i) { for (int b = 0; b < boxes.size(); b++) { if (moms.get(b) == i) { deleteBoxNoShift(boxes.get(b)); } } System.out.println("Boxes:+" + boxes); System.out.println("stories:+" + stories); System.out.println("Moms:+" + moms); System.out.println("titles:+" + titles); } private void deleteBoxNoShift(Box box) { int i = boxes.indexOf(box); boxes.remove(i); titles.remove(i); stories.remove(i); moms.remove(i); links.remove(i); images.remove(i); deleteAllMyChildren(i); } @Override public void keyPressed(KeyEvent k) { // System.out.println("hey"); if (game != null) { game.keyPressed(k); } if (postit != null) { postit.keyPressed(k); } if(variables!=null){ variables.keyPressed(k); } } @Override public void keyReleased(KeyEvent k) { // TODO Auto-generated method stub } @Override public void keyTyped(KeyEvent k) { // TODO Auto-generated method stub } public void allChildren(int shift, int index) { System.out.println("\nallChildren shift:" + shift + " index:" + index); // System.out.println(moms); // TODO Auto-generated method stub for (int b = 0; b < boxes.size(); b++) { if (moms.get(b) == index) { // System.out.print("Hey there bitch"); boxes.get(b).x += shift; // shapes[b].x+=shift; // System.out.print("Get you bitch ass back son"); allChildren(shift, b); } } } private void leftMousePressed(MouseEvent m) { // TODO Auto-generated method stub if (functionality) { int mouseX = m.getX(); int mouseY = m.getY(); for (int i = 0; i < elementRect.length; i++) { if (mouseX > elementRect[i].x && mouseX < elementRect[i].x + elementRect[i].width && mouseY > elementRect[i].y && mouseY < elementRect[i].y + elementRect[i].height) { iconClicked(i); } } } } private void iconClicked(int i) { System.out.println("You clicked on icon #" + i); if (functionality && vacancy) { if(tut!=null && tut.frame<3){ tut.die(); } if (i == 0) { centerBoxes(); } if (i == 1) { vacancy = false; save_n_load = new SaveLoad(this, false); } if (i == 2) { vacancy = false; save_n_load = new SaveLoad(this, true); } if (i == 3) { vacancy = false; functionality = false; game = new Game(this, false, null,"0"); } if (i == 4) { saveWarn = new SaveWarn(this,false); vacancy=false; functionality=false; /*leader.create = new createScreen(stageWidth, stageHeight, leader, false);*/ } if (i == 5) { vacancy = false; postit = new Postit(this); } if (i == 6) { saveWarn = new SaveWarn(this,true); vacancy=false; functionality=false; //leader.menu.rise = true; } if(i == 7){ /* functionality=false; vacancy=false; variables = new Variables(this); */ } } } public void centerBoxes() { System.out.println("What"); int xDist = (stageWidth / 2) - boxes.get(0).x - boxes.get(0).width / 2; int yDist = (stageHeight / 2) - boxes.get(0).y - boxes.get(0).height / 2; for (Box box : boxes) { box.x += xDist; box.y += yDist; } } public void rightMousePressed(MouseEvent m) { if (functionality) { int mouseX = m.getX(); int mouseY = m.getY(); for (Box b : boxes) { if(b.alpha!=0){ int i = boxes.indexOf(b); if (mouseX > b.x && mouseX < b.x + b.width && mouseY > b.y && mouseY < b.y + b.height) {// You clicked a box boolean isParent = false; for (int b2 = 0; b2 < boxes.size(); b2++) { if (moms.get(b2) == i) { isParent = true; } } if (!isParent) { i = moms.get(i); } try { for (int x = 0; x < boxes.size(); x++) { if (boxes.get(x).alpha != 0 && boxes.get(i).alpha!=0) { boxes.get(x).alpha = 50; if (moms.get(x) == i) { boxes.get(x).alpha = 255; } boxes.get(i).alpha = 255; } } } catch (Exception e) { } } } } } } public void removeGame() { game = null; vacancy = true; functionality = true; } public void mouseMoved(MouseEvent m) { if (save_n_load != null) { save_n_load.mouseMoved(m); } if (postit != null) { postit.mouseMoved(m); } } public void hideAllChildren(int i, boolean first) { if (!first) { boxes.get(i).alpha = 0; boxes.get(i).invisibleChildren=true; } for (int e = 0; e < moms.size(); e++) { if (moms.get(e) == i) { hideAllChildren(e, false); } } } public void showAllChildren(int i, boolean first) { if (!first) { boxes.get(i).alpha = 50; boxes.get(i).invisibleChildren=false; } for (int e = 0; e < moms.size(); e++) { if (moms.get(e) == i) { showAllChildren(e, false); } } } }<file_sep>/Arbit/Runnable/src/mySqlFetcher.java import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.URL; import java.net.URLConnection; public class mySqlFetcher { PlayGame _root; public int page; public int catagory; public boolean nsfw; public String[] ids; public String[] authors; public String[] views; public String[] dates; public String[] rating; public String[] comments; public String[] titles; public String[] nsfws; public String[] urls = { "http://myrighttoplay.com/Arbitrio/Java/featured.php", "http://myrighttoplay.com/Arbitrio/Java/hot.php", "http://myrighttoplay.com/Arbitrio/Java/high_rating.php", "http://myrighttoplay.com/Arbitrio/Java/newest.php", "http://myrighttoplay.com/Arbitrio/Java/contriversal.php" }; private boolean success=true; public mySqlFetcher(int catagory, int page, boolean nsfw, PlayGame playGame) { _root=playGame; this.catagory=catagory; this.page=page; this.nsfw=nsfw; System.out.println("Loading content.."); try{ // open a connection to the site URL url = new URL(urls[catagory]); URLConnection con = url.openConnection(); // activate the output con.setDoOutput(true); PrintStream ps = new PrintStream(con.getOutputStream()); // send your parameters to your site ps.print("&nsfw="+nsfw+"&page="+page); // we have to get the input stream in order to actually send the request con.getInputStream(); // close the print stream ps.close(); InputStream r = con.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(r)); int i=0; for(String line; (line = reader.readLine()) != null;){ //System.out.println(line); if(i==0){ ids = line.split("/////"); } if(i==1){ titles=line.split("/////"); } if(i==2){ authors=line.split("/////"); } if(i==3){ dates=line.split("/////"); } if(i==4){ rating=line.split("/////"); } if(i==5){ views=line.split("/////"); } if(i==6){ nsfws=line.split("/////"); } if(i==7){ comments=line.split("/////"); } i++; } String ID ="["; String AUTH= "["; String TITLE= "["; String DATES= "["; String VIEWS= "["; String NSFWS= "["; String COMM= "["; for(int n=0;n<ids.length;n++){ ID+=ids[n]+","; AUTH+=authors[n]+","; TITLE+=titles[n]+","; DATES+=dates[n]+","; VIEWS+=views[n]+","; NSFWS+=nsfws[n]+","; COMM+=comments[n]+","; } ID+="]"; AUTH+="]"; TITLE+="]"; DATES+="]"; VIEWS+="]"; NSFWS+="]"; COMM+="]"; System.out.println(ID); System.out.println(AUTH); System.out.println(TITLE); System.out.println(DATES); System.out.println(VIEWS); System.out.println(NSFWS); System.out.println(COMM); }catch(Exception e){ //Failed to connect to server System.out.println("Failed to load contents"); success=false; _root._root.menu.noConnect=100; _root._root.menu.rise=true; } if(success){ _root.generateFetch(ids.length,ids,authors,titles,dates,views,nsfws,comments,rating); _root._root.menu.fall=true; _root._root.menu.play_btn.createFlag=false; } } } <file_sep>/Arbit/Runnable/src/Vars.java import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; public class Vars { Image new_var = Images.create_var; Image var_set = Images.varSettings; Image glow_pane =Images.variablePaneGlow; Image name_glow =Images.varNameGlow; Image type_opts = Images.type_opts; Image var_value =Images.varValue; Image var_val_high =Images.VarvalHigh; public int x; public int y; public boolean focused; public Variables _root; public Image pane = new_var; public boolean newbie = true; private Functions funk = new Functions(); Rectangle rect; Rectangle close; Rectangle name; Rectangle type; Rectangle value; String name_str = "Name"; String type_str = "Boolean"; String value_str = "True"; Fonts font = new Fonts(); private boolean name_highlight = false; private boolean type_highlight = false; String box1 = "Number"; String box2 = "Text"; Rectangle Box1; Rectangle Box2; int text_shift = 0; private boolean show_value_opts; private Rectangle boolean_Rect; private boolean highlight_value; private boolean Text = false; public Vars(int x, int y, Variables parent) { this.x = x; this.y = y; this._root = parent; rect = new Rectangle(x, y + 5, 380, 27); close = new Rectangle(x + 355, y + 5, 30, 27); name = new Rectangle(x + 2, y + 5, 95, 27); type = new Rectangle(x + 105, y + 5, 95, 27); value = new Rectangle(x + 210, y + 5, 140, 27); boolean_Rect = new Rectangle(x + 210, y + 5, 140, 28); } public void draw(Graphics stage) { if (newbie) { stage.drawImage(new_var, x, y, null); } else { if (focused) { stage.drawImage(glow_pane, x - 3, y - 3, null); } else { stage.drawImage(var_set, x, y, null); } if (name_highlight) { stage.drawImage(name_glow, x + 1, y, null); } if (highlight_value) { stage.drawImage(var_val_high, x + 207, y + 1, null); } if (type_highlight) { stage.drawImage(type_opts, x + 106, y + 24, null); stage.drawString(box1, x + 125, y + 41); stage.drawString(box2, x + 137 + text_shift, y + 63); } Fonts.setSize(16); stage.setFont(Fonts.regFont); @SuppressWarnings("deprecation") FontMetrics fm = Toolkit.getDefaultToolkit().getFontMetrics( Fonts.regFont); int w = fm.stringWidth(name_str); stage.drawString(name_str, x + 48 - (w / 2), y + 18); w = fm.stringWidth(type_str); stage.drawString(type_str, x + 153 - (w / 2), y + 18); w = fm.stringWidth(value_str); stage.drawString(value_str, x + 275 - (w / 2), y + 18); } } public void mousePressed(MouseEvent m) { int mouseX = m.getX(); int mouseY = m.getY(); Rectangle recty = new Rectangle(rect.x, rect.y, rect.width - 232, rect.height); if (newbie && funk.hitTest(recty, mouseX, mouseY)) { pane = var_set; newbie = false; y += 6; _root.clearFocused(); focused = true; } if (!newbie) { if (funk.hitTest(value, mouseX, mouseY)) { if (type_str.equals("Boolean")) { show_value_opts = true; } else if (type_str.equals("Number")) { highlight_value = true; Text = false; } else { highlight_value = true; Text = true; } } else { highlight_value = false; } if (show_value_opts) { if (funk.hitTest(boolean_Rect, mouseX, mouseY)) { if (value_str.equals("True")) { value_str = "False"; } else { value_str = "True"; } show_value_opts = false; } } else if (type_highlight) { if (funk.hitTest(Box1, mouseX, mouseY)) { if (type_str.equals("Boolean")) { type_str = "Number"; box1 = "Boolean"; box2 = "Text"; text_shift = 0; value_str = "0"; } else if (type_str.equals("Number")) { type_str = "Boolean"; box1 = "Number"; box2 = "Text"; text_shift = 0; value_str = "True"; } else { type_str = "Boolean"; box1 = "Number"; box2 = "Text"; text_shift = 0; value_str = "True"; } } if (funk.hitTest(Box2, mouseX, mouseY)) { if (type_str.equals("Boolean")) { type_str = "Text"; box1 = "Boolean"; box2 = "Number"; text_shift -= 11; value_str = "Something"; } else if (type_str.equals("Number")) { type_str = "Text"; box1 = "Boolean"; box2 = "Number"; text_shift -= 11; value_str = "Something"; } else { type_str = "Number"; box1 = "Boolean"; box2 = "Text"; text_shift = 0; value_str = "0"; } } } else if (funk.hitTest(close, mouseX, mouseY)) { pane = new_var; newbie = true; focused = false; y -= 6; } else if (funk.hitTest(rect, mouseX, mouseY)) { _root.clearFocused(); focused = true; } else { focused = false; } if (focused) { if (funk.hitTest(name, mouseX, mouseY)) { name_highlight = true; } else { name_highlight = false; } if (funk.hitTest(type, mouseX, mouseY)) { type_highlight = true; Box1 = new Rectangle(x + 106, y + 25, 100, 20); Box2 = new Rectangle(x + 106, y + 46, 100, 20); } else { type_highlight = false; } } if (!focused) { name_highlight = false; type_highlight = false; show_value_opts = false; highlight_value = false; } } } public void keyPressed(KeyEvent k) { if (highlight_value) { if (Text) { value_str = funk.editString(k, value_str, 90, Fonts.regFont, "Something", 39, 122, 9001,true); } else { value_str = funk.editString(k, value_str, 60, Fonts.regFont, "0", 48, 57, 8,false); } } else if (name_highlight) { name_str = funk.editString(k, name_str, 68, Fonts.regFont, "Name", 39, 122, 9001,true); } } } <file_sep>/Arbit/Runnable/src/chatButtons.java import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.MouseEvent; public class chatButtons { private PlayGame _root; private boolean light; private Image chat_dark = Images.chat_dark; private Image chat_light = Images.chat_light; public boolean visible=false; public int x=450; public int y; public String comments="0"; private Font regFont; private Rectangle hitBox; public String id; public chatButtons(PlayGame playGame, boolean light, int chatY) { // TODO Auto-generated constructor stub this._root=playGame; this.light=light; this.y=chatY; this.regFont = Images.biko_reg; this.regFont = this.regFont.deriveFont(Font.PLAIN, 12f); hitBox = new Rectangle(x+8,y+3,36,36); } public void draw(Graphics stage) { // TODO Auto-generated method stub if(Integer.parseInt(comments)==0){ visible=false; }else{ visible=true; } if(visible){ if(light){ stage.drawImage(chat_light,x-3,y,null); }else{ stage.drawImage(chat_dark,x-3,y,null); } stage.setFont(regFont); stage.setColor(new Color(50,50,50)); @SuppressWarnings("deprecation") FontMetrics fm = Toolkit.getDefaultToolkit().getFontMetrics(stage.getFont()); int w = fm.stringWidth(comments); stage.drawString(comments,x+28-w,y+40); } //drawRect(hitBox,stage); } public void checkClicked(MouseEvent m) { int mouseX= m.getX(); int mouseY= m.getY(); if(StorySelection.vacancy && visible && mouseX>hitBox.x && mouseX<hitBox.x+hitBox.width && mouseY>hitBox.y && mouseY<hitBox.y+hitBox.height){ openComments(); } } private void openComments() { StorySelection.vacancy=false; _root.comments = new Comments(_root,id); } @SuppressWarnings("unused") private void drawRect(Rectangle rect, Graphics stage) { stage.fillRect(rect.x,rect.y,rect.width,rect.height); } @SuppressWarnings("unused") private void trace(String string) { System.out.println(string); } } <file_sep>/Arbit/Runnable/src/Images.java import java.awt.Font; import java.awt.Image; public class Images { public static Image Arbit; public static Image Loading_Data; public static Image PostOnline; public static Image SceneLink; public static Image Untitled2; public static Image VarvalHigh; public static Image ability; public static Image abilityIcon; public static Image abilityIconGlow; public static Image action_pane; public static Image arrow_btn; public static Image arrow_btn_glow; public static Image arrow_left; public static Image arrow_left_faded; public static Image arrow_right; public static Image arrow_right_faded; public static Image background; public static Image background2; public static Image boxDropShadow; public static Image boxLink; public static Image chat_dark; public static Image chat_light; public static Image comments; public static Image connecting_to_server; public static Image connection_failure; public static Image createBg; public static Image createNewGlow; public static Image create_var; public static Image exit_btn; public static Image exit_btn_glow; public static Image eye; public static Image eye_2; public static Image angry_dark; public static Image angry_light; public static Image comment_thanks; public static Image estatic_dark; public static Image estatic_light; public static Image happy_dark; public static Image happy_light; public static Image meh_dark; public static Image meh_light; public static Image sad_dark; public static Image sad_light; public static Image thanks; public static Image fetching_games; public static Image generate_btn; public static Image generate_btn_glow; public static Image link; public static Image load; public static Image load_glow; public static Image longDropShaddow; public static Image long_highlight; public static Image menuChibi_1; public static Image menuChibi_2; public static Image new_btn; public static Image new_btn_glow; public static Image noPic; public static Image no_spam; public static Image nsfw_sticker; public static Image play_game_layout; public static Image post_it_btn; public static Image post_it_btn_glow; public static Image rateComment; public static Image save_btn; public static Image save_btn_glow; public static Image save_n_load; public static Image save_warning; public static Image selected; public static Image selected2; public static Image senario_pane; public static Image small_left_arrow; public static Image small_left_arrow_faded; public static Image small_right_arrow; public static Image small_right_arrow_faded; public static Image successful_upload; public static Image tutorial_pane_1; public static Image tutorial_pane_2; public static Image tutorial_pane_3; public static Image tutorial_pane_4; public static Image tutorial_pane_5; public static Image tutorial_pane_6; public static Image tutorial_pane_7; public static Image tutorial_prompt1; public static Image type_opts; public static Image unsuccessful_upload; public static Image varNameGlow; public static Image varSettings; public static Image varValue; public static Image variablePane; public static Image variablePaneGlow; public static Font code_light; public static Font code_bold; public static Font biko_bold; public static Font biko_reg; public static int loader = 0; public static void Load() { Arbit = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/Arbit.png"); loader++; Loading_Data = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/Loading_Data.png"); loader++; PostOnline = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/PostOnline.png"); loader++; SceneLink = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/SceneLink.png"); loader++; Untitled2 = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/Untitled-2.png"); loader++; VarvalHigh = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/VarValHigh.png"); loader++; ability = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/ability.png"); loader++; abilityIcon = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/abilityIcon.png"); loader++; abilityIconGlow = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/abilityIconGlow.png"); loader++; action_pane = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/action_pane.png"); loader++; arrow_btn = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/arrow_btn.png"); loader++; arrow_btn_glow = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/arrow_btn_glow.png"); loader++; arrow_left = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/arrow_left.png"); loader++; arrow_left_faded = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/arrow_left_faded.png"); loader++; arrow_right = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/arrow_right.png"); loader++; arrow_right_faded = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/arrow_right_faded.png"); loader++; background = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/background.png"); loader++; background2 = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/background2.png"); loader++; boxDropShadow = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/boxDropShadow.png"); loader++; boxLink = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/boxLink.png"); loader++; chat_dark = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/chat_dark.png"); loader++; chat_light = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/chat_light.png"); loader++; comments = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/comments.png"); loader++; connecting_to_server = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/connecting_to_server.png"); loader++; connection_failure = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/connection_failure.png"); loader++; createBg = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/createBg.png"); loader++; createNewGlow = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/createNewGlow.png"); loader++; create_var = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/create_var.png"); loader++; exit_btn = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/exit_btn.png"); loader++; exit_btn_glow = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/exit_btn_glow.png"); loader++; eye = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/eye.png"); loader++; eye_2 = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/eye_2.png"); loader++; angry_dark = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/faces/angry_dark.png"); loader++; angry_light = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/faces/angry_light.png"); loader++; comment_thanks = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/faces/comment_thanks.png"); loader++; estatic_dark = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/faces/estatic_dark.png"); loader++; estatic_light = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/faces/estatic_light.png"); loader++; happy_dark = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/faces/happy_dark.png"); loader++; happy_light = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/faces/happy_light.png"); loader++; meh_dark = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/faces/meh_dark.png"); loader++; meh_light = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/faces/meh_light.png"); loader++; sad_dark = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/faces/sad_dark.png"); loader++; sad_light = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/faces/sad_light.png"); loader++; thanks = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/faces/thanks.png"); loader++; fetching_games = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/fetching_games.png"); loader++; generate_btn = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/generate_btn.png"); loader++; generate_btn_glow = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/generate_btn_glow.png"); loader++; link = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/link.png"); loader++; load = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/load.png"); loader++; load_glow = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/load_glow.png"); loader++; longDropShaddow = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/longDropShaddow.png"); loader++; long_highlight = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/long_highlight.png"); loader++; menuChibi_1 = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/menuChibi_1.png"); loader++; menuChibi_2 = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/menuChibi_2.png"); loader++; new_btn = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/new_btn.png"); loader++; new_btn_glow = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/new_btn_glow.png"); loader++; noPic = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/noPic.png"); loader++; no_spam = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/no_spam.png"); loader++; nsfw_sticker = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/nsfw_sticker.png"); loader++; play_game_layout = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/play_game_layout.png"); loader++; post_it_btn = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/post_it_btn.png"); loader++; post_it_btn_glow = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/post_it_btn_glow.png"); loader++; rateComment = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/rateComment.png"); loader++; save_btn = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/save_btn.png"); loader++; save_btn_glow = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/save_btn_glow.png"); loader++; save_n_load = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/save_n_load.png"); loader++; save_warning = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/save_warning.png"); loader++; selected = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/selected.png"); loader++; selected2 = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/selected2.png"); loader++; senario_pane = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/senario_pane.png"); loader++; small_left_arrow = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/small_left_arrow.png"); loader++; small_left_arrow_faded = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/small_left_arrow_faded.png"); loader++; small_right_arrow = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/small_right_arrow.png"); loader++; small_right_arrow_faded = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/small_right_arrow_faded.png"); loader++; successful_upload = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/successful_upload.png"); loader++; tutorial_pane_1 = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/tutorial_pane_1.png"); loader++; tutorial_pane_2 = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/tutorial_pane_2.png"); loader++; tutorial_pane_3 = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/tutorial_pane_3.png"); loader++; tutorial_pane_4 = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/tutorial_pane_4.png"); loader++; tutorial_pane_5 = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/tutorial_pane_5.png"); loader++; tutorial_pane_6 = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/tutorial_pane_6.png"); loader++; tutorial_pane_7 = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/tutorial_pane_7.png"); loader++; tutorial_prompt1 = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/tutorial_prompt1.png"); loader++; type_opts = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/type_opts.png"); loader++; unsuccessful_upload = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/unsuccessful_upload.png"); loader++; varNameGlow = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/varNameGlow.png"); loader++; varSettings = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/varSettings.png"); loader++; varValue = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/varValue.png"); loader++; variablePane = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/variablePane.png"); loader++; variablePaneGlow = Functions .loadImage("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Data/variablePaneGlow.png"); loader++; code_light = Functions .loadFont("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Fonts/CODE_Light.ttf"); loader++; code_bold = Functions .loadFont("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Fonts/CODE_Bold.ttf"); loader++; biko_bold = Functions .loadFont("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Fonts/Biko_Bold.ttf"); loader++; biko_reg = Functions .loadFont("http://myrighttoplay.com/1337file/arbitTest/ArbitRun/Fonts/Biko_Regular.ttf"); } } <file_sep>/Arbit/Runnable/src/Variables.java import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; public class Variables { Image pane = Images.variablePane; int pane_width = pane.getWidth(null); int pane_height = pane.getHeight(null); createScreen _root; int x; int y; Rectangle closeRect; Rectangle confirmRect; Functions funk = new Functions(); Vars vars[] = new Vars[8]; Fonts font = new Fonts(); public Variables(createScreen parent){ _root = parent; x=(_root.stageWidth/2)-(pane_width/2); y=(_root.stageHeight/2)-(pane_width/2); closeRect = new Rectangle(422,106,30,30); confirmRect = new Rectangle(390,106,30,30); for(int i=0; i<vars.length; i++){ vars[i] = new Vars(x+15,y+34+(i*32),this); } } public void draw(Graphics stage) { stage.drawImage(pane,x,y,null); boolean noNoobs = true; Vars focused = new Vars(0,0,this); for(Vars var: vars){ var.draw(stage); if(!var.newbie){ noNoobs=false; } if(var.focused){ focused=var; } } if(focused.y>10){ focused.draw(stage); } if(!noNoobs){ Fonts.setSize(12); stage.setFont(Fonts.regFont); stage.drawString("Initial value", x+250, y+35); } } public void mousePressed(MouseEvent m) { int mouseX = m.getX(); int mouseY = m.getY(); if(funk.hitTest(closeRect,mouseX,mouseY)){ die(); } if(funk.hitTest(confirmRect,mouseX,mouseY)){ String[] transfer_names = new String[8]; String[] transfer_type = new String[8]; Object[] transfer_value = new Object[8]; for(int i=0;i<8;i++){ if(!vars[i].newbie){ if(vars[i].type_str.equals("Boolean")){ funk.trace("theres a boolean:"+ vars[i].value_str); transfer_names[i]= vars[i].name_str; transfer_type[i] = vars[i].type_str; transfer_value[i] = vars[i].value; }else if(vars[i].type_str.equals("Number")){ funk.trace("Theres a number:"+vars[i].value_str); transfer_names[i]= vars[i].name_str; transfer_type[i] = vars[i].type_str; transfer_value[i] = vars[i].value; }else if(vars[i].type_str.equals("Text")){ funk.trace("Theres a string:"+vars[i].value_str); transfer_names[i]= vars[i].name_str; transfer_type[i] = vars[i].type_str; transfer_value[i] = vars[i].value; } }else{ transfer_names[i]= null; transfer_type[i] = null; transfer_value[i]= null; } _root.var_names=transfer_names; _root.var_type=transfer_type; _root.var_value=transfer_value; die(); } } for(Vars var: vars){ var.mousePressed(m); } } public void die(){ _root.vacancy=true; _root.functionality=true; _root.variables=null; } public void keyPressed(KeyEvent k) { for(Vars var:vars){ var.keyPressed(k); } } public void clearFocused() { for(Vars var:vars){ var.focused=false; } } } <file_sep>/Arbit/AppletTest/src/gameApplet.java import java.awt.BorderLayout; import javax.swing.JApplet; import javax.swing.SwingUtilities; public class gameApplet extends JApplet { /** * */ private static final long serialVersionUID = 2397850403794206025L; //Called when this applet is loaded into the browser. public void init() { SwingUtilities.invokeLater(new Runnable() { public void run() { // frame description // our Canvas GameCanvas canvas = new GameCanvas(); add(canvas, BorderLayout.CENTER); // set it's size and make it visible setSize(510, 580); setVisible(true); // now that is visible we can tell it that we will use 2 buffers to do the repaint // befor being able to do that, the Canvas as to be visible canvas.createBufferStrategy(2); } }); } } <file_sep>/Arbit/AppletTest/src/Texty.java import java.awt.Font; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; public class Texty { Object _root; String[] printStory = { "", "", "", "", "", "", "", "", "", "" }; int x=0; int y=0; public boolean active=true; public String story; public int desired_length = 45; public int max_length=300; public Font font = new Font("Lucida Console", Font.BOLD, 9); public Rectangle blink; private int blinkX=200; private int blinkY=200; private int blinkTimer=0; public Texty(Object parent,int x,int y, String story){ _root=parent; this.x=x; this.y=y; this.story=story; System.out.println("x:" + x + "y:" + y + parent + story); } public Texty(){ _root=null; x=0; y=0; story=""; } public void draw(Graphics stage){ enterFrame(); stage.setFont(font); for (int s = 0; s < printStory.length; s++) { stage.drawString(printStory[s], x + 18, y + 48 + s * 10); } blink = new Rectangle(blinkX,blinkY,1,10); blinkTimer++; if(blinkTimer>50){ //stage.drawRect(blink.x, blink.y, blink.width, blink.height); } if(blinkTimer>100){ blinkTimer=0; } } private void enterFrame() { // wrap it before you tap it(the key that it); String drawString = story; int i = 0; while (drawString.length() > desired_length && i < 9) { try { int splitPoint = drawString.lastIndexOf(" ", desired_length-1); printStory[i] = drawString.substring(0, splitPoint); drawString = drawString.substring(splitPoint + 1, drawString.length()); i++; } catch (Exception e) { // fix the spamscribble } } printStory[i] = drawString; i++; for (; i < printStory.length; i++) { printStory[i] = ""; } } public void keyPressed(KeyEvent k) { if (active) { if (k.getKeyCode() == 8 && story.length() > 0) { story = story.substring(0, story.length() - 1); } else { if (story.equals("Type to create the senario.")) { story = ""; } int[] a = new int[100]; int j = 0; for(int i = 0; i<story.length(); i++){ if(story.charAt(i) == (char)32){a[j] = i; j++;} } int index = 0; for(int i = 0; i<a.length&&index<a[i] ; i++){ index = a[i]; } System.out.println(index); if (((k.getKeyChar() >= 39 && k.getKeyChar() <= 122) || k .getKeyChar() == ' ') && story.length() < max_length) { story += k.getKeyChar(); } if(_root instanceof Scene){ Scene root = ((Scene)_root); if (k.getKeyCode() == 10 && !(root.parent.tut.frame > 2 && root.parent.tut.frame < 6)) { root.die(root.parent); } if(story.length()>30 && (story.substring(index+1,story.length()-1)).length() > (desired_length-4)) {story += (char)32;} } } } else if(_root instanceof Scene) { if(((Scene) _root).boxLink!=null){ ((Scene) _root).boxLink.keyPressed(k); }else{ ((Scene) _root).abilityBox.keyPressed(k); } } } @SuppressWarnings("unused") private void trace(String story) { System.out.println(story); } @SuppressWarnings("unused") public void mousePressed(MouseEvent m) { int mouseX=m.getX(); int mouseY=m.getY(); } } <file_sep>/Arbit/AppletTest/src/Fonts.java import java.awt.Font; public class Fonts { public static Font regFont; public static Font boldFont; public Fonts() { regFont = Images.biko_reg; regFont = regFont.deriveFont(Font.PLAIN, 13f); boldFont = Images.biko_bold; boldFont = boldFont.deriveFont(Font.PLAIN, 13f); } public static void setSize(int i) { regFont = regFont.deriveFont(Font.PLAIN, i); boldFont = boldFont.deriveFont(Font.PLAIN, i); } } <file_sep>/Arbit/AppletTest/src/ShowImage.java import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import java.awt.event.MouseEvent; public class ShowImage { Game _root; private Rectangle bg; private int alpha=0; private Image img; private int x=0; private int y=0; private int width; private int height; private int yDes; private int wait; private boolean fadeIn=true; private boolean fadeOut=false; private boolean death=false; public ShowImage(Game game,Image img) { _root=game; bg = new Rectangle(0,0,_root._root.stageWidth,_root._root.stageHeight); this.img = img; double imgW = img.getWidth(null); double imgH = img.getHeight(null); // System.out.println("Owidth: "+imgW+" Oheight:"+imgH); if (imgW > 500 || imgH > 500) { double newratio = (imgW) / (imgH); double newratio2 = (imgH) / (imgW); // System.out.println("ratio1: "+newratio+" ratio2:"+newratio2); if (newratio > newratio2) { imgW = 150; imgH = 150 * newratio2; } else { imgH = 150; imgW = newratio * 150; } } width = (int) imgW; height = (int) imgH; x=(_root._root.stageWidth/2)-(width/2)-5; yDes = (_root._root.stageHeight/2)-(height/2); y=-height; alpha=0; } public void draw(Graphics stage) { if(fadeIn && alpha<160){ alpha+=5; } if(fadeOut && alpha>=5){ alpha-=5; } y+=(yDes-y)/10; stage.setColor(new Color(0,0,0,alpha)); stage.fillRect(0,0,bg.width,bg.height); stage.drawImage(img,x,y,width,height,null); wait++; if(death && alpha<5){ _root.vacancy=true; _root.showImage=null; } } public void mousePressed(MouseEvent m) { if(wait>16){ yDes=-height-40; fadeIn=false; fadeOut=true; death=true; } } }
3fbf4261080e70d04f246ffcd994654e5bc2b1ed
[ "Java" ]
14
Java
saternius/Arbitrio
2ab0e40a1b8aa8f2596d12b93b7210eb9bd05ee0
aa14ebacc493d72ffbe860b012395d4714bbe471
refs/heads/master
<file_sep># REFERENCE ### Design References [Comments on Foreclosed](http://commentsonforeclosed.com/) ![x](http://31.media.tumblr.com/bbaac1b5bf80eae917516d19cbb1db66/tumblr_msoqhjOGj01shfct6o1_1280.png) [Architecture Workroom](http://www.architectureworkroom.eu/en/) ![x](http://25.media.tumblr.com/1395eaeb58de209972b6e7642a07dc07/tumblr_msorcs6PdN1shfct6o1_1280.png) Brown Center at [Stanford](http://brown.stanford.edu/) and [Columbia](http://brown.columbia.edu/) ![Brown Center Website](https://raw.github.com/columbiagsapp/red-review/master/images/references/brown-columbia-edu.png) ### Coding References List toggle [Public-Library](http://public-library.org/) ![x](http://31.media.tumblr.com/34487dc109bb6aaac72e10d9868324cb/tumblr_msoqhjOGj01shfct6o2_1280.png) <file_sep># GSAPP RED Review A catch-all for RED related news and a student-run tumblr (blog) for school and industry updates. The tumblr will feed content into the GSAPP website. ## Format A tumblr theme that will accomodate all posts types and include: * live feed of the next two upcoming RED-tagged events from events.gsapp.org * live feed of the latest two RED-tagged posts from ccgsapp.org * dedicated space for latest CURE news * page with directory of all current students with photos, names and links to LinkedIn profiles, highlighting program council and RED Review editors * page incorporating RED travel twitter feeds (~January each year) * page listing all previous RED newsletters (links to Mailchimp newsletters) - should there be a signup? * list of resources for RED alumni * consideration for sticky major announcements (banner? medalion?) such as "CURE Benefit MM/DD" * ## Menu Filters * All * Alumni * Alumni Profiles * Class of 2014 * CURE * Guest Speakers * Interdisciplinary * Interviews Local Static Pages * About * Current Students * Alumni Newsletters External Links (To be determined in full shortly) * [CURE] (http://www.arch.columbia.edu/centers/cure-center-urban-real-estate) * [MSRED Program](http://www.arch.columbia.edu/programs/real-estate-development) * [RED Events](http://events.gsapp.org/tagged/red) * [GSAPP Alumni](http://www.arch.columbia.edu/alumni) * [CURE Research](http://www.arch.columbia.edu/centers/cure-center-urban-real-estate/research) * [Facebook]() * [LinkedIn]() * [Twitter]() ## Roles Lead: @troyth Design: @kyongkim Dev: @ebberly <file_sep>### 0.0.1 1. Change right sidebar to have latest event at top, followed by 10 latest RED-tagged CC posts 2. Add GSAPP to bottom of left side bar 3. Scroll to "News" then fix the header 4. Incorporate photo and video post types 5. Add newsletter index page with newsletter signup link to mailchimp 6. Add current student index with headshots, names, links to linkedin <file_sep># Schedule #### Wednesday, September 4, 12pm Meeting to discuss general direction and sketch IA. @ebberly and @kyongkim will bring ideas and sketch wireframes for layout based on README. #### Tuesday, September 10, 10am-12pm Meeting to discuss wireframes @kyongkim will bring a sketch for wireframes @kyongkim and @ebberly will bring some design inspiration examples #### Date TBD Meeting with RED Student editors <file_sep>![x](https://github.com/columbiagsapp/red-review/diff_blob/eb727833369b55840eaf7e915d8296837de05e61/images/comps/main.jpg?raw=true) ![x](https://github.com/columbiagsapp/red-review/blob/master/images/comps/content.jpg?raw=true) <file_sep>$(document).ready( function() { var MONTHS = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; function fetchCCPosts(){ var cc_feed_url = "http://ccgsapp.org/red-news-json-feed"; $.ajax(cc_feed_url, { dataType: "jsonp", success: function(data) { var $html = []; data.nodes.forEach(function(post){ var html = []; var d = new Date( parseInt(post.node.created) * 1000 ); var date = d.getDate() + ' ' + MONTHS[ d.getMonth() ] + ', ' + d.getFullYear(); html.push( '<div class="cc-post">' ); html.push( '<div class="date_type">' ); html.push( '<div class="date">' ); html.push( date ); html.push( '</div>');//date html.push( '<div class="type">' ); html.push( 'CC:GSAPP' ); html.push( '</div>' );//type html.push( '</div>');//date_type html.push( '<a target="_blank" href="http://ccgsapp.org/node/' + post.node.nid + '" class="cc-title">' ); html.push( post.node.field_excerpt_value ); html.push( '</a>'); html.push( '</div>');//cc-post html = html.join(''); $html.push( html ); }); $('#cc-feed').append( $html.join('') ); $('.cc-title').hover(function(){ $(this).closest('.cc-post').css('background', 'url(http://www.columbia.edu/cu/arch/red-news/hover_bg.png)'); }, function(){ $(this).closest('.cc-post').css('background', ''); }); } }); } fetchCCPosts(); function fetchEvents(){ var events_feed_url = "http://events.gsapp.org/red-news-events-json"; $.ajax(events_feed_url, { dataType: "jsonp", success: function(data) { var $html = []; data.nodes.forEach(function(ev){ var html = []; var d = new Date( ev.node.field_event_date_value ); var minutes = d.getMinutes(); if(minutes.length < 2){ minutes = "0" + minutes; } var hours = d.getHours(); if(hours > 12){ hours = parseInt( hours ) - 12; } var date = d.getDate() + ' ' + MONTHS[ d.getMonth() ] + ', ' + d.getFullYear() + ' ' + hours + ':' + minutes; html.push( '<div class="event">' ); html.push( '<div class="date_type">' ); html.push( '<div class="date">' ); html.push( '<div class="event-date">' ); html.push( date ); html.push( '</div>' );//event-date html.push( '</div>' );//date html.push( '<div class="type">Event</div>'); html.push( '<div class="event-location">' ); html.push( ev.node.field_event_location_value ); html.push( '</div>' );//event-location html.push( '</div>' );//date_type html.push( '<a target="_blank" href="http://events.gsapp.org/node/' + ev.node.nid + '" class="event-title">' ); html.push( ev.node.title ); html.push( '</a>' ); html.push( '</div>' );//events html = html.join(''); $html.push( html ); }); $('#events-feed').append( $html.join('') ); $('.event-title').hover(function(){ $(this).closest('.event').css('background', 'url(http://www.columbia.edu/cu/arch/red-news/hover_bg.png)'); }, function(){ $(this).closest('.event').css('background', ''); }); } }); } fetchEvents(); // MOVE, FADE FEATURES FOR LOGO ------------- $(window).scroll(function(){ var scrollTop = 160; var scrolled = $(window).scrollTop(); if(scrolled >= scrollTop){ $('#header').css({position: 'fixed', top: '-145px'});//-135 $('#nav').css({position: 'fixed', marginTop: '79px'}); $('#main').css({ marginTop: "239px"}); } if(scrolled < scrollTop){ $('#header').css({position: 'relative', top: "0"}); $('#nav').css({position: 'absolute', marginTop: "0"}); $('#main').css({ marginTop: "0"}); } //var opacityfactor = scrolled/scrollTop; //$("#headerfademask").css({'opacity': opacityfactor}); });//end window scroll // CHANGE SELECTED FILTER BOX **should be made dynamic** if (document.location.pathname == "/") { $('#filterall').attr("src", 'http://www.columbia.edu/cu/arch/red-news/filteron.png'); } if (document.location.pathname == "/tagged/alumni") { $('#filteralumni').attr("src", 'http://www.columbia.edu/cu/arch/red-news/filteron.png'); } if (document.location.pathname == "/tagged/class-of-2014") { $('#filterclass2014').attr("src", 'http://www.columbia.edu/cu/arch/red-news/filteron.png'); } if (document.location.pathname == "/tagged/cure") { $('#filtercure').attr("src", 'http://www.columbia.edu/cu/arch/red-news/filteron.png'); } if (document.location.pathname == "/tagged/interdisciplinary") { $('#filterinterdis').attr("src", 'http://www.columbia.edu/cu/arch/red-news/filteron.png'); } if (document.location.pathname == "/tagged/guest") { $('#filterguest').attr("src", 'http://www.columbia.edu/cu/arch/red-news/filteron.png'); } if (document.location.pathname == "/tagged/durst") { $('#filterdurst').attr("src", 'http://www.columbia.edu/cu/arch/red-news/filteron.png'); } if (document.location.pathname == "/tagged/travel") { $('#filtertravel').attr("src", 'http://www.columbia.edu/cu/arch/red-news/filteron.png'); } $('.post-permalink-target').hover(function(){ $(this).closest('.post').css('background', 'url(http://www.columbia.edu/cu/arch/red-news/hover_bg.png)'); }, function(){ $(this).closest('.post').css('background', ''); }); }); // END $(document).ready.....
f446542e1e68368242d4cc0356fb96120009f48c
[ "Markdown", "JavaScript" ]
6
Markdown
columbiagsapp/gsapp-red-news.tumblr.com
aade783c55fc2270629c4358bddc87945f901148
c1d119279216e8f1eb4addfe1bbd41e550ead8aa
refs/heads/master
<repo_name>Misha-Mody/GUESSING-GAME-<file_sep>/C.cpp #include<iostream> #include<string> #include<windows.h> using namespace std; struct TreeNode{ string data; TreeNode *left; TreeNode *right; }; class BinaryTree{ private: TreeNode *root; public: BinaryTree() { root=NULL; begin(root); } void begin(TreeNode *&); void win(); void lose(TreeNode *&,TreeNode *&); }; void BinaryTree::begin(TreeNode *& tree) { system("COLOR FS"); char ch,ch1,ch2; if(tree!=NULL) { cout<<"\t\t\t"; cout<<tree->data<<"\n "; cin>>ch; if(ch=='N'||ch=='n') { if(tree->right!=NULL) { if(tree->right->left==NULL && tree->right->right==NULL) { cout<<"\t\t\t"; cout<<"\nIs it "<<tree->right->data<<" ?"; cin>>ch1; if(ch1=='Y'||ch1=='y') { system("COLOR 5F"); win(); } else { system("COLOR 20"); lose(tree,tree->right); } } else { system("COLOR F5"); begin(tree->right); } } else { system("COLOR 20"); lose(tree->right,tree); } } else { if(tree->left!=NULL) { if(tree->left->left!=NULL) { system("COLOR F5"); begin(tree->left); } else { cout<<"\t\t\t"; cout<<"\nIs it "<<tree->left->data<<" ?"; cin>>ch2; if(ch2=='Y'||ch2=='y') { system("COLOR 5F"); win(); } else { system("COLOR 20"); lose(tree,tree->left); } } } else { system("COLOR 20"); lose(tree->left,tree); } } } else { system("COLOR 20"); lose(tree,tree); } } void BinaryTree::win() //line 84 { char ch; system("COLOR 5F"); cout<<"\t\t\t"; cout<<"\nI win !\n"<<endl; cout<<"\t\t\t"; cout<<"\nPlay again ?[Y/N]\n"; cin>>ch; if(ch=='y'||ch=='Y') { system("COLOR 5F"); cout<<endl; begin(root); } else { cout<<"\n\t\t\t\t\t\t\t\t"; cout<<"********** THANK YOU FOR PLAYING ***************"; } } void BinaryTree::lose(TreeNode *&tree,TreeNode *&tree2) { string question; string answer; char ch,ch2; TreeNode* oneNode=new TreeNode; TreeNode* twoNode=new TreeNode; if(root==NULL) { cout<<"\n\t\t"; cout<<"******************** I KNOW NOTHING YET ***********"<<endl<<endl; cout<<"\n\t\t"; cout<<"Think and give me a person,place or thing\n"; getline(cin,answer); } else{ cout<<"\t\t\t\t"; cout<< "I give up."<<endl; cout<<"\t\t\t\t"; getline(cin,answer); cout<<"What is it?Please tell me \n"; getline(cin,answer); } if(tree !=NULL) { cout<<"\n\t\t"; cout<<"I need a question to distinguish "<<answer<<" from a\an "<<tree2->data<<".\n"; } else if(root!=NULL) { cout<<"\n\t\t"; if(tree2->left!=NULL) { if(tree2->left->left==NULL) { cout<<"I need a question to distinguish "<<answer<<"from a\an"<<tree2->left->data<<".\n"; } } } else{ cout<<"\n\t\t"; cout<<"I need a question for me to know what that is\n"; } cout<<"\n\t\t"; cout<<"Enter the question\n"; getline(cin,question); cout<<"\n\t\t"; cout<<"If answer were "<<answer<<" the answer would be? \n"; cin>>ch; if(tree!=NULL) { oneNode->data=question; if(ch=='y'||ch=='Y') { oneNode->right=tree2; oneNode->left=twoNode; } else{ oneNode->left=tree2; oneNode->right=twoNode; } tree2=oneNode; twoNode->data=answer; twoNode->right=twoNode->left=NULL; } else { tree=oneNode; oneNode->data=question; if(ch=='Y'||ch=='y') { oneNode->right=NULL; oneNode->left=twoNode; } else { oneNode->left=NULL; oneNode->right=twoNode; } twoNode->data=answer; twoNode->left=twoNode->right=NULL; } if(root==NULL) { root=tree; } cout<<"\t\t\t"; cout<<"Play Again ?(y/n)"; cin>>ch2; cout<<endl; if(ch2=='Y'||ch2=='y') begin(root); else { cout<<"\n\t\t\t"; cout<<"************THANK YOU FOR PLAYING***********"; } } void instructions() { system("COLOR D0"); cout<<"****************HELLO AND WELCOME TO THE GUESSING GAME****************\n\n\n"; cout<<"INSTRUCTIONS\n"; cout<<"1.THINK OF A WORD\n 2.THE COMPUTER WILL TRY TO GUESS IT BY ASKING YES OR NO QUESTIONS\n"; cout<<"3.THE COMPUTER WILL KEEP TRYING TILL IT WINS OR GIVES UP\n"; cout<<"4.IF THE COMPUTER GIVES UP,IT WILL STORE THE WORD IN TREE AND A RELATABLE QUESTION TO IT\n"; } int main() { instructions(); BinaryTree guessingGame; return 0; } <file_sep>/README.md # GUESSING-GAME- We used binary trees as are main data-structure and updates it dynamically to implement a guessing game in C++. The tree had nodes with attributes like a question and a “yes” or “no” answer to that question. The program would first initiate you to type in the object you want to guess , the question relating to it and the yes or no answer to the question. The program will then try to guess the object based on your answers and in case of an incorrect response the program would prompt you to type in another question-answer pair to get closer to the object and this updating the tree dynamically.
997289621a3cb4ebfb9eaa066f5e80440a416cb5
[ "Markdown", "C++" ]
2
C++
Misha-Mody/GUESSING-GAME-
b829fee778b109625ea44bae10a079533e379dda
604feeef98f52021faffeae8a755d9d1ce8f4d14
refs/heads/master
<file_sep># Weather-App-Tkinter This is a simple GUI Weather App with python Tkinter <file_sep>import tkinter as tk from tkinter import * from PIL import ImageTk, Image import requests HEIGHT = 600 WIDTH = 600 def format_weather(weather): try: name = weather['name'] desc = weather['weather'][0]['description'] temp = weather['main']['temp'] final_str = 'City: %s \nCondition: %s \nTemprature: %s (°C)' % ( name, desc, temp) except: final_str = 'There was a problem retrieving that information' return final_str def get_weather(city): weather_key = '1708c9c264af3574982477a5bcf7a9d8' url = 'https://api.openweathermap.org/data/2.5/weather' params = {'APPID': weather_key, 'q': city, 'units': 'metric'} response = requests.get(url, params=params) weather = response.json() # injuti moshakhas mikonim koja mishe dataha ro koja represent konim label['text'] = format_weather(weather) root = tk.Tk() root.geometry("400x300") root.title('Weather App') # canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH) # canvas is a container # canvas.pack() # background_image = ImageTk.PhotoImage(Image.open("background.jpg")) # background_label = tk.Label(root, image=background_image) # background_label.place(relwidth=1, relheight=1) class Example(Frame): def __init__(self, master, *pargs): Frame.__init__(self, master, *pargs) self.image = Image.open("background.jpg") self.img_copy = self.image.copy() self.background_image = ImageTk.PhotoImage(self.image) self.background = Label(self, image=self.background_image) self.background.pack(fill=BOTH, expand=YES) self.background.bind('<Configure>', self._resize_image) def _resize_image(self, event): new_width = event.width new_height = event.height self.image = self.img_copy.resize((new_width, new_height)) self.background_image = ImageTk.PhotoImage(self.image) self.background.configure(image=self.background_image) e = Example(root) e.pack() frame = tk.Frame(root, bg='#80b3ff', bd=5) frame.place(relx=0.5, rely=0.1, relwidth=0.75, relheight=0.1, anchor='n') entry = tk.Entry(frame, font=40) entry.place(relwidth=0.65, relheight=1) button = tk.Button(frame, text="Get Weather", font=40, command=lambda: get_weather(entry.get())) button.place(relx=0.7, relwidth=0.3, relheight=1) lower_frame = tk.Frame(root, bg='#80b3ff', bd=10) lower_frame.place(relx=0.5, rely=0.25, relwidth=0.75, relheight=0.6, anchor='n') label = tk.Label(lower_frame) label.place(relwidth=1, relheight=1) root.mainloop()
c6d8ff515a5719f619d4c412cd7d26760f6fea93
[ "Markdown", "Python" ]
2
Markdown
RasoulXR10/Weather-App-Tkinter
34fa79cd1743e8d0230775553c072fca979b5c27
20d49c2faddff5ba9e8096b3da77ab31ce0df378
refs/heads/master
<repo_name>Dreamy26/popschools.org<file_sep>/src/components/Home.js import React from "react"; import Navbar from "./Navbar"; import "../css/tailwind.css"; import "../App.css"; // import 'bulma/css/bulma.css' import homeimg from "../image/home.png"; import { AnimatedOnScroll } from "react-animated-css-onscroll"; import { CheckCircleFilled, InteractionFilled } from "@ant-design/icons"; import Footer from "./Footer"; import "uikit/dist/css/uikit.css"; import "uikit/dist/js/uikit"; function Home() { return ( <div> <Navbar /> <div class=""> <div className=" "> <div className="container"> <div className="flex flex-wrap"> <div className="w-full md:w-3/5 "> <div className=" px-3 py-16 "> <p className="font-extrabold text-blue-900 text-center md:text-left text-5xl"> Welcome to{" "} <span class="text-6xl text-gray-7 900" > PopSchools </span>{" "} </p> <p className="text-gray-600 py-4 text-2xl "> We exist today to create an inclusive community for pre-career and early-career software developers, provide opportunities for networking, and make pathways to paying work in tech roles </p> <div className="grid grid-cols-2 md:grid-cols-2 py-4 gap-4"> <div> <a href="https://circle.popschools.com/c/welcome"> <button class="bg-transparent hover:bg-gray-900 text-gray-700 font-semibold hover:text-white py-2 px-4 border border-gray-500 hover:border-transparent rounded-lg"> Join our community </button> </a> </div> <div></div> </div> </div> </div> <div className="w-full md:w-2/5 "> <AnimatedOnScroll animationIn="bounceInRight"> <div class="px-3 md:py-24 object-right "> <img src={homeimg} alt="" className="w-full rounded-lg shadow-lg" /> </div> </AnimatedOnScroll> </div> </div> </div> </div> </div> {/* service are placed here */} <div className=" mb-8 bgpro"> <div className="container"> <p className="text-gray-600 md:px-32 text-4xl font-bold text-center py-2"> PopSchools is meant to create access to a safe and inclusive community, mutual aid, and paying work opportunities through apprenticeships to early-career technologists </p> </div> <div className="container py-8"> <div className="grid grid-cols-2 md:grid-cols-4 gap-8"> <div className="ml-3 mr-3 px-4 bg-gray-300 rounded-lg shadow-lg" data-aos="zoom-in-down" data-aos-duration="1000" > <p className="text-center text-6xl text-gray-800"> <CheckCircleFilled /> </p> <p className="text-center py-3 text-sm font-bold text-gray-800"> {" "} Career Guidance </p> </div> <div className="ml-3 mr-3 px-4 bg-gray-300 rounded-lg shadow-lg" data-aos="flip-right" > <p className="text-center text-6xl text-gray-800"> <InteractionFilled /> </p> <p className="text-center py-3 text-sm font-bold text-gray-800"> {" "} Study Group </p> </div> <div className=" ml-3 mr-3 px-4 bg-gray-300 rounded-lg shadow-lg" data-aos="fade-down" data-aos-duration="1000" > <p className="text-center text-6xl text-gray-800"> <CheckCircleFilled /> </p> <p className="text-center py-3 text-sm font-bold text-gray-800"> {" "} Opportunities </p> </div> <div className=" ml-3 mr-3 px-4 bg-gray-300 rounded-lg shadow-lg" data-aos="fade-down" data-aos-duration="1000" > <p className="text-center text-6xl text-gray-800"> <CheckCircleFilled /> </p> <p className="text-center py-3 text-sm font-bold text-gray-800"> {" "} Daily Challenges </p> </div> </div> </div> </div> {/* footer */} <Footer /> </div> ); } export default Home; <file_sep>/README.md # PopSchools.org Website (WIP) We are in the process of relaunching PopSchools and building the community and codebase in public. Eventually the popschools.org site will be an entry point to all things PopSchools. We are getting set up now to be able to accept code and content contributions. Sign up and [join our community](https://circle.popschools.com) if you would like to participate in our projects. <file_sep>/src/components/Footer.js import React from "react"; import Logo from "../image/logo.png"; import "../css/tailwind.css"; import "../App.css"; import { GithubFilled, TwitterCircleFilled } from "@ant-design/icons"; // import 'bulma/css/bulma.css' function Footer() { return ( <> <div className="mtop"> <div className="container py-8"> <div className="flex flex-wrap "> <div className="w-full md:w-1/3 "> <img src={Logo} className="w-64 " alt="popschools" /> </div> <div className="w-full md:w-2/3"> <div className="grid grid-cols-2 md:grid-cols-3"> <div> <p className="py-3 px-3 text-gray-600 font-bold"> On Social Media </p> <p className="text-gray-600 py-4 px-3"> Follow us on our social media </p> <hr /> <a href="https://github.com/PopSchools/popschools.org"> <span className=" px-3 text-gray-600 text-4xl inline-block"> <GithubFilled /> </span>{" "} </a> <a href="https://twitter.com/popschoolsorg"> <span className="px-3 text-gray-600 text-4xl inline-block"> <TwitterCircleFilled /> </span>{" "} </a> </div> </div> <div className="grid grid-cols-2 md:grid-cols-2"> <div className="py-6"> <span className="text-left text-gray-600 py-2 px-3"> <span dangerouslySetInnerHTML={{ __html: "&copy;" }} /> {new Date().getFullYear()} PopSchools, Inc. </span> </div> </div> </div> </div> </div> </div> </> ); } export default Footer;
0f84270ce156e889e83fcc48501836d79501d8d7
[ "JavaScript", "Markdown" ]
3
JavaScript
Dreamy26/popschools.org
c46b9016113516fa6d9aea07c73d2561ca142c6b
aa026ccebd9fe81660ca8c55e94339608297ffdf
refs/heads/master
<repo_name>srtsignin/config<file_sep>/configure.sh kubectl apply -f admin-user-cluster-role-binding.yaml kubectl apply -f admin-user-service-account.yaml helm init --service-account=admin-user helm repo add rook-beta https://charts.rook.io/beta helm repo update helm install --name cert-manager --namespace kube-system stable/cert-manager helm install --namespace rook-ceph-system rook-beta/rook-ceph kubectl apply -f srtsignin-namespaces.yaml kubectl create secret generic srtsignin-role-secret --from-file=./secrets/auth-keys.properties kubectl create secret generic srtsignin-cardfire-secret --from-file=./secrets/secrets-cf.properties kubectl create secret generic srtsignin-active-users-secret --from-file=./secrets/active-users-config.json kubectl create secret generic srtsignin-data-service-secret --from-file=./secrets/data-service-conf.json kubectl create secret generic srtsignin-registration-secret --from-file=./secrets/registration-config.json kubectl create secret generic srtsignin-role-secret -n stage --from-file=./stage-secrets/auth-keys.properties kubectl create secret generic srtsignin-cardfire-secret -n stage --from-file=./stage-secrets/secrets-cf.properties kubectl create secret generic srtsignin-active-users-secret -n stage --from-file=./stage-secrets/active-users-config.json kubectl create secret generic srtsignin-data-service-secret -n stage --from-file=./stage-secrets/data-service-conf.json kubectl create secret generic srtsignin-registration-secret -n stage --from-file=./stage-secrets/registration-config.json kubectl apply -f .
d25dbbd0b6751fbcf8653db8bc134228a1015e23
[ "Shell" ]
1
Shell
srtsignin/config
54d5b865d2dad52786c62ad9d92b330f5206a0a1
fb68b77e44f649e8cd208b319b7966cd673fd43f
refs/heads/master
<file_sep>package competicao; import robo.Robo; public class Competidor { private String nome; private robo.Robo roboDoCompetidor; private String relatorio = ""; public Competidor(String nome, Robo robo) { this.nome = nome; roboDoCompetidor = robo; relatorio = nome + "\nRobo: " + roboDoCompetidor.getNome() + "\n| Braço: " + roboDoCompetidor.getBraco().getNome() + "\n| Perna: " + roboDoCompetidor.getPerna().getNome() + "\n| Torso: " + roboDoCompetidor.getTorso().getNome() + "\nHP: " + roboDoCompetidor.getHP() + "\nATK: " + roboDoCompetidor.getATK() + "\nDEF: " + roboDoCompetidor.getDEF() + "\nAGL: " + roboDoCompetidor.getAGL() + "\n\n"; } public String getNome() { return nome; } public robo.Robo getRobo() { return roboDoCompetidor; } public String getRelatorio() { return relatorio; } public void setRelatorio(String relatorio) { this.relatorio += relatorio; } } <file_sep>package robo; public class Perna extends Peca { private int agl; public Perna(String nome, int def, int agl) { super(nome, def); this.agl = agl; } public int getAGL() { return agl; } } <file_sep>package robo; import java.util.Random; public class Prefab { private static Random random = new Random(); public static Braco[] braco = { new Braco("Braço padrão", 20, 20), new Braco("Braço forte", 15, 25), new Braco("Braço resistente", 25, 15) }; public static Perna[] perna = { new Perna("Perna padrão", 20, 20), new Perna("Perna agil", 15, 25), new Perna("Perna forte", 25, 15) }; public static Torso[] torso = { new Torso("Torso padrão", 20, 50), new Torso("Torso grande", 10, 60), new Torso("Torso resistente", 30, 40) }; // Relatorios para a IU public static String bracoRelatorio = braco[0].getNome() + "\nDEF: " + braco[0].getDEF() + "\nATK: " + braco[0].getATK() + "\n\n" + braco[1].getNome() + "\nDEF: " + braco[1].getDEF() + "\nATK: " + braco[1].getATK() + "\n\n" + braco[2].getNome() + "\nDEF: " + braco[2].getDEF() + "\nATK: " + braco[2].getATK() + "\n\n"; public static String pernaRelatorio = perna[0].getNome() + "\nDEF: " + perna[0].getDEF() + "\nAGL: " + perna[0].getAGL() + "\n\n" + perna[1].getNome() + "\nDEF: " + perna[1].getDEF() + "\nAGL: " + perna[1].getAGL() + "\n\n" + perna[2].getNome() + "\nDEF: " + perna[2].getDEF() + "\nAGL: " + perna[2].getAGL() + "\n\n"; public static String torsoRelatorio = torso[0].getNome() + "\nDEF: " + torso[0].getDEF() + "\nHP: " + torso[0].getHP() + "\n\n" + torso[1].getNome() + "\nDEF: " + torso[1].getDEF() + "\nHP: " + torso[1].getHP() + "\n\n" + torso[2].getNome() + "\nDEF: " + torso[2].getDEF() + "\nHP: " + torso[2].getHP() + "\n\n"; // Opções para a IU public static String[] bracoOps = { braco[0].getNome(), braco[1].getNome(), braco[2].getNome() }; public static String[] pernaOps = { perna[0].getNome(), perna[1].getNome(), perna[2].getNome() }; public static String[] torsoOps = { torso[0].getNome(), torso[1].getNome(), torso[2].getNome() }; // Monta robo com peças aleatorias public static Robo pecasAleatorias(String nome) { return new Robo(nome, braco[random.nextInt(3)], perna[random.nextInt(3)], torso[random.nextInt(3)]); } } <file_sep>package robo; public class Peca { private String nome; private int def; public Peca(String nome, int def) { super(); this.nome = nome; this.def = def; } public String getNome() { return nome; } public int getDEF() { return def; } }
b8f28c3ee6692216775ec8fabf7a1081a03a1699
[ "Java" ]
4
Java
evandro-crr/t2-INE5402
c393dd917c0a45e0ab46bd61c082a4c4e04541b4
dc40dee0a551b4c081efc0a0579b1ff21d238653
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package dictionary; /** * * @author Administrator */ public class DictionayApp extends javax.swing.JFrame { /** * Creates new form DictionayApp */ public DictionayApp() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane8 = new javax.swing.JScrollPane(); jRadioButton1 = new javax.swing.JRadioButton(); jRadioButton2 = new javax.swing.JRadioButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea2 = new javax.swing.JTextArea(); jButton2 = new javax.swing.JButton(); jScrollPane3 = new javax.swing.JScrollPane(); jButton1 = new javax.swing.JButton(); jScrollPane4 = new javax.swing.JScrollPane(); jList1 = new javax.swing.JList<>(); jScrollPane6 = new javax.swing.JScrollPane(); jTextField1 = new javax.swing.JTextField(); jScrollPane2 = new javax.swing.JScrollPane(); jLabel2 = new javax.swing.JLabel(); jScrollPane5 = new javax.swing.JScrollPane(); jRadioButton3 = new javax.swing.JRadioButton(); jScrollPane7 = new javax.swing.JScrollPane(); jRadioButton4 = new javax.swing.JRadioButton(); jPanel1 = new javax.swing.JPanel(); jRadioButton1.setText("jRadioButton1"); jScrollPane8.setViewportView(jRadioButton1); jRadioButton2.setText("jRadioButton2"); jRadioButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton2ActionPerformed(evt); } }); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setPreferredSize(new java.awt.Dimension(654, 432)); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jTextArea2.setColumns(20); jTextArea2.setRows(5); jScrollPane1.setViewportView(jTextArea2); getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 100, 360, 310)); jButton2.setText("Dịch văn bản"); getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 20, 110, 30)); jButton1.setText("Thêm"); jButton1.setToolTipText("java"); jButton1.setMaximumSize(new java.awt.Dimension(23, 23)); jButton1.setMinimumSize(new java.awt.Dimension(23, 23)); jButton1.setPreferredSize(new java.awt.Dimension(20, 23)); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jScrollPane3.setViewportView(jButton1); getContentPane().add(jScrollPane3, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 20, 90, 30)); jList1.setModel(new javax.swing.AbstractListModel<String>() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; public int getSize() { return strings.length; } public String getElementAt(int i) { return strings[i]; } }); jScrollPane4.setViewportView(jList1); getContentPane().add(jScrollPane4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 100, 250, 310)); jScrollPane6.setViewportView(jTextField1); getContentPane().add(jScrollPane6, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 270, 50)); jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/055824786958bce.jpeg"))); // NOI18N jScrollPane2.setViewportView(jLabel2); getContentPane().add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); jRadioButton3.setText("jRadioButton3"); jRadioButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton3ActionPerformed(evt); } }); jScrollPane5.setViewportView(jRadioButton3); getContentPane().add(jScrollPane5, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 60, 110, 40)); jRadioButton4.setText("jRadioButton4"); jScrollPane7.setViewportView(jRadioButton4); getContentPane().add(jScrollPane7, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 60, 110, 40)); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 105, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 70, Short.MAX_VALUE) ); getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(680, 110, -1, 70)); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButton1ActionPerformed private void jRadioButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton3ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jRadioButton3ActionPerformed private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jRadioButton2ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(DictionayApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(DictionayApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(DictionayApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(DictionayApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new DictionayApp().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel2; private javax.swing.JList<String> jList1; private javax.swing.JPanel jPanel1; private javax.swing.JRadioButton jRadioButton1; private javax.swing.JRadioButton jRadioButton2; private javax.swing.JRadioButton jRadioButton3; private javax.swing.JRadioButton jRadioButton4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JScrollPane jScrollPane5; private javax.swing.JScrollPane jScrollPane6; private javax.swing.JScrollPane jScrollPane7; private javax.swing.JScrollPane jScrollPane8; private javax.swing.JTextArea jTextArea2; private javax.swing.JTextField jTextField1; // End of variables declaration//GEN-END:variables }
a74bc141ecbe763bc638d50743157c7524268522
[ "Java" ]
1
Java
buidangthutra/BTL
bb663456f97e3222ecc5c83dea689f28176559c8
964c4f292fd0a183e3f470de345bd5a5ac754f60
refs/heads/master
<repo_name>AleksandrBoguckiy/01-first-project<file_sep>/src/redux/dialogs-reducer.js const SEND_MESSAGE = 'SEND-MESSAGE'; const UPDATE_SEND_MESSAGE_TEXT = 'UPDATE-SEND-MESSAGE-TEXT'; let initialState = { dialogs: [ {id: '1', name: 'Oleg'}, {id: '2', name: 'Egor'}, {id: '3', name: 'Mariya'}, {id: '4', name: 'Aleksandr'}, {id: '5', name: 'Ruslan'}, {id: '6', name: 'Irina'} ], messages: [ {id: '1', message: 'Hi!'}, {id: '2', message: 'How are you?'}, {id: '3', message: 'Hey, are you there?'}, {id: '4', message: 'Hello Friend! Yes I am listening to you'} ], newMessageText: '' } const dialogsReducer = (state = initialState, action) => { switch (action.type) { case 'SEND-MESSAGE': let newMessage = {id: 5, message: state.newMessageText} return { ...state, messages: [...state.messages, newMessage], newMessageText: ('') } case 'UPDATE-SEND-MESSAGE-TEXT': return { ...state, newMessageText: action.newText } default: return state; } } export const sendMessageActionCreator = () => ({type: SEND_MESSAGE}); export const updateSendMessageTextActionCreator = (text) => ({type: UPDATE_SEND_MESSAGE_TEXT, newText: text}); export default dialogsReducer;<file_sep>/src/Components/Dialogs/Dialogs.jsx import React from 'react'; import style from './Dialogs.module.css'; import DialogItem from "./DialogItem/DialogItem"; import Message from "./Message/Message"; const Dialogs = (props) => { let dialogElements = props.dialogsPage.dialogs.map(d => <DialogItem name={d.name} key={d.id} id={d.id} />); let messageElements = props.dialogsPage.messages.map(m => <Message message={m.message} key={m.id} />); let newMessage = React.createRef(); let sendMessage = () => { props.sendMessage(); } let onMessageChange = () => { let text = newMessage.current.value; props.updateSendMessageText(text); } return ( <div className={style.dialogs}> <div className={style.dialogItems}> { dialogElements } </div> <div className={style.messages}> { messageElements } </div> <div className={style.inputForm}> <div> <textarea onChange={onMessageChange} ref={newMessage} placeholder={'Write a message...'} value={props.dialogsPage.newMessageText} /> </div> <div> <button onClick={sendMessage} className={style.btn + " " + style.btn1}>Send message</button> </div> </div> </div> ) } export default Dialogs;<file_sep>/src/Components/common/Preloader.js import React from "react"; import style from './Preloader.module.css'; const Preloader = (props) => { return <div className = {style.lds_roller} > <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </div> } export default Preloader;<file_sep>/src/redux/sidebar-reducer.js let initialState = { myFriends: [ {id: '1', name: 'Alex'}, {id: '2', name: 'Romeo'}, {id: '3', name: 'Nik'} ] } const sidebarReducer = (state = initialState, action) => { return state; } export default sidebarReducer;<file_sep>/src/Components/Login/Login.jsx import React from 'react'; import style from './Login.module.css'; const Login = () => { return <h className={style.login}> Login </h> } export default Login;<file_sep>/src/Components/Profile/ProfileInfo/ProfileStatus.jsx import React, {useEffect} from 'react'; import style from './ProfileInfo.module.css'; const ProfileStatus = (props) => { let [editMode, setEditMode] = React.useState(false); let [status, setStatus] = React.useState(props.status); useEffect(() => { setStatus(props.status) }, [props.status]); const activateEditMode = () => { setEditMode(true); } const deactivateEditMode = () => { setEditMode(false); props.updateUserStatus(status); } const onStatusChange = (e) => { setStatus(e.currentTarget.value); } return ( <div className={style.status}> { editMode ? <div> <input className={style.edit_status} onChange={onStatusChange} onBlur={deactivateEditMode} type='text' value={status} autoFocus={true} /> </div> : <div> <span onDoubleClick={activateEditMode}>{props.status || '-----'}</span> </div> } </div> ) }; export default ProfileStatus;<file_sep>/src/redux/profile-reducer.js import {profileAPI} from "../api/api"; const ADD_POST = 'ADD-POST'; const UPDATE_NEW_POST_TEXT = 'UPDATE-NEW-POST-TEXT'; const SET_USER_PROFILE = 'SET-USER-PROFILE'; const SET_USER_STATUS = 'SET-USER-STATUS'; let initialState = { posts: [ {id: '1', message: 'Hey, how are you?', like: '15'}, {id: '2', message: "It's my first post!", like: '23'}, ], newPostText: '', profile: null, status: '' } const profileReducer = (state = initialState, action) => { switch (action.type) { case 'ADD-POST': let newPost = {id: 3, message: state.newPostText, like: 2}; return { ...state, posts: [newPost, ...state.posts], newPostText: ('') }; case 'UPDATE-NEW-POST-TEXT': return { ...state, newPostText: action.newText }; case 'SET-USER-PROFILE': return { ...state, profile: action.profile }; case 'SET-USER-STATUS': return { ...state, status: action.status }; default: return state; } } export const addPostActionCreator = () => ({type: ADD_POST}); export const updateNewPostTextActionCreator = (text) => ({type: UPDATE_NEW_POST_TEXT, newText: text}); export const setUserProfile = (profile) => ({type: SET_USER_PROFILE, profile}); export const setUserStatus = (status) => ({type: SET_USER_STATUS, status}) export const getUserProfile = (userId) => { return (dispatch) => { profileAPI.getProfile(userId).then(data => { dispatch(setUserProfile(data)); }); } } export const getUserStatus = (userId) => { return (dispatch) => { profileAPI.getUserStatus(userId).then(data => { dispatch(setUserStatus(data)); }); } } export const updateUserStatus = (status) => { return (dispatch) => { profileAPI.updateUserStatus(status).then(data => { if (data.resultCode === 0) { dispatch(setUserStatus(status)); } }); } } export default profileReducer;<file_sep>/src/redux/store.js import profileReducer from "./profile-reducer"; import dialogsReducer from "./dialogs-reducer"; import sidebarReducer from "./sidebar-reducer"; let store = { _state: { profilePage: { posts: [ {id: '1', message: 'Hey, how are you?', like: '15'}, {id: '2', message: "It's my first post!", like: '23'}, ], newPostText: '' }, dialogsPage: { dialogs: [ {id: '1', name: 'Oleg'}, {id: '2', name: 'Egor'}, {id: '3', name: 'Mariya'}, {id: '4', name: 'Aleksandr'}, {id: '5', name: 'Ruslan'}, {id: '6', name: 'Irina'} ], messages: [ {id: '1', message: 'Hi!'}, {id: '2', message: 'How are you?'}, {id: '3', message: 'Hey, are you there?'}, {id: '4', message: 'Hello Friend! Yes I am listening to you'} ], newMessageText: '' }, sidebar: { myFriends: [ {id: '1', name: 'Alex'}, {id: '2', name: 'Romeo'}, {id: '3', name: 'Nik'} ] } }, _callSubscriber () { console.log('State changed') }, subscribe (observer) { this._callSubscriber = observer; }, getState() { return this._state }, dispatch(action) { //{type:'ADD-POST' and 'SEND-MESSAGE'} this._state.profilePage = profileReducer(this._state.profilePage, action); this._state.dialogsPage = dialogsReducer(this._state.dialogsPage, action); this._state.sidebar = sidebarReducer(this._state.sidebar, action); this._callSubscriber(this._state); } } export default store; window.store = store;
af8cea53aea01b6faabbfccc0984865926fe8c62
[ "JavaScript" ]
8
JavaScript
AleksandrBoguckiy/01-first-project
ee2b72d5d5a3e85484e0bcb834e6605e60a4073a
890ce9701134fc6943771787952b8bbdcc56374e
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace MyKnockoutTest.APIControlllers { [RoutePrefix("api")] public class AdventureWorks : ApiController { } }<file_sep>function MyGridViewModel() { var self = this; self.chosenDetail = ko.observable(); self.masterItems = ko.observableArray(); self.detailItems = ko.observableArray(); self.chosenMasterItem = ko.observable(); self.ItemChosen = function (masterItem) { var chosenDetail = self.detailItems().filter(function (detailItem) { return detailItem.masterid() === masterItem.id() }); if(chosenDetail.length > 0) { self.chosenDetail(chosenDetail[0]); } }; }<file_sep>function DetailRecordModel(id, title, masterid) { var self = this; self.id = ko.observable(); self.title = ko.observable(); self.masterid = ko.observable(); self.id(id); self.title(title); self.masterid(masterid); self.detailRecord = ko.computed(function () { return "ID: " + self.id() + " Title: " + self.title() + " MasterID: " + self.masterid(); }, this); };<file_sep>function MasterRecordModel(id, title) { var self = this; self.id = ko.observable(); self.title = ko.observable(); self.id(id); self.title(title); self.masterRecordString = ko.computed(function () { return "ID: " + self.id() + " Title: " + self.title(); }, this); }
528c8b5e455cc8a230bf9af9fea857118520cb14
[ "JavaScript", "C#" ]
4
C#
jgelinas33/MyKnockoutTesting
16204112e7d4ad375013dfdfd78d5e79938329c2
e74f9a53c4e0ef34a574e02d91e84e82fbc3d04a
refs/heads/master
<repo_name>robinske/flask-app<file_sep>/app_config.py import logging import os BASE_DIR = os.path.abspath(os.path.dirname(__file__)) TIMEZONE = 'America/Los_Angeles' # Number of times a password is hashed BCRYPT_LOG_ROUNDS = 12 # Configuration of a Gmail account for sending mails MAIL_SERVER = 'smtp.gmail.com' MAIL_PORT = 465 MAIL_USE_TLS = False MAIL_USE_SSL = True MAIL_USERNAME = os.environ['EMAIL_USER'] MAIL_PASSWORD = os.environ['EMAIL_PASSWORD'] MAIL_SENDER = os.environ['EMAIL_SENDER'] LOG_LEVEL = logging.DEBUG LOG_FILENAME = 'activity.log' SECRET_KEY = os.environ['SECRET_KEY'] SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] SQLALCHEMY_TRACK_MODIFICATIONS = True <file_sep>/run.sh #!/bin/bash virtualenv env source env/bin/activate export DATABASE_URL='postgresql://localhost:5432/boilerplate' export SECRET_KEY='super-secret' gunicorn wsgi:app <file_sep>/test-mail.py from flask import Flask from flask.ext.mail import Mail, Message app = Flask(__name__) # app.config.update( # DEBUG=True, # MAIL_SERVER='smtp.gmail.com', # MAIL_PORT=465, # MAIL_USE_TLS=True, # ) mail = Mail(app) def sendmail(): msg = Message( 'Subject', sender='<EMAIL>', recipients=['<EMAIL>']) msg.body = "Body here" mail.send(msg) sendmail() <file_sep>/setup.sh #!/bin/bash set -e export DATABASE_URL='postgresql://localhost:5432/boilerplate' export SECRET_KEY='super-secret' virtualenv env source env/bin/activate make install python manage.py initdb <file_sep>/app/__init__.py from flask import Flask, render_template app = Flask(__name__) # Setup the app with the config.py file app.config.from_object('app_config') # Setup the database from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy(app) # Setup the mail server from flask_mail import Mail mail = Mail(app) # Setup the password crypting from flask_bcrypt import Bcrypt bcrypt = Bcrypt(app) # Import the views from app.views import main, user, error app.register_blueprint(user.userbp) # Setup the user login process from flask_login import LoginManager from app.models import User login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'userbp.signin' @login_manager.user_loader def load_user(email): return User.query.filter(User.email == email).first() <file_sep>/manage.py from flask_script import Manager, prompt_bool from flask_migrate import Migrate, MigrateCommand from termcolor import colored from app import app, db, models manager = Manager(app) @manager.command def initdb(): ''' Create the Postgresql tables. ''' db.create_all() print(colored('The Postgresql tables have been created', 'green')) @manager.command def dropdb(): ''' Delete the Postgresql database data. ''' if prompt_bool('Are you sure you want to lose all your Postgresql data?'): db.drop_all() print(colored('The Postgresql data has been deleted', 'green')) if __name__ == '__main__': manager.run()
dd69c261e092517c3599fde6c8e88446024dc435
[ "Python", "Shell" ]
6
Python
robinske/flask-app
fc60cf7dce27273559ac97262d9ce8c025fc1923
54a863e0e49075316e119046f7ade775dc5ed0d3
refs/heads/main
<repo_name>shawn83924/NetworkTest<file_sep>/Assets/Scripts/Udp/480P/UdpSender480p.cs using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Net; using System.Net.Sockets; using System.Threading; using UnityEngine; public class UdpSender480p : MonoBehaviour { Camera Cam; Texture2D image; /// <summary> /// 原始影像畫面 /// </summary> byte[][] ViewData = new byte[2][]; /// <summary> /// 傳送的對象IP跟port /// </summary> private IPEndPoint ipEndPoint; /// <summary> /// UDP傳送者,也就是自己 /// </summary> private UdpClient udpClient; /// <summary> /// 負責進行圖形處理的Thread /// </summary> private Thread[] ViewDataProcessing = new Thread[2]; /// <summary> /// 中斷圖形處理 Thread 的 Gate /// </summary> private AutoResetEvent[] DataProcessGate = new AutoResetEvent[2]; /// <summary> /// 傳送的Frame號碼 /// </summary> private int FrameNum; // Start is called before the first frame update void Start() { Cam = GetComponent<Camera>(); image = new Texture2D(Cam.targetTexture.width, Cam.targetTexture.height, TextureFormat.RGB24, false); ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5555); //ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5555); udpClient = new UdpClient(); FrameNum = 0; for (int i = 0; i < DataProcessGate.Length; i++) { DataProcessGate[i] = new AutoResetEvent(false); } for (int i = 0; i < ViewDataProcessing.Length; i++) { ViewDataProcessing[i] = new Thread(ProcessView); } for (int i = 0; i < ViewDataProcessing.Length; i++) { ViewDataProcessing[i].Start(i); } StartCoroutine(ProcessGraphic()); } /// <summary> /// 進行圖形壓縮以及傳送 /// </summary> /// <param name="Th_Num">Thread Number</param> private void ProcessView(object Th_Num) { int ThreadNumber = (int)Th_Num; while (true) { //先中斷執行序,等待呼叫執行 DataProcessGate[ThreadNumber].WaitOne(); //壓縮影像 byte[] CompressView = Compress(ViewData[ThreadNumber]); lock (udpClient) { //開始切割分批傳送 for (int i = 0, j = 0; i < CompressView.Length; i += 65400, j++) { //建立要傳送的封包 byte[] SendBuffer; //設定封包大小,最大為 65412,最後 12byte 是作為驗證使用欄位 if (i + 65400 <= CompressView.Length) { SendBuffer = new byte[65412]; } else { SendBuffer = new byte[CompressView.Length - i + 12]; } //複製壓縮封包區段給傳送封包 Array.Copy(CompressView, i, SendBuffer, 0, SendBuffer.Length - 12); //在後綴加上 Frame number, 切割 Number, 總壓縮長度 Array.Copy(BitConverter.GetBytes(FrameNum), 0, SendBuffer, SendBuffer.Length - 12, 4); Array.Copy(BitConverter.GetBytes(j), 0, SendBuffer, SendBuffer.Length - 8, 4); Array.Copy(BitConverter.GetBytes(CompressView.Length), 0, SendBuffer, SendBuffer.Length - 4, 4); //送出封包 try { //傳送 udpClient.Send(SendBuffer, SendBuffer.Length, ipEndPoint); } catch (Exception e) { Debug.Log(e); } } FrameNum++; } } } IEnumerator ProcessGraphic() { //處理圖形的Thread編號 int ProcessNumber = 0; while (true) { //掃描有無等待的Thread int i; for (i = 0; i < ViewDataProcessing.Length; i++) { if (ViewDataProcessing[i].ThreadState == ThreadState.WaitSleepJoin) { ProcessNumber = i;//有等待的 Thread 就紀錄 Thread 編號 break; } } //無等待的Thread就等待至下一個Frame if (i >= ViewDataProcessing.Length) { yield return null; continue; } RenderTexture currentRT = RenderTexture.active; RenderTexture.active = Cam.targetTexture; Cam.Render(); image.ReadPixels(new Rect(0, 0, Cam.targetTexture.width, Cam.targetTexture.height), 0, 0); image.Apply(); RenderTexture.active = currentRT; ViewData[ProcessNumber] = image.GetRawTextureData(); DataProcessGate[ProcessNumber].Set(); yield return null; } } /// <summary> /// 壓縮演算法 /// </summary> /// <param name="data"></param> /// <returns></returns> public byte[] Compress(byte[] data) { MemoryStream ms = new MemoryStream(); GZipStream zip = new GZipStream(ms, System.IO.Compression.CompressionLevel.Fastest, true); zip.Write(data, 0, data.Length); zip.Close(); ms.Position = 0; byte[] compressed = new byte[ms.Length]; ms.Read(compressed, 0, compressed.Length); byte[] gzBuffer = new byte[compressed.Length + 4]; Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length); Buffer.BlockCopy(BitConverter.GetBytes(data.Length), 0, gzBuffer, 0, 4); return gzBuffer; } /// <summary> /// 解壓縮演算法 /// </summary> /// <param name="data"></param> /// <returns></returns> public byte[] Decompress(byte[] data) { MemoryStream ms = new MemoryStream(); int msgLength = BitConverter.ToInt32(data, 0); ms.Write(data, 4, data.Length - 4); byte[] buffer = new byte[msgLength]; ms.Position = 0; GZipStream zip = new GZipStream(ms, CompressionMode.Decompress); zip.Read(buffer, 0, buffer.Length); zip.Close(); return buffer; } void OnApplicationQuit() { udpClient.Close(); CloseThread(); } /// <summary> /// 關閉Thread /// </summary> void CloseThread() { //關閉執行緒 for (int i = 0; i < ViewDataProcessing.Length; i++) { ViewDataProcessing[i].Interrupt(); ViewDataProcessing[i].Abort(); } } } <file_sep>/README.md # NetworkTest 網路測試以及實驗的專案 <file_sep>/Assets/Scripts/Udp/1080P/UdpSender1080p.cs using UnityEngine; using System.IO; using System.IO.Compression; using System.Net.Sockets; using System.Net; using System.Threading; using System; public class UdpSender1080p : MonoBehaviour { Camera Cam; Texture2D image; /// <summary> /// 原始影像畫面 /// </summary> byte[] ViewData = new byte[1920 * 1080 * 3]; /// <summary> /// 切分的影像,長度為原始影像的 1/8 + 2 bytes,1 byte 會作為切割編號,1 byte會作為fram編號 /// </summary> byte[][] ViewFragment = new byte[8][]; /// <summary> /// 傳送的對象IP跟port /// </summary> private IPEndPoint ipEndPoint; /// <summary> /// UDP傳送者,也就是自己 /// </summary> private UdpClient udpClient; /// <summary> /// 負責進行圖形處理的Thread /// </summary> private Thread[] ViewDataProcessing = new Thread[8]; /// <summary> /// 中斷圖形處理 Thread 的 Gate /// </summary> private AutoResetEvent[] DataProcessGate = new AutoResetEvent[8]; /// <summary> /// 計算圖形的 Thread Counter /// </summary> private int ProcessingCount = 8; /// <summary> /// 傳送的Frame編號 /// </summary> private byte[] FramNum = new byte[1]; private void Start() { Application.targetFrameRate = 60; Cam = GetComponent<Camera>(); image = new Texture2D(Cam.targetTexture.width, Cam.targetTexture.height, TextureFormat.RGB24, false); ipEndPoint = new IPEndPoint(IPAddress.Parse("192.168.0.173"), 5555); udpClient = new UdpClient(); //初始化切分後影像的空間 for (int i = 0; i < ViewFragment.Length; i++) { ViewFragment[i] = new byte[1920 * 1080 * 3 / 8 + 2]; } //初始設定8個影像處理的thread for (int i = 0; i < ViewDataProcessing.Length; i++) { ViewDataProcessing[i] = new Thread(ProcessView); } //初始設定 Thread Gate for (int i = 0; i < DataProcessGate.Length; i++) { DataProcessGate[i] = new AutoResetEvent(false); } //開始執行影像處理Thread for (int i = 0; i < ViewDataProcessing.Length; i++) { ViewDataProcessing[i].Start(i); } #region 影像存檔測試 /* RenderTexture currentRT = RenderTexture.active; RenderTexture.active = Cam.targetTexture; Cam.Render(); image.ReadPixels(new Rect(0, 0, Cam.targetTexture.width, Cam.targetTexture.height), 0, 0); image.Apply(); RenderTexture.active = currentRT; byte[] bytes = image.EncodeToPNG(); File.WriteAllBytes(Application.dataPath + "/../SavedScreen.png", bytes); */ #endregion } private void ProcessView(object obj) { int ProcessNumber = (int)obj; while (true) { //先中斷執行序,等待呼叫執行 DataProcessGate[ProcessNumber].WaitOne(); //切分圖像 SplitView(ProcessNumber); //壓縮圖像 byte[] CompressView = Compress(ViewFragment[ProcessNumber]); //傳送圖像 lock (udpClient) { udpClient.Send(CompressView, CompressView.Length, ipEndPoint); ProcessingCount++; } } } private void Update() { //如果 ProcessingCount 大於等於 8 ,就更新影像 if (ProcessingCount >= 8) { RenderTexture currentRT = RenderTexture.active; RenderTexture.active = Cam.targetTexture; Cam.Render(); image.ReadPixels(new Rect(0, 0, Cam.targetTexture.width, Cam.targetTexture.height), 0, 0); image.Apply(); RenderTexture.active = currentRT; ViewData = image.GetRawTextureData(); //更新完影像後先將 ProcessingCount 歸 0 ,防止影像更新 ProcessingCount = 0; //fram 數加 1 lock (FramNum) { FramNum[0] += 1; if (FramNum[0] == 200) { FramNum[0] = 0; }//限制 FramNum 數字為 0~199 } //開始處理影像 for (int i = 0; i < DataProcessGate.Length; i++) { //處理圖形並傳送 DataProcessGate[i].Set(); } } } /// <summary> /// 切分圖像函示,將原始圖像依照 Byte 切分 8 等分 /// </summary> /// <param name="number">切分編號,數字為 0~7 </param> public void SplitView(int number) { //設定切割編號 ViewFragment[number][ViewData.Length / 8] = (byte)number; //設定fram編號 ViewFragment[number][ViewData.Length / 8 + 1] = FramNum[0]; // i 為原始資料編號, j 為寫入資料編號 for (int i = number * 3, j = 0; i < ViewData.Length; i += 24, j += 3) { ViewFragment[number][j] = ViewData[i];//R ViewFragment[number][j + 1] = ViewData[i + 1];//G ViewFragment[number][j + 2] = ViewData[i + 2];//B } } /// <summary> /// 壓縮演算法 /// </summary> /// <param name="data"></param> /// <returns></returns> public byte[] Compress(byte[] data) { MemoryStream ms = new MemoryStream(); GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true); zip.Write(data, 0, data.Length); zip.Close(); ms.Position = 0; byte[] compressed = new byte[ms.Length]; ms.Read(compressed, 0, compressed.Length); byte[] gzBuffer = new byte[compressed.Length + 4]; Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length); Buffer.BlockCopy(BitConverter.GetBytes(data.Length), 0, gzBuffer, 0, 4); return gzBuffer; } /// <summary> /// 解壓縮演算法 /// </summary> /// <param name="data"></param> /// <returns></returns> public byte[] Decompress(byte[] data) { MemoryStream ms = new MemoryStream(); int msgLength = BitConverter.ToInt32(data, 0); ms.Write(data, 4, data.Length - 4); byte[] buffer = new byte[msgLength]; ms.Position = 0; GZipStream zip = new GZipStream(ms, CompressionMode.Decompress); zip.Read(buffer, 0, buffer.Length); zip.Close(); return buffer; } void OnApplicationQuit() { udpClient.Close(); CloseThread(); } /// <summary> /// 關閉Thread /// </summary> void CloseThread() { //關閉執行緒 for (int i = 0; i < ViewDataProcessing.Length; i++) { DataProcessGate[i].Set(); ViewDataProcessing[i].Interrupt(); ViewDataProcessing[i].Abort(); } } } <file_sep>/Assets/Scripts/Tcp/ConnectChecking/CheckingServer.cs using UnityEngine; using System.Collections; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System; /// <summary> /// 此程式為接收Client 連線訊號,並透過不斷傳送字串偵測對方是否還存在 /// </summary> public class CheckingServer : MonoBehaviour { Socket serverSocket; //伺服器端socket Socket[] clientSockets = new Socket[10]; //客戶端socket IPEndPoint ipEnd; //偵聽埠 string recvStr; //接收的字串 string sendStr; //傳送的字串 byte[] recvData = new byte[1024]; //接收的資料,必須為位元組 byte[] sendData = new byte[1024]; //傳送的資料,必須為位元組 int recvLen; //接收的資料長度 Thread connectThread; //連線執行緒 Thread[] RecvThread = new Thread[10];//接收執行緒 public int RecvNum;//連線端的數量 string editString; void Start() { //在這裡初始化server InitSocket(); //不斷傳送data,確認Client是否還活著 StartCoroutine(CheckClientSurvive()); } void InitSocket() { //定義偵聽埠,偵聽任何本機 IP 的 5566 Port ipEnd = new IPEndPoint(IPAddress.Any, 5566); //定義套接字型別,在主執行緒中定義 serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //連線 serverSocket.Bind(ipEnd); //開始偵聽,最大10個連線 serverSocket.Listen(10); //開啟接收連線執行緒 connectThread = new Thread(new ThreadStart(SocketConnet)); connectThread.Start(); RecvNum = 0; //開啟多接收執行緒 for (int i = 0; i < RecvThread.Length; i++) { RecvThread[i] = new Thread(SocketReceive); } } //連線 void SocketConnet() { while (true) { if (RecvNum == RecvThread.Length) { continue; } //控制檯輸出偵聽狀態 print("Waiting for a client"); //一旦接受連線,建立一個客戶端 Socket socket = serverSocket.Accept(); //將得到的 Socket 加入Array中 int SocketIndex = AddClientSocket(socket); if (SocketIndex == clientSockets.Length) { continue; } //獲取客戶端的IP和埠 IPEndPoint ipEndClient = (IPEndPoint)clientSockets[SocketIndex].RemoteEndPoint; //輸出客戶端的IP和埠 print("Connect with " + ipEndClient.Address.ToString() + ":" + ipEndClient.Port.ToString()); //連線成功則傳送資料 sendStr = "Welcome to my server"; SocketSend(sendStr, SocketIndex); } } //伺服器接收 void SocketReceive(object RecvNumber) { //Thread編號 int num = (int)RecvNumber; //進入接收迴圈 while (true) { //對data清空 recvData = new byte[1024]; //獲取收到的資料的長度 try { recvLen = clientSockets[num].Receive(recvData); } catch (Exception e) { Debug.Log(e); //如果對方已斷線,接收不到資料,則斷開Socket連線,清除相關參數 if (clientSockets[num].RemoteEndPoint == null) { RemoveClientSocket(num); } } //如果收到的資料長度為0,則進入下一個迴圈 if (recvLen == 0) { continue; } //輸出接收到的資料 recvStr = Encoding.ASCII.GetString(recvData, 0, recvLen); print(recvStr); //將接收到的資料經過處理再發送出去 sendStr = "From Server: " + recvStr; SocketSend(sendStr, num); } } void SocketSend(string sendStr, int num) { //清空傳送快取 sendData = new byte[1024]; //資料型別轉換 sendData = Encoding.ASCII.GetBytes(sendStr); //傳送 try { clientSockets[num].Send(sendData, sendData.Length, SocketFlags.None); } catch (Exception e) { Debug.Log(e); } } /// <summary> /// 傳送Data給Client的協程,每0.1秒傳一次,確認Client端是否還活著 /// </summary> /// <returns></returns> IEnumerator CheckClientSurvive() { while (true) { for (int i = 0; i < clientSockets.Length; i++) { if (clientSockets[i] != null) SocketSend("ServerCheck", i); } yield return new WaitForSeconds(0.1f); } } void OnGUI() { editString = GUI.TextField(new Rect(10, 10, 100, 20), editString); if (GUI.Button(new Rect(10, 30, 60, 20), "send")) { for (int i = 0; i < clientSockets.Length; i++) { if (clientSockets[i] != null) SocketSend(editString, i); } } } //連線關閉 void SocketQuit() { //關閉執行緒 if (connectThread != null) { connectThread.Interrupt(); connectThread.Abort(); } //關閉客戶端 for (int i = 0; i < clientSockets.Length; i++) { if (clientSockets[i] != null) clientSockets[i].Close(); } for (int i = 0; i < RecvThread.Length; i++) { RecvThread[i].Interrupt(); RecvThread[i].Abort(); } //最後關閉伺服器 serverSocket.Close(); print("diconnect"); } void OnApplicationQuit() { SocketQuit(); } /// <summary> /// 新增 ClientSocket 至 Array 中 /// </summary> /// <param name="ClientSocket"></param> int AddClientSocket(Socket ClientSocket) { int i = 0; //尋找Array中為null的位置 for (; i < clientSockets.Length;i++) { if (clientSockets[i] == null) { break; } } if (i >= clientSockets.Length) { return clientSockets.Length; } lock (clientSockets) { clientSockets[i] = ClientSocket; RecvNum++; } //啟動監聽該 Socket 的 Thread RecvThread[i].Start(i); //回傳Array中的Index return i; } /// <summary> /// 切斷該Socket連線 /// </summary> /// <param name="ClientIndex"></param> void RemoveClientSocket(int ClientIndex) { Debug.Log("RemoveClientSocket"); if (clientSockets[ClientIndex] != null) { clientSockets[ClientIndex].Close(); clientSockets[ClientIndex] = null; } RecvNum--; Thread CloseThread = RecvThread[ClientIndex]; RecvThread[ClientIndex] = new Thread(SocketReceive); CloseThread.Interrupt(); CloseThread.Abort(); } } <file_sep>/Assets/Scripts/Udp/1080P/UdpServer1080p.cs using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Net; using System.Net.Sockets; using System.Threading; using UnityEngine; using CompressionLevel = System.IO.Compression.CompressionLevel; public class UdpServer1080p : MonoBehaviour { /// <summary> /// 接收資料的 ip 跟 port /// </summary> private IPEndPoint ipEndPoint; /// <summary> /// 接收資料的udp Client /// </summary> private UdpClient udpClient; /// <summary> /// 進行圖像接收的Thread /// </summary> private Thread receiveThread; /// <summary> /// 接收到的圖像 bytes /// </summary> private byte[] receiveByte; /// <summary> /// 解壓縮後的圖像 Bytes,最後 2 Bytes 中,1 byte 會作為切割編號,1 byte會作為fram編號 /// </summary> byte[][] ViewFragment = new byte[10][]; /// <summary> /// 畫面的圖像 Buffer /// </summary> private byte[][] ViewData = new byte[5][]; /// <summary> /// 每個 Buffer 的封包組合次數 /// </summary> private byte[] ViewDataCollectCount = new byte[5]; /// <summary> /// 要渲染給RenderTexture的圖形 /// </summary> Texture2D image; /// <summary> /// 要被渲染的Rendertexture /// </summary> public RenderTexture TargetTexture; /// <summary> /// 負責進行圖形處理的Thread /// </summary> private Thread[] ViewDataProcessing = new Thread[10]; /// <summary> /// 中斷圖形處理 Thread 的 Gate /// </summary> private static AutoResetEvent[] DataProcessGate = new AutoResetEvent[10]; /// <summary> /// 更新影像的條件變數,如果為 false 就不能更新 /// </summary> private bool ReceiveLock = false; /// <summary> /// 更新的fram編號 /// </summary> private byte FramNum; void Start() { Application.targetFrameRate = 90; ipEndPoint = new IPEndPoint(IPAddress.Any, 5555); udpClient = new UdpClient(ipEndPoint.Port); image = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false); //初始化切分後影像的空間 for (int i = 0; i < ViewFragment.Length; i++) { ViewFragment[i] = new byte[1920 * 1080 * 3 / 8 + 2]; } //初始化畫面圖像Buffer for (int i = 0; i < ViewData.Length; i++) { ViewData[i] = new byte[1920 * 1080 * 3]; } //初始設定8個影像處理的thread for (int i = 0; i < ViewDataProcessing.Length; i++) { ViewDataProcessing[i] = new Thread(ProcessView); } //初始設定 Thread Gate for (int i = 0; i < DataProcessGate.Length; i++) { DataProcessGate[i] = new AutoResetEvent(false); } //開始執行影像處理Thread for (int i = 0; i < ViewDataProcessing.Length; i++) { ViewDataProcessing[i].Start(i); } receiveThread = new Thread(ReceiveView); receiveThread.IsBackground = true; receiveThread.Start(); } void ProcessView(object obj) { int ThreadNumber = (int)obj; while (true) { //先中斷執行序,等待呼叫執行 DataProcessGate[ThreadNumber].WaitOne(); //解壓縮資料 lock (receiveByte) { ViewFragment[ThreadNumber] = Decompress(receiveByte); } //取得 fram 編號,數字為0~4 byte FramNumber = (byte)(ViewFragment[ThreadNumber][ViewFragment[ThreadNumber].Length - 1] % 5); //取得切割編號 byte SegmentNumber = ViewFragment[ThreadNumber][ViewFragment[ThreadNumber].Length - 2]; // 將收到的資料寫入Buffer中, i 為畫面資料編號, j 為解壓縮資料編號 for (int i = SegmentNumber * 3, j = 0; i < ViewData[FramNumber].Length; i += 24, j += 3) { ViewData[FramNumber][i] = ViewFragment[ThreadNumber][j]; ViewData[FramNumber][i + 1] = ViewFragment[ThreadNumber][j + 1]; ViewData[FramNumber][i + 2] = ViewFragment[ThreadNumber][j + 2]; } // Buffer 封包數量 +1 lock (ViewDataCollectCount) { //ViewDataCollectCount[FramNumber] += (byte)(1 << ThreadNumber); ViewDataCollectCount[FramNumber] += 1; //如果該 Buffer 封包量到達8個,畫出該 Buffer 畫面 if (ViewDataCollectCount[FramNumber] == 8) { //歸 0 Buffer 封包數量 ViewDataCollectCount[FramNumber] = 0; //也歸 0 前8個 Buffer 封包數量 ViewDataCollectCount[(ViewDataCollectCount.Length + FramNumber - 1) % 5] = 0; ViewDataCollectCount[(ViewDataCollectCount.Length + FramNumber - 2) % 5] = 0; ViewDataCollectCount[(ViewDataCollectCount.Length + FramNumber - 3) % 5] = 0; ViewDataCollectCount[(ViewDataCollectCount.Length + FramNumber - 4) % 5] = 0; //設定要更新的 Fram 編號 FramNum = FramNumber; //將Lock設為True ReceiveLock = true; } } } } void ReceiveView() { while (true) { //接收資料 receiveByte = udpClient.Receive(ref ipEndPoint); //搜尋正在睡眠的 Thread for (int i = 0; i < ViewDataProcessing.Length; i++) { if (ViewDataProcessing[i].ThreadState == ThreadState.WaitSleepJoin) { //找到後解封睡眠,讓該 Thread 處理封包資料 DataProcessGate[i].Set(); break; } } } } private void Update() { //如果現在還在接收封包就停止更新畫面 if (ReceiveLock == false) { return; } //更新Texture2D資料 image.LoadRawTextureData(ViewData[FramNum]); image.Apply(); //將Texture2D圖形更新至RenderTexture Graphics.Blit(image, TargetTexture); //停止畫面更新,改為封包接收 ReceiveLock = false; } private void OnDisable() { udpClient.Close(); receiveThread.Join(); receiveThread.Abort(); } private void OnDestroy() { receiveThread.Abort(); for (int i = 0; i < ViewDataProcessing.Length; i++) { DataProcessGate[i].Set(); ViewDataProcessing[i].Interrupt(); ViewDataProcessing[i].Abort(); } } /// <summary> /// 壓縮演算法 /// </summary> /// <param name="data"></param> /// <returns></returns> public byte[] Compress(byte[] data) { MemoryStream ms = new MemoryStream(); GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true); zip.Write(data, 0, data.Length); zip.Close(); ms.Position = 0; byte[] compressed = new byte[ms.Length]; ms.Read(compressed, 0, compressed.Length); byte[] gzBuffer = new byte[compressed.Length + 4]; Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length); Buffer.BlockCopy(BitConverter.GetBytes(data.Length), 0, gzBuffer, 0, 4); return gzBuffer; } /// <summary> /// 解壓縮演算法 /// </summary> /// <param name="data"></param> /// <returns></returns> public byte[] Decompress(byte[] data) { MemoryStream ms = new MemoryStream(); int msgLength = BitConverter.ToInt32(data, 0); ms.Write(data, 4, data.Length - 4); byte[] buffer = new byte[msgLength]; ms.Position = 0; GZipStream zip = new GZipStream(ms, CompressionMode.Decompress); zip.Read(buffer, 0, buffer.Length); zip.Close(); return buffer; } } <file_sep>/Assets/Scripts/MoveMent/BallMovement.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class BallMovement : MonoBehaviour { public float Speed; public float Distance; private float dis; private void Start() { dis = Distance; } // Update is called once per frame void Update() { transform.position += transform.forward * Time.deltaTime * Speed; dis -= Time.deltaTime * Mathf.Abs(Speed); if (dis <= 0) { dis = Distance; Speed = -Speed; } } } <file_sep>/Assets/Scripts/Udp/480P/UdpServer480p.cs using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Net; using System.Net.Sockets; using System.Threading; using UnityEngine; public class UdpServer480p : MonoBehaviour { /// <summary> /// 接收資料的 ip 跟 port /// </summary> private IPEndPoint ipEndPoint; /// <summary> /// 接收資料的udp Client /// </summary> private UdpClient udpClient; /// <summary> /// 接收到的圖像 bytes /// </summary> private byte[] receiveByte; /// <summary> /// 接收圖像的Queue /// </summary> Queue<byte[]> RecvQueue; /// <summary> /// 畫面的圖像 Buffer /// </summary> private byte[] ViewData = new byte[854 * 480 * 3]; /// <summary> /// 接收的Frame編號 /// </summary> int FrameNum; /// <summary> /// 要渲染給RenderTexture的圖形 /// </summary> Texture2D image; /// <summary> /// 要被渲染的Rendertexture /// </summary> public RenderTexture TargetTexture; /// <summary> /// 負責進行接收封包的Thread /// </summary> private Thread receiveThread; /// <summary> /// 負責進行圖形處理的Thread /// </summary> private Thread ProcessThread; /// <summary> /// 渲染開關,為True則無法渲染畫面 /// </summary> private bool RenderLock = true; // Start is called before the first frame update void Start() { ipEndPoint = new IPEndPoint(IPAddress.Any, 5555); udpClient = new UdpClient(ipEndPoint.Port); image = new Texture2D(TargetTexture.width, TargetTexture.height, TextureFormat.RGB24, false); FrameNum = 0; RecvQueue = new Queue<byte[]>(); receiveThread = new Thread(new ThreadStart(RecvViewData)); receiveThread.Start(); ProcessThread = new Thread(new ThreadStart(ProcessViewData)); ProcessThread.Start(); StartCoroutine(ProcessGraphic()); } IEnumerator ProcessGraphic() { while (true) { if (RenderLock == true) { yield return null; continue; } //更新Texture2D資料 image.LoadRawTextureData(ViewData); //yield return new WaitUntil(() => { image.LoadImage(ViewData); return false; }); image.Apply(); //將Texture2D圖形更新至RenderTexture Graphics.Blit(image, TargetTexture); RenderLock = true; } } private void RecvViewData() { while (true) { //接收資料 receiveByte = udpClient.Receive(ref ipEndPoint); //將資料放入佇列儲存 RecvQueue.Enqueue(receiveByte); } } private void ProcessViewData() { //一整個Frame的壓縮Array byte[] FrameData = new byte[0]; //從 Queue 提取的封包資料 byte[] recvData; //一個 Frame 的壓縮片段數量 int FragmentCount = 0; while (true) { //確認RecvQueue是否有資料,有就抓,沒有就繼續偵測 if (RecvQueue.Count > 0) { recvData = RecvQueue.Dequeue(); } else { continue; } //收到的data的Frame number int GetFrameNumber = BitConverter.ToInt32(recvData, recvData.Length - 12); //如果收到的data的Frame number小於目前處理的Frame Number,直接跳過 if (GetFrameNumber < FrameNum) { continue; } //如果收到的data的Frame number大於目前處理的Frame Number,代表收到新的Frame,就 Reset 處理的資料 else if (GetFrameNumber > FrameNum) { FrameData = new byte[0]; FrameNum = GetFrameNumber; //Debug.Log(FrameNum); } //將data加入byte array中 //如果是第一個封包片段要組合 if (FrameData.Length == 0) { //宣告符合壓縮封包長度的Array FrameData = new byte[BitConverter.ToInt32(recvData, recvData.Length - 4)]; //宣告封包片段總量 FragmentCount = decimal.ToInt32(Math.Ceiling(Convert.ToDecimal((float)FrameData.Length / 65400))); } //將收到的data加入壓縮的Array Array.Copy(recvData, 0, FrameData, BitConverter.ToInt32(recvData, recvData.Length - 8) * 65400, recvData.Length - 12); FragmentCount--; //Frame資料收集滿 if (FragmentCount == 0) { //解壓縮資料 ViewData = Decompress(FrameData); FrameData = new byte[0]; RenderLock = false; } } } private void OnDestroy() { receiveThread.Interrupt(); receiveThread.Abort(); ProcessThread.Interrupt(); ProcessThread.Abort(); } /// <summary> /// 壓縮演算法 /// </summary> /// <param name="data"></param> /// <returns></returns> public byte[] Compress(byte[] data) { MemoryStream ms = new MemoryStream(); GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true); zip.Write(data, 0, data.Length); zip.Close(); ms.Position = 0; byte[] compressed = new byte[ms.Length]; ms.Read(compressed, 0, compressed.Length); byte[] gzBuffer = new byte[compressed.Length + 4]; Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length); Buffer.BlockCopy(BitConverter.GetBytes(data.Length), 0, gzBuffer, 0, 4); return gzBuffer; } /// <summary> /// 解壓縮演算法 /// </summary> /// <param name="data"></param> /// <returns></returns> public byte[] Decompress(byte[] data) { MemoryStream ms = new MemoryStream(); int msgLength = BitConverter.ToInt32(data, 0); ms.Write(data, 4, data.Length - 4); byte[] buffer = new byte[msgLength]; ms.Position = 0; GZipStream zip = new GZipStream(ms, CompressionMode.Decompress); zip.Read(buffer, 0, buffer.Length); zip.Close(); return buffer; } }
0643bdb03af9459d0b60870b5621006ba1f9ac81
[ "Markdown", "C#" ]
7
C#
shawn83924/NetworkTest
fa575c0affe225b6c1bfeb3ea9e3c6471a42782b
88dcb382c56ad3690355460a389ae8d7ffed35cc
refs/heads/master
<file_sep>import Vue from "vue"; import { VueEmotion } from "@egoist/vue-emotion"; Vue.use(VueEmotion); <file_sep>import { IMainTheme } from "@/theme/theme"; import { styled } from "@egoist/vue-emotion"; export const OkButton = styled("span")` transition: all 0.15s ease-in-out, box-shadow 0.15s ease-in-out; background: ${({ theme, hasErrors, }: { theme: IMainTheme; hasErrors: boolean; }) => (hasErrors ? theme.error : theme.border)}; display: flex; justify-content: center; color: ${({ theme, hasErrors }: { theme: IMainTheme; hasErrors: boolean }) => hasErrors ? theme.colors.white : theme.text}; border-color: ${({ theme, hasErrors, }: { theme: IMainTheme; hasErrors: boolean; }) => (hasErrors ? theme.borderError : theme.border)}; outline: none; width: 32px; `; export const CloseButton = styled(OkButton)` background: ${({ theme }: { theme: IMainTheme }) => theme.colors.boxGray}; display: flex; justify-content: center; color: ${({ theme }: { theme: IMainTheme }) => theme.text}; border: 1px solid ${({ theme, hasErrors }: { theme: IMainTheme; hasErrors: boolean }) => hasErrors ? theme.borderError : theme.border}; border-top-right-radius: 8px; border-bottom-right-radius: 8px; `; export const URLActionToggle = styled("button")` display: flex; align-items: center; height: 32px; width: 32px; margin-bottom: 0; font-size: 1rem; font-weight: 400; line-height: 1.5; color: #495057; text-align: center; white-space: nowrap; background-color: ${({ theme }: { theme: IMainTheme }) => theme.colors.boxGray}; border: none; border-radius: 0.25rem; position: relative; &:hover { background: ${({ theme }: { theme: IMainTheme }) => theme.border}; } &:active { background: #494c53; color: #fff; } ul { position: absolute; left: -118px; } border-radius: 8px; border-top-right-radius: 0; border-bottom-right-radius: 0; `; export const URLToggleExternal = styled(URLActionToggle)` border-radius: 8px; border-top-left-radius: 0; border-bottom-left-radius: 0; `; <file_sep>import { IMainTheme } from "@/theme/theme"; import { styled } from "@egoist/vue-emotion"; export const URLPreview = styled("div")` display: grid; grid-template-columns: 32px 1fr 32px; width: 100%; `; export const URLPreviewContent = styled("div")` display: flex; justify-content: space-between; padding-left: 0.5rem; padding-right: 0.5rem; align-items: center; span { display: none; cursor: pointer; } &:hover { span { display: block; } } `; export const URLContainer = styled("div")` position: relative; display: flex; flex-wrap: wrap; align-items: stretch; width: 300px; max-width: 300px; border: 1px solid ${(props: { isEditing: boolean }) => props.isEditing ? "transparent" : "gray"}; border-radius: 8px; box-sizing: content; `; <file_sep># vue-component-convrrt ## Quick Start For development: ```npm i``` ```npm run serve``` For StoryBook: ```npm run storybook``` <file_sep>import "./vue-emotion"; import "./vee-validate"; <file_sep>import URLInputComponent from "../components/URLInput.vue"; import "../plugins"; export default { title: "URL/URLInput", component: URLInputComponent, argTypes: { inputType: { control: { type: "select", options: ["email", "text", "number"] }, }, validationRules: { control: { type: "select", options: ["required", "required|email"] }, }, }, }; const Template = (args: any, { argTypes }: any) => { return { props: Object.keys(argTypes), components: { URLInputComponent }, template: '<URLInputComponent v-bind="$props" @onCancelled="onCancelled" @onSubmit="onSubmit" />', }; }; export const Email = Template.bind({}); (Email as any).args = { inputType: "email", validationRules: "required|email", }; <file_sep>import "../src/plugins" import { MainTheme } from "../src/theme/theme"; import ThemeProvider from "../src/ThemeProvider.vue"; export const parameters = { actions: { argTypesRegex: "^on[A-Z].*" }, controls: { matchers: { color: /(background|color)$/i, date: /Date$/, }, }, } export const decorators = [ (story) => ({ components: { story, ThemeProvider}, data(){ return {theme: MainTheme} }, provide(){ return { theme: this.theme } }, template: '<theme-provider><story /></theme-provider>' }) ];<file_sep>import URLComponent from "../components/URL.vue"; import "../plugins"; export default { title: "URL/URLComponent", component: URLComponent, }; export const defaultView = (args: any, { argTypes }: any) => { return { props: Object.keys(argTypes), components: { URLComponent }, template: `<URLComponent v-bind="$props" :style="{marginTop: '10rem',marginLeft: '10rem'}" />`, }; }; <file_sep>import { ValidationProvider } from "vee-validate"; import { styled } from "@egoist/vue-emotion"; import { IMainTheme } from "@/theme/theme"; export const StyledValidationProvider = styled(ValidationProvider)` position: relative; display: flex; width: 100%; outline: 1px solid transparent; border: 0; border-radius: 8px; overflow: auto; input { position: relative; flex: 1 1 auto; width: 1%; margin-bottom: 0; padding: 0.275rem 0.65rem; font-size: 1rem; line-height: 1.5; background-color: ${({ theme }: { theme: IMainTheme }) => theme.body}; transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out; border-radius: 8px; border-top-right-radius: 0; border-bottom-right-radius: 0; &:focus { outline: 0; } } div { display: flex; margin-left: -1px; > * { display: flex; align-items: center; margin-bottom: 0; font-size: 1rem; font-weight: 400; line-height: 1.5; } } `; <file_sep>import Vue from "vue"; import "@/plugins"; import { MainTheme } from "@/theme/theme"; import App from "./App.vue"; import store from "./store"; Vue.config.productionTip = false; new Vue({ provide() { return { theme: (this as any).theme, }; }, data() { return { theme: MainTheme, }; }, store, render: (h) => h(App), }).$mount("#app"); <file_sep>declare module "*.vue" { import Vue from "vue"; export default Vue; } // TODO: fix any typing for '@egoist/vue-emotion' declare module "@egoist/vue-emotion"; // TODO: fix any typing for 'vue-styled-components' declare module "vue-styled-components"; <file_sep>import { createGlobalStyle } from "@egoist/vue-emotion"; import { IMainTheme } from "./theme"; export const GlobalStyle = createGlobalStyle` body { background-color: ${({ theme }: { theme: IMainTheme }) => { return theme.body; }}; color: ${({ theme }: { theme: IMainTheme }) => theme.text}; font-family: "Nunito", sans-serif; box-sizing: border-box; } `; <file_sep>export interface IColorTheme { darkerGray: string; lighterGray: string; lightGray: string; darkGray: string; white: string; boxGray: string; error: string; } export interface IMainTheme { body: string; text: string; error: string; borderError: string; border: string; colors: IColorTheme; } export const colorTheme = { darkerGray: "#494C53", lighterGray: "#F0F2F6", lightGray: "#BCC2CB", darkGray: "#494C53", white: "#ffffff", boxGray: "#F0F2F6", error: "#E74F30", }; export const MainTheme = { body: colorTheme.white, text: colorTheme.darkerGray, error: colorTheme.error, borderError: "#C73222", border: "#BCC2CB", colors: colorTheme, }; <file_sep>export class URLItemModel { icon: any; title: string; validationRules: string; inputType: string; value = ""; constructor( icon: any, title: string, validationRules: string, inputType: string ) { this.icon = icon; this.title = title; this.validationRules = validationRules; this.inputType = inputType; } public clear() { this.value = ""; } } export class URIListModel { urlActions: Array<URLItemModel> = []; currentUrlItem: URLItemModel | null = null; public addURLItem(urlItem: URLItemModel) { this.urlActions.push(urlItem); } public addUrlComponent( icon: any, title: string, validationRules = "required", inputType = "text" ) { const urlItem = new URLItemModel(icon, title, validationRules, inputType); this.addURLItem(urlItem); } public clear() { this.currentUrlItem = null; } } <file_sep>import { required, digits, email, max, regex, min, max_value, min_value, } from "vee-validate/dist/rules"; import { extend, setInteractionMode } from "vee-validate"; setInteractionMode("eager"); extend("digits", { ...digits, message: "{_field_} needs to be {length} digits. ({_value_})", }); extend("required", { ...required, message: "{_field_} can not be empty", }); extend("max", { ...max, message: "{_field_} may not be greater than {length} characters", }); extend("min", { ...min, message: "{_field_} may be greater than {length} characters", }); extend("max_value", { ...max_value, message: "{_field_} value is too long", }); extend("min_value", { ...min_value, message: "{_field_} value is too short", }); extend("regex", { ...regex, message: "{_field_} {_value_} does not match {regex}", }); extend("email", { ...email, message: "Email must be valid", }); <file_sep>import { library } from "@fortawesome/fontawesome-svg-core"; import { faEnvelopeOpen, faNewspaper, } from "@fortawesome/free-regular-svg-icons"; import { faPhoneAlt } from "@fortawesome/free-solid-svg-icons"; // this will bundle only registered icons to reduce bundle size const icons = [faEnvelopeOpen, faNewspaper, faPhoneAlt]; library.add(...icons); <file_sep>import { URLItemModel } from "../components/models/urlmodel"; import URListComponent from "../components/URList.vue"; import { faEnvelopeOpen, faNewspaper, } from "@fortawesome/free-regular-svg-icons"; import { faPhoneAlt } from "@fortawesome/free-solid-svg-icons"; import "../plugins"; export default { title: "URL/URList", component: URListComponent, argTypes: { onSelectedAction: { action: "clicked" } }, }; const Template = (args: any, { argTypes }: any) => { return { props: Object.keys(argTypes), components: { URListComponent }, template: '<URListComponent :actions="actions" @onSelectedAction="onSelectedAction" />', }; }; export const List = Template.bind({}); (List as any).args = { actions: [ new URLItemModel( faEnvelopeOpen, "Link to Email", "required|email", "email" ), new URLItemModel(faNewspaper, "Link to URL", "required", "text"), new URLItemModel(faPhoneAlt, "Link to Phone", "required", "number"), ], }; <file_sep>import { IMainTheme } from "@/theme/theme"; import { styled } from "@egoist/vue-emotion"; export const InputField = styled("input")` border: 1px solid ${({ theme, hasErrors }: { theme: IMainTheme; hasErrors: boolean }) => hasErrors ? theme.borderError : theme.border}; `;
c095ba7519942d06d0151557a0c3dfe2b86e87d3
[ "Markdown", "TypeScript", "JavaScript" ]
18
TypeScript
eadwinCode/vue-component-convrrt
9fb6224ec0a4df2b0c0744c9904d3fa350adc89b
558de441e5e093c5ac58115a5ee571c16e45d873
refs/heads/master
<repo_name>ircrelay/ircrelay-www-redirect<file_sep>/app.py import os from flask import Flask, redirect app = Flask(__name__) @app.route("/") def hello(): return redirect('http://www.ircrelay.com') @app.route("/<slug>") def catch_all(slug): return redirect('http://www.ircrelay.com/%s' % slug) if __name__ == "__main__": app.run(host='0.0.0.0', port=os.environ['PORT'])
7a9f1c1d1fc272a92c355428dfbda0ae376c8962
[ "Python" ]
1
Python
ircrelay/ircrelay-www-redirect
f84eb6237f6246e00539916cf2e239b363707b25
473498def8fc1b56b9448205b1cad216c7bdc912
refs/heads/master
<file_sep>import styled from 'styled-components/native'; // Hieronder pas je de MainContainer aan. Dit is de basis container van Tab1.js, Tab2.js en Tab3.js // Probeer maar eens de background-color aan te passen, // zie je dat de achtergrond van alle pagina's wordt aangepast? export const MainContainer = styled.View` flex: 1; background-color: salmon; align-items: center; justify-content: center; `; // Hieronder pas je de ScrollContainer aan, deze wordt gebruikt in Tab1.js export const ScrollContainer = styled.View` `; // Hieronder pas je de ArrayList aan, deze wordt gebruikt in Tab2.js export const ArrayList = styled.FlatList` `; // Hieronder pas je de ListItems aan, deze wordt gebruikt in Tab2.js export const ListItem = styled.View` `; <file_sep>import styled from 'styled-components/native'; export const NormalButton = styled.TouchableOpacity` background-color: ${props => props.color || 'lightblue'}; padding: 10px; border-radius: 7px; `<file_sep>import React from 'react'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import { createStackNavigator } from '@react-navigation/stack'; import Tab1 from './Tabs/Tab1'; import Tab2 from './Tabs/Tab2'; import Tab3 from './Tabs/Tab3'; import { NavigationContainer } from '@react-navigation/native'; import { Icon } from 'react-native-elements'; const Tab = createBottomTabNavigator(); const Stack1 = createStackNavigator(); const Stack2 = createStackNavigator(); const Stack3 = createStackNavigator(); // Hierboven niks aanpassen AUB! // Het onderdeel hieronder kun je aanpassen! const Tab1Name = "NAAM TAB 1" const Tab2Name = "NAAM TAB 2" const Tab3Name = "NAAM TAB 3" const Tab1Icon = "directions-walk" const Tab2Icon = "directions-walk" const Tab3Icon = "directions-walk" // Het onderdeel hierboven kun je aanpassen! // Hieronder niks aanpassen AUB! function tab1Screen(){ return ( <Stack1.Navigator> <Stack1.Screen name={Tab1Name} component={Tab1} /> </Stack1.Navigator> ); } function tab2Screen(){ return ( <Stack2.Navigator> <Stack2.Screen name={Tab2Name} component={Tab2} /> </Stack2.Navigator> ); } function tab3Screen(){ return ( <Stack3.Navigator> <Stack3.Screen name={Tab3Name} component={Tab3} /> </Stack3.Navigator> ); } export default function App() { return ( <NavigationContainer> <Tab.Navigator> <Tab.Screen name={Tab1Name} options={{ tabBarIcon: ({ color, size }) => ( <Icon name={Tab1Icon} color={color} size={size} /> ), }} component={tab1Screen}/> <Tab.Screen name={Tab2Name} options={{ tabBarIcon: ({ color, size }) => ( <Icon name={Tab2Icon} color={color} size={size} /> ), }} component={tab2Screen} /> <Tab.Screen name={Tab3Name} options={{ tabBarIcon: ({ color, size }) => ( <Icon name={Tab3Icon} color={color} size={size} /> ), }} component={tab3Screen} /> </Tab.Navigator> </NavigationContainer> ); } <file_sep>import styled from "styled-components/native"; export const SmallText = styled.Text` font-size: 12px; color: 'black'; `; export const NormalText = styled.Text` font-size: 16px; color: 'black'; `; export const Tab2Text = styled.Text` font-size: 16px; color: 'black'; `; export const BigText = styled.Text` font-size: 20px; color: 'black'; `;<file_sep>import { StatusBar } from 'expo-status-bar'; import React from 'react'; import { ArrayList, ListItem, MainContainer } from './Components/Containers'; import { Tab2Text } from './Components/Text'; import { ArrayData } from './Data'; /* Hieronder ga je een ListView gebruiken. Een ListView gebruik je om data uit een array te printen. De data uit de array komt uit Data.js. De bedoeling is dat jij de data uit deze array op het scherm weet te printen. Kijk op https://docs.expo.io/versions/v37.0.0/react-native/using-a-listview/ voor meer info over een ListView. OPDRACHT 1: Zoals je op je telefoon kunt zien wordt het stukje met 'Hier komen de gegevens uit Data.js te staan.' meerdere keren geprint. Waarom is dat zo? OPDRARCHT 2: Vervang 'Hier komen de gegevens uit Data.js te staan.' voor {item.name}. Wat gebeurd er? OPDRACHT 3: Voeg meerdere NormalText componenten toe en gebruik de namen uit Data.js om alle gegevens op je scherm te printen. OPDRACHT 4: Voeg padding toe aan de ListItem, deze vind je in Containers.js Voeg ook andere styling toe op deze pagina Eventueel kan je ook stying aan Tab2Text toevoegen in Text.js */ export default function Tab2() { return ( <MainContainer> <ArrayList data={ArrayData} renderItem={(item) => <ListItem> <Tab2Text>Hier komen de gegevens uit Data.js te staan.</Tab2Text> </ListItem>} /> </MainContainer> ); } <file_sep>export const ArrayData = [ { "key": '1as', "first_name": "Elisa", "last_name": "O'Scanlon", "email": "<EMAIL>", "gender": "Female" }, { "key": '2as', "first_name": "Mauricio", "last_name": "Brecken", "email": "<EMAIL>", "gender": "Male" }, { "key": '3as', "first_name": "Melisa", "last_name": "MacEnelly", "email": "<EMAIL>", "gender": "Female" }, { "key": '4as', "first_name": "Wilek", "last_name": "Duxbury", "email": "<EMAIL>", "gender": "Male" }, { "key": '5as', "first_name": "Demetria", "last_name": "Windrus", "email": "<EMAIL>", "gender": "Female" }, { "key": '6as', "first_name": "Janeta", "last_name": "Carnow", "email": "<EMAIL>", "gender": "Female" }, { "key": '7as', "first_name": "Norris", "last_name": "Easman", "email": "<EMAIL>", "gender": "Male" }, { "key": '8as', "first_name": "Storm", "last_name": "Althorpe", "email": "<EMAIL>", "gender": "Female" }, { "key": '9as', "first_name": "Nicolle", "last_name": "Cumesky", "email": "<EMAIL>", "gender": "Female" }, { "key": '10as', "first_name": "Darleen", "last_name": "Dornin", "email": "<EMAIL>", "gender": "Female" } ]
de5108cd8afc0f68718f243a12f14194059d9ad3
[ "JavaScript" ]
6
JavaScript
Samy-F/oefeningen-les-5
faac4d7d2cc2ea58da912752c6799efe5a61c0d6
0a5c67a6d6bb128ce69510269c6d70c413b92f79
refs/heads/master
<file_sep>#define BLYNK_USE_DIRECT_CONNECT #include <BlynkSimpleSerialBLE.h> char auth[] = "<KEY>"; BlynkTimer timer; int setMin,setMax ; BLYNK_WRITE(V1){ setMin = param.asInt(); // membaca variabel V1 } BLYNK_WRITE(V2){ setMax = param.asInt(); // membaca variabel V2 } void updateSuhu(){ unsigned long temptot = 0; for(byte x = 0; x < 64; x++) { temptot += analogRead(A5); } unsigned int temp = temptot >> 6; // bagi hasil dengan 64 float suhu= temp * 0.48828125; // 2.0479; Blynk.virtualWrite(V0, suhu); if(suhu<=setMin){ digitalWrite(A4,HIGH); //jika suhu kurang dari samadengan setMax relay hidup Blynk.virtualWrite(V3, 1023); //hidupkan led } if(suhu>=setMax){ digitalWrite(A4,LOW); //jika suhu lebih besar samadengan setMax relay mati Blynk.virtualWrite(V3, 0); //matikan led } } void setup(){ Serial.begin(38400); Blynk.begin(Serial, auth); timer.setInterval(1000L, updateSuhu); //update suhu setiap 1000 mili detik pinMode(A4,OUTPUT); //jadikan A4 sebagai output } void loop(){ Blynk.run(); timer.run(); // Initiates BlynkTimer } <file_sep>#include "max6675.h" #include <ESP8266WiFi.h> int thermoDO = D5; int thermoCLK = D6; int thermoCS = D7; MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO); void setup(){ Serial.begin(9600); } void loop(){ delay(1000); Serial.println(thermocouple.readCelsius()); }
fa67aa5095f991844466d9e7512cfdb8b24393cd
[ "C++" ]
2
C++
anung-git/proyek
00b3547f57835ffba32f532f2b277bb18ef64a56
2e15747f8653a5ae4ce414ee7081d1d5b908dbb1
refs/heads/master
<repo_name>aaronferrucci/santacruzvoting<file_sep>/main.R library(ggplot2) library(sp) library(rgdal) library(rgeos) data <- readOGR(dsn="./original", layer="Precincts") data@data$id <- rownames(data@data) dataPoints <- fortify(data, region="id") dataDF <- merge(dataPoints, data@data, by="id") dataDF$Precinct <- as.integer(as.character(dataDF$Precinct)) source("parse_voter_data.R") # 'merge' reorders the data.frame, which ruins the choropleth... # dataDF2 <- merge(sort=F, dataDF, turnout_by_precinct[, c("Precinct", "Turnout")], by="Precinct") dataDF$Turnout <- turnout_by_precinct[match(dataDF$Precinct, turnout_by_precinct$Precinct, nomatch=which(turnout_by_precinct$Turnout == min(turnout_by_precinct$Turnout))[1]), "Turnout"] dataDF$'Registered Voters' <- turnout_by_precinct$'Registered Voters'[match(dataDF$Precinct, turnout_by_precinct$Precinct)] dataDF$'Registered Voters' <- ifelse(is.na(dataDF$'Registered Voters'), 0, dataDF$'Registered Voters') dataDF$'Ballots Cast' <- turnout_by_precinct$'Ballots Cast'[match(dataDF$Precinct, turnout_by_precinct$Precinct)] dataDF$'Ballots Cast' <- ifelse(is.na(dataDF$'Ballots Cast'), 0, dataDF$'Ballots Cast') ggData <- ggplot(data=dataDF, aes(x=long, y=lat, group=group, fill=`Turnout`)) + geom_polygon() + geom_path(color="white", size=0.1) + scale_fill_gradient(low="darkgreen", high="green") + coord_equal() + theme(axis.text=element_blank()) print(ggData) ggsave("plot.png") <file_sep>/parse_voter_data.R library(tabulizer) # Voter turnout data, by precinct, is technically available, but locked # away in a pdf file. Someone will pay for this crime against data. In the # meantime, here's some hacky code that converts to a usable format. This # is very particular to this pdf, and should be expected to break whenever # the pdf is updated. But it's better than typing the data manually. file <- "./ensov.pdf" rawpages <- extract_tables(file, pages=seq(1,6)) dims <- get_page_dims(file, pages=1) # specifying this area - which is nominally the entire page - would seem to do # nothing. I do it because without it, data is scrambled (candidate names # interpolated into precinct names). rawpages <- extract_tables(file, pages=seq(1,6), area=list(c(1, 1, dims[[1]][2], dims[[1]][1]))) trimmedpages <- lapply(rawpages, function(x) { df <- as.data.frame(x); return(df[,c(1, 2, 3, 4)]) }) voter_data <- do.call(rbind, trimmedpages) voter_data$V1 = as.character(voter_data$V1) voter_data$V2 <- as.integer(as.character(voter_data$V2)) voter_data$V3 <- as.integer(as.character(voter_data$V3)) voter_data$V4 <- as.integer(as.character(voter_data$V4)) # Untidy: on some pages, column 2 is blank. For those, shift columns 3 and 4 # left. voter_data$'Registered Voters' <- ifelse(is.na(voter_data$V2), voter_data$V3, voter_data$V2) voter_data$'Ballots Cast' <- ifelse(is.na(voter_data$V2), voter_data$V4, voter_data$V3) voter_data$Precinct <- voter_data$V1 voter_data <- subset(voter_data, select=-c(V1, V2, V3, V4)) # Reorder the columns... voter_data <- voter_data[c('Precinct', 'Registered Voters', 'Ballots Cast')] # After the by-precinct data, there's a summary. So untidy! # Remove rows starting at the one with "Precinct Totals" index <- which(voter_data$Precinct == "Precinct Totals") voter_data <- voter_data[seq(1, index - 1),] # "Precinct Data" is messy. It appears in two forms: # 10020SIMPKINS # 10020 - Vote By Mail / Absentee R # step 1: extract the "vote by mail/absentee" nature of the record to a new # field voter_data$Absentee <- grepl("Vote By Mail", voter_data$Precinct) # step 2: trim the precinct field to just the 5-digit number # (consider saving the precinct name, e.g. "SIMPKINS") voter_data$Precinct <- substring(voter_data$Precinct, 1, 5) voter_data$Precinct <- as.integer(voter_data$Precinct) # Sanity checks all(voter_data$'Registered Voters' >= voter_data$'Ballots Cast') library(dplyr) turnout_by_precinct <- group_by(voter_data, Precinct) turnout_by_precinct <- summarize(turnout_by_precinct, `Registered Voters` = first(`Registered Voters`), `Ballots Cast` = sum(`Ballots Cast`)) turnout_by_precinct$Turnout <- turnout_by_precinct$'Ballots Cast' / turnout_by_precinct$'Registered Voters' turnout_by_precinct$Turnout <- ifelse(is.na(turnout_by_precinct$Turnout), 0, turnout_by_precinct$Turnout) <file_sep>/README.md # santacruzvoting An analysis of voting patterns in Santa Cruz County. References: * shp file for Santa Cruz County voter precincts: [https://earthworks.stanford.edu/catalog/stanford-tc328sr9298](https://earthworks.stanford.edu/catalog/stanford-tc328sr9298) * A drop-down offers downloads of various file formats, including "original" and "generated" shapefiles * I use the "original" shapefile * voting results by precinct: [Unofficial Election Night Precinct by Precinct Results](http://www.votescount.com/Portals/16/june18/ensov.pdf) Voter turnout, by precinct: ![alt text](https://github.com/aaronferrucci/santacruzvoting/blob/master/plot.png "Voter Precincts")
26ba61ff6de29a0dcc8f0943662f056d80c090b6
[ "Markdown", "R" ]
3
R
aaronferrucci/santacruzvoting
a7c0bc5b26873f6c742b661cff6514e159530740
bc36b6024d80d57a32e2be53fd73cb48901464f7
refs/heads/master
<file_sep>package com.example.hp.project; import android.content.Intent; import android.graphics.Bitmap; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; public class Camera extends AppCompatActivity { Button b1,b2; ImageView w; TextView t; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_camera); b1=(Button)findViewById(R.id.button13); b2=(Button)findViewById(R.id.button14); w=(ImageView)findViewById(R.id.imageView3); t=(TextView)findViewById(R.id.textView2); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i =new Intent(Camera.this , On.class); startActivity(i); finish(); } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i =new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(i ,0); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode , resultCode,data); Bitmap bm=(Bitmap)data.getExtras().get("data"); w.setImageBitmap(bm); } } <file_sep># android_app Hands on android studio to understand basic concept <file_sep>package com.example.hp.project; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.webkit.WebView; import android.widget.Button; import android.widget.TextView; public class Result extends AppCompatActivity { Button b1,b2,b3,b4; TextView t; WebView w; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_result); b1=(Button)findViewById(R.id.button32); b2=(Button)findViewById(R.id.button33); b3=(Button)findViewById(R.id.button34); b4=(Button)findViewById(R.id.button35); t=(TextView)findViewById(R.id.textView12); t.setText("Your score is "+Quiz.score); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i=new Intent(Result.this ,Facebook.class); startActivity(i); finish(); } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i=new Intent(Result.this ,Twitter.class); startActivity(i); finish(); } }); b3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i=new Intent(Result.this ,Netcap.class); startActivity(i); finish(); } }); b4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i=new Intent(Result.this ,On.class); startActivity(i); finish(); } }); } } <file_sep>package com.example.hp.project; import android.content.Intent; import android.speech.tts.TextToSpeech; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.util.Locale; public class Cal extends AppCompatActivity { Button b1,b2,b3,b4,b5,b6,b7; TextView t1,t2; EditText e1,e2; TextToSpeech tt; String q; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cal); b7=(Button)findViewById(R.id.button15); b1=(Button)findViewById(R.id.button16); b2=(Button)findViewById(R.id.button17); b3=(Button)findViewById(R.id.button18); b4=(Button)findViewById(R.id.button19); b5=(Button)findViewById(R.id.button20); b6=(Button)findViewById(R.id.button21); t1=(TextView)findViewById(R.id.textView3); t2=(TextView)findViewById(R.id.textView4); e1=(EditText)findViewById(R.id.editText8); e2=(EditText)findViewById(R.id.editText9); tt=new TextToSpeech(this, new TextToSpeech.OnInitListener() { @Override public void onInit(int i) { tt.setLanguage(Locale.ENGLISH); tt.setSpeechRate(0.3f); } }); b7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i= new Intent(Cal.this , On.class); startActivity(i); finish(); } }); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String s1=e1.getText().toString(); String s2=e2.getText().toString(); if(s1.equals("") || s2.equals("")){ Toast.makeText(Cal.this, "ENTER NUMBER CAREFULLY", Toast.LENGTH_SHORT).show(); } else { Float i1=Float.valueOf(s1); Float i2=Float.valueOf(s2); Float i3=i1 +i2; String s3=" YOUR ANSWER IS " + Float.toString(i3); t2.setText(s3); q=s3; Toast.makeText(Cal.this, "ADDITION SUCCESFULL", Toast.LENGTH_SHORT).show(); } } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String s1=e1.getText().toString(); String s2=e2.getText().toString(); if(s1.equals("") || s2.equals("")){ Toast.makeText(Cal.this, "ENTER NUMBER CAREFULLY", Toast.LENGTH_SHORT).show(); } else { Float i1=Float.valueOf(s1); Float i2=Float.valueOf(s2); Float i3=i1 -i2; String s3=" YOUR ANSWER IS " + Float.toString(i3); t2.setText(s3); q=s3; Toast.makeText(Cal.this, "SUBTRACTION SUCCESFULL", Toast.LENGTH_SHORT).show(); } } }); b3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String s1=e1.getText().toString(); String s2=e2.getText().toString(); if(s1.equals("") || s2.equals("")){ Toast.makeText(Cal.this, "ENTER NUMBER CAREFULLY", Toast.LENGTH_SHORT).show(); } else { Float i1=Float.valueOf(s1); Float i2=Float.valueOf(s2); Float i3=i1 *i2; String s3=" YOUR ANSWER IS " + Float.toString(i3); t2.setText(s3); q=s3; Toast.makeText(Cal.this, "MULTIPLICATION SUCCESFULL", Toast.LENGTH_SHORT).show(); } } }); b4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String s1=e1.getText().toString(); String s2=e2.getText().toString(); if(s1.equals("") || s2.equals("")){ Toast.makeText(Cal.this, "ENTER NUMBER CAREFULLY", Toast.LENGTH_SHORT).show(); } else { Float i1=Float.valueOf(s1); Float i2=Float.valueOf(s2); Float i3=i1 /i2; String s3=" YOUR ANSWER IS " + Float.toString(i3); t2.setText(s3); q=s3; Toast.makeText(Cal.this, "DIVISION SUCCESFULL", Toast.LENGTH_SHORT).show(); } } }); b5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { tt.speak(q, TextToSpeech.QUEUE_FLUSH,null); } }); b6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { e1.setText(""); e2.setText(""); t2.setText(""); } }); } }
919dfd6ed72c73c168524798c9d948da8a531d51
[ "Markdown", "Java" ]
4
Java
ashishjain5665/android_app
0b5a366e484b3bd9d120ae8d08130372095a3d79
74edad45ab501705ef8c3efee1e9ddffcde755d4
refs/heads/master
<repo_name>linmingeng/Xfzs.marketing.app<file_sep>/src/services/fetch.js import { CALL_API } from 'redux-api-middleware' import { normalize } from 'normalizr' import fetch from 'isomorphic-fetch' import auth from './auth' export const DEFAULT_FAILURE = 'FAILURE' export const LOADING = 'LOADING' export const CLEART_ERROR = 'CLEART_ERROR' const baseUrl = 'http://api.shop.hxzcgf.cn' const imageUrl = 'http://img.hxzcgf.com' const queueUrl = 'http://mk.queue.hxzcgf.cn' export const api = { passport: 'http://passport.hxzcgf.cn', passportApi: 'http://passport.api.hxzcgf.cn', upload: imageUrl + '/api/upload/base64', antiForgery: baseUrl + '/api/antiForgery', wxSdk: baseUrl + '/api/wx/jssdk', topic: baseUrl + '/api/services/app/vote', log: baseUrl + '/api/app/log', imgHost: imageUrl, lottery: baseUrl + '/api/services/app/lottery', order: baseUrl + '/api/services/app/order', delivery: baseUrl + '/api/services/app/delivery', redEnvelop: baseUrl + '/api/services/app/redEnvelop', redEnvelopQueue: queueUrl + '/api/queue', companyService: baseUrl + '/api/services/app/companyService' } function isNotConent(response) { if (response !== null && response.status === 401) { auth.login() return } return (response === null || response.status === 204) ? Promise.resolve({ json: {}, response: { ok: true } }) : response.json().then(json => ({ json, response })) } function defaultOptions() { return { method: 'post', headers: { 'Content-Type': 'application/json', 'X-XSRF-TOKEN': auth.getAntiForgeryToken() }, credentials: 'include' } } export function fetchJson(url, data, method) { var request = { method: method || 'post', headers: defaultOptions().headers, credentials: 'include' } if (request.method === 'post' || request.method === 'put') { request.body = JSON.stringify(data) } if ((request.method === 'get' || request.method === 'delete') && data) { var esc = encodeURIComponent var query = Object.keys(data) .map(k => esc(k) + '=' + esc(data[k])) .join('&') url += `?${query}` } return fetch(url, request).then(response => isNotConent(response)) } export const injectApi = (options) => { const { schema, onSuccess, body } = options delete options.schema delete options.onSuccess if (options.method === 'post' || options.method === 'put') { options.body = JSON.stringify(options.body) } if ((options.method === 'get' || options.method === 'delete') && options.body) { var esc = encodeURIComponent var query = Object.keys(options.body) .map(k => esc(k) + '=' + esc(options.body[k])) .join('&') options.endpoint += `?${query}` delete options.body } return { [CALL_API]: Object.assign({}, defaultOptions(), options, { types: [ options.types[0], { type: options.types[1], payload: (action, state, res) => { const contentType = res.headers.get('Content-Type') if (contentType && contentType.indexOf('json')) { return res.json().then((json) => { if (typeof onSuccess === 'function') { onSuccess(json) } var convertResult = {} if (schema) { convertResult = json.result.items ? listConvert(json, schema, body) : entityConvert(json, schema) } else { convertResult.json = json } convertResult.body = body return convertResult }) } } }, options.types[2] ] }) } } function listConvert(json, schema, body) { if (body) { const total = json.result.total const entitys = normalize(json.result.items, schema) entitys.pagination = { ids: entitys.result, total: total % body.pageSize === 0 ? total / body.pageSize : parseInt(total / body.pageSize) + 1, current: body.current, pageSize: body.pageSize } delete entitys.result return entitys } else { return normalize(json.result.items, schema) } } function entityConvert(json, schema) { return schema ? normalize(json.result, schema) : json } <file_sep>/src/routes/Ranking/index.js import NProgress from 'nprogress' // import { injectReducer } from '../../store/reducers' export default (store) => ({ path: 'topic/ranking', getComponent(nextState, cb) { require.ensure([], (require) => { const Container = require('./containers/RankingContainer').default // const reducer = require('./modules/signup').default // injectReducer(store, { key: 'signup', reducer }) cb(null, Container) NProgress.done() }, 'ranking') }, onEnter: () => { NProgress.start() } }) <file_sep>/src/routes/Index/containers/IndexContainer.js import { connect } from 'react-redux' import IndexView from '../components/IndexView' import { getServiceCategory } from '../modules/index' const mapDispatchToProps = { getServiceCategory } const mapStateToProps = ({ index }) => { // console.log(index) const { serviceCategorys, servicePagination } = index return { serviceList: servicePagination.map(id => serviceCategorys[id]) || [] } } export default connect(mapStateToProps, mapDispatchToProps)(IndexView) <file_sep>/src/components/AddressEditor/AddressEditor.js import React from 'react' import { Popup, PopupHeader, Form, FormCell, CellBody, CellHeader, Label, Input, ButtonArea, Button } from 'react-weui' import cnCity from './cnCity' import CityPicker from './CityPicker' class AddressEditor extends React.PureComponent { static propTypes = { onRequestClose: React.PropTypes.func.isRequired, onRequestSave: React.PropTypes.func.isRequired, show: React.PropTypes.bool.isRequired } state = { showCity: false, selectedCityGroups: [], city: '', editAddress: {} } constructor(props) { super(props) this.handleChangeForm = this.handleChangeForm.bind(this) this.handleSave = this.handleSave.bind(this) this.handleShowCity = this.handleShowCity.bind(this) this.handleHideCity = this.handleHideCity.bind(this) this.handleChangeCity = this.handleChangeCity.bind(this) } render() { const { show, onRequestClose } = this.props return <Popup show={show} onRequestClose={onRequestClose}> <PopupHeader left="关闭" right="" leftOnClick={onRequestClose} rightOnClick={onRequestClose} /> <Form style={{ marginTop: 0 }}> <FormCell> <CellHeader> <Label>收货人</Label> </CellHeader> <CellBody> <Input type="text" placeholder="请输入您的姓名" onChange={this.handleChangeForm('name')} /> </CellBody> </FormCell> <FormCell> <CellHeader> <Label>联系电话</Label> </CellHeader> <CellBody> <Input type="tel" placeholder="请输入您的联系电话" onChange={this.handleChangeForm('phoneNumber')} /> </CellBody> </FormCell> <FormCell> <CellHeader> <Label>选择地区</Label> </CellHeader> <CellBody> <Input type="text" placeholder="请选择您的地区" value={this.state.selectedCityGroups.map(g => g.name).join('')} onClick={this.handleShowCity} readOnly /> </CellBody> </FormCell> <FormCell> <CellHeader> <Label>详细地址</Label> </CellHeader> <CellBody> <Input type="text" placeholder="请输入详细地址" onChange={this.handleChangeForm('fullAddress')} /> </CellBody> </FormCell> <FormCell> <CellHeader> <Label>邮政编码</Label> </CellHeader> <CellBody> <Input type="number" placeholder="请输入邮政编码(可选)" onChange={this.handleChangeForm('zipCode')} /> </CellBody> </FormCell> </Form> <ButtonArea> <Button className="weui-btn_xf" onClick={this.handleSave}>保存收货地址</Button> </ButtonArea> <CityPicker data={cnCity} onCancel={this.handleHideCity} onChange={this.handleChangeCity} show={this.state.showCity} /> </Popup> } handleChangeForm(name) { return (e) => { const { editAddress } = this.state editAddress[name] = e.target.value this.setState({ editAddress }) } } handleSave() { const { onRequestSave } = this.props const { editAddress, selectedCityGroups } = this.state if (selectedCityGroups.length > 0) { editAddress.provinceCode = selectedCityGroups[0].code editAddress.cityCode = selectedCityGroups[1].code editAddress.areaCode = selectedCityGroups[2].code onRequestSave(editAddress) } } handleShowCity() { this.setState({ showCity: true }) } handleHideCity() { this.setState({ showCity: false }) } handleChangeCity(text) { this.setState({ selectedCityGroups: text, showCity: false }) } } export default AddressEditor <file_sep>/src/components/TopicContainer/TopicContainer.js import React from 'react' import { Dialog } from 'react-weui' import PureRenderMixin from 'react-addons-pure-render-mixin' import Nav from 'components/Nav' import TrafficCount from 'components/TrafficCount' import MiniSearch from 'components/MiniSearch' import './TopicContainer.scss' import { api } from 'services/fetch' import index from './assets/index.png' import topicDate from './assets/topic-date.png' import topicDesc from './assets/topic-desc.png' import ranking from './assets/ranking.png' import search from './assets/search.png' import singup from './assets/signup.png' import usercenter from './assets/usercenter.png' import share from './assets/share.png' import auth from 'services/auth' class TopicContainer extends React.Component { static propTypes = { topic: React.PropTypes.object.isRequired, getTopic: React.PropTypes.func.isRequired, children: React.PropTypes.any } static contextTypes = { router: React.PropTypes.object.isRequired } state = { showTopicDate: false, showSearch: false } constructor(props) { super(props) this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this) this.ShowTopicDate = this.ShowTopicDate.bind(this) this.hideShowTopicDate = this.hideShowTopicDate.bind(this) this.handleShowSearch = this.handleShowSearch.bind(this) this.handleCancelSearch = this.handleCancelSearch.bind(this) this.handleSubmitSearch = this.handleSubmitSearch.bind(this) this.handleChangeSearch = this.handleChangeSearch.bind(this) } componentDidMount() { if (!this.props.topic.desc) { this.props.getTopic(this.props.topic.id) } } render() { const { topic, children } = this.props const navs = [ { icon: <img src={index} />, label: '投票首页', onClick: () => this.context.router.push('/') }, { icon: <img src={topicDate} />, label: '活动日期', onClick: this.ShowTopicDate }, { icon: <img src={topicDesc} />, label: '活动介绍', onClick: () => this.context.router.push('/topic/desc') }, { icon: <img src={ranking} />, label: '实时排名', onClick: () => this.context.router.push('/topic/ranking') }, { icon: <img src={singup} />, label: '我要报名', onClick: () => this.context.router.push('/topic/signup') }, { icon: <img src={search} />, label: '投票搜索', onClick: this.handleShowSearch }, { icon: <img src={share} />, label: '分享拉票', onClick: () => this.context.router.push('/topic/signup') }, { icon: <img src={usercenter} />, label: '注销登录', onClick: auth.logout } ] return ( <div className="container"> { topic.focus && <img src={`${api.imgHost}/414_100_w/${topic.focus}`} className="banner" /> } <div className="region"> <TrafficCount {...topic} /> <Nav navs={navs} /> <Dialog title="活动日期" buttons={[{ label: '确定', onClick: this.hideShowTopicDate }]} show={this.state.showTopicDate}> <p>{topic.voteTime.startTime.replace('T', ' ')}</p> <p>至</p> <p>{topic.voteTime.endTime.replace('T', ' ')}</p> </Dialog> </div> <MiniSearch show={this.state.showSearch} onSubmit={this.handleSubmitSearch} onCancel={this.handleCancelSearch} onChange={this.handleChangeSearch} /> {children} </div> ) } ShowTopicDate() { this.setState({ showTopicDate: true }) } hideShowTopicDate() { this.setState({ showTopicDate: false }) } handleShowSearch() { this.setState({ showSearch: true }) } handleCancelSearch() { this.setState({ showSearch: false }) } handleSubmitSearch() { this.setState({ showSearch: false }) this.context.router.push('/?q=' + this.state.search) } handleChangeSearch(text) { this.setState({ search: text }) } } export default TopicContainer <file_sep>/src/components/Nav/Nav.js import React from 'react' import './Nav.scss' export const Nav = ({ navs }) => { return ( <div className="navs"> { navs.map(n => <a className="nav" key={n.label} href="javascript:void(0);" onClick={n.onClick}> <div className="nav-icon"> {n.icon} </div> <p className="nav-label"> {n.label} </p> </a>) } </div > ) } Nav.propTypes = { navs: React.PropTypes.array.isRequired } export default Nav <file_sep>/src/routes/index.js // We only need to import the modules necessary for initial render import NProgress from 'nprogress' import auth from 'services/auth' import { injectReducer } from '../store/reducers' import CoreLayout from '../layouts/CoreLayout/CoreLayout' import Home from './Home' import Index from './Index/index.js' import TopicDescRoute from './TopicDesc' import SignupRoute from './Signup' import RankingRoute from './Ranking' import VoterRoute from './Voter' import CounterRoute from './Counter' import LotteryRoute from './Lottery' import RedEnvelopTopicRoute from './RedEnvelopTopic' import RedEnvelopTakeRoute from './RedEnvelopTake' import RedEnvelopRecordRoute from './RedEnvelopRecord' import TrainRoute from './Train' import TrainConsultRoute from './TrainConsult' import PersonageIndexRoute from './PersonageIndex' /* Note: Instead of using JSX, we recommend using react-router PlainRoute objects to build route definitions. */ export const createRoutes = (store) => ([ { path: '/', name: '首页', getComponent: (nextState, cb) => { NProgress.start() if (nextState.location.query.id) { sessionStorage.setItem('id', nextState.location.query.id) } const reducer = require('./Home/modules/home').default injectReducer(store, { key: 'home', reducer }) cb(null, CoreLayout) NProgress.done() }, indexRoute: Home(store), childRoutes: [ CounterRoute(store), TopicDescRoute(store), SignupRoute(store), RankingRoute(store), VoterRoute(store), LotteryRoute(store), RedEnvelopTopicRoute(store), RedEnvelopTakeRoute(store), RedEnvelopRecordRoute(store), TrainRoute(store), TrainConsultRoute(store), PersonageIndexRoute(store) ], onEnter: () => { auth.fetchAntiForgery() auth.fetchUserInfo() } }, Index(store) ]) /* Note: childRoutes can be chunked or otherwise loaded programmatically using getChildRoutes with the following signature: getChildRoutes (location, cb) { require.ensure([], (require) => { cb(null, [ // Remove imports! require('./Counter').default(store) ]) }) } However, this is not necessary for code-splitting! It simply provides an API for async route definitions. Your code splitting should occur inside the route `getComponent` function, since it is only invoked when the route exists and matches. */ export default createRoutes <file_sep>/src/components/AddressEditor/CityPicker.js import React from 'react' import { Picker } from 'react-weui' class CityPicker extends React.PureComponent { static propTypes = { onChange: React.PropTypes.func, onCancel: React.PropTypes.func, data: React.PropTypes.array.isRequired, dataMap: React.PropTypes.object, selected: React.PropTypes.array, show: React.PropTypes.bool } static defaultProps = { data: [], dataMap: { id: 'name', items: 'sub' }, selected: [], show: false } constructor(props) { super(props) const { data, selected, dataMap } = this.props const { groups, newselected } = this.parseData(data, dataMap.items, selected) this.state = { groups, selected: newselected, picker_show: false, text: '' } this.updateGroup = this.updateGroup.bind(this) this.parseData = this.parseData.bind(this) this.handleChange = this.handleChange.bind(this) } parseData(data, subKey, selected = [], group = [], newselected = []) { let _selected = 0 if (Array.isArray(selected) && selected.length > 0) { let _selectedClone = selected.slice(0) _selected = _selectedClone.shift() selected = _selectedClone } if (typeof data[_selected] === 'undefined') { _selected = 0 } newselected.push(_selected) let item = data[_selected] var _group = JSON.parse(JSON.stringify(data)) _group.forEach(g => delete g[subKey]) group.push({ items: _group, mapKeys: { 'label': this.props.dataMap.id } }) if (typeof item[subKey] !== 'undefined' && Array.isArray(item[subKey])) { return this.parseData(item[subKey], subKey, selected, group, newselected) } else { return { groups: group, newselected } } } updateGroup(item, i, groupIndex, selected, picker) { const { data, dataMap } = this.props const { groups, newselected } = this.parseData(data, dataMap.items, selected) let text = '' try { groups.forEach((group, i) => { text += `${group['items'][selected[i]][this.props.dataMap.id]} ` }) } catch (err) { text = this.state.text } this.setState({ groups, text, selected: newselected }) picker.setState({ selected: newselected }) } handleChange() { if (this.props.onChange) { const { groups, selected } = this.state const selectedGroups = [] groups.forEach((group, i) => { selectedGroups.push(group['items'][selected[i]]) }) this.props.onChange(selectedGroups) } } render() { return ( <Picker lang={{ leftBtn: '关闭', rightBtn: '确定' }} show={this.props.show} onGroupChange={this.updateGroup} onChange={this.handleChange} defaultSelect={this.state.selected} groups={this.state.groups} onCancel={this.props.onCancel} /> ) } } export default CityPicker <file_sep>/src/services/log.js import { api, fetchJson } from './fetch' function GetQueryString(name) { const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)') const r = window.location.search.substr(1).match(reg) return r ? unescape(r[2]) : '' } window.onerror = function (errorMessage, scriptURI, lineNumber, columnNumber, error) { fetchJson( api.log, { message: errorMessage, script: scriptURI, line: lineNumber, column: columnNumber }, 'post') } // 微信js sdk签名不支持pushstate需要记录下首次进入的地址 sessionStorage['first-url'] = window.location.href sessionStorage['_rc'] = GetQueryString('_c') <file_sep>/src/routes/RedEnvelopTopic/components/RedEnvelopList.js import React from 'react' import { Link } from 'react-router' import { api } from 'services/fetch' import './RedEnvelopList.scss' const RedEnvelopList = ({ data }) => ( < ul className="red-envelop-list" > { data.map((value, index) => <li key={index} className={index % 2 === 0 ? 'item' : 'item high-bg'}> <div> <img src={`${api.imgHost}/50_50_w/${value.senderFace}`} /> </div> <div> <h3>{value.senderName}</h3> <p>红包总数:{value.number}个</p> <p>{value.canTakeTime.replace('T', ' ')}</p> </div> <div> <Link className="link" to={`/rd/take/${value.topicId}/${value.id}`}>{ (new Date(value.canTakeTime.replace('T', ' ').replace(/-/g, '/')).getTime() - new Date().getTime() < 0) ? '蜂抢红包' : '立即分享' }</Link> </div> </li>) } { data.length === 0 && <li className="item"> <span className="link">敬请期待</span> </li> } </ul > ) RedEnvelopList.propTypes = { data: React.PropTypes.array.isRequired } export default RedEnvelopList <file_sep>/src/routes/TrainConsult/containers/TrainConsultContainer.js import { connect } from 'react-redux' import { saveWorkOrder, getService } from '../modules/trainconsult' // import { getService } from '../../Train/modules/train' import TrainConsultView from '../components/TrainConsultView' const mapDispatchToProps = { saveWorkOrder, getService } const mapStateToProps = ({ trainconsult }) => { const { workOrder, workOrderPagination, services, servicePagination } = trainconsult return { uid:trainconsult.uid, workOrder: workOrderPagination.ids.map(id => workOrder[id]) || [], params:trainconsult.params, services: servicePagination.ids.map(id => services[id]) || [] } } export default connect(mapStateToProps, mapDispatchToProps)(TrainConsultView) <file_sep>/src/routes/Lottery/components/LotteryResult.js import React from 'react' import { Dialog, Button, ButtonArea } from 'react-weui' import './LotteryResult.scss' import { api } from 'services/fetch' import missImage from './assets/miss.png' export const LotteryResult = ({ result, onAgain, onCancel }) => { const msg = result.isWinning ? `恭喜您抽中${result.productName}` : '很遗憾!未中奖' return <div className="lottery-result"> <Dialog show> { result.isWinning ? <img src={`${api.imgHost}/250_250_w/${result.image}`} /> : <img src={missImage} /> } <h2 className="msg">{msg}</h2> <p className="span">{ result.isPoints ? '蜂币已发放到您的账号请注意查收' : '请尽快确认地址地址,以便您及时收到奖品' }</p> <ButtonArea direction="horizontal"> <Button onClick={onCancel} type="default"> 关闭 </Button> <Button className="weui-btn_xf" onClick={onAgain}> 继续 </Button> </ButtonArea> </Dialog> </div > } LotteryResult.propTypes = { result: React.PropTypes.object.isRequired, onAgain: React.PropTypes.func.isRequired, onCancel: React.PropTypes.func.isRequired } export default LotteryResult <file_sep>/src/routes/RedEnvelopTake/components/RedEnvelopTakeView.js import React from 'react' import { Link } from 'react-router' import { api } from 'services/fetch' import './RedEnvelopTakeView.scss' import Countdown from './Countdown' import Share from 'components/Share' import Toptips from 'components/Toptips' import ResultModal from './ResultModal' // import { Toast } from 'react-weui' class RedEnvelopTakeView extends React.PureComponent { static propTypes = { params: React.PropTypes.object.isRequired, redEnvelop: React.PropTypes.object.isRequired, topic: React.PropTypes.object.isRequired, getRedEnvelop: React.PropTypes.func.isRequired, getRedEnvelopTopic: React.PropTypes.func.isRequired, takeRedEnvelop: React.PropTypes.func.isRequired, getTakeResult: React.PropTypes.func.isRequired, getShareCode: React.PropTypes.func.isRequired, trySaveShareRecords: React.PropTypes.func.isRequired } state = { showShare: false, showResult: false, result: {}, loading: false, error: '', shareContent: { title: '蜂抢红包', desc: '点击领取红包', link: window.location.href, headerimage: `${api.imgHost}/e1/e135988a39a1f307a8eb0995bfc06847.png` } } constructor(props) { super(props) this.handleHideShare = this.handleHideShare.bind(this) this.handleShowShare = this.handleShowShare.bind(this) this.handleTake = this.handleTake.bind(this) } componentDidMount() { const { getRedEnvelop, getRedEnvelopTopic, params, topic } = this.props const { topicId, id } = params if (!topic.id) { getRedEnvelopTopic(topicId) } getRedEnvelop(id) this.handleShareCode(topicId) } componentWillUnmount() { this.timer && clearTimeout(this.timer) } render() { return ( <div className="red-envelop-take-container"> {this.renderMerchants()} <div className="take-warp"> <a href="javascript:void(0)" className="take-btn" onClick={this.handleTake} /> <p className="my-has-take-number">剩余次数:{this.props.topic.currentUserCanReceiveTimes}次</p> <Link to={`/rd/record/${this.props.params.topicId}`} className="take-records-btn">领取记录</Link> <Link to={`/rd/topic/${this.props.params.topicId}`} className="take-records-btn">更多红包</Link> </div> <Countdown redEnvelop={this.props.redEnvelop} skipMinutes={this.props.topic.skipMinutes} /> <a className="share-btn" onClick={this.handleShowShare}>立即分享</a> <p className="share-text">分享赢更多抢红包次数</p> { this.state.showResult && <ResultModal show={this.state.showResult} result={this.state.result} onClose={() => this.setState({ showResult: false })} /> } <Share show={this.state.showShare} content={this.state.shareContent} onHide={this.handleHideShare} /> {/* <Toast icon="loading" show={this.state.loading}>加载中</Toast> */} <Toptips show={!!this.state.error} text={this.state.error} /> </div> ) } renderMerchants() { const { redEnvelop } = this.props return ( <div className="merchants-warp"> <p className="name">{redEnvelop.senderName}</p> <p className="number">红包总数: {redEnvelop.number}个</p> </div> ) } handleHideShare() { this.setState({ showShare: false }) } handleShowShare() { const { getShareCode, topic, redEnvelop } = this.props if (this.state.shareContent.link.indexOf('?') > -1) { this.setState({ showShare: true }) } else { getShareCode({ id: topic.id }).then(({ json }) => { if (redEnvelop) { this.state.shareContent.desc = `${redEnvelop.senderName}邀请您领取红包【小蜂找事】` } else { this.state.shareContent.desc = '小蜂找事邀请您领取红包' } this.state.shareContent.link = this.state.shareContent.link + '?c=' + json.result this.setState({ showShare: true, shareContent: { ...this.state.shareContent } }) }) } } handleTake() { const { redEnvelop, getTakeResult, takeRedEnvelop } = this.props // if (topic.currentUserCanReceiveTimes <= 0) { // this.setState({ error: '次数不足' }) // this.timer = setTimeout(() => { // this.setState({ error: '' }) // }, 1000) // return // } var endTime = new Date(redEnvelop.canTakeTime.replace('T', ' ').replace(/-/g, '/')) if (endTime > new Date()) { this.setState({ error: '红包还未开启' }) this.timer = setTimeout(() => { this.setState({ error: '' }) }, 1000) return } let retries = 10 const getTakeResultLoop = (backend) => { getTakeResult(redEnvelop.id, backend, ({ result }) => { if (result.status > 0) { result.face = redEnvelop.senderFace result.link = redEnvelop.senderLink this.setState({ loading: false, showResult: true, result }) } else if (retries > 0) { getTakeResultLoop(backend) retries-- } else { this.setState({ showResult: true, loading: false, status: 0, face: redEnvelop.senderFace, link: redEnvelop.senderLink }) } }) } if (redEnvelop) { this.setState({ loading: true }) takeRedEnvelop(redEnvelop.id, (json) => { getTakeResultLoop(json.backend) }) } else { this.setState({ error: '敬请期待下一轮' }) this.timer = setTimeout(() => { this.setState({ error: '' }) }, 2000) } } handleShareCode(topicId) { setTimeout(() => { // 值从RedEnvelopTopicView来 var code = sessionStorage['red-envelop-share-code'] if (code) { const { trySaveShareRecords } = this.props trySaveShareRecords({ topicId, shareCode: code }) .then(({ json }) => { json.result && sessionStorage.removeItem('red-envelop-share-code') }) } }, 2000) } } export default RedEnvelopTakeView <file_sep>/src/components/VoterList/VoterList.js import React from 'react' import './VoterList.scss' export const VoterList = ({ children }) => ( <div className="region voter-list"> {children} </div> ) VoterList.propTypes = { children: React.PropTypes.any } export default VoterList <file_sep>/src/components/RegionTitle/index.js import RegionTitle from './RegionTitle' export default RegionTitle <file_sep>/src/components/VotingButton/VotingButton.js import React from 'react' import PureRenderMixin from 'react-addons-pure-render-mixin' import { Button, Toast } from 'react-weui' import './VotingButton.scss' class VotingButton extends React.Component { static propTypes = { voterId: React.PropTypes.string.isRequired, onVoting: React.PropTypes.func.isRequired, className: React.PropTypes.string.isRequired } state = { showToast: false } constructor(props) { super(props) this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this) this.handleClick = this.handleClick.bind(this) } componentWillUnmount() { this.toastTimer && clearTimeout(this.state.toastTimer) } render() { return ( <Button className={this.props.className} onClick={this.handleClick}> 投票 <Toast icon="success-no-circle" show={this.state.showToast}>投票成功</Toast> </Button> ) } handleClick() { const { voterId, onVoting } = this.props onVoting(voterId, () => { this.setState({ showToast: true }) this.toastTimer = setTimeout(() => { this.setState({ showToast: false }) }, 2000) }) } } export default VotingButton <file_sep>/src/routes/Ranking/components/RankingView.js import React from 'react' import { Link } from 'react-router' import PureRenderMixin from 'react-addons-pure-render-mixin' import './RankingView.scss' import TopicContainer from 'components/TopicContainer' import RegionTitle from 'components/RegionTitle' import { api } from 'services/fetch' class RankingView extends React.Component { static propTypes = { topic: React.PropTypes.object.isRequired, voters: React.PropTypes.array.isRequired, getVoters: React.PropTypes.func.isRequired } constructor(props) { super(props) this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this) } componentDidMount() { // console.log(this.props) // console.log(topic.id) const { topic, getVoters } = this.props getVoters(topic.id) } render() { const { voters } = this.props return <TopicContainer {...this.props}> <div className="region ranking-view"> <RegionTitle title="实时排名" /> <ul className="ranking-list"> <li className="row title"> <span className="col">排名</span> <span className="col voter">参与人</span> <span className="col">票数</span> </li> { voters.map((voter, index) => this.renderRankingRow(voter, index)) } </ul> </div> </TopicContainer> } renderRankingRow(voter, index) { const cls = 'col ' + this.renderClass(index + 1) return <li className="row" key={voter.id}> <div className={cls}>{index + 1}</div> <div className="col voter"> <Link to={`/topic/voter/${voter.id}`}> <img src={`${api.imgHost}/50x50_w/${voter.faceDescription.image}`} className="voter-headerimage" /> <div className="voter-desc"> <p>NO.{voter.number}</p> <p>{voter.name}</p> </div> </Link> </div> <div className="col">{voter.numberOfVotes}票</div> </li> } renderClass(top) { switch (top) { case 1: return 'ranking-top-1' case 2: return 'ranking-top-2' case 3: return 'ranking-top-3' default: return 'ranking-top-other' } } } export default RankingView <file_sep>/src/routes/TopicDesc/containers/TopicDescContainer.js import { connect } from 'react-redux' import { getTopic } from '../../Home/modules/home' import TopicDescView from '../components/TopicDescView' const mapDispatchToProps = { getTopic } const mapStateToProps = ({ home }) => { return { topic: home.topic } } export default connect(mapStateToProps, mapDispatchToProps)(TopicDescView) <file_sep>/src/routes/RedEnvelopTake/components/Countdown.js import React from 'react' import './Countdown.scss' class Countdown extends React.Component { static propTypes = { redEnvelop: React.PropTypes.object.isRequired, skipMinutes: React.PropTypes.any } timer = null componentWillUnmount() { this.timer && clearInterval(this.timer) } render() { const { redEnvelop, skipMinutes } = this.props // const filters = redEnvelopList // .filter(r => new Date(r.canTakeTime.replace('T', ' ').replace(/-/g, '/')) > new Date()) // const nextRedEnvelop = filters.length > 0 ? filters[0] : null const zfill = (num, fill) => { var len = ('' + num).length return (Array( fill > len ? fill - len + 1 || 0 : 0 ).join(0) + num) } let endTime let isStart if (redEnvelop && redEnvelop.canTakeTime) { this.timer && clearInterval(this.timer) endTime = new Date(redEnvelop.canTakeTime.replace('T', ' ').replace(/-/g, '/')) if (endTime < new Date()) { isStart = true endTime.setMinutes(skipMinutes) } this.timer = setInterval(() => { const ele = document.getElementById('countdown') const startTime = new Date().getTime() const diff = endTime.getTime() - startTime const num1 = zfill(parseInt(diff / 1000 / 60 / 60, 10), 2) const num2 = zfill(parseInt(diff / 1000 / 60 % 60, 10), 2) const num3 = zfill(parseInt(diff / 1000 % 60, 10), 2) const result = `${num1}:${num2}:${num3}` if (diff < 0) { clearInterval(this.timer) // if (ele) window.location.reload() } else { if (ele) ele.innerText = result } }, 1000) } return ( <div className="next-red-envelop"> <p>{isStart ? '距离结束' : '距离开始'}</p> <p id="countdown" className="countdown">{redEnvelop ? '00:00:00' : '没有红包'}</p> </div> ) } } export default Countdown <file_sep>/src/routes/Index/components/IndexView.js import React from 'react' import './IndexView.scss' import { api } from 'services/fetch' import { Dialog } from 'react-weui' import shopIcon from './assets/shop.png' import train from './assets/train.png' class IndexView extends React.Component { static propTypes = { serviceList: React.PropTypes.array.isRequired, getServiceCategory: React.PropTypes.func.isRequired } constructor(props) { super(props) this.show = this.show.bind(this) } static contextTypes = { router: React.PropTypes.object.isRequired } state = { showIOS1: false, style1: { buttons: [ { label: 'Ok', onClick: this.hideDialog.bind(this) } ] } }; hideDialog() { this.setState({ showIOS1: false }) } componentDidMount() { const { getServiceCategory } = this.props getServiceCategory() } render() { const query = location.href.split('?')[1] || '' const { serviceList } = this.props const fixServiceList = [{ icon: shopIcon, id: 0, name: '蜂币商城', sort: 0, onClick: () => { location.href = 'http://shop.hxzcgf.cn/?' + query } }, { icon: train, id: 3, name: '培训活动', sort: 1, onClick : () => this.context.router.push('train/index/?id=' + 3) }] const allServiceList = fixServiceList.concat( serviceList.map(s => { s.onClick = () => this.context.router.push('train/index/?id=' + s.id) return s })) return (<div className="index-view"> <img className="banner" src="http://api.shop.hxzcgf.cn/Assets/upload/2016/11/10/赚蜂币,抢豪礼1478770496.png" /> <div className="navs-wapper"> <div className="navs"> { allServiceList.map((service) => this.renderRankingRow(service)) } </div> </div > <Dialog type="ios" title={this.state.style1.title} buttons={this.state.style1.buttons} show={this.state.showIOS1}> 该功能还在开发中....... </Dialog> </div> ) } show() { this.setState({ showIOS1: true }) } renderRankingRow(service) { return <a className="nav" key={service.name} href="javascript:void(0);" onClick={service.onClick}> <div className="nav-icon"> <img src={service.icon.indexOf('data') > -1 ? service.icon : `${api.imgHost}/${service.icon}`} /> </div> <p className="nav-label"> {service.name} </p> </a> } } export default IndexView <file_sep>/src/components/TopicContainer/index.js import TopicContainer from './TopicContainer' export default TopicContainer <file_sep>/src/layouts/CoreLayout/CoreLayout.js import React from 'react' import { connect } from 'react-redux' import { Toast } from 'react-weui' import Footer from '../../components/Footer' import Toptips from '../../components/Toptips' import './CoreLayout.scss' export const CoreLayout = (props) => { const contentMinHeightCls = { minHeight: document.documentElement.clientHeight - 24 + 'px' } return ( <div> <div style={contentMinHeightCls}> {props.children} </div> <Footer /> <Toast icon="loading" show={props.loading}>加载中</Toast> <Toptips show={!!props.error} text={props.error} /> </div > ) } CoreLayout.propTypes = { children: React.PropTypes.element.isRequired, loading: React.PropTypes.bool, error: React.PropTypes.string } const mapStateToProps = (state) => ({ loading: state.home.loading || false, error: state.home.error || '' }) export default connect(mapStateToProps, {})(CoreLayout) <file_sep>/src/services/auth.js import { api, fetchJson } from './fetch' let currentUser = { name: '', code: '' } export default { login() { window.location.href = `${api.passport}/login?redirectURL=${encodeURIComponent(window.location.href)}&_rc=${sessionStorage['_rc']}` }, logout() { window.location.href = `${api.passport}/logout?redirectURL=${encodeURIComponent(window.location.href)}` }, fetchAntiForgery() { fetchJson(api.antiForgery, {}, 'get') .then(({ json }) => { localStorage.XSRFTOKEN = json }) }, fetchUserInfo() { fetchJson(`${api.passportApi}/api/app/account/info`, {}, 'get') .then(({ json }) => { currentUser = json.result }) }, getUserInfo() { return currentUser }, getAntiForgeryToken() { return localStorage.XSRFTOKEN || '' } } <file_sep>/src/components/VoterItem/index.js import VoterItem from './VoterItem' export default VoterItem <file_sep>/src/routes/Lottery/components/Turntable.js import React from 'react' import './Turntable.scss' import pointerImage from './assets/turntable-pointer.png' import './wilq32' class Turntable extends React.PureComponent { static propTypes = { products: React.PropTypes.array.isRequired, onRotate: React.PropTypes.func.isRequired, rotate: React.PropTypes.bool.isRequired } state = { isStop: true } offsetWidth = (document.body.OffsetWidth || document.documentElement.clientWidth) - 20 constructor(props) { super(props) this.handleRotate = this.handleRotate.bind(this) } componentDidUpdate() { const { products } = this.props const ctx = this.refs.prize.getContext('2d') this.rednerPrize(products, ctx) } componentWillReceiveProps(nextProps) { if (nextProps.rotate) { this.handleRotate() } } shouldComponentUpdate(nextProps, nextState) { if (nextProps.products.length === this.props.products.length && nextProps.rotate === this.props.rotate && nextState.isStop === this.state.isStop) { return false } return true } render() { return ( <div className="turntable-banner"> <div className="turntable" style={{ height: this.offsetWidth }}> <canvas className="prize-list" ref="prize" width={this.offsetWidth} height={this.offsetWidth} /> <img src={pointerImage} className="pointer" onClick={this.handleRotate} /> </div> </div> ) } rednerPrize(products, ctx) { const turnplate = { outsideRadius: (this.offsetWidth - 31) / 2, // 大转盘外圆的半径 textRadius: (this.offsetWidth - 85) / 2, // 大转盘奖品位置距离圆心的距离 insideRadius: (this.offsetWidth - 235) / 2, // 大转盘内圆的半径 startAngle: 0 // 开始角度 } const arc = Math.PI / (products.length / 2) // 在给定矩形内清空一个矩形 ctx.clearRect(0, 0, this.offsetWidth, this.offsetWidth) ctx.strokeStyle = '#FFBE04' // font 属性设置或返回画布上文本内容的当前字体属性 ctx.font = 'bold 16px -apple-system-font,Helvetica Neue,sans-serif' for (let i = 0; i < products.length; i++) { const angle = turnplate.startAngle + i * arc ctx.fillStyle = i % 2 === 0 ? '#FFF4D6' : '#FFFFFF' ctx.beginPath() // arc(x,y,r,起始角,结束角,绘制方向) 方法创建弧/曲线用于创建圆或部分圆 ctx.arc(this.offsetWidth / 2, this.offsetWidth / 2, turnplate.outsideRadius, angle, angle + arc, false) ctx.arc(this.offsetWidth / 2, this.offsetWidth / 2, turnplate.insideRadius, angle + arc, angle, true) ctx.stroke() ctx.fill() // 锁画布(为了保存之前的画布状态) ctx.save() // ----绘制奖品开始---- ctx.fillStyle = '#E5302F' // translate方法重新映射画布上的 (0,0) 位置 ctx.translate( this.offsetWidth / 2 + Math.cos(angle + arc / 2) * turnplate.textRadius, this.offsetWidth / 2 + Math.sin(angle + arc / 2) * turnplate.textRadius) // rotate方法旋转当前的绘图 ctx.rotate(angle + arc / 2 + Math.PI / 2) var text = products[i].name ctx.fillText(text, -ctx.measureText(text).width / 2, 0) // img是先在外部先download下 ctx.drawImage(document.getElementById(products[i].id), -20, 10) // 把当前画布返回调整到上一个save状态之前 ctx.restore() } } handleRotate() { if (!this.state.isStop) { return } this.state.isStop = false const { onRotate, products } = this.props const cfg = { angle: 0, animateTo: 1800, duration: 8000, callback: () => { this.state.isStop = true } } const wilq32 = new window.Wilq32.PhotoEffect(this.refs.prize, cfg) onRotate(result => { let index = 0 for (let i = 0; i < products.length; i++) { if (products[i].id === result.productId) { index = i + 1 } } let angles = index * (360 / products.length) - (360 / (products.length * 2)) if (angles < 270) { angles = 270 - angles } else { angles = 360 - angles + 270 } cfg.animateTo = angles + 1800 // const cfg = { // angle: 0, // animateTo: angles + 1800, // duration: 8000, // callback: () => { // this.state.isStop = true // } // } // return new window.Wilq32.PhotoEffect(this.refs.prize, cfg) wilq32._handleRotation(cfg) }) } } export default Turntable <file_sep>/src/routes/Index/modules/index.js import { api, injectApi, DEFAULT_FAILURE } from 'services/fetch' import { Schema, arrayOf } from 'normalizr' const serviceCategorySchema = new Schema('serviceCategory') // ------------------------------------ // Constants // ------------------------------------ export const SERVICE_CATEGORY_LIST_REQUEST = 'SERVICE_CATEGORY_LIST_REQUEST' export const SERVICE_CATEGORY_LIST_SUCCESS = 'SERVICE_CATEGORY_LIST_SUCCESS' export const SERVICE_CATEGORY_LIST_FAILURE = DEFAULT_FAILURE // ------------------------------------ // Actions // ------------------------------------ export const getServiceCategory = () => injectApi({ endpoint: api.companyService + '/getServiceCategoryList', method: 'get', schema: arrayOf(serviceCategorySchema), types: [ SERVICE_CATEGORY_LIST_REQUEST, SERVICE_CATEGORY_LIST_SUCCESS, SERVICE_CATEGORY_LIST_FAILURE ] }) export const actions = { getServiceCategory } // ------------------------------------ // Action Handlers // ------------------------------------ const ACTION_HANDLERS = { [SERVICE_CATEGORY_LIST_SUCCESS]: (state, { payload }) => { // console.log(payload) return Object.assign({}, state, { serviceCategorys: payload.entities.serviceCategory, servicePagination: payload.result }) } // [SERVICE_CATEGORY_LIST_SUCCESS]: (state, { payload }) => { // state.serviceCategorys = payload.entities.serviceCategory // state.servicePagination = payload.result // console.log(state.servicePagination) // return Object.assign({}, state) // } } // ------------------------------------ // Reducer // ------------------------------------ const initialState = { serviceCategorys: {}, servicePagination: [] } export default function counterReducer(state = initialState, action) { const handler = ACTION_HANDLERS[action.type] return handler ? handler(state, action) : state } <file_sep>/src/middleware/apiErrorsMiddleware.js import auth from '../services/auth' export default ({ dispatch, getState }) => next => action => { if (action.type === 'FAILURE') { if (action.payload.status === 401) { auth.login() return } } const requestType = action.type.slice(action.type.lastIndexOf('_') + 1) if (requestType === 'FAILURE') { setTimeout(() => { dispatch({ type: 'CLEART_ERROR' }) }, 1500) } return next(action) } <file_sep>/src/routes/Signup/containers/SignupContainer.js import { connect } from 'react-redux' import { getTopic } from '../../Home/modules/home' import { upload, submitSingup, getSignup } from '../modules/signup' import SignupView from '../components/SignupView' const mapDispatchToProps = { getTopic, submitSingup, getSignup } const mapStateToProps = ({ home, signup }) => { return { topic: home.topic, signup, upload } } export default connect(mapStateToProps, mapDispatchToProps)(SignupView) <file_sep>/src/routes/Signup/components/SignupView.js import React from 'react' import TopicContainer from 'components/TopicContainer' import RegionTitle from 'components/RegionTitle' import './SignupView.scss' import SignupForm from './SignupForm' export const SignupView = (props) => { const { topic, signup, getSignup, submitSingup, upload } = props const handleOnSubmit = (signup, cb) => { signup.topicId = topic.id submitSingup(signup, cb) } const bindGeSignup = () => getSignup(topic.id) return ( <TopicContainer {...props}> <div className="region signup-view"> <RegionTitle title={`${signup.id ? '已报名' : '报名中心'}`} /> <SignupForm onUpload={upload} onSubmit={handleOnSubmit} signup={signup} getSignup={bindGeSignup} topicId={props.topic.id} /> </div> </TopicContainer> ) } SignupView.propTypes = { topic: React.PropTypes.object.isRequired, signup: React.PropTypes.object, upload: React.PropTypes.func.isRequired, submitSingup: React.PropTypes.func.isRequired, getSignup: React.PropTypes.func.isRequired } export default SignupView <file_sep>/src/routes/RedEnvelopTopic/components/RedEnvelopTopicView.js import React from 'react' import { api } from 'services/fetch' import RedEnvelopList from './RedEnvelopList' import './RedEnvelopTopicView.scss' import topicHeaer from './assets/topic-heaer.png' import appQR from './assets/appQR.png' class RedEnvelopTopicView extends React.PureComponent { static propTypes = { params: React.PropTypes.object.isRequired, location: React.PropTypes.object.isRequired, topic: React.PropTypes.object.isRequired, getRedEnvelopTopic: React.PropTypes.func.isRequired, getCanTakeRedEnvelopList: React.PropTypes.func.isRequired, redEnvelopList: React.PropTypes.array.isRequired } componentDidMount() { const { getRedEnvelopTopic, getCanTakeRedEnvelopList, params } = this.props getRedEnvelopTopic(params.id) getCanTakeRedEnvelopList(params.id) } constructor(props) { super(props) if (props.location.query.c) { sessionStorage['red-envelop-share-code'] = props.location.query.c } } render() { const { topic, redEnvelopList } = this.props return ( <div className="red-envelop-topic-container"> <div className="top-bg"> <img src={topicHeaer} className="img" /> </div> <RedEnvelopList data={redEnvelopList} /> <img src={`${api.imgHost}/${topic.desc}`} className="img" /> <div className="app-download"> <img src={appQR} className="img" /> <p>扫码下载App</p> </div> </div> ) } } export default RedEnvelopTopicView <file_sep>/src/routes/Lottery/components/UserDrawRecord.js import React from 'react' import { Icon } from 'react-weui' import './UserDrawRecord.scss' export const UserDrawRecord = ({ drawRecord, onSetAddress }) => { const rednerOper = (dr) => { if (dr.isPointsProduct) { return <span className="icon-txt"><Icon value="success-circle" />已领取</span> } else { if (dr.isShip) { return <span className="icon-txt"><Icon value="success-circle" />已发货</span> } else { if (dr.shippingAddress) { return <span className="icon-txt"><Icon value="waiting-circle" />等待发货</span> } else { return <span className="icon-txt"><Icon value="warn" />点击设置地址</span> } } } } const handleClick = (dr) => { return () => { if ((!dr.isPointsProduct) && (!dr.shippingAddress)) { onSetAddress(dr) } } } return <div className="user-draw-record" id="userDrawRecord"> <label className="label-bg">我的中奖</label> <ul> { drawRecord.map((dr, index) => <li key={dr.id}> <p>{ dr.creationTime.replace('T', ' ').split(':')[0] + ':' + dr.creationTime.replace('T', ' ').split(':')[1] }&nbsp;</p> <p>奖品:<b>{dr.productName}</b></p> <p className="oper" onClick={handleClick(dr)}>{rednerOper(dr)}</p> </li>) } </ul> </div> } UserDrawRecord.propTypes = { drawRecord: React.PropTypes.array.isRequired, onSetAddress: React.PropTypes.func.isRequired } export default UserDrawRecord <file_sep>/src/middleware/loadingMiddleware.js export default ({ dispatch, getState }) => next => action => { const requestType = action.type.slice(action.type.lastIndexOf('_') + 1) const state = getState() const loading = state.home ? state.home.loading : false if (requestType === 'REQUEST' && !loading) { dispatch({ type: 'LOADING', loading: true }) } else if (requestType === 'SUCCESS' && loading) { dispatch({ type: 'LOADING', loading: false }) } else if (requestType === 'FAILURE') { dispatch({ type: 'LOADING', loading: false }) } return next(action) } <file_sep>/gulpfile.js var gulp = require('gulp') var gutil = require('gulp-util') var ftp = require('vinyl-ftp') gulp.task('ftp', function () { var conn = ftp.create({ host: 'vote.hxzcgf.cn', port: 215, user: 'vote.app', password: '<PASSWORD>', parallel: 3, log: gutil.log }) return gulp.src('dist/**/*') .pipe(conn.dest('/')) }) <file_sep>/src/routes/Lottery/components/LotteryView.js import React from 'react' import './LotteryView.scss' import { api } from 'services/fetch' import Turntable from './Turntable' import LotteryResult from './LotteryResult' import GlobalDrawRecord from './GlobalDrawRecord' import UserDrawRecord from './UserDrawRecord' import AddressPopup from 'components/AddressPopup' import AddressEditor from 'components/AddressEditor' import Share from 'components/Share' class LotteryView extends React.PureComponent { static propTypes = { id: React.PropTypes.string.isRequired, products: React.PropTypes.array.isRequired, globalDrawRecords: React.PropTypes.array.isRequired, userDrawRecords: React.PropTypes.array.isRequired, userWallet: React.PropTypes.object.isRequired, shippingAddress: React.PropTypes.array.isRequired, getProducts: React.PropTypes.func.isRequired, getWallet: React.PropTypes.func.isRequired, draw: React.PropTypes.func.isRequired, addPoints: React.PropTypes.func.isRequired, getGlobalDrawRecords: React.PropTypes.func.isRequired, getUserDrawRecords: React.PropTypes.func.isRequired, getShippingAddress: React.PropTypes.func.isRequired, saveShippingAddress: React.PropTypes.func.isRequired, setShippingAddress: React.PropTypes.func.isRequired } state = { result: {}, showResult: false, rotate: false, showAddress: false, showAddressEditor: false, showShare: false } shareContent = { title: '蜂动全城,百分百中奖,百万蜂币等你来抽', desc: '免费贺岁大片,优惠意大利西餐,韩国智力拼图,20w份大礼全城随心抽', link: window.location.href, headerimage: `${api.imgHost}/f0/f0a3e45b5957dd55916085198212abd3.png` } constructor(props) { super(props) this.handleOnRotate = this.handleOnRotate.bind(this) this.handleRotate = this.handleRotate.bind(this) this.handleToUserRecord = this.handleToUserRecord.bind(this) this.handleSetAddress = this.handleSetAddress.bind(this) this.handleSelectedAddress = this.handleSelectedAddress.bind(this) this.handleSaveeditorAddress = this.handleSaveeditorAddress.bind(this) this.handleShowResult = this.handleShowResult.bind(this) this.handleAddressPopupOnRequestClose = this.handleAddressPopupOnRequestClose.bind(this) this.handleAddressPopupOnEdit = this.handleAddressPopupOnEdit.bind(this) this.handleAddressPopupOnChange = this.handleAddressPopupOnChange.bind(this) this.handleAddressEditorOnRequestClose = this.handleAddressEditorOnRequestClose.bind(this) this.handleShowShare = this.handleShowShare.bind(this) this.handleHideShare = this.handleHideShare.bind(this) } componentDidMount() { const { getProducts, getWallet, getGlobalDrawRecords, getUserDrawRecords, id } = this.props getProducts(id) getWallet() getGlobalDrawRecords(id) // this.timer = setInterval(() => { // getGlobalDrawRecords(id) // }, 5000) getUserDrawRecords(id) } componentWillUnmount() { this.timer && clearInterval(this.timer) } render() { const { products, userWallet, shippingAddress, globalDrawRecords, userDrawRecords } = this.props return ( <div className="lottery-container"> <div style={{ position: 'absolute', top: '-100px' }}> { // 这里的代码是为了兼容Turntable组件里的canvas画图 products.map(p => <img key={p.id} src={`${api.imgHost}/40_40_w/${p.image}`} id={p.id} />) } </div> <Turntable products={products} rotate={this.state.rotate} onRotate={this.handleOnRotate} /> <div className="user-wallet"> <h3>我的蜂币{userWallet.points}个</h3> <a className="my-draw-record" href="#userDrawRecord">中奖记录</a> <a className="my-draw-record" onClick={this.handleShowShare}>点击分享</a> </div> <div className="area-banner" /> <GlobalDrawRecord drawRecords={globalDrawRecords} /> <div className="rule"> <label className="label-bg">抽奖规则</label> <ul> <li>1.每次抽奖消耗20蜂币</li> <li>2.实物奖品将在7个工作日内寄出</li> <li>3.本活动在法律法规范围内,最终解释权归小蜂找事所有</li> </ul> </div> <div className="area-banner" /> <UserDrawRecord drawRecord={userDrawRecords} onSetAddress={this.handleSetAddress} /> { this.state.showResult && <LotteryResult result={this.state.result} onAgain={this.handleRotate} onCancel={this.handleShowResult} /> } <AddressPopup show={this.state.showAddress} shippingAddress={shippingAddress} onRequestClose={this.handleAddressPopupOnRequestClose} onRequestOk={this.handleSelectedAddress} onEdit={this.handleAddressPopupOnEdit} onChange={this.handleAddressPopupOnChange} /> <AddressEditor onRequestClose={this.handleAddressEditorOnRequestClose} onRequestSave={this.handleSaveeditorAddress} show={this.state.showAddressEditor} /> <Share show={this.state.showShare} content={this.shareContent} onHide={this.handleHideShare} /> </div> ) } handleOnRotate(cb) { const { draw, id, addPoints, products } = this.props draw(id, (json) => { if (json.success) { const { result } = json var filterProduct = products.filter(p => p.id === result.productId) if (filterProduct.length > 0) result.image = filterProduct[0].image cb(result) setTimeout(() => { if (result.isPoints) { addPoints(result.points) } this.setState({ showResult: true, result }) }, 7000) } this.setState({ rotate: false }) }) } handleRotate() { this.setState({ rotate: true, showResult: false }) } handleToUserRecord() { document.body.scroll(700) } handleSetAddress(drawRecord) { const { getShippingAddress, shippingAddress } = this.props this.setState({ showAddress: true, setAddressDrawRecord: drawRecord }) if (shippingAddress.length === 0) { getShippingAddress() } } handleSelectedAddress() { const { setShippingAddress } = this.props const { setAddressDrawRecord, selectedAddress } = this.state if (selectedAddress) { setShippingAddress(setAddressDrawRecord.id, selectedAddress) this.setState({ showAddress: false }) } } handleSaveeditorAddress(address) { const { saveShippingAddress } = this.props saveShippingAddress(address) this.setState({ showAddressEditor: false, showAddress: true }) } handleShowResult() { this.setState({ showResult: false }) } handleAddressPopupOnRequestClose() { this.setState({ showAddress: false }) } handleAddressPopupOnEdit() { this.setState({ showAddressEditor: true, showAddress: false }) } handleAddressPopupOnChange(e) { this.setState({ selectedAddress: e.target.value }) } handleAddressEditorOnRequestClose() { this.setState({ showAddressEditor: false, showAddress: true }) } handleHideShare() { this.setState({ showShare: false }) } handleShowShare() { this.setState({ showShare: true }) } } export default LotteryView <file_sep>/src/components/MiniSearch/MiniSearch.js import React from 'react' import { PopupHeader, Popup, SearchBar } from 'react-weui' import './MiniSearch.scss' export const MiniSearch = ({ show, onSubmit, onCancel, onChange }) => ( <Popup show={show} onRequestClose={onCancel}> <PopupHeader left="取消" right="确定" leftOnClick={onCancel} rightOnClick={onSubmit} /> <div className="mini-search"> <SearchBar onChange={onChange} placeholder="请输入编号或昵称" /> </div> </Popup> ) MiniSearch.propTypes = { show: React.PropTypes.bool.isRequired, onSubmit: React.PropTypes.func.isRequired, onCancel: React.PropTypes.func.isRequired, onChange: React.PropTypes.func.isRequired } export default MiniSearch <file_sep>/src/components/VoterList/index.js import VoterList from './VoterList' export default VoterList <file_sep>/src/routes/Home/modules/home.js import { api, injectApi, DEFAULT_FAILURE, LOADING, CLEART_ERROR } from 'services/fetch' import { Schema, arrayOf } from 'normalizr' const topicSchema = new Schema('topic') const voterSchema = new Schema('voter') // ------------------------------------ // Constants // ------------------------------------ export const TOPIC_INFO_REQUEST = 'TOPIC_INFO_REQUEST' export const TOPIC_INFO_SUCCESS = 'TOPIC_INFO_SUCCESS' export const TOPIC_INFO_FAILURE = DEFAULT_FAILURE export const VOTER_LIST_REQUEST = 'VOTER_LIST_REQUEST' export const VOTER_LIST_SUCCESS = 'VOTER_LIST_SUCCESS' export const VOTER_LIST_FAILURE = DEFAULT_FAILURE export const MY_VOTER_REQUEST = 'MY_VOTER_REQUEST' export const MY_VOTER_SUCCESS = 'MY_VOTER_SUCCESS' export const MY_VOTER_FAILURE = DEFAULT_FAILURE export const VOTING_REQUEST = 'VOTING_REQUEST' export const VOTING_SUCCESS = 'VOTING_SUCCESS' export const VOTING_FAILURE = DEFAULT_FAILURE // ------------------------------------ // Actions // ------------------------------------ export const getTopic = (topicId) => injectApi({ endpoint: api.topic + '/getTopic', method: 'get', body: { id: topicId }, schema: topicSchema, types: [ TOPIC_INFO_REQUEST, TOPIC_INFO_SUCCESS, TOPIC_INFO_FAILURE ] }) export const getMyVoter = (topicId) => injectApi({ endpoint: api.topic + '/getMyVoter', method: 'get', body: { id: topicId }, schema: voterSchema, types: [ MY_VOTER_REQUEST, MY_VOTER_SUCCESS, MY_VOTER_FAILURE ] }) export const getVoters = (topicId, order = 1) => injectApi({ endpoint: api.topic + '/getVoterList', method: 'get', body: { topicId, pageSize: 100, current: 1, order }, schema: arrayOf(voterSchema), types: [ VOTER_LIST_REQUEST, VOTER_LIST_SUCCESS, VOTER_LIST_FAILURE ] }) export const voting = (voterId, onSuccess) => injectApi({ endpoint: api.topic + '/voting', method: 'post', body: { id: voterId }, onSuccess, types: [ VOTING_REQUEST, VOTING_SUCCESS, VOTING_FAILURE ] }) export const actions = { getTopic, getVoters, getMyVoter, voting } // ------------------------------------ // Action Handlers // ------------------------------------ const ACTION_HANDLERS = { [LOADING]: (state, action) => Object.assign({}, state, { loading: action.loading }), [TOPIC_INFO_SUCCESS]: (state, { payload }) => { console.log(sessionStorage.getItem('id')) const { entities: { topic }, result } = payload return Object.assign({}, state, { topic: topic[result] }) }, [VOTER_LIST_SUCCESS]: (state, action) => { const { payload } = action // console.log(payload) return Object.assign({}, state, { voters: payload.entities.voter, voterPagination: payload.pagination }) }, [MY_VOTER_SUCCESS]: (state, { payload }) => { const { entities: { voter }, result } = payload return Object.assign({}, state, { myVoter: voter[result] }) }, [VOTING_SUCCESS]: (state, { payload }) => { state.voters[payload.body.id].numberOfVotes++ return Object.assign({}, state) }, [DEFAULT_FAILURE]: (state, action) => { return Object.assign({}, state, { error: action.payload.response.error.message }) }, [CLEART_ERROR]: (state, action) => { return Object.assign({}, state, { error: '' }) } } // ------------------------------------ // Reducer // ------------------------------------ const initialState = { topic: { id: sessionStorage.getItem('id'), voterSum: 0, numberOfVoteSum: 0, viewSum: 0, voteTime: { startTime: '', endTime: '' } }, voters: {}, voterPagination: { ids: [], total: 0, current: 0, pageSize: 100 } } export default function counterReducer(state = initialState, action) { const handler = ACTION_HANDLERS[action.type] return handler ? handler(state, action) : state } <file_sep>/src/routes/Voter/components/VoterView.js import React from 'react' import PureRenderMixin from 'react-addons-pure-render-mixin' import { ButtonArea, Button } from 'react-weui' import TopicContainer from 'components/TopicContainer' import VotingButton from 'components/VotingButton' import Share from 'components/Share' import './VoterView.scss' import { api } from 'services/fetch' class VoterView extends React.Component { static propTypes = { id: React.PropTypes.string.isRequired, topic: React.PropTypes.object.isRequired, voter: React.PropTypes.object.isRequired, getVoterDetail: React.PropTypes.func.isRequired, voting: React.PropTypes.func.isRequired } static contextTypes = { router: React.PropTypes.object.isRequired } state = { showShare: false } constructor(props) { super(props) this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this) this.handleToNext = this.handleToNext.bind(this) this.handleShare = this.handleShare.bind(this) this.handleHideShare = this.handleHideShare.bind(this) } componentDidMount() { const { getVoterDetail, id } = this.props getVoterDetail(id) } componentWillReceiveProps(nextProps) { const { id } = nextProps if (id && (id !== this.props.id)) { this.props.getVoterDetail(id) } } render() { const { voter, voting } = this.props return ( <TopicContainer {...this.props}> <div className="region voter-view"> <div className="voter-warp"> <div className="ranking"> <p>排名:{voter.ranking}</p> <p>票数:{voter.numberOfVotes}</p> </div> <div className="voter-info"> <p>昵称:{voter.name}</p> <p>编号:{voter.number}</p> <p>与上一名差距:{voter.difference}票</p> { voter.descriptions && voter.descriptions.map(d => <div key={d.id} className="voter-info"> <p className="headerimage"> <img src={`${api.imgHost}/500x500_w/${d.image}`} /> </p> <p>{d.text}</p> </div>) } </div> </div> <ButtonArea direction="horizontal" className="button-area"> <VotingButton voterId={voter.id} onVoting={voting} className="weui-btn_xf" /> <Button onClick={this.handleShare}>拉票</Button> <Button type="default" onClick={this.handleToNext}>下一条</Button> </ButtonArea> <Share show={this.state.showShare} content={this.getShareContent()} onHide={this.handleHideShare} /> </div> </TopicContainer > ) } handleToNext() { const next = this.props.voter.next next && this.context.router.push(`/topic/voter/${next}`) } handleShare() { this.setState({ showShare: true }) } handleHideShare() { this.setState({ showShare: false }) } getShareContent() { const faceDescription = this.props.voter && this.props.voter.descriptions ? this.props.voter.descriptions[0] : { text: '', image: '' } return { title: '你回家你旅游我买单', desc: faceDescription.text, link: `http://${window.location.host}/topic/voter/${this.props.voter.id}?id=${this.props.topic.id}`, headerimage: `${api.imgHost}/${faceDescription.image}` } } } export default VoterView <file_sep>/src/components/VotingButton/index.js import VotingButton from './VotingButton' export default VotingButton <file_sep>/src/routes/Home/containers/HomeContainer.js import { connect } from 'react-redux' import { getTopic, getVoters, voting } from '../modules/home' import HomeView from '../components/HomeView' const mapDispatchToProps = { getTopic, getVoters, voting } const mapStateToProps = ({ home }, ownProps) => { const { voters, voterPagination } = home const { location: { query } } = ownProps let allVoters = voterPagination.ids.map(id => voters[id]) || [] if (query.q) { allVoters = allVoters.filter(v => v.number.toString() === query.q || (v.name.indexOf(query.q) > -1)) } return { topic: home.topic, voters: allVoters } } export default connect(mapStateToProps, mapDispatchToProps)(HomeView) <file_sep>/src/routes/Lottery/containers/LotteryContainer.js import { connect } from 'react-redux' import * as actions from '../modules/lottery' import LotteryView from '../components/LotteryView' const mapDispatchToProps = { ...actions } const mapStateToProps = ({ lottery }, ownProps) => { const { products, productsPagination, userWallet, drawRecords, shippingAddress, gloablDrawRecordPagination, userDrawRecordPagination, shippingAddressPagination } = lottery return { id: ownProps.location.query.id, products: productsPagination.ids.map(id => products[id]) || [], userWallet, globalDrawRecords: gloablDrawRecordPagination.ids.map(id => drawRecords[id]) || [], userDrawRecords: userDrawRecordPagination.ids.map(id => drawRecords[id]) || [], shippingAddress: shippingAddressPagination.ids.map(id => shippingAddress[id]) || [] } } export default connect(mapStateToProps, mapDispatchToProps)(LotteryView) <file_sep>/src/routes/Lottery/modules/lottery.js import { api, injectApi, DEFAULT_FAILURE } from 'services/fetch' import { Schema, arrayOf } from 'normalizr' const prodcutSchema = new Schema('product') const userWalletSchema = new Schema('userWallet') const drawRecordSchema = new Schema('drawRecord') const shippingAddressSchema = new Schema('shippingAddress') // ------------------------------------ // Constants // ------------------------------------ export const PRODCUT_LIST_REQUEST = 'PRODCUT_LIST_REQUEST' export const PRODCUT_LIST_SUCCESS = 'PRODCUT_LIST_SUCCESS' export const PRODCUT_LIST_FAILURE = DEFAULT_FAILURE export const USER_WALLET_REQUEST = 'USER_WALLET_REQUEST' export const USER_WALLET_SUCCESS = 'USER_WALLET_SUCCESS' export const USER_WALLET_FAILURE = DEFAULT_FAILURE export const DRAW_REQUEST = 'DRAW_REQUEST_NOT' export const DRAW_SUCCESS = 'DRAW_SUCCESS_NOT' export const DRAW_FAILURE = DEFAULT_FAILURE export const ADD_USER_WALLET_POINTS = 'ADD_USER_WALLET_POINTS' export const DRAW_RECORDS_LIST_REQUEST = 'DRAW_RECORDS_LIST_REQUEST_NOT' export const DRAW_RECORDS_LIST_SUCCESS = 'DRAW_RECORDS_LIST_SUCCESS_NOT' export const DRAW_RECORDS_LIST_FAILURE = DEFAULT_FAILURE export const USER_DRAW_RECORDS_LIST_REQUEST = 'USER_DRAW_RECORDS_LIST_REQUEST' export const USER_DRAW_RECORDS_LIST_SUCCESS = 'USER_DRAW_RECORDS_LIST_SUCCESS' export const USER_DRAW_RECORDS_LIST_FAILURE = DEFAULT_FAILURE export const SHIPPING_ADDRESS_LIST_REQUEST = 'SHIPPING_ADDRESS_LIST_REQUEST' export const SHIPPING_ADDRESS_LIST_SUCCESS = 'SHIPPING_ADDRESS_LIST_SUCCESS' export const SHIPPING_ADDRESS_LIST_FAILURE = DEFAULT_FAILURE export const SAVE_SHIPPING_ADDRESS_REQUEST = 'SAVE_SHIPPING_ADDRESS_REQUEST' export const SAVE_SHIPPING_ADDRESS_SUCCESS = 'SAVE_SHIPPING_ADDRESS_SUCCESS' export const SAVE_SHIPPING_ADDRESS_FAILURE = DEFAULT_FAILURE export const SET_SHIPPING_ADDRESS_REQUEST = 'SET_SHIPPING_ADDRESS_REQUEST' export const SET_SHIPPING_ADDRESS_SUCCESS = 'SET_SHIPPING_ADDRESS_SUCCESS' export const SET_SHIPPING_ADDRESS_FAILURE = DEFAULT_FAILURE // ------------------------------------ // Actions // ------------------------------------ export const getProducts = (lotteryId) => injectApi({ endpoint: api.lottery + '/getProductList', method: 'get', body: { id: lotteryId }, schema: arrayOf(prodcutSchema), types: [ PRODCUT_LIST_REQUEST, PRODCUT_LIST_SUCCESS, PRODCUT_LIST_FAILURE ] }) export const getWallet = () => injectApi({ endpoint: api.order + '/getCurrentUserWallet', method: 'get', schema: userWalletSchema, types: [ USER_WALLET_REQUEST, USER_WALLET_SUCCESS, USER_WALLET_FAILURE ] }) export const draw = (id, onSuccess) => injectApi({ endpoint: api.lottery + '/draw', method: 'post', body: { id }, schema: drawRecordSchema, types: [ DRAW_REQUEST, DRAW_SUCCESS, DRAW_FAILURE ], onSuccess }) export const addPoints = (points) => { return { type: ADD_USER_WALLET_POINTS, points: points } } export const getGlobalDrawRecords = (id) => injectApi({ endpoint: api.lottery + '/getLotteryecords', method: 'get', body: { id, pageSize: 5, current: 1, isWinning: true }, schema: arrayOf(drawRecordSchema), types: [ DRAW_RECORDS_LIST_REQUEST, DRAW_RECORDS_LIST_SUCCESS, DRAW_RECORDS_LIST_FAILURE ] }) export const getUserDrawRecords = (id) => injectApi({ endpoint: api.lottery + '/getLotteryecords', method: 'get', body: { id, pageSize: 50, current: 1, isWinning: true, isSelf: true }, schema: arrayOf(drawRecordSchema), types: [ USER_DRAW_RECORDS_LIST_REQUEST, USER_DRAW_RECORDS_LIST_SUCCESS, USER_DRAW_RECORDS_LIST_FAILURE ] }) export const getShippingAddress = () => injectApi({ endpoint: api.delivery + '/getShippingAddressList', method: 'get', schema: arrayOf(shippingAddressSchema), types: [ SHIPPING_ADDRESS_LIST_REQUEST, SHIPPING_ADDRESS_LIST_SUCCESS, SHIPPING_ADDRESS_LIST_FAILURE ] }) export const saveShippingAddress = (sa) => injectApi({ endpoint: api.delivery + '/saveShippingAddress', method: 'post', body: sa, schema: shippingAddressSchema, types: [ SAVE_SHIPPING_ADDRESS_REQUEST, SAVE_SHIPPING_ADDRESS_SUCCESS, SAVE_SHIPPING_ADDRESS_FAILURE ] }) export const setShippingAddress = (lotteryRecordId, shippingAddressId) => injectApi({ endpoint: api.lottery + '/SetShippingAddress', method: 'post', body: { id: lotteryRecordId, shippingAddressId }, types: [ SET_SHIPPING_ADDRESS_REQUEST, SET_SHIPPING_ADDRESS_SUCCESS, SET_SHIPPING_ADDRESS_FAILURE ] }) export const actions = { getProducts, getWallet, draw, addPoints, getGlobalDrawRecords, getUserDrawRecords, getShippingAddress, saveShippingAddress, setShippingAddress } // ------------------------------------ // Action Handlers // ------------------------------------ const ACTION_HANDLERS = { [PRODCUT_LIST_SUCCESS]: (state, { payload }) => { state.products = payload.entities.product state.productsPagination = payload.pagination return Object.assign({}, state) }, [USER_WALLET_SUCCESS]: (state, { payload }) => { const { entities: { userWallet }, result } = payload state.userWallet = userWallet[result] return Object.assign({}, state) }, [DRAW_SUCCESS]: (state, { payload }) => { const { entities: { drawRecord }, result } = payload const dr = drawRecord[result] state.drawRecords[result] = drawRecord[result] state.userDrawRecordPagination.ids.push(result) state.userWallet.points -= dr.payPoints return Object.assign({}, state) }, [ADD_USER_WALLET_POINTS]: (state, action) => { state.userWallet.points += action.points return Object.assign({}, state) }, [DRAW_RECORDS_LIST_SUCCESS]: (state, { payload }) => { const { entities: { drawRecord }, pagination } = payload state.drawRecords = Object.assign(state.drawRecords, drawRecord) state.gloablDrawRecordPagination = pagination return Object.assign({}, state) }, [USER_DRAW_RECORDS_LIST_SUCCESS]: (state, { payload }) => { const { entities: { drawRecord }, pagination } = payload state.drawRecords = Object.assign(state.drawRecords, drawRecord) state.userDrawRecordPagination = pagination return Object.assign({}, state) }, [SHIPPING_ADDRESS_LIST_SUCCESS]: (state, { payload }) => { state.shippingAddress = payload.entities.shippingAddress state.shippingAddressPagination = { ids: payload.result } return Object.assign({}, state) }, [SAVE_SHIPPING_ADDRESS_SUCCESS]: (state, { payload }) => { const { entities: { shippingAddress }, result } = payload state.shippingAddress[result] = shippingAddress[result] state.shippingAddressPagination.ids.push(result) return Object.assign({}, state) }, [SET_SHIPPING_ADDRESS_SUCCESS]: (state, { payload }) => { state.drawRecords[payload.body.id].shippingAddress = payload.body.shippingAddressId return Object.assign({}, state) } } // ------------------------------------ // Reducer // ------------------------------------ const initialState = { products: [], productsPagination: { ids: [] }, userWallet: {}, drawRecords: {}, shippingAddress: {}, userDrawRecordPagination: { ids: [] }, gloablDrawRecordPagination: { ids: [] }, shippingAddressPagination: { ids: [] } } export default function counterReducer(state = initialState, action) { const handler = ACTION_HANDLERS[action.type] return handler ? handler(state, action) : state } <file_sep>/src/routes/RedEnvelopTake/index.js import NProgress from 'nprogress' import { injectReducer } from '../../store/reducers' export default (store) => ({ path: 'rd/take/:topicId/:id', getComponent(nextState, cb) { require.ensure([], (require) => { const Container = require('./containers/RedEnvelopTakeContainer').default const reducer = require('./modules/redEnvelopTake').default injectReducer(store, { key: 'redEnvelopTake', reducer }) const topicReducer = require('../RedEnvelopTopic/modules/redEnvelopTopic').default injectReducer(store, { key: 'redEnvelopTopic', reducer: topicReducer }) cb(null, Container) NProgress.done() }, 'redEnvelopTake') }, onEnter: () => { NProgress.start() } }) <file_sep>/src/routes/RedEnvelopTake/modules/redEnvelopTake.js import { api, injectApi, fetchJson, DEFAULT_FAILURE } from 'services/fetch' import { Schema } from 'normalizr' const redEnvelopSchema = new Schema('redEnvelop') // ------------------------------------ // Constants // ------------------------------------ export const RED_ENVELOP_REQUEST = 'RED_ENVELOP_REQUEST' export const RED_ENVELOP_SUCCESS = 'RED_ENVELOP_SUCCESS' export const RED_ENVELOP_FAILURE = DEFAULT_FAILURE export const RED_ENVELOP_TAKE_REQUEST = 'RED_ENVELOP_TAKE_REQUEST' export const RED_ENVELOP_TAKE_SUCCESS = 'RED_ENVELOP_TAKE_SUCCESS' export const RED_ENVELOP_TAKE_FAILURE = DEFAULT_FAILURE export const RECEIVE_TAKE_RESULT_REQUEST = 'RECEIVE_TAKE_RESULT_REQUEST' export const RECEIVE_TAKE_RESULT_SUCCESS = 'RECEIVE_TAKE_RESULT_SUCCESS' export const RECEIVE_TAKE_RESULT_FAILURE = DEFAULT_FAILURE // ------------------------------------ // Actions // ------------------------------------ export const getRedEnvelop = (id) => injectApi({ endpoint: api.redEnvelop + '/getRedEnvelop', method: 'get', body: { id }, schema: redEnvelopSchema, types: [ RED_ENVELOP_REQUEST, RED_ENVELOP_SUCCESS, RED_ENVELOP_FAILURE ] }) export const takeRedEnvelop = (id, onSuccess) => injectApi({ endpoint: api.redEnvelopQueue, method: 'post', body: { redEnvelopId: id }, onSuccess, types: [ RED_ENVELOP_TAKE_REQUEST, RED_ENVELOP_TAKE_SUCCESS, RED_ENVELOP_TAKE_FAILURE ] }) export const getTakeResult = (redEnvelopId, takeId, onSuccess) => injectApi({ endpoint: api.redEnvelop + '/getTakeingResult', method: 'get', body: { redEnvelopId, takeId }, onSuccess, types: [ RECEIVE_TAKE_RESULT_REQUEST, RECEIVE_TAKE_RESULT_SUCCESS, RECEIVE_TAKE_RESULT_FAILURE ] }) export const getShareCode = (data) => fetchJson( api.redEnvelop + '/getShareCode', data, 'get') export const trySaveShareRecords = (data) => fetchJson( api.redEnvelop + '/saveShareRecords', data, 'post') export const actions = { getRedEnvelop, takeRedEnvelop, getTakeResult } // ------------------------------------ // Action Handlers // ------------------------------------ const ACTION_HANDLERS = { [RED_ENVELOP_SUCCESS]: (state, { payload }) => { state.redEnvelop = payload.entities.redEnvelop[payload.result] return { ...state } } } // ------------------------------------ // Reducer // ------------------------------------ const initialState = { redEnvelop: {} // redEnvelopPagination: { ids: [] } } export default function counterReducer(state = initialState, action) { const handler = ACTION_HANDLERS[action.type] return handler ? handler(state, action) : state } <file_sep>/src/routes/PersonageIndex/containers/personageIndexContainer.js import { connect } from 'react-redux' import PersonageIndexView from '../components/PersonageIndexView' const mapDispatchToProps = { } const mapStateToProps = ({ index }) => { // // console.log(index) // const { serviceCategorys, servicePagination } = index // return { // serviceList: servicePagination.map(id => serviceCategorys[id]) || [] // } } export default connect(mapStateToProps, mapDispatchToProps)(PersonageIndexView) <file_sep>/src/routes/PersonageIndex/components/PersonageIndexView.js import React from 'react' import './PersonageIndexView.scss' import shop from './assets/shop.png' import canvass from './assets/canvass.png' import Lottery from './assets/Lottery.png' import RedEnvelop from './assets/RedEnvelop.png' import Nav from 'components/Nav' class IndexView extends React.Component { static propTypes = { } static contextTypes = { router: React.PropTypes.object.isRequired } // componentDidMount() { // const { getServiceCategory } = this.props // getServiceCategory() // // console.log(serviceList) // } render() { console.log(this.props) const query = location.href.split('?')[1] || '' const icons = [{ icon: < img src={shop} style={{ height: '45.5px' }} />, label: '蜂币商城', onClick: () => { location.href = 'http://shop.hxzcgf.cn?' + query } // http://shop.hxzcgf.cn?l=15927678095&p=fe35c6a960bf8a2560c237cc9b516dcf }, { icon: < img src={Lottery} style={{ height: '45.5px' }} />, label: '蜂狂抽奖', onClick: () => { location.href = 'http://vote.hxzcgf.cn/lottery/index?id=9616469a-e26d-45e1-a7aa-53b22f4f53dc&' + query } // http://vote.hxzcgf.cn/lottery/index?id=9616469a-e26d-45e1-a7aa-53b22f4f53dc"); }, { icon: < img src={RedEnvelop} style={{ height: '45.5px' }} />, label: '蜂抢红包', onClick: () => { location.href = 'http://vote.hxzcgf.cn/rd/topic/1' } }, { icon: < img src={canvass} style={{ height: '45.5px' }} />, label: '蜂拥拉票', onClick: () => { location.href = 'http://vote.hxzcgf.cn?id=9e74e4de-35b3-4b2e-9701-69ae7f9fc1ca&' + query } // http://vote.hxzcgf.cn?id=9e74e4de-35b3-4b2e-9701-69ae7f9fc1ca"); } ] return (<div className="index-view"> <img className="banner" src="http://api.shop.hxzcgf.cn/Assets/upload/2016/11/10/赚蜂币,抢豪礼1478770496.png" /> <div className="navs-wapper"> <Nav navs={[...icons]} /> </div > </div> ) } } export default IndexView <file_sep>/src/routes/Train/containers/TrainContainer.js import { connect } from 'react-redux' import { getService } from '../modules/train' import TrainView from '../components/TrainView' const mapDispatchToProps = { getService } const mapStateToProps = ({ train }) => { const { services, servicePagination } = train // console.log(train) return { params:train.params, services: servicePagination.ids.map(id => services[id]) || [] } } export default connect(mapStateToProps, mapDispatchToProps)(TrainView) <file_sep>/src/routes/RedEnvelopTake/components/ResultModal.js import React from 'react' import './ResultModal.scss' import { Dialog } from 'react-weui' import { api } from 'services/fetch' // import win from './assets/win.png' // import lose from './assets/lose.png' export const ResultModal = ({ show, result, onClose }) => ( <Dialog type="ios" show={show} className="result-modal"> <div className="close-wapper"><a className="close" onClick={onClose} href="javascript:void(0)">&nbsp;</a></div> <div className="content"> {/* <img src={result.status === 1 ? win : lose} className="status" /> */} <div className="bg"> <p className="text">{result.status === 1 ? `获得${result.type === 1 ? '现金' : '蜂币'}${result.value}${result.type === 1 ? '元' : '个'}` : '很遗憾~没有抢到'} </p> <p>红包由以下企业赞助</p> <a href={result.link}><img src={`${api.imgHost}/${result.face}`} className="face" /></a> { result.status === 1 && <a href={result.link} className="link">领取</a> } </div> </div> </Dialog> ) ResultModal.propTypes = { show: React.PropTypes.bool.isRequired, result: React.PropTypes.object.isRequired, onClose: React.PropTypes.func.isRequired } export default ResultModal <file_sep>/src/services/wxSdk.js import { api, fetchJson } from './fetch' export const wxSdk = { retries: 0, fetchCfg(currentUrl) { return fetchJson(api.wxSdk, { url: currentUrl }, 'get') }, hideAllNonBaseMenuItem() { if (!wxSdk.currentUrl) { wxSdk.currentUrl = window.location.href } this.fetchCfg(wxSdk.currentUrl).then(({ json }) => { if (json.success) { const cfg = json.result const wx = window.wx wx.config({ debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: cfg.appId, // 必填,公众号的唯一标识 timestamp: cfg.timestamp, // 必填,生成签名的时间戳 nonceStr: cfg.nonceStr, // 必填,生成签名的随机串 signature: cfg.signature, // 必填,签名,见附录1 jsApiList: [ 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone', 'showAllNonBaseMenuItem', 'hideAllNonBaseMenuItem' ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2 }) wx.error(function (res) { if (res.errMsg === 'config:invalid signature' && wxSdk.retries < 3) { // 值从services/log.js来 wxSdk.currentUrl = sessionStorage['first-url'] wxSdk.retries++ wxSdk.hideAllNonBaseMenuItem() } }) wx.ready(function () { wx.hideAllNonBaseMenuItem() wxSdk.retries = 0 }) } else { alert(json.error.message) } }) }, share(title, desc, link, icon, success, error, close) { const wx = window.wx const shareCfg = { title, // 分享标题 desc, // 分享描述 link: link, // 分享链接 imgUrl: icon, // 分享图标 type: 'link', // 分享类型,music、video或link,不填默认为link dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空 success: close, cancel: close } wx.showAllNonBaseMenuItem() wx.onMenuShareTimeline(shareCfg) wx.onMenuShareAppMessage(shareCfg) wx.onMenuShareQQ(shareCfg) wx.onMenuShareWeibo(shareCfg) wx.onMenuShareQZone(shareCfg) success() // if (!wxSdk.currentUrl) { // wxSdk.currentUrl = window.location.href // } // this.fetchCfg(wxSdk.currentUrl).then(({ json }) => { // if (json.success) { // const cfg = json.result // const wx = window.wx // wx.config({ // debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 // appId: cfg.appId, // 必填,公众号的唯一标识 // timestamp: cfg.timestamp, // 必填,生成签名的时间戳 // nonceStr: cfg.nonceStr, // 必填,生成签名的随机串 // signature: cfg.signature, // 必填,签名,见附录1 // jsApiList: [ // 'onMenuShareTimeline', // 'onMenuShareAppMessage', // 'onMenuShareQQ', // 'onMenuShareWeibo', // 'onMenuShareQZone', // 'showAllNonBaseMenuItem', // 'hideAllNonBaseMenuItem' // ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2 // }) // wx.error(function (res) { // alert(res.errMsg) // if (res.errMsg === 'config:invalid signature' && wxSdk.retries < 3) { // // 值从services/log.js来 // wxSdk.currentUrl = sessionStorage['first-url'] // wxSdk.retries++ // wxSdk.share(title, desc, link.icon, success, error, close) // } // }) // wx.ready(function () { // const shareCfg = { // title, // 分享标题 // desc, // 分享描述 // link: link, // 分享链接 // imgUrl: icon, // 分享图标 // type: 'link', // 分享类型,music、video或link,不填默认为link // dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空 // success: close, // cancel: close // } // wx.showAllNonBaseMenuItem() // wx.onMenuShareTimeline(shareCfg) // wx.onMenuShareAppMessage(shareCfg) // wx.onMenuShareQQ(shareCfg) // wx.onMenuShareWeibo(shareCfg) // wx.onMenuShareQZone(shareCfg) // wxSdk.retries = 0 // success() // }) // } else { // error(json.error.message) // } // }) } } export default wxSdk <file_sep>/src/routes/Train/modules/train.js import { api, injectApi, DEFAULT_FAILURE } from 'services/fetch' import { Schema, arrayOf } from 'normalizr' const companyServiceSchema = new Schema('companyService') // ------------------------------------ // Constants // ------------------------------------ export const SERVICE_CATEGORY_TAKE_LIST_REQUEST = 'SERVICE_CATEGORY_TAKE_LIST_REQUEST' export const SERVICE_CATEGORY_TAKE_LIST_SUCCESS = 'SERVICE_CATEGORY_TAKE_LIST_SUCCESS' export const SERVICE_CATEGORY_TAKE_LIST_FAILURE = DEFAULT_FAILURE // ------------------------------------ // Actions // ------------------------------------ export const getService = (topicid) => injectApi({ endpoint: api.companyService + '/getServiceList', method: 'get', body: { CategoryId: topicid, pageSize: 100, current: 1 }, schema: arrayOf(companyServiceSchema), types: [ SERVICE_CATEGORY_TAKE_LIST_REQUEST, SERVICE_CATEGORY_TAKE_LIST_SUCCESS, SERVICE_CATEGORY_TAKE_LIST_FAILURE ] }) export const actions = { getService } // ------------------------------------ // Action Handlers // ------------------------------------ const ACTION_HANDLERS = { [SERVICE_CATEGORY_TAKE_LIST_SUCCESS]: (state, { payload }) => { state.services = payload.entities.companyService state.servicePagination = payload.pagination return Object.assign({}, state) } } // ------------------------------------ // Reducer // ------------------------------------ const initialState = { params: { id: sessionStorage.getItem('id') }, services: {}, servicePagination: { ids: [], total: 0, current: 0, pageSize: 100 } } export default function counterReducer(state = initialState, action) { const handler = ACTION_HANDLERS[action.type] return handler ? handler(state, action) : state } <file_sep>/src/components/TrafficCount/index.js import TrafficCount from './TrafficCount' export default TrafficCount <file_sep>/src/routes/RedEnvelopTopic/modules/redEnvelopTopic.js import { api, injectApi, DEFAULT_FAILURE } from 'services/fetch' import { Schema, arrayOf } from 'normalizr' import { RECEIVE_TAKE_RESULT_SUCCESS } from '../../RedEnvelopTake/modules/redEnvelopTake' const redEnvelopSchema = new Schema('redEnvelop') const redEnvelopTopicSchema = new Schema('redEnvelopTopic') // ------------------------------------ // Constants // ------------------------------------ export const RED_ENVELOP_TOPIC_REQUEST = 'RED_ENVELOP_TOPIC_REQUEST' export const RED_ENVELOP_TOPIC_SUCCESS = 'RED_ENVELOP_TOPIC_SUCCESS' export const RED_ENVELOP_TOPIC_FAILURE = DEFAULT_FAILURE export const RED_ENVELOP_LIST_REQUEST = 'RED_ENVELOP_LIST_REQUEST' export const RED_ENVELOP_LIST_SUCCESS = 'RED_ENVELOP_LIST_SUCCESS' export const RED_ENVELOP_LIST_FAILURE = DEFAULT_FAILURE // ------------------------------------ // Actions // ------------------------------------ export const getCanTakeRedEnvelopList = (id) => injectApi({ endpoint: api.redEnvelop + '/getCanTakeRedEnvelopList', method: 'get', body: { id }, schema: arrayOf(redEnvelopSchema), types: [ RED_ENVELOP_LIST_REQUEST, RED_ENVELOP_LIST_SUCCESS, RED_ENVELOP_LIST_FAILURE ] }) export const getRedEnvelopTopic = (id) => injectApi({ endpoint: api.redEnvelop + '/getTopic', method: 'get', body: { id }, schema: arrayOf(redEnvelopTopicSchema), types: [ RED_ENVELOP_TOPIC_REQUEST, RED_ENVELOP_TOPIC_SUCCESS, RED_ENVELOP_TOPIC_FAILURE ] }) export const actions = { getRedEnvelopTopic, getCanTakeRedEnvelopList } // ------------------------------------ // Action Handlers // ------------------------------------ const ACTION_HANDLERS = { [RED_ENVELOP_LIST_SUCCESS]: (state, { payload }) => { state.redEnvelops = payload.entities.redEnvelop state.redEnvelopsPagination = payload.pagination return Object.assign({}, state) }, [RED_ENVELOP_TOPIC_SUCCESS]: (state, { payload }) => { state.topic = payload.result return Object.assign({}, state) }, [RECEIVE_TAKE_RESULT_SUCCESS]: (state, { payload }) => { if (payload.json.result.status === 1) { state.topic.currentUserCanReceiveTimes-- return Object.assign({}, state) } return state } } // ------------------------------------ // Reducer // ------------------------------------ const initialState = { topic: {}, redEnvelops: {}, redEnvelopsPagination: { ids: [] } } export default function counterReducer(state = initialState, action) { const handler = ACTION_HANDLERS[action.type] return handler ? handler(state, action) : state }
0d5bf48382b25ce60241c71ca445d57e72256706
[ "JavaScript" ]
52
JavaScript
linmingeng/Xfzs.marketing.app
a47d4b06f6ac976b1172d6c5a01f84428e6f4f61
ca512158acae92c76defcbc416fd53f2dc37081b
refs/heads/master
<file_sep><?php /** * Created by PhpStorm. * User: root * Date: 1/09/16 * Time: 2:17 PM */ include_once 'config/Database.php'; $coucou = new Database(); $coucou->getGlobals(); <file_sep>#Products Manager v2 ##What's this ? Single page product manager built with __PHP7__, __MySQL__, __JQuery__, __AngularJS 1.5.8__ and __AJAX__. Thanks to codeofaninja for this amazing tutorial. Next improvement will be to include this manager in a global admin panel.<file_sep><?php /** * Created by PhpStorm. * User: G0ttferd0m * Date: 30/08/16 * Time: 3:15 PM */ //used to connect to the DB class Database { // public $_db_handler; //Function to make connection to DB when class is instanced // public function __construct($host, $name, $login, $psw){ // // try { // $this->_db_handler = new PDO("mysql:host=" . $host . ";dbname=" . $name, $login, $psw); // //$this->_db_handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // } // // catch (PDOException $exception){ // die('Error : ' . $exception->getMessage()); // } // // return $this->_db_handler; // } // specify your own database credentials private $_host; private $_db_name; private $_username; private $_password; public $dbh; public function getGlobals() { $GLOBALS = parse_ini_file('config/config.ini'); // var_dump($GLOBALS); $this->_host = $GLOBALS['DB_HOST']; $this->_db_name = $GLOBALS['DB_NAME']; $this->_username = $GLOBALS['DB_LOGIN']; $this->_password = $GLOBALS['DB_PSW']; return true; } // get the database connection public function getConnection(){ $this->dbh = null; try{ $this->dbh = new PDO("mysql:host=" . $this->_host . ";dbname=" . $this->_db_name, $this->_username, $this->_password); }catch(PDOException $exception){ echo "Connection error: " . $exception->getMessage(); } return $this->dbh; } }<file_sep><?php //DB connection include_once 'config/Database.php'; //instance db & obj $db = new Database(); $db->getGlobals(); $dbh = $db->getConnection(); //create instance product object include_once 'objects/Product.php'; $product = new Product($dbh); //get posted data $data = json_decode(file_get_contents("php://input")); //set product property values $product->name = $data->name; $product->price = $data->price; $product->description = $data->description; $product->created = date('Y-m-d H:i:s'); //create product if($product->create()) { echo "Product was created."; } else { echo "Unable to create product."; }<file_sep><?php header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); //include db and obj files include_once 'config/Database.php'; include_once 'objects/Product.php'; //instance db & obj $db = new Database(); $db->getGlobals(); $dbh = $db->getConnection(); $products = new Product($dbh); //var_dump($products); $stmt = $products->readAll(); $num = $stmt->rowCount(); $data = ""; if ($num > 0){ $x = 1; while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { // var_dump($row); extract($row); $data .= '{'; $data .= '"id" : "' . $id . '",'; $data .= '"name" : "' . $name . '",'; $data .= '"description" : "' . html_entity_decode($description) . '",'; $data .= '"price" : "' . $price . '"'; $data .= '}'; $data .= $x<$num ? ',' : ''; $x++; } echo '{"records":[' . $data . ']}'; }<file_sep><?php /** * Created by PhpStorm. * User: G0ttferd0m * Date: 31/08/16 * Time: 9:47 AM */ phpinfo();<file_sep>/** * Created by root on 1/09/16. */ //jquery code $(document).ready(function(){ //ini modal $('.modal-trigger').leanModal(); });<file_sep><?php include_once 'config/Database.php'; include_once 'objects/Product.php'; $db = new Database(); $db->getGlobals(); $dbh = $db->getConnection(); $product = new Product($dbh); $data = json_decode(file_get_contents("php://input")); $product->id = $data->id; $product->name = $data->name; $product->description = $data->description; $product->price = $data->price; if($product->update()) { echo "Product was updated."; } else { echo "Unable to update product."; }<file_sep><?php /** * Created by PhpStorm. * User: G0ttferd0m * Date: 1/09/16 * Time: 10:25 AM */ class Product { //database connection and table name private $dbh; private $table_name = "products"; //object properties public $id; public $name; public $description; public $price; public $created; //constructor with $db as database connection public function __construct($db) { $this->dbh = $db; } function create() { $query = "INSERT INTO " . $this->table_name . " SET name=:name, price=:price, description=:description, created=:created"; $stmt = $this->dbh->prepare($query); $this->name = htmlspecialchars(strip_tags($this->name)); $this->price = htmlspecialchars(strip_tags($this->price)); $this->description = htmlspecialchars(strip_tags($this->description)); $stmt->bindParam(":name", $this->name); $stmt->bindParam(":price", $this->price); $stmt->bindParam(":description", $this->description); $stmt->bindParam(":created", $this->created); if($stmt->execute()) { return true; } else { echo"<pre>"; print_r($stmt->errorInfo()); echo"</pre>"; return false; } } function readAll() { $query = "SELECT id, name, description, price, created FROM " . $this->table_name . " ORDER BY id DESC"; $stmt = $this->dbh->prepare($query); $stmt->execute(); return $stmt; } function readOne(){ // query to read single record $query = "SELECT name, price, description FROM " . $this->table_name . " WHERE id = ? LIMIT 0,1"; // prepare query statement $stmt = $this->dbh->prepare( $query ); // bind id of product to be updated $stmt->bindParam(1, $this->id); // execute query $stmt->execute(); // get retrieved row $row = $stmt->fetch(PDO::FETCH_ASSOC); // set values to object properties $this->name = $row['name']; $this->price = $row['price']; $this->description = $row['description']; } function update() { $query = "UPDATE " . $this->table_name . " SET name=:name, price=:price, description=:description WHERE id=:id"; $stmt = $this->dbh->prepare($query); $stmt->name = htmlspecialchars(strip_tags($this->name)); $stmt->description = htmlspecialchars(strip_tags($this->description)); $stmt->price = htmlspecialchars(strip_tags($this->price)); $stmt->bindParam(':name', $this->name); $stmt->bindParam(':description', $this->description); $stmt->bindParam(':price', $this->price); $stmt->bindParam(':id', $this->id); if($stmt->execute()) { return true; } else { return false; } } function delete(){ // delete query $query = "DELETE FROM " . $this->table_name . " WHERE id = ?"; // prepare query $stmt = $this->dbh->prepare($query); // bind id of record to delete $stmt->bindParam(1, $this->id); // execute query if($stmt->execute()){ return true; }else{ return false; } } }<file_sep><?php /** * Created by PhpStorm. * User: G0ttferd0m * Date: 31/08/16 * Time: 12:00 PM */ ?> <!doctype html> <!--suppress ALL --> <html> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Read Products</title> <!-- material design CSS--> <link rel="stylesheet" href="libs/materialize/css/materialize.min.css"> <!-- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/css/materialize.min.css">--> <!-- material design button--> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <!-- custom css--> <link rel="stylesheet" href="libs/css/style.css"> </head> <body> <!--page content and controls'll be here--> <div class="container" ng-app="myApp" ng-controller="productsCtrl"> <div class="row"> <div class="col s12"> <h4>Products</h4> <!-- used for searching the current list --> <input type="text" ng-model="search" class="form-control" placeholder="Search product..." /> <!-- table that shows product record list --> <table class="hoverable bordered"> <thead> <tr> <th class="text-align-center">ID</th> <th class="width-30-pct">Name</th> <th class="width-30-pct">Description</th> <th class="text-align-center">Price</th> <th class="text-align-center">Action</th> </tr> </thead> <tbody ng-init="getAll()"> <tr ng-repeat="d in names | filter:search"> <td class="text-align-center">{{ d.id }}</td> <td>{{ d.name }}</td> <td>{{ d.description }}</td> <td class="text-align-center">{{ d.price }}</td> <td> <a ng-click="readOne(d.id)" class="waves-effect waves-light btn margin-bottom-1em"><i class="material-icons left">edit</i>Edit</a> <a ng-click="deleteProduct(d.id)" class="waves-effect waves-light btn margin-bottom-1em"><i class="material-icons left">delete</i>Delete</a> </td> </tr> </tbody> </table> <!-- modal form for creating new product--> <div id="modal-product-form" class="modal"> <div class="modal-content"></div> <h4 id="modal-product-title">Create New Product</h4> <div class="row"> <div class="input-field col s12"> <input ng-model="name" type="text" class="validate" id="form-name" placeholder="Type name here"> <label for="name">Name</label> </div> <div class="input-field col s12"> <textarea ng-model="description" name="description" class="validate materialize-textarea" placeholder="Type description here"></textarea> <label for="description">Description</label> </div> <div class="input-field col s12"> <input ng-model="price" type="text" name="price" class="validate" id="form-price" placeholder="Type price here"></input> <label for="price">Price</label> </div> <div class="input-field col s12"> <a id="btn-create-product" class="waves-effect waves-light btn margin-bottom-1em" ng-click="createProduct()"><i class="material-icons left">add</i>Create</a> <a id="btn-update-product" class="waves-effect waves-light btn margin-bottom-1em" ng-click="updateProduct()"><i class="material-icons left">edit</i>Save Changes</a> <a class="modal-action modal-close waves-effect waves-light btn margin-bottom-1em"><i class="material-icons left">close</i>Close</a> </div> </div> </div> <!-- End form create/update products--> <!-- Floating button for creating product--> <div class="fixed-action-btn" style="bottom: 45px; right: 24px;"> <a class="waves-effect waves-light btn modal-trigger btn-floating btn-large red" href="#modal-product-form" ng-click="showCreateForm()"><i class="large material-icons">add</i></a> </div> </div><!-- End col s12 --> </div><!-- end row --> </div><!-- end container --> <!--JQuery--> <script type="text/javascript" src="libs/JS/jquery.min.js"></script> <!--material design JS--> <script type="text/javascript" src="libs/materialize/js/materialize.min.js"></script> <!--angular--> <script type="text/javascript" src="libs/JS/angular.min-1.5.8.js"></script> <!--myApp.js custom Angular functions--> <script type="text/javascript" src="libs/JS/myApp.js"></script> <!--load ModalTrigger--> <script type="text/javascript" src="libs/JS/loadModaljQuery.js"></script> </body> </html>
1a7e9635ccd0837084509b3645b40eca095d4ef7
[ "Markdown", "JavaScript", "PHP" ]
10
PHP
g0ttferd0m/productManagerAngular
3e5baf6668a938fe5651664f9274414c3132aa89
296446fa54e42367b72bb5595e7c5dc517489452
refs/heads/master
<file_sep><?php $UserName = $_POST['name']; $Email = $_POST['email']; $Phone = $_POST['phone']; $Subject = $_POST['subject']; $Msg = $_POST['message']; if(!empty($UserName) || !empty($Email) || !empty($Subject) || !empty($Msg)) { $to = '<EMAIL>'; $Headers = 'Wiadomość od: ' . $UserName . '.' . "\r\n" . 'Skontaktować się z nim można na podany adres: ' . $Email . "\r\n" . 'Jego numer telefonu to: ' . $Phone; mb_language("uni"); mb_internal_encoding("UTF-8"); mail($to, $Subject, $Msg, $Headers); } else { echo '403'; } ?><file_sep>$(window).ready(function(){ // Show or hide Modal Slider if($(window).width() > 900) { let modalWithSlider = `<div class="modal fade" id="ModalCenter" tabindex="-1" role="dialog" aria-labelledby="ModalCenterTitle" aria-hidden="true"> <div class=" modal-lg modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div id="carouselExample" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExample" data-slide-to="0"></li> <li data-target="#carouselExample" data-slide-to="1"></li> <li data-target="#carouselExample" data-slide-to="2"></li> <li data-target="#carouselExample" data-slide-to="3"></li> <li data-target="#carouselExample" data-slide-to="4"></li> <li data-target="#carouselExample" data-slide-to="5"></li> <li data-target="#carouselExample" data-slide-to="6"></li> <li data-target="#carouselExample" data-slide-to="7"></li> <li data-target="#carouselExample" data-slide-to="8"></li> <li data-target="#carouselExample" data-slide-to="9"></li> <li data-target="#carouselExample" data-slide-to="10"></li> <li data-target="#carouselExample" data-slide-to="11"></li> <li data-target="#carouselExample" data-slide-to="12"></li> <li data-target="#carouselExample" data-slide-to="13"></li> </ol> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a1.jpg" alt="First slide" > </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a2.jpg" alt="Second slide" > </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a3.jpg" alt="Third slide"> </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a4.jpg" alt="Fourth slide"> </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a5.jpg" alt="Fifth slide"> </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a6.jpg" alt="Sixth slide"> </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a7.jpg" alt="Seventh slide"> </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a8.jpg" alt="Eigth slide"> </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a9.jpg" alt="Nineth slide"> </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a10.jpg" alt="Tenth slide"> </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a11.jpg" alt="Eleventh slide"> </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a12.jpg" alt="Twelveth slide"> </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a13.jpg" alt="Thirteenth slide"> </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a14.jpg" alt="Fourteenth slide"> </div> </div> <a class="carousel-control-prev" href="#carouselExample" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExample" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div>` $('script').before($(modalWithSlider)) } if($(window).width() <= 900){ $('#ModalCenter').detach() } // Show and hide logo if navbar is not collapsed let btnNavToggler = document.querySelector('.navbar-toggler'); let navCollapse = document.querySelector('.navbar-collapse'); btnNavToggler.addEventListener('click', () => { let logo = document.querySelector('.logo'); setTimeout(() => { if(btnNavToggler.getAttribute('aria-expanded') == 'true'){ btnNavToggler.style.border = 'none'; logo.style.display = 'none'; } else { navCollapse.classList.remove('collapsing'); navCollapse.classList.add('collapse'); btnNavToggler.style.border = '1px solid rgba(0,0,0,0.1)'; logo.style.display = 'block'; } }, 20) }); // Init Call button let btnCall = document.querySelector('.btn-call'); // Add click animation on Call Button // btnCall.addEventListener('click', () => { // btnCall.classList.add('clicked'); // setTimeout(() => { // btnCall.classList.remove('clicked'); // }, 150); // }); // Add shuffle animation on Call Button window.addEventListener('load', () => { setTimeout(() => { animFromBottom(btnCall); setTimeout(() => { animShuffle(btnCall); btnCall.style.bottom = '40px'; }, 300); }, 300); }); // Shuffle Call Button time after time let shuffleInterval = setInterval(() => { animShuffle(btnCall); }, 3000); // Show or hide navbar after page is loaded window.addEventListener('load', function() { let firstBlock = document.querySelector('.first'); let firstBlockBottom = firstBlock.getBoundingClientRect().bottom; let headNavBar = document.querySelector('.navbar'); let logo = document.querySelector('.logo'); let navLinkText = document.querySelectorAll('.nav-link-text'); if(firstBlockBottom < 525) { logo.style.filter = 'invert(0)'; headNavBar.classList.add('bgIn'); setTimeout(() => { headNavBar.style.backgroundColor = '#f8f9fa'; }, 250) btnNavToggler.style.filter = 'invert(0)'; navLinkText.forEach(item => { item.style.color = '#000'; }); } else if (firstBlockBottom > 525){ logo.style.filter = 'invert(1)'; btnNavToggler.style.filter = 'invert(1)'; headNavBar.style.backgroundColor = '#f8f9fa00'; navLinkText.forEach(item => { item.style.color = '#fff'; }); } }); // Invert, scroll and hide head navbar while scrolling window.addEventListener('scroll', function() { let firstBlock = document.querySelector('.first'); let firstBlockBottom = firstBlock.getBoundingClientRect().bottom; let thirdBlock = document.querySelector('.second'); let thirdBlockTop = thirdBlock.getBoundingClientRect().top; let headNavBar = document.querySelector('.navbar'); let logo = document.querySelector('.logo'); let navLinkText = document.querySelectorAll('.nav-link-text'); console.log(firstBlockBottom); if(firstBlockBottom < 725) { logo.style.filter = 'invert(0)'; btnNavToggler.style.filter = 'invert(0)'; headNavBar.classList.add('bgIn'); headNavBar.style.backgroundColor = '#f8f9fa'; navLinkText.forEach(item => { item.style.color = '#000'; item.addEventListener('mouseover', () => {item.style.color = '#ff5e00'}); item.addEventListener('mouseout', () => {item.style.color = '#000'}); }); } if (firstBlockBottom > 800){ logo.style.filter = 'invert(1)'; btnNavToggler.style.filter = 'invert(1)'; headNavBar.classList.remove('bgIn'); headNavBar.style.backgroundColor = '#f8f9fa00'; navLinkText.forEach(item => { item.style.color = '#fff'; item.addEventListener('mouseover', () => {item.style.color = '#ff5e00'}); item.addEventListener('mouseout', () => {item.style.color = '#fff'}); }); } if(thirdBlockTop < 150){ headNavBar.style.opacity = 0; } if (thirdBlockTop > 250){ headNavBar.style.opacity = 1; } }); // Hide portfolio galery and add slider galery $(window).resize(function(){ if($(window).width() > 900) { let modalWithSlider = `<div class="modal fade" id="ModalCenter" tabindex="-1" role="dialog" aria-labelledby="ModalCenterTitle" aria-hidden="true"> <div class=" modal-lg modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div id="carouselExample" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExample" data-slide-to="0"></li> <li data-target="#carouselExample" data-slide-to="1"></li> <li data-target="#carouselExample" data-slide-to="2"></li> <li data-target="#carouselExample" data-slide-to="3"></li> <li data-target="#carouselExample" data-slide-to="4"></li> <li data-target="#carouselExample" data-slide-to="5"></li> <li data-target="#carouselExample" data-slide-to="6"></li> <li data-target="#carouselExample" data-slide-to="7"></li> <li data-target="#carouselExample" data-slide-to="8"></li> <li data-target="#carouselExample" data-slide-to="9"></li> <li data-target="#carouselExample" data-slide-to="10"></li> <li data-target="#carouselExample" data-slide-to="11"></li> <li data-target="#carouselExample" data-slide-to="12"></li> <li data-target="#carouselExample" data-slide-to="13"></li> </ol> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a1.jpg" alt="First slide" > </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a2.jpg" alt="Second slide" > </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a3.jpg" alt="Third slide"> </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a4.jpg" alt="Fourth slide"> </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a5.jpg" alt="Fifth slide"> </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a6.jpg" alt="Sixth slide"> </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a7.jpg" alt="Seventh slide"> </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a8.jpg" alt="Eigth slide"> </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a9.jpg" alt="Nineth slide"> </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a10.jpg" alt="Tenth slide"> </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a11.jpg" alt="Eleventh slide"> </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a12.jpg" alt="Twelveth slide"> </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a13.jpg" alt="Thirteenth slide"> </div> <div class="carousel-item"> <img class="d-block w-100 img-portfolio" src="img/portfolio/a14.jpg" alt="Fourteenth slide"> </div> </div> <a class="carousel-control-prev" href="#carouselExample" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExample" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div>` $('script').before($(modalWithSlider)) } if($(window).width() <= 900){ $('#ModalCenter').detach() } }); // Function to make PopUpFromBottom animation function animFromBottom(el){ el.style.display = 'block'; el.classList.add('animShow'); el.style.bottom = '40px'; setTimeout(() => { el.classList.remove('animShow'); }, 300) } // Function to make HideToBottom animation function animToBottom(el){ setTimeout(() => { el.classList.add('animHide'); setTimeout(() => { el.classList.remove('animHide'); el.style.bottom = '-150px'; el.style.display = 'none'; }, 300); }, 250) } // Function to make shuffle animation function animShuffle(el){ el.classList.add('shuffled'); setTimeout(() => { el.classList.remove('shuffled'); }, 1100); } // Sending email without reloading page (AJAX) let btnSend = document.querySelector('.btn-submit'); btnSend.addEventListener('click', e => { sendEmail(); e.preventDefault(); }); // Sending mail function function sendEmail(){ // Getting all of inputs from contact form let name = document.querySelector('input[name="name"]').value; let subject = document.querySelector('input[name="subject"]').value; let email = document.querySelector('input[name="email"]').value; let phone = document.querySelector('input[name="phone"]').value; let message = document.querySelector('textarea[name="message"]').value; //Checking if inputs aren't empty if(name == '' || subject == '' && email == '' || message == '') { //If at least one form is empty - show warning message let msg = "Prosimy wypełnić puste miejsca"; document.querySelector('.contact-alert-message').innerHTML = `<div class="alert alert-danger">${msg}</div>`; } else { //If aren't empty - show success message let msg = "Wiadomość została wysłana"; document.querySelector('.contact-alert-message').innerHTML = `<div class="alert alert-success">${msg}</div>`; //Creating new FormData object let formdata = new FormData(); formdata.append('email', email); formdata.append('phone', phone); formdata.append('name', name); formdata.append('subject', subject); formdata.append('message', message); //Create XMLHttpRequest object let xhr = new XMLHttpRequest(); xhr.onload = function(){ if(this.status == 200){ let msg = "Wiadomość została wysłana"; document.querySelector('.contact-alert-message').innerHTML = `<div class="alert alert-success">${msg}</div>`; } } xhr.open('POST', '../sendEmail.php', true); xhr.send(formdata); } } // Initialize Contact Modal WIndow and Close Button let contactModal = document.querySelector('#contactModal'); let btnClose = document.querySelector('.close'); // Show and hide Call Button if Contact Modal Form is showing or isn't. btnCall.addEventListener('click', () => { clearInterval(shuffleInterval); if(btnCall.classList.contains('shuffled')){ btnCall.classList.remove('shuffled'); setTimeout(() => { if(contactModal.style.display == 'block'){ animToBottom(btnCall); } }, 200) } else { setTimeout(() => { if(contactModal.style.display == 'block'){ animToBottom(btnCall); } }, 200) } }); //Show Call Button after clicking on Contact Modal Close Button btnClose.addEventListener('click', () => { shuffleInterval = setInterval(() => { animShuffle(btnCall); }, 3000); setTimeout(() => { if(contactModal.style.display == 'none'){ animFromBottom(btnCall); } }, 300); }) //Show Call Button after clicking somewhere but not on Contact Modal window.addEventListener('click', () => { setTimeout(() => { if(contactModal.style.display == 'none'){ shuffleInterval = setInterval(() => { animShuffle(btnCall); }, 3000); animFromBottom(btnCall); } }, 300); }); // Befor-After Slider $.fn.BeerSlider = function( options ) { options = options || {}; return this.each( function () { new BeerSlider( this, options ); }); }; $( ".beer-slider" ).each( function( index, el ) { $( el ).BeerSlider( {start: $( el ).data( "start" ) } ) }); });<file_sep># Wild Sobol First commercial website for Warsaw Renovation Company - WildSobol. Stack of technologies i've used in this project: - HTML5. - CSS3 and SASS preprocessor. - Some Bootstrap elements (Modal Windows and Image slider). - A little bit of jQuery code. - Vanilla JS is used for creating some animation and for working with DOM-elements. - AJAX and PHP is used for sending email without reloading page. You can visit website via link http://wildsobol.pl/
91488137f92de71da7747bc1e41b31a5b2d824d5
[ "JavaScript", "Markdown", "PHP" ]
3
PHP
andymtv/wildsobol
151353a0b206ebbf3a61eb9307115a033e7423ee
b04e875ffe8ee87c96a86572ef71183a51fd75b0
refs/heads/master
<repo_name>muttushingadi/programming<file_sep>/06:pattern_of_1_323.rb ###Print the following pattern # 1 # 323 # 54345 # 7654567 # 987656789 ########################## class Patount for line in 1..5 for s in 1..5-line print " " end k=(2*line)-1 for i in 1..line print k k=k-1 end for j in 1..line-1 print line+j end puts "\n" end end <file_sep>/30:sherlock_the_beast.rb puts "enter the no of test cases" t=gets.chomp.to_i while t>0 n=gets.chomp.to_i if n==1 or n==2 or n==4 or n==7 puts "-1" elsif n%3==0 puts "5"*n elsif n%3==2 puts "5"*(n-5)+"3"*5 elsif n%3==1 puts "5"*(n-10)+"3"*10 end t=t-1 end<file_sep>/24:std_count_words.rb def count_substring(s,sub) s_length=s.length sub_length=sub.length count=0 for index in 0..s_length-1 res=compare(sub,s[index..index+sub_length-1]) if res==true count=count+1 next end end return count end def compare(s1,s2) if s1==s2 return true end end puts "enter the sentence" c1=gets.chomp puts "enter word" c2=gets.chomp r=count_substring(c1,c2) puts r <file_sep>/27:steady_genes.rb ## To find the minimum length of the substring replaced to make steady gene #################################### class Genes def left_min_length(a) a_length=a.length l_count=0 ca=cc=cg=ct=0 for range in 0..a_length-1 if a[range]=='A' ca=ca+1 if ca>a_length/4 break end l_count=l_count+1 elsif a[range]=='C' cc=cc+1 if cc>a_length/4 break end l_count=l_count+1 elsif a[range]=='G' cg=cg+1 if cg>a_length/4 break end l_count=l_count+1 elsif a[range]=='T' ct=ct+1 if ct>a_length/4 break end l_count=l_count+1 end end return l_count,ca,cc,cg,ct end def right_min_length(a) a_length=a.length r_count=0 range=a_length-1 l_count,ca,cc,cg,ct=left_min_length(a) while range>=0 if a[range]=='A' ca=ca+1 if ca>a_length/4 break end r_count=r_count+1 elsif a[range]=='C' cc=cc+1 if cc>a_length/4 break end r_count=r_count+1 elsif a[range]=='G' cg=cg+1 if cg>a_length/4 break end r_count=r_count+1 elsif a[range]=='T' ct=ct+1 if ct>a_length/4 break end r_count=r_count+1 end range=range-1 end return r_count,l_count end end def compare(l,r,a) return a.length-(l+r) end puts "enter main string" str=gets.chomp r=Genes.new right_res,left_res=r.right_min_length(str) result=compare(left_res,right_res,str) puts result <file_sep>/11:row_odd_sum.rb #Find and print the sum all odd numbers in each row of given matrix ############################################## def rw_odd(arr) n=arr.length for row in 0..n-1 sum=0 for col in 0..n-1 if ((arr[row][col] % 2) != 0) sum += arr[row][col] end end print sum puts "\n" end end a=[[1,2,3],[7,5,6],[7,1,3]] rw_odd(a)<file_sep>/20:leap_year.rb #To check the number of leap years in a given range of years ############################## puts "Enter the first year" n1=gets.chomp.to_i puts "Enter the second year" n2=gets.chomp.to_i puts "leap years are" count=0 while n1 <= n2 if n1%100!=0 and n1%4==0 or n1%400==0 puts n1 end n1=n1+1 end<file_sep>/14:check_enter_key.rb # To print all given names in single line until enter key pressed ####################################### puts "enter the name" n=gets.chomp c=[] while !n.empty? c.push(n) n=gets.chomp end c.each do |x| print "#{x} " end puts "\n"<file_sep>/18:sum_plus_factorial.rb # To find the sum of summation of given number and factorial of given number. ############################################# def fact(num) prod=1 while num >0 prod=prod*num num=num-1 end return prod end def addition(a) sum=0; while a>0 sum=sum+a; a=a-1 end return sum end def get_input(m,n) puts "enter first number" m=gets.chomp.to_i puts "enter second number" n=gets.chomp.to_i return m,n end a,b=get_input(a,b) for i in a..b puts addition(i)+fact(i) a=a-1 end<file_sep>/15:check_exit.rb # come out of the program if given name is 'exit' and 'bye' ####################################### puts "enter the name" name= gets.chomp while name !='exit' and name!='bye' puts name name=gets.chomp end <file_sep>/01:pattern_of_1_11.rb ###To print the following pattern # 1 # 11 # 111 # 1111 ######## class PrintAllOnes for line in 1..4 for count in 1..line print "1" end puts "\n" end end <file_sep>/05:pattern_of_57.rb ##Print the following pattern #5 7 #9 11 13 #15 17 19 21 ############### class Pat5 i=5 for line in 1..3 for count in 1..line print "#{i}" i=i+2 end puts "\n" end end <file_sep>/02:pattern_of_1_12.rb ###To print the follwing pattern # 1 # 12 # 123 # 1234 ############### class Pat2 for i in 1..3 for j in 1..i print "#{j}" end puts "\n" end end <file_sep>/03:pattern_of_1_23.rb ### To print the following pattern # 1 # 23 # 456 # 78910 ###################### class Pat3 k=1 for line in 1..4 for count in 1..line print "#{k}" k=k+1; end puts "\n" end end <file_sep>/12:arr_check.rb ## print 'YES' if sum of the two elements of given array equal to the #specified variable value ################################################# def a_check(arr,k) n=arr.length for i in 0..n-2 for j in i+1..n-1 if arr[i] + arr[j]) == k print "yes" end end end puts "\n" end a=[2,1,4,5,6,3] a_check(a,12) <file_sep>/17:multiplication_n.rb ## print the multiplication of given number, specified times with another fixed given number. ############################################## def multiply(m,n) pd=0 for i in 1..n pd=i*m; print pd puts "\n" end end multiply(2,30) <file_sep>/13:form_bigger_number.rb ## To form Bigger number from the given array elements ############################################### def big_num(b) n=b.length c=[] for i in 0..n-1 for j in 0..n-1 if i != j puts "#{b[i]}"+"#{b[j]} " end end end end a=[9,92,909,9009] big_num(a) <file_sep>/29:stdent_database.rb puts "enter the no of test cases" t=gets.chomp.to_i while t>0 a=[] puts "enter the no of student in class and cancellation threshold" n=gets.chomp.to_i thr=gets.chomp.to_i for i in 0..n-1 a[i]=gets.chomp.to_i end cin=0 cout=0 a.each do |x| if x <= 0 thr=thr-1 end end if thr>0 puts "YES" else puts "NO" end t=t-1 end <file_sep>/25:Robot_rovers.rb class Rover def initialize(data) @x = data[0].to_i @y = data[1].to_i @dir= data[2] end def make_all_movement(str) for index in 0..str.length-1 if str[index] == 'L' t1=turn_left elsif str[index]=='R' t=turn_right elsif str[index]=='M' t2=mov end end end def turn_left if @dir == 'N' @dir='W' elsif @dir == 'W' @dir='S' elsif @dir == 'S' @dir='E' elsif @dir == 'E' @dir='N' end end def turn_right if @dir == 'N' @dir='E' elsif @dir == 'W' @dir='N' elsif @dir == 'S' @dir='W' elsif @dir == 'E' @dir='S' end end def mov if @dir == 'N' @y=@y+1 elsif @dir == 'S' @y= @y-1 elsif @dir == 'E' @x=@x+1 elsif @dir == 'W' @x=@x-1 end end end class Nasa def send_all_instructions(instr) end end class Mars_controller ##sa=Nasa.new def execute_instruction(str) value=str.split() no_of_rovers= process_instruction(value) i=1 while (i<no_of_rovers*2) r=Rover.new(value[i]) i=i+1 r.make_all_movement(value[i]) i=i+1 puts r.inspect end end def process_instruction(instr) l=instr.length return (l-1)/2 end end str="55 12N LMLMLMLMM 33E MMRMMRMRRM" m=Mars_controller.new m.execute_instruction(str) <file_sep>/09:row_sum.rb #find and print sum of all the rows of given matrix ###################################### def rw_sum(row) n=row.length for rw in 0..n-1 sum=0 for col in 0..n-1 sum += row[rw][col] end print sum puts "\n" end end a= [[1,2,4],[2,3,5],[1,4,3]] rw_sum(a)<file_sep>/08:column_sum.rb #find & print sum of all the coloumns of given matrix ##################################### def c_sum(b) n=b.length for col in 0..n-1 sum=0 for rw in 0..n-1 sum=sum+b[rw][col] end print sum puts "\n" end end a= [[1,2,3],[2,3,1],[1,4,3]] c_sum(a) <file_sep>/10:row_even_sum.rb #Find and print the sum all even numbers in each row of given matrix ############################################## def rw_even(arr) n=arr.length for row in 0..n-1 sum=0 for col in 0..n-1 if ((arr[row][col] % 2) == 0) sum += arr[row][col] end end print sum puts "\n" end end a=[[1,2,4],[4,5,6],[1,8,5]] rw_even(a)<file_sep>/28:Ingredients_testcases.rb puts "enter the no of test cases" t=gets.chomp puts "enter the no of ingredients" n=gets.chomp for i in 0..n a[i]=gets.chomp end sum=0 while t>0 for i in 0..n sum+=a[i] end end <file_sep>/04:pattern_of_1_323.rb ###Print the following pattern # 1 # 323 # 54345 # 7654567 # 987656789 ########################## def pat6(n) for line in 1..n for s in 1..n-line print " " end k=(2*line)-1 for i in 1..line print k k=k-1 end for j in 1..line-1 print "#{line+j}" end puts "\n" end end pat6(4) <file_sep>/19:poem_99.rb #To print the poem :99 bottles of beer on the wall, 99 bottles of beer. # Take one down and pass it around, '#{num}' bottles of beer on the wall. #################################### num=99.to_i while num!= 0 if(num==1) puts "#{num} bottle of beer on the wall, #{num} bottle of beer." else puts "#{num} bottles of beer on the wall, #{num} bottles of beer." end num=num-1 if num==1 puts "Take one down and pass it around, #{num} bottle of beer on the wall." elsif num!=1 && num !=0 puts "Take one down and pass it around, #{num} bottles of beer on the wall." else puts "Take one down and pass it around, no more bottles of beer on the wall." end end num=99 puts "No more bottles of beer on the wall, no more bottles of beer." puts "Go to the store and buy some more, #{num} bottles of beer on the wall."<file_sep>/23:count_word_in_sentence.rb #To count the number of times the given word occured in a given sentence. ########################################### def count_str(s1,s2) l1=s1.length l2=s2.length count=0 for i in 0..l1-1 j=0 c1=0 while j<l2 if s1[i]==s2[j] c1=c1+1 i=i+1 j=j+1 next else break end end if c1==l2 count=count+1 end end puts count end puts "enter the sentence" c1=gets.chomp puts "enter word" c2=gets.chomp count_str(c1,c2) <file_sep>/22:digit_t_word_class.rb class Integer def to_s "welcome" end def to_eng my_hash=Hash.new my_hash={ 1=>"one",2=>"two",3=>"three",4=>"four",5=>"five", 6=>"six",7=>"seven",8=>"eight",9=>"nine",10=>"ten", 11=>"eleven",12=>"twelve",13=>"thirteen",14=>"fourteen",15=>"fifteen", 16=>"sixteen",17=>"seventeen",18=>"eighteen",19=>"nineteen",20=>"twenty", 30=>"thirty",40=>"fourty",50=>"fifty",60=>"sixty",70=>"seventy", 80=>"eighty",90=>"ninty" } #if k.start_with?("0") # print "zero " #end n=self if my_hash.has_key?(n) puts my_hash[n] elsif n<=99 puts [my_hash[n- n%10],my_hash[n%10]].join(" ") elsif n<=999 d=n%100 if d<20 puts [my_hash[n/100],"hundred",[my_hash[d]]].join(" ") else puts [my_hash[n/100],"hundred",my_hash[d-n%10],my_hash[n%10]].join(" ") end else puts "provide 3 digit input" end end end puts 124.to_eng puts 12.to_s<file_sep>/16:sum_of_n.rb # To find the summation of given number. ################################# puts "enter the number" num=gets.chomp.to_i sum=0; while num>0 sum=sum+num num=num-1 end puts sum<file_sep>/26:array_split.rb def solution(x,a) l=a.length k=1 while k <= l c1=0 c2=0 for i in 0..k-1 if a[i] == x c1=c1+1 end end for j in k..l-1 if a[j] != x c2=c2+1 end end if c1==c2 return k end k=k+1 end end x=111 a=[111,10,1,10,2,2,1] res=solution(x,a) puts res<file_sep>/07:diagonal_sum.rb #Find & print the sum of diagonal elements of a given Matrix ########################################### def arr(sq) n=sq.length sum=0; for count in 0..n-1 sum=sum+sq[count][count] end print sum puts "\n" end a=[[1,2,3],[3,2,1],[4,5,6]] arr(a)
2de612f83474d1e96b440990073e40324c5fe7f6
[ "Ruby" ]
29
Ruby
muttushingadi/programming
004b145a3d7a68dc0330467b8740555bab7306d8
395045287266dacc31c2d6d04ed018445ef500fd
refs/heads/master
<repo_name>crysdelima/ys-challenge<file_sep>/survey-front/test/integrated/containers/SurveyScreen.test.js import { mount } from 'enzyme'; import toJson from 'enzyme-to-json'; import { Provider } from 'react-redux' import service from '../../../src/service/SurveyService'; import startStore from '../../../src/redux/index' import SurveyScreen from '../../../src/containers/SurveyScreen'; const formDataMock = { identity: { name: '<NAME>', email: '<EMAIL>' }, details: { age: 25, gender: 'male' }, favorites: { book: 'The book', colors: ['green', 'blue'] } } describe('<SurveyScreen />', () => { test('Render correctly', () => { const store = startStore(); const wrapper = mount( <Provider store={store}> <SurveyScreen initialData={{}} /> </Provider> ); expect(toJson(wrapper)).toMatchSnapshot(); }); test('Should start in the first step with some data and navigate to next step', () => { const store = startStore(); const wrapper = mount( <Provider store={store}> <SurveyScreen initialData={{ identity: { ...formDataMock.identity } }} /> </Provider> ); expect(store.getState().survey.formData.identity.name).toEqual(formDataMock.identity.name); expect(store.getState().survey.formData.identity.email).toEqual(formDataMock.identity.email); wrapper.find('Button').at(0).simulate('click') expect(store.getState().steps.currentStep).toEqual('details') }); test('Should save data when any component call onSave prop', () => { const store = startStore(); service.getStep = () => 'identity' const wrapper = mount( <Provider store={store}> <SurveyScreen initialData={{ identity: { name: '<NAME>', email: '' } }} /> </Provider> ); wrapper.find('Identity').prop('onSave')('identity', { name: 'new name', email: '' } ) expect(store.getState().survey.formData.identity.name).toEqual('new name'); }); test('Should back to previous step when click the Previous button', () => { const store = startStore(); service.getStep = () => 'favorites' const wrapper = mount( <Provider store={store}> <SurveyScreen initialData={{ favorites: { ...formDataMock.favorites } }} /> </Provider> ); wrapper.find('Button').at(0).simulate('click'); expect(store.getState().steps.currentStep).toEqual('details') }); test('Should submit data and finish survey when showing last step and user click submit button', () => { const store = startStore(); service.getStep = () => 'summary' const wrapper = mount( <Provider store={store}> <SurveyScreen initialData={formDataMock} /> </Provider> ); wrapper.find('Button').at(1).simulate('click') expect(wrapper.find('MessageHeader').prop('content')).toEqual('Your survey was submitted.'); }); }) <file_sep>/survey-front/test/unit-tests/components/survey-steps/Summary.test.js import { shallow } from 'enzyme'; import Summary from '../../../../src/components/survey-steps/Summary'; import toJson from 'enzyme-to-json'; describe('<Summary />', () => { test('Render correctly', () => { const wrapper = shallow( <Summary formData={{ identity: { name: '<NAME>', email: '<EMAIL>' }, details: { age: 25, gender: 'female' }, favorites: { book: 'The book', colors: ['green', 'blue'] } }} /> ); expect(toJson(wrapper)).toMatchSnapshot(); }); }) <file_sep>/survey-front/test/unit-tests/service/SurveyService.test.js import SurveyService from '../../../src/service/SurveyService'; const obj = { identity: { name: 'name', email: '<EMAIL>' } }; const localStorageMock = { getItem: jest.fn(), setItem: jest.fn(), removeItem: jest.fn(), clear: jest.fn() }; Object.defineProperty(window, 'localStorage', { value: localStorageMock }) describe('SurveyService', () => { it('Should call saveData', () => { SurveyService.saveData(obj); expect(localStorageMock.setItem).toBeCalledWith('surveyData', JSON.stringify(obj)); }); it('Should call endSurvey', () => { SurveyService.endSurvey(); expect(localStorageMock.setItem).toBeCalledWith("surveyData", JSON.stringify({ status: 'finished' })); expect(localStorageMock.removeItem).toBeCalledWith("surveyStep"); // chamar outro }); it('Should call saveStep', () => { SurveyService.saveStep('identity'); expect(localStorageMock.setItem).toBeCalledWith("surveyStep", 'identity'); }); it('Should call getData', () => { // SurveyService.getData(); window.localStorage.getItem = () => JSON.stringify(obj) expect(SurveyService.getData()).toEqual(obj); }); it('Should call getStep', () => { window.localStorage.getItem = () => 'identity' expect(SurveyService.getStep()).toEqual("identity"); }); })<file_sep>/survey-front/src/config/data-validation.js const isEmail = str => { const exp = new RegExp(/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/); return exp.test(str); }; const dataValidation = { isEmail, }; export default dataValidation;<file_sep>/survey-front/src/components/survey-steps/Details.js import React, { useState, useEffect } from 'react'; import PropTypes from 'prop-types'; import { Form } from 'semantic-ui-react'; import { debounce } from 'lodash'; const onSaveWithDebounce = debounce((data, onSave, onDisableNextStep) => { if (Object.values(data).every(i => !!i)) { onDisableNextStep(false); } return onSave('details', data) }, 500); const ageInterval = Array.from({ length: 100 }, (value, key) => ({ key, text: key + 1, value: key + 1 })); const Details = ({ initialData, onDisableNextStep, onSave, }) => { const [formData, setFormData] = useState({ ...initialData }); useEffect(() => { const validFormData = Object.values(formData).every(i => !!i) onDisableNextStep(!validFormData); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const onChange = (e, { name, value }) => { onDisableNextStep(true) onSaveWithDebounce.cancel(); const newFormData = { ...formData, [name]: value, }; setFormData(newFormData); onSaveWithDebounce(newFormData, onSave, onDisableNextStep); }; return ( <Form> <Form.Select label='Age' name='age' onChange={onChange} options={ageInterval} required placeholder='Select your age' value={formData.age} /> <Form.Field required> <label>Gender</label> <Form.Group> <Form.Radio label='Male' checked={formData.gender === 'male'} name='gender' onChange={onChange} value='male' /> <Form.Radio label='Female' checked={formData.gender === 'female'} name='gender' onChange={onChange} value='female' /> <Form.Radio label='Other' checked={formData.gender === 'other'} name='gender' onChange={onChange} value='other' /> </Form.Group> </Form.Field> </Form> ); }; Details.propTypes = { initialData: PropTypes.shape({ age: PropTypes.number.isRequired, gender: PropTypes.string.isRequired, }).isRequired, onSave: PropTypes.func.isRequired, }; export default Details;<file_sep>/survey-front/src/config/colorsList.js const colorsList = [ {name: 'Blue', value: 'blue'}, {name: 'Green', value: 'green'}, {name: 'Yellow', value: 'yellow'}, {name: 'Red', value: 'red'}, {name: 'Orange', value: 'orange'}, {name: 'Purple', value: 'purple'}, {name: 'Gray', value: 'gray'} ]; export default colorsList;<file_sep>/survey-front/src/redux/stepsSlice.js import { createSlice } from '@reduxjs/toolkit' import service from '../service/SurveyService'; export const stepsSlice = createSlice({ name: 'steps', initialState: { currentStep: null, }, reducers: { setCurrentStep: (state, action) => { const step = action.payload; state.currentStep = step return service.saveStep(step) } } }); export const { setCurrentStep } = stepsSlice.actions export default stepsSlice.reducer <file_sep>/survey-front/src/index.js import React from 'react'; import ReactDOM from 'react-dom'; import { debounce, get } from 'lodash'; import { Provider } from 'react-redux'; import 'semantic-ui-css/semantic.min.css'; import { Message } from 'semantic-ui-react' import startStore from './redux/index' import service from './service/SurveyService'; import SurveyScreen from './containers/SurveyScreen'; const ROOT_ELEMENT = 'survey-root'; const store = startStore(); debounce(() => { const initialData = service.getData(); const surveyStatus = get(initialData, 'status', null) const app = surveyStatus === 'finished' ? ( <Message info content='You have completed the survey.' /> ) : ( <Provider store={store}> <SurveyScreen initialData={initialData} /> </Provider> ) ReactDOM.render(app, document.getElementById(ROOT_ELEMENT)); }, 2000)();<file_sep>/survey-front/src/containers/SurveyScreen.js import React, { useState, useEffect } from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { isEmpty } from 'lodash'; import { Message } from 'semantic-ui-react'; import { setCurrentStep } from '../redux/stepsSlice'; import { endSurvey, updateFormData } from '../redux/surveySlice'; import surveyStaps, { getNextStepKey, getPrevStepKey } from '../config/stepsHandler'; import service from '../service/SurveyService'; import SurveyWrapper from '../components/SurveyWrapper'; // Survey Steps import Identity from '../components/survey-steps/Identity'; import Details from '../components/survey-steps/Details'; import Favorites from '../components/survey-steps/Favorites'; import Summary from '../components/survey-steps/Summary'; const setInitialStep = dispatch => { const firstStep = service.getStep() || surveyStaps[0].key; return dispatch(setCurrentStep(firstStep)); }; const setSurveyInitialData = (dispatch, initialData) => { if (!isEmpty(initialData)) { return Object.keys(initialData).forEach(step => { dispatch(updateFormData({ step, data: initialData[step] })) }) } return null; }; const SurveyScreen = ({ initialData }) => { const [currentStep, formData] = useSelector(state => ([ state.steps.currentStep, state.survey.formData, ])); const dispatch = useDispatch(); const [nextStepKey, setNextStepKey] = useState(null); const [prevStepKey, setPrevStepKey] = useState(null); const [listWithActiveStep, setListWithActiveStep] = useState([]); const [disableNextStep, onDisableNextStep] = useState(false); const [openModal, setOpenModal] = useState(true); useEffect(() => { if(!currentStep) { setInitialStep(dispatch); setSurveyInitialData(dispatch, initialData); } else { setNextStepKey(getNextStepKey(currentStep)); setPrevStepKey(getPrevStepKey(currentStep)); setListWithActiveStep([...surveyStaps].map(item => { if (item.key === currentStep) return { ...item, active: true }; return { ...item }; })) } }, [currentStep, initialData, dispatch]); const onSaveFormData = (step, data) => { dispatch(updateFormData({step, data})) } const onSubmit = () => { dispatch(endSurvey()) return setOpenModal(false); } if (!openModal) { return ( <Message positive icon='check' header='Your survey was submitted.' /> ) } let surveyContent = null; switch(currentStep) { case surveyStaps[0].key: surveyContent = ( <Identity onDisableNextStep={onDisableNextStep} onSave={onSaveFormData} initialData={formData.identity} /> ); break; case surveyStaps[1].key: surveyContent = ( <Details onSave={onSaveFormData} onDisableNextStep={onDisableNextStep} initialData={formData.details} /> ); break; case surveyStaps[2].key: surveyContent = ( <Favorites onDisableNextStep={onDisableNextStep} onSave={onSaveFormData} initialData={formData.favorites} /> ); break; case surveyStaps[3].key: surveyContent = ( <Summary formData={formData} /> ); break; default: surveyContent = null; break; } return ( <SurveyWrapper disableNextStep={disableNextStep} listWithActiveStep={listWithActiveStep} onClickPrevStep={!!prevStepKey && (() => dispatch(setCurrentStep(prevStepKey)))} onClickNextStep={!!nextStepKey && (() => dispatch(setCurrentStep(nextStepKey)))} onSubmit={currentStep === surveyStaps[3].key && onSubmit} openModal={openModal} > {surveyContent} </SurveyWrapper> ); } export default SurveyScreen; <file_sep>/survey-front/src/redux/index.js import { configureStore } from '@reduxjs/toolkit' import stepsSlice from './stepsSlice'; import surveySlice from './surveySlice'; const startStore = () => configureStore({ reducer: { steps: stepsSlice, survey: surveySlice, } }); export default startStore;<file_sep>/survey-front/src/components/SurveyWrapper.js import React from 'react'; import PropTypes from 'prop-types'; import { Button, Modal, Step, Segment } from 'semantic-ui-react'; const SurveyWrapper = ({ children, disableNextStep, listWithActiveStep, onClickNextStep, onClickPrevStep, onSubmit, openModal, }) => { return ( <Modal centered={false} open={openModal} > <Modal.Header> Profile Survey </Modal.Header> <Modal.Content> {listWithActiveStep.length > 0 && ( <Step.Group attached="top" items={listWithActiveStep} widths={listWithActiveStep.length} /> )} <Segment attached> {children} </Segment> </Modal.Content> <Modal.Actions> {onClickPrevStep && ( <Button content="Previous" icon='left arrow' labelPosition='left' onClick={onClickPrevStep} primary /> )} {onClickNextStep && ( <Button content="Next" disabled={disableNextStep} icon='right arrow' labelPosition='right' onClick={onClickNextStep} primary /> )} {onSubmit && ( <Button content="Submit" icon='right arrow' labelPosition='right' onClick={onSubmit} color="green" /> )} </Modal.Actions> </Modal> ) }; SurveyWrapper.propTypes = { children: PropTypes.element, disableNextStep: PropTypes.bool.isRequired, listWithActiveStep: PropTypes.array, onClickNextStep: PropTypes.oneOfType([PropTypes.func, PropTypes.bool]), onClickPrevStep: PropTypes.oneOfType([PropTypes.func, PropTypes.bool]), onSubmit: PropTypes.oneOfType([PropTypes.func, PropTypes.bool]), openModal: PropTypes.bool.isRequired, }; SurveyWrapper.defaultProps = { children: null, listWithActiveStep: [], onClickNextStep: false, onClickPrevStep: false, onSubmit: false, } export default SurveyWrapper; <file_sep>/survey-front/test/unit-tests/components/SurveyWrapper.test.js import { shallow } from 'enzyme'; import SurveyWrapper from '../../../src/components/SurveyWrapper'; import toJson from 'enzyme-to-json'; const steps = [{ key: 'step1', icon: 'table', title: 'Step 1' }, { key: 'step2', icon: 'info', title: 'Step 2', }]; describe('<SurveyWrapper />', () => { test('Render correctly', () => { const wrapper = shallow( <SurveyWrapper disableNextStep={false} listWithActiveStep={steps} onClickPrevStep={() => {}} onClickNextStep={() => {}} onSubmit={() => {}} openModal={true} /> ); expect(toJson(wrapper)).toMatchSnapshot(); }); test('Should correctly handle navigation buttons', () => { const onClickPrevStep = jest.fn(); const onClickNextStep = jest.fn(); const onSubmit = jest.fn(); const wrapper = shallow( <SurveyWrapper disableNextStep={false} listWithActiveStep={steps} onClickPrevStep={onClickPrevStep} onClickNextStep={onClickNextStep} onSubmit={onSubmit} openModal={true} /> ); // expect(toJson(wrapper)).toMatchSnapshot(); }); }) <file_sep>/survey-front/src/service/SurveyService.js const SURVEY_DATA = 'surveyData'; const SURVEY_STEP = 'surveyStep' const saveData = data => { const dataString = JSON.stringify(data); return window.localStorage.setItem(SURVEY_DATA, dataString); }; const endSurvey = () => { const dataString = JSON.stringify({ status: 'finished' }); window.localStorage.removeItem(SURVEY_STEP); return window.localStorage.setItem(SURVEY_DATA, dataString); }; const saveStep = step => { return window.localStorage.setItem(SURVEY_STEP, step); }; const getData = () => { const data = window.localStorage.getItem(SURVEY_DATA); return JSON.parse(data); }; const getStep = () => { const data = window.localStorage.getItem(SURVEY_STEP); return data; } const actions = { saveData, endSurvey, saveStep, getData, getStep } export default actions <file_sep>/survey-front/src/redux/surveySlice.js import { createSlice } from '@reduxjs/toolkit' import service from '../service/SurveyService'; const initialState = { status: null, formData: { identity: { name: '', email: '', }, details: { age: 0, gender: '', }, favorites: { book: '', colors: [], } } } export const stepsSlice = createSlice({ name: 'survey', initialState: { ...initialState }, reducers: { updateFormData: (state, action) => { const { data, step } = action.payload; state.status = 'filling'; state.formData[step] = data; return service.saveData(state.formData) }, endSurvey: state => { state.status = 'finished'; state.formData = initialState.formData; return service.endSurvey(); } } }); export const { endSurvey, updateFormData } = stepsSlice.actions export default stepsSlice.reducer <file_sep>/survey-front/src/components/survey-steps/Favorites.js import React, { useState, useEffect } from 'react'; import PropTypes from 'prop-types'; import { Form, Checkbox } from 'semantic-ui-react'; import { debounce, isEmpty } from 'lodash'; import colorsList from '../../config/colorsList'; const onSaveWithDebounce = debounce((data, onSave, onDisableNextStep) => { const disable = Object.values(data).every(i => !isEmpty(i)); onDisableNextStep(!disable); return onSave('favorites', data); }, 300); const Favorites = ({ initialData, onDisableNextStep, onSave, }) => { const [formData, setFormData] = useState({ ...initialData }); useEffect(() => { const validFormData = Object.values(formData).every(i => !isEmpty(i)) onDisableNextStep(!validFormData); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const onChange = e => { onSaveWithDebounce.cancel(); const newFormData = { ...formData, [e.target.name]: e.target.value, }; setFormData(newFormData); onSaveWithDebounce(newFormData, onSave, onDisableNextStep); }; const onCheckboxChange = (e, { name, value, checked }) => { const colors = [...formData.colors]; if (checked) { colors.push(value) } else { const valueIndex = colors.findIndex(item => item === value); colors.splice(valueIndex, 1); } return onChange({ target: { name, value: colors } }); } return ( <Form> <Form.Input id='survey-identity-field-favorite-book' label='Favorite Book' name='book' onChange={onChange} required placeholder='Type your favorite book name' value={formData.book} /> <Form.Field required> <label>Favorite Colors</label> {colorsList.map(item => ( <Form.Field key={item.value}> <Checkbox checked={formData.colors.includes(item.value)} label={item.name} name='colors' onChange={onCheckboxChange} value={item.value} /> </Form.Field> ))} </Form.Field> </Form> ); }; Favorites.propTypes = { initialData: PropTypes.shape({ book: PropTypes.string.isRequired, colors: PropTypes.array.isRequired, }).isRequired, onDisableNextStep: PropTypes.func.isRequired, onSave: PropTypes.func.isRequired, }; export default Favorites;<file_sep>/README.md # YieldStreet code challenge This repo contains a Survey app build with ReactJS, Redux, Semantic UI and other usefull libs. You can see this app running by cloning the repo and opening `example.html` in your web browser. A small HTML file that imports the React app static JS and CSS files and render the survey. ## The React App You can navigate to the `survey-front` folder, where are located the React app source files and run (The app was built using `yarn` but you can use `npm` without problem.): - `yarn` to install dependencies - `yarn start` to run development server - `yarn build` to generate a production version. The JS and CSS files are generated with the same name to prevent breaking other pages including the survey and get allway the most recent changes. - `yarn test` to run the unit tests. ### Folder structure - `/components` Components that render the UI. They contains a small fragment of code, usual, the style rules and can be reused. - `/containers` Components with the screen logic. They can connect with Redux, call some Service APIs, handle application flow and usually return the `/components` to build the screen style. - `/config` Some app static configs. - `/redux` React Redux config files. Each application logical separation have a `*Slice.js` file with redux settings. Usually, they are: initial state and actions to handle the state. - `/service` Functions to connect with service APIs. Usually, they are called by Redux actions or containers to do some CRUD operations with an API. ### Data Store Service The app use the web browser localStorage to store the survey data, simulating the comunication with an API. ### Test `unit-tests` This app makes use of Redux containers/components logic. That means the components have only the style rules, just receiving props and showing content using Sematic UI elements to build the view and they can be used by other containers. To get a consistent result, was developed unit tests to assure all changes on the components will be verified. `integrated` Containers can interact with Redux, API service, static configs and other data source to get the needed information to build the logic that will return components with apropriated props to build the desired screen. To assume that all data sources and logics are correctly working, was developed integrated tests for containers, assuring all needed interaction will be correact. <file_sep>/survey-front/src/components/survey-steps/Summary.js import React from 'react'; import PropTypes from 'prop-types'; import { Table } from 'semantic-ui-react' import colorsList from '../../config/colorsList'; const Summary = ({ formData }) => { const formatString = str => `${str.charAt(0).toUpperCase()}${str.slice(1)}`; const formatValue = (fieldName, value) => { switch(fieldName) { case 'gender': return formatString(value); case 'colors': { const colorName = value.map(item => { const color = colorsList.find(c => c.value === item) return color.name }); return colorName.join(', ') } default: return value; } } return ( <Table celled structured> <Table.Header> <Table.Row> <Table.HeaderCell rowSpan='2'>Step</Table.HeaderCell> <Table.HeaderCell rowSpan='2'>Field Name</Table.HeaderCell> <Table.HeaderCell rowSpan='2'>Field Value</Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> {Object.keys(formData).map(step => { const stepKeys = Object.keys(formData[step]); return stepKeys.map((row, index) => ( <Table.Row key={row}> {index === 0 && ( <Table.Cell rowSpan={stepKeys.length}>{formatString(step)}</Table.Cell> )} <Table.Cell>{formatString(row)}</Table.Cell> <Table.Cell>{formatValue(row, formData[step][row])}</Table.Cell> </Table.Row> )) })} </Table.Body> </Table> ); }; Summary.propTypes = { formData: PropTypes.object.isRequired, }; export default Summary;<file_sep>/survey-front/test/unit-tests/components/survey-steps/Identity.test.js import { mount } from 'enzyme'; import toJson from 'enzyme-to-json'; import Identity from '../../../../src/components/survey-steps/Identity'; describe('<Identity />', () => { test('Should render correctly with inital value', () => { const wrapper = mount( <Identity initialData={{ name: '<NAME>', email: '<EMAIL>' }} onDisableNextStep={() => {}} onSave={() => {}} /> ); expect(toJson(wrapper)).toMatchSnapshot(); }); test('Should call prop to disable next button in the flow', () => { const onDisableNextStep = jest.fn(); mount( <Identity initialData={{ name: '<NAME>', email: '<EMAIL>', }} onDisableNextStep={onDisableNextStep} onSave={() => {}} /> ); expect(onDisableNextStep).toBeCalledWith(false); }); test('Should call onSave after change input value', done => { const onSave = (step, data) => { expect(step).toEqual("identity") expect(data).toEqual({ email: "<EMAIL>", name: "<NAME>" }); return done(); }; const wrapper = mount( <Identity initialData={{ name: '<NAME>', email: '<EMAIL>', }} onDisableNextStep={() => {}} onSave={onSave} /> ); wrapper.find('input').at(0).simulate('change', { target: { name: 'name', value: '<NAME>' }}) wrapper.find('input').at(1).simulate('change', { target: { name: 'email', value: '<EMAIL>' }}) }); })
281c4a4ba01b815965a90993174cfdf11177d094
[ "JavaScript", "Markdown" ]
18
JavaScript
crysdelima/ys-challenge
f1222021717c2c0250b95d72c4691f768b8095fa
6778d5df0fec2be6d5d6fa1dd72a9d0dfe4b1a18
refs/heads/master
<file_sep>import sys sys.setrecursionlimit(10000) class Colors: ''' Doc ''' END = '\33[0m' BOLD = '\33[1m' ITALIC = '\33[3m' BLACK = '\33[30m' RED = '\33[31m' GREEN = '\33[32m' YELLOW = '\33[33m' BLUE = '\33[34m' VIOLET = '\33[35m' BEIGE = '\33[36m' WHITE = '\33[37m' def color_print(self, color_text, text): print('{}{}{}'.format(color_text, text, self.END)) class Ackermann(Colors): ''' Doc ''' def __init__(self, top=None, init=True): self.top = top if init: self.color_print(self.BOLD, '\nWelcome, this is the Ackermann\'s algorithm') print('Please insert a number to generate the table with test values') self.menu() def menu(self): while True: try: print('\n----------------------------------') print('1: Print recursive table') print('2: Print specific value') print('0: Exit') print('----------------------------------\n') action = int(input('\nInsert a valid option: ')) if action == 1: self.print_table() elif action == 2: self.print_specific_value() elif action == 0: print('Bye, come back soon!') break else: print('was inserted a incorrect value, try again') except ValueError: print('Has occurred a problem, try again') self.menu() def print_table(self): self.top = int(input('From 1 to <value>:')) print('\n------------------') print('| m | n | A(m,n) |') print('------------------') for i in range(1, self.top + 1): for j in range(1, i + 1): print('| {} | {} | {} |'.format(i, j, self.ackermann(i, j))) def print_specific_value(self): m = int(input('Insert value to M: ')) n = int(input('Insert value to N: ')) print('\n A({}, {}) = {}'.format( m, n, self.ackermann(m, n) )) def ackermann(self, m, n): if m == 0: return n + 1 elif n == 0: return self.ackermann(m - 1, 1) else: # m or n rather than zero return self.ackermann(m - 1, self.ackermann(m, n - 1)) Ackermann() #print(Ackermann(init=False).ackermann(1,1))
508a7d99bf1227a4cedfb4dd8a4679a56fc4d82e
[ "Python" ]
1
Python
brianou7/ackermann
9f7dca21fccd1eb74c532c4afde7bc0c4a487ce0
090b37d3fc3e78f0da9964db2b62cea464b9780e
refs/heads/master
<repo_name>sastorsl/net-test<file_sep>/README.md # Net Test Monitors network connectivity for downtime. # Table Of Contents - [Overview](#overview) - [Output](#output) - [Sites](#sites) - [Test Results](#test-results) - [Usage](#usage) - [Net Test](#net-test) - [Filter](#filter) - [Analyse](#analyse) # Overview Set of scripts for analysing network connectivity. The `net-test.sh` tool will check network connectivity every second by pinging well known websites. If the tool fails to connect to one well known website it will try to connect to the next well known website. A network connectivity test will only fail if all websites can not be contacted. # Output ## Sites The sites which the tool checks connectivity by connecting to will be printed out in order of precedence when `net-test.sh` is started. Each site will appear on a new line, which will start with a `#`. This behavior can be disabled by passing the `--no-header` argument to `net-test.sh`. ## Test Results The results of connectivity tests will be recorded in the following format: ``` <Unix Time> <Connected?> <Website Index> <Latency> ``` - Unix Time: Time test was started, seconds since epoch - Connected?: 1 if connected to internet, 0 if not - Website Index: Which website was successfully connected to. Index starts at 0 - Latency: Time in milliseconds, -1 if test failed The output of this command can then be passed into the `filter.sh` command to display separate out tests which pass from tests which fail. Output can also be passed to `analyse` to see statistics about the test. # Usage ## Net Test Runs network connectivity tests every second. Usage: `net-test.sh` Arguments: - `--no-header`: Don't print the list of sites the script contacts when the script begins. This can be used if one wishes to continue appending statements to an existing log file. To save the output for later analysis: `net-test.sh >> test.log`. Example output: ``` #1.1.1.1 #8.8.8.8 #google.com #wikipedia.com 1526769729 1 0 7.395 1526769730 1 0 10.374 1526769731 1 0 10.385 1526769732 1 0 5.797 1526769733 1 0 7.082 1526769734 1 0 8.669 1526769735 1 0 20.135 1526769736 1 0 20.029 ``` ## Filter Filters network connectivity output to only show specific types of test output. Usage: `filter.sh < test.log` Arguments: - `--status` (String): Filter tests which pass or fail. Accepted values: `pass`, `fail` - `--sites`: Displays sites header from test output, must be only argument provided to filter. To directly pipe in the net test output: `net-test.sh | filter.sh` Or to filter log file output in real time: `tail -f test.log | filter.sh` ## Analyse Display statistics about test output. The analyse tool is written in C to achieve higher performance. A version was written in Bash, but it took upwards of 2 minutes to complete what the C version could do in seconds. To build the analyse tool navigate to the `analyse` directory and run `make`. This will compile the analyse tool and output a binary named `analyse`. Usage: `analyse < test.log` Analyse expects test logs to be provided via stdin. If there is more than 2 minute gap between tests the script assumes net-test was paused. And will disregard this gap when counting the total running time. The number of successful and failed tests along average latency will be printed out. Example output: ``` Total: 86800, Failed: 99.990% (86791), Succeeded: 0.010% (9) Ruuning time: 25:25:39, Avrg latency: 10.391 ms ``` <file_sep>/filter.sh #!/usr/bin/env bash # #? # Filter - Searches Net Test output for network connectivity tests with specific # statuses # # Usage: filter.sh # # Expects stdin to be net-test.sh output # # Arguments: # --status (String): Filter output to only show tests which "pass" or # "fail" # --sites: Will only show the sites header from test output. Can not be # used with any other argument #? # Parse arguments default_op_status=".*" op_status="$default_op_status" op_sites="false" while [ ! -z "$1" ]; do key="$1" shift case "$key" in --status) if [ "$1" == "pass" ]; then op_status=1 elif [ "$1" == "fail" ]; then op_status=0 else echo "Error: --status argument expects either \"pass\" or \"fail\"" >&2 exit 1 fi shift ;; --sites) op_sites="true" ;; *) echo "Error: unknown argument \"$key\"" >&2 exit 1 ;; esac done # Check --sites argument is only argument if passed if [ "$op_status" != "$default_op_status" ] && [ "$op_sites" == "true" ]; then echo "Error: --sites argument can not be provided with any other arguments" >&2 exit 1 fi # If sites arg provided if [ "$op_sites" == "true" ]; then # Read lines until no more sites headers while read -r line; do if [[ "$line" =~ ^# ]]; then echo "$line" | sed -e 's/^#\(.*\)/\1/' else exit 0 fi done else cat - | grep -P "^.* $op_status .* .*" fi <file_sep>/analyse/analyse.c #include <stdio.h> #include <string.h> #include <stdlib.h> int main() { // Counters int lastT = -1; int deltaT = 0; int failed = 0; int succeeded = 0; float latencyTotal = 0.0; int numTests = 0; // For each line size_t buffSize; char *buff = NULL; while (getline(&buff, &buffSize, stdin) > 0) { // Check if site header line if (buff[0] == '#') { continue; } // Extract test result parts int i = 0; char *subtok = strtok(buff, " "); int testT = -1; float testLatency = 0.0; while (subtok !=NULL) { if (i == 0) { // If test time char *endptr; int inttok = strtol(subtok, &endptr, 10); if (endptr == subtok) { // Check parse error printf("Error parsing test time: %s, errno: %d\n", subtok, inttok); return 1; } // Set lastT testT = inttok; } else if (i == 1) { // If test result // If successfull test char *endptr; int inttok = strtol(subtok, &endptr, 10); if (endptr == subtok) { // Check parse error printf("Error parsing test status: %s, errno: %d\n", subtok, inttok); return 1; } if (inttok == 1) { succeeded++; } else if (inttok == 0) { failed++; } else { printf("Error unknown test result value %d\n", inttok); return 1; } } else if (i == 3) { // If latency testLatency = atof(subtok); latencyTotal += testLatency; } subtok = strtok(NULL, " "); i++; } // Determine if script was paused int testDt = testT - lastT; if (testDt < 120) { deltaT += testDt; } lastT = testT; numTests++; } // Print results // -- -- Calculate percentages float failedPercent = 0.0; float succeededPercent = 0.0; if (numTests != 0) { failedPercent = ((float)failed / (float)numTests) * 100; succeededPercent = ((float)succeeded / (float)numTests) * 100; } // -- -- Calculate duration int hours = deltaT / 3600; int minutes = (deltaT % 3600) / 60; int seconds = deltaT % 60; // -- -- Calculate average latency float avrgLatency = latencyTotal / (float)numTests; // -- -- Output printf("Total: %d, Failed: %.3f% (%d), Succeeded: %.3f% (%d)\n", numTests, failedPercent, failed, succeededPercent, succeeded); printf("Ruuning time: %d:%d:%d, Avrg latency: %.3f ms\n", hours, minutes, seconds, avrgLatency); return 0; } <file_sep>/analyse/Makefile OUT=analyse SRC=analyse.c # analyse compiles the analyse tool # Arguments: # - GCC_FLAGS (Optional): Will be passed into GCC at compile time analyse: analyse.c gcc ${GCC_FLAGS} -o "${OUT}" "${SRC}" <file_sep>/net-test.sh #!/usr/bin/env bash # #? # Net Test - Monitors network connectivity for downtime. # # Usage: net-test.sh # # Attempts to connect to an internet service to verify internet connectivity # every second. Prints the status of this check in the format: # # <Unix Time> <Internet Connectivity> <Fallback Number> <Ping Time> # # Where <Internet Connectivity> is a 0 or a 1. And <Fallback Number> is the # index of the site in test_sites which the internet connectivity status was # determined with. # # Arguments # --no-header: Makes script not print sites header #? # List of sites to test internet connectivity with test_sites=("1.1.1.1" "8.8.8.8" "google.com" "wikipedia.com") test_interval=1 # Arguments op_no_header="false" while [ ! -z "$1" ]; do key="$1" shift case "$key" in --no-header) op_no_header="true" ;; *) echo "Error: unknown argument \"$key\"" >&2 exit 1 ;; esac done # Print site names if [ "$op_no_header" != "true" ]; then for site in "${test_sites[@]}"; do echo "#$site" done fi # Check while true; do current_time="$(date +%s)" internet_conn=0 fallback_num=0 ping_time="-1" # Try each test site until one succeeds for site in "${test_sites[@]}"; do ping_time_out=$((ping -c 1 "$site" | tail -1 | awk '{print $4}' | cut -d '/' -f 2) 2> /dev/null) if [ ! -z "$ping_time_out" ]; then internet_conn=1 ping_time="$ping_time_out" break fi fallback_num=$(("$fallback_num" + 1)) done # Record echo "$current_time $internet_conn $fallback_num $ping_time" sleep "$test_interval" done
ff0ccbe97541e285c0514e8dbacf2138909b203b
[ "Markdown", "C", "Makefile", "Shell" ]
5
Markdown
sastorsl/net-test
d9dc3c6b4e533c25da4e1c13e5edbac0672ddaf4
fe70e54b175a77619aa22d0554d94216ff123536
refs/heads/master
<repo_name>mikehodgson/plexopt<file_sep>/README.md # plexopt ## What is it? plexopt is a quick and dirty script I wrote to optimize videos for direct play using Plex. ## Usage Modify the variables at the top of the script, as neccessary, then: python plexopt.py <input filename> <output directory><file_sep>/plexopt.py #!/usr/bin/env python import sys import os import re from pathlib import Path import subprocess import json _FFMPEG_EXECUTABLE = 'ffmpeg' _FFPROBE_EXECUTABLE = 'ffprobe' _DESIRED_AUDIO = ['ac3','dts','dca','aac','mp3','mp2'] _DESIRED_VIDEO = ['hevc','h265','h.265','x265','vc1','h264','h.264','x264','wmv3','mpeg4','mpeg2video','vp9'] _OUTPUT_FORMAT = 'mp4' _DESIRED_LANGUAGE = ['eng'] def build_destination_path(infile, outdir): return Path(os.path.join(outdir, os.path.splitext(os.path.basename(infile))[0]+"."+_OUTPUT_FORMAT)) def do_conversion(infile, outfile, include_streams): cmd = _FFMPEG_EXECUTABLE + " -i \"" + str(infile.resolve()) + "\" -map " + " -map ".join(include_streams) + " -c copy \"" + str(outfile.resolve()) + "\"" print("running: " + cmd) try: subprocess.check_call(cmd) return True except subprocess.CalledProcessError: return False def convert(infile, outfile): result = subprocess.run(_FFPROBE_EXECUTABLE + " -v quiet -print_format json -show_streams " + str(infile.resolve()), shell=True, check=True, stdout=subprocess.PIPE) stream_data = json.loads(result.stdout) include_streams = [] for stream in stream_data['streams']: if stream['codec_type'] == 'audio': if (stream['tags']['language'] in _DESIRED_LANGUAGE) and (stream['codec_name'] in _DESIRED_AUDIO): print('found audio! ' + str(stream['index']) + ' ' + stream['codec_name'] + ' ' + stream['tags']['language']) include_streams.append('0:' + str(stream['index'])) elif stream['codec_type'] == 'video': if stream['codec_name'] in _DESIRED_VIDEO: print('found video! ' + str(stream['index']) + ' ' + stream['codec_name']) include_streams.append('0:' + str(stream['index'])) return do_conversion(infile, outfile, include_streams) def run(): infile = "" outfile = "" if (len(sys.argv) < 3): print('usage: plexopt.py <infile> <outdir>') sys.exit() infile = Path(sys.argv[1]) outdir = Path(sys.argv[2]) if not infile.is_file(): print('input file does not exist!') sys.exit() if not outdir.is_dir(): print('output directory does not exist!') sys.exit() outfile = build_destination_path(infile, outdir) print(outfile) result = convert(infile, outfile) if result: print('conversion succeeded!') else: print('conversion failed') run()
ea10d35a133be93f13f713285aeda6cb3a7d42b5
[ "Markdown", "Python" ]
2
Markdown
mikehodgson/plexopt
3ed9a0d8f9a8c69576faa7e1ac2bd6c5dca65ea8
ae5cf3b6d2a1dca77b2531008602542af9b77010
refs/heads/master
<file_sep> var RQ = require('./rq'); var _ = require('underscore'); var path = require('path'); var appPath = path.dirname(process.mainModule.filename); var configPath = path.join(appPath, 'config.js'); var config = require(configPath); var readers = require('./lib/readers'); var writer = require('./lib/writer')(config); function fetchDataForServer(requestion, server, lastMetrics) { RQ.sequence([ readers.connectToMongoDb, readers.fetchServerStatus, writer.toGraphiteMetricsArray(server, config.metrics.serverStatus, lastMetrics), writer.sendToGraphite ])(requestion, server); } function fetchReplicaStatus(requestion, server) { RQ.sequence([ readers.connectToMongoDb, readers.replSetGetStatus, writer.replicaSetToGraphiteMetrics, writer.sendToGraphite ])(requestion, server); } var lastResultArray = []; function intervalLoop() { var workArray = config.servers.map(function(server, index) { return function(requestion) { fetchDataForServer(requestion, server, lastResultArray[index]); }; }); RQ.parallel(workArray)(function(success, failure) { if (failure) { console.log('Error:', failure); } else { lastResultArray = success; console.log('ServerStatus fetched and set to graphite'); } }); var clusters = _.values(_.groupBy(config.servers, 'cluster')); var work = clusters.map(function(servers) { var replicaWork = servers.map(function(server, index) { return function(requestion) { fetchReplicaStatus(requestion, server); }; }); return RQ.fallback(replicaWork); }); RQ.parallel(work)(function(success, failure) { if (failure) { console.log('Error:', failure); } else { console.log('ReplicaSetStatus fetched and set to graphite'); } }); } setInterval(intervalLoop, config.intervalSeconds * 1000); <file_sep>mongodb-metrics =============== Fetches metrics from multiple mongodb servers, replica set status and database stats and sends them to graphite <file_sep> var MongoClient = require('mongodb').MongoClient, Db = require('mongodb').Db, Server = require('mongodb').Server, Admin = require('mongodb').Admin, ReadPreference = require('mongodb').ReadPreference, RQ = require('../rq'); function toMongoDbCallback(requesition, db) { return function(err, data) { if (!err && db) { requesition({db: db, data: data}); } requesition(data, err || undefined); }; } function connectToMongoDb (requesition, server) { console.log('Connecting to mongodb: %s', server.host); var db = new Db("admin", new Server(server.host, server.port || 27017, {}, {}), { safe: false }); db.open(toMongoDbCallback(requesition)); // close db connection after 500ms setTimeout(function () { console.log('closing connection'); db.close(); }, 500); } function fetchServerStatus (requesition, db) { console.log('fetching serverStatus'); db.command({ "serverStatus" : 1}, toMongoDbCallback(requesition)); } function fetchServerInfo (requesition, db) { console.log('fetching serverInfo'); var admin = db.admin(); admin.serverInfo(toMongoDbCallback(requesition)); } function replSetGetStatus (requesition, db) { console.log("fetching replSetStatus"); var admin = db.admin(); admin.replSetGetStatus(toMongoDbCallback(requesition)); } function listDatabases (requesition, db) { console.log("fetching database list"); var admin = db.admin(); admin.listDatabases(toMongoDbCallback(requesition, db)); } function dbStats (requesition, params) { var db = params.db; var databases = params.data.databases; var dbStatsRequestors = databases.map(function(database) { return function(callback) { console.log("getting dbStats for %s", database.name); var otherDb = db.db(database.name); otherDb.stats(toMongoDbCallback(callback)); }; }); RQ.parallel(dbStatsRequestors)(requesition); } module.exports = { connectToMongoDb: connectToMongoDb, fetchServerStatus: fetchServerStatus, replSetGetStatus: replSetGetStatus };
7d602db72468d60780674d7baf7944c055526736
[ "JavaScript", "Markdown" ]
3
JavaScript
srwiser/mongodb-metrics
da09fae321ea8405608b3195622a834904bc4729
35e6e82a7558c4e01df8896133b1e31959300ba6
refs/heads/master
<file_sep>const team = { _players: [ { firstName: 'Lionel', lastName: 'Messi', age: 33 }, { firstName: 'Luis', lastName: 'Suarez', age: 33 }, { firstName: 'Gerard', lastName: 'Pique', age: 33 } ], _games: [ { opponent: '<NAME>', teamPoints: 2, opponentPoints: 2 }, { opponent: 'Villarreal', teamPoints: 4, opponentPoints: 1 }, { opponent: 'Espanyol', teamPoints: 1, opponentPoints: 0 } ], get players () { return this._players; }, get games () { return this._games; }, addPlayer (firstName, lastName, age){ const player = { firstName, lastName, age }; this._players.push(player); }, addGame (opponent, teamPoints, opponentPoints) { const game = { opponent, teamPoints, opponentPoints }; this._games.push(game); } }; team.addPlayer('Name1', 'Surname1', 20); team.addPlayer('Name2', 'Surname2', 25); team.addPlayer('Name3', 'Surname3', 30); //console.log(team._players); team.addGame('Opponent1', 1, 1); team.addGame('Opponent2', 2, 2); team.addGame('Opponent3', 3, 3); console.log(team._games);
fd7116df59bbc37151407333e33db26b5310f9a2
[ "JavaScript" ]
1
JavaScript
UserMe07/JS-Project-Team-Stats
5d120d6fb17e695b4d2f3d95190ff1a59eadc737
4a2b9f2e0c06e89f3945d38e1dbf706abf87f076
refs/heads/master
<file_sep>// 1) Given an array K with N integers from 1 to N+1 such // that the array has exactly one integer missing, write a Java // function that returns the missing integer. // e.g. given K = [3,5,4,1], the function should return 2 // SOLUTION 1 function missingInt(array){ array.sort() for (let i=0; i<=array.length; i++) { if(array[i] + 1 !== array[i+1]){ return array[i] + 1 } } } // SOLUTION 2 function missingInt(array){ const total = (array.length + 1) * (array.length + 2)/2 const arraySum = array.reduce((a,b) => a+b) return total - arraySum } // test // console.log(missingInt([3,5,4,1])) // console.log(missingInt([3,2,5,1,6,7,9,4])) // 2. // 2) Given a string S of length N, write a Java function // that transforms the string by reversing characters in groups // of four, and returns the transformed string. // e.g. when S = 'Lorem at' the output should be 'eroLta m' // when S = ' Tempor ip' the output should be 'meT roppi' function reverseInGroups(str) { let finalStr = '' return str.split('').reverse().slice(4).join('') } function reverseInGroups(str) { let newArray = [] str.split('') for (let elem of str) { const last = newArray[newArray.length - 1] if (!last || last.length === 4) { newArray.push([elem]) } else { last.push(elem) } } for (let elem of newArray) { return elem.reverse().join('') } } // console.log(reverseStr("abcdefg", 2)) // console.log(reverseInGroups('Lorem at'))
916501082bda2882ac59f9af18934a7f18b3f4a1
[ "JavaScript" ]
1
JavaScript
Kalunge/assessment
7ab323b33f541381386b1617aafbc0564e67254b
267c76403b73b73c122808b6caf87ebd2895b37e
refs/heads/main
<repo_name>hyeon-wooo/react-native-cardview-withtype<file_sep>/README.md # @hyeonwoo/react-native-card-view > `Note!!` This is the same with the 'react-native-card-view' library. This is just what i have added the index.d.ts, the type define file on exsting that. note it. JUST WITH TYPE. [![npm](https://nodei.co/npm/react-native-cardview.png?downloads=true&downloadRank=true&stars=true)](https://www.npmjs.com/package/react-native-cardview) Native CardView that compatible for iOS and Android( both lollipop and pre-lolipop). ##### [Website](https://kishanjvaghela.github.io/react-native-cardview/) ##### [Material Design Card Spec](https://www.google.com/design/spec/components/cards.html) ##### [CardView Android Documentation](http://developer.android.com/intl/zh-tw/reference/android/support/v7/widget/CardView.html) ## Getting started ```bash $ npm install react-native-cardview --save # --- or --- $ yarn add react-native-cardview ``` ### Mostly automatic installation `$ react-native link react-native-cardview` ### Manual installation #### iOS Dont need to setup #### Android 1. Open up `android/app/src/main/java/[...]/MainApplication.java` - Add `import com.kishanjvaghela.cardview.RNCardViewPackage;` to the imports at the top of the file - Add `new RNCardViewPackage()` to the list returned by the `getPackages()` method 2. Append the following lines to `android/settings.gradle`: ``` include ':react-native-cardview' project(':react-native-cardview').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-cardview/android') ``` 3. Insert the following lines inside the dependencies block in `android/app/build.gradle`: ``` implementation project(':react-native-cardview') ``` ## Usage ![N|Example](https://github.com/Kishanjvaghela/react-native-cardview/raw/master/docs/Example-Snapshot.png) ![N|Example](https://github.com/Kishanjvaghela/react-native-cardview/raw/master/docs/ezgif-4-b87dbfaf72.gif) ## Example Browse the files in the [/example](https://github.com/Kishanjvaghela/react-native-cardview/tree/master/example) directory. ```javascript import CardView from "react-native-cardview"; <CardView cardElevation={2} cardMaxElevation={2} cornerRadius={5}> <Text>Elevation 0</Text> </CardView>; ``` You can also follow - https://reactnativecode.com/creating-card-view-in-android-ios-app-example/ - http://androidseekho.com/others/reactnative/how-to-use-card-view-in-react-native ## Attributes - **cardElevation** (Android/iOS) An attribute to set the elevation of the card. This will increase the 'drop-shadow' of the card. There can be some performance impact when using a very high elevation value. - **cardMaxElevation** (Android) An attribute to support shadow on pre-lollipop device in android. [cardMaxElevation](http://developer.android.com/intl/zh-tw/reference/android/support/v7/widget/CardView.html) - **cornerRadius** (Android/iOS) An attribute to set the radius of the card. - **useCompatPadding** (Android) CardView adds additional padding to draw shadows on platforms before Lollipop. [setUseCompatPadding](<https://developer.android.com/reference/android/support/v7/widget/CardView.html#setUseCompatPadding(boolean)>) - **cornerOverlap** (Android) On pre-Lollipop platforms, CardView does not clip the bounds of the Card for the rounded corners. Instead, it adds padding to content so that it won't overlap with the rounded corners. You can disable this behavior by setting this field to false. Setting this value on Lollipop and above does not have any effect unless you have enabled compatibility padding. [setPreventCornerOverlap](<https://developer.android.com/reference/android/support/v7/widget/CardView.html#setPreventCornerOverlap(boolean)>) <file_sep>/index.d.ts import * as React from 'react' import { ViewStyle, ViewProperties, TextStyle, ViewProps, } from 'react-native' export interface ICardViewProps extends ViewProps { /** * (Android/iOS) - An attribute to set the elevation of the card. * This will increase the 'drop-shadow' of the card. * There can be some performance impact when using a very high elevation value. */ cornerRadius?: number, /** * (Android) - An attribute to support shadow on pre-lollipop device in android. * http://developer.android.com/intl/zh-tw/reference/android/support/v7/widget/CardView.html */ cardElevation?: number, /** * (Android/iOS) - An attribute to set the radius of the card. */ cardMaxElevation?: number, /** * (Android) - CardView adds additional padding to draw shadows on platforms before Lollipop. * https://developer.android.com/reference/android/support/v7/widget/CardView.html#setUseCompatPadding(boolean) */ useCompatPadding?: boolean, /** * (Android) - On pre-Lollipop platforms, CardView does not clip the bounds of the Card for the rounded corners. * Instead, it adds padding to content so that it won't overlap with the rounded corners. * You can disable this behavior by setting this field to false. * https://developer.android.com/reference/android/support/v7/widget/CardView.html#setPreventCornerOverlap(boolean) */ cornerOverlap?: boolean } export default class CardView extends React.Component<ICardViewProps> {}
5d1c0c2f5c1ff095fa7dfed9719e64ee42b9729f
[ "Markdown", "TypeScript" ]
2
Markdown
hyeon-wooo/react-native-cardview-withtype
86cd3c633464372de17eed3f791181461f5c1108
5c6cdc675fd3850288510723fc4488857ee95a4c
refs/heads/master
<file_sep># linux-configure This repo contains my own linux configure files <file_sep>#!/bin/bash apt-get install -y curl wget build-essential libncurses5-dev python-dev git wget -c ftp://ftp.vim.org/pub/vim/unix/vim-7.4.tar.bz2 tar -xjf vim-7.4.tar.bz2 cd vim74 ./configure --with-features=huge \ --enable-multibyte \ --enable-rubyinterp \ --enable-pythoninterp \ --with-python-config-dir=/usr/lib/python2.7/config \ --enable-perlinterp \ --enable-luainterp \ --enable-gui=gtk2 \ --enable-cscope make install -j4 cd .. cat >>${HOME}/.bashrc <<EOF alias vi='/usr/local/bin/vim' EOF source ${HOME}/.bashrc
f886cb7dc890ef574256f0e982929a595f4b08f0
[ "Markdown", "Shell" ]
2
Markdown
gitchs/linux-configure
b1ef3337de7bdf67c893b31bc90b0f69d2391a53
80ffa87354a881e7bb9cef66fddbf7c38a5e6491
refs/heads/master
<repo_name>txoyp/php<file_sep>/myPhp/server.php <?php /** * Created by PhpStorm. * User: Lenovo * Date: 2018/10/14 * Time: 13:51 */ $name = $_GET['name']; $p1 = $_GET['p1']; $p2 = $_GET['p2']; if($name == ''){ echo 'nameErr'; }elseif($p1 == ''){ echo 'p1Err'; } elseif ($p2 == ''){ echo 'p2Err'; }elseif($p1 != $p2){ echo 'error'; } else{ echo 'success'; } ?><file_sep>/myPhp/reg.php <!DOCTYPE html> <html> <head> <style> .error{ color: red; } </style> </head> <body> 用户名:<input type="text" id="username"> <span class="error name-err"></span> <br> 密码:<input type="<PASSWORD>" id="pwd1"> <span class="error p1-err"></span> <br> 确认密码:<input type="<PASSWORD>" id="<PASSWORD>"> <span class="error p2-err"></span> <span class="error p3-err"></span> <button id="btn">注册 </button> <script src="js/jquery-1.12.4.js"></script> <script> $(function () { $('#btn').on('click',function () { var username = $('#username').val(); var pwd1 = $('#pwd1').val(); //val() 获取值 var pwd2 = $('#pwd2').val(); $.get('server.php',{ //url地址(绝对/相对),对象(向url地址中传数据),回调,返回数据类型 name:username, p1:pwd1, p2:pwd2, },function (data) { if(data == 'nameErr') { $('.name-err').html('用户名不能为空'); } else if(data == 'p1Err'){ $('.name-err').html('密码不能为空'); } else if(data == 'p2Err'){ $('.name-err').html('确认密码不能为空'); } else if(data == 'error'){ $('.name-err').html('密码不一致'); } else{ $('.name-err').html(''); } },'text'); }) $('#username').focus(function () { $('.name-err').html(''); }) }) </script> <?php ?> </body> </html>
0bf6dcc7cd30123e9d223db4bd69e69815dcd77e
[ "PHP" ]
2
PHP
txoyp/php
0d2e6856ac77ae759d7192155a02e80733716169
bf85791a54a320d3cb44a91495fe78b9e5842e94
refs/heads/master
<repo_name>JohnDMasterson/cubemmo<file_sep>/README.md # cubemmo This is a webGL demo I made for sig-soft. It has an online version running at http://cubemmo.herokuapp.com For the app to work properly, there must be multiple users on the site (or multiple browser tabs) Controls: W/S/A/D for moving forward/backward/left/right Q/E For rotating Left/Right <file_sep>/public/javascripts/index.js // Startup websocket connection var socket = io.connect('/'); //my socket id; var myId = ""; // Initializes position for the user; var position = {'x':0, 'y':0, 'z':0}; //initializes the cubes direction var angle = 0; //holds other objects that we need to draw var otherCubes = {}; //gl instance var gl; //buffers for vertices var cubeVertexBuffer; var cubeIndexBuffer; var cubeColorBuffer; //matrices used for transformations var mvMatrix = mat4.create(); var pMatrix = mat4.create(); //matrix for knowing if key is pressed or not var isPressed = {}; //this is called when the document loads $(document).ready(function (){ webGLStart(); //client is given his id socket.on('give_id', function (id) { myId = id; socket.emit('give_position', {'id':myId, 'pos':position, 'ang':angle}); socket.emit('get_all_positions'); }); //client is requested for his position socket.on('get_position', function () { socket.emit('give_position', {'id':myId, 'pos':position, 'ang':angle} ); }); //client is told another client's position socket.on('update_position', function ( cube ) { if (cube.id != myId) { otherCubes[cube.id] = cube; } }); //other client disconnected socket.on('delete_cube', function ( cubeID ) { delete otherCubes[cubeID]; }); //server gives client all positions socket.on('give_all_positions', function ( allPos ) { var strin = "" for (p in allPos) { if (allPos[p].id != myId) { otherCubes[p] = allPos[p]; } } }); }); //initializes webgl, sets up key handlers, and starts the program function webGLStart() { var canvas = document.getElementById("cubemmo-canvas"); initGL(canvas); initShaders(); initBuffers(); //arow key controls document.onkeydown = handleKeyDown; document.onkeyup = handleKeyUp; //background color, black gl.clearColor(0.0, 0.0, 0.0, 1.0); //enables 3D stuff gl.enable(gl.DEPTH_TEST); mainLoop(); } //tries to start webgl. If it can't, it alerts the user function initGL(canvas) { try { gl = canvas.getContext("webgl", {preserveDrawingBuffer: true}); window.addEventListener('resize', resizeCanvas); resizeCanvas(); } catch (e) { } if(!gl) { alert ("Could not initialize WebGL"); } } function getShader(gl, glslcode, type) { var shader; if (type == "x-shader/x-fragment") { shader = gl.createShader(gl.FRAGMENT_SHADER); } else if (type == "x-shader/x-vertex") { shader = gl.createShader(gl.VERTEX_SHADER); } else { return null; } gl.shaderSource(shader, glslcode); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { alert(gl.getShaderInfoLog(shader)); return null; } return shader; } function initShaders() { var fsource = getSourceSync("shaders/default.frag"); var vsource = getSourceSync("shaders/default.vert"); var fragmentShader = getShader(gl, fsource, "x-shader/x-fragment"); var vertexShader = getShader(gl, vsource, "x-shader/x-vertex"); shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertexShader); gl.attachShader(shaderProgram, fragmentShader); gl.linkProgram(shaderProgram); if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { alert("Could not initialize shaders"); } gl.useProgram(shaderProgram); shaderProgram.vertexAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition"); gl.enableVertexAttribArray(shaderProgram.vertexAttribute); shaderProgram.colorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor"); gl.enableVertexAttribArray(shaderProgram.colorAttribute); shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix"); shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix"); } //main loop for the program //calls the key handler, then draws function mainLoop() { keyHandler(); drawScene(); requestAnimFrame(mainLoop); } function initBuffers() { //three buffers created //first buffer holds all the vertices //second buffer holds the indices in the order we want to call them //third buffer holds colors for vertices cubeVertexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexBuffer); var vertices = [ 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, -1.0, -1.0, -1.0 ]; gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); cubeVertexBuffer.itemSize = 3; cubeVertexBuffer.numItems = 8; //index buffer //tells the shaer the order of what to draw cubeIndexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeIndexBuffer); var indices = [ //front faces 0, 1, 2, 1, 3, 2, //back faces 4, 6, 7, 4, 7, 5, //top faces 4, 5, 0, 5, 1, 0, //right faces 4, 0, 2, 6, 4, 2, //bottom faces 2, 3, 6, 3, 7, 6, //left faces 1, 5, 3, 5, 7, 3 ]; gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW); cubeIndexBuffer.numItems = 36; //color buffer //tells shader what color each vertex is cubeColorBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, cubeColorBuffer); var colors = [ 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0 ]; gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW); cubeColorBuffer.itemSize = 4; cubeColorBuffer.numItems = 8; } function drawScene() { //sets up viewport gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight); //clears out the previous buffers in video cards memory gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); //perspective matrix mat4.perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0, pMatrix); //the section below draws the squares //binds the vertices gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexBuffer); gl.vertexAttribPointer(shaderProgram.vertexAttribute, cubeVertexBuffer.itemSize, gl.FLOAT, false, 0, 0); //binds the colors gl.bindBuffer(gl.ARRAY_BUFFER, cubeColorBuffer); gl.vertexAttribPointer(shaderProgram.colorAttribute, cubeColorBuffer.itemSize, gl.FLOAT, false, 0, 0); //binds indices gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeIndexBuffer); for(c in otherCubes) { //Turns mvMatrix into identity mat4.identity(mvMatrix); //first, we rotate the world to how your cube see's it mat4.rotate(mvMatrix, degToRad(-angle), [0,1,0]); //then we translate the world's origin to where your cube is mat4.translate(mvMatrix, [-position.x, -position.y, -position.z]); //next, we translate the other cubes to the origin mat4.translate(mvMatrix, [otherCubes[c].pos.x, otherCubes[c].pos.y, otherCubes[c].pos.z]); //finally, we rotate the other cube mat4.rotate(mvMatrix, degToRad(otherCubes[c].ang), [0,1,0]); //passes matrices into shader program gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix); gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix); //draws elements //this uses the index buffer to choose the order of drawing //it takes three indices at a time gl.drawElements(gl.TRIANGLES, cubeIndexBuffer.numItems, gl.UNSIGNED_SHORT, 0); } } //converts degrees to radians function degToRad(degrees) { return degrees * Math.PI / 180; } //used for getting files from server var getSourceSync = function(url) { var req = new XMLHttpRequest(); req.open("GET", url, false); req.send(null); return (req.status == 200) ? req.responseText : null; }; function handleKeyUp(event) { isPressed[event.keyCode] = false; } function handleKeyDown(event) { isPressed[event.keyCode] = true; } function keyHandler() { //these control movement //a 65 if(isPressed[65] == true) { moveRight(-.15); } //w 87 if(isPressed[87] == true) { moveForward(.15); } //d 68 if(isPressed[68] == true) { moveRight(.15); } //s 83 if(isPressed[83] == true) { moveForward(-.15); } //these control turning //q 81 if(isPressed[81] == true) { turnRight(1); } //e 69 if(isPressed[69] == true) { turnRight(-1); } } function moveForward(distance) { var xtemp = distance*Math.sin(degToRad(angle)); var ztemp = distance*Math.cos(degToRad(angle)); position.x = position.x - xtemp; position.z = position.z - ztemp; socket.emit('give_position', {'id':myId, 'pos':position, 'ang':angle} ); } function moveRight(distance) { var xtemp = distance*Math.sin(degToRad(angle-90)); var ztemp = distance*Math.cos(degToRad(angle-90)); position.x = position.x - xtemp; position.z = position.z - ztemp; socket.emit('give_position', {'id':myId, 'pos':position, 'ang':angle} ); } function turnRight(distance) { angle = (angle + distance)%360; socket.emit('give_position', {'id':myId, 'pos':position, 'ang':angle} ); } function resizeCanvas() { var canvas = document.getElementById("cubemmo-canvas"); // only change the size of the canvas if the size it's being displayed // has changed. if (gl.viewportWidth != canvas.clientWidth || gl.viewportHeight != canvas.clientHeight) { // Change the size of the canvas to match the size it's being displayed gl.viewportWidth = canvas.width = canvas.clientWidth; gl.viewportHeight = canvas.height = canvas.clientHeight; } }
30bcadd46509651cda079b4dda7f845e66300a0d
[ "Markdown", "JavaScript" ]
2
Markdown
JohnDMasterson/cubemmo
a1ba1c2b3f62677a9224cebd59f2e9cc13ea55b1
9c79110b0ee69a04253eb0052097f1873872935a
refs/heads/master
<repo_name>Iemnur/LBEE-Decropper<file_sep>/SharedInc.h // Version 1.0 - Initial release // Version 1.1 - Added fix for CGs which have cropped decals // Version 1.2 - Added fix for heartbeat effect which occurs on a few CGs #define VERSION 1.2 // MS says Win7 supports D3D11_1. But, after trying this, it appears that using any 11_1 features on win7 won't work. I hate Microsoft. // Using D3D11_1 will implement the changes using UAVs in geometry shader. // Without D3D11_1, we have to use stream out and SRVs instead #define USE_D3D11_1 0 <file_sep>/Readme.txt 0. Introduction This project is used to resize the CGs in Little Busters! English Edition so that they are not cropped from 4:3 to fill inside a 16:9 window. Instead they will be fit inside the window with black borders on the left and right. 1. Hook The first step is to have the patch DLL intercept the D3D11 calls. From there we can adjust them to change the rendering. This is done with the patch D3D11 DLL that first finds the real D3D11 Dll and and gets the address of all that DLL's functions. This is done in DllMain(). Then after the device is created, we get the VTable of the DeviceContext and use Minhook to override the DrawIndexed() and SetPredication() functions. All of the work to adjust the rendering is done in DrawIndexed. The SetPredication hook is only used to detect a frame transition. 2. D3D11 In DrawIndexed(), we need to be able to detect when LBEE is rendering a 4:3 CG that has been cropped to 16:9. We do this by checking that the dimensions of PS SRV 0 are 1280x960. Once this has been deteced we add Geometry Shader to the D3D11 pipeline. This Geometry Shader will resize the CG. We also need to change the PS samplers to use bilinear filtering and have a black background color. Also we need to configure the stream out state. We also need to detect when the CG has a Decal on it. These Decals are used by the app to produce variations on the base CG. Since we have transformed the CG, we also need to apply the same transformation to the Decal so that it is rendered in the correct position. These decals are detected by examing the BlendState. 3. GS To adjust the rendering, a GS interception path has been chosen. This is very convenient to use since this stage is optional, not used by LBEE, and occurs between the VS and PS. This point in the rendering allows us to override the position and texture coordinates of the CG after the VS calculates them and before the Rasterizer/PS use them. The math in the GS shaders is a little bit tricky and I will only give an overview here. For full detail, see the hlsl code. LBEE takes a source CG of 1280x960 and renders it into 1280x720 space. This means that only a 720 pixel portion of the 960 vertical range appears on screen. The exact range that gets displayed varies by CG. The LBEE is somewhat confusing as it uses two different methods to scale the CG. Sometimes it renders 1280x960 geometry with a Y texture coordinate in the [0,1] range and uses the position coordinates to determine what is visible on screen. Other times, it renders only 1280x720 geometry on the screen, and uses the texture coordinates to determine what is visible. The GSs have to account for both approaches. There are a few CGs where the game uses a small amount of CG scaling to produce a heartbeat effect. This is accounted for the GS code by the "scaleFactor" variable. After the CgGs has run, we write the min/max posititons to the stream out buffer. These need to be read during the DecalGs so that we can apply the correct transformation to the Decal as well. 4. Acknowledgements The following projects have helped make this project possible: https://github.com/TsudaKageyu/minhook Used to override the D3D11 calls. https://github.com/DrNseven/D3D11-Wallhack Used this as reference to find the major numbers to offset into the contextvtable http://www.hulver.com/scoop/story/2006/2/18/125521/185 Used this to generate the function definitions for D3D11. <file_sep>/D3D11.cpp #if defined (_DEBUG) #define _CRT_SECURE_NO_WARNINGS #endif #include <stdio.h> #include <windows.h> #include <d3d11.h> #include "MinHook.h" #include "SharedInc.h" #include "CgGs.h" #include "DecalGs.h" // A release build crashes and I'm not entirely sure why. It's probably caused by the entry points using jmp statements #define SAFE_RELEASE(x) if (x != NULL) { x->Release(); x = NULL; } #if defined (_DEBUG) #define DEBUG_LOG_EN 0 #endif #if DEBUG_LOG_EN static FILE * debug; #define DEBUG(x) fprintf x #define DEBUGFLUSH fflush(debug) #else // DEBUG_LOG_EN #define DEBUG(x) #define DEBUGFLUSH #endif // DEBUG_LOG_EN static HINSTANCE gs_hDLL = 0; int (__stdcall * _O_D3D11CoreCreateDevice)(); extern "C" void __declspec(naked) __stdcall _I_D3D11CoreCreateDevice() { DEBUG((debug, "D3D11CoreCreateDevice\n")); __asm { jmp _O_D3D11CoreCreateDevice } } int (__stdcall * _O_D3D11CoreCreateLayeredDevice)(); extern "C" void __declspec(naked) __stdcall _I_D3D11CoreCreateLayeredDevice() { DEBUG((debug, "D3D11CoreCreateLayeredDevice\n")); __asm { jmp _O_D3D11CoreCreateLayeredDevice } } int (__stdcall * _O_D3D11CoreGetLayeredDeviceSize)(); extern "C" void __declspec(naked) __stdcall _I_D3D11CoreGetLayeredDeviceSize() { DEBUG((debug, "D3D11CoreGetLayeredDeviceSize\n")); __asm { jmp _O_D3D11CoreGetLayeredDeviceSize } } int (__stdcall * _O_D3D11CoreRegisterLayers)(); extern "C" void __declspec(naked) __stdcall _I_D3D11CoreRegisterLayers() { DEBUG((debug, "D3D11CoreRegisterLayers\n")); __asm { jmp _O_D3D11CoreRegisterLayers } } // ORIGINAL /* int (__stdcall * _O_D3D11CreateDevice)(); extern "C" void __declspec(naked) __stdcall _I_D3D11CreateDevice() { DEBUG((debug, "D3D11CreateDevice\n")); __asm { jmp _O_D3D11CreateDevice } } */ DWORD_PTR* pDeviceVTable = NULL; DWORD_PTR* pContextVTable = NULL; typedef void(__stdcall *D3D11DrawIndexedHook) (ID3D11DeviceContext* pContext, UINT IndexCount, UINT StartIndexLocation, INT BaseVertexLocation); D3D11DrawIndexedHook phookD3D11DrawIndexed = NULL; typedef void(__stdcall *D3D11SetPredicationHook) (ID3D11DeviceContext* pContext, ID3D11Predicate *pPredicate, BOOL PredicateValue); D3D11SetPredicationHook phookD3D11SetPredication = NULL; ID3D11GeometryShader* pCgGs = NULL; ID3D11GeometryShader* pDecalGs = NULL; ID3D11SamplerState* pBlackBorderSampler = NULL; ID3D11Buffer* pTexCoordsBuff = NULL; #if USE_D3D11_1 ID3D11UnorderedAccessView* pTexCoordsUav = NULL; #else ID3D11ShaderResourceView* pTexCoordsSrv = NULL; #endif BOOL frameHasCg = FALSE; void WINAPI hookD3D11SetPredication(ID3D11DeviceContext* pContext, ID3D11Predicate *pPredicate, BOOL PredicateValue) { // The app calls this at the start and end of every frame. So we'll use this to detect when a frame ends. // I don't think they would use it any other time. The app has no use for predication. DEBUG((debug, "hookD3D11SetPredication\n")); frameHasCg = FALSE; phookD3D11SetPredication(pContext, pPredicate, PredicateValue); DEBUGFLUSH; } void WINAPI hookD3D11DrawIndexed(ID3D11DeviceContext* pContext, UINT IndexCount, UINT StartIndexLocation, INT BaseVertexLocation) { //return; DEBUG((debug, "hookD3D11DrawIndexed\n")); ID3D11GeometryShader* pGs = NULL; ID3D11ShaderResourceView* pSrv = NULL; ID3D11Resource* pResource = NULL; D3D11_RESOURCE_DIMENSION resDim = D3D11_RESOURCE_DIMENSION_UNKNOWN; D3D11_TEXTURE2D_DESC texDesc; texDesc.Width = 0; static const int NumSamplers = 4; BOOL restoreGs = FALSE; BOOL swapSamplers = FALSE; ID3D11SamplerState* pOrigSampler[NumSamplers] = { NULL, NULL, NULL, NULL }; // The sampler slot used seems to change afer recalling the text ID3D11ShaderResourceView* pNoSrv = NULL; ID3D11Buffer* pNoBuffer = NULL; ID3D11BlendState* pBlendState = NULL; D3D11_BLEND_DESC blendDesc; UINT soOffset = 0; blendDesc.RenderTarget[0].BlendEnable = 0; #if USE_D3D11_1 ID3D11RenderTargetView* pRtv = NULL; ID3D11DepthStencilView* pDsv = NULL; #else BOOL restoreSo = FALSE; BOOL restoreGsSrv = FALSE; #endif pContext->GSGetShader(&pGs, NULL, NULL); pContext->PSGetShaderResources(0, 1, &pSrv); // Detect CG decal if (frameHasCg == TRUE) { pContext->OMGetBlendState(&pBlendState, NULL, NULL); if (pBlendState != NULL) { pBlendState->GetDesc(&blendDesc); // Detect the CG decal based on the slightly unusual blend state. // Other draw calls appear to keep the Src alpha rather than the dest if (blendDesc.RenderTarget[0].BlendEnable == 1 && blendDesc.RenderTarget[0].SrcBlendAlpha == D3D10_BLEND_ZERO && blendDesc.RenderTarget[0].DestBlendAlpha == D3D10_BLEND_ONE) { DEBUG((debug, "hookD3D11DrawIndexed Decal detected\n")); DEBUGFLUSH; // Swap in the replacement GS to adjust the vertex positions restoreGs = TRUE; pContext->GSSetShader(pDecalGs, NULL, NULL); // Swap in our replacement sampler. // After hiding and recalling text, the app will switch to a point sampler instead of a linear sampler // for some reason. This becomes a problem now that the CG is being shrunk down to the window size. // To fix this, swap in our linear sampler. swapSamplers = TRUE; #if USE_D3D11_1 // Add the texture coordinates UAV to the output merger stage. // I'm not going to bother unbinding the UAV after the draw call. pContext->OMGetRenderTargets(1, &pRtv, &pDsv); pContext->OMSetRenderTargetsAndUnorderedAccessViews(1, &pRtv, pDsv, 1, 1, &pTexCoordsUav, NULL); SAFE_RELEASE(pRtv); SAFE_RELEASE(pDsv); #else restoreGsSrv = TRUE; pContext->GSSetShaderResources(0, 1, &pTexCoordsSrv); #endif } } SAFE_RELEASE(pBlendState) } // Detect CG else if (pSrv != NULL && pGs == NULL && pCgGs != NULL && pDecalGs != NULL && pBlackBorderSampler #if USE_D3D11_1 && pTexCoordsUav #else && pTexCoordsBuff #endif ) { pSrv->GetResource(&pResource); if (pResource != NULL) { pResource->GetType(&resDim); if (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE2D) { static_cast<ID3D11Texture2D*>(pResource)->GetDesc(&texDesc); // Detect the 4:3 CG based on the W/H if (texDesc.Width == 1280 && texDesc.Height == 960) { DEBUG((debug, "hookD3D11DrawIndexed CG detected\n")); DEBUGFLUSH; frameHasCg = TRUE; // Swap in the replacement GS to adjust the texture coordinates restoreGs = TRUE; pContext->GSSetShader(pCgGs, NULL, NULL); // Swap in a sampler with a black border color. swapSamplers = TRUE; #if USE_D3D11_1 // Add the texture coordinates UAV to the output merger stage. // I'm not going to bother unbinding the UAV after the draw call. pContext->OMGetRenderTargets(1, &pRtv, &pDsv); pContext->OMSetRenderTargetsAndUnorderedAccessViews(1, &pRtv, pDsv, 1, 1, &pTexCoordsUav, NULL); SAFE_RELEASE(pRtv); SAFE_RELEASE(pDsv); #else restoreSo = TRUE; pContext->SOSetTargets(1, &pTexCoordsBuff, &soOffset); #endif } } SAFE_RELEASE(pResource) } SAFE_RELEASE(pSrv) } SAFE_RELEASE(pGs); if (swapSamplers) { pContext->PSGetSamplers(0, NumSamplers, &pOrigSampler[0]); for (UINT i = 0; i < NumSamplers; i++) { pContext->PSSetSamplers(i, 1, &pBlackBorderSampler); } } ///// phookD3D11DrawIndexed(pContext, IndexCount, StartIndexLocation, BaseVertexLocation); ///// if (restoreGs) { pContext->GSSetShader(NULL, NULL, NULL); } if (swapSamplers) { pContext->PSSetSamplers(0, NumSamplers, &pOrigSampler[0]); for (int i = 0; i < NumSamplers; i++) { SAFE_RELEASE(pOrigSampler[i]) } } #if USE_D3D11_1 == 0 if (restoreSo) { pContext->SOSetTargets(1, &pNoBuffer, NULL); } if (restoreGsSrv) { pContext->GSSetShaderResources(0, 1, &pNoSrv); } #endif DEBUGFLUSH; } /* typedef void(__stdcall *D3D11CreateTexture2D) (ID3D11Device* pDevice, const D3D11_TEXTURE2D_DESC *pDesc, const D3D11_SUBRESOURCE_DATA *pInitialData, ID3D11Texture2D **ppTexture2D); D3D11CreateTexture2D phookD3D11CreateTexture2D = NULL; void WINAPI hookD3D11CreateTexture2D(ID3D11Device* pDevice, const D3D11_TEXTURE2D_DESC *pDesc, const D3D11_SUBRESOURCE_DATA *pInitialData, ID3D11Texture2D **ppTexture2D) { phookD3D11CreateTexture2D(pDevice, pDesc, pInitialData, ppTexture2D); } */ extern "C" { // This function is called via function pointer which does not respect __declspec(naked). // To solve this we must make this a "normal" function which calls the real D3D11 DLL function // in the "normal" manner. We need access to the parameters anyway. typedef HRESULT(WINAPI *tD3D11CreateDevice)(_In_opt_ VOID* pAdapter, D3D_DRIVER_TYPE DriverType, HMODULE Software, UINT Flags, _In_opt_ const D3D_FEATURE_LEVEL* pFeatureLevels, UINT FeatureLevels, UINT SDKVERSION, _Out_opt_ ID3D11Device** ppDevice, _Out_opt_ D3D_FEATURE_LEVEL* pFeatureLevel, _Out_opt_ VOID** ppImmediateContext); tD3D11CreateDevice _O_D3D11CreateDevice; HRESULT WINAPI _I_D3D11CreateDevice( _In_opt_ VOID* pAdapter, D3D_DRIVER_TYPE DriverType, HMODULE Software, UINT Flags, _In_opt_ const D3D_FEATURE_LEVEL* pFeatureLevels, UINT FeatureLevels, UINT SDKVERSION, _Out_opt_ ID3D11Device** ppDevice, _Out_opt_ D3D_FEATURE_LEVEL* pFeatureLevel, _Out_opt_ VOID** ppImmediateContext) { MH_STATUS mhRet; HRESULT createDeviceHr; HRESULT hr; D3D11_SAMPLER_DESC samplerDesc; D3D11_BUFFER_DESC bufferDesc; // wait for debugger #if 0 static BOOL wait = TRUE; while (wait); #endif #if DEBUG_LOG_EN // The debug runtime gets angry about mismatched VS/GS/PS in/out semantics and removes the GS. // So we can't use the debug runtime. I hate Microsoft. //Flags &= ~(D3D11_CREATE_DEVICE_DEBUG); //Flags |= D3D11_CREATE_DEVICE_DEBUG; #endif DEBUG((debug, "D3D11CreateDevice\n")); #if USE_D3D11_1 D3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc; // The D3D version needs to upgraded to 11.1 so that we can access UAVs from GS. D3D_FEATURE_LEVEL retFl; D3D_FEATURE_LEVEL fl[2] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0 }; createDeviceHr = _O_D3D11CreateDevice(pAdapter, DriverType, Software, Flags, &fl[0], 2, SDKVERSION, ppDevice, &retFl, ppImmediateContext); if (pFeatureLevel != NULL) { *pFeatureLevel = retFl; } if (retFl != D3D_FEATURE_LEVEL_11_1) { DEBUG((debug, "Could not Create D3D11.1 Device\n")); } #else D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; createDeviceHr = _O_D3D11CreateDevice(pAdapter, DriverType, Software, Flags, pFeatureLevels, 2, SDKVERSION, ppDevice, pFeatureLevel, ppImmediateContext); #endif if (*ppImmediateContext != NULL && phookD3D11DrawIndexed == NULL #if USE_D3D11_1 && retFl == D3D_FEATURE_LEVEL_11_1 #endif ) { // Get the VTable and Hook DrawIndexed pContextVTable = (DWORD_PTR*)(*ppImmediateContext); pContextVTable = (DWORD_PTR*)pContextVTable[0]; mhRet = MH_CreateHook((DWORD_PTR*)pContextVTable[12], hookD3D11DrawIndexed, reinterpret_cast<void**>(&phookD3D11DrawIndexed)); if (mhRet != MH_OK) { DEBUG((debug, "Error. MH_CreateHook DrawIndexed Failed.\n")); } mhRet = MH_EnableHook((DWORD_PTR*)pContextVTable[12]); if (mhRet != MH_OK) { DEBUG((debug, "Error. MH_EnableHook DrawIndexed Failed.\n")); } mhRet = MH_CreateHook((DWORD_PTR*)pContextVTable[30], hookD3D11SetPredication, reinterpret_cast<void**>(&phookD3D11SetPredication)); if (mhRet != MH_OK) { DEBUG((debug, "Error. MH_CreateHook SetPredication Failed.\n")); } mhRet = MH_EnableHook((DWORD_PTR*)pContextVTable[30]); if (mhRet != MH_OK) { DEBUG((debug, "Error. MH_EnableHook SetPredication Failed.\n")); } // Create the Decrop GS now since we have the device pointer #if USE_D3D11_1 hr = (*ppDevice)->CreateGeometryShader(&g_CgGs[0], sizeof(g_CgGs), NULL, &pCgGs); #else D3D11_SO_DECLARATION_ENTRY pSoDecl[7] = { { 0, "SV_POSITION", 0, 0, 4, 0 }, { 0, "a", 0, 0, 4, 0 }, { 0, "b", 0, 0, 4, 0 }, { 0, "c", 0, 0, 4, 0 }, { 0, "d", 0, 0, 4, 0 }, { 0, "e", 0, 0, 4, 0 }, { 0, "f", 0, 0, 4, 0 }, }; hr = (*ppDevice)->CreateGeometryShaderWithStreamOutput(&g_CgGs[0], sizeof(g_CgGs), &pSoDecl[0], 7, NULL, 0, 0, NULL, &pCgGs); #endif if (hr != S_OK || pCgGs == NULL) { DEBUG((debug, "Error. CgGs compile failed.\n")); } hr = (*ppDevice)->CreateGeometryShader(&g_DecalGs[0], sizeof(g_DecalGs), NULL, &pDecalGs); if (hr != S_OK || pDecalGs == NULL) { DEBUG((debug, "Error. DecalGs compile failed.\n")); } samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_BORDER; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_BORDER; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_BORDER; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; samplerDesc.BorderColor[0] = 0.0f; samplerDesc.BorderColor[1] = 0.0f; samplerDesc.BorderColor[2] = 0.0f; samplerDesc.BorderColor[3] = 0.0f; samplerDesc.MinLOD = 0.0f; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; hr = (*ppDevice)->CreateSamplerState(&samplerDesc, &pBlackBorderSampler); if (hr != S_OK || pBlackBorderSampler == NULL) { DEBUG((debug, "Error. Black border color sampler create failed.\n")); } bufferDesc.ByteWidth = #if USE_D3D11_1 sizeof(float)* 256; #else sizeof(float)* 256; #endif bufferDesc.Usage = D3D11_USAGE_DEFAULT; bufferDesc.BindFlags = #if USE_D3D11_1 D3D11_BIND_UNORDERED_ACCESS; #else D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_STREAM_OUTPUT; #endif bufferDesc.CPUAccessFlags = 0; bufferDesc.MiscFlags = 0; bufferDesc.StructureByteStride = sizeof(float); hr = (*ppDevice)->CreateBuffer(&bufferDesc, NULL, &pTexCoordsBuff); if (hr != S_OK || pTexCoordsBuff == NULL) { DEBUG((debug, "Error. Tex Coords Buffer Create Failed.\n")); } #if USE_D3D11_1 uavDesc.Format = DXGI_FORMAT_R32_FLOAT; uavDesc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER; uavDesc.Buffer.FirstElement = 0; uavDesc.Buffer.NumElements = bufferDesc.ByteWidth / sizeof(float);; uavDesc.Buffer.Flags = 0; hr = (*ppDevice)->CreateUnorderedAccessView(pTexCoordsBuff, &uavDesc, &pTexCoordsUav); if (hr != S_OK || pTexCoordsUav == NULL) { DEBUG((debug, "Error. Tex Coords UAV Create Failed.\n")); } #else srvDesc.Format = DXGI_FORMAT_R32_FLOAT; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFER; srvDesc.Buffer.FirstElement = 0; srvDesc.Buffer.NumElements = bufferDesc.ByteWidth / sizeof(float); hr = (*ppDevice)->CreateShaderResourceView(pTexCoordsBuff, &srvDesc, &pTexCoordsSrv); if (hr != S_OK || pTexCoordsSrv == NULL) { DEBUG((debug, "Error. Tex Coords SRV Create Failed.\n")); } #endif } DEBUGFLUSH; return createDeviceHr; } } int (__stdcall * _O_D3D11CreateDeviceAndSwapChain)(); extern "C" void __declspec(naked) __stdcall _I_D3D11CreateDeviceAndSwapChain() { DEBUG((debug, "D3D11CreateDeviceAndSwapChain\n")); __asm { jmp _O_D3D11CreateDeviceAndSwapChain } } int (__stdcall * _O_D3DKMTCloseAdapter)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTCloseAdapter() { DEBUG((debug, "D3DKMTCloseAdapter\n")); __asm { jmp _O_D3DKMTCloseAdapter } } int (__stdcall * _O_D3DKMTCreateAllocation)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTCreateAllocation() { DEBUG((debug, "D3DKMTCreateAllocation\n")); __asm { jmp _O_D3DKMTCreateAllocation } } int (__stdcall * _O_D3DKMTCreateContext)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTCreateContext() { DEBUG((debug, "D3DKMTCreateContext\n")); __asm { jmp _O_D3DKMTCreateContext } } int (__stdcall * _O_D3DKMTCreateDevice)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTCreateDevice() { DEBUG((debug, "D3DKMTCreateDevice\n")); __asm { jmp _O_D3DKMTCreateDevice } } int (__stdcall * _O_D3DKMTCreateSynchronizationObject)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTCreateSynchronizationObject() { DEBUG((debug, "D3DKMTCreateSynchronizationObject\n")); __asm { jmp _O_D3DKMTCreateSynchronizationObject } } int (__stdcall * _O_D3DKMTDestroyAllocation)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTDestroyAllocation() { DEBUG((debug, "D3DKMTDestroyAllocation\n")); __asm { jmp _O_D3DKMTDestroyAllocation } } int (__stdcall * _O_D3DKMTDestroyContext)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTDestroyContext() { DEBUG((debug, "D3DKMTDestroyContext\n")); __asm { jmp _O_D3DKMTDestroyContext } } int (__stdcall * _O_D3DKMTDestroyDevice)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTDestroyDevice() { DEBUG((debug, "D3DKMTDestroyDevice\n")); __asm { jmp _O_D3DKMTDestroyDevice } } int (__stdcall * _O_D3DKMTDestroySynchronizationObject)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTDestroySynchronizationObject() { DEBUG((debug, "D3DKMTDestroySynchronizationObject\n")); __asm { jmp _O_D3DKMTDestroySynchronizationObject } } int (__stdcall * _O_D3DKMTEscape)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTEscape() { DEBUG((debug, "D3DKMTEscape\n")); __asm { jmp _O_D3DKMTEscape } } int (__stdcall * _O_D3DKMTGetContextSchedulingPriority)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTGetContextSchedulingPriority() { DEBUG((debug, "D3DKMTGetContextSchedulingPriority\n")); __asm { jmp _O_D3DKMTGetContextSchedulingPriority } } int (__stdcall * _O_D3DKMTGetDeviceState)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTGetDeviceState() { DEBUG((debug, "D3DKMTGetDeviceState\n")); __asm { jmp _O_D3DKMTGetDeviceState } } int (__stdcall * _O_D3DKMTGetDisplayModeList)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTGetDisplayModeList() { DEBUG((debug, "D3DKMTGetDisplayModeList\n")); __asm { jmp _O_D3DKMTGetDisplayModeList } } int (__stdcall * _O_D3DKMTGetMultisampleMethodList)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTGetMultisampleMethodList() { DEBUG((debug, "D3DKMTGetMultisampleMethodList\n")); __asm { jmp _O_D3DKMTGetMultisampleMethodList } } int (__stdcall * _O_D3DKMTGetRuntimeData)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTGetRuntimeData() { DEBUG((debug, "D3DKMTGetRuntimeData\n")); __asm { jmp _O_D3DKMTGetRuntimeData } } int (__stdcall * _O_D3DKMTGetSharedPrimaryHandle)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTGetSharedPrimaryHandle() { DEBUG((debug, "D3DKMTGetSharedPrimaryHandle\n")); __asm { jmp _O_D3DKMTGetSharedPrimaryHandle } } int (__stdcall * _O_D3DKMTLock)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTLock() { DEBUG((debug, "D3DKMTLock\n")); __asm { jmp _O_D3DKMTLock } } int (__stdcall * _O_D3DKMTOpenAdapterFromHdc)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTOpenAdapterFromHdc() { DEBUG((debug, "D3DKMTOpenAdapterFromHdc\n")); __asm { jmp _O_D3DKMTOpenAdapterFromHdc } } int (__stdcall * _O_D3DKMTOpenResource)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTOpenResource() { DEBUG((debug, "D3DKMTOpenResource\n")); __asm { jmp _O_D3DKMTOpenResource } } int (__stdcall * _O_D3DKMTPresent)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTPresent() { DEBUG((debug, "D3DKMTPresent\n")); __asm { jmp _O_D3DKMTPresent } } int (__stdcall * _O_D3DKMTQueryAdapterInfo)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTQueryAdapterInfo() { DEBUG((debug, "D3DKMTQueryAdapterInfo\n")); __asm { jmp _O_D3DKMTQueryAdapterInfo } } int (__stdcall * _O_D3DKMTQueryAllocationResidency)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTQueryAllocationResidency() { DEBUG((debug, "D3DKMTQueryAllocationResidency\n")); __asm { jmp _O_D3DKMTQueryAllocationResidency } } int (__stdcall * _O_D3DKMTQueryResourceInfo)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTQueryResourceInfo() { DEBUG((debug, "D3DKMTQueryResourceInfo\n")); __asm { jmp _O_D3DKMTQueryResourceInfo } } int (__stdcall * _O_D3DKMTRender)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTRender() { DEBUG((debug, "D3DKMTRender\n")); __asm { jmp _O_D3DKMTRender } } int (__stdcall * _O_D3DKMTSetAllocationPriority)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTSetAllocationPriority() { DEBUG((debug, "D3DKMTSetAllocationPriority\n")); __asm { jmp _O_D3DKMTSetAllocationPriority } } int (__stdcall * _O_D3DKMTSetContextSchedulingPriority)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTSetContextSchedulingPriority() { DEBUG((debug, "D3DKMTSetContextSchedulingPriority\n")); __asm { jmp _O_D3DKMTSetContextSchedulingPriority } } int (__stdcall * _O_D3DKMTSetDisplayMode)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTSetDisplayMode() { DEBUG((debug, "D3DKMTSetDisplayMode\n")); __asm { jmp _O_D3DKMTSetDisplayMode } } int (__stdcall * _O_D3DKMTSetDisplayPrivateDriverFormat)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTSetDisplayPrivateDriverFormat() { DEBUG((debug, "D3DKMTSetDisplayPrivateDriverFormat\n")); __asm { jmp _O_D3DKMTSetDisplayPrivateDriverFormat } } int (__stdcall * _O_D3DKMTSetGammaRamp)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTSetGammaRamp() { DEBUG((debug, "D3DKMTSetGammaRamp\n")); __asm { jmp _O_D3DKMTSetGammaRamp } } int (__stdcall * _O_D3DKMTSetVidPnSourceOwner)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTSetVidPnSourceOwner() { DEBUG((debug, "D3DKMTSetVidPnSourceOwner\n")); __asm { jmp _O_D3DKMTSetVidPnSourceOwner } } int (__stdcall * _O_D3DKMTSignalSynchronizationObject)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTSignalSynchronizationObject() { DEBUG((debug, "D3DKMTSignalSynchronizationObject\n")); __asm { jmp _O_D3DKMTSignalSynchronizationObject } } int (__stdcall * _O_D3DKMTUnlock)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTUnlock() { DEBUG((debug, "D3DKMTUnlock\n")); __asm { jmp _O_D3DKMTUnlock } } int (__stdcall * _O_D3DKMTWaitForSynchronizationObject)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTWaitForSynchronizationObject() { DEBUG((debug, "D3DKMTWaitForSynchronizationObject\n")); __asm { jmp _O_D3DKMTWaitForSynchronizationObject } } int (__stdcall * _O_D3DKMTWaitForVerticalBlankEvent)(); extern "C" void __declspec(naked) __stdcall _I_D3DKMTWaitForVerticalBlankEvent() { DEBUG((debug, "D3DKMTWaitForVerticalBlankEvent\n")); __asm { jmp _O_D3DKMTWaitForVerticalBlankEvent } } int (__stdcall * _O_D3DPerformance_BeginEvent)(); extern "C" void __declspec(naked) __stdcall _I_D3DPerformance_BeginEvent() { DEBUG((debug, "D3DPerformance_BeginEvent\n")); __asm { jmp _O_D3DPerformance_BeginEvent } } int (__stdcall * _O_D3DPerformance_EndEvent)(); extern "C" void __declspec(naked) __stdcall _I_D3DPerformance_EndEvent() { DEBUG((debug, "D3DPerformance_EndEvent\n")); __asm { jmp _O_D3DPerformance_EndEvent } } int (__stdcall * _O_D3DPerformance_GetStatus)(); extern "C" void __declspec(naked) __stdcall _I_D3DPerformance_GetStatus() { DEBUG((debug, "D3DPerformance_GetStatus\n")); __asm { jmp _O_D3DPerformance_GetStatus } } int (__stdcall * _O_D3DPerformance_SetMarker)(); extern "C" void __declspec(naked) __stdcall _I_D3DPerformance_SetMarker() { DEBUG((debug, "D3DPerformance_SetMarker\n")); __asm { jmp _O_D3DPerformance_SetMarker } } int (__stdcall * _O_EnableFeatureLevelUpgrade)(); extern "C" void __declspec(naked) __stdcall _I_EnableFeatureLevelUpgrade() { DEBUG((debug, "EnableFeatureLevelUpgrade\n")); __asm { jmp _O_EnableFeatureLevelUpgrade } } int (__stdcall * _O_OpenAdapter10)(); extern "C" void __declspec(naked) __stdcall _I_OpenAdapter10() { DEBUG((debug, "OpenAdapter10\n")); __asm { jmp _O_OpenAdapter10 } } int (__stdcall * _O_OpenAdapter10_2)(); extern "C" void __declspec(naked) __stdcall _I_OpenAdapter10_2() { DEBUG((debug, "OpenAdapter10_2\n")); __asm { jmp _O_OpenAdapter10_2 } } BOOL WINAPI DllMain(HINSTANCE hI, DWORD reason, LPVOID notUsed) { if (reason == DLL_PROCESS_ATTACH) { #if DEBUG_LOG_EN if(!debug) { char tempPath[MAX_PATH]; GetTempPath(sizeof(tempPath), tempPath); strcat_s(tempPath, "D3D11_DLL_SHIM_DEBUG.txt"); debug = fopen(tempPath, "w"); } #endif // DEBUG_LOG_EN DEBUG((debug, "DllMain\n")); char realDLL[MAX_PATH]; (void)GetSystemDirectory(realDLL, sizeof(realDLL) - 1); strcat_s(realDLL, MAX_PATH, "\\D3D11.dll"); gs_hDLL = LoadLibrary(realDLL); if (!gs_hDLL) return FALSE; _O_D3D11CoreCreateDevice = GetProcAddress(gs_hDLL, "D3D11CoreCreateDevice"); _O_D3D11CoreCreateLayeredDevice = GetProcAddress(gs_hDLL, "D3D11CoreCreateLayeredDevice"); _O_D3D11CoreGetLayeredDeviceSize = GetProcAddress(gs_hDLL, "D3D11CoreGetLayeredDeviceSize"); _O_D3D11CoreRegisterLayers = GetProcAddress(gs_hDLL, "D3D11CoreRegisterLayers"); _O_D3D11CreateDevice = (tD3D11CreateDevice)GetProcAddress(gs_hDLL, "D3D11CreateDevice"); _O_D3D11CreateDeviceAndSwapChain = GetProcAddress(gs_hDLL, "D3D11CreateDeviceAndSwapChain"); _O_D3DKMTCloseAdapter = GetProcAddress(gs_hDLL, "D3DKMTCloseAdapter"); _O_D3DKMTCreateAllocation = GetProcAddress(gs_hDLL, "D3DKMTCreateAllocation"); _O_D3DKMTCreateContext = GetProcAddress(gs_hDLL, "D3DKMTCreateContext"); _O_D3DKMTCreateDevice = GetProcAddress(gs_hDLL, "D3DKMTCreateDevice"); _O_D3DKMTCreateSynchronizationObject = GetProcAddress(gs_hDLL, "D3DKMTCreateSynchronizationObject"); _O_D3DKMTDestroyAllocation = GetProcAddress(gs_hDLL, "D3DKMTDestroyAllocation"); _O_D3DKMTDestroyContext = GetProcAddress(gs_hDLL, "D3DKMTDestroyContext"); _O_D3DKMTDestroyDevice = GetProcAddress(gs_hDLL, "D3DKMTDestroyDevice"); _O_D3DKMTDestroySynchronizationObject = GetProcAddress(gs_hDLL, "D3DKMTDestroySynchronizationObject"); _O_D3DKMTEscape = GetProcAddress(gs_hDLL, "D3DKMTEscape"); _O_D3DKMTGetContextSchedulingPriority = GetProcAddress(gs_hDLL, "D3DKMTGetContextSchedulingPriority"); _O_D3DKMTGetDeviceState = GetProcAddress(gs_hDLL, "D3DKMTGetDeviceState"); _O_D3DKMTGetDisplayModeList = GetProcAddress(gs_hDLL, "D3DKMTGetDisplayModeList"); _O_D3DKMTGetMultisampleMethodList = GetProcAddress(gs_hDLL, "D3DKMTGetMultisampleMethodList"); _O_D3DKMTGetRuntimeData = GetProcAddress(gs_hDLL, "D3DKMTGetRuntimeData"); _O_D3DKMTGetSharedPrimaryHandle = GetProcAddress(gs_hDLL, "D3DKMTGetSharedPrimaryHandle"); _O_D3DKMTLock = GetProcAddress(gs_hDLL, "D3DKMTLock"); _O_D3DKMTOpenAdapterFromHdc = GetProcAddress(gs_hDLL, "D3DKMTOpenAdapterFromHdc"); _O_D3DKMTOpenResource = GetProcAddress(gs_hDLL, "D3DKMTOpenResource"); _O_D3DKMTPresent = GetProcAddress(gs_hDLL, "D3DKMTPresent"); _O_D3DKMTQueryAdapterInfo = GetProcAddress(gs_hDLL, "D3DKMTQueryAdapterInfo"); _O_D3DKMTQueryAllocationResidency = GetProcAddress(gs_hDLL, "D3DKMTQueryAllocationResidency"); _O_D3DKMTQueryResourceInfo = GetProcAddress(gs_hDLL, "D3DKMTQueryResourceInfo"); _O_D3DKMTRender = GetProcAddress(gs_hDLL, "D3DKMTRender"); _O_D3DKMTSetAllocationPriority = GetProcAddress(gs_hDLL, "D3DKMTSetAllocationPriority"); _O_D3DKMTSetContextSchedulingPriority = GetProcAddress(gs_hDLL, "D3DKMTSetContextSchedulingPriority"); _O_D3DKMTSetDisplayMode = GetProcAddress(gs_hDLL, "D3DKMTSetDisplayMode"); _O_D3DKMTSetDisplayPrivateDriverFormat = GetProcAddress(gs_hDLL, "D3DKMTSetDisplayPrivateDriverFormat"); _O_D3DKMTSetGammaRamp = GetProcAddress(gs_hDLL, "D3DKMTSetGammaRamp"); _O_D3DKMTSetVidPnSourceOwner = GetProcAddress(gs_hDLL, "D3DKMTSetVidPnSourceOwner"); _O_D3DKMTSignalSynchronizationObject = GetProcAddress(gs_hDLL, "D3DKMTSignalSynchronizationObject"); _O_D3DKMTUnlock = GetProcAddress(gs_hDLL, "D3DKMTUnlock"); _O_D3DKMTWaitForSynchronizationObject = GetProcAddress(gs_hDLL, "D3DKMTWaitForSynchronizationObject"); _O_D3DKMTWaitForVerticalBlankEvent = GetProcAddress(gs_hDLL, "D3DKMTWaitForVerticalBlankEvent"); _O_D3DPerformance_BeginEvent = GetProcAddress(gs_hDLL, "D3DPerformance_BeginEvent"); _O_D3DPerformance_EndEvent = GetProcAddress(gs_hDLL, "D3DPerformance_EndEvent"); _O_D3DPerformance_GetStatus = GetProcAddress(gs_hDLL, "D3DPerformance_GetStatus"); _O_D3DPerformance_SetMarker = GetProcAddress(gs_hDLL, "D3DPerformance_SetMarker"); _O_EnableFeatureLevelUpgrade = GetProcAddress(gs_hDLL, "EnableFeatureLevelUpgrade"); _O_OpenAdapter10 = GetProcAddress(gs_hDLL, "OpenAdapter10"); _O_OpenAdapter10_2 = GetProcAddress(gs_hDLL, "OpenAdapter10_2"); MH_STATUS mhRet = MH_Initialize(); if (mhRet != MH_OK) { DEBUG((debug, "Error. MH_Initialize() Failed.\n")); } } else if (reason == DLL_PROCESS_DETACH) { MH_STATUS mhRet = MH_Uninitialize(); if (mhRet != MH_OK) { DEBUG((debug, "Error. MH_Uninitialize() Failed.\n")); } mhRet = MH_DisableHook((DWORD_PTR*)pContextVTable[12]); if (mhRet != MH_OK) { DEBUG((debug, "Error. MH_DisableHook DrawIndexed Failed.\n")); } mhRet = MH_DisableHook((DWORD_PTR*)pContextVTable[30]); if (mhRet != MH_OK) { DEBUG((debug, "Error. MH_DisableHook SetPredication Failed.\n")); } #if DEBUG_LOG_EN if(debug) fclose(debug); #endif // DEBUG_LOG_EN FreeLibrary(gs_hDLL); } return TRUE; }
f17833b4b8e1abce87164b90c042d05b819011f4
[ "C", "Text", "C++" ]
3
C
Iemnur/LBEE-Decropper
a16bf7d1a51127b4a89249affae67bb3f3737514
8b63aef4791ae7157573b2de588dee5a3416fc72
refs/heads/master
<repo_name>WISEPLAT/Scratch-3.9-on-Linux<file_sep>/README.md # Scratch-3.9-on-Linux Hello! This is repository for my students who use Linux for ther study in programming. This script allow to install Scratch 3.9 on Ubuntu 20.04 in one click :) How to use it to install Scratch on Ubuntu (Linux): 1) If you want to get for installing Scratch from official site: sudo apt install git git clone https://github.com/WISEPLAT/Scratch-3.9-on-Linux.git cd Scratch-3.9-on-Linux ./install_scratch_ok.sh 2) If you want to get for installing Scratch from Github site: sudo apt install git git clone https://github.com/WISEPLAT/Scratch-3.9-on-Linux.git cd Scratch-3.9-on-Linux ./install_scratch_ok_get_Scratch_from_Github.sh <file_sep>/install_scratch_ok_get_Scratch_from_Github.sh #!/bin/bash cd ~ sudo apt-get update mkdir ~/Scratch cd ~/Scratch wget "https://github.com/WISEPLAT/Scratch-3.9-on-Linux/blob/master/Scratch%20Desktop%20Setup%203.9.0.exe" sudo apt-get install -y p7zip-full 7z x Scratch\ Desktop\ Setup\ 3.9.0.exe cd \$PLUGINSDIR 7z x app-64.7z cd resources file app.asar electron.asar static/ cd ~ sudo apt install -y npm npm install electron --save-dev ls ~/node_modules/electron/dist cd ~/Scratch cp -r ~/node_modules/electron/dist scratch-desktop cd scratch-desktop cp -r ~/Scratch/\$PLUGINSDIR/resources/{app.asar,static} resources/ sudo ln -s electron scratch-desktop cd ~ sudo sh -c "echo '[Desktop Entry] Encoding=UTF-8 Version=1.0 Type=Application Exec=$PWD/Scratch/scratch-desktop/scratch-desktop Icon=$PWD/Scratch/\$PLUGINSDIR/resources/static/assets/b7853f557e4426412e64bb3da6531a99.svg Terminal=false Name=Scratch Comment= Programming system and content development tool Categories=Application;Education;Development;ComputerScience; MimeType=application/x-scratch-project ' > /usr/share/applications/scratch.desktop" cd ~/Scratch/scratch-desktop ./scratch-desktop
aee4066b745285f67bbe6d878f2cc0b59d418b17
[ "Markdown", "Shell" ]
2
Markdown
WISEPLAT/Scratch-3.9-on-Linux
35feee88831e8f904f789577a037199103f49722
be5960c04f8b2b1be3e7e9375222f5ad3e900b2b
refs/heads/master
<file_sep># 2021-06-29 Features: * Retries of internal requests * Add `includeTags` to input * Pagination * Linting and refactoring Bug fix: * Remove patterns from input as they are considered required # 2021-06-25 Features: * Added CHANGELOG * Update SDK to 1.2.1 * Added photos and username to reviews * Added currency and country selection Bug fix: * Random crash on search * Linting<file_sep>const ReviewQuery = `query ReviewListQuery($locationId: Int!, $offset: Int, $limit: Int, $filters: [FilterConditionInput!], $prefs: ReviewListPrefsInput, $initialPrefs: ReviewListPrefsInput, $filterCacheKey: String, $prefsCacheKey: String, $keywordVariant: String!, $needKeywords: Boolean = true) { cachedFilters: personalCache(key: $filterCacheKey) cachedPrefs: personalCache(key: $prefsCacheKey) locations(locationIds: [$locationId]) { locationId parentGeoId name placeType reviewSummary { rating count } keywords(variant: $keywordVariant) @include(if: $needKeywords) { keywords { keyword } } ... on LocationInformation { parentGeoId } ... on LocationInformation { parentGeoId } ... on LocationInformation { name currentUserOwnerStatus { isValid } } ... on LocationInformation { locationId currentUserOwnerStatus { isValid } } ... on LocationInformation { locationId parentGeoId accommodationCategory currentUserOwnerStatus { isValid } url } reviewListPage(page: {offset: $offset, limit: $limit}, filters: $filters, prefs: $prefs, initialPrefs: $initialPrefs, filterCacheKey: $filterCacheKey, prefsCacheKey: $prefsCacheKey) { totalCount preferredReviewIds reviews { ... on Review { id url location { locationId name } createdDate publishedDate provider { isLocalProvider } userProfile { id userId: id isMe isVerified displayName username avatar { id photoSizes { url width height } } hometown { locationId fallbackString location { locationId additionalNames { long } name } } contributionCounts { sumAllUgc helpfulVote } route { url } } } ... on Review { title language url } ... on Review { language translationType } ... on Review { roomTip } ... on Review { tripInfo { stayDate } location { placeType } } ... on Review { additionalRatings { rating ratingLabel } } ... on Review { tripInfo { tripType } } ... on Review { language translationType mgmtResponse { id language translationType } } ... on Review { text publishedDate username connectionToSubject language mgmtResponse { id text language publishedDate username connectionToSubject } } ... on Review { id locationId title text rating absoluteUrl mcid translationType mtProviderId photos { id statuses photoSizes { url width height } } userProfile { id displayName username } } ... on Review { mgmtResponse { id } provider { isLocalProvider } } ... on Review { translationType location { locationId parentGeoId } provider { isLocalProvider isToolsProvider } original { id url locationId userId language submissionDomain } } ... on Review { locationId mcid attribution } ... on Review { __typename locationId helpfulVotes photoIds route { url } socialStatistics { followCount isFollowing isLiked isReposted isSaved likeCount repostCount tripCount } status userId userProfile { id displayName isFollowing } location { __typename locationId additionalNames { normal long longOnlyParent longParentAbbreviated longOnlyParentAbbreviated longParentStateAbbreviated longOnlyParentStateAbbreviated geo abbreviated abbreviatedRaw abbreviatedStateTerritory abbreviatedStateTerritoryRaw } parent { locationId additionalNames { normal long longOnlyParent longParentAbbreviated longOnlyParentAbbreviated longParentStateAbbreviated longOnlyParentStateAbbreviated geo abbreviated abbreviatedRaw abbreviatedStateTerritory abbreviatedStateTerritoryRaw } } } } ... on Review { text language } ... on Review { locationId absoluteUrl mcid translationType mtProviderId originalLanguage rating } ... on Review { id locationId title labels rating absoluteUrl mcid translationType mtProviderId alertStatus } } } reviewAggregations { ratingCounts languageCounts alertStatusCount } } } `; const SearchQuery = `query TypeaheadQuery($request: Typeahead_RequestInput!) { Typeahead_autocomplete(request: $request) { resultsId partial results { __typename ...TypeAhead_LocationItemFields ...TypeAhead_UserProfileFields ...TypeAhead_QuerySuggestionFields ...TypeAhead_RescueResultFields ...TypeAhead_ListResultFields } } } fragment TypeAhead_LocationItemFields on Typeahead_LocationItem { documentId locationId details { ...TypeAheadLocationInformationFields } } fragment TypeAhead_UserProfileFields on Typeahead_UserProfileItem { documentId userId details { ...TypeAheadUserProfileFields } } fragment TypeAheadLocationInformationFields on LocationInformation { localizedName localizedAdditionalNames { longOnlyHierarchy } streetAddress { street1 } locationV2 { placeType names { longOnlyHierarchyTypeaheadV2 } vacationRentalsRoute { url } } url HOTELS_URL: hotelsUrl ATTRACTIONS_URL: attractionOverviewURL RESTAURANTS_URL: restaurantOverviewURL placeType latitude longitude isGeo thumbnail { photoSizeDynamic { maxWidth maxHeight urlTemplate } } } fragment TypeAheadUserProfileFields on MemberProfile { username displayName followerCount isVerified isFollowing avatar { photoSizeDynamic { maxWidth maxHeight urlTemplate } } route { url } } fragment TypeAhead_QuerySuggestionFields on Typeahead_QuerySuggestionItem { documentId text route { url } buCategory parentGeoDetails { names { longOnlyHierarchyTypeaheadV2 } } } fragment TypeAhead_RescueResultFields on Typeahead_RescueResultItem { documentId text } fragment TypeAhead_ListResultFields on Typeahead_ListResultItem { documentId locationId listResultType FORUMListURL { url } details { localizedName localizedAdditionalNames { longOnlyHierarchy } locationV2 { placeType names { longOnlyHierarchyTypeaheadV2 } vacationRentalsRoute { url } } HOTELListURL: hotelsUrl RESTAURANTListURL: restaurantOverviewURL ATTRACTIONListURL: attractionOverviewURL thumbnail { photoSizeDynamic { maxWidth maxHeight urlTemplate } } } } `; const PriceQuery = `query BusinessAdvantageQuery($locationId: Int!, $deviceType: BaAggregation_DeviceType, $trafficSource: BaAggregation_TrafficSource, $commerceCountryId: Int!, $servletName: String!, $hotelTravelInfo: BaAggregation_HotelTravelInfoInput, $withContactLinks: Boolean!) { locations(locationIds: [$locationId]) { locationId businessAdvantageData(deviceType: $deviceType, trafficSource: $trafficSource, commerceCountryId: $commerceCountryId, servletName: $servletName, hotelTravelInfo: $hotelTravelInfo) { specialOffer { headingForTeaser specialOfferId specialOfferType lightboxClickUrl } contactLinks @include(if: $withContactLinks) { contactLinkType linkUrl @encode } } } } `; module.exports = { // ReviewQuery, SearchQuery, // PriceQuery, };
608cd3cc613ac3d37aa4db0de5c3af5c45db1ed0
[ "Markdown", "JavaScript" ]
2
Markdown
christopherdoughty/tripadvisor-scraper
328ad2b5037ab8f77d858499947b9a8c575007dc
7a465dcf42c055289a4c783b9f0eee65e7a55ad0
refs/heads/master
<file_sep># Screenshotter ![Screenshotter Logo](http://www.skatanicstudios.co.uk/wp-content/uploads/2020/04/logo.jpg) #### Package for taking gameplay screenshots in the Unity Editor across all three pipeline types. Screenshotter is a simple Camera controller plug-in for Unity that is designed to make the process of gameplay screenshots fast, easy and flexible! It allows you to fly around your scene with a game-pad to line-up a shot and adjust a Depth of Field post-process on the camera without interacting with controls in the editor. **Features**: * Camera Controller using a Gamepad * Depth of Field Controls * One Click Screenshot Feature * Cross-Compatible with Built-In/URP/HDRP Renderers ## Installation **Walkthrough Video** [![Walkthrough Video](https://img.youtube.com/vi/frMOMNGxbN0/0.jpg)](https://www.youtube.com/watch?v=frMOMNGxbN0) Simply open the package manager in Unity, choose the (+) sign and choose "Add Package From Git URL" and enter the url https://github.com/neon8100/screenshotter.git Alternatively, download the Clone the project and import using the "Add Package From Disk" option. **Once the Package is Downloaded** right click in the hierarchy and choose "Screenshotter Camera". This will add a new Screenshotter Camera GameObject to scene and Screenshotter should detect your current render pipeline and adapt its settings/components accordingly. With your Gamepad active hit play. You should now be able to fly around your scene using the Screenshotter Camera. ## Controls The screenshotter camera is designed primarily to work with an Xbox controller, but it should detect and use any Unity Supported Gamepad. The system uses the Player Input package to map its controls and send messages to the system, so feel free to adjust/remap them. **Default Controls** *General Controls* - View/Back : Take Screenshot - Options/Start : Pause/Resume TimeScale - A: Change Mode - Y: Toggle Debug Text - L3 (Click Left Stick In): Toggle Speed - Right Trigger: Zoom In - Left Trigger: Zoom Out - Right Bumper: Camera Up - Left Bumper: Camera Down *Move Mode* - Left Stick - Move - Right Stick - Fly *DOF Mode* - Left Stick Vertical - Adjust Focal Point - Left Stick Horiztonal - Adjust Narrownes - Right Stick Vertical - Increase/Decrease Aperture ## TODO * Support for cycling through different "Image Effect" post-processes <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using UnityEngine.InputSystem; namespace SkatanicStudios { public class ScreenshotterMenu { static Camera camera; [MenuItem("GameObject/Screenshotter Camera", false, 10)] public static void CreateCamera() { GameObject screenshotterCamera = new GameObject("Screenshotter Camera", typeof(Screenshotter)); string[] path = AssetDatabase.FindAssets("ScreenshotterActions", null); camera = screenshotterCamera.GetComponent<Camera>(); PlayerInput input = screenshotterCamera.GetComponent<PlayerInput>(); input.actions = (InputActionAsset)AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(path[0]), typeof(InputActionAsset)); input.defaultControlScheme = "Gamepad"; input.neverAutoSwitchControlSchemes = true; input.camera = camera; #if UNITY_URP //We need to wait for the object to be added so we can enable post processing on this camera automatically EditorApplication.update += OnUpdate; } static void OnUpdate() { if (camera.GetComponent<UnityEngine.Rendering.Universal.UniversalAdditionalCameraData>() != null) { EditorApplication.update -= OnUpdate; UnityEngine.Rendering.Universal.UniversalAdditionalCameraData universalCameraData = camera.GetComponent<UnityEngine.Rendering.Universal.UniversalAdditionalCameraData>(); universalCameraData.renderPostProcessing = true; } #endif } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.Rendering; #if UNITY_EDITOR using UnityEditor; #endif #if UNITY_HDRP using UnityEngine.Rendering.HighDefinition; #elif UNITY_URP using UnityEngine.Rendering.Universal; #elif UNITY_BUILT_IN using UnityEngine.Rendering.PostProcessing; #endif namespace SkatanicStudios { [RequireComponent(typeof(Camera))] [RequireComponent(typeof(PlayerInput))] public class Screenshotter : MonoBehaviour { PlayerInput input; Camera camera; #if UNITY_HDRP || UNITY_URP Volume volume; DepthOfField depthOfField; #elif UNITY_BUILT_IN PostProcessLayer layer; PostProcessVolume volume; DepthOfField depthOfField; #endif public bool invertLook; public bool gameViewScreenshot = true; public Vector2Int screenShotResolution = new Vector2Int(1920, 1080); public Color debugTextColor = Color.yellow; public int debugFontSize = 30; float speed = 1f; float horizontal; float vertical; float height; float lookVertical; float lookHorizontal; float zoomIn; float zoomOut; bool showDebug = true; bool isDOFControl; float timeScale = 1; private void Awake() { camera = GetComponent<Camera>(); input = GetComponent<PlayerInput>(); //Make this the camera in focus camera.depth = float.MaxValue; #if UNITY_HDRP || UNITY_URP volume = gameObject.AddComponent<Volume>(); volume.priority = 100f; volume.profile = new VolumeProfile(); depthOfField = volume.profile.Add<DepthOfField>(true); #if UNITY_HDRP depthOfField.focusMode.Override(DepthOfFieldMode.Manual); #elif UNITY_URP depthOfField.mode.Override(DepthOfFieldMode.Bokeh); #endif #elif UNITY_BUILT_IN gameObject.layer = LayerMask.NameToLayer("PostProcessing"); layer = gameObject.AddComponent<PostProcessLayer>(); layer.volumeLayer.value = LayerMask.GetMask("PostProcessing"); volume = gameObject.AddComponent<PostProcessVolume>(); volume.priority = 100; volume.profile = new PostProcessProfile(); volume.isGlobal = true; camera.allowHDR = true; depthOfField = volume.profile.AddSettings<DepthOfField>(); #endif } public void OnMove(InputValue value) { horizontal = value.Get<Vector2>().x; vertical = value.Get<Vector2>().y; } public void OnLook(InputValue value) { lookHorizontal = value.Get<Vector2>().x; lookVertical = value.Get<Vector2>().y; } public void OnZoomIn(InputValue value) { zoomIn = value.Get<float>(); } public void OnZoomOut(InputValue value) { zoomOut = value.Get<float>(); } public void OnCameraUp(InputValue value) { height = value.Get<float>() * speed; } public void OnCameraDown(InputValue value) { height = value.Get<float>() * -speed; } public void OnToggleDebug(InputValue value) { if (value.Get<float>() == 1) { showDebug = !showDebug; } } public void OnToggleControls(InputValue value) { if (value.Get<float>() == 1) { isDOFControl = !isDOFControl; } } public void OnToggleSpeed(InputValue value) { if (value.Get<float>() == 1) { if (speed == 0.1f) { speed = 2; } else if (speed == 2) { speed = 1; } else if (speed == 1) { speed = 0.5f; } else if (speed == 0.5f) { speed = 0.1f; } } } public void OnScreenshot(InputValue value) { if (value.Get<float>() == 1) { TakeScreenshot(); } } public void OnPause(InputValue value) { if (value.Get<float>() == 1) { if (timeScale == 0) { timeScale = 1; } else { timeScale = 0; } Time.timeScale = timeScale; } } public void OnNext(InputValue value) { //TODO Profile Switching } public void OnPrevious(InputValue value) { //TODO Profile Switching } #if UNITY_HDRP float nearStart; float nearEnd; float farStart; float farEnd; #elif UNITY_URP || UNITY_BUILT_IN float focusDistance; float focalLength; float aperture; #endif private void Update() { #if UNITY_HDRP nearStart = depthOfField.nearFocusStart.GetValue<float>(); nearEnd = depthOfField.nearFocusEnd.GetValue<float>(); farStart = depthOfField.farFocusStart.GetValue<float>(); farEnd = depthOfField.farFocusEnd.GetValue<float>(); #elif UNITY_URP || UNITY_BUILT_IN focusDistance = depthOfField.focusDistance.GetValue<float>(); focalLength = depthOfField.focalLength.GetValue<float>(); aperture = depthOfField.aperture.GetValue<float>(); #endif if (isDOFControl) { if (Mathf.Abs(vertical) < 0.25f) { vertical = 0; } if (Mathf.Abs(horizontal) < 0.25f) { horizontal = 0; } if (Mathf.Abs(lookHorizontal) < 0.25f) { lookHorizontal = 0; } if (Mathf.Abs(lookVertical) < 0.25f) { lookVertical = 0; } #if UNITY_HDRP float nearFocusStart = vertical * speed; float nearFocusEnd = horizontal * speed; float farFocusStart = lookVertical * speed; float farFocusEnd = lookHorizontal * speed; nearStart += nearFocusStart; nearEnd += nearFocusEnd; farStart += farFocusStart; farEnd += farFocusEnd; if (nearStart > nearEnd) { nearEnd = nearStart; } if (farStart > farEnd) { farEnd = farStart; } if (farStart < 0) { farStart = 0; } if (nearStart < 0) { nearStart = 0; } if (farEnd < 0) { farEnd = 0; } if(nearEnd < 0) { nearEnd = 0; } depthOfField.nearFocusStart.Override(nearStart); depthOfField.nearFocusEnd.Override(nearEnd); depthOfField.farFocusStart.Override(farStart); depthOfField.farFocusEnd.Override(farEnd); #elif UNITY_URP || UNITY_BUILT_IN focusDistance += vertical * speed; focalLength += horizontal * speed; aperture += lookVertical * speed; if (focalLength < 0) { focalLength = 0; } if (focusDistance < 0) { focusDistance = 0; } if (aperture < 0.1f) { aperture = 0.1f; } depthOfField.focalLength.Override(focalLength); depthOfField.focusDistance.Override(focusDistance); depthOfField.aperture.Override(aperture); #endif } else { transform.position = Vector3.Lerp(transform.position, transform.position + (transform.forward * vertical) + (transform.right * horizontal) + (Vector3.up * height), speed); transform.Rotate(Vector3.up, lookHorizontal * speed); if (invertLook) { transform.Rotate(Vector3.right, lookVertical * speed); } else { transform.Rotate(Vector3.right, -lookVertical * speed); } transform.rotation = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, 0); } if (camera.fieldOfView > 0) { camera.fieldOfView -= zoomIn; } if (camera.fieldOfView < 100) { camera.fieldOfView += zoomOut; } } public int screenshotCount; public void TakeScreenshot() { #if UNITY_EDITOR string time = string.Format("{0}_{1}_{2}", System.DateTime.Now.Year, System.DateTime.Now.Month, System.DateTime.Now.Day); string name = string.Format("{0}_{1}_shot_{2}", time, Application.productName, screenshotCount).ToLower(); string fullpathname = EditorUtility.SaveFilePanel("Save Screenshot", "", name, "png"); TakeNewScreenshot(fullpathname); screenshotCount++; #endif } public void TakeNewScreenShot(string path, string filename) { string fname = string.Format("{0}/{1}.png", path, filename); TakeNewScreenshot(fname); } public void TakeNewScreenshot(string fullPath) { if (gameViewScreenshot) { ScreenCapture.CaptureScreenshot(fullPath); } else { if (camera == null) { camera = GetComponent<Camera>(); } RenderTexture rt = new RenderTexture(screenShotResolution.x, screenShotResolution.y, 24); camera.targetTexture = rt; Texture2D screenShot = new Texture2D(screenShotResolution.x, screenShotResolution.y, TextureFormat.RGBA32, false); camera.Render(); RenderTexture.active = rt; screenShot.ReadPixels(new Rect(0, 0, screenShotResolution.x, screenShotResolution.y), 0, 0); camera.targetTexture = null; RenderTexture.active = null; //added to avoid errors if (Application.isEditor) { DestroyImmediate(rt); } else { Destroy(rt); } byte[] bytes = screenShot.EncodeToPNG(); System.IO.File.WriteAllBytes(fullPath, bytes); } Debug.Log(string.Format("Took screenshot to: {0}", fullPath)); } private void OnGUI() { if (showDebug) { string label = ""; #if UNITY_HDRP label = string.Format("SCREENSHOTTER DEBUG (Y) \nMode {0} (A) \nSpeed {1} (L3)\n\nDEPTH OF FIELD Near = LS, Far = RS)\nNear Start:{2}\nNear End: {3}\nFar Start {4}\nFar End {5}\n\nTime Scale:{6}", (isDOFControl)? "DoF" : "Look", speed, nearStart, nearEnd, farStart, farEnd, Time.timeScale); #elif UNITY_URP || UNITY_BUILT_IN label = string.Format("SCREENSHOTTER DEBUG (Y) \nMode {0} (A) \nSpeed {1} (L3)\n\nDEPTH OF FIELD Focus Length/Distance = LS, Aperture = RS)\nFocal Distance: {3}\nFocal Narrowness:{2}\nApature {4}f\n\nTime Scale:{5}", (isDOFControl) ? "DoF" : "Look", speed, focalLength, focusDistance, aperture, Time.timeScale); #endif GUI.skin.label.fontSize = debugFontSize; GUI.contentColor = debugTextColor; GUI.Label(new Rect(20, 20, Screen.width, Screen.height), label); } } } } <file_sep># screenshotter Package for taking gameplay screenshots in the Unity Editor across all three pipeline types Push Command: -git subtree push --prefix Assets/Plugins/Screenshotter origin upm <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using UnityEngine.Rendering; namespace SkatanicStudios { [InitializeOnLoad] public class ScreenshotterPipelineType { const string DEFINE_HDRP = "UNITY_HDRP"; const string DEFINE_URP = "UNITY_URP"; const string DEFINE_BUILTIN = "UNITY_BUILT_IN"; public enum PipelineType { HighDefinition, Universal, BuiltIn, None } public static PipelineType GetPipelineType() { #if UNITY_2019_1_OR_NEWER if (GraphicsSettings.renderPipelineAsset != null) { // SRP var srpType = GraphicsSettings.renderPipelineAsset.GetType().ToString(); if (srpType.Contains("HDRenderPipelineAsset")) { return PipelineType.HighDefinition; } else if (srpType.Contains("UniversalRenderPipelineAsset") || srpType.Contains("LightweightRenderPipelineAsset")) { return PipelineType.Universal; } else return PipelineType.None; } #elif UNITY_2017_1_OR_NEWER if (GraphicsSettings.renderPipelineAsset != null) { // SRP not supported before 2019 return PipelineType.None; } #endif // no SRP return PipelineType.BuiltIn; } //Set the build defines static ScreenshotterPipelineType() { EditorApplication.update += SetPipelineType; } static void SetPipelineType() { PipelineType type = GetPipelineType(); var targetPlatform = EditorUserBuildSettings.selectedBuildTargetGroup; string defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetPlatform); bool isEmpty = false; if (string.IsNullOrEmpty(defines)) { isEmpty = true; } switch (GetPipelineType()) { case PipelineType.BuiltIn: Debug.Log("Screenshotter Set to Built In"); if (!defines.Contains(DEFINE_BUILTIN)) { defines += (isEmpty) ? DEFINE_BUILTIN : ";" + DEFINE_BUILTIN; } break; case PipelineType.HighDefinition: Debug.Log("Screenshotter Set to High Definition"); if (!defines.Contains(DEFINE_HDRP)) { defines += (isEmpty) ? DEFINE_HDRP : ";" + DEFINE_HDRP; } break; case PipelineType.Universal: Debug.Log("Screenshotter Set to Universal"); if (!defines.Contains(DEFINE_URP)) { defines += (isEmpty) ? DEFINE_URP : ";" + DEFINE_URP; } break; case PipelineType.None: Debug.LogError("No Pipeline Type is available! Screenshotter not supported in this version of Unity!"); break; } PlayerSettings.SetScriptingDefineSymbolsForGroup(targetPlatform, defines); EditorApplication.update -= SetPipelineType; } } }
3ab3d2e262049f884b8b8186804fdb58e9fcb678
[ "Markdown", "C#" ]
5
Markdown
eclipseanu/screenshotter
aeccca898ca1bcfe858ef7923b93cfacb399f91c
406ac55a48e7becedfe836c476a406d3b433e83c
refs/heads/main
<repo_name>cricol-marina/task-manager-core<file_sep>/src/main/java/com/stefanini/taskmanager/messagesender/MessageReceiver.java package com.stefanini.taskmanager.messagesender; public interface MessageReceiver { /** * This method is used print received message * @param message */ void receive(Message message); String getAddress(); } <file_sep>/src/main/java/com/stefanini/taskmanager/messagesender/Message.java package com.stefanini.taskmanager.messagesender; public class Message { private String text; private String address; public Message() {} public Message (String text, String addres) { this.text = text; this.address = addres; } public void setAddress(String address) { this.address = address; } public String getAddress() { return address; } public String getText() { return text; } } <file_sep>/src/main/java/com/stefanini/taskmanager/messagesender/MessageCreatorImpl.java package com.stefanini.taskmanager.messagesender; import java.lang.reflect.Field; import com.stefanini.taskmanager.annotations.Email; import com.stefanini.taskmanager.annotations.EmailField; public class MessageCreatorImpl implements MessageCreator{ public String createMessage(Object object) throws IllegalArgumentException, IllegalAccessException { // String message = object.getClass().getAnnotation(Email.class).emailText(); // for (Field field : object.getClass().getDeclaredFields()) { // field.setAccessible(true); // if (field.isAnnotationPresent(EmailField.class)) { // message = message.replaceAll(field.getAnnotation(EmailField.class).fieldName(),String.valueOf(field.get(object))); // } // } return ""; } } <file_sep>/src/main/java/com/stefanini/taskmanager/exception/AddTaskException.java package com.stefanini.taskmanager.exception; public class AddTaskException extends Exception{ public AddTaskException(String message) { super(message); } } <file_sep>/src/main/java/com/stefanini/taskmanager/dto/UserDTO.java package com.stefanini.taskmanager.dto; import com.stefanini.taskmanager.annotations.Email; import com.stefanini.taskmanager.annotations.EmailField; @Email(emailText = "User {firstName} / {lastName} identified by username {userName} has been created!") public class UserDTO { @EmailField(fieldName = "firstName") private String firstName; @EmailField(fieldName = "lastName") private String lastName; @EmailField(fieldName = "userName") private String username; public UserDTO() {} public UserDTO(String firstName, String lastName, String username) { this.firstName = firstName; this.lastName = lastName; this.username = username; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override public String toString() { return "User {" + "username = ' " + username + '\'' + ",firstName = " + firstName + ",lastName=' " + lastName+ '\'' + '}'; } } <file_sep>/src/main/java/com/stefanini/taskmanager/annotations/Email.java package com.stefanini.taskmanager.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(value = ElementType.TYPE) @Retention (value = RetentionPolicy.RUNTIME) public @interface Email { String emailText(); } <file_sep>/src/main/java/com/stefanini/taskmanager/messagesender/MessageCreator.java package com.stefanini.taskmanager.messagesender; public interface MessageCreator { /** * This method is used to create message template * @param object * @return message * @throws IllegalArgumentException * @throws IllegalAccessException * @throws NoSuchFieldException * @throws SecurityException * @return message */ String createMessage(Object object) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException; } <file_sep>/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>taskmanager</groupId> <artifactId>taskmanager-core</artifactId> <version>0.0.3-SNAPSHOT</version> <packaging>jar</packaging> <name>DAO</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.24</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.14.1</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.4.31.Final</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.8.2</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.9</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>2.5.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.3.2</version> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>3.11.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>3.2.0</version> <configuration> <show>private</show> <nohelp>true</nohelp> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>aspectj-maven-plugin</artifactId> <version>1.7</version> <configuration> <complianceLevel>1.8</complianceLevel> <source>1.8</source> <target>1.8</target> <showWeaveInfo>true</showWeaveInfo> <verbose>true</verbose> <Xlint>ignore</Xlint> <encoding>UTF-8 </encoding> </configuration> <executions> <execution> <goals> <!-- use this goal to weave all your main classes --> <goal>compile</goal> <!-- use this goal to weave all your test classes --> <goal>test-compile</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project><file_sep>/README.md # task-manager-core-<file_sep>/src/main/java/com/stefanini/taskmanager/dto/TaskDTO.java package com.stefanini.taskmanager.dto; import com.stefanini.taskmanager.annotations.Email; import com.stefanini.taskmanager.annotations.EmailField; import com.stefanini.taskmanager.domain.User; @Email(emailText = "Task {taskTitle} {taskDescription} has been assigned to {username}") public class TaskDTO { @EmailField(fieldName = "username") private String username; @EmailField(fieldName = "taskTitle") private String title; @EmailField(fieldName = "taskDescription") private String description; public TaskDTO() {} public TaskDTO(String username, String title, String description) { this.username = username; this.title = title; this.description = description; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { return "TaskDTO [username=" + username + ", title=" + title + ", description=" + description + "]"; } } <file_sep>/src/main/java/main.java import com.stefanini.taskmanager.dao.factory.AbstractFactoryUser; import com.stefanini.taskmanager.dao.factory.impl.UserDAOFactoryHibernate; import com.stefanini.taskmanager.service.UserService; import com.stefanini.taskmanager.service.impl.UserServiceImpl; public class main { public static void main(String[] args) { // TODO Auto-generated method stub AbstractFactoryUser daoFactory = new UserDAOFactoryHibernate(); UserService userService = new UserServiceImpl(daoFactory); userService.showAllUsers(); } } <file_sep>/src/test/java/com/stefanini/taskmanager/test/service/TestTaskService.java package com.stefanini.taskmanager.test.service; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.verify; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import com.stefanini.taskmanager.dao.TasksDAO; import com.stefanini.taskmanager.dao.UserDAO; import com.stefanini.taskmanager.domain.Task; import com.stefanini.taskmanager.domain.User; import com.stefanini.taskmanager.dto.TaskDTO; import com.stefanini.taskmanager.exception.AddTaskException; import com.stefanini.taskmanager.service.impl.TasksServiceImpl; @RunWith(MockitoJUnitRunner.class) public class TestTaskService { @InjectMocks private TasksServiceImpl taskService = new TasksServiceImpl(); @Mock TasksDAO taskDAO; @Mock UserDAO userDAO; @Before public void initTest() { MockitoAnnotations.initMocks(this); } @Test public void testTaskService_addTask_Success() throws AddTaskException { TaskDTO taskDTO = new TaskDTO("minulea", "task_title", "task_description"); User user = new User("Marina", "Cricol", "minulea"); Mockito.when(userDAO.getUserByUsername("minulea")).thenReturn(user); taskDTO = taskService.addTask(taskDTO); assertEquals("task_title", taskDTO.getTitle()); assertEquals("task_description", taskDTO.getDescription()); assertEquals("minulea", taskDTO.getUsername()); } @Test public void testTaskService_ShowTaskByUser_Success() { List<Task> taskList = new ArrayList<Task>(); Mockito.when(taskDAO.getTasksByUser("searcher")).thenReturn(taskList); taskService.showTaskByUser("searcher"); verify(taskDAO).getTasksByUser("searcher"); } @Test public void testTaskService_GetTaskList_Success() { List<Task> taskList = new ArrayList<Task>(); Task task = new Task(new User("Pavel", "Cricol", "searcher"), "tt", "td"); taskList.add(task); Mockito.when(taskDAO.getTaskList()).thenReturn(taskList); List<TaskDTO> taskListDTO = taskService.getTaskList(); assertEquals(taskListDTO.get(0).getTitle(), taskList.get(0).getTitle()); assertEquals(taskListDTO.get(0).getDescription(), taskList.get(0).getDescription()); assertEquals(taskListDTO.get(0).getUsername(), taskList.get(0).getUser().getUsername()); } } <file_sep>/src/main/java/com/stefanini/taskmanager/dao/factory/impl/TaskDAOFactoryHibernate.java package com.stefanini.taskmanager.dao.factory.impl; import com.stefanini.taskmanager.dao.TasksDAO; import com.stefanini.taskmanager.dao.factory.AbstractFactoryTask; import com.stefanini.taskmanager.dao.hibernate.TaskDAOHibernate; public class TaskDAOFactoryHibernate implements AbstractFactoryTask{ public TasksDAO getDAO() { return TaskDAOHibernate.getInstance(); } } <file_sep>/src/test/java/com/stefanini/taskmanager/test/service/TestUserService.java package com.stefanini.taskmanager.test.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; import java.sql.SQLIntegrityConstraintViolationException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import com.stefanini.taskmanager.dao.UserDAO; import com.stefanini.taskmanager.domain.User; import com.stefanini.taskmanager.dto.UserDTO; import com.stefanini.taskmanager.exception.CreateUserException; import com.stefanini.taskmanager.service.impl.UserServiceImpl; import com.stefanini.taskmanager.util.MapperEntityToDTO; @RunWith(MockitoJUnitRunner.class) public class TestUserService { @InjectMocks private UserServiceImpl userService = new UserServiceImpl(); @Mock UserDAO userDAO ; @Before public void initTest() { MockitoAnnotations.initMocks(this); } @Test public void testUserService_createUser_CreationSuccess() throws CreateUserException, SQLIntegrityConstraintViolationException{ UserDTO userDTO = new UserDTO(); userDTO.setFirstName("FirstName"); userDTO.setLastName("LastName"); userDTO.setUsername("username"); userDTO = userService.createUser(userDTO); verify(userDAO).createUser(any(User.class)); assertEquals("FirstName", userDTO.getFirstName()); } @Test(expected = CreateUserException.class) public void testUserService_createUser_CreationException() throws CreateUserException, SQLIntegrityConstraintViolationException { UserDTO userDTO = new UserDTO(); doThrow(SQLIntegrityConstraintViolationException.class) .when(userDAO) .createUser(any(User.class)); userService.createUser(userDTO); } @Test public void testUserService_getUserByUsername_Succes() { UserDTO userDTO = new UserDTO("Marina", "Cricol", "mina"); User user = MapperEntityToDTO.mapDtoToEntity(userDTO); Mockito.when(userDAO.getUserByUsername("mina")).thenReturn(user); userDTO = userService.getUserByUsername(userDTO.getUsername()); verify(userDAO).getUserByUsername(user.getUsername()); assertEquals(userDTO.getUsername(), (userDAO.getUserByUsername(userDTO.getUsername())).getUsername()); } @Test public void testUserService_showAllUsers_Success() { userService.showAllUsers(); verify(userDAO).getUserList(); } }
efe72d044c46373628cc3ccaf4e2141d7e8c2960
[ "Markdown", "Java", "Maven POM" ]
14
Java
cricol-marina/task-manager-core
b4e13f733b9f4e9e8502cb720da88d899ea3842f
07846dde3943a0dd6d530cdfe400ebbbfe65f737
refs/heads/master
<file_sep>class Customer: ''' This program devloped by <NAME>''' bankname = "SOUMYA BANK" def __init__(self,name,balance=0.0): self.name = name self.balance = balance def deposite(self,amount): self.balance = self.balance+amount print("After deposite the amount is:",self.balance) def withdraw(self,amount): if amount>self.balance: print("Insufficient Funds") else: self.balance = self.balance-amount print("After withdraw balance is:",self.balance) print("Welcome to",Customer.bankname) name = input("Enter your name:") print("Thank you Mr.",name) c = Customer(name) while True: print("d-deposite\nw-withdrawl\ne-Exit") option = input("Chose your option from above:") if option.lower()=="d": amount = float(input("Enter amount to deposite:")) c.deposite(amount) elif option.lower()=="w": amount = float(input("Enter amount to withdrawl:")) c.withdraw(amount) elif option.lower()=="e" print("Thanks for Banking with us") else: print("You have chosen Invalid option...Plz chose valid option
6a48019e088a221534f8d9bc1b254c31022b2faf
[ "Python" ]
1
Python
soumya4073/24th-Jun-devops
e54cc788da5886f85cbc56273d811e498ff699a2
af19e7b568ea1038e46a2a7c3d447d20f782a707
refs/heads/master
<file_sep>package robin.example.com.sudoku; import android.app.Activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class Grille extends AppCompatActivity { Dessin dessin; Activity context; int grille; int level; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_grille); context = this; Bundle bundle = context.getIntent().getExtras(); grille = bundle.getInt("grille"); level = bundle.getInt("niveau"); dessin = (Dessin) findViewById(R.id.grille); int file; if(level ==1) file = R.raw.premier; else if(level == 2) file = R.raw.deuxieme; else file = R.raw.troisieme; InputStream inputStream = this.getResources().openRawResource(file); BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream)); if (inputStream != null) { for (int i = 0; i <= grille; i++) { try { dessin.grille = buffer.readLine(); } catch (IOException e) { e.printStackTrace(); } } } } } <file_sep>package robin.example.com.sudoku; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; public class AffichageChoixGrille extends AppCompatActivity{ Activity context; ListView listGrille; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_affichage_choix_grille); context = this; final Bundle bundle = context.getIntent().getExtras(); this.setTitle("Sudoku Niveau "+bundle.getInt("niveau")); ArrayList<vgrille> items = new ArrayList<vgrille>(); for(int i=1; i <= 100; i++){ items.add(new vgrille((double) bundle.getInt("niveau"), i)); } listGrille = findViewById(R.id.listGrille); MyAdapter adapter = new MyAdapter(this, items); listGrille.setAdapter(adapter); listGrille.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, final int position, long id) { final vgrille item = (vgrille) parent.getAdapter().getItem(position); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("Choix Niveau"); builder.setMessage(item.level+"---->"+item.done+"%"); builder.setPositiveButton("Continuez",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { Intent intent = new Intent(context, Grille.class); intent.putExtra("niveau", bundle.getInt("niveau")); intent.putExtra("grille", position); context.startActivity(intent); } }); builder.show(); } }); } }
3e3bb4dec5e05205bdf7a0f5c73a5dcbb10621b5
[ "Java" ]
2
Java
RobiNoob/Sudoku_Cesi
3242e441465d3eab79051e40eb7b2ab218bdd6d0
e3a8ff3f5f70b7e735fd8d74736a8eeaaad96d8a
refs/heads/master
<repo_name>Ewertonn/SITA2<file_sep>/registro/migrations/0006_auto_20180604_2137.py # Generated by Django 2.0.5 on 2018-06-05 00:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('registro', '0005_auto_20180527_1057'), ] operations = [ migrations.CreateModel( name='Reserva', fields=[ ('Reserva_id', models.AutoField(primary_key=True, serialize=False)), ], ), migrations.RemoveField( model_name='motorista', name='Motorista_idade', ), migrations.RemoveField( model_name='motorista', name='Motorista_sexo', ), migrations.RemoveField( model_name='usuario', name='Usuario_idade', ), migrations.RemoveField( model_name='usuario', name='Usuario_sexo', ), migrations.AddField( model_name='rota', name='Rota_data', field=models.DateField(null=True), ), migrations.AddField( model_name='rota', name='Rota_semanal', field=models.BooleanField(default=True), ), migrations.AddField( model_name='rota', name='Rota_veiculo', field=models.ManyToManyField(blank=True, to='registro.Veiculo'), ), migrations.AddField( model_name='usuario', name='Usuario_email', field=models.EmailField(max_length=254, null=True), ), migrations.AddField( model_name='veiculo', name='Veiculo_cor', field=models.CharField(max_length=20, null=True), ), migrations.AddField( model_name='veiculo', name='Veiculo_motorista', field=models.ManyToManyField(blank=True, to='registro.Motorista'), ), migrations.AddField( model_name='veiculo', name='Veiculo_placa', field=models.CharField(max_length=7, null=True), ), migrations.AlterField( model_name='motorista', name='Motorista_senha', field=models.CharField(max_length=100), ), migrations.AlterField( model_name='motorista', name='Motorista_veiculo', field=models.ManyToManyField(blank=True, to='registro.Veiculo'), ), migrations.AlterField( model_name='rota', name='Rota_horario', field=models.TimeField(), ), migrations.AlterField( model_name='veiculo', name='Veiculo_rota', field=models.ManyToManyField(blank=True, to='registro.Rota'), ), migrations.AddField( model_name='reserva', name='Reserva_motorista', field=models.ManyToManyField(to='registro.Motorista'), ), migrations.AddField( model_name='reserva', name='Reserva_rota', field=models.ManyToManyField(to='registro.Rota'), ), migrations.AddField( model_name='reserva', name='Reserva_usuario', field=models.ManyToManyField(to='registro.Usuario'), ), migrations.AddField( model_name='reserva', name='Reserva_veiculo', field=models.ManyToManyField(to='registro.Veiculo'), ), migrations.AddField( model_name='usuario', name='Usuario_reserva', field=models.ManyToManyField(to='registro.Reserva'), ), ] <file_sep>/registro/forms.py from .models import Usuario, Motorista, Reserva, Rota, Veiculo from django import forms from django.contrib.auth.models import User from django.forms import ModelForm class UserModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UserModelForm, self).__init__(*args, **kwargs) self.fields['email'].required = True self.fields['first_name'].required = True self.fields['last_name'].required = True class Meta: model = User fields = ['first_name', 'last_name', 'username', 'password', 'email'] help_texts = {'username' : ''} def save(self,commit=True): user = super(UserModelForm,self).save(commit=False) user.set_password(self.cleaned_data['password']) if commit: user.save() return user class usuarioformulario(forms.ModelForm): #Usuario_senha = forms.CharField(widget=forms.PasswordInput) class Meta: model = Usuario fields = ['Usuario_contato'] #'Usuario_contato','Usuario_senha','Usuario_email','Usuario_imagem', Usuario_contato] class motoristaformulario(forms.ModelForm): #Motorista_senha = forms.CharField(widget=forms.PasswordInput) class Meta: model = Motorista fields = ['Motorista_contato']#'Motorista_contato','Motorista_senha','Motorista_nome','Motorista_imagem'] class reservaformulario(forms.ModelForm): class Meta: model = Reserva fields = ['Reserva_rota'] class rotaformulario(forms.ModelForm): class Meta: model = Rota fields = ['Rota_id','Rota_pontopartida','Rota_pontochegada', 'Rota_localpartida', 'Rota_horario', 'Rota_data', 'Rota_veiculo', 'valor'] class veiculoformulario(forms.ModelForm): class Meta: model = Veiculo fields = ['Veiculo_placa','Veiculo_modelo','Veiculo_cor']<file_sep>/registro/admin.py from django.contrib import admin from registro.models import Usuario from registro.models import Motorista from registro.models import Veiculo from registro.models import Rota from registro.models import Reserva class UsuarioAdmin(admin.ModelAdmin): model = Usuario list_display = ['user'] #list_display = ['Usuario_nome','Usuario_contato'] search_fields = ['user'] #search_fields = ['Usuario_nome'] save_on_top = True admin.site.register(Usuario, UsuarioAdmin) class MotoristaAdmin(admin.ModelAdmin): model = Motorista list_display = ['user'] #list_display = ['Motorista_nome','Motorista_contato'] search_fields = ['user'] #search_fields = ['Motorista_nome'] save_on_top = True admin.site.register(Motorista, MotoristaAdmin) class VeiculoAdmin(admin.ModelAdmin): model = Veiculo list_display = ['Veiculo_modelo','Veiculo_placa'] search_fields = ['Veiculo_placa'] save_on_top = True admin.site.register(Veiculo, VeiculoAdmin) class RotaAdmin(admin.ModelAdmin): model = Rota list_display = ['Rota_pontopartida','Rota_pontochegada','Rota_horario'] search_fields = ['Rota_pontopartida'] save_on_top = True admin.site.register(Rota, RotaAdmin) class ReservaAdmin(admin.ModelAdmin): model = Reserva list_display = ['Reserva_id'] search_fields = ['Reserva_id'] save_on_top = True admin.site.register(Reserva, ReservaAdmin)<file_sep>/registro/migrations/0007_auto_20180817_0846.py # Generated by Django 2.0.4 on 2018-08-17 11:46 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('registro', '0006_auto_20180604_2137'), ] operations = [ migrations.RemoveField( model_name='motorista', name='Motorista_contato', ), migrations.RemoveField( model_name='motorista', name='Motorista_nome', ), migrations.RemoveField( model_name='motorista', name='Motorista_senha', ), migrations.RemoveField( model_name='usuario', name='Usuario_contato', ), migrations.RemoveField( model_name='usuario', name='Usuario_email', ), migrations.RemoveField( model_name='usuario', name='Usuario_nome', ), migrations.RemoveField( model_name='usuario', name='Usuario_senha', ), migrations.AddField( model_name='motorista', name='user', field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='usuario', name='user', field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ] <file_sep>/registro/migrations/0008_auto_20180817_0921.py # Generated by Django 2.0.4 on 2018-08-17 12:21 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('registro', '0007_auto_20180817_0846'), ] operations = [ migrations.AddField( model_name='motorista', name='Motorista_contato', field=models.CharField(max_length=15, null=True), ), migrations.AddField( model_name='usuario', name='Usuario_contato', field=models.CharField(max_length=15, null=True), ), ] <file_sep>/registro/urls.py from django.urls import path from . import views urlpatterns = [ path('home', views.home, name='home'), path('home2', views.home2, name='home2'), path('home3', views.home3, name='home3'), path('login', views.dologin, name = 'dologin'), path('telamotorista', views.telamotorista, name ='telamotorista'), path('telausuario', views.reservaformulario.as_view()), path('motoristaregistro', views.motoristaformulario.as_view()), path('usuarioregistro', views.usuarioformulario.as_view()), path('autenticacao', views.entraar), path('logout', views.dologout), path('oi', views.criar_user), path('deletar_rota/<int:id>', views.deletar_rota, name='deletar_rota'), #path('usuarioformulario', views.entrar), #path('cadastrar/', views.cadastrar_usuario), ]<file_sep>/registro/migrations/0017_auto_20181117_2157.py # Generated by Django 2.0.4 on 2018-11-18 00:57 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('registro', '0016_merge_20181117_2137'), ] operations = [ migrations.RemoveField( model_name='reserva', name='Reserva_motorista', ), migrations.RemoveField( model_name='reserva', name='Reserva_veiculo', ), migrations.AlterField( model_name='rota', name='Motorista', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ] <file_sep>/registro/migrations/0014_auto_20181113_1746.py # Generated by Django 2.1.3 on 2018-11-13 20:46 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('registro', '0013_auto_20181107_2001'), ] operations = [ migrations.RemoveField( model_name='motorista', name='Motorista_veiculo', ), migrations.RemoveField( model_name='veiculo', name='Veiculo_motorista', ), migrations.AddField( model_name='veiculo', name='Motorista', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ] <file_sep>/registro/migrations/0003_auto_20180526_0912.py # Generated by Django 2.0.5 on 2018-05-26 12:12 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('registro', '0002_auto_20180525_2016'), ] operations = [ migrations.RemoveField( model_name='rota', name='Rota_motorista', ), migrations.RemoveField( model_name='rota', name='Rota_veiculo', ), ] <file_sep>/registro/migrations/0016_merge_20181117_2137.py # Generated by Django 2.0.4 on 2018-11-18 00:37 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('registro', '0015_auto_20181114_0736'), ('registro', '0014_auto_20181112_1655'), ] operations = [ ] <file_sep>/registro/migrations/0021_auto_20181121_0748.py # Generated by Django 2.0.7 on 2018-11-21 10:48 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('registro', '0020_auto_20181120_0835'), ] operations = [ migrations.RemoveField( model_name='veiculo', name='Veiculo_rota', ), migrations.RemoveField( model_name='rota', name='Rota_veiculo', ), migrations.AddField( model_name='rota', name='Rota_veiculo', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='registro.Veiculo'), ), ] <file_sep>/registro/migrations/0010_rota_valor.py # Generated by Django 2.1.3 on 2018-11-01 22:42 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('registro', '0009_auto_20181101_1939'), ] operations = [ migrations.AddField( model_name='rota', name='valor', field=models.FloatField(null=True), ), ] <file_sep>/registro/migrations/0020_auto_20181120_0835.py # Generated by Django 2.1.3 on 2018-11-20 11:35 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('registro', '0019_auto_20181120_0832'), ] operations = [ migrations.AlterField( model_name='usuario', name='Usuario_contato', field=models.CharField(max_length=15, null=True, validators=[django.core.validators.RegexValidator('^[0-9]*$', 'Apenas números.')]), ), ] <file_sep>/registro/models.py from django.db import models from django.contrib.auth.models import User from django.core.validators import MinLengthValidator, RegexValidator class Usuario(models.Model): Usuario_id = models.AutoField(primary_key=True) Usuario_contato = models.CharField(max_length=15,validators=[ RegexValidator(r'^[0-9]*$', 'Apenas números.') ], null=True) user = models.OneToOneField(User,on_delete=models.CASCADE, null=True) #Usuario_reserva = models.ManyToManyField('Reserva') def __str__(self): return self.user.first_name + " " + self.user.last_name class Motorista(models.Model): Motorista_id = models.AutoField(primary_key=True) Motorista_contato = models.CharField(max_length=15,validators=[ RegexValidator(r'^[0-9]*$', 'Apenas números.') ], null=True) user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) def __str__(self): return self.user.first_name + " " + self.user.last_name class Veiculo(models.Model): Veiculo_id = models.AutoField(primary_key=True) Veiculo_placa = models.CharField(null=True,max_length=7) Veiculo_modelo = models.CharField(max_length=50) Veiculo_cor = models.CharField(null=True,max_length=20) Motorista=models.ForeignKey(User, on_delete=models.CASCADE, null=True) def __str__(self): return self.Veiculo_placa class Rota(models.Model): Rota_id = models.AutoField(primary_key=True) Rota_pontopartida = models.CharField(max_length=100) Rota_pontochegada = models.CharField(max_length=100) Rota_localpartida = models.CharField(max_length=50) Rota_horario = models.TimeField() Rota_data = models.DateField(null=True) Rota_veiculo = models.ForeignKey('Veiculo', on_delete=models.CASCADE, null=True) Motorista=models.ForeignKey(User, on_delete=models.CASCADE, null=True) valor=models.FloatField(null=True) def __str__(self): return self.Rota_pontopartida + " - " + self.Rota_pontochegada + " - " + self.Motorista.username + "- " + str(self.Rota_horario) class Reserva(models.Model): Reserva_id = models.AutoField(primary_key=True) Reserva_rota = models.ManyToManyField('Rota') Usuario=models.ForeignKey(User, on_delete=models.CASCADE, null=True) <file_sep>/registro/migrations/0002_auto_20180525_2016.py # Generated by Django 2.0.5 on 2018-05-25 23:16 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('registro', '0001_initial'), ] operations = [ migrations.CreateModel( name='Motorista', fields=[ ('Motorista_id', models.AutoField(primary_key=True, serialize=False)), ('Motorista_nome', models.CharField(max_length=100)), ('Motorista_idade', models.CharField(max_length=3)), ('Motorista_contato', models.CharField(max_length=15)), ('Motorista_sexo', models.CharField(choices=[('masculino', 'Masculino'), ('feminino', 'Feminino')], max_length=100)), ], ), migrations.CreateModel( name='Rota', fields=[ ('Rota_id', models.AutoField(primary_key=True, serialize=False)), ('Rota_pontopartida', models.CharField(max_length=100)), ('Rota_pontochegada', models.CharField(max_length=100)), ('Rota_horario', models.DateTimeField()), ('Rota_motorista', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='registro.Motorista')), ], ), migrations.CreateModel( name='Veiculo', fields=[ ('Veiculo_id', models.AutoField(primary_key=True, serialize=False)), ('Veiculo_modelo', models.CharField(max_length=50)), ('Veiculo_motorista', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='registro.Motorista')), ('Veiculo_rota', models.ManyToManyField(to='registro.Rota')), ], ), migrations.AddField( model_name='usuario', name='Usuario_contato', field=models.CharField(default=0, max_length=15), preserve_default=False, ), migrations.AlterField( model_name='usuario', name='Usuario_idade', field=models.CharField(max_length=3), ), migrations.AddField( model_name='rota', name='Rota_veiculo', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='registro.Veiculo'), ), migrations.AddField( model_name='motorista', name='Motorista_veiculo', field=models.ManyToManyField(to='registro.Veiculo'), ), ] <file_sep>/registro/migrations/0018_rota_rota_localpartida.py # Generated by Django 2.0.4 on 2018-11-19 12:50 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('registro', '0017_auto_20181117_2157'), ] operations = [ migrations.AddField( model_name='rota', name='Rota_localpartida', field=models.CharField(default=django.utils.timezone.now, max_length=50), preserve_default=False, ), ] <file_sep>/registro/migrations/0009_auto_20181101_1939.py # Generated by Django 2.1.3 on 2018-11-01 22:39 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('registro', '0008_auto_20180817_0921'), ] operations = [ migrations.RemoveField( model_name='rota', name='Rota_semanal', ), migrations.AddField( model_name='rota', name='Motorista', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='registro.Motorista'), ), ] <file_sep>/registro/migrations/0001_initial.py # Generated by Django 2.0.5 on 2018-05-25 21:56 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Usuario', fields=[ ('Usuario_id', models.AutoField(primary_key=True, serialize=False)), ('Usuario_nome', models.CharField(max_length=100)), ('Usuario_idade', models.DateField()), ('Usuario_sexo', models.CharField(choices=[('masculino', 'Masculino'), ('feminino', 'Feminino')], max_length=100)), ], ), ] <file_sep>/registro/migrations/0005_auto_20180527_1057.py # Generated by Django 2.0.5 on 2018-05-27 13:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('registro', '0004_remove_veiculo_veiculo_motorista'), ] operations = [ migrations.AddField( model_name='motorista', name='Motorista_senha', field=models.CharField(default='admin', max_length=100), ), migrations.AddField( model_name='usuario', name='Usuario_senha', field=models.CharField(default='admin', max_length=100), ), ] <file_sep>/registro/views.py from django.shortcuts import render , redirect from django.views.generic import View, CreateView, UpdateView, DeleteView from django.contrib.auth import authenticate, login, logout from .forms import usuarioformulario, motoristaformulario, UserModelForm, reservaformulario, rotaformulario, veiculoformulario from django.contrib.auth.models import User, Group from django.http import HttpResponseRedirect from django.views.decorators.http import require_POST from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_protect from .models import Usuario, Reserva, Rota, Motorista, Veiculo from django.http import HttpResponse from django.utils.decorators import method_decorator import datetime from django.contrib import messages aux = False @csrf_protect def home(request): global aux rotas=[] date_format = '%d/%m/%Y' valor = aux aux = False try: origem = request.GET.get('o') destino = request.GET.get('d') data = datetime.datetime.strptime(request.GET.get('dt'), date_format) rotas = Rota.objects.filter(Rota_pontopartida=origem, Rota_pontochegada=destino, Rota_data=data) return render(request, 'home/index.html', {'rotas':rotas, 'valor': valor}) except: return render(request, 'home/index.html', {'rotas':rotas, 'valor': valor}) def dologin(request): return render(request, 'login/login.html') def motoristaregistro(request): return render(request, 'motoristaregistro/index.html') def usuarioregistro(request): return render(request, 'usuarioregistro/index.html') @login_required @csrf_protect def telamotorista(request): rotas = Rota.objects.filter(Motorista=request.user) reservas = Reserva.objects.filter(Reserva_rota__Motorista=request.user) form_class2 = veiculoformulario template_name = 'telamotorista/index.html' veiculos = Veiculo.objects.filter(Motorista=request.user) @method_decorator(login_required) def get(self, request): form2 = self.form_class2(None) veiculos = Veiculo.objects.all() rotas = Rota.objects.filter(Motorista=request.user) return render(request, self.template_name, {'form2':form2, 'veiculos':veiculos, 'rotas' : rotas}) if request.method == 'POST': form = rotaformulario(request.POST) form2 = veiculoformulario(request.POST) if form.is_valid(): f = form.save(commit=False) f.Motorista = request.user f.save() form.save() return redirect('/sita/telamotorista') elif form2.is_valid(): veiculo = form2.save(commit=False) veiculo.save() veiculo.Veiculo_placa = form2.cleaned_data['Veiculo_placa'] veiculo.Veiculo_modelo = form2.cleaned_data['Veiculo_modelo'] veiculo.Veiculo_cor = form2.cleaned_data['Veiculo_cor'] f = form2.save(commit=False) f.Motorista = request.user f.save() veiculo.save() messages.error(request, 'Veiculo cadastrado com sucesso!') return redirect('/sita/telamotorista') return redirect('/sita/telamotorista') else: messages.error(request, 'Corrija os dados') return redirect('telamotorista') else: form = rotaformulario() form.fields['Rota_veiculo'].queryset=Veiculo.objects.filter(Motorista=request.user) form2 = veiculoformulario rotas = Rota.objects.filter(Motorista=request.user) return render(request, 'telamotorista/index.html', {'veiculos':veiculos, 'form3' : form, 'rotas' : rotas, 'reservas':reservas, 'form2':form2}) @login_required def telausuario(request): return render(request, 'telausuario/index.html') @login_required def telausuario(request): return render(request, 'telausuario/index.html') @login_required def deletar_rota(request, id): u = Rota.objects.get(Rota_id=id) u.delete() return redirect('telamotorista') @require_POST def entraar(request): if request.method == 'POST': user = authenticate(username=request.POST['username'], password=request.POST['<PASSWORD>']) if user is None: return redirect('dologin') elif user is not None: login(request, user) u = User.objects.get(username=user) if u.groups.filter(name='Usuário').exists(): return redirect ('/telausuario') if u.groups.filter(name='Motorista').exists(): return redirect ('/telamotorista') return redirect('dologin') class usuarioformulario(View): form1_class = UserModelForm form2_class = usuarioformulario template_name = 'usuarioregistro/index.html' def get(self, request): form1 = self.form1_class(None) form2 = self.form2_class(None) return render(request, self.template_name, {'form1':form1, 'form2':form2}) #colocando no banco de dados def post(self, request): form1 = self.form1_class(request.POST) form2 = self.form2_class(request.POST) if form1.is_valid() and form2.is_valid(): user = form1.save(commit=False) usuario = form2.save(commit=False) u_name = user.username user.save() usuario.save() u = User.objects.get(username=u_name) usuario.user = u group = Group.objects.get(name='Usuário') u.groups.add(group) u.save() usuario.save() global aux aux = True return redirect('home') return render(request, self.template_name, {'form1':form1, 'form2':form2}) class motoristaformulario(View): form1_class = UserModelForm form2_class = motoristaformulario template_name = 'motoristaregistro/index.html' def get(self, request): form1 = self.form1_class(None) form2 = self.form2_class(None) return render(request, self.template_name, {'form1':form1, 'form2':form2}) #colocando no banco de dados def post(self, request): form1 = self.form1_class(request.POST) form2 = self.form2_class(request.POST) if form1.is_valid() and form2.is_valid(): user = form1.save(commit=False) motorista = form2.save(commit=False) u_name = user.username user.save() u = User.objects.get(username=u_name) motorista.user = u group = Group.objects.get(name='Motorista') u.groups.add(group) u.save() motorista.save() global aux aux = True return redirect('home') return render(request, self.template_name, {'form1':form1, 'form2':form2}) def dologout(request): logout(request) return redirect('/home') def criar_user(request): if request.method == 'POST': form = UserModelForm(request.POST) if form.is_valid(): form.save() return HttpResponse('ok') else: return HttpResponse('errado') else: form = UserModelForm() return render(request, 'motoristaregistro/oi.html', {'form' : form}) class reservaformulario(View): form_class = reservaformulario template_name = 'telausuario/index.html' @method_decorator(login_required) def get(self, request): form = self.form_class(None) reservas = Reserva.objects.filter(Usuario=request.user) return render(request, self.template_name, {'form':form, 'reservas':reservas}) #colocando no banco de dados def post(self, request): form = self.form_class(request.POST) if form.is_valid(): reserva = form.save(commit=False) reserva.save() reserva.Reserva_rota.set(form.cleaned_data['Reserva_rota']) reserva.Usuario = request.user reserva.save() return redirect('/sita/telausuario') return render(request, self.template_name, {'form':form}) #Continuação dos homes para quando o usuario clicar em inicio @csrf_protect def home2(request): rotas=[] date_format = '%d/%m/%Y' try: origem = request.GET.get('o') destino = request.GET.get('d') data = datetime.datetime.strptime(request.GET.get('dt'), date_format) rotas = Rota.objects.filter(Rota_pontopartida=origem, Rota_pontochegada=destino, Rota_data=data) print(rotas) return render(request, 'home2/home2.html', {'rotas':rotas}) except: print(rotas) return render(request, 'home2/home2.html', {'rotas':rotas}) @csrf_protect def home3(request): rotas=[] date_format = '%d/%m/%Y' try: origem = request.GET.get('o') destino = request.GET.get('d') horario = request.GET.get('h') data = datetime.datetime.strptime(request.GET.get('dt'), date_format) rotas = Rota.objects.filter(Rota_pontopartida=origem, Rota_pontochegada=destino, Rota_data=data) print(rotas) return render(request, 'home3/home3.html', {'rotas':rotas}) except: print(rotas) return render(request, 'home3/home3.html', {'rotas':rotas})<file_sep>/registro/migrations/0004_remove_veiculo_veiculo_motorista.py # Generated by Django 2.0.5 on 2018-05-26 12:20 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('registro', '0003_auto_20180526_0912'), ] operations = [ migrations.RemoveField( model_name='veiculo', name='Veiculo_motorista', ), ] <file_sep>/registro/migrations/0014_auto_20181112_1655.py # Generated by Django 2.1.1 on 2018-11-12 19:55 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('registro', '0013_auto_20181107_2001'), ] operations = [ migrations.AlterField( model_name='rota', name='Motorista', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='registro.Motorista'), ), ]
ea18d043c5338a9d893ecdf0fb29e9df9c83dc11
[ "Python" ]
22
Python
Ewertonn/SITA2
a6899f9eb8e6d1fbc3a8b1f95c706894bb07e1c6
5dc76a5b8d2d4f6ca6e12e4ae6941735ef68f80f